330 lines
11 KiB
Python
330 lines
11 KiB
Python
|
|
"""
|
|
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 UTC, datetime
|
|
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(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()
|