uv-scripts / idref-alignment /eval_idref_alignment.py
Geraldine's picture
Add IdRef alignment evaluation uv script
141e69a verified
Raw
History Blame Contribute Delete
15.1 kB
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "datasets>=2.19",
# "huggingface-hub>=0.23",
# "httpx>=0.27",
# "tqdm>=4.66",
# ]
# ///
"""
Evaluation script for the Humatheque IdRef-Qualinka alignment API.
It runs the deployed `/align/person` endpoint over the
`Geraldine/humatheque-vlm-sudoc-grounded-idref` dataset (used as an evaluation
set with golden {name -> PPN} pairs) and reports alignment accuracy.
For each row:
1. Build the document context from `sudoc_record_templated`
(title, subtitle, discipline, institution, doctoral_school, degree_type, year).
2. For each golden {name: ppn} in `idref_persname_ppns`, POST to /align/person
with the name + context.
3. Compare the predicted PPN against the golden PPN.
Metrics reported:
- accepted_correct : status == "accepted" AND best_ppn == gold (production decision is right)
- accepted_total : status == "accepted" (regardless of correctness)
- top1_correct : best_candidate.ppn == gold (ranking quality, ignoring threshold)
- topk_correct : gold appears anywhere in the ranked candidates (recall of the candidate search)
- precision/recall/F1 of the "accepted" decision, plus status breakdown.
Run:
uv run eval_idref_alignment.py
uv run eval_idref_alignment.py --limit 10 --concurrency 4 --out results.jsonl
IDREF_API_KEY=xxx uv run eval_idref_alignment.py # if the API requires a key
Usage examples are listed via --help.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import sys
from collections import Counter
from dataclasses import dataclass, field, asdict
from typing import Any
import httpx
from datasets import load_dataset
from tqdm import tqdm
# --------------------------------------------------------------------------- #
# Configuration / CLI
# --------------------------------------------------------------------------- #
DEFAULT_API = "https://idref-linker.smartbiblia.fr"
DEFAULT_DATASET = "Geraldine/humatheque-vlm-sudoc-grounded-idref"
DEFAULT_EMBEDDING_MODEL = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--api-base", default=os.getenv("IDREF_API_BASE", DEFAULT_API),
help=f"Base URL of the alignment API (default: {DEFAULT_API})")
p.add_argument("--dataset", default=DEFAULT_DATASET, help="HF dataset id used for evaluation")
p.add_argument("--split", default="train", help="Dataset split (default: train)")
p.add_argument("--api-key", default=os.getenv("IDREF_API_KEY", ""),
help="X-API-Key header value (or set IDREF_API_KEY). Empty if the API is open.")
p.add_argument("--embedding-model", default=DEFAULT_EMBEDDING_MODEL,
help="Embedding model passed to the API (empty string => lexical similarity).")
p.add_argument("--max-candidates", type=int, default=20)
p.add_argument("--max-docs-per-role", type=int, default=20)
p.add_argument("--reference-top-k", type=int, default=3)
p.add_argument("--limit", type=int, default=0, help="Evaluate only the first N rows (0 = all).")
p.add_argument("--concurrency", type=int, default=4, help="Max concurrent API requests.")
p.add_argument("--request-timeout", type=float, default=90.0, help="Per-request HTTP timeout (s).")
p.add_argument("--out", default="idref_eval_results.jsonl", help="Per-person JSONL output path.")
p.add_argument("--summary-out", default="idref_eval_summary.json", help="Summary JSON output path.")
return p.parse_args()
# --------------------------------------------------------------------------- #
# Context extraction + payload building
# --------------------------------------------------------------------------- #
def build_context(templated: str | dict[str, Any] | None) -> dict[str, Any]:
"""Parse `sudoc_record_templated` (JSON string or dict) into the document context."""
extraction: dict[str, Any]
if isinstance(templated, dict):
extraction = templated
elif isinstance(templated, str) and templated.strip():
try:
extraction = json.loads(templated)
except json.JSONDecodeError:
extraction = {}
else:
extraction = {}
return extraction
def build_align_payload(extraction: dict[str, Any], name: str, embedding_model: str,
max_candidates: int, max_docs_per_role: int, reference_top_k: int) -> dict[str, Any]:
"""Mirror the API's expected AlignPersonRequest body (see provided reference)."""
return {
"name": name,
"title": str(extraction.get("title") or ""),
"subtitle": str(extraction.get("subtitle") or ""),
"discipline": str(extraction.get("discipline") or ""),
"institution": str(extraction.get("granting_institution") or ""),
"doctoral_school": str(extraction.get("doctoral_school") or ""),
"degree_type": str(extraction.get("degree_type") or ""),
"year": str(extraction.get("defense_year") or ""),
"max_candidates": max_candidates,
"max_docs_per_role": max_docs_per_role,
"reference_top_k": reference_top_k,
"embedding_model": embedding_model,
}
def parse_idref_column(raw: Any) -> dict[str, str]:
"""`idref_persname_ppns` is stored as a JSON string like '[{"Name": "ppn", ...}]'.
Return a flat {name: ppn} mapping.
"""
if raw is None:
return {}
obj = raw
if isinstance(raw, str):
try:
obj = json.loads(raw)
except json.JSONDecodeError:
return {}
merged: dict[str, str] = {}
if isinstance(obj, list):
for d in obj:
if isinstance(d, dict):
for k, v in d.items():
merged[str(k)] = str(v)
elif isinstance(obj, dict):
for k, v in obj.items():
merged[str(k)] = str(v)
return merged
# --------------------------------------------------------------------------- #
# Per-person evaluation record
# --------------------------------------------------------------------------- #
@dataclass
class PersonEval:
row_index: int
case_id: str
base_id: str
name: str
gold_ppn: str
status: str = "error"
best_ppn: str | None = None # API decision (only set when status == accepted)
top1_ppn: str | None = None # top-ranked candidate, regardless of threshold
top1_score: float | None = None
candidate_ppns: list[str] = field(default_factory=list)
gold_rank: int | None = None # 1-based position of gold in ranked candidates, else None
accepted_correct: bool = False
top1_correct: bool = False
topk_correct: bool = False
error: str | None = None
def evaluate_response(rec: PersonEval, resp: dict[str, Any]) -> PersonEval:
rec.status = str(resp.get("status") or "unknown")
rec.best_ppn = resp.get("best_ppn")
best_cand = resp.get("best_candidate") or {}
rec.top1_ppn = best_cand.get("ppn")
rec.top1_score = (best_cand.get("score") or {}).get("final")
cands = resp.get("candidates") or []
rec.candidate_ppns = [c.get("ppn") for c in cands if isinstance(c, dict)]
if rec.gold_ppn in rec.candidate_ppns:
rec.gold_rank = rec.candidate_ppns.index(rec.gold_ppn) + 1
rec.accepted_correct = (rec.status == "accepted" and rec.best_ppn == rec.gold_ppn)
rec.top1_correct = (rec.top1_ppn == rec.gold_ppn)
rec.topk_correct = (rec.gold_ppn in rec.candidate_ppns)
return rec
# --------------------------------------------------------------------------- #
# Async runner
# --------------------------------------------------------------------------- #
async def call_align(client: httpx.AsyncClient, url: str, headers: dict[str, str],
payload: dict[str, Any], retries: int = 2) -> dict[str, Any]:
last_err = ""
for attempt in range(retries + 1):
try:
r = await client.post(url, json=payload, headers=headers)
if r.status_code == 200:
return r.json()
last_err = f"HTTP {r.status_code}: {r.text[:200]}"
except Exception as exc: # noqa: BLE001
last_err = f"{type(exc).__name__}: {exc}"
await asyncio.sleep(1.5 * (attempt + 1))
raise RuntimeError(last_err or "unknown error")
async def run_eval(args: argparse.Namespace) -> None:
print(f"Loading dataset {args.dataset} (split={args.split}) ...", file=sys.stderr)
ds = load_dataset(args.dataset, split=args.split)
# We never need the decoded image; drop it to avoid Pillow dependency.
if "thumbnail" in ds.column_names:
ds = ds.remove_columns(["thumbnail"])
n_rows = len(ds) if args.limit <= 0 else min(args.limit, len(ds))
# Build the flat list of (row, person) tasks.
tasks_meta: list[PersonEval] = []
payloads: list[dict[str, Any]] = []
for i in range(n_rows):
row = ds[i]
ctx = build_context(row.get("sudoc_record_templated"))
gold = parse_idref_column(row.get("idref_persname_ppns"))
for name, ppn in gold.items():
tasks_meta.append(PersonEval(
row_index=i,
case_id=str(row.get("case_id") or ""),
base_id=str(row.get("base_id") or ""),
name=name,
gold_ppn=str(ppn),
))
payloads.append(build_align_payload(
ctx, name, args.embedding_model,
args.max_candidates, args.max_docs_per_role, args.reference_top_k,
))
print(f"{n_rows} documents -> {len(tasks_meta)} person alignment requests.", file=sys.stderr)
url = args.api_base.rstrip("/") + "/align/person"
headers = {"Content-Type": "application/json"}
if args.api_key:
headers["X-API-Key"] = args.api_key
sem = asyncio.Semaphore(args.concurrency)
limits = httpx.Limits(max_connections=args.concurrency, max_keepalive_connections=args.concurrency)
timeout = httpx.Timeout(args.request_timeout)
results: list[PersonEval] = [None] * len(tasks_meta) # type: ignore[list-item]
async with httpx.AsyncClient(limits=limits, timeout=timeout, follow_redirects=True) as client:
pbar = tqdm(total=len(tasks_meta), desc="aligning", file=sys.stderr)
async def worker(idx: int) -> None:
rec = tasks_meta[idx]
async with sem:
try:
resp = await call_align(client, url, headers, payloads[idx])
rec = evaluate_response(rec, resp)
except Exception as exc: # noqa: BLE001
rec.error = str(exc)
rec.status = "error"
results[idx] = rec
pbar.update(1)
await asyncio.gather(*(worker(i) for i in range(len(tasks_meta))))
pbar.close()
# ----------------------------------------------------------------------- #
# Write per-person JSONL
# ----------------------------------------------------------------------- #
with open(args.out, "w", encoding="utf-8") as fh:
for rec in results:
fh.write(json.dumps(asdict(rec), ensure_ascii=False) + "\n")
# ----------------------------------------------------------------------- #
# Aggregate metrics
# ----------------------------------------------------------------------- #
total = len(results)
errors = sum(1 for r in results if r.error)
evaluated = total - errors
accepted = sum(1 for r in results if r.status == "accepted")
accepted_correct = sum(1 for r in results if r.accepted_correct)
top1_correct = sum(1 for r in results if r.top1_correct)
topk_correct = sum(1 for r in results if r.topk_correct)
status_breakdown = Counter(r.status for r in results)
def pct(num: int, den: int) -> float:
return round(100.0 * num / den, 2) if den else 0.0
# Treat "accepted" as the positive prediction; gold is always a real positive (every person has a true PPN).
# precision = accepted_correct / accepted ; recall = accepted_correct / evaluated
precision = pct(accepted_correct, accepted)
recall = pct(accepted_correct, evaluated)
f1 = round(2 * precision * recall / (precision + recall), 2) if (precision + recall) else 0.0
summary = {
"dataset": args.dataset,
"split": args.split,
"api_base": args.api_base,
"embedding_model": args.embedding_model,
"documents_evaluated": n_rows,
"person_requests_total": total,
"request_errors": errors,
"evaluated": evaluated,
"metrics": {
"accepted_decisions": accepted,
"accepted_correct": accepted_correct,
"accepted_accuracy_over_evaluated_pct": pct(accepted_correct, evaluated),
"top1_correct": top1_correct,
"top1_accuracy_pct": pct(top1_correct, evaluated),
"topk_correct_(gold_in_candidates)": topk_correct,
"candidate_recall_pct": pct(topk_correct, evaluated),
"accepted_precision_pct": precision,
"accepted_recall_pct": recall,
"accepted_f1": f1,
},
"status_breakdown": dict(status_breakdown),
}
with open(args.summary_out, "w", encoding="utf-8") as fh:
json.dump(summary, fh, ensure_ascii=False, indent=2)
# ----------------------------------------------------------------------- #
# Console report
# ----------------------------------------------------------------------- #
print("\n" + "=" * 70)
print("IdRef alignment evaluation — summary")
print("=" * 70)
print(f"Dataset : {args.dataset} [{args.split}]")
print(f"API : {args.api_base} (embedding={args.embedding_model or 'lexical'})")
print(f"Documents : {n_rows}")
print(f"Person requests : {total} (errors: {errors}, evaluated: {evaluated})")
print("-" * 70)
m = summary["metrics"]
print(f"Accepted decisions : {accepted}/{evaluated} ({pct(accepted, evaluated)}%)")
print(f"Accepted & correct : {accepted_correct}/{evaluated} ({m['accepted_accuracy_over_evaluated_pct']}%)")
print(f"Top-1 correct : {top1_correct}/{evaluated} ({m['top1_accuracy_pct']}%)")
print(f"Gold in candidates : {topk_correct}/{evaluated} ({m['candidate_recall_pct']}%) <- candidate recall")
print("-" * 70)
print(f"Accepted precision : {precision}% (correct / accepted)")
print(f"Accepted recall : {recall}% (correct / evaluated)")
print(f"Accepted F1 : {f1}")
print("-" * 70)
print("Status breakdown :")
for st, c in status_breakdown.most_common():
print(f" {st:<15}: {c}")
print("=" * 70)
print(f"Per-person details : {args.out}")
print(f"Summary JSON : {args.summary_out}")
def main() -> None:
args = parse_args()
asyncio.run(run_eval(args))
if __name__ == "__main__":
main()