From 807adbd6e410f1ce2812fe0f876933cfda720d3b Mon Sep 17 00:00:00 2001 From: "noemi.kallweit" Date: Tue, 21 Jul 2026 00:28:18 +0200 Subject: [PATCH] feat(jobs): add news topic-mapping as background job --- background-jobs/Dockerfile | 3 + background-jobs/entrypoint.sh | 19 +- service/scripts/news/topic_mapper/README.md | 79 +++++ .../news/topic_mapper/map_news_topics.py | 329 ++++++++++++++++++ .../scripts/news/topic_mapper/news_mapping.py | 30 ++ .../news/topic_mapper/requirements.txt | 2 + service/src/main/inse/background_jobs/seed.py | 24 +- 7 files changed, 483 insertions(+), 3 deletions(-) create mode 100644 service/scripts/news/topic_mapper/README.md create mode 100644 service/scripts/news/topic_mapper/map_news_topics.py create mode 100644 service/scripts/news/topic_mapper/news_mapping.py create mode 100644 service/scripts/news/topic_mapper/requirements.txt diff --git a/background-jobs/Dockerfile b/background-jobs/Dockerfile index 68f19974..e80b739f 100644 --- a/background-jobs/Dockerfile +++ b/background-jobs/Dockerfile @@ -23,6 +23,9 @@ COPY service/scripts/news/ude/ ./news/ude/ # The project topic-mapper keeps its package path so its absolute import resolves. COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/ +# The news topic-mapper imports the project topic-mapper, so it keeps its path too. +COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/ + # The bund foerderportal crawler (runs with its own dir as cwd for its JSON configs). COPY service/scripts/projects/bund/ ./projects/bund/ diff --git a/background-jobs/entrypoint.sh b/background-jobs/entrypoint.sh index 5f1f4d52..8eebef41 100644 --- a/background-jobs/entrypoint.sh +++ b/background-jobs/entrypoint.sh @@ -33,6 +33,21 @@ case "$JOB" in --output-index projects_bund_openalex_topics \ --api-base-url "${PROJECT_TOPICS_API_BASE_URL:-http://host.docker.internal:8000}" ;; + news-keywords) + # Extract news keywords with the LLM. Writes to the docker test index, so + # 'aktuell_postproc' stays untouched. + exec python sync.py --update-keywords \ + --target-index "${NEWS_KEYWORDS_TARGET_INDEX:-docker-job_test}" \ + --limit "${NEWS_KEYWORDS_LIMIT:-50}" \ + --threads "${NEWS_KEYWORDS_THREADS:-4}" + ;; + news-topics) + # Map the keywords of enriched news articles to OpenAlex topics. + exec python -m service.scripts.news.topic_mapper.map_news_topics \ + --output-index "${NEWS_TOPICS_OUTPUT_INDEX:-docker-job_test}" \ + --max-docs "${NEWS_TOPICS_MAX_DOCS:-50}" \ + --api-base-url "${PROJECT_TOPICS_API_BASE_URL:-http://host.docker.internal:8000}" + ;; demo-a) exec python demo.py 20 ;; @@ -43,11 +58,11 @@ case "$JOB" in exec python demo.py 30 ;; "") - echo "No job given. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 + echo "No job given. Available jobs: news, news-stats, news-crawl, news-keywords, news-topics, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 exit 2 ;; *) - echo "Unknown job: $JOB. Available jobs: news, news-stats, news-crawl, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 + echo "Unknown job: $JOB. Available jobs: news, news-stats, news-crawl, news-keywords, news-topics, project-topics, bund-crawl, demo-a, demo-b, demo-c" >&2 exit 2 ;; esac diff --git a/service/scripts/news/topic_mapper/README.md b/service/scripts/news/topic_mapper/README.md new file mode 100644 index 00000000..213df178 --- /dev/null +++ b/service/scripts/news/topic_mapper/README.md @@ -0,0 +1,79 @@ +# News → OpenAlex topic mapping + +Batch counterpart to `news.logic._match_topics_for_keywords`, which matches an +article's keywords on every detail request without persisting the result. This +script maps the LLM-extracted `keywords` of the enriched articles in +`aktuell_postproc` to OpenAlex topics via the backend's +`/api/topics/vector-search` endpoint, and persists one document per +(article, keyword) pair into an output index with the explicit mapping from +`news_mapping.py`: + +```json +{ + "news_id": "...", + "keyword": "", + "source_index": "aktuell_postproc", + "source_field": "keywords", + "topic_matches": [ + { + "rank": 1, + "topic_id": "...", + "topic_display_name": "...", + "subfield": "...", + "field": "...", + "domain": "...", + "match_score": null + } + ], + "match_method": "sentence_transformer", + "model_name": "...", + "built_at": "..." +} +``` + +`match_score` is `null` because the endpoint does not expose Elasticsearch +scores; `rank` preserves the search result order. + +This script only ever **reads** `aktuell_postproc` and writes into the separate test index. Caching the topics back into `aktuell_postproc` is done by the news detail endpoint (`news/logic.py`), not here. + +Keywords are **not** extracted here. `background-jobs/app/sync.py` (job `news`) +writes them into `aktuell_postproc` first, the same way the bund projects +already carry their keyword field before `map_project_topics.py` runs. + +The Elasticsearch plumbing (point-in-time scan, batched topic search, bulk +indexing, retries) is imported from +`service/scripts/projects/topic_mapper/map_project_topics.py` rather than +duplicated — that directory must stay next to this one. + +## Setup + +```bash +pip install -r requirements.txt +``` + +Credentials are read from `service/src/main/inse/.env` by default (override +with `--env-file`), and the backend must be running (e.g. `./gradlew serve`) +because the topic search goes through its API. + +## Usage + +```bash +python map_news_topics.py --output-index docker-job_test +``` + +Test run against a few articles without writing anything: + +```bash +python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50 +``` + +Runs are resumable: (article, keyword) pairs already present in the output +index are skipped, and each unique keyword is searched only once across all +articles that use it. Pairs whose search failed are left unwritten so the next +run retries them. + +## As a background job + +Registered in `background-jobs/entrypoint.sh` as `news-topics`, writing into +the test index `docker-job_test` and capped at a few articles. Both are +overridable via `NEWS_TOPICS_OUTPUT_INDEX` and `NEWS_TOPICS_MAX_DOCS`. diff --git a/service/scripts/news/topic_mapper/map_news_topics.py b/service/scripts/news/topic_mapper/map_news_topics.py new file mode 100644 index 00000000..f34dc42e --- /dev/null +++ b/service/scripts/news/topic_mapper/map_news_topics.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 +""" +map_news_topics.py — Map news keywords to OpenAlex topics. + +Batch counterpart to news.logic._match_topics_for_keywords. This script streams +the enriched articles from aktuell_postproc, reads their LLM-extracted +'keywords', matches every unique keyword against OpenAlex topics and persists +one document per (article, keyword) pair into a separate output index: + + {news_id, keyword, source_index, source_field, topic_matches[], + match_method, model_name, built_at} + +The source index is only ever read. Writing the topics back into +aktuell_postproc is the job of the news detail endpoint, not of this script. + +Keywords are not extracted here — sync.py (job 'news') writes them into +aktuell_postproc, the same way the bund projects already carry their keyword +field before map_project_topics.py runs. + +The run is resumable: (article, keyword) pairs already present in the output +index are skipped, so an interrupted run can simply be restarted. Each unique +keyword is searched only once, across all articles that use it. + +Usage: + python map_news_topics.py --output-index docker-job_test + +Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY in the environment +or in the service .env, plus a running backend serving +/api/topics/vector-search (e.g. ./gradlew serve). +""" +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import json +import logging +import os +import sys +from datetime import datetime, timezone +from pathlib import Path + +from dotenv import load_dotenv + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "projects" / "topic_mapper")) +import map_project_topics as base + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from news_mapping import NEWS_TOPICS_MAPPING + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +logger = logging.getLogger(__name__) + +SOURCE_INDEX = "aktuell_postproc" +KEYWORD_FIELD = "keywords" +NEWS_ID_FIELD = "news_id" + + +async def ensure_index(index: str, cluster: str) -> None: + """Creates the output index with the explicit mapping if it does not exist.""" + url, headers = base.es_headers(cluster) + client = base.get_http_client() + + response = await client.head(f"{url}/{index}", headers=headers) + if response.status_code == 200: + logger.info("Output index '%s' already exists.", index) + return + + response = await client.put( + f"{url}/{index}", json={"mappings": NEWS_TOPICS_MAPPING}, headers=headers + ) + response.raise_for_status() + logger.info("Created output index '%s' with explicit mapping.", index) + + +def output_doc_id(news_id: str, keyword: str) -> str: + """Stable id per (article, keyword) pair. + + Derived from news_id rather than the aktuell_postproc document id, so a + reindex of the postproc index does not duplicate the mappings. + """ + digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12] + return f"{news_id}::{digest}" + + +async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str, tuple[str, str]]: + """Returns output_doc_id -> (news_id, keyword) for every enriched article.""" + entries: dict[str, tuple[str, str]] = {} + total = 0 + docs_with_keywords = 0 + + async for hit in base.scan( + index=SOURCE_INDEX, + cluster=cluster, + query={"exists": {"field": KEYWORD_FIELD}}, + source=[NEWS_ID_FIELD, KEYWORD_FIELD], + ): + total += 1 + doc_source = hit.get("_source", {}) + keywords = base.extract_text_values(doc_source, KEYWORD_FIELD) + news_id = doc_source.get(NEWS_ID_FIELD) + if keywords and news_id: + docs_with_keywords += 1 + for keyword in keywords: + entries[output_doc_id(news_id, keyword)] = (news_id, keyword) + if total % 50000 == 0: + logger.info("Scanned %d source documents...", total) + if max_docs and total >= max_docs: + logger.info("Stopping scan at --max-docs=%d.", max_docs) + break + + logger.info( + "Scanned %d documents from '%s', %d with non-empty '%s' (%d article/keyword pairs).", + total, + SOURCE_INDEX, + docs_with_keywords, + KEYWORD_FIELD, + len(entries), + ) + return entries + + +async def run(args: argparse.Namespace) -> None: + built_at = datetime.now(timezone.utc).isoformat() + model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME") + + await base.check_backend(args.api_base_url) + + if not args.dry_run: + await ensure_index(index=args.output_index, cluster=args.output_cluster) + + entries = await fetch_source_entries(cluster=args.source_cluster, max_docs=args.max_docs) + if not entries: + logger.warning("No keywords in '%s' — run the 'news' job first.", SOURCE_INDEX) + return + + if args.overwrite: + logger.info("--overwrite: re-mapping every pair, existing documents are replaced.") + covered = set() + else: + covered = await base.fetch_covered_doc_ids( + index=args.output_index, cluster=args.output_cluster + ) + pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered} + logger.info( + "Coverage: %d/%d pairs already in '%s', %d still to be processed.", + len(entries) - len(pending), + len(entries), + args.output_index, + len(pending), + ) + if not pending: + logger.info("Nothing left to process.") + return + + docs_by_keyword: dict[str, list[tuple[str, str]]] = {} + for doc_id, (news_id, keyword) in pending.items(): + docs_by_keyword.setdefault(keyword, []).append((doc_id, news_id)) + unique_keywords = sorted(docs_by_keyword) + logger.info( + "%d unique keywords cover the %d pending pairs.", len(unique_keywords), len(pending) + ) + + backup_docs: list[dict] = [] + docs_done = 0 + keywords_done = 0 + + for start in range(0, len(unique_keywords), args.text_batch_size): + chunk = unique_keywords[start : start + args.text_batch_size] + matches_by_keyword = await base.match_keywords( + chunk, + api_base_url=args.api_base_url, + top_k=args.top_k, + search_type=args.search_type, + ) + + documents = [] + for keyword in chunk: + if keyword not in matches_by_keyword: + continue # search failed — left for the next run + for doc_id, news_id in docs_by_keyword[keyword]: + documents.append( + ( + doc_id, + { + "news_id": news_id, + "keyword": keyword, + "source_index": SOURCE_INDEX, + "source_field": KEYWORD_FIELD, + "topic_matches": matches_by_keyword[keyword], + "match_method": base.MATCH_METHOD, + "model_name": model_name, + "built_at": built_at, + }, + ) + ) + + if documents and not args.dry_run: + await base.bulk_index( + index=args.output_index, cluster=args.output_cluster, documents=documents + ) + if args.output: + backup_docs.extend(doc for _, doc in documents) + + keywords_done += len(chunk) + docs_done += len(documents) + logger.info( + "Progress: %d/%d keywords, %d/%d pending pairs indexed into '%s'.", + keywords_done, + len(unique_keywords), + docs_done, + len(pending), + args.output_index, + ) + + skipped = len(pending) - docs_done + if skipped: + logger.warning( + "%d pairs were NOT indexed due to failed searches — rerun the script to retry.", + skipped, + ) + + if args.output: + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8" + ) + logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path) + + logger.info( + "Done. %d documents indexed this run, %d covered in total.", + docs_done, + len(covered) + docs_done, + ) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Map the keywords of enriched news articles to OpenAlex topics.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "Examples:\n" + " python map_news_topics.py --output-index docker-job_test\n" + " python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50" + ), + ) + parser.add_argument( + "--output-index", required=True, help="Index to persist the topic mappings into" + ) + parser.add_argument( + "--source-cluster", + default="inse", + choices=["inse", "nes"], + help=f"Cluster holding '{SOURCE_INDEX}' (default: inse)", + ) + parser.add_argument( + "--output-cluster", + default="inse", + choices=["inse", "nes"], + help="Cluster of the output index (default: inse)", + ) + parser.add_argument( + "--api-base-url", + default=base.DEFAULT_API_BASE_URL, + help=f"Base URL of the running backend (default: {base.DEFAULT_API_BASE_URL})", + ) + parser.add_argument( + "--top-k", + type=int, + default=1, + help=( + "Number of topic matches per keyword (default: 1, matching the single " + "match the news detail endpoint shows). Only truncates the result list; " + "ranking is unaffected." + ), + ) + parser.add_argument( + "--search-type", + default="hybrid", + choices=["hybrid", "semantic"], + help="Topic search type, mirrors vector_search_topics (default: hybrid)", + ) + parser.add_argument( + "--text-batch-size", + type=int, + default=base.TEXT_BATCH_SIZE, + help=f"Unique keywords searched per chunk (default: {base.TEXT_BATCH_SIZE})", + ) + parser.add_argument( + "--env-file", + default=str(base.DEFAULT_ENV_FILE), + help=f"Path to a .env with Elasticsearch credentials (default: {base.DEFAULT_ENV_FILE})", + ) + parser.add_argument( + "--max-docs", + type=int, + default=None, + help=f"Stop scanning '{SOURCE_INDEX}' after N documents (for test runs)", + ) + parser.add_argument( + "--output", + default=None, + help="Optional path for a local JSON backup of the documents built this run", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help=( + "Re-map pairs that are already in the output index instead of skipping " + "them; document ids are deterministic, so they are replaced in place " + "(use after changing --top-k or --search-type)" + ), + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Build the mapping without creating/writing the output index", + ) + args = parser.parse_args() + + if args.env_file and Path(args.env_file).exists(): + load_dotenv(dotenv_path=args.env_file) + + asyncio.run(run(args)) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/news/topic_mapper/news_mapping.py b/service/scripts/news/topic_mapper/news_mapping.py new file mode 100644 index 00000000..28a6d909 --- /dev/null +++ b/service/scripts/news/topic_mapper/news_mapping.py @@ -0,0 +1,30 @@ +"""Elasticsearch mapping for news -> OpenAlex topic mapping indices. + +One document per (news article, keyword) pair. Articles in aktuell_postproc +carry up to KEYWORD_LIMIT keywords each, so an article normally yields +several documents. +""" + +NEWS_TOPICS_MAPPING = { + "properties": { + "news_id": {"type": "keyword"}, + "keyword": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "source_index": {"type": "keyword"}, + "source_field": {"type": "keyword"}, + "topic_matches": { + "type": "nested", + "properties": { + "rank": {"type": "integer"}, + "topic_id": {"type": "keyword"}, + "topic_display_name": {"type": "keyword"}, + "subfield": {"type": "keyword"}, + "field": {"type": "keyword"}, + "domain": {"type": "keyword"}, + "match_score": {"type": "float"}, + }, + }, + "match_method": {"type": "keyword"}, + "model_name": {"type": "keyword"}, + "built_at": {"type": "date"}, + } +} diff --git a/service/scripts/news/topic_mapper/requirements.txt b/service/scripts/news/topic_mapper/requirements.txt new file mode 100644 index 00000000..7507eb03 --- /dev/null +++ b/service/scripts/news/topic_mapper/requirements.txt @@ -0,0 +1,2 @@ +httpx>=0.27 +python-dotenv>=1.0 diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py index 2b26d3f8..bcadaa17 100644 --- a/service/src/main/inse/background_jobs/seed.py +++ b/service/src/main/inse/background_jobs/seed.py @@ -28,11 +28,33 @@ PREDEFINED_JOBS: list[dict] = [ "Ordnet die Schlagwörter der Bund-Projekte über die Topic-Vektorsuche " "des Backends OpenAlex-Themen zu. Läuft als Dry-Run (--dry-run): liest " "nur aus dem Quellindex und schreibt nichts nach Elasticsearch. " - "Benötigt ein erreichbares Backend und INSE-Elasticsearch-Zugang." ), "target_index": "-", "command": "project-topics", }, + { + "name": "News-Schlagwort-Extraktion (Testlauf)", + "description": ( + "Extrahiert per LLM die Schlagwörter aus den News-Artikeln und legt sie " + "im Testindex „docker-job_test“ ab. „aktuell_postproc“ bleibt dabei " + "unverändert. Begrenzt auf wenige Artikel; da nichts im Quellindex " + "markiert wird, verarbeitet jeder Lauf erneut die ersten Artikel." + ), + "target_index": "docker-job_test", + "command": "news-keywords", + }, + { + "name": "News-Themen-Mapping (Testlauf)", + "description": ( + "Ordnet die per LLM extrahierten Schlagwörter der angereicherten " + "News-Artikel („aktuell_postproc“) über die Topic-Vektorsuche des " + "Backends OpenAlex-Themen zu und schreibt je Artikel-Schlagwort-Paar " + "ein Dokument in den Testindex „docker-job_test“. Begrenzt auf wenige " + "Artikel; erneute Läufe überspringen bereits gemappte Paare." + ), + "target_index": "docker-job_test", + "command": "news-topics", + }, { "name": "Bund-Crawler (Testlauf, ohne Upload)", "description": (