File size: 5,983 Bytes
2e511b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | #!/usr/bin/env python3
"""Reproduce the headline table of the AI4Law poster (and its footnote numbers).
Reads ``data/analysis/per_column.csv`` (produced by ``legex-analysis`` over all
countries and models; regenerate the whole chain with
``scripts/reproduce_paper.sh``) and aggregates the per-field confusion buckets
over two field sets:
* ``10 structured fields`` -- the 11 evaluated fields minus the free-text
``legal_subject_judgement`` (unbounded label space, human-human agreement
<1%, see data/analysis/iaa/ANALYSIS.md section 2.1);
* ``Cost block (4 fields)`` -- dispute value, losing share, court costs,
party compensation.
For every system it prints recall on gold-filled cells, precision on emitted
cells, F1, and the false-fill (hallucination) rate on gold-empty cells, each
with its denominator n and +-1 SE = sqrt(p*(1-p)/n) in percentage points.
Metric definitions match ``legex/analysis/quant_results.py::_metrics`` and
``legex/evaluation`` (buckets: tp / mismatch / missed / hallucinated / tn).
Usage:
uv run python scripts/poster_metrics.py # human-readable table
uv run python scripts/poster_metrics.py --latex # poster LaTeX rows
"""
import argparse
import csv
import math
from collections import defaultdict
from pathlib import Path
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",
)
COST_BLOCK: tuple[str, ...] = (
"dispute_value_nominal",
"plaintiff_loosing_share",
"court_cost_awarded_nominal",
"party_compensation_awarded_nominal",
)
STRUCTURED: tuple[str, ...] = tuple(
f for f in EVAL_FIELDS if f != "legal_subject_judgement"
)
FIELD_SETS: tuple[tuple[str, tuple[str, ...]], ...] = (
("10 structured fields", STRUCTURED),
("Cost block (4 fields)", COST_BLOCK),
("All 11 fields", EVAL_FIELDS), # footnote cross-check: recall 51-58%
)
# (model id in CSV, poster label). Order = row order in the poster table.
SYSTEMS: tuple[tuple[str, str], ...] = (
("gemini/gemini-3.1-flash-lite", "Gemini"),
("gpt-5.4-mini", "ChatGPT"),
("harvey", "Harvey"),
)
_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")
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 _aggregate(csv_path: Path) -> dict[str, dict[str, dict[str, int]]]:
"""model -> column -> summed confusion buckets."""
counts: dict[str, dict[str, dict[str, int]]] = defaultdict(
lambda: defaultdict(lambda: {k: 0 for k in _BUCKETS})
)
with csv_path.open(newline="") as fh:
for row in csv.DictReader(fh):
cell = counts[row["model"]][row["column"]]
for k in _BUCKETS:
cell[k] += int(row[k])
return counts
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
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": hallu / gold_empty if gold_empty else 0.0,
"false_fill_se": _se_pp(hallu / gold_empty if gold_empty else 0.0, gold_empty),
}
def _sum_fields(
per_column: dict[str, dict[str, int]], fields: tuple[str, ...]
) -> dict[str, int]:
out = {k: 0 for k in _BUCKETS}
for f in fields:
for k in _BUCKETS:
out[k] += per_column[f][k]
return out
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument(
"--csv",
type=Path,
default=Path(__file__).resolve().parents[1] / "data/analysis/per_column.csv",
help="per_column.csv produced by legex-analysis (default: data/analysis/)",
)
ap.add_argument(
"--latex", action="store_true",
help="emit the poster table rows as LaTeX instead of plain text",
)
args = ap.parse_args()
counts = _aggregate(args.csv)
if args.latex:
for model, label in SYSTEMS:
cells: list[str] = []
for _, fields in FIELD_SETS[:2]: # structured + cost block only
m = _metrics(_sum_fields(counts[model], fields))
cells += [
f"{m['recall'] * 100:.1f}\\%",
f"{m['precision'] * 100:.1f}\\%",
f"{m['f1']:.2f}",
f"{m['false_fill'] * 100:.1f}\\%",
]
print(f"{label} & " + " & ".join(cells) + r" \\")
return
for set_name, fields in FIELD_SETS:
print(f"=== {set_name} ===")
for model, label in SYSTEMS:
m = _metrics(_sum_fields(counts[model], fields))
print(
f"{label:8s}"
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()
if __name__ == "__main__":
main()
|