Files
kallweit f898644d46
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
feat(news-keywords): add keyword extraction evaluation harness and results
2026-09-15 19:18:32 +02:00

187 lines
6.1 KiB
Python

"""Collects the article sample for the keyword evaluation.
Reads `aktuell` (title + content) and joins the `authors` field from
`aktuell_postproc`, which the person-name check uses as a per-article list of
names that must not show up as keywords.
Writes one JSON object per line to data/articles.jsonl, so a corpus-wide run
stays a single file:
{"_id": ..., "maintitle": ..., "full_content": ..., "date": ...,
"authors": [...]}
Usage:
python fetch_articles.py # 500 articles, seed 42
python fetch_articles.py --sample 2000
python fetch_articles.py --all # every article in the index
"""
import argparse
import json
import os
import random
import requests
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 SystemExit(
"INSE_ELASTIC_API_KEY ist nicht gesetzt. Lege eine .env an oder exportiere die Variable."
)
ES_HEADERS = {
"Authorization": f"ApiKey {INSE_API_KEY}",
"Content-Type": "application/json",
}
RANDOM_SEED = 42
OUTPUT_FILE = "data/articles.jsonl"
MGET_CHUNK = 200
def scroll_ids(index):
"""Returns every _id of an index via a scrolling search."""
ids = []
response = requests.post(
f"{INSE_URL}/{index}/_search?scroll=2m",
json={"query": {"match_all": {}}, "_source": False, "size": 1000},
headers=ES_HEADERS,
)
response.raise_for_status()
data = response.json()
scroll_id = data.get("_scroll_id")
hits = data["hits"]["hits"]
while hits:
ids.extend(hit["_id"] for hit in hits)
response = requests.post(
f"{INSE_URL}/_search/scroll",
json={"scroll": "2m", "scroll_id": scroll_id},
headers=ES_HEADERS,
)
response.raise_for_status()
data = response.json()
scroll_id = data.get("_scroll_id")
hits = data["hits"]["hits"]
if scroll_id:
requests.delete(
f"{INSE_URL}/_search/scroll",
json={"scroll_id": [scroll_id]},
headers=ES_HEADERS,
)
return ids
def mget(index, ids, source_fields):
"""Fetches documents by id in chunks.
The `ids` body form of _mget takes no top-level `_source`; source
filtering has to go into the query string, otherwise Elasticsearch
answers 400.
"""
documents = []
params = {"_source": ",".join(source_fields)} if source_fields else None
for start in range(0, len(ids), MGET_CHUNK):
chunk = ids[start:start + MGET_CHUNK]
response = requests.post(
f"{INSE_URL}/{index}/_mget",
json={"ids": chunk},
params=params,
headers=ES_HEADERS,
)
response.raise_for_status()
documents.extend(response.json()["docs"])
return documents
def fetch_authors(news_ids):
"""Maps news_id -> extracted author names from aktuell_postproc.
Searched by the `news_id` field rather than fetched by document id: the
sync job POSTs to /_doc without an id, so Elasticsearch assigns a random
_id and an _mget on news_id would quietly find nothing. This mirrors how
the service resolves postproc entries.
"""
authors_by_id = {}
for start in range(0, len(news_ids), MGET_CHUNK):
chunk = news_ids[start:start + MGET_CHUNK]
response = requests.post(
f"{INSE_URL}/aktuell_postproc/_search",
json={
"query": {"terms": {"news_id.keyword": chunk}},
"_source": ["news_id", "authors"],
"size": min(len(chunk) * 2, 10000),
},
headers=ES_HEADERS,
)
response.raise_for_status()
for hit in response.json().get("hits", {}).get("hits", []):
source = hit.get("_source", {})
news_id = source.get("news_id")
if news_id:
authors_by_id[news_id] = source.get("authors") or []
return authors_by_id
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--sample", type=int, default=500, help="Stichprobengröße (Default: 500).")
parser.add_argument("--all", action="store_true", help="Alle Artikel statt einer Stichprobe.")
parser.add_argument("--seed", type=int, default=RANDOM_SEED, help="Zufalls-Seed.")
parser.add_argument("--output", default=OUTPUT_FILE)
args = parser.parse_args()
print("Hole alle _id aus dem Index 'aktuell'...")
all_ids = scroll_ids("aktuell")
print(f"{len(all_ids)} Artikel im Index.")
if args.all:
selected = all_ids
else:
if len(all_ids) < args.sample:
raise SystemExit("Nicht genug Dokumente für die Stichprobe.")
random.seed(args.seed)
selected = random.sample(all_ids, args.sample)
print(f"Ausgewählt: {len(selected)} Artikel (Seed={args.seed}).")
print("Hole Artikelinhalte...")
documents = mget("aktuell", selected, ["maintitle", "full_content", "date"])
print("Hole Autorennamen aus 'aktuell_postproc'...")
authors_by_id = fetch_authors(selected)
with_authors = sum(1 for names in authors_by_id.values() if names)
print(
f" {len(authors_by_id)}/{len(selected)} Artikel haben einen Postproc-Eintrag, "
f"davon {with_authors} mit Namen."
)
os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True)
written = 0
with open(args.output, "w", encoding="utf-8") as output_file:
for document in documents:
if not document.get("found"):
continue
source = document.get("_source", {})
news_id = document.get("_id")
record = {
"_id": news_id,
"maintitle": source.get("maintitle"),
"full_content": source.get("full_content"),
"date": source.get("date"),
"authors": authors_by_id.get(news_id, []),
}
output_file.write(json.dumps(record, ensure_ascii=False) + "\n")
written += 1
print(f"Fertig. {written} Datensätze in '{args.output}'.")
if __name__ == "__main__":
main()