import elastic.client as es_client import llm.client as llm_client import json import argparse import time import threading from concurrent.futures import ThreadPoolExecutor, as_completed def print_pretty_json(data): print(json.dumps(data, indent=2)) def sync_single_news(news_id, max_retries=3): attempt = 0 while attempt < max_retries: try: news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"] is_news_relevant = llm_client.is_news_relevant(news_text) authors = llm_client.extract_names(news_text) keywords = llm_client.extract_keywords(news_text) new_entry = { "news_id": news_id, "relevant": is_news_relevant, "authors": authors, "keywords": keywords, } es_client.add_entry("aktuell_postproc", new_entry) return True except Exception as error: attempt += 1 print(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: print(f"Error: {news_id} - {error}") return False def update_keywords_single(postproc_entry, max_retries=3): doc_id = postproc_entry["_id"] news_id = postproc_entry["_source"]["news_id"] attempt = 0 while attempt < max_retries: try: news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"] keywords = llm_client.extract_keywords(news_text) es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords}) return True except Exception as error: attempt += 1 print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: print(f"Error: {news_id} - {error}") return False def main(): parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.") parser.add_argument( "--delete-all", action="store_true", help="Delete all entries from index 'aktuell_postproc'.", ) parser.add_argument( "--sync-delta", action="store_true", help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.", ) parser.add_argument( "--update-keywords", action="store_true", help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).", ) parser.add_argument( "--reset-keywords", action="store_true", help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.", ) parser.add_argument( "--stats", action="store_true", help="Print statistics about the entries in 'aktuell_postproc' and 'aktuell'.", ) parser.add_argument( "--threads", type=int, default=4, help="Number of threads for --sync-delta (Default: 4).", ) parser.add_argument( "--limit", type=int, default=None, help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).", ) args = parser.parse_args() if args.delete_all: es_client.delete_all_entries("aktuell_postproc") if args.reset_keywords: result = es_client.remove_field_all("aktuell_postproc", "keywords") print(f"Removed 'keywords' from {result.get('updated', 0)} entries.") if args.sync_delta: start_time = time.time() aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"]) postproc_ids_raw = es_client.get_all_entries("aktuell_postproc", fields=["news_id"]) source_ids = set(entry["_id"] for entry in aktuell_ids_raw) target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw) missing_ids = source_ids - target_ids print(f"Number of missing IDs: {len(missing_ids)}") missing_ids = list(missing_ids) total = len(missing_ids) processed = 0 succeeded = 0 progress_lock = threading.Lock() with ThreadPoolExecutor(max_workers=args.threads) as executor: futures = [executor.submit(sync_single_news, news_id) for news_id in missing_ids] for future in as_completed(futures): was_successful = future.result() with progress_lock: processed += 1 if was_successful: succeeded += 1 print(f"Sync: {processed} / {total}") end_time = time.time() print(f"Sync DONE: {succeeded} entries synced.") print(f"Time taken: {end_time - start_time} seconds.") if args.update_keywords: start_time = time.time() postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"]) pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] print(f"Number of entries without keywords: {len(pending)}") if args.limit is not None: pending = pending[:args.limit] total = len(pending) print(f"Processing {total} entries.") processed = 0 succeeded = 0 progress_lock = threading.Lock() with ThreadPoolExecutor(max_workers=args.threads) as executor: futures = [executor.submit(update_keywords_single, entry) for entry in pending] for future in as_completed(futures): was_successful = future.result() with progress_lock: processed += 1 if was_successful: succeeded += 1 print(f"Update keywords: {processed} / {total}") end_time = time.time() print(f"Update keywords DONE: {succeeded} entries updated.") print(f"Time taken: {end_time - start_time} seconds.") if args.stats: aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"]) print(f"Total entries in 'aktuell': {len(aktuell_entries)}") postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"]) total_entries = len(postproc_entries) relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1) irrelevant_count = total_entries - relevant_count news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"]) news_without_extracted_names = total_entries - news_with_extracted_names news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords")) news_without_keywords = total_entries - news_with_keywords print(f"Total entries in 'aktuell_postproc': {total_entries}") print(f"Relevant entries: {relevant_count}") print(f"Irrelevant entries: {irrelevant_count}") print(f"Entries with extracted names: {news_with_extracted_names}") print(f"Entries without extracted names: {news_without_extracted_names}") print(f"Entries with keywords: {news_with_keywords}") print(f"Entries without keywords: {news_without_keywords}") if __name__ == "__main__": main()