diff --git a/preprocessing/.dockerignore b/preprocessing/.dockerignore new file mode 100644 index 00000000..9b43b1ce --- /dev/null +++ b/preprocessing/.dockerignore @@ -0,0 +1,5 @@ +.env +.env.* +__pycache__/ +*.pyc +.venv/ diff --git a/preprocessing/.env.example b/preprocessing/.env.example new file mode 100644 index 00000000..51667cb8 --- /dev/null +++ b/preprocessing/.env.example @@ -0,0 +1,7 @@ +# Copy this file to `.env` and fill in the real values. +# `.env` is gitignored and is NOT baked into the image. +INSE_ELASTIC_URL=https://inse.nes.uni-due.de/elastic +INSE_ELASTIC_API_KEY=your-elastic-api-key-here +INSE_LLM_BASE_URL=https://project.nes.uni-due.de/llm2/v1/ +INSE_LLM_API_KEY=your-llm-api-key-here +INSE_LLM_MODEL=gemma4-e4b diff --git a/preprocessing/.gitignore b/preprocessing/.gitignore new file mode 100644 index 00000000..ccbef30f --- /dev/null +++ b/preprocessing/.gitignore @@ -0,0 +1,5 @@ +# Local secrets – never commit +.env + +__pycache__/ +*.pyc diff --git a/preprocessing/Dockerfile b/preprocessing/Dockerfile new file mode 100644 index 00000000..c3d7e8ab --- /dev/null +++ b/preprocessing/Dockerfile @@ -0,0 +1,17 @@ +# Preprocessing worker, news enrichment job (v1) +FROM python:3.13-slim + +WORKDIR /app + +# Install dependencies first so this layer is cached when only code changes. +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy the job code. No secrets here, config is read from env vars at runtime. +COPY app/ ./ + +# Small dispatcher that maps a job name to the right command. +COPY entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/preprocessing/app/elastic/client.py b/preprocessing/app/elastic/client.py new file mode 100644 index 00000000..a3c06382 --- /dev/null +++ b/preprocessing/app/elastic/client.py @@ -0,0 +1,137 @@ +import os +import requests +from requests.adapters import HTTPAdapter +from urllib.parse import quote +from dotenv import load_dotenv + +load_dotenv() + +INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic") +INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY") +if not INSE_API_KEY: + raise RuntimeError( + "INSE_ELASTIC_API_KEY is not set. Copy .env.example to .env and fill it in, " + "or pass it as an environment variable." + ) + +ES_HEADERS = { + "Authorization": f"ApiKey {INSE_API_KEY}", + "Content-Type": "application/json", +} + +_session = requests.Session() +_session.headers.update(ES_HEADERS) +_adapter = HTTPAdapter(pool_connections=32, pool_maxsize=32) +_session.mount("https://", _adapter) +_session.mount("http://", _adapter) + +def _send_es_request(method: str, url: str, payload: dict = None) -> dict: + + try: + response = _session.request( + method=method, + url=url, + json=payload, + ) + response.raise_for_status() + return response.json() + except requests.RequestException as error: + print(f"Send Request failed: ({method} {url}): {error}") + raise + +def add_entry(index: str, entry: dict): + + endpoint = f"{INSE_URL}/{index}/_doc" + + document_body = { + "news_id": entry["news_id"], + "relevant": int(entry["relevant"]), + "authors": entry["authors"], + "keywords": entry.get("keywords", []), + } + + response_data = _send_es_request("POST", endpoint, payload=document_body) + + created_id = response_data["_id"] + entry["_id"] = created_id + + return created_id + +def update_entry(index: str, document_id: str, partial_doc: dict): + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}" + + return _send_es_request("POST", endpoint, payload={"doc": partial_doc}) + +def get_entry(index: str, document_id: str) -> dict: + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}" + + return _send_es_request("GET", endpoint) + +def delete_entry(index: str, document_id: str): + + encoded_document_id = quote(document_id, safe="") + endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}" + + return _send_es_request("DELETE", endpoint) + +def get_all_entries(index: str, fields: list = None) -> list: + + if not fields: + source_fields = True + else: + source_fields = fields + + endpoint = f"{INSE_URL}/{index}/_search" + + page_size = 1000 + results = [] + last_sort_value = None + + while True: + payload = { + "query": {"match_all": {}}, + "size": page_size, + "sort": [{"_doc": "asc"}], + "_source": source_fields, + } + if last_sort_value is not None: + payload["search_after"] = last_sort_value + + response_data = _send_es_request("POST", endpoint, payload=payload) + results_list = response_data["hits"]["hits"] + + if not results_list: + break + + results.extend(results_list) + last_sort_value = results_list[-1]["sort"] + + return results + +def delete_all_entries(index: str): + + endpoint = f"{INSE_URL}/{index}/_delete_by_query" + + payload = { + "query": {"match_all": {}} + } + + return _send_es_request("POST", endpoint, payload=payload) + +def remove_field_all(index: str, field: str): + + endpoint = f"{INSE_URL}/{index}/_update_by_query" + + payload = { + "query": {"exists": {"field": field}}, + "script": { + "source": f"ctx._source.remove('{field}')", + "lang": "painless", + }, + } + + return _send_es_request("POST", endpoint, payload=payload) diff --git a/preprocessing/app/llm/client.py b/preprocessing/app/llm/client.py new file mode 100644 index 00000000..e798d14c --- /dev/null +++ b/preprocessing/app/llm/client.py @@ -0,0 +1,95 @@ +import os +import requests +from openai import OpenAI, APIConnectionError +from dotenv import load_dotenv + +load_dotenv() + +LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/") +LLM_API_KEY = os.getenv("INSE_LLM_API_KEY") +if not LLM_API_KEY: + raise RuntimeError( + "INSE_LLM_API_KEY is not set. Copy .env.example to .env and fill it in, " + "or pass it as an environment variable." + ) +LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b") + +SYSTEM_PROMPT_RELEVANT = (""" + Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen. + Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit. + Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird. + Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht. + Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug. + Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein. + Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1. +""") + +SYSTEM_PROMPT_NAMES = (""" + Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht. + Es können mehrere Personen sein. Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen. + Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden. + Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"person\": [\"Vorname Nachname\", \"Vorname Nachname\"]} + Gib keine Erklärungen und kein Markdown aus, nur das JSON. +""") + +SYSTEM_PROMPT_KEYWORDS = (""" + Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords). + Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen. + Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels. + Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird. + Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff. + Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben. + Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]} + Gib keine Erklärungen und kein Markdown aus, nur das JSON. +""") + +_client = OpenAI( + base_url=LLM_BASE_URL, + api_key=LLM_API_KEY, + timeout=30, +) + +def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95): + try: + response = _client.chat.completions.create( + model=model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ], + temperature=temperature, + top_p=top_p, + extra_body={"top_k": 64}, + ) + except APIConnectionError: + return None + + return response.choices[0].message.content or None + +def is_news_relevant(text: str) -> bool: + result = call(SYSTEM_PROMPT_RELEVANT, text) + if result is None: + return False + return result.strip() == "1" + +def extract_names(text: str) -> list[str]: + result = call(SYSTEM_PROMPT_NAMES, text) + if result is None: + return [] + try: + import json + data = json.loads(result) + return data.get("person", []) + except json.JSONDecodeError: + return [] + +def extract_keywords(text: str) -> list[str]: + result = call(SYSTEM_PROMPT_KEYWORDS, text) + if result is None: + return [] + try: + import json + data = json.loads(result) + return data.get("keywords", []) + except json.JSONDecodeError: + return [] diff --git a/preprocessing/app/sync.py b/preprocessing/app/sync.py new file mode 100644 index 00000000..72f330b4 --- /dev/null +++ b/preprocessing/app/sync.py @@ -0,0 +1,197 @@ +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() diff --git a/preprocessing/entrypoint.sh b/preprocessing/entrypoint.sh new file mode 100644 index 00000000..4cfaa044 --- /dev/null +++ b/preprocessing/entrypoint.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env sh +# Job dispatcher for the preprocessing worker. +# Usage: e.g. docker run news +set -eu + +JOB="${1:-}" + +case "$JOB" in + news) + # Enrich new 'aktuell' articles into 'aktuell_postproc' (relevance, authors, keywords). + exec python sync.py --sync-delta + ;; + news-stats) + # Print counts for the aktuell / aktuell_postproc indices (read-only). + exec python sync.py --stats + ;; + "") + echo "No job given. Available jobs: news, news-stats" >&2 + exit 2 + ;; + *) + echo "Unknown job: $JOB. Available jobs: news, news-stats" >&2 + exit 2 + ;; +esac diff --git a/preprocessing/requirements.txt b/preprocessing/requirements.txt new file mode 100644 index 00000000..d5f8a74c --- /dev/null +++ b/preprocessing/requirements.txt @@ -0,0 +1,3 @@ +requests~=2.32 +openai~=2.41 +python-dotenv~=1.0