feature/news-keyword-extraction #318
@@ -4,6 +4,9 @@
|
||||
service/*
|
||||
!service/scripts
|
||||
|
||||
# Keyword extraction contract, shared with background-jobs/app/llm/client.py.
|
||||
!service/src/main/inse/news/keyword_extraction.py
|
||||
|
||||
# Data-only folders that do not belong in the job image.
|
||||
service/scripts/multipliers
|
||||
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
try:
|
||||
# The job images copy this module next to sync.py, see
|
||||
# service/scripts/jobs-image/Dockerfile.
|
||||
import keyword_extraction
|
||||
except ModuleNotFoundError:
|
||||
# Running from a repo checkout, where it sits in the service package.
|
||||
sys.path.append(
|
||||
str(Path(__file__).resolve().parents[3] / "service/src/main/inse/news")
|
||||
)
|
||||
import keyword_extraction
|
||||
|
||||
load_dotenv()
|
||||
|
||||
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
|
||||
@@ -32,24 +45,33 @@ SYSTEM_PROMPT_NAMES = ("""
|
||||
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):
|
||||
def call(
|
||||
system_prompt,
|
||||
user_prompt,
|
||||
model=LLM_MODEL,
|
||||
temperature=1.0,
|
||||
top_p=0.95,
|
||||
top_k=64,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
):
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": schema_name or "response",
|
||||
"strict": True,
|
||||
"schema": json_schema,
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
response = _client.chat.completions.create(
|
||||
model=model,
|
||||
@@ -59,7 +81,8 @@ def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.9
|
||||
],
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
extra_body={"top_k": top_k},
|
||||
response_format=response_format,
|
||||
)
|
||||
except APIConnectionError:
|
||||
return None
|
||||
@@ -83,13 +106,37 @@ def extract_names(text: str) -> list[str]:
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
def extract_keywords(maintitle: str | None, full_content: str | None) -> list[str]:
|
||||
"""Extracts an article's keywords, identically to the news detail endpoint.
|
||||
|
||||
Prompt, input bound, sampling and normalization all come from
|
||||
keyword_extraction, so both callers write the same keywords into
|
||||
aktuell_postproc regardless of which one reaches an article first.
|
||||
"""
|
||||
user_prompt = keyword_extraction.build_user_prompt(maintitle, full_content)
|
||||
if not user_prompt:
|
||||
return []
|
||||
|
||||
result = call(
|
||||
keyword_extraction.KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt,
|
||||
temperature=keyword_extraction.TEMPERATURE,
|
||||
top_p=keyword_extraction.TOP_P,
|
||||
top_k=keyword_extraction.TOP_K,
|
||||
json_schema=keyword_extraction.RESPONSE_SCHEMA,
|
||||
schema_name=keyword_extraction.SCHEMA_NAME,
|
||||
)
|
||||
if result is None:
|
||||
return []
|
||||
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
candidates = data.get("keywords")
|
||||
if not isinstance(candidates, list):
|
||||
return []
|
||||
|
||||
return keyword_extraction.normalize_keywords(candidates)
|
||||
|
||||
@@ -20,10 +20,11 @@ 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"]
|
||||
article = es_client.get_entry("aktuell", news_id)["_source"]
|
||||
news_text = article["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)
|
||||
keywords = llm_client.extract_keywords(article.get("maintitle"), news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
@@ -48,8 +49,10 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr
|
||||
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)
|
||||
article = es_client.get_entry("aktuell", news_id)["_source"]
|
||||
keywords = llm_client.extract_keywords(
|
||||
article.get("maintitle"), article["full_content"]
|
||||
)
|
||||
if not keywords:
|
||||
# Empty article or unparseable LLM answer: writing an empty list
|
||||
# would look like a success and block a later retry.
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Arbeitsblatt und Auswertung für die manuelle Bewertung (Layer 2).
|
||||
|
||||
Layer 1 misst Regelkonformität, Layer 2 misst inhaltliche Qualität. Das geht
|
||||
nur von Hand, und zwar in drei Phasen — die Reihenfolge ist Teil der Methode:
|
||||
|
||||
Phase 1 --draw 50
|
||||
Arbeitsblatt ziehen und die *Soll-Begriffe* eintragen, BEVOR die
|
||||
Modellausgabe sichtbar ist. Sonst richtet sich die Annotation an
|
||||
den Vorschlägen des Modells aus und der Recall wird
|
||||
systematisch zu gut.
|
||||
|
||||
Phase 2 --attach --config neu
|
||||
Die extrahierten Keywords ins Arbeitsblatt einspielen und
|
||||
jedes einzeln bewerten.
|
||||
|
||||
Phase 3 --score
|
||||
Precision, Recall und die Verteilung der Urteile berechnen.
|
||||
|
||||
Bewertungsschema (vor der Annotation festgelegt):
|
||||
|
||||
"richtig" inhaltlich zentral für den Artikel und im Text verankert
|
||||
"akzeptabel" kommt vor und ist nicht irreführend, aber randständig, zu
|
||||
allgemein oder zu speziell — würde man selbst nicht wählen
|
||||
"falsch" irreführend, nicht aus dem Artikel, oder klarer Verstoß
|
||||
gegen die Aufgabe (Personenname, Datum, Floskel)
|
||||
|
||||
Soll-Begriffe: die ein bis drei Begriffe, ohne die eine Keywordliste zu
|
||||
diesem Artikel unvollständig wäre. Es geht um das Minimum, nicht
|
||||
um die ideale Liste.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import checks
|
||||
|
||||
ARTICLES_FILE = "data/articles.jsonl"
|
||||
RUNS_DIR = "runs"
|
||||
ANNOTATION_DIR = "annotation"
|
||||
WORKSHEET = os.path.join(ANNOTATION_DIR, "layer2_worksheet.json")
|
||||
RANDOM_SEED = 42
|
||||
|
||||
VERDICTS = ("richtig", "akzeptabel", "falsch")
|
||||
|
||||
|
||||
def load_jsonl(path):
|
||||
records = []
|
||||
with open(path, encoding="utf-8") as input_file:
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line:
|
||||
records.append(json.loads(line))
|
||||
return records
|
||||
|
||||
|
||||
def worksheet_entry(article):
|
||||
return {
|
||||
"_id": article["_id"],
|
||||
"maintitle": article.get("maintitle"),
|
||||
"full_content": article.get("full_content"),
|
||||
# Phase 1: hier die 1-3 Soll-Begriffe eintragen.
|
||||
"essential_keywords": [],
|
||||
# Phase 2 füllt das hier.
|
||||
"judgements": [],
|
||||
# Optional: Begriff -> true/false, falls der automatische
|
||||
# Abgleich in Phase 3 einen Soll-Begriff falsch zuordnet.
|
||||
"essential_overrides": {},
|
||||
}
|
||||
|
||||
|
||||
def replace(worksheet_path):
|
||||
"""Ersetzt nicht annotierte Artikel durch neue aus derselben Stichprobe."""
|
||||
worksheet = json.load(open(worksheet_path, encoding="utf-8"))
|
||||
keep = [article for article in worksheet if article["essential_keywords"]]
|
||||
drop = [article for article in worksheet if not article["essential_keywords"]]
|
||||
|
||||
if not drop:
|
||||
print("Alle Artikel im Arbeitsblatt sind annotiert — nichts zu ersetzen.")
|
||||
return
|
||||
|
||||
excluded_path = os.path.join(ANNOTATION_DIR, "excluded.json")
|
||||
excluded = []
|
||||
if os.path.exists(excluded_path):
|
||||
excluded = json.load(open(excluded_path, encoding="utf-8"))
|
||||
|
||||
for article in drop:
|
||||
excluded.append(
|
||||
{
|
||||
"_id": article["_id"],
|
||||
"maintitle": article.get("maintitle"),
|
||||
"content_length": len(article.get("full_content") or ""),
|
||||
"reason": None,
|
||||
}
|
||||
)
|
||||
|
||||
used = {article["_id"] for article in worksheet} | {item["_id"] for item in excluded}
|
||||
pool = [article for article in load_jsonl(ARTICLES_FILE) if article["_id"] not in used]
|
||||
if len(pool) < len(drop):
|
||||
raise SystemExit(f"Nur noch {len(pool)} unbenutzte Artikel in der Stichprobe.")
|
||||
|
||||
random.seed(RANDOM_SEED + len(excluded))
|
||||
replacements = random.sample(pool, len(drop))
|
||||
|
||||
os.makedirs(ANNOTATION_DIR, exist_ok=True)
|
||||
with open(worksheet_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(
|
||||
keep + [worksheet_entry(article) for article in replacements],
|
||||
output_file,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
with open(excluded_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(excluded, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"{len(drop)} Artikel ersetzt. Arbeitsblatt: {len(keep)} annotiert + {len(drop)} neu.")
|
||||
print(f"Aussortiert dokumentiert in {excluded_path}.\n")
|
||||
print("Neu zu annotieren:")
|
||||
for article in replacements:
|
||||
length = len(article.get("full_content") or "")
|
||||
print(f" {length:>6} Zeichen {article['_id']}")
|
||||
|
||||
|
||||
def draw(count, output):
|
||||
articles = load_jsonl(ARTICLES_FILE)
|
||||
random.seed(RANDOM_SEED)
|
||||
selected = random.sample(articles, min(count, len(articles)))
|
||||
|
||||
worksheet = [worksheet_entry(article) for article in selected]
|
||||
|
||||
os.makedirs(ANNOTATION_DIR, exist_ok=True)
|
||||
with open(output, "w", encoding="utf-8") as output_file:
|
||||
json.dump(worksheet, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"{len(worksheet)} Artikel -> {output}")
|
||||
print("\nPhase 1: pro Artikel 1-3 Soll-Begriffe in 'essential_keywords' eintragen.")
|
||||
print("Die Modellausgabe dabei NICHT ansehen.")
|
||||
|
||||
|
||||
def attach(config, worksheet_path):
|
||||
worksheet = json.load(open(worksheet_path, encoding="utf-8"))
|
||||
run = {
|
||||
entry["_id"]: entry
|
||||
for entry in load_jsonl(os.path.join(RUNS_DIR, f"{config}.jsonl"))
|
||||
if entry.get("repeat", 0) == 0
|
||||
}
|
||||
|
||||
missing = 0
|
||||
without_essentials = 0
|
||||
for article in worksheet:
|
||||
if not article["essential_keywords"]:
|
||||
without_essentials += 1
|
||||
|
||||
entry = run.get(article["_id"])
|
||||
if entry is None or entry.get("error"):
|
||||
missing += 1
|
||||
continue
|
||||
|
||||
existing = {item["keyword"]: item["verdict"] for item in article["judgements"]}
|
||||
article["judgements"] = [
|
||||
{"keyword": keyword, "verdict": existing.get(keyword)}
|
||||
for keyword in entry.get("keywords") or []
|
||||
]
|
||||
|
||||
with open(worksheet_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(worksheet, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
total = sum(len(article["judgements"]) for article in worksheet)
|
||||
print(f"{total} Keywords aus '{config}' eingespielt -> {worksheet_path}")
|
||||
if missing:
|
||||
print(f" {missing} Artikel ohne Lauf-Eintrag (noch nicht extrahiert?).")
|
||||
if without_essentials:
|
||||
print(
|
||||
f" WARNUNG: {without_essentials} Artikel ohne Soll-Begriffe. "
|
||||
"Phase 1 sollte vor Phase 2 abgeschlossen sein."
|
||||
)
|
||||
print(f"\nPhase 2: 'verdict' je Keyword auf {' / '.join(VERDICTS)} setzen.")
|
||||
|
||||
|
||||
def essential_covered(essential, keywords, overrides):
|
||||
"""Gilt ein Soll-Begriff als abgedeckt?
|
||||
|
||||
Automatischer Abgleich mit derselben flexionstoleranten Phrasenlogik wie
|
||||
L2.
|
||||
"""
|
||||
if essential in overrides:
|
||||
return bool(overrides[essential])
|
||||
|
||||
for keyword in keywords:
|
||||
index = checks.build_article_index(keyword)
|
||||
if checks.literal_l2(essential, index):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def score(worksheet_path):
|
||||
worksheet = json.load(open(worksheet_path, encoding="utf-8"))
|
||||
|
||||
counts = {verdict: 0 for verdict in VERDICTS}
|
||||
unjudged = 0
|
||||
essential_total = 0
|
||||
essential_hit = 0
|
||||
unmatched = []
|
||||
|
||||
for article in worksheet:
|
||||
keywords = [item["keyword"] for item in article["judgements"]]
|
||||
for item in article["judgements"]:
|
||||
verdict = item.get("verdict")
|
||||
if verdict in counts:
|
||||
counts[verdict] += 1
|
||||
else:
|
||||
unjudged += 1
|
||||
|
||||
overrides = article.get("essential_overrides") or {}
|
||||
for essential in article.get("essential_keywords") or []:
|
||||
essential_total += 1
|
||||
if essential_covered(essential, keywords, overrides):
|
||||
essential_hit += 1
|
||||
else:
|
||||
unmatched.append((article["_id"], essential, keywords))
|
||||
|
||||
judged = sum(counts.values())
|
||||
if not judged:
|
||||
raise SystemExit("Keine 'verdict'-Werte gesetzt.")
|
||||
|
||||
print("## Layer 2 — inhaltliche Bewertung\n")
|
||||
print(f"Bewertete Keywords: {judged}" + (f" (offen: {unjudged})" if unjudged else ""))
|
||||
for verdict in VERDICTS:
|
||||
share = 100.0 * counts[verdict] / judged
|
||||
print(f" {verdict:<12} {counts[verdict]:>4} ({share:.1f} %)".replace(".", ","))
|
||||
|
||||
precision = 100.0 * (counts["richtig"] + counts["akzeptabel"]) / judged
|
||||
strict = 100.0 * counts["richtig"] / judged
|
||||
print(f"\nPrecision (richtig + akzeptabel): {precision:.1f} %".replace(".", ","))
|
||||
print(f"Precision (nur richtig): {strict:.1f} %".replace(".", ","))
|
||||
|
||||
if essential_total:
|
||||
recall = 100.0 * essential_hit / essential_total
|
||||
print(
|
||||
f"\nSoll-Begriff-Recall: {essential_hit}/{essential_total} "
|
||||
f"({recall:.1f} %)".replace(".", ",")
|
||||
)
|
||||
if unmatched:
|
||||
print("\nNicht abgedeckte Soll-Begriffe (auf Fehlzuordnung prüfen):")
|
||||
for news_id, essential, keywords in unmatched[:20]:
|
||||
print(f" [{news_id[:35]}] {essential!r} vs {keywords}")
|
||||
else:
|
||||
print("\nKeine Soll-Begriffe eingetragen — Recall nicht berechenbar.")
|
||||
|
||||
results = {
|
||||
"judged": judged,
|
||||
"counts": counts,
|
||||
"precision_incl_acceptable": round(precision, 1),
|
||||
"precision_strict": round(strict, 1),
|
||||
"essential_total": essential_total,
|
||||
"essential_hit": essential_hit,
|
||||
}
|
||||
with open("results_layer2.json", "w", encoding="utf-8") as output_file:
|
||||
json.dump(results, output_file, ensure_ascii=False, indent=2)
|
||||
print("\n-> results_layer2.json")
|
||||
|
||||
|
||||
def kappa(first_path, second_path):
|
||||
"""Cohen's Kappa zwischen zwei unabhängig annotierten Arbeitsblättern."""
|
||||
first = {
|
||||
(article["_id"], item["keyword"]): item.get("verdict")
|
||||
for article in json.load(open(first_path, encoding="utf-8"))
|
||||
for item in article["judgements"]
|
||||
}
|
||||
second = {
|
||||
(article["_id"], item["keyword"]): item.get("verdict")
|
||||
for article in json.load(open(second_path, encoding="utf-8"))
|
||||
for item in article["judgements"]
|
||||
}
|
||||
|
||||
shared = [
|
||||
(first[key], second[key])
|
||||
for key in first.keys() & second.keys()
|
||||
if first[key] in VERDICTS and second[key] in VERDICTS
|
||||
]
|
||||
if not shared:
|
||||
raise SystemExit("Keine gemeinsam bewerteten Keywords gefunden.")
|
||||
|
||||
agreed = sum(1 for left, right in shared if left == right)
|
||||
observed = agreed / len(shared)
|
||||
|
||||
expected = 0.0
|
||||
for verdict in VERDICTS:
|
||||
left_share = sum(1 for left, _ in shared if left == verdict) / len(shared)
|
||||
right_share = sum(1 for _, right in shared if right == verdict) / len(shared)
|
||||
expected += left_share * right_share
|
||||
|
||||
value = (observed - expected) / (1 - expected) if expected < 1 else 1.0
|
||||
print(f"Gemeinsam bewertet: {len(shared)}")
|
||||
print(f"Übereinstimmung: {100 * observed:.1f} %".replace(".", ","))
|
||||
print(f"Cohens Kappa: {value:.3f}".replace(".", ","))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--draw", type=int, metavar="N", help="Phase 1: Arbeitsblatt ziehen.")
|
||||
parser.add_argument(
|
||||
"--replace",
|
||||
action="store_true",
|
||||
help="Nicht annotierte Artikel durch neue aus der Stichprobe ersetzen.",
|
||||
)
|
||||
parser.add_argument("--attach", action="store_true", help="Phase 2: Keywords einspielen.")
|
||||
parser.add_argument("--config", default="neu", help="Lauf für --attach (Default: neu).")
|
||||
parser.add_argument("--score", action="store_true", help="Phase 3: auswerten.")
|
||||
parser.add_argument("--kappa", metavar="ZWEITES_BLATT", help="Cohens Kappa gegen ein zweites Arbeitsblatt.")
|
||||
parser.add_argument("--worksheet", default=WORKSHEET)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.draw:
|
||||
draw(args.draw, args.worksheet)
|
||||
elif args.replace:
|
||||
replace(args.worksheet)
|
||||
elif args.attach:
|
||||
attach(args.config, args.worksheet)
|
||||
elif args.score:
|
||||
score(args.worksheet)
|
||||
elif args.kappa:
|
||||
kappa(args.worksheet, args.kappa)
|
||||
else:
|
||||
parser.print_help()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{
|
||||
"_id": "30112023_UlrikeBohnsack_Altrektorverstorben",
|
||||
"maintitle": "Altrektor verstorben",
|
||||
"content_length": 2293,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "11062015__Aufarbeiten,anerkennenunderinnern_archiv",
|
||||
"maintitle": "Aufarbeiten, anerkennen und erinnern",
|
||||
"content_length": 1369,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "27072021_UlrikeEichweber_LehrenziehenausderPandemie",
|
||||
"maintitle": "Lehren ziehen aus der Pandemie",
|
||||
"content_length": 826,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "05042017_ManuelaMnch_Jubilare-April2017",
|
||||
"maintitle": "Jubilare - April 2017",
|
||||
"content_length": 81,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "26072023_UlrikeEichweber_HilfefrdieHausarbeit",
|
||||
"maintitle": "Hilfe für die Hausarbeit",
|
||||
"content_length": 758,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "05112019_ManuelaMnch_Lehrstuhlvertretungen-November2019",
|
||||
"maintitle": "Lehrstuhlvertretungen - November 2019",
|
||||
"content_length": 182,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "07102005_ChristophLindemann_Kraft-Wrme-KopplungimFokus_archiv",
|
||||
"maintitle": "Kraft-Wärme-Kopplung im Fokus",
|
||||
"content_length": 3348,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "11122019_ManuelaMnch_Umhabilitationen-Dezember2019",
|
||||
"maintitle": "Umhabilitationen - Dezember 2019",
|
||||
"content_length": 234,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "17082018_ManuelaMnch_Seniorprofessuren-September2018",
|
||||
"maintitle": "Seniorprofessuren - September 2018",
|
||||
"content_length": 96,
|
||||
"reason": null
|
||||
}
|
||||
]
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"0": "rrrarr",
|
||||
"1": "rrrrra",
|
||||
"2": "rrrraa",
|
||||
"3": "rraaa",
|
||||
"4": "rrraaa",
|
||||
"5": "rrrrra",
|
||||
"6": "rraaaa",
|
||||
"7": "arraaa",
|
||||
"8": "raarr",
|
||||
"9": "rraaar",
|
||||
"10": "rrrraa",
|
||||
"11": "rrrraa",
|
||||
"12": "rraaaa",
|
||||
"13": "araaaa",
|
||||
"14": "aaaaaa",
|
||||
"15": "raaaaa",
|
||||
"16": "rraaaf",
|
||||
"17": "rraaaa",
|
||||
"18": "rrarar",
|
||||
"19": "rrraaa",
|
||||
"20": "raa",
|
||||
"21": "rraaaa",
|
||||
"22": "raarar",
|
||||
"23": "rarrra",
|
||||
"24": "rrrrar",
|
||||
"25": "rraaaa",
|
||||
"26": "aaaaaa",
|
||||
"27": "rarraa",
|
||||
"28": "rrrafa",
|
||||
"29": "rafraa",
|
||||
"30": "rraaaa",
|
||||
"31": "rrafar",
|
||||
"32": "rraara",
|
||||
"33": "rraaaa",
|
||||
"34": "rrrrfa",
|
||||
"35": "rraraa",
|
||||
"36": "rraaaa",
|
||||
"37": "rrrrra",
|
||||
"38": "rraaaa",
|
||||
"39": "rrrrfa",
|
||||
"40": "rrraaf",
|
||||
"41": "rraaaa",
|
||||
"42": "rraaa",
|
||||
"43": "rraaaa",
|
||||
"44": "rrrraa",
|
||||
"45": "rrrraa",
|
||||
"46": "rrraaa",
|
||||
"47": "raraaa",
|
||||
"48": "rraaaa",
|
||||
"49": "rrrrra"
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
"""Deterministic Layer-1 checks for extracted news keywords.
|
||||
|
||||
Every check mirrors a rule the extraction prompt states, so the result is a
|
||||
compliance rate rather than a quality judgement. A check returns:
|
||||
|
||||
True — rule satisfied
|
||||
False — rule violated
|
||||
None — not determinable (e.g. spaCy missing, or no noun to inspect)
|
||||
|
||||
`None` is counted separately in evaluate.py and never silently folded into the
|
||||
pass or fail bucket.
|
||||
|
||||
Levels of "appears literally in the text" (L0 ⊆ L1 ⊆ L2):
|
||||
|
||||
L0 exact case-folded, word-boundary match in title + content
|
||||
L1 normalized additionally NFKC, collapsed whitespace, hyphens removed
|
||||
L2 lemma every token of the keyword matches a token lemma of the
|
||||
article (requires spaCy)
|
||||
|
||||
L2 is the primary metric: the prompt demands base forms ("Nominativ
|
||||
Singular"), so a keyword may legitimately differ from the inflected surface
|
||||
form in the article. L0 and L1 are reported as stricter bounds.
|
||||
"""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
# --- optional spaCy -------------------------------------------------------
|
||||
|
||||
_NLP = None
|
||||
_SPACY_TRIED = False
|
||||
|
||||
|
||||
def get_nlp():
|
||||
"""Loads de_core_news_sm once; returns None when spaCy is unavailable."""
|
||||
global _NLP, _SPACY_TRIED
|
||||
if _SPACY_TRIED:
|
||||
return _NLP
|
||||
_SPACY_TRIED = True
|
||||
try:
|
||||
import spacy
|
||||
|
||||
_NLP = spacy.load("de_core_news_sm")
|
||||
except Exception:
|
||||
_NLP = None
|
||||
return _NLP
|
||||
|
||||
|
||||
# --- text normalization ---------------------------------------------------
|
||||
|
||||
_WHITESPACE = re.compile(r"\s+")
|
||||
_HYPHENS = re.compile(r"[-‐-―]")
|
||||
|
||||
|
||||
def casefold_text(text):
|
||||
return unicodedata.normalize("NFKC", text or "").casefold()
|
||||
|
||||
|
||||
def normalize_text(text):
|
||||
"""NFKC + casefold + hyphens removed + whitespace collapsed."""
|
||||
text = casefold_text(text)
|
||||
text = _HYPHENS.sub("", text)
|
||||
return _WHITESPACE.sub(" ", text).strip()
|
||||
|
||||
|
||||
def _contains_with_boundaries(haystack, needle):
|
||||
if not needle:
|
||||
return False
|
||||
pattern = r"(?<!\w)" + re.escape(needle) + r"(?!\w)"
|
||||
return re.search(pattern, haystack) is not None
|
||||
|
||||
|
||||
# --- literal occurrence ---------------------------------------------------
|
||||
|
||||
def literal_l0(keyword, article_text):
|
||||
return _contains_with_boundaries(casefold_text(article_text), casefold_text(keyword))
|
||||
|
||||
|
||||
def literal_l1(keyword, article_text):
|
||||
"""L0 oder ein Treffer nach Normalisierung.
|
||||
|
||||
Die L0-Disjunktion ist nötig, damit L0 ⊆ L1 per Konstruktion gilt: das
|
||||
Entfernen der Bindestriche kann Komposita verschmelzen und dadurch eine
|
||||
Wortgrenze zerstören ("S-Bahn" trifft in "S-Bahn-Station", "sbahn" nicht
|
||||
mehr in "sbahnstation"). Ohne die Disjunktion läge L1 in genau diesen
|
||||
Fällen unter L0.
|
||||
"""
|
||||
if literal_l0(keyword, article_text):
|
||||
return True
|
||||
return _contains_with_boundaries(normalize_text(article_text), normalize_text(keyword))
|
||||
|
||||
|
||||
_WORD = re.compile(r"\w+")
|
||||
|
||||
|
||||
def _inflection_tolerance(token):
|
||||
"""How many trailing characters may differ, by token length.
|
||||
|
||||
German inflection is suffixal and short ("-e", "-en", "-er", "-s"), so a
|
||||
small bounded tolerance captures it. The bound also keeps compounds apart:
|
||||
"Forschung" does not match "Forschungsprojekt" (8 extra characters), which
|
||||
is exactly the generalization the prompt forbids.
|
||||
"""
|
||||
length = len(token)
|
||||
if length >= 6:
|
||||
return 3
|
||||
if length >= 4:
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
def _spacy_tokens(text, nlp):
|
||||
"""(lemma, surface) pairs of a text, punctuation and whitespace dropped."""
|
||||
document = nlp(text or "")
|
||||
return [
|
||||
(token.lemma_.casefold(), token.text.casefold())
|
||||
for token in document
|
||||
if not token.is_punct and not token.is_space
|
||||
]
|
||||
|
||||
|
||||
def build_article_index(article_text, nlp=None):
|
||||
"""Prepares an article for the L2 check.
|
||||
|
||||
Both variants keep the token **order**, because L2 requires a multi-word
|
||||
keyword to occur as a contiguous phrase — "Forschung und Entwicklung" must
|
||||
not count merely because all three words appear somewhere in the article.
|
||||
|
||||
With spaCy: lemma/surface pairs, the linguistically correct basis. Without
|
||||
it: normalized surface tokens, matched suffix-tolerantly. The method is
|
||||
part of the index so callers can tell which one produced the numbers.
|
||||
"""
|
||||
nlp = nlp or get_nlp()
|
||||
|
||||
if nlp is None:
|
||||
return {
|
||||
"method": "flexion",
|
||||
"tokens": _WORD.findall(normalize_text(article_text)),
|
||||
}
|
||||
|
||||
return {"method": "lemma", "tokens": _spacy_tokens(article_text, nlp)}
|
||||
|
||||
|
||||
def _tokens_match_with_inflection(keyword_token, article_token):
|
||||
"""One token pair, allowing a short suffix on either side.
|
||||
|
||||
The article may inflect the keyword's base form ("Forschungsprojekt" vs
|
||||
"Forschungsprojekte"), or the keyword may itself be the longer surface
|
||||
form. The bound keeps compounds apart: "Forschung" never matches
|
||||
"Forschungsprojekt".
|
||||
"""
|
||||
if keyword_token == article_token:
|
||||
return True
|
||||
if article_token.startswith(keyword_token):
|
||||
return len(article_token) - len(keyword_token) <= _inflection_tolerance(keyword_token)
|
||||
if keyword_token.startswith(article_token):
|
||||
return len(keyword_token) - len(article_token) <= _inflection_tolerance(article_token)
|
||||
return False
|
||||
|
||||
|
||||
def _lemma_tokens_match(keyword_token, article_token):
|
||||
keyword_lemma, keyword_surface = keyword_token
|
||||
article_lemma, article_surface = article_token
|
||||
return (
|
||||
keyword_lemma == article_lemma
|
||||
or keyword_lemma == article_surface
|
||||
or keyword_surface == article_surface
|
||||
)
|
||||
|
||||
|
||||
def _contiguous_match(keyword_tokens, article_tokens, compare):
|
||||
"""True when the keyword tokens occur as a contiguous run, in order."""
|
||||
span = len(keyword_tokens)
|
||||
if span == 0 or span > len(article_tokens):
|
||||
return False
|
||||
for start in range(len(article_tokens) - span + 1):
|
||||
if all(
|
||||
compare(keyword_tokens[offset], article_tokens[start + offset])
|
||||
for offset in range(span)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def literal_l2(keyword, index, nlp=None):
|
||||
"""True when the keyword occurs in the article as a contiguous phrase.
|
||||
|
||||
Each token may differ by inflection — identical lemma with spaCy, a short
|
||||
suffix without it — but the tokens must be adjacent and in order. That is
|
||||
the level at which the two prompt rules ("kommt im Text vor" and
|
||||
"Grundform") are satisfiable at the same time: the term is genuinely taken
|
||||
from the text, only its form is normalized.
|
||||
"""
|
||||
if index is None:
|
||||
return None
|
||||
|
||||
if index["method"] == "lemma":
|
||||
nlp = nlp or get_nlp()
|
||||
if nlp is None:
|
||||
return None
|
||||
keyword_tokens = _spacy_tokens(keyword, nlp)
|
||||
return _contiguous_match(keyword_tokens, index["tokens"], _lemma_tokens_match)
|
||||
|
||||
keyword_tokens = _WORD.findall(normalize_text(keyword))
|
||||
return _contiguous_match(keyword_tokens, index["tokens"], _tokens_match_with_inflection)
|
||||
|
||||
|
||||
# --- per-article structure ------------------------------------------------
|
||||
|
||||
def count_ok(raw_keywords, limit):
|
||||
"""At most `limit` keywords in the RAW model output."""
|
||||
if raw_keywords is None:
|
||||
return None
|
||||
return len(raw_keywords) <= limit
|
||||
|
||||
|
||||
def no_duplicates(raw_keywords):
|
||||
"""No case-insensitive duplicates in the RAW model output."""
|
||||
if raw_keywords is None:
|
||||
return None
|
||||
seen = [item.strip().casefold() for item in raw_keywords if isinstance(item, str)]
|
||||
return len(seen) == len(set(seen))
|
||||
|
||||
|
||||
MIN_STEM_LENGTH = 4
|
||||
|
||||
|
||||
def no_stem_redundancy(keywords):
|
||||
"""No keyword is contained in another ("Forschung" next to "Forschungsprojekt").
|
||||
|
||||
Plain containment rather than a stemmer: Snowball maps those two examples
|
||||
to different stems, so stemming would miss the case the prompt names.
|
||||
"""
|
||||
if keywords is None:
|
||||
return None
|
||||
normalized = [normalize_text(item) for item in keywords if isinstance(item, str)]
|
||||
normalized = [item for item in normalized if len(item) >= MIN_STEM_LENGTH]
|
||||
for i, left in enumerate(normalized):
|
||||
for j, right in enumerate(normalized):
|
||||
if i != j and left in right and left != right:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def redundant_pairs(keywords):
|
||||
"""The offending pairs, for qualitative inspection."""
|
||||
pairs = []
|
||||
normalized = {
|
||||
item: normalize_text(item) for item in keywords if isinstance(item, str)
|
||||
}
|
||||
for left, left_norm in normalized.items():
|
||||
if len(left_norm) < MIN_STEM_LENGTH:
|
||||
continue
|
||||
for right, right_norm in normalized.items():
|
||||
if left is not right and left_norm in right_norm and left_norm != right_norm:
|
||||
pairs.append((left, right))
|
||||
return pairs
|
||||
|
||||
|
||||
# --- forbidden content ----------------------------------------------------
|
||||
|
||||
_MONTH_NAMES = {
|
||||
"januar", "februar", "märz", "april", "mai", "juni", "juli",
|
||||
"august", "september", "oktober", "november", "dezember",
|
||||
}
|
||||
_YEAR = re.compile(r"^(19|20)\d{2}$")
|
||||
_FULL_DATE = re.compile(r"(?<!\d)\d{1,2}\.\s?\d{1,2}\.\s?(19|20)?\d{2}(?!\d)")
|
||||
|
||||
|
||||
def no_date(keyword):
|
||||
"""False, wenn das Schlagwort eine Datumsangabe ist.
|
||||
|
||||
Eine Jahreszahl *innerhalb* eines längeren Begriffs zählt nicht: sie
|
||||
gehört dort in aller Regel zu einem Eigennamen ("Horizont 2020",
|
||||
"Agenda 2010", "EUSA Games 2020"), und Programm- und Veranstaltungsnamen
|
||||
verbietet der Prompt nicht. Gemeldet wird deshalb nur, was ausschließlich
|
||||
aus Datumsbestandteilen besteht, sowie ein vollständiges Tagesdatum an
|
||||
beliebiger Stelle.
|
||||
|
||||
Grenzfall: "Sommersemester 2015" gilt damit als konform, obwohl es eine
|
||||
Zeitangabe enthält. Das ist bewusst die vorsichtigere Richtung — falsch
|
||||
gemeldete Eigennamen wären der teurere Fehler.
|
||||
"""
|
||||
if _FULL_DATE.search(casefold_text(keyword)):
|
||||
return False
|
||||
|
||||
tokens = _WORD.findall(normalize_text(keyword))
|
||||
if not tokens:
|
||||
return True
|
||||
|
||||
return not all(
|
||||
_YEAR.match(token) or token in _MONTH_NAMES or token.isdigit()
|
||||
for token in tokens
|
||||
)
|
||||
|
||||
|
||||
MIN_NAME_TOKEN = 3
|
||||
|
||||
|
||||
def no_person_name_authors(keyword, authors):
|
||||
"""False when the keyword is one of the article's own extracted names.
|
||||
|
||||
Uses the `authors` field the pipeline already produces, so this check
|
||||
needs no external model and no annotation.
|
||||
"""
|
||||
if authors is None:
|
||||
return None
|
||||
keyword_norm = normalize_text(keyword)
|
||||
if not keyword_norm:
|
||||
return True
|
||||
|
||||
for author in authors:
|
||||
author_norm = normalize_text(author)
|
||||
if not author_norm:
|
||||
continue
|
||||
if keyword_norm == author_norm:
|
||||
return False
|
||||
parts = [part for part in author_norm.split() if len(part) >= MIN_NAME_TOKEN]
|
||||
if keyword_norm in parts:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def no_person_name_ner(keyword, nlp=None):
|
||||
"""False when spaCy tags the whole keyword as a person entity."""
|
||||
nlp = nlp or get_nlp()
|
||||
if nlp is None:
|
||||
return None
|
||||
document = nlp(keyword or "")
|
||||
for entity in document.ents:
|
||||
if entity.label_ == "PER" and entity.text.strip() == (keyword or "").strip():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# --- grammatical form -----------------------------------------------------
|
||||
|
||||
def base_form(keyword, nlp=None):
|
||||
"""True when the keyword's head noun is nominative singular.
|
||||
|
||||
German head nouns sit at the end of a phrase, so the last NOUN/PROPN token
|
||||
is inspected. Returns None when the keyword contains no noun at all.
|
||||
"""
|
||||
nlp = nlp or get_nlp()
|
||||
if nlp is None:
|
||||
return None
|
||||
|
||||
document = nlp(keyword or "")
|
||||
nouns = [token for token in document if token.pos_ in ("NOUN", "PROPN")]
|
||||
if not nouns:
|
||||
return None
|
||||
|
||||
head = nouns[-1]
|
||||
numbers = head.morph.get("Number")
|
||||
cases = head.morph.get("Case")
|
||||
if not numbers or not cases:
|
||||
return None
|
||||
return "Sing" in numbers and "Nom" in cases
|
||||
|
||||
|
||||
# --- aggregation helpers --------------------------------------------------
|
||||
|
||||
def check_keyword(keyword, article_text, index, authors, nlp=None):
|
||||
"""All keyword-level checks for one keyword."""
|
||||
l0 = literal_l0(keyword, article_text)
|
||||
l1 = literal_l1(keyword, article_text)
|
||||
|
||||
# L0 ⊆ L1 ⊆ L2, so the expensive pass only runs where L1 already failed.
|
||||
if l1:
|
||||
l2 = True
|
||||
else:
|
||||
l2 = literal_l2(keyword, index, nlp=nlp)
|
||||
|
||||
return {
|
||||
"literal_l0": l0,
|
||||
"literal_l1": l1,
|
||||
"literal_l2": l2,
|
||||
"no_person_name_authors": no_person_name_authors(keyword, authors),
|
||||
"no_person_name_ner": no_person_name_ner(keyword, nlp=nlp),
|
||||
"no_date": no_date(keyword),
|
||||
"base_form": base_form(keyword, nlp=nlp),
|
||||
}
|
||||
|
||||
|
||||
def check_article(raw_keywords, keywords, limit):
|
||||
"""All article-level checks for one article."""
|
||||
return {
|
||||
"count_ok": count_ok(raw_keywords, limit),
|
||||
"no_duplicates": no_duplicates(raw_keywords),
|
||||
"no_stem_redundancy": no_stem_redundancy(keywords),
|
||||
}
|
||||
|
||||
|
||||
def jaccard(left, right):
|
||||
"""Set overlap of two keyword lists, case-insensitive."""
|
||||
left_set = {item.casefold() for item in left if isinstance(item, str)}
|
||||
right_set = {item.casefold() for item in right if isinstance(item, str)}
|
||||
if not left_set and not right_set:
|
||||
return 1.0
|
||||
if not left_set or not right_set:
|
||||
return 0.0
|
||||
return len(left_set & right_set) / len(left_set | right_set)
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Applies the Layer-1 checks to an extraction run and aggregates the counts.
|
||||
|
||||
Separate from extract_keywords.py on purpose: the LLM calls are slow and cost
|
||||
GPU time, the checks are cheap, so a changed check definition must not force a
|
||||
re-extraction.
|
||||
|
||||
Writes
|
||||
results_<config>.json aggregated counts for results.py
|
||||
decisions/<config>.jsonl one record per keyword decision, for manual review
|
||||
|
||||
Usage:
|
||||
python evaluate.py --config neu
|
||||
python evaluate.py --config alt
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import sys
|
||||
from collections import Counter
|
||||
from itertools import combinations
|
||||
from pathlib import Path
|
||||
|
||||
import checks
|
||||
|
||||
sys.path.append(str(Path(__file__).resolve().parents[2] / "service/src/main/inse/news"))
|
||||
import keyword_extraction # noqa: E402
|
||||
|
||||
ARTICLES_FILE = "data/articles.jsonl"
|
||||
RUNS_DIR = "runs"
|
||||
DECISIONS_DIR = "decisions"
|
||||
MAX_EXAMPLES = 25
|
||||
|
||||
KEYWORD_CHECKS = [
|
||||
"literal_l0",
|
||||
"literal_l1",
|
||||
"literal_l2",
|
||||
"no_person_name_authors",
|
||||
"no_person_name_ner",
|
||||
"no_date",
|
||||
"base_form",
|
||||
]
|
||||
ARTICLE_CHECKS = ["count_ok", "no_duplicates", "no_stem_redundancy"]
|
||||
|
||||
|
||||
def load_jsonl(path):
|
||||
records = []
|
||||
with open(path, encoding="utf-8") as input_file:
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line:
|
||||
records.append(json.loads(line))
|
||||
return records
|
||||
|
||||
|
||||
def empty_tally():
|
||||
return {"pass": 0, "fail": 0, "na": 0}
|
||||
|
||||
|
||||
def tally(bucket, value):
|
||||
if value is None:
|
||||
bucket["na"] += 1
|
||||
elif value:
|
||||
bucket["pass"] += 1
|
||||
else:
|
||||
bucket["fail"] += 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", required=True)
|
||||
parser.add_argument("--articles", default=ARTICLES_FILE)
|
||||
parser.add_argument("--run", default=None, help="Default: runs/<config>.jsonl")
|
||||
args = parser.parse_args()
|
||||
|
||||
run_path = args.run or os.path.join(RUNS_DIR, f"{args.config}.jsonl")
|
||||
if not os.path.exists(run_path):
|
||||
raise SystemExit(
|
||||
f"'{run_path}' existiert nicht — für '{args.config}' wurde noch nicht "
|
||||
f"extrahiert.\nZuerst: python extract_keywords.py --config {args.config}"
|
||||
)
|
||||
|
||||
articles = {record["_id"]: record for record in load_jsonl(args.articles)}
|
||||
run_records = load_jsonl(run_path)
|
||||
|
||||
nlp = checks.get_nlp()
|
||||
if nlp is None:
|
||||
print(
|
||||
"Hinweis: spaCy/de_core_news_sm nicht verfügbar.\n"
|
||||
" L2 läuft über den Flexions-Fallback (suffixtolerant, ohne Abhängigkeit).\n"
|
||||
" Grundform- und NER-Prüfung werden als 'n. v.' gezählt."
|
||||
)
|
||||
|
||||
keyword_tallies = {name: empty_tally() for name in KEYWORD_CHECKS}
|
||||
article_tallies = {name: empty_tally() for name in ARTICLE_CHECKS}
|
||||
article_tallies["literal_all"] = empty_tally()
|
||||
|
||||
errors = Counter()
|
||||
keyword_counts = []
|
||||
examples = {name: [] for name in KEYWORD_CHECKS + ARTICLE_CHECKS}
|
||||
decisions = []
|
||||
by_article_repeats = {}
|
||||
|
||||
keywords_total = 0
|
||||
articles_evaluated = 0
|
||||
|
||||
for entry in run_records:
|
||||
news_id = entry["_id"]
|
||||
by_article_repeats.setdefault(news_id, []).append(entry)
|
||||
|
||||
# Only the first repeat feeds the compliance counts; the extra repeats
|
||||
# exist for the reproducibility measure and would otherwise weight
|
||||
# those articles more heavily.
|
||||
if entry.get("repeat", 0) != 0:
|
||||
continue
|
||||
|
||||
if entry.get("error"):
|
||||
errors[entry["error"].split(":")[0]] += 1
|
||||
continue
|
||||
|
||||
article = articles.get(news_id)
|
||||
if article is None:
|
||||
errors["article_missing"] += 1
|
||||
continue
|
||||
|
||||
articles_evaluated += 1
|
||||
raw_keywords = entry.get("raw_keywords")
|
||||
keywords = entry.get("keywords") or []
|
||||
keyword_counts.append(len(raw_keywords) if raw_keywords is not None else 0)
|
||||
|
||||
article_text = " ".join(
|
||||
part for part in (article.get("maintitle"), article.get("full_content")) if part
|
||||
)
|
||||
authors = article.get("authors")
|
||||
|
||||
article_results = checks.check_article(
|
||||
raw_keywords, keywords, keyword_extraction.KEYWORD_LIMIT
|
||||
)
|
||||
for name, value in article_results.items():
|
||||
tally(article_tallies[name], value)
|
||||
if value is False and len(examples[name]) < MAX_EXAMPLES:
|
||||
detail = {"_id": news_id, "keywords": raw_keywords}
|
||||
if name == "no_stem_redundancy":
|
||||
detail["pairs"] = checks.redundant_pairs(keywords)
|
||||
examples[name].append(detail)
|
||||
|
||||
# Building the article index is the expensive part, so do it only when
|
||||
# some keyword actually needs it.
|
||||
index = None
|
||||
index_built = False
|
||||
article_literal_ok = True
|
||||
article_literal_undecided = False
|
||||
|
||||
for keyword in keywords:
|
||||
if not isinstance(keyword, str) or not keyword.strip():
|
||||
continue
|
||||
keywords_total += 1
|
||||
|
||||
if not index_built and not checks.literal_l1(keyword, article_text):
|
||||
index = checks.build_article_index(article_text, nlp=nlp)
|
||||
index_built = True
|
||||
|
||||
results = checks.check_keyword(keyword, article_text, index, authors, nlp=nlp)
|
||||
for name, value in results.items():
|
||||
tally(keyword_tallies[name], value)
|
||||
if value is False and len(examples[name]) < MAX_EXAMPLES:
|
||||
examples[name].append({"_id": news_id, "keyword": keyword})
|
||||
|
||||
if results["literal_l2"] is False:
|
||||
article_literal_ok = False
|
||||
elif results["literal_l2"] is None:
|
||||
article_literal_undecided = True
|
||||
|
||||
decisions.append({"_id": news_id, "keyword": keyword, **results})
|
||||
|
||||
# A single undecidable keyword makes the whole article undecidable —
|
||||
# otherwise a missing spaCy model would silently report every article
|
||||
# as compliant.
|
||||
if article_literal_ok and article_literal_undecided:
|
||||
tally(article_tallies["literal_all"], None)
|
||||
else:
|
||||
tally(article_tallies["literal_all"], article_literal_ok)
|
||||
|
||||
# Reproducibility: mean pairwise Jaccard across repeats of the same article.
|
||||
determinism = None
|
||||
repeated = {
|
||||
news_id: entries
|
||||
for news_id, entries in by_article_repeats.items()
|
||||
if len({entry.get("repeat", 0) for entry in entries}) > 1
|
||||
}
|
||||
if repeated:
|
||||
scores = []
|
||||
for entries in repeated.values():
|
||||
usable = [entry["keywords"] for entry in entries if not entry.get("error")]
|
||||
if len(usable) < 2:
|
||||
continue
|
||||
scores.extend(
|
||||
checks.jaccard(left, right) for left, right in combinations(usable, 2)
|
||||
)
|
||||
if scores:
|
||||
determinism = {
|
||||
"articles": len(repeated),
|
||||
"repeats": max(len(entries) for entries in repeated.values()),
|
||||
"mean_pairwise_jaccard": round(statistics.mean(scores), 4),
|
||||
"identical_share": round(
|
||||
sum(1 for score in scores if score == 1.0) / len(scores), 4
|
||||
),
|
||||
}
|
||||
|
||||
results = {
|
||||
"config": args.config,
|
||||
"l2_method": "lemma" if nlp is not None else "flexion",
|
||||
"articles_evaluated": articles_evaluated,
|
||||
"keywords_total": keywords_total,
|
||||
"errors": dict(errors),
|
||||
"keyword_level": keyword_tallies,
|
||||
"article_level": article_tallies,
|
||||
"descriptive": {
|
||||
"mean_keywords": round(statistics.mean(keyword_counts), 2) if keyword_counts else 0,
|
||||
"median_keywords": statistics.median(keyword_counts) if keyword_counts else 0,
|
||||
"articles_zero_keywords": sum(1 for count in keyword_counts if count == 0),
|
||||
"articles_exactly_six": sum(1 for count in keyword_counts if count == 6),
|
||||
"articles_over_six": sum(
|
||||
1 for count in keyword_counts if count > keyword_extraction.KEYWORD_LIMIT
|
||||
),
|
||||
},
|
||||
"determinism": determinism,
|
||||
"examples": examples,
|
||||
}
|
||||
|
||||
output_path = f"results_{args.config}.json"
|
||||
with open(output_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(results, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
os.makedirs(DECISIONS_DIR, exist_ok=True)
|
||||
decisions_path = os.path.join(DECISIONS_DIR, f"{args.config}.jsonl")
|
||||
with open(decisions_path, "w", encoding="utf-8") as decisions_file:
|
||||
for decision in decisions:
|
||||
decisions_file.write(json.dumps(decision, ensure_ascii=False) + "\n")
|
||||
|
||||
print(
|
||||
f"{articles_evaluated} Artikel, {keywords_total} Schlagwörter ausgewertet.\n"
|
||||
f"-> {output_path}\n-> {decisions_path}"
|
||||
)
|
||||
if errors:
|
||||
print(f"Fehler: {dict(errors)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Runs the keyword extraction under a named configuration and logs raw output.
|
||||
|
||||
Two configurations are defined:
|
||||
|
||||
* `neu` — the production contract, imported from the service module
|
||||
`inse.news.keyword_extraction`, so the evaluation tests what actually ships
|
||||
(title + 20.000-char bound, strict JSON schema, temperature 0.0,
|
||||
normalization).
|
||||
* `alt` — the behaviour of the background job before the paths were unified:
|
||||
full content without the title, no schema, temperature 1.0, and the raw
|
||||
model list persisted without normalization.
|
||||
|
||||
The RAW model response is written out alongside the parsed list, because the
|
||||
count- and duplicate checks have to look at what the model produced, not at
|
||||
what normalize_keywords() left over.
|
||||
|
||||
Output: runs/<config>.jsonl, one object per article and repeat:
|
||||
|
||||
{"_id": ..., "config": ..., "repeat": 0, "raw_response": "...",
|
||||
"raw_keywords": [...], "keywords": [...], "error": null}
|
||||
|
||||
Runs are resumable — (\\_id, repeat) pairs already present are skipped.
|
||||
|
||||
Usage:
|
||||
python extract_keywords.py --config neu
|
||||
python extract_keywords.py --config alt
|
||||
python extract_keywords.py --config neu --repeats 5 --limit 200
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
# The production contract lives in the service package; import it rather than
|
||||
# restating it, so "neu" cannot silently drift away from what ships.
|
||||
sys.path.append(str(Path(__file__).resolve().parents[2] / "service/src/main/inse/news"))
|
||||
import keyword_extraction # noqa: E402
|
||||
|
||||
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 SystemExit(
|
||||
"INSE_LLM_API_KEY ist nicht gesetzt. Lege eine .env an oder exportiere die Variable."
|
||||
)
|
||||
LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b")
|
||||
|
||||
_client = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY, timeout=120)
|
||||
|
||||
INPUT_FILE = "data/articles.jsonl"
|
||||
OUTPUT_DIR = "runs"
|
||||
|
||||
# Legacy configuration, kept verbatim for the comparison column.
|
||||
ALT_TEMPERATURE = 1.0
|
||||
ALT_TOP_P = 0.95
|
||||
ALT_TOP_K = 64
|
||||
|
||||
|
||||
def build_prompt_neu(record):
|
||||
return keyword_extraction.build_user_prompt(
|
||||
record.get("maintitle"), record.get("full_content")
|
||||
)
|
||||
|
||||
|
||||
def build_prompt_alt(record):
|
||||
"""Legacy: bare full_content, no title, no length bound."""
|
||||
text = (record.get("full_content") or "").strip()
|
||||
return text or None
|
||||
|
||||
|
||||
CONFIGS = {
|
||||
"neu": {
|
||||
"system_prompt": keyword_extraction.KEYWORD_SYSTEM_PROMPT,
|
||||
"build_prompt": build_prompt_neu,
|
||||
"temperature": keyword_extraction.TEMPERATURE,
|
||||
"top_p": keyword_extraction.TOP_P,
|
||||
"top_k": keyword_extraction.TOP_K,
|
||||
"json_schema": keyword_extraction.RESPONSE_SCHEMA,
|
||||
"schema_name": keyword_extraction.SCHEMA_NAME,
|
||||
"normalize": True,
|
||||
},
|
||||
"alt": {
|
||||
"system_prompt": keyword_extraction.KEYWORD_SYSTEM_PROMPT,
|
||||
"build_prompt": build_prompt_alt,
|
||||
"temperature": ALT_TEMPERATURE,
|
||||
"top_p": ALT_TOP_P,
|
||||
"top_k": ALT_TOP_K,
|
||||
"json_schema": None,
|
||||
"schema_name": None,
|
||||
"normalize": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def call_llm(config, user_prompt):
|
||||
response_format = None
|
||||
if config["json_schema"] is not None:
|
||||
response_format = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": config["schema_name"],
|
||||
"strict": True,
|
||||
"schema": config["json_schema"],
|
||||
},
|
||||
}
|
||||
|
||||
response = _client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": config["system_prompt"]},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=config["temperature"],
|
||||
top_p=config["top_p"],
|
||||
extra_body={"top_k": config["top_k"]},
|
||||
response_format=response_format,
|
||||
)
|
||||
return response.choices[0].message.content or ""
|
||||
|
||||
|
||||
def parse_raw(raw_response):
|
||||
"""Parses the model answer without applying any normalization."""
|
||||
try:
|
||||
data = json.loads(raw_response)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
candidates = data.get("keywords")
|
||||
if not isinstance(candidates, list):
|
||||
return None
|
||||
return candidates
|
||||
|
||||
|
||||
def extract_one(record, config_name, repeat):
|
||||
config = CONFIGS[config_name]
|
||||
result = {
|
||||
"_id": record["_id"],
|
||||
"config": config_name,
|
||||
"repeat": repeat,
|
||||
"raw_response": None,
|
||||
"raw_keywords": None,
|
||||
"keywords": [],
|
||||
"error": None,
|
||||
}
|
||||
|
||||
user_prompt = config["build_prompt"](record)
|
||||
if not user_prompt:
|
||||
result["error"] = "empty_article"
|
||||
return result
|
||||
|
||||
try:
|
||||
raw_response = call_llm(config, user_prompt)
|
||||
except APIConnectionError as error:
|
||||
result["error"] = f"connection_error: {error}"
|
||||
return result
|
||||
except Exception as error: # noqa: BLE001 - one bad article must not stop the run
|
||||
result["error"] = f"llm_error: {error}"
|
||||
return result
|
||||
|
||||
result["raw_response"] = raw_response
|
||||
raw_keywords = parse_raw(raw_response)
|
||||
|
||||
if raw_keywords is None:
|
||||
result["error"] = "unparseable_response"
|
||||
return result
|
||||
|
||||
result["raw_keywords"] = raw_keywords
|
||||
if config["normalize"]:
|
||||
result["keywords"] = keyword_extraction.normalize_keywords(raw_keywords)
|
||||
else:
|
||||
# Legacy behaviour: whatever the model returned was persisted as-is.
|
||||
result["keywords"] = raw_keywords
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def load_articles(path, limit):
|
||||
records = []
|
||||
with open(path, encoding="utf-8") as input_file:
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line:
|
||||
records.append(json.loads(line))
|
||||
return records[:limit] if limit else records
|
||||
|
||||
|
||||
def load_done(path):
|
||||
"""Returns the (_id, repeat) pairs already written, so runs can resume."""
|
||||
done = set()
|
||||
if not os.path.exists(path):
|
||||
return done
|
||||
with open(path, encoding="utf-8") as existing:
|
||||
for line in existing:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
done.add((entry.get("_id"), entry.get("repeat")))
|
||||
return done
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", choices=sorted(CONFIGS), required=True)
|
||||
parser.add_argument("--input", default=INPUT_FILE)
|
||||
parser.add_argument("--output", default=None, help="Default: runs/<config>.jsonl")
|
||||
parser.add_argument("--threads", type=int, default=4)
|
||||
parser.add_argument("--limit", type=int, default=None, help="Nur die ersten N Artikel.")
|
||||
parser.add_argument(
|
||||
"--repeats",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Wiederholungen je Artikel für die Reproduzierbarkeitsmessung (Default: 1).",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
output_path = args.output or os.path.join(OUTPUT_DIR, f"{args.config}.jsonl")
|
||||
|
||||
records = load_articles(args.input, args.limit)
|
||||
done = load_done(output_path)
|
||||
|
||||
jobs = [
|
||||
(record, repeat)
|
||||
for record in records
|
||||
for repeat in range(args.repeats)
|
||||
if (record["_id"], repeat) not in done
|
||||
]
|
||||
total = len(jobs)
|
||||
print(
|
||||
f"Konfiguration '{args.config}': {len(records)} Artikel x {args.repeats} "
|
||||
f"Wiederholung(en), {total} offen, {len(done)} bereits vorhanden."
|
||||
)
|
||||
if not total:
|
||||
return
|
||||
|
||||
write_lock = threading.Lock()
|
||||
processed = 0
|
||||
failed = 0
|
||||
|
||||
with open(output_path, "a", encoding="utf-8") as output_file:
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [
|
||||
executor.submit(extract_one, record, args.config, repeat)
|
||||
for record, repeat in jobs
|
||||
]
|
||||
for future in as_completed(futures):
|
||||
result = future.result()
|
||||
with write_lock:
|
||||
output_file.write(json.dumps(result, ensure_ascii=False) + "\n")
|
||||
output_file.flush()
|
||||
processed += 1
|
||||
if result["error"]:
|
||||
failed += 1
|
||||
if processed % 25 == 0 or processed == total:
|
||||
print(f" {processed} / {total} (Fehler: {failed})")
|
||||
|
||||
print(f"Fertig. {processed} Aufrufe, davon {failed} mit Fehler. -> {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,186 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,8 @@
|
||||
requests==2.34.2
|
||||
openai==2.41.0
|
||||
python-dotenv==1.0.1
|
||||
tabulate==0.9.0
|
||||
|
||||
# Optional, for the lemma-, Grundform- and NER-based checks.
|
||||
# Without it those checks report "n. v." instead of a number:
|
||||
# pip install spacy==3.8.2 && python -m spacy download de_core_news_sm
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Prints the Layer-1 tables.
|
||||
|
||||
Reads results_<config>.json for every configuration given
|
||||
and emits the compliance table, the descriptive table and the error table.
|
||||
|
||||
Usage:
|
||||
python results.py
|
||||
python results.py --configs neu
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
L2_LABELS = {"lemma": "L2, Lemma", "flexion": "L2, Flexion"}
|
||||
|
||||
COMPLIANCE_ROWS = [
|
||||
("Wörtlich im Text ({l2})", "keyword_level", "literal_l2"),
|
||||
(" davon normalisiert (L1)", "keyword_level", "literal_l1"),
|
||||
(" davon exakt (L0)", "keyword_level", "literal_l0"),
|
||||
("Artikel ohne Wörtlichkeitsverstoß", "article_level", "literal_all"),
|
||||
("Höchstens sechs Schlagwörter (roh)", "article_level", "count_ok"),
|
||||
("Keine Duplikate (roh)", "article_level", "no_duplicates"),
|
||||
("Keine Stamm-Redundanz", "article_level", "no_stem_redundancy"),
|
||||
("Keine Personennamen (Autorenfeld)", "keyword_level", "no_person_name_authors"),
|
||||
("Keine Personennamen (NER)", "keyword_level", "no_person_name_ner"),
|
||||
("Keine Datumsangaben", "keyword_level", "no_date"),
|
||||
("Grundform (Nom. Sg.)", "keyword_level", "base_form"),
|
||||
]
|
||||
|
||||
DESCRIPTIVE_ROWS = [
|
||||
("Ausgewertete Artikel", "articles_evaluated"),
|
||||
("Ausgewertete Schlagwörter", "keywords_total"),
|
||||
]
|
||||
|
||||
DESCRIPTIVE_SUB_ROWS = [
|
||||
("Schlagwörter je Artikel (Mittelwert)", "mean_keywords"),
|
||||
("Schlagwörter je Artikel (Median)", "median_keywords"),
|
||||
("Artikel ohne Schlagwörter", "articles_zero_keywords"),
|
||||
("Artikel mit genau sechs", "articles_exactly_six"),
|
||||
("Artikel mit mehr als sechs", "articles_over_six"),
|
||||
]
|
||||
|
||||
|
||||
def format_rate(bucket):
|
||||
"""'x/N (yy,y %)', or a bound when some cases are not determinable.
|
||||
|
||||
Undecidable cases are not dropped from the denominator: doing so would
|
||||
report a flattering rate over exactly the easy cases (without spaCy, only
|
||||
the keywords that already passed L1 are decidable at L2, which would print
|
||||
100 %). With n. v. present the honest statement is an interval — every
|
||||
undetermined case is a pass in the best and a failure in the worst case.
|
||||
"""
|
||||
passed = bucket["pass"]
|
||||
failed = bucket["fail"]
|
||||
not_available = bucket["na"]
|
||||
total = passed + failed + not_available
|
||||
|
||||
if total == 0:
|
||||
return "–"
|
||||
if passed + failed == 0:
|
||||
return f"n. v. ({not_available})"
|
||||
|
||||
if not_available == 0:
|
||||
percentage = f"{100.0 * passed / total:.1f}".replace(".", ",")
|
||||
return f"{passed}/{total} ({percentage} %)"
|
||||
|
||||
lower = f"{100.0 * passed / total:.1f}".replace(".", ",")
|
||||
upper = f"{100.0 * (passed + not_available) / total:.1f}".replace(".", ",")
|
||||
return f"{passed}/{total} ({lower}–{upper} %, {not_available} n. v.)"
|
||||
|
||||
|
||||
def load(config):
|
||||
path = f"results_{config}.json"
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding="utf-8") as results_file:
|
||||
return json.load(results_file)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--configs", nargs="+", default=["alt", "neu"])
|
||||
args = parser.parse_args()
|
||||
|
||||
loaded = [(config, load(config)) for config in args.configs]
|
||||
available = [(config, data) for config, data in loaded if data]
|
||||
missing = [config for config, data in loaded if not data]
|
||||
|
||||
if not available:
|
||||
raise SystemExit("Keine results_<config>.json gefunden. Erst evaluate.py laufen lassen.")
|
||||
if missing:
|
||||
print(f"Hinweis: keine Ergebnisse für {', '.join(missing)} — Spalte entfällt.\n")
|
||||
|
||||
labels = {"alt": "Alt-Konfig", "neu": "Neu-Konfig"}
|
||||
headers = ["Kriterium"] + [labels.get(config, config) for config, _ in available]
|
||||
|
||||
methods = {data.get("l2_method", "lemma") for _, data in available}
|
||||
l2_label = " / ".join(sorted(L2_LABELS.get(method, method) for method in methods))
|
||||
|
||||
rows = []
|
||||
for label, section, key in COMPLIANCE_ROWS:
|
||||
row = [label.format(l2=l2_label)]
|
||||
for _, data in available:
|
||||
bucket = data[section].get(key)
|
||||
row.append(format_rate(bucket) if bucket else "–")
|
||||
rows.append(row)
|
||||
|
||||
determinism_row = ["Reproduzierbarkeit (Jaccard, Wiederholungen)"]
|
||||
for _, data in available:
|
||||
determinism = data.get("determinism")
|
||||
if not determinism:
|
||||
determinism_row.append("–")
|
||||
else:
|
||||
value = f"{determinism['mean_pairwise_jaccard']:.4f}".replace(".", ",")
|
||||
determinism_row.append(f"{value} (n={determinism['articles']})")
|
||||
rows.append(determinism_row)
|
||||
|
||||
print("## Regelkonformität (Layer 1)\n")
|
||||
print(tabulate(rows, headers=headers, tablefmt="orgtbl"))
|
||||
|
||||
print("\n\n## Deskriptive Kennzahlen\n")
|
||||
descriptive_rows = []
|
||||
for label, key in DESCRIPTIVE_ROWS:
|
||||
descriptive_rows.append([label] + [str(data[key]) for _, data in available])
|
||||
for label, key in DESCRIPTIVE_SUB_ROWS:
|
||||
descriptive_rows.append(
|
||||
[label] + [str(data["descriptive"][key]).replace(".", ",") for _, data in available]
|
||||
)
|
||||
print(tabulate(descriptive_rows, headers=headers, tablefmt="orgtbl"))
|
||||
|
||||
error_keys = sorted({key for _, data in available for key in data["errors"]})
|
||||
if error_keys:
|
||||
print("\n\n## Fehlerfälle\n")
|
||||
error_rows = [
|
||||
[key] + [str(data["errors"].get(key, 0)) for _, data in available]
|
||||
for key in error_keys
|
||||
]
|
||||
print(tabulate(error_rows, headers=headers, tablefmt="orgtbl"))
|
||||
|
||||
print("\n\n## Beispiele für Verstöße (für den Fließtext)\n")
|
||||
for config, data in available:
|
||||
for check in ("literal_l2", "no_person_name_authors", "no_date"):
|
||||
found = data["examples"].get(check) or []
|
||||
if not found:
|
||||
continue
|
||||
sample = ", ".join(
|
||||
f"\"{item.get('keyword')}\"" for item in found[:5] if item.get("keyword")
|
||||
)
|
||||
if sample:
|
||||
print(f"- [{config}] {check}: {sample}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"judged": 294,
|
||||
"counts": {
|
||||
"richtig": 177,
|
||||
"akzeptabel": 101,
|
||||
"falsch": 16
|
||||
},
|
||||
"precision_incl_acceptable": 94.6,
|
||||
"precision_strict": 60.2,
|
||||
"essential_total": 125,
|
||||
"essential_hit": 96
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"judged": 294,
|
||||
"counts": {
|
||||
"richtig": 141,
|
||||
"akzeptabel": 146,
|
||||
"falsch": 7
|
||||
},
|
||||
"precision_incl_acceptable": 97.6,
|
||||
"precision_strict": 48.0,
|
||||
"essential_total": 125,
|
||||
"essential_hit": 96
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
{
|
||||
"config": "neu",
|
||||
"l2_method": "flexion",
|
||||
"articles_evaluated": 500,
|
||||
"keywords_total": 2890,
|
||||
"errors": {},
|
||||
"keyword_level": {
|
||||
"literal_l0": {
|
||||
"pass": 2461,
|
||||
"fail": 429,
|
||||
"na": 0
|
||||
},
|
||||
"literal_l1": {
|
||||
"pass": 2464,
|
||||
"fail": 426,
|
||||
"na": 0
|
||||
},
|
||||
"literal_l2": {
|
||||
"pass": 2796,
|
||||
"fail": 94,
|
||||
"na": 0
|
||||
},
|
||||
"no_person_name_authors": {
|
||||
"pass": 2889,
|
||||
"fail": 1,
|
||||
"na": 0
|
||||
},
|
||||
"no_person_name_ner": {
|
||||
"pass": 0,
|
||||
"fail": 0,
|
||||
"na": 2890
|
||||
},
|
||||
"no_date": {
|
||||
"pass": 2890,
|
||||
"fail": 0,
|
||||
"na": 0
|
||||
},
|
||||
"base_form": {
|
||||
"pass": 0,
|
||||
"fail": 0,
|
||||
"na": 2890
|
||||
}
|
||||
},
|
||||
"article_level": {
|
||||
"count_ok": {
|
||||
"pass": 499,
|
||||
"fail": 1,
|
||||
"na": 0
|
||||
},
|
||||
"no_duplicates": {
|
||||
"pass": 500,
|
||||
"fail": 0,
|
||||
"na": 0
|
||||
},
|
||||
"no_stem_redundancy": {
|
||||
"pass": 464,
|
||||
"fail": 36,
|
||||
"na": 0
|
||||
},
|
||||
"literal_all": {
|
||||
"pass": 415,
|
||||
"fail": 85,
|
||||
"na": 0
|
||||
}
|
||||
},
|
||||
"descriptive": {
|
||||
"mean_keywords": 5.78,
|
||||
"median_keywords": 6.0,
|
||||
"articles_zero_keywords": 0,
|
||||
"articles_exactly_six": 439,
|
||||
"articles_over_six": 1
|
||||
},
|
||||
"determinism": null,
|
||||
"examples": {
|
||||
"literal_l0": [
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "internationale Kooperationen"
|
||||
},
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "Wissenschaftler"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Zahnstruktur"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Nano- und Werkstoffwissenschaft"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "mechanische Messung"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "Hochsee-Windpark"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "bipolares Kabelsystem"
|
||||
},
|
||||
{
|
||||
"_id": "07102019__Stipendium–auchohneEinser-Abi",
|
||||
"keyword": "Förderwerke"
|
||||
},
|
||||
{
|
||||
"_id": "22052017_ClaudiaBraczko_RentnerarbeitimBetrieb",
|
||||
"keyword": "Teilzeit- und Minijobs"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Internationale Möbelmesse IMM Cologne"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Wohnobjekt aus Edelstahl"
|
||||
},
|
||||
{
|
||||
"_id": "20112018_DrAlexandraNießen_NanogroßbeiTumorforschung",
|
||||
"keyword": "Implantat"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "kardiovaskuläre Erkrankung"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "romantische Poesie"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Süßwassersystem"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Forschungsprojekt"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Sanierungsstrategie"
|
||||
},
|
||||
{
|
||||
"_id": "16112017_UlrikeEichweber_WiewarendieerstenWochen",
|
||||
"keyword": "UDE-Panel"
|
||||
},
|
||||
{
|
||||
"_id": "08102019_UlrikeEichweber_KIinderFinanzwelt",
|
||||
"keyword": "Banken-Symposium"
|
||||
},
|
||||
{
|
||||
"_id": "21092018_BeateKostka_Zweifacherfolgreich",
|
||||
"keyword": "Deutsche Forschungsgemeinschaft"
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keyword": "regionale Ausdrücke"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Reaktorunglück von Fukushima"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Rotes Kreuz"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Deutsche Science Slam Meisterschaft"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Wirkstoffkombination"
|
||||
}
|
||||
],
|
||||
"literal_l1": [
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "internationale Kooperationen"
|
||||
},
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "Wissenschaftler"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Zahnstruktur"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Nano- und Werkstoffwissenschaft"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "mechanische Messung"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "Hochsee-Windpark"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "bipolares Kabelsystem"
|
||||
},
|
||||
{
|
||||
"_id": "07102019__Stipendium–auchohneEinser-Abi",
|
||||
"keyword": "Förderwerke"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Internationale Möbelmesse IMM Cologne"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Wohnobjekt aus Edelstahl"
|
||||
},
|
||||
{
|
||||
"_id": "20112018_DrAlexandraNießen_NanogroßbeiTumorforschung",
|
||||
"keyword": "Implantat"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "kardiovaskuläre Erkrankung"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "romantische Poesie"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Süßwassersystem"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Forschungsprojekt"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Sanierungsstrategie"
|
||||
},
|
||||
{
|
||||
"_id": "16112017_UlrikeEichweber_WiewarendieerstenWochen",
|
||||
"keyword": "UDE-Panel"
|
||||
},
|
||||
{
|
||||
"_id": "08102019_UlrikeEichweber_KIinderFinanzwelt",
|
||||
"keyword": "Banken-Symposium"
|
||||
},
|
||||
{
|
||||
"_id": "21092018_BeateKostka_Zweifacherfolgreich",
|
||||
"keyword": "Deutsche Forschungsgemeinschaft"
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keyword": "regionale Ausdrücke"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Reaktorunglück von Fukushima"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Rotes Kreuz"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Deutsche Science Slam Meisterschaft"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Wirkstoffkombination"
|
||||
},
|
||||
{
|
||||
"_id": "27102015__NeuesKonzeptsollPflegeerleichtern_archiv",
|
||||
"keyword": "emotionale Belastung"
|
||||
}
|
||||
],
|
||||
"literal_l2": [
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "bipolares Kabelsystem"
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keyword": "regionale Ausdrücke"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Rotes Kreuz"
|
||||
},
|
||||
{
|
||||
"_id": "29112018_BeateKostka_RelevanteInformationenausDatenbergen",
|
||||
"keyword": "Verkehrsvorhersage"
|
||||
},
|
||||
{
|
||||
"_id": "11092015__JemehrMutationen,destowirksamer_archiv",
|
||||
"keyword": "Wirkmechanismus"
|
||||
},
|
||||
{
|
||||
"_id": "19092006__ZweiFliegenmiteinerKlappeschlagen_archiv",
|
||||
"keyword": "Virtueller Weiterbildungsstudiengang Wirtschaftsinformatik"
|
||||
},
|
||||
{
|
||||
"_id": "11042005_UlrikeBohnsack_GroßeFestveranstaltunginBerlin_archiv",
|
||||
"keyword": "Linguistik"
|
||||
},
|
||||
{
|
||||
"_id": "20032026_DrAlexandraNießen_GuteZusammenarbeitmitKI",
|
||||
"keyword": "Arbeitsplatz"
|
||||
},
|
||||
{
|
||||
"_id": "14092021_UlrikeEichweber_IFWW-Frderpreis",
|
||||
"keyword": "wissenschaftlicher Nachwuchs"
|
||||
},
|
||||
{
|
||||
"_id": "14092021_UlrikeEichweber_IFWW-Frderpreis",
|
||||
"keyword": "Trinkwasser"
|
||||
},
|
||||
{
|
||||
"_id": "14092021_UlrikeEichweber_IFWW-Frderpreis",
|
||||
"keyword": "Abwasser"
|
||||
},
|
||||
{
|
||||
"_id": "13122023_DrAlexandraNießen_WasistanderUnilos",
|
||||
"keyword": "Smart City"
|
||||
},
|
||||
{
|
||||
"_id": "21052024_CathrinBecker_Wannmanwenwieanspricht",
|
||||
"keyword": "Spender:in"
|
||||
},
|
||||
{
|
||||
"_id": "05042024_CathrinBecker_10JahreSpitzenfrderung",
|
||||
"keyword": "Leitthema"
|
||||
},
|
||||
{
|
||||
"_id": "02122019_DrAlexandraNießen_EuropaweiterAustausch",
|
||||
"keyword": "Akademisches Auslandsamt"
|
||||
},
|
||||
{
|
||||
"_id": "16062025_UlrikeEichweber_Dalberg-PreisfrtransdisziplinreNachwuchsforschung",
|
||||
"keyword": "Geisteswissenschaften"
|
||||
},
|
||||
{
|
||||
"_id": "09032017_UlrikeBohnsack_DieAngstvormScheitern",
|
||||
"keyword": "Risiko"
|
||||
},
|
||||
{
|
||||
"_id": "08092020_DrAlexandraNießen_Cooperatingrobots",
|
||||
"keyword": "remote-controlled robot arm"
|
||||
},
|
||||
{
|
||||
"_id": "27072021_UlrikeEichweber_LehrenziehenausderPandemie",
|
||||
"keyword": "Lehrkraft"
|
||||
},
|
||||
{
|
||||
"_id": "06112019_DrAlexandraNießen_Typischdeutsch",
|
||||
"keyword": "Kulturwissenschaftliches Institut"
|
||||
},
|
||||
{
|
||||
"_id": "03062019_UlrikeEichweber_EuropischekonomeninGenua",
|
||||
"keyword": "Vortrag"
|
||||
},
|
||||
{
|
||||
"_id": "12102012__Studienstartfr25TeilnehmerInnen_archiv",
|
||||
"keyword": "Stipendium"
|
||||
},
|
||||
{
|
||||
"_id": "12112007_JuliaHarzendorf_LeistungenfrsStudiumanrechnen_archiv",
|
||||
"keyword": "Logistikstudiengang"
|
||||
},
|
||||
{
|
||||
"_id": "16082022_ThomasWittek_ErsterSchnappschusseinesScheibenwinds",
|
||||
"keyword": "Schwarzes Loch"
|
||||
},
|
||||
{
|
||||
"_id": "16082022_ThomasWittek_ErsterSchnappschusseinesScheibenwinds",
|
||||
"keyword": "massereicher Stern"
|
||||
}
|
||||
],
|
||||
"no_person_name_authors": [
|
||||
{
|
||||
"_id": "01092017_CathrinBecker_AlleParteienimberblick",
|
||||
"keyword": "Politikwissenschaftler"
|
||||
}
|
||||
],
|
||||
"no_person_name_ner": [],
|
||||
"no_date": [],
|
||||
"base_form": [],
|
||||
"count_ok": [
|
||||
{
|
||||
"_id": "30042019_UlrikeEichweber_FrwenigerCO",
|
||||
"keywords": [
|
||||
"Stadtradeln",
|
||||
"Klima-Bündnisses e.V.",
|
||||
"CO2",
|
||||
"Radler",
|
||||
"Kilometer",
|
||||
"Duisburg",
|
||||
"Essen"
|
||||
]
|
||||
}
|
||||
],
|
||||
"no_duplicates": [],
|
||||
"no_stem_redundancy": [
|
||||
{
|
||||
"_id": "14022003_MonikaRgge_KonzertinderKreuzeskirche_archiv",
|
||||
"keywords": [
|
||||
"Essener Studentenorchester",
|
||||
"Konzert",
|
||||
"Orchester",
|
||||
"Studenten",
|
||||
"Folkwang-Hochschule Essen",
|
||||
"Musizieren"
|
||||
],
|
||||
"pairs": [
|
||||
["Orchester", "Essener Studentenorchester"],
|
||||
["Studenten", "Essener Studentenorchester"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "22052017_ClaudiaBraczko_RentnerarbeitimBetrieb",
|
||||
"keywords": [
|
||||
"Rentnerarbeit im Betrieb",
|
||||
"Fachkräftemangel",
|
||||
"Teilzeit- und Minijobs",
|
||||
"Wissensverlust",
|
||||
"flexibler Personalpuffer",
|
||||
"Rentner"
|
||||
],
|
||||
"pairs": [["Rentner", "Rentnerarbeit im Betrieb"]]
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keywords": [
|
||||
"Variantenwörterbuch",
|
||||
"Standardsprache",
|
||||
"Linguistik",
|
||||
"Soziolinguistik",
|
||||
"regionale Ausdrücke",
|
||||
"Grammatik"
|
||||
],
|
||||
"pairs": [["Linguistik", "Soziolinguistik"]]
|
||||
},
|
||||
{
|
||||
"_id": "19052009__InallenStudienphasengutberaten_archiv",
|
||||
"keywords": [
|
||||
"Mentoring-System",
|
||||
"Studierendenbetreuung",
|
||||
"Studierende",
|
||||
"Fachbereichen",
|
||||
"persönliche Beratung",
|
||||
"Studienabbrüche"
|
||||
],
|
||||
"pairs": [["Studierende", "Studierendenbetreuung"]]
|
||||
},
|
||||
{
|
||||
"_id": "20112019_ChristineHarrell_EinNichtsmitgroßerWirkung",
|
||||
"keywords": [
|
||||
"chronische Rückenschmerzen",
|
||||
"Open-Label Placebos",
|
||||
"Schmerz",
|
||||
"Beweglichkeit",
|
||||
"klinische Neurowissenschaft",
|
||||
"Schmerztherapie"
|
||||
],
|
||||
"pairs": [
|
||||
["Schmerz", "chronische Rückenschmerzen"],
|
||||
["Schmerz", "Schmerztherapie"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "17042018_BeateKostka_FitfrdieDemokratie",
|
||||
"keywords": [
|
||||
"Demokratie",
|
||||
"Jugendliche",
|
||||
"politische und zivilgesellschaftliche Bildung",
|
||||
"politisches Wissen",
|
||||
"Elternhaus",
|
||||
"demokratiekompetent"
|
||||
],
|
||||
"pairs": [["Demokratie", "demokratiekompetent"]]
|
||||
},
|
||||
{
|
||||
"_id": "21052024_CathrinBecker_Wannmanwenwieanspricht",
|
||||
"keywords": [
|
||||
"Stammzelle",
|
||||
"Blut",
|
||||
"Spendenbereitschaft",
|
||||
"Spender:in",
|
||||
"Information",
|
||||
"Blutkrebs"
|
||||
],
|
||||
"pairs": [["Blut", "Blutkrebs"]]
|
||||
},
|
||||
{
|
||||
"_id": "27112014__DerFallBeloMonte_archiv",
|
||||
"keywords": [
|
||||
"Menschrechte",
|
||||
"Konflikt",
|
||||
"Ureinwohner",
|
||||
"Belo Monte-Wasserkraftwerk",
|
||||
"Amazonasgebiet",
|
||||
"Grundlegende politische Konflikte"
|
||||
],
|
||||
"pairs": [["Konflikt", "Grundlegende politische Konflikte"]]
|
||||
},
|
||||
{
|
||||
"_id": "26062017_CathrinBecker_PionierforschungzuNanopartikeln",
|
||||
"keywords": [
|
||||
"Nanopartikel",
|
||||
"Pionierforschung",
|
||||
"lasergenerierte Nanoteilchen",
|
||||
"Biomedizin- und Energietechnik",
|
||||
"kontinuierlichen laserbasierten Nanopartikelsynthese",
|
||||
"Habilitationsschrift"
|
||||
],
|
||||
"pairs": [
|
||||
[
|
||||
"Nanopartikel",
|
||||
"kontinuierlichen laserbasierten Nanopartikelsynthese"
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "18122023__Pathtosustainablehydrogen",
|
||||
"keywords": [
|
||||
"green hydrogen",
|
||||
"electrocatalysts",
|
||||
"oxygen evolution reaction",
|
||||
"surface transformation",
|
||||
"perovskite",
|
||||
"crystal facet-dependent surface transformation"
|
||||
],
|
||||
"pairs": [
|
||||
[
|
||||
"surface transformation",
|
||||
"crystal facet-dependent surface transformation"
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "01072014_AlexandraNießen_MathematikalsLebenshilfe_archiv",
|
||||
"keywords": [
|
||||
"Mathematik",
|
||||
"Problemlösen",
|
||||
"Didaktik",
|
||||
"Techniken und Strategien des Problemlösens",
|
||||
"Heurismen",
|
||||
"Learning the Science of Education"
|
||||
],
|
||||
"pairs": [
|
||||
["Problemlösen", "Techniken und Strategien des Problemlösens"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "02052017_ManuelaMnch_Berufungen-Mai2017",
|
||||
"keywords": [
|
||||
"Professur",
|
||||
"Juniorprofessur",
|
||||
"Medizinische Onkologie mit Schwerpunkt Gastrointestinale Onkologie",
|
||||
"Informatik",
|
||||
"Experimentelle Physik",
|
||||
"Fakultät für Medizin"
|
||||
],
|
||||
"pairs": [["Professur", "Juniorprofessur"]]
|
||||
},
|
||||
{
|
||||
"_id": "16112011_CarmenTomlik_ZumSchutzezndenderIdeen_archiv",
|
||||
"keywords": [
|
||||
"PatentScouts",
|
||||
"Erfinderberatung",
|
||||
"Forschungsergebnis",
|
||||
"Patent",
|
||||
"Drittmittel",
|
||||
"Biomedizin"
|
||||
],
|
||||
"pairs": [["Patent", "PatentScouts"]]
|
||||
},
|
||||
{
|
||||
"_id": "27112020_DrAlexandraNießen_SpracheverleihtFlgel",
|
||||
"keywords": [
|
||||
"Mehrsprachigkeit",
|
||||
"gesellschaftliche Teilhabe",
|
||||
"Arbeitsmarkt",
|
||||
"Deutsch als Zweitsprache",
|
||||
"Fremdsprachen",
|
||||
"Sprache"
|
||||
],
|
||||
"pairs": [
|
||||
["Sprache", "Deutsch als Zweitsprache"],
|
||||
["Sprache", "Fremdsprachen"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "02112009__NochzehnStipendienzuvergeben_archiv",
|
||||
"keywords": [
|
||||
"Stipendien",
|
||||
"Erstsemester",
|
||||
"Migrationshintergrund",
|
||||
"NRW-Stipendienprogramm",
|
||||
"Diversity Management"
|
||||
],
|
||||
"pairs": [["Stipendien", "NRW-Stipendienprogramm"]]
|
||||
},
|
||||
{
|
||||
"_id": "10082005_ChristophLindemann_1000LernmodulefrdieMedizin_archiv",
|
||||
"keywords": [
|
||||
"Learning Resource Server Medizin",
|
||||
"Lernmodul",
|
||||
"Medizin",
|
||||
"Aus-, Fort- und Weiterbildung",
|
||||
"Datenbank",
|
||||
"Internet-Portal"
|
||||
],
|
||||
"pairs": [["Medizin", "Learning Resource Server Medizin"]]
|
||||
},
|
||||
{
|
||||
"_id": "24092003_DanielaEndrulat_TrauerumlangjhrigenKlinikleiter_archiv",
|
||||
"keywords": [
|
||||
"Unfallchirurgie",
|
||||
"Klinik und Poliklinik für Unfallchirurgie",
|
||||
"Präklinische Unfallrettung",
|
||||
"Klinische Schockforschung",
|
||||
"Tumor-Chirurgie",
|
||||
"Ausbildung von Notarzt"
|
||||
],
|
||||
"pairs": [
|
||||
["Unfallchirurgie", "Klinik und Poliklinik für Unfallchirurgie"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "08042021_UlrikeEichweber_UDE-Lehrpreis",
|
||||
"keywords": [
|
||||
"Duisburg-Essener Lehrpreis",
|
||||
"Lehrpreis",
|
||||
"Fakultäten",
|
||||
"Fachschaftsräte",
|
||||
"Kandidat",
|
||||
"Team"
|
||||
],
|
||||
"pairs": [["Lehrpreis", "Duisburg-Essener Lehrpreis"]]
|
||||
},
|
||||
{
|
||||
"_id": "25052011__NickReillybesuchtUniversitt_archiv",
|
||||
"keywords": [
|
||||
"Elektromobilität",
|
||||
"Automobiltechnik",
|
||||
"Brennstoffzelle",
|
||||
"Automobilindustrie",
|
||||
"Zentrum für BrennstoffzellenTechnik",
|
||||
"Nano-Material"
|
||||
],
|
||||
"pairs": [["Brennstoffzelle", "Zentrum für BrennstoffzellenTechnik"]]
|
||||
},
|
||||
{
|
||||
"_id": "13102005_MonikaRgge_VortragberDemenzen_archiv",
|
||||
"keywords": [
|
||||
"Demenzen",
|
||||
"Früherkennung und Diagnostik von Demenzen",
|
||||
"Klinik für Psychiatrie und Psychotherapie",
|
||||
"Essener Universitätsklinikum"
|
||||
],
|
||||
"pairs": [["Demenzen", "Früherkennung und Diagnostik von Demenzen"]]
|
||||
},
|
||||
{
|
||||
"_id": "19022026__MathematikldtzumTagderoffenenTr",
|
||||
"keywords": [
|
||||
"Mathematik",
|
||||
"Tag der offenen Tür",
|
||||
"Mathematikstudium",
|
||||
"Schnuppervorlesung",
|
||||
"Quantencomputer",
|
||||
"Brettspiel"
|
||||
],
|
||||
"pairs": [["Mathematik", "Mathematikstudium"]]
|
||||
},
|
||||
{
|
||||
"_id": "18122012__BestmglicheHeilung_archiv",
|
||||
"keywords": [
|
||||
"Krebs",
|
||||
"Translationale Krebsforschung",
|
||||
"Therapie",
|
||||
"Diagnostik",
|
||||
"Immunsystem",
|
||||
"individualisierte Therapie"
|
||||
],
|
||||
"pairs": [
|
||||
["Krebs", "Translationale Krebsforschung"],
|
||||
["Therapie", "individualisierte Therapie"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "28082025_DrAlexandraNießen_Wissenshungerkanngestilltwerden",
|
||||
"keywords": [
|
||||
"Universität Duisburg-Essen",
|
||||
"Gasthörer",
|
||||
"Lehrprogramm",
|
||||
"Gasthörerverzeichnis",
|
||||
"Einschreibung",
|
||||
"Smart Farming"
|
||||
],
|
||||
"pairs": [["Gasthörer", "Gasthörerverzeichnis"]]
|
||||
},
|
||||
{
|
||||
"_id": "15102019_UlrikeEichweber_Einblickein30JahreForschung",
|
||||
"keywords": [
|
||||
"China",
|
||||
"Forschung",
|
||||
"Vorlesungsreihe",
|
||||
"China as a Developmental State",
|
||||
"Theory-based Researcg and Fieldwork",
|
||||
"Chinese Party State"
|
||||
],
|
||||
"pairs": [["China", "China as a Developmental State"]]
|
||||
},
|
||||
{
|
||||
"_id": "20062007_BeateKostka_DatenbertragungmitLicht_archiv",
|
||||
"keywords": [
|
||||
"Datenübertragung mit Licht",
|
||||
"Optoelektronik",
|
||||
"Laser",
|
||||
"Glasfaserkabel",
|
||||
"Halbleiter-Laser",
|
||||
"Medizintechnik"
|
||||
],
|
||||
"pairs": [["Laser", "Halbleiter-Laser"]]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -18,4 +18,7 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||
# Copy the job code.
|
||||
COPY background-jobs/app/ ./
|
||||
|
||||
# Keyword extraction contract shared with the service (inse.news.logic).
|
||||
COPY service/src/main/inse/news/keyword_extraction.py ./keyword_extraction.py
|
||||
|
||||
COPY service/scripts/ ./service/scripts/
|
||||
|
||||
@@ -14,6 +14,9 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY background-jobs/app/ ./
|
||||
|
||||
# Keyword extraction contract shared with the service (inse.news.logic).
|
||||
COPY service/src/main/inse/news/keyword_extraction.py ./keyword_extraction.py
|
||||
|
||||
# Writes into docker-job_test, leaving production aktuell_postproc untouched.
|
||||
# A non-postproc target re-extracts entries that already have keywords (real
|
||||
# content) and updates them in place, keyed on news_id (re-runs overwrite, no
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Shared contract for the LLM keyword extraction on news articles.
|
||||
|
||||
Two callers extract keywords and write them into the same `keywords` field of
|
||||
`aktuell_postproc`:
|
||||
|
||||
* the background job (`background-jobs/app/sync.py`), which covers the corpus,
|
||||
* the article detail endpoint (`inse.news.logic`), which fills the gap for
|
||||
articles the job has not reached yet.
|
||||
|
||||
The job images
|
||||
install neither pydantic nor the rest of the `inse` package; they copy this
|
||||
single file next to `sync.py`, see `service/scripts/jobs-image/Dockerfile` and
|
||||
`service/scripts/jobs-image/news-keywords/Dockerfile`.
|
||||
"""
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
|
||||
# Safety bound on the prompt: articles have about ~2.000
|
||||
# characters, so this limit is practically never reached. It only prevents a
|
||||
# crawl result from overflowing the context window or stalling a page load.
|
||||
KEYWORD_CONTENT_CHARS = 20000
|
||||
|
||||
# The result is persisted once and never recomputed,
|
||||
# so re-running an article has to yield the same keywords.
|
||||
TEMPERATURE = 0.0
|
||||
TOP_P = 0.95
|
||||
TOP_K = 64
|
||||
|
||||
SCHEMA_NAME = "keywords"
|
||||
|
||||
# Mirrors `NewsKeywords.model_json_schema()`. Spelled out so the job can
|
||||
# constrain the response without pulling in pydantic; `NewsKeywords` stays the
|
||||
# parser on the service side.
|
||||
RESPONSE_SCHEMA = {
|
||||
"properties": {
|
||||
"keywords": {
|
||||
"description": "The extracted keywords from the article.",
|
||||
"items": {"type": "string"},
|
||||
"title": "Keywords",
|
||||
"type": "array",
|
||||
}
|
||||
},
|
||||
"required": ["keywords"],
|
||||
"title": "NewsKeywords",
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
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.
|
||||
"""
|
||||
|
||||
|
||||
def build_user_prompt(maintitle: str | None, full_content: str | None) -> str | None:
|
||||
"""Builds the user message, or None if the article carries no text at all."""
|
||||
text = " ".join(
|
||||
part
|
||||
for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS])
|
||||
if part
|
||||
).strip()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
return f"Artikel:\n{text}"
|
||||
|
||||
|
||||
def normalize_keywords(candidates: list) -> list:
|
||||
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
if not isinstance(item, str):
|
||||
continue
|
||||
term = item.strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
@@ -18,6 +18,15 @@ from ..snippets import (
|
||||
snippet_with_context,
|
||||
)
|
||||
from ..topics.logic import vector_search_topics_batch
|
||||
from .keyword_extraction import (
|
||||
KEYWORD_SYSTEM_PROMPT,
|
||||
RESPONSE_SCHEMA,
|
||||
SCHEMA_NAME,
|
||||
TEMPERATURE,
|
||||
TOP_P,
|
||||
build_user_prompt,
|
||||
normalize_keywords,
|
||||
)
|
||||
from .model import (
|
||||
MatchedTopic,
|
||||
MentionedPerson,
|
||||
@@ -49,19 +58,6 @@ CONTENT_HIGHLIGHT = {
|
||||
"require_field_match": False,
|
||||
}
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
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.
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
@@ -507,22 +503,21 @@ async def _get_article_keywords(
|
||||
if cached_keywords:
|
||||
return cached_keywords, postproc_id
|
||||
|
||||
text = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not text:
|
||||
user_prompt = build_user_prompt(maintitle, full_content)
|
||||
if not user_prompt:
|
||||
return [], postproc_id
|
||||
|
||||
response = await llm.call(
|
||||
system_prompt=KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt=f"Artikel:\n{text}",
|
||||
json_schema=NewsKeywords.model_json_schema(),
|
||||
schema_name="keywords",
|
||||
temperature=0.3,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=RESPONSE_SCHEMA,
|
||||
schema_name=SCHEMA_NAME,
|
||||
temperature=TEMPERATURE,
|
||||
top_p=TOP_P,
|
||||
)
|
||||
|
||||
try:
|
||||
keywords = _normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
|
||||
keywords = normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
|
||||
except ValidationError:
|
||||
logger.warning(f"Keyword extraction for news {news_id} returned no valid JSON: {response}")
|
||||
keywords = []
|
||||
@@ -549,19 +544,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
|
||||
return topics
|
||||
|
||||
|
||||
def _normalize_keywords(candidates: list) -> list:
|
||||
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
term = item.strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> str | None:
|
||||
"""Caches the keywords and returns the postproc document id they landed in."""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user