From a3ecaa70a877dd4a6576ffebe7e7ac9aef6e6f95 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Mon, 15 Jun 2026 17:13:26 +0200 Subject: [PATCH] add benchmark code for name extraction --- .../news_ident_person/benchmark_prompts.py | 219 ++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 llm_evaluations/news_ident_person/benchmark_prompts.py diff --git a/llm_evaluations/news_ident_person/benchmark_prompts.py b/llm_evaluations/news_ident_person/benchmark_prompts.py new file mode 100644 index 00000000..cc7f91db --- /dev/null +++ b/llm_evaluations/news_ident_person/benchmark_prompts.py @@ -0,0 +1,219 @@ +import os +import json +from time import time + +from llm_classify_news import call, parse_label, parse_persons + +RUN_NAME = "42" + +CLASSIFY_PROMPT = (""" + Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen. + Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit. + Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird. + Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht. + Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug. + Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein. + Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1. +""") + +EXTRACT_PROMPT = (""" + Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: + Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht. Es können mehrere Personen sein. + Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen. + Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden. + Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"person": ["Vorname Nachname", "Vorname Nachname"]} + Gib keine Erklärungen und kein Markdown aus, nur das JSON. +""") + +DATA_FOLDER = "validation_data" +OUTPUT_FILE = f"benchmark_{RUN_NAME}.json" +SKIP_UNVERIFIED = True + +TITLES = {"prof", "dr", "dipl", "ing", "habil", "med", "rer", "nat", "phil", "hc"} + + +def normalize_name(name): + text = name.lower().replace(".", " ") + + kept_tokens = [] + for token in text.split(): + if token in TITLES: + continue + kept_tokens.append(token) + + return " ".join(kept_tokens) + + +def normalize_set(names): + result = set() + for name in names: + normalized = normalize_name(name) + if normalized: + result.add(normalized) + return result + + +def evaluate_file(record): + full_content = record.get("full_content", "") + true_label = record.get("llm_label") + true_persons = record.get("llm_persons", []) + + pred_label = parse_label(call(CLASSIFY_PROMPT, full_content)) + + result = { + "_id": record.get("_id"), + "true_label": true_label, + "pred_label": pred_label, + "true_persons": true_persons, + "pred_persons": None, + "names_exact_match": None, + } + + if true_label == 1 and pred_label == 1: + pred_persons = parse_persons(call(EXTRACT_PROMPT, full_content)) + result["pred_persons"] = pred_persons + result["names_exact_match"] = (normalize_set(true_persons) == normalize_set(pred_persons)) + + return result + + +def safe_divide(zaehler, nenner): + if nenner == 0: + return 0.0 + return zaehler / nenner + + +def compute_metrics(results): + tp = 0 + fp = 0 + fn = 0 + tn = 0 + errors = 0 + + name_exact_matches = 0 + n_name_articles = 0 + + for result in results: + true_label = result["true_label"] + pred_label = result["pred_label"] + + if pred_label is None: + errors += 1 + elif true_label == 1 and pred_label == 1: + tp += 1 + elif true_label == 0 and pred_label == 1: + fp += 1 + elif true_label == 1 and pred_label == 0: + fn += 1 + elif true_label == 0 and pred_label == 0: + tn += 1 + + if result["pred_persons"] is not None: + n_name_articles += 1 + true_set = normalize_set(result["true_persons"]) + pred_set = normalize_set(result["pred_persons"]) + + if result["names_exact_match"]: + name_exact_matches += 1 + + + precision = safe_divide(tp, tp + fp) + recall = safe_divide(tp, tp + fn) + f1 = safe_divide(2 * precision * recall, precision + recall) + accuracy = safe_divide(tp + tn, tp + tn + fp + fn) + + classification = { + "tp": tp, + "fp": fp, + "fn": fn, + "tn": tn, + "errors": errors, + "accuracy": accuracy, + "precision": precision, + "recall": recall, + "f1": f1, + } + + name_extraction = { + "n_articles": n_name_articles, + } + + return classification, name_extraction + + +def load_records(): + + records = [] + n_skipped = 0 + + for file_name in sorted(os.listdir(DATA_FOLDER)): + if not file_name.endswith(".json"): + continue + + with open(os.path.join(DATA_FOLDER, file_name), "r", encoding="utf-8") as f: + record = json.load(f) + + if SKIP_UNVERIFIED and not record.get("verified", False): + n_skipped += 1 + continue + + records.append(record) + + return records, n_skipped + + +def print_report(classification, name_extraction): + print("\n" + "=" * 50) + print(f"Benchmark: {RUN_NAME}") + print("=" * 50) + print("Klassifikation (Positiv = Label 1):") + print(f" TP={classification['tp']} FP={classification['fp']} " + f"FN={classification['fn']} TN={classification['tn']} " + f"Fehler={classification['errors']}") + print(f" Accuracy : {classification['accuracy']:.3f}") + print(f" Precision: {classification['precision']:.3f}") + print(f" Recall : {classification['recall']:.3f}") + print(f" F1 : {classification['f1']:.3f}") + print("-" * 50) + print(f"Namensextraktion (ueber {name_extraction['n_articles']} TP-Artikel):") + print("=" * 50) + + +def main(): + start = time() + records, n_skipped = load_records() + print(f"{len(records)} Datensaetze geladen ({n_skipped} unverifiziert uebersprungen).") + + if len(records) == 0: + print("Keine Datensaetze gefunden. Abbruch!") + raise SystemExit(1) + + results = [] + for record in records: + result = evaluate_file(record) + print(f"{result['_id']}: true={result['true_label']} pred={result['pred_label']} " + f"names_match={result['names_exact_match']}") + results.append(result) + + classification, name_extraction = compute_metrics(results) + print_report(classification, name_extraction) + + output = { + "run_name": RUN_NAME, + "classify_prompt": CLASSIFY_PROMPT, + "extract_prompt": EXTRACT_PROMPT, + "n_total": len(records), + "n_skipped_unverified": n_skipped, + "classification": classification, + "name_extraction": name_extraction, + "items": results, + } + + with open(OUTPUT_FILE, "w", encoding="utf-8") as f: + json.dump(output, f, ensure_ascii=False, indent=2) + + print(f"\nErgebnisse in '{OUTPUT_FILE}' gespeichert.") + print(f"Verarbeitungszeit: {time() - start:.2f} Sekunden") + +if __name__ == "__main__": + main()