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

331 lines
12 KiB
Python

"""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()