"""Compare Goldenset gold labels against inference output. Reads each country's gold labels — from ``Goldenset_*.xlsx`` (the maintainers' workbooks) or, with ``--gold-dir``, from the published goldenset JSONL — and the matching predictions JSONL, then reports per-field agreement. """ import argparse import logging import sys from pathlib import Path from openpyxl import load_workbook from legex import published from legex.evaluation.comparison import ( BUCKETS, classify_cell, derived, is_label_column, normalise, ) from legex.inference import inference_output_path from legex.utils import ( countries_with_goldenset, goldenset_path, goldenset_sheet, read_inference_jsonl, ) log = logging.getLogger(__name__) def _read_goldenset_rows(cc: str) -> tuple[list[str], dict[str, dict[str, str]]]: """Return (label_columns, rows_by_case_id) for a country's Goldenset.""" wb = load_workbook(goldenset_path(cc), read_only=True, data_only=True) ws = goldenset_sheet(wb) rows = ws.iter_rows(values_only=True) header = [str(c) if c is not None else "" for c in next(rows)] if "case_id" not in header: raise ValueError(f"{goldenset_path(cc)} GOLDENSET sheet missing case_id column") label_columns = [h for h in header if is_label_column(h)] by_id: dict[str, dict[str, str]] = {} for row in rows: if not any(row): continue cells = dict(zip(header, row)) case_id = normalise(cells.get("case_id")) if not case_id: continue labels = {col: normalise(cells.get(col)) for col in label_columns} if not any(labels.values()): continue by_id[case_id] = labels return label_columns, by_id def _read_predictions(path: Path) -> dict[str, dict[str, str]]: by_id: dict[str, dict[str, str]] = {} for row in read_inference_jsonl(path): case_id = normalise(row.get("case_id")) if not case_id: continue # Rows whose inference failed are treated like absent inference if normalise(row.get("error")): continue labels = {k: normalise(v) for k, v in row.items() if is_label_column(k)} if not any(labels.values()): continue by_id[case_id] = {k: normalise(v) for k, v in row.items()} return by_id def _coverage( gold: dict[str, dict[str, str]], preds: dict[str, dict[str, str]] ) -> dict[str, int]: gold_ids, pred_ids = set(gold), set(preds) return { "gold": len(gold_ids), "pred": len(pred_ids), "overlap": len(gold_ids & pred_ids), "missing": len(gold_ids - pred_ids), "extra": len(pred_ids - gold_ids), } def score_country( cc: str, prompt_version: str, source: str, model: str, verbose: bool = True, *, gold_dir: Path | None = None, inference_dir: Path | None = None, ) -> tuple[dict[str, dict[str, int]], dict[str, int]] | None: """Return (per-column counters, case coverage stats). ``gold_dir`` / ``inference_dir`` switch the respective input to the published JSONL bundles (see ``legex.published``); by default the maintainers' XLSX workbooks and working inference files are read. """ pred_path = ( published.inference_file(inference_dir, cc, model) if inference_dir is not None else inference_output_path(cc, prompt_version, source, model) ) if not pred_path.exists(): if verbose: log.warning(f"[{cc}] missing predictions {pred_path}, skipping") return None gold_path = published.gold_file(gold_dir, cc) if gold_dir is not None else goldenset_path(cc) if not gold_path.exists(): if verbose: log.warning(f"[{cc}] missing goldenset {gold_path}, skipping") return None if gold_dir is not None: label_columns, gold = published.load_gold_labels(gold_dir, cc) else: label_columns, gold = _read_goldenset_rows(cc) preds = _read_predictions(pred_path) stats = _coverage(gold, preds) counters: dict[str, dict[str, int]] = {col: {b: 0 for b in BUCKETS} for col in label_columns} if verbose: print() log.info( f"[{cc}] gold={stats['gold']} pred={stats['pred']} overlap={stats['overlap']} " f"missing={stats['missing']} extra={stats['extra']}" ) for case_id in (cid for cid in gold if cid in preds): g, p = gold[case_id], preds[case_id] for col in label_columns: counters[col][classify_cell(g.get(col, ""), p.get(col, ""), col)] += 1 return counters, stats def _print_report( cc: str, counters: dict[str, dict[str, int]], coverage: dict[str, int] | None = None ) -> None: name_width = max(max((len(c) for c in counters), default=0), len("column")) print(f"=== {cc} ===") if coverage is not None: print( f"cases: gold={coverage['gold']} pred={coverage['pred']} " f"overlap={coverage['overlap']} missing={coverage['missing']} " f"extra={coverage['extra']}" ) print( f"{'column'.ljust(name_width)} " f"{'TP':>5} {'Mism':>5} {'Miss':>5} {'Hallu':>5} {'TN':>5} " f"{'P':>7} {'R':>7} {'F1':>5}" ) for col, c in counters.items(): p, r, f1 = derived(c) f1_s = f"{f1:.2f}" if (p + r) else " - " print( f"{col.ljust(name_width)} " f"{c['tp']:>5} {c['mismatch']:>5} {c['missed']:>5} " f"{c['hallucinated']:>5} {c['tn']:>5} " f"{p:>7.2%} {r:>7.2%} {f1_s:>5}" ) def evaluate( countries: list[str] | None, model: str, prompt_version: str, source: str, gold_dir: Path | None = None, inference_dir: Path | None = None, ) -> None: overall: dict[str, dict[str, int]] = { col: {b: 0 for b in BUCKETS} for col in published.LABEL_FIELDS } overall_coverage = {"gold": 0, "pred": 0, "overlap": 0, "missing": 0, "extra": 0} if countries is None: countries = ( published.countries_with_gold(gold_dir) if gold_dir is not None else countries_with_goldenset() ) seen_any = False for cc in countries: result = score_country( cc, prompt_version, source, model, gold_dir=gold_dir, inference_dir=inference_dir, ) if result is None: continue counters, coverage = result seen_any = True _print_report(cc, counters, coverage) for key in overall_coverage: overall_coverage[key] += coverage[key] for col, c in counters.items(): overall.setdefault(col, {b: 0 for b in BUCKETS}) for b in BUCKETS: overall[col][b] += c[b] if seen_any: _print_report("ALL", overall, overall_coverage) def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) parser = argparse.ArgumentParser( prog="legex-evaluate", description="Compare Goldenset labels against LLM inference output.", ) parser.add_argument( "--country", action="extend", nargs="+", dest="countries", help="Country code(s). Repeatable and/or space-separated. Defaults to all with a Goldenset.", ) parser.add_argument( "--model", required=True, help="Model id of the predictions to evaluate (must match the classify run).", ) parser.add_argument("--prompt_version", default="v3", help="Prompt version (default: v3).") parser.add_argument( "--gold-dir", type=Path, default=None, help="Read gold labels from published goldenset JSONL under this directory " "instead of the XLSX workbooks.", ) parser.add_argument( "--inference-dir", type=Path, default=None, help="Read predictions from published inference JSONL under this directory " "instead of the working files.", ) source = parser.add_mutually_exclusive_group() source.add_argument("--full_text", dest="source", action="store_const", const="full_text", help="Evaluate predictions made from the full_text column.") source.add_argument("--pdf", dest="source", action="store_const", const="pdf", help="Evaluate predictions made from PDFs.") args = parser.parse_args() if args.inference_dir is None and args.source is None: parser.error("one of --full_text / --pdf is required (unless --inference-dir is used)") evaluate( countries=args.countries, model=args.model, prompt_version=args.prompt_version, source=args.source, gold_dir=args.gold_dir, inference_dir=args.inference_dir, ) if __name__ == "__main__": main()