import elastic.client as es_client import llm.client as llm_client import json import argparse import time import logging import threading from concurrent.futures import ThreadPoolExecutor, as_completed logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logger = logging.getLogger(__name__) POSTPROC_INDEX = "aktuell_postproc" def print_pretty_json(data): logger.info(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 logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: logger.error(f"Error: {news_id} - {error}") return False def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3): doc_id = postproc_entry["_id"] source = postproc_entry["_source"] news_id = 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) if not keywords: # Empty article or unparseable LLM answer: writing an empty list # would look like a success and block a later retry. logger.info(f"Skipped {news_id}: no keywords extracted.") return False if target_index == POSTPROC_INDEX: es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords}) else: # Key the target doc on news_id so re-runs update it in place # instead of piling up a new document each time. es_client.index_entry( target_index, news_id, { "news_id": news_id, "relevant": source.get("relevant", 0), "authors": source.get("authors", []), "keywords": keywords, }, ) return True except Exception as error: attempt += 1 logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})") if attempt < max_retries: time.sleep(1) else: logger.error(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).", ) parser.add_argument( "--target-index", default=POSTPROC_INDEX, help=( f"Index that --update-keywords writes to (default: {POSTPROC_INDEX}). Any other " "index gets new documents instead of in-place updates, and every entry is " "re-extracted rather than only those missing keywords." ), ) 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") logger.info(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 logger.info(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 logger.info(f"Sync: {processed} / {total}") end_time = time.time() logger.info(f"Sync DONE: {succeeded} entries synced.") logger.info(f"Time taken: {end_time - start_time} seconds.") if args.update_keywords: start_time = time.time() postproc_entries = es_client.get_all_entries( POSTPROC_INDEX, fields=["news_id", "keywords", "relevant", "authors"] ) if args.target_index == POSTPROC_INDEX: pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")] logger.info(f"Number of entries without keywords: {len(pending)}") else: # Writing elsewhere never marks the postproc entries, so the "missing # keywords" filter would select the same entries on every run. Pick # entries that already have keywords instead: those are known to come # from articles with actual content, unlike the empty archive stubs. pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")] logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.") if args.limit is not None: pending = pending[:args.limit] total = len(pending) logger.info(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, args.target_index) for entry in pending ] for future in as_completed(futures): was_successful = future.result() with progress_lock: processed += 1 if was_successful: succeeded += 1 logger.info(f"Update keywords: {processed} / {total}") end_time = time.time() logger.info(f"Update keywords DONE: {succeeded} entries updated.") logger.info(f"Time taken: {end_time - start_time} seconds.") if args.stats: aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"]) logger.info(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 logger.info(f"Total entries in 'aktuell_postproc': {total_entries}") logger.info(f"Relevant entries: {relevant_count}") logger.info(f"Irrelevant entries: {irrelevant_count}") logger.info(f"Entries with extracted names: {news_with_extracted_names}") logger.info(f"Entries without extracted names: {news_without_extracted_names}") logger.info(f"Entries with keywords: {news_with_keywords}") logger.info(f"Entries without keywords: {news_without_keywords}") if __name__ == "__main__": main()