252 lines
8.7 KiB
Python
252 lines
8.7 KiB
Python
"""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()
|