| """Cross-jurisdiction analysis of Goldenset vs prediction CSVs. |
| |
| Builds on `legex.evaluation.score_country`: reuses the (tp, mismatch, missed, |
| hallucinated, tn) per-cell buckets and exposes paper-headline aggregates — |
| hallucination rate, recall-when-filled, miss rate — across countries, fields, |
| models, legal traditions, and language families. |
| |
| Outputs CSV + LaTeX tables under ``--out`` (default ``data/analysis``). |
| """ |
|
|
| import argparse |
| import csv |
| import logging |
| import re |
| import sys |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| from legex import published |
| from legex.config import settings |
| from legex.evaluation import BUCKETS, derived, score_country |
| from legex.utils import countries_with_goldenset |
|
|
| log = logging.getLogger(__name__) |
|
|
|
|
| |
| LEGAL_TRADITION: dict[str, str] = { |
| "au": "common", "hk": "common", "in": "common", "nz": "common", |
| "sg": "common", "uk": "common", "us": "common", "gh": "common", |
| "ph": "common", |
| "am": "civil", "at": "civil", "be": "civil", "br": "civil", |
| "ch": "civil", "de": "civil", "es": "civil", "fr": "civil", |
| "ge": "civil", "it": "civil", "li": "civil", "lu": "civil", |
| "np": "civil", "rs": "civil", "tw": "civil", "xk": "civil", |
| "al": "civil", |
| } |
|
|
| LANGUAGE_FAMILY: dict[str, str] = { |
| "au": "en-latin", "hk": "en-latin", "in": "en-latin", "nz": "en-latin", |
| "sg": "en-latin", "uk": "en-latin", "us": "en-latin", "gh": "en-latin", |
| "ph": "en-latin", |
| "at": "eu-latin", "be": "eu-latin", "br": "eu-latin", "ch": "eu-latin", |
| "de": "eu-latin", "es": "eu-latin", "fr": "eu-latin", "it": "eu-latin", |
| "li": "eu-latin", "lu": "eu-latin", "rs": "eu-latin", "al": "eu-latin", |
| "xk": "eu-latin", |
| "am": "non-latin", "ge": "non-latin", "np": "non-latin", "tw": "non-latin", |
| } |
|
|
|
|
| COST_BLOCK: tuple[str, ...] = ( |
| "dispute_value_nominal", |
| "plaintiff_loosing_share", |
| "court_cost_awarded_nominal", |
| "party_compensation_awarded_nominal", |
| ) |
|
|
|
|
| DERIVED_KEYS = ( |
| "accuracy", |
| "recall_when_filled", |
| "precision_when_emitted", |
| "hallucination_rate", |
| "miss_rate", |
| "wrong_when_both_filled", |
| "f1", |
| ) |
|
|
|
|
| def derived_metrics(c: dict[str, int]) -> dict[str, float]: |
| """Seven paper-headline metrics from a single bucket counter.""" |
| tp, mism, miss, hallu, tn = c["tp"], c["mismatch"], c["missed"], c["hallucinated"], c["tn"] |
| total = tp + mism + miss + hallu + tn |
| filled_gold = tp + mism + miss |
| empty_gold = hallu + tn |
| both_filled = tp + mism |
| p, r, f1 = derived(c) |
| return { |
| "accuracy": (tp + tn) / total if total else 0.0, |
| "recall_when_filled": r, |
| "precision_when_emitted": p, |
| "hallucination_rate": hallu / empty_gold if empty_gold else 0.0, |
| "miss_rate": miss / filled_gold if filled_gold else 0.0, |
| "wrong_when_both_filled": mism / both_filled if both_filled else 0.0, |
| "f1": f1, |
| } |
|
|
|
|
| def add_buckets(a: dict[str, int], b: dict[str, int]) -> dict[str, int]: |
| return {k: a.get(k, 0) + b.get(k, 0) for k in BUCKETS} |
|
|
|
|
| def sum_buckets(counters: dict[str, dict[str, int]], cols: tuple[str, ...] | None = None) -> dict[str, int]: |
| """Sum bucket counts across `cols` (or all columns when None).""" |
| out = {k: 0 for k in BUCKETS} |
| for col, c in counters.items(): |
| if cols is not None and col not in cols: |
| continue |
| for k in BUCKETS: |
| out[k] += c[k] |
| return out |
|
|
|
|
| _INFERENCE_FILENAME_RE = re.compile(r"^Goldenset_(.+?)_(v\d+)_(full_text|pdf)_(.+)\.jsonl$") |
|
|
|
|
| def models_present(cc: str, inference_dir: Path | None = None) -> list[str]: |
| """Inverse of `model_filename_slug`: which models have an inference file for `cc`.""" |
| if inference_dir is not None: |
| return sorted( |
| model for model in published.MODEL_FILES |
| if published.inference_file(inference_dir, cc, model).exists() |
| ) |
| d = settings.data_dir / cc |
| if not d.is_dir(): |
| return [] |
| found: set[str] = set() |
| for p in d.glob("Goldenset_*_v*_*.jsonl"): |
| m = _INFERENCE_FILENAME_RE.match(p.name) |
| if not m: |
| continue |
| slug = m.group(4) |
| |
| |
| if slug.startswith("gemini_"): |
| found.add("gemini/" + slug[len("gemini_"):]) |
| elif slug.startswith("anthropic_"): |
| found.add("anthropic/" + slug[len("anthropic_"):]) |
| else: |
| found.add(slug) |
| return sorted(found) |
|
|
|
|
| def collect( |
| countries: list[str], |
| models: list[str], |
| prompt_version: str, |
| source: str, |
| gold_dir: Path | None = None, |
| inference_dir: Path | None = None, |
| ) -> list[tuple[str, str, dict[str, dict[str, int]]]]: |
| """Score every (country, model) pair. Returns rows of (cc, model, counters).""" |
| rows: list[tuple[str, str, dict[str, dict[str, int]]]] = [] |
| for cc in countries: |
| ms = models or models_present(cc, inference_dir) |
| for model in ms: |
| result = score_country( |
| cc, prompt_version, source, model, verbose=False, |
| gold_dir=gold_dir, inference_dir=inference_dir, |
| ) |
| if result is None: |
| log.info(f"[{cc}/{model}] no scoreable data, skipping") |
| continue |
| counters, _coverage = result |
| rows.append((cc, model, counters)) |
| log.info(f"[{cc}/{model}] scored {len(counters)} columns") |
| return rows |
|
|
|
|
| def _fmt(v: float) -> str: |
| return f"{v:.4f}" |
|
|
|
|
| def _write_csv(path: Path, header: list[str], rows: list[dict[str, object]]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with open(path, "w", encoding="utf-8", newline="") as f: |
| w = csv.DictWriter(f, fieldnames=header, extrasaction="ignore") |
| w.writeheader() |
| w.writerows(rows) |
|
|
|
|
| def write_per_country_per_column(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: |
| header = ["country", "model", "column", *BUCKETS, *DERIVED_KEYS] |
| out_rows: list[dict[str, object]] = [] |
| for cc, model, counters in rows: |
| for col, c in counters.items(): |
| d = derived_metrics(c) |
| out_rows.append({ |
| "country": cc, "model": model, "column": col, |
| **c, **{k: _fmt(d[k]) for k in DERIVED_KEYS}, |
| }) |
| _write_csv(out / "per_country_per_column.csv", header, out_rows) |
|
|
|
|
| def write_per_country(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: |
| """One row per (cc, model): summed buckets across all label columns, plus |
| cost-block-only summed buckets. Also adds tradition / language tags.""" |
| header = [ |
| "country", "model", "legal_tradition", "language_family", |
| *BUCKETS, *DERIVED_KEYS, |
| *(f"cost_{k}" for k in BUCKETS), |
| *(f"cost_{k}" for k in DERIVED_KEYS), |
| ] |
| out_rows: list[dict[str, object]] = [] |
| for cc, model, counters in rows: |
| all_b = sum_buckets(counters) |
| cost_b = sum_buckets(counters, COST_BLOCK) |
| d_all = derived_metrics(all_b) |
| d_cost = derived_metrics(cost_b) |
| out_rows.append({ |
| "country": cc, "model": model, |
| "legal_tradition": LEGAL_TRADITION.get(cc, ""), |
| "language_family": LANGUAGE_FAMILY.get(cc, ""), |
| **all_b, |
| **{k: _fmt(d_all[k]) for k in DERIVED_KEYS}, |
| **{f"cost_{k}": cost_b[k] for k in BUCKETS}, |
| **{f"cost_{k}": _fmt(d_cost[k]) for k in DERIVED_KEYS}, |
| }) |
| _write_csv(out / "per_country.csv", header, out_rows) |
|
|
|
|
| def write_per_column(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: |
| """One row per (model, column): summed across countries.""" |
| agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in BUCKETS}) |
| for _cc, model, counters in rows: |
| for col, c in counters.items(): |
| for k in BUCKETS: |
| agg[(model, col)][k] += c[k] |
| header = ["model", "column", *BUCKETS, *DERIVED_KEYS] |
| out_rows: list[dict[str, object]] = [] |
| for (model, col), c in sorted(agg.items()): |
| d = derived_metrics(c) |
| out_rows.append({ |
| "model": model, "column": col, **c, |
| **{k: _fmt(d[k]) for k in DERIVED_KEYS}, |
| }) |
| _write_csv(out / "per_column.csv", header, out_rows) |
|
|
|
|
| def _write_grouped( |
| out: Path, name: str, group_map: dict[str, str], |
| rows: list[tuple[str, str, dict[str, dict[str, int]]]], |
| ) -> None: |
| agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in BUCKETS}) |
| cost_agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in BUCKETS}) |
| counts: dict[tuple[str, str], int] = defaultdict(int) |
| for cc, model, counters in rows: |
| group = group_map.get(cc) |
| if group is None: |
| continue |
| key = (model, group) |
| all_b = sum_buckets(counters) |
| cost_b = sum_buckets(counters, COST_BLOCK) |
| for k in BUCKETS: |
| agg[key][k] += all_b[k] |
| cost_agg[key][k] += cost_b[k] |
| counts[key] += 1 |
| header = [ |
| "model", "group", "n_countries", |
| *BUCKETS, *DERIVED_KEYS, |
| *(f"cost_{k}" for k in BUCKETS), |
| *(f"cost_{k}" for k in DERIVED_KEYS), |
| ] |
| out_rows: list[dict[str, object]] = [] |
| for (model, group), c in sorted(agg.items()): |
| cost_c = cost_agg[(model, group)] |
| d_all = derived_metrics(c) |
| d_cost = derived_metrics(cost_c) |
| out_rows.append({ |
| "model": model, "group": group, |
| "n_countries": counts[(model, group)], |
| **c, |
| **{k: _fmt(d_all[k]) for k in DERIVED_KEYS}, |
| **{f"cost_{k}": cost_c[k] for k in BUCKETS}, |
| **{f"cost_{k}": _fmt(d_cost[k]) for k in DERIVED_KEYS}, |
| }) |
| _write_csv(out / f"{name}.csv", header, out_rows) |
|
|
|
|
| def _latex_escape(s: str) -> str: |
| return s.replace("\\", "\\textbackslash{}").replace("&", "\\&").replace("_", "\\_").replace("%", "\\%") |
|
|
|
|
| def _pct(v: float) -> str: |
| return f"{v * 100:5.1f}\\%" |
|
|
|
|
| def write_headline_latex(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: |
| """One LaTeX `tabular` per model: rows = jurisdiction, cols = headline metrics.""" |
| by_model: dict[str, list[tuple[str, dict[str, dict[str, int]]]]] = defaultdict(list) |
| for cc, model, counters in rows: |
| by_model[model].append((cc, counters)) |
|
|
| out.mkdir(parents=True, exist_ok=True) |
| lines: list[str] = [] |
| for model in sorted(by_model): |
| lines.append("% Auto-generated by legex-analysis.") |
| lines.append("\\begin{table}[h]") |
| lines.append( |
| "\\caption{Headline extraction metrics by jurisdiction for model \\texttt{" |
| f"{_latex_escape(model)}" |
| "}. Accuracy is per-cell. Recall is over the cells where the expert recorded a value. " |
| "Hallucination rate is the share of legitimately-empty cells where the model invented a value. " |
| "Cost-block $F_1$ aggregates over the four monetary variables.}" |
| ) |
| lines.append("\\label{tab:headline-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}") |
| lines.append("\\centering\\small") |
| lines.append("\\begin{tabular}{@{}lrrrr@{}}") |
| lines.append("\\toprule") |
| lines.append("Jurisdiction & Accuracy & Recall$_{\\text{filled}}$ & Hallu. rate & Cost $F_1$ \\\\") |
| lines.append("\\midrule") |
| for cc, counters in sorted(by_model[model]): |
| d_all = derived_metrics(sum_buckets(counters)) |
| d_cost = derived_metrics(sum_buckets(counters, COST_BLOCK)) |
| lines.append( |
| f"{cc.upper()} & {_pct(d_all['accuracy'])} & {_pct(d_all['recall_when_filled'])} " |
| f"& {_pct(d_all['hallucination_rate'])} & {d_cost['f1']:.3f} \\\\" |
| ) |
| lines.append("\\bottomrule") |
| lines.append("\\end{tabular}") |
| lines.append("\\end{table}") |
| lines.append("") |
| (out / "headline.tex").write_text("\n".join(lines), encoding="utf-8") |
|
|
|
|
| def write_per_field_latex(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: |
| """One LaTeX table per model: rows = variable, cols = headline metrics (summed across jurisdictions).""" |
| by_model_col: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: {k: 0 for k in BUCKETS})) |
| for _cc, model, counters in rows: |
| for col, c in counters.items(): |
| for k in BUCKETS: |
| by_model_col[model][col][k] += c[k] |
|
|
| out.mkdir(parents=True, exist_ok=True) |
| lines: list[str] = [] |
| for model in sorted(by_model_col): |
| lines.append("% Auto-generated by legex-analysis.") |
| lines.append("\\begin{table}[h]") |
| lines.append( |
| "\\caption{Per-field extraction metrics, summed across jurisdictions, for model \\texttt{" |
| f"{_latex_escape(model)}" |
| "}.}" |
| ) |
| lines.append("\\label{tab:per-field-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}") |
| lines.append("\\centering\\small") |
| lines.append("\\begin{tabular}{@{}lrrrr@{}}") |
| lines.append("\\toprule") |
| lines.append("Variable & Accuracy & Recall$_{\\text{filled}}$ & Hallu. rate & $F_1$ \\\\") |
| lines.append("\\midrule") |
| for col, c in sorted(by_model_col[model].items()): |
| d = derived_metrics(c) |
| lines.append( |
| f"\\texttt{{{_latex_escape(col)}}} & {_pct(d['accuracy'])} " |
| f"& {_pct(d['recall_when_filled'])} & {_pct(d['hallucination_rate'])} " |
| f"& {d['f1']:.3f} \\\\" |
| ) |
| lines.append("\\bottomrule") |
| lines.append("\\end{tabular}") |
| lines.append("\\end{table}") |
| lines.append("") |
| (out / "per_field.tex").write_text("\n".join(lines), encoding="utf-8") |
|
|
|
|
| def analyse( |
| countries: list[str] | None, |
| models: list[str] | None, |
| prompt_version: str, |
| source: str, |
| out_dir: Path, |
| gold_dir: Path | None = None, |
| inference_dir: Path | None = None, |
| ) -> None: |
| if countries is None: |
| countries = ( |
| published.countries_with_gold(gold_dir) |
| if gold_dir is not None |
| else countries_with_goldenset() |
| ) |
| rows = collect(countries, models or [], prompt_version, source, gold_dir, inference_dir) |
| if not rows: |
| log.warning("no (country, model) pairs produced results; nothing to write") |
| return |
| out_dir.mkdir(parents=True, exist_ok=True) |
| write_per_country_per_column(out_dir, rows) |
| write_per_country(out_dir, rows) |
| write_per_column(out_dir, rows) |
| _write_grouped(out_dir, "per_tradition", LEGAL_TRADITION, rows) |
| _write_grouped(out_dir, "per_language", LANGUAGE_FAMILY, rows) |
| write_headline_latex(out_dir / "tables", rows) |
| write_per_field_latex(out_dir / "tables", rows) |
| log.info(f"wrote analysis for {len(rows)} (country, model) pairs to {out_dir}") |
|
|
|
|
| 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-analysis", |
| description="Cross-jurisdiction analysis of Goldenset vs LLM predictions.", |
| ) |
| parser.add_argument( |
| "--country", action="extend", nargs="+", dest="countries", |
| help="Country code(s). Repeatable. Default: all countries with a Goldenset.", |
| ) |
| parser.add_argument( |
| "--model", action="append", dest="models", |
| help="Model id (repeatable). Default: every model with an inference file per country.", |
| ) |
| parser.add_argument("--prompt_version", default="v3") |
| parser.add_argument( |
| "--out", type=Path, default=Path("data/analysis"), |
| help="Output directory (default: data/analysis).", |
| ) |
| 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.", |
| ) |
| src = parser.add_mutually_exclusive_group() |
| src.add_argument("--full_text", dest="source", action="store_const", const="full_text") |
| src.add_argument("--pdf", dest="source", action="store_const", const="pdf") |
| 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)") |
| analyse( |
| countries=args.countries, |
| models=args.models, |
| prompt_version=args.prompt_version, |
| source=args.source, |
| out_dir=args.out, |
| gold_dir=args.gold_dir, |
| inference_dir=args.inference_dir, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|