"""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.config import settings from legex.evaluation import SYSTEMS, _BUCKETS, _derived, score_country from legex.utils import evaluable_countries log = logging.getLogger(__name__) # Paper §A. Static maps — adding a jurisdiction = adding two entries. 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 emitted = tp + mism + hallu 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_CSV_RE = re.compile(r"^inference_(.+)\.csv$") def models_present(cc: str) -> list[str]: """Which systems have an inference_.csv on disk for `cc`.""" d = settings.data_dir / cc if not d.is_dir(): return [] found: set[str] = set() for p in d.glob("inference_*.csv"): m = _INFERENCE_CSV_RE.match(p.name) if m: found.add(m.group(1)) return sorted(found) def collect( countries: list[str], models: list[str] ) -> list[tuple[str, str, dict[str, dict[str, int]]]]: """Score every (country, system) pair. Returns rows of (cc, system, counters).""" rows: list[tuple[str, str, dict[str, dict[str, int]]]] = [] for cc in countries: ms = models or models_present(cc) for model in ms: result = score_country(cc, model, verbose=False) 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)}" "}. Recall when filled is over the cells where the expert recorded a value. " "False-fill rate is the share of legitimately-empty cells where the model " "invented a value.}" ) lines.append("\\label{tab:headline-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}") lines.append("\\centering\\small") lines.append("\\begin{tabular}{@{}lrr@{}}") lines.append("\\toprule") lines.append("Jurisdiction & Recall when filled & False-fill rate \\\\") lines.append("\\midrule") for cc, counters in sorted(by_model[model]): d_all = derived_metrics(sum_buckets(counters)) lines.append( f"{cc.upper()} & {_pct(d_all['recall_when_filled'])} " f"& {_pct(d_all['hallucination_rate'])} \\\\" ) 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)}" "}. Recall when filled is over the cells where the expert recorded a value. False-fill " "rate is the share of legitimately-empty cells where the model invented a value.}" ) lines.append("\\label{tab:per-field-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}") lines.append("\\centering\\small") lines.append("\\begin{tabular}{@{}lrr@{}}") lines.append("\\toprule") lines.append("Variable & Recall when filled & False-fill rate \\\\") lines.append("\\midrule") for col, c in sorted(by_model_col[model].items()): d = derived_metrics(c) lines.append( f"\\texttt{{{_latex_escape(col)}}} " f"& {_pct(d['recall_when_filled'])} & {_pct(d['hallucination_rate'])} \\\\" ) 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, out_dir: Path, ) -> None: targets = countries or evaluable_countries() rows = collect(targets, models or []) if not rows: log.warning("no (country, system) 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, system) 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 JSONL goldensets vs system inference CSVs.", ) parser.add_argument( "--country", action="extend", nargs="+", dest="countries", help=( "Country code(s). Repeatable. " "Default: every jurisdiction with a goldenset_.jsonl minus the " "round-2 exclusion set (BE/NP/RS plus TW/BR/HK/IN)." ), ) parser.add_argument( "--system", "--model", action="extend", nargs="+", dest="models", choices=list(SYSTEMS), help=f"Inference system(s). Repeatable. Default: every system with a CSV on disk per country ({list(SYSTEMS)}).", ) parser.add_argument( "--out", type=Path, default=Path("data/analysis"), help="Output directory (default: data/analysis).", ) args = parser.parse_args() analyse( countries=args.countries, models=args.models, out_dir=args.out, ) if __name__ == "__main__": main()