Download legex/analysis/quant_results.py from legexbenchmark/code: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/datasets/legexbenchmark/code/resolve/main/legex/analysis/quant_results.py
- Command line
-
hf download hf://datasets/legexbenchmark/code/legex/analysis/quant_results.py
-
curl -L -o quant_results.py https://huggingface.co/datasets/legexbenchmark/code/resolve/main/legex/analysis/quant_results.py
11.2 kB
| """Render the manuscript's headline results table (`tab:overall`). | |
| Reads `data/analysis/per_country_per_column.csv` (produced by | |
| `legex-analysis`), restricts it to the 19 release jurisdictions, and renders | |
| the camera-ready headline table in the poster convention: recall on | |
| gold-filled cells, precision on emitted cells, F1, and the false-fill | |
| (hallucination) rate on gold-empty cells — each percentage with its ±1 SE — | |
| over the 10 structured fields (the 11 evaluated fields minus the free-text | |
| ``legal_subject_judgement``, whose unbounded label space has <1% human-human | |
| agreement) and over the four-field cost block. Denominators (n) are reported | |
| in the caption. | |
| The console echo additionally prints the "All 11 fields" cross-check and the | |
| exact denominators so prose numbers can be sourced from the same run. | |
| """ | |
| import argparse | |
| import csv | |
| import logging | |
| import math | |
| import sys | |
| from pathlib import Path | |
| from legex.analysis.countries import RELEASE_COUNTRIES | |
| log = logging.getLogger(__name__) | |
| EVAL_FIELDS: tuple[str, ...] = ( | |
| "legal_subject_judgement", | |
| "trial_start_date", | |
| "trial_end_date", | |
| "dispute_value_nominal", | |
| "plaintiff_loosing_share", | |
| "court_cost_awarded_nominal", | |
| "party_compensation_awarded_nominal", | |
| "plaintiffs_all_count", | |
| "defendants_all_count", | |
| "plaintiff_no1_ISIC1_industry_category", | |
| "defendant_no1_ISIC1_industry_category", | |
| ) | |
| STRUCTURED_FIELDS: tuple[str, ...] = tuple( | |
| f for f in EVAL_FIELDS if f != "legal_subject_judgement" | |
| ) | |
| COST_BLOCK: tuple[str, ...] = ( | |
| "dispute_value_nominal", | |
| "plaintiff_loosing_share", | |
| "court_cost_awarded_nominal", | |
| "party_compensation_awarded_nominal", | |
| ) | |
| FIELD_SETS: tuple[tuple[str, str, tuple[str, ...]], ...] = ( | |
| ("structured", "10 structured fields", STRUCTURED_FIELDS), | |
| ("cost", "Cost block (4 fields)", COST_BLOCK), | |
| ("all11", "All 11 fields", EVAL_FIELDS), # console cross-check only | |
| ) | |
| # (model id in CSV, label). Order = row order in the headline table. | |
| # The paper set renders tab:overall exactly as in the manuscript; the "all" | |
| # set adds the two transparency runs (released, not scored in the paper). | |
| PAPER_SYSTEMS: tuple[tuple[str, str], ...] = ( | |
| ("gemini/gemini-3.1-flash-lite", "Gemini"), | |
| ("gpt-5.4-mini", "GPT-5.4-mini"), | |
| ("harvey", "Harvey"), | |
| ("legora-1", "Legora"), | |
| ) | |
| ALL_SYSTEMS: tuple[tuple[str, str], ...] = ( | |
| PAPER_SYSTEMS[:3] | |
| + (("harvey-2", "Harvey 2"),) | |
| + PAPER_SYSTEMS[3:] | |
| + (("legora-2", "Legora 2"),) | |
| ) | |
| SYSTEM_SETS = {"paper": PAPER_SYSTEMS, "all": ALL_SYSTEMS} | |
| _BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn") | |
| def _empty() -> dict[str, int]: | |
| return {k: 0 for k in _BUCKETS} | |
| def _se_pp(p: float, n: int) -> float: | |
| """±1 standard error of a proportion, in percentage points.""" | |
| return 100.0 * math.sqrt(p * (1.0 - p) / n) if n else float("nan") | |
| def _metrics(c: dict[str, int]) -> dict[str, float]: | |
| tp, mism, miss, hallu, tn = ( | |
| c["tp"], c["mismatch"], c["missed"], c["hallucinated"], c["tn"], | |
| ) | |
| gold_filled = tp + mism + miss | |
| gold_empty = hallu + tn | |
| emitted = tp + mism + hallu | |
| r = tp / gold_filled if gold_filled else 0.0 | |
| p = tp / emitted if emitted else 0.0 | |
| ff = hallu / gold_empty if gold_empty else 0.0 | |
| return { | |
| "n_gold_filled": gold_filled, | |
| "n_gold_empty": gold_empty, | |
| "n_emitted": emitted, | |
| "recall": r, | |
| "recall_se": _se_pp(r, gold_filled), | |
| "precision": p, | |
| "precision_se": _se_pp(p, emitted), | |
| "f1": 2 * p * r / (p + r) if (p + r) else 0.0, | |
| "false_fill": ff, | |
| "false_fill_se": _se_pp(ff, gold_empty), | |
| } | |
| def _aggregate( | |
| csv_path: Path, systems: tuple[tuple[str, str], ...] | |
| ) -> dict[str, dict[str, dict[str, int]]]: | |
| """{ model -> { field-set key -> bucket counter } }.""" | |
| out: dict[str, dict[str, dict[str, int]]] = { | |
| m: {key: _empty() for key, _, _ in FIELD_SETS} for m, _ in systems | |
| } | |
| release = set(RELEASE_COUNTRIES) | |
| models = {m for m, _ in systems} | |
| field_sets = [(key, set(fields)) for key, _, fields in FIELD_SETS] | |
| with open(csv_path, encoding="utf-8", newline="") as f: | |
| for row in csv.DictReader(f): | |
| if row["country"] not in release or row["model"] not in models: | |
| continue | |
| col = row["column"] | |
| counts = {k: int(row[k]) for k in _BUCKETS} | |
| for key, fields in field_sets: | |
| if col in fields: | |
| for k in _BUCKETS: | |
| out[row["model"]][key][k] += counts[k] | |
| return out | |
| def _fmt_pct_se(m: dict[str, float], metric: str) -> str: | |
| return ( | |
| f"{m[metric] * 100:.1f}\\,$\\pm$\\,{m[f'{metric}_se']:.1f}\\%" | |
| ) | |
| def _fmt_f1(v: float) -> str: | |
| return f"{v:.2f}" | |
| def _bold_best( | |
| values: list[float], rendered: list[str], higher_is_better: bool = True | |
| ) -> list[str]: | |
| best = max(values) if higher_is_better else min(values) | |
| return [ | |
| rf"\textbf{{{s}}}" if v == best else s | |
| for v, s in zip(values, rendered) | |
| ] | |
| def _caption( | |
| agg: dict[str, dict[str, dict[str, int]]], systems: tuple[tuple[str, str], ...] | |
| ) -> str: | |
| """The manuscript's tab:overall caption, with per-system denominators in row order.""" | |
| names = "/".join(label for _, label in systems) | |
| n = { | |
| key: { | |
| kind: "/".join(str(_metrics(agg[m][key])[kind]) for m, _ in systems) | |
| for kind in ("n_gold_filled", "n_gold_empty") | |
| } | |
| for key, _, _ in FIELD_SETS[:2] | |
| } | |
| return ( | |
| r"\caption{Headline extraction metrics over the 19 release jurisdictions" | |
| r" (8 core and 11 preview), computed over each system's successfully" | |
| r" processed cases (metric definitions in \cref{sec:systems}). The left" | |
| r" block covers the ten structured fields, the right block the four" | |
| r" cost-block variables; percentages carry $\pm$1\,SE." | |
| f" Denominators, in row order ({names}), are" | |
| f" $n_{{\\text{{filled}}}}$\\,=\\,{n['structured']['n_gold_filled']} and" | |
| f" $n_{{\\text{{empty}}}}$\\,=\\,{n['structured']['n_gold_empty']} over the" | |
| f" ten structured fields, and" | |
| f" $n_{{\\text{{filled}}}}$\\,=\\,{n['cost']['n_gold_filled']} and" | |
| f" $n_{{\\text{{empty}}}}$\\,=\\,{n['cost']['n_gold_empty']} over the cost" | |
| r" block; Harvey and Legora have smaller denominators because of their" | |
| r" ingest gaps. F1 standard errors are below 0.01 and omitted." | |
| "\n" | |
| r"The best value per column is marked in \textbf{bold} (lower is better" | |
| r" for false fill).}" | |
| ) | |
| def render_table( | |
| agg: dict[str, dict[str, dict[str, int]]], systems: tuple[tuple[str, str], ...] | |
| ) -> str: | |
| metrics = { | |
| m: {key: _metrics(agg[m][key]) for key, _, _ in FIELD_SETS} | |
| for m, _ in systems | |
| } | |
| lines: list[str] = [] | |
| lines.append(r"% Auto-generated by legex-quant-results — do not edit by hand.") | |
| lines.append( | |
| r"% Aggregated over the 19 release jurisdictions; free-text" | |
| r" legal_subject_judgement excluded from scoring (reported separately)." | |
| ) | |
| lines.append(r"\begin{table*}[t]") | |
| lines.append(r"\centering\small") | |
| lines.append( | |
| r"\begin{tabular}{@{}l rrrr@{\hskip 14pt} rrrr@{}}" | |
| ) | |
| lines.append(r"\toprule") | |
| lines.append( | |
| r" & \multicolumn{4}{c}{10 structured fields}" | |
| r" & \multicolumn{4}{c}{Cost block (4 fields)} \\" | |
| ) | |
| lines.append(r"\cmidrule(lr){2-5}\cmidrule(l){6-9}") | |
| lines.append( | |
| r"System & Recall & Precision & F1 & False fill" | |
| r" & Recall & Precision & F1 & False fill \\" | |
| ) | |
| lines.append(r"\midrule") | |
| cells: dict[str, list[str]] = {m: [] for m, _ in systems} | |
| for key, _, _ in FIELD_SETS[:2]: | |
| for metric, higher_better in ( | |
| ("recall", True), ("precision", True), ("f1", True), ("false_fill", False), | |
| ): | |
| values = [metrics[m][key][metric] for m, _ in systems] | |
| if metric == "f1": | |
| rendered = [_fmt_f1(v) for v in values] | |
| else: | |
| rendered = [_fmt_pct_se(metrics[m][key], metric) for m, _ in systems] | |
| for (m, _), s in zip(systems, _bold_best(values, rendered, higher_better)): | |
| cells[m].append(s) | |
| for m, label in systems: | |
| lines.append(f"{label} & " + " & ".join(cells[m]) + r" \\") | |
| lines.append(r"\bottomrule") | |
| lines.append(r"\end{tabular}") | |
| lines.append(r"\vskip 0.05in") | |
| lines.append(_caption(agg, systems)) | |
| lines.append(r"\label{tab:overall}") | |
| lines.append(r"\end{table*}") | |
| lines.append("") | |
| return "\n".join(lines) | |
| def _print_console_summary( | |
| agg: dict[str, dict[str, dict[str, int]]], systems: tuple[tuple[str, str], ...] | |
| ) -> None: | |
| """Human-readable echo, incl. denominators and the all-11-fields cross-check, | |
| so manuscript prose numbers can be copied from the same run.""" | |
| for key, label, _ in FIELD_SETS: | |
| print(f"=== {label} (19 release jurisdictions) ===") | |
| for model, _ in systems: | |
| m = _metrics(agg[model][key]) | |
| print( | |
| f"{model:<28}" | |
| f" recall {m['recall'] * 100:5.1f}%±{m['recall_se']:.1f}" | |
| f" (n={m['n_gold_filled']})" | |
| f" precision {m['precision'] * 100:5.1f}%±{m['precision_se']:.1f}" | |
| f" (n={m['n_emitted']})" | |
| f" F1 {m['f1']:.3f}" | |
| f" false-fill {m['false_fill'] * 100:5.1f}%±{m['false_fill_se']:.1f}" | |
| f" (n={m['n_gold_empty']})" | |
| ) | |
| print() | |
| 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-quant-results", | |
| description="Render the camera-ready headline results table (tab:overall).", | |
| ) | |
| parser.add_argument( | |
| "--input", type=Path, | |
| default=Path("data/analysis/per_country_per_column.csv"), | |
| help="per_country_per_column.csv produced by legex-analysis.", | |
| ) | |
| parser.add_argument( | |
| "--out", type=Path, | |
| default=Path("data/analysis/quant_results.tex"), | |
| help="Where to write the rendered LaTeX table.", | |
| ) | |
| parser.add_argument( | |
| "--systems", choices=sorted(SYSTEM_SETS), default="paper", | |
| help="'paper' renders tab:overall exactly as in the manuscript; 'all' " | |
| "adds the harvey-2 and legora-2 transparency runs.", | |
| ) | |
| args = parser.parse_args() | |
| if not args.input.exists(): | |
| raise SystemExit( | |
| f"{args.input} not found — run `legex-analysis` first to generate it." | |
| ) | |
| systems = SYSTEM_SETS[args.systems] | |
| agg = _aggregate(args.input, systems) | |
| tex = render_table(agg, systems) | |
| args.out.parent.mkdir(parents=True, exist_ok=True) | |
| args.out.write_text(tex, encoding="utf-8") | |
| log.info(f"wrote {args.out}") | |
| _print_console_summary(agg, systems) | |
| if __name__ == "__main__": | |
| main() | |