code / legex /quant_results.py
anonymous
[code] Initial release of the code.
6f5156a
"""Render the `Quantitative Results` LaTeX section.
Reads `data/analysis/per_country_per_column.csv` (produced by
`legex-analysis`), restricts it to the twelve evaluated jurisdictions
and the fourteen evaluated fields, then prints the section preamble plus
the headline table that compares the three systems on Acc / Recall /
Hallucination / F1, both over all fields and over the four-field cost
block.
"""
import argparse
import csv
import logging
import sys
from collections import defaultdict
from pathlib import Path
log = logging.getLogger(__name__)
# Jurisdictions that survive the round-2 PDF audit (TW/BR/HK/IN excluded
# because their source PDFs were incomplete; BE/NP/RS excluded because
# inference was intentionally skipped for them).
EVALUATED_COUNTRIES: tuple[str, ...] = (
"am", "au", "ch", "de", "es", "fr", "ge",
"nz", "ph", "sg", "uk", "us",
)
H2H_COUNTRIES = EVALUATED_COUNTRIES # backwards-compat alias
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",
)
# (system slug as written by legex-analysis, LaTeX label). Order = row order
# in the headline table.
SYSTEMS: tuple[tuple[str, str], ...] = (
("gemini", r"\texttt{gemini-3.1-flash-lite}"),
("gpt", r"\texttt{gpt-5.4-mini} "),
("harvey", r"\textsc{Harvey} "),
)
_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")
def _empty() -> dict[str, int]:
return {k: 0 for k in _BUCKETS}
def _metrics(c: dict[str, int]) -> dict[str, float]:
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
p_denom = tp + mism + hallu
p = tp / p_denom if p_denom else 0.0
r = tp / filled_gold if filled_gold else 0.0
f1 = 2 * p * r / (p + r) if (p + r) else 0.0
return {
"accuracy": (tp + tn) / total if total else 0.0,
"recall_when_filled": r,
"hallucination_rate": hallu / empty_gold if empty_gold else 0.0,
"f1": f1,
}
def _aggregate(
csv_path: Path,
) -> dict[str, dict[str, dict[str, int]]]:
"""{ model -> { 'all' | 'cost' -> bucket counter } }."""
out: dict[str, dict[str, dict[str, int]]] = {
m: {"all": _empty(), "cost": _empty()} for m, _ in SYSTEMS
}
h2h = set(H2H_COUNTRIES)
eval_fields = set(EVAL_FIELDS)
cost_fields = set(COST_BLOCK)
models = {m for m, _ in SYSTEMS}
with open(csv_path, encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["country"] not in h2h or row["model"] not in models:
continue
col = row["column"]
if col not in eval_fields:
continue
counts = {k: int(row[k]) for k in _BUCKETS}
for k in _BUCKETS:
out[row["model"]]["all"][k] += counts[k]
if col in cost_fields:
for k in _BUCKETS:
out[row["model"]]["cost"][k] += counts[k]
return out
def _fmt_pct(v: float) -> str:
return f"{v * 100:.1f}\\%"
def _fmt_f1(v: float) -> str:
return f"{v:.3f}"
def _bold_best(values: list[float], formatter, higher_is_better: bool = True) -> list[str]:
best = max(values) if higher_is_better else min(values)
return [
rf"\textbf{{{formatter(v)}}}" if v == best else formatter(v)
for v in values
]
def render_section(agg: dict[str, dict[str, dict[str, int]]]) -> str:
lines: list[str] = []
lines.append(r"% Auto-generated by legex-quant-results — do not edit by hand.")
lines.append(r"\section{Quantitative Results}")
lines.append("")
lines.append(
r"We score the three systems against the human coded dataset: a commercial"
)
lines.append(
r"review-table product by \textsc{Harvey} and two schema-constrained LLM"
)
lines.append(
r"pipelines (\texttt{gpt-5.4-mini} and \texttt{gemini-3.1-flash-lite})."
)
lines.append(
r"Since the dataset contains missing fields, e.g.\ where a court judgement"
)
lines.append(
r"does not issue costs we evaluate our systems against two metrics:"
)
lines.append(r"\begin{itemize}")
lines.append(
r" \item \textbf{Accuracy when filled}: how often the system extracts the"
r" correct value given that the human expert has classified it."
)
lines.append(
r" \item \textbf{Hallucination rate}: how often the system extracts a"
r" value given that the human expert has left the field empty."
)
lines.append(r"\end{itemize}")
lines.append("")
metrics_all = {m: _metrics(agg[m]["all"]) for m, _ in SYSTEMS}
metrics_cost = {m: _metrics(agg[m]["cost"]) for m, _ in SYSTEMS}
def _p(model: str, panel: str, key: str) -> str:
src = metrics_all if panel == "all" else metrics_cost
return f"{src[model][key] * 100:.1f}"
lines.append(
r"\Cref{tab:overall} shows the same trade-off on both panels: the two"
r" LLM pipelines are more eager extractors, while \textsc{Harvey} is"
r" more conservative. Across all " + str(len(EVAL_FIELDS)) + r" evaluated"
r" fields \texttt{gpt-5.4-mini} and \texttt{gemini-3.1-flash-lite}"
r" reach accuracy when filled of "
+ _p("gpt", "all", "recall_when_filled") + r"\,\% and "
+ _p("gemini", "all", "recall_when_filled")
+ r"\,\%, alongside \textsc{Harvey} at "
+ _p("harvey", "all", "recall_when_filled") + r"\,\%, but the LLM"
r" pipelines pay for that recall with hallucination rates of "
+ _p("gpt", "all", "hallucination_rate") + r"\,\% and "
+ _p("gemini", "all", "hallucination_rate") + r"\,\% against \textsc{Harvey}'s "
+ _p("harvey", "all", "hallucination_rate") + r"\,\%."
r" Narrowing to the four cost-block variables, the three systems"
r" converge on accuracy ("
+ _p("harvey", "cost", "recall_when_filled") + r"--"
+ _p("gemini", "cost", "recall_when_filled") + r"\,\%), and the"
r" hallucination rates land at "
+ _p("gemini", "cost", "hallucination_rate") + r"\,\% (Gemini), "
+ _p("harvey", "cost", "hallucination_rate") + r"\,\% (Harvey), and "
+ _p("gpt", "cost", "hallucination_rate") + r"\,\% (GPT)."
r" No single system dominates: the LLM pipelines are preferable when"
r" the downstream task tolerates noisy extractions in exchange for"
r" coverage, whereas \textsc{Harvey} is preferable when emitted values"
r" must be trusted on the non-cost variables."
)
lines.append("")
acc_all = [metrics_all[m]["recall_when_filled"] for m, _ in SYSTEMS]
hal_all = [metrics_all[m]["hallucination_rate"] for m, _ in SYSTEMS]
acc_cost = [metrics_cost[m]["recall_when_filled"] for m, _ in SYSTEMS]
hal_cost = [metrics_cost[m]["hallucination_rate"] for m, _ in SYSTEMS]
acc_all_s = _bold_best(acc_all, _fmt_pct, True)
hal_all_s = _bold_best(hal_all, _fmt_pct, False)
acc_cost_s = _bold_best(acc_cost, _fmt_pct, True)
hal_cost_s = _bold_best(hal_cost, _fmt_pct, False)
lines.append(r"\begin{table}[h]")
lines.append(
r"\caption{Overall metrics on the "
+ str(len(EVALUATED_COUNTRIES))
+ r" head-to-head jurisdictions, golden-set rows with no"
r" expert-filled field excluded."
r" \emph{Acc.\ when filled} is the share of expert-filled cells the"
r" system extracts correctly; \emph{Hallu.\ rate} is the share of"
r" expert-empty cells where the system invented a value."
r" The right block restricts the same metrics to the four cost-block"
r" variables. Best per column in \textbf{bold} (lower is better for"
r" Hallu.\ rate)."
r"}"
)
lines.append(r"\label{tab:overall}")
lines.append(r"\centering\small")
lines.append(r"\begin{tabular}{@{}lrr@{\hskip 12pt}rr@{}}")
lines.append(r"\toprule")
lines.append(
r" & \multicolumn{2}{c}{All "
+ str(len(EVAL_FIELDS))
+ r" evaluated fields} & \multicolumn{2}{c}{Cost block ("
+ str(len(COST_BLOCK))
+ r" fields)} \\"
)
lines.append(r"\cmidrule(lr){2-3}\cmidrule(l){4-5}")
lines.append(
r"System & Acc.\ when filled & Hallu.\ rate"
r" & Acc.\ when filled & Hallu.\ rate \\"
)
lines.append(r"\midrule")
for i, (_, label) in enumerate(SYSTEMS):
lines.append(
f"{label} & {acc_all_s[i]} & {hal_all_s[i]}"
f" & {acc_cost_s[i]} & {hal_cost_s[i]} \\\\"
)
lines.append(r"\bottomrule")
lines.append(r"\end{tabular}")
lines.append(r"\end{table}")
lines.append("")
return "\n".join(lines)
def _print_console_summary(agg: dict[str, dict[str, dict[str, int]]]) -> None:
"""Quick human-readable echo so the user sees the numbers in the terminal too."""
print(f"{'system':<28} {'set':<5} {'Acc.filled':>11} {'Hallu':>6}")
for model, _ in SYSTEMS:
for tag in ("all", "cost"):
m = _metrics(agg[model][tag])
print(
f"{model:<28} {tag:<5} "
f"{m['recall_when_filled']:>11.1%} {m['hallucination_rate']:>6.1%}"
)
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 Quantitative Results section + headline table.",
)
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 section.",
)
args = parser.parse_args()
if not args.input.exists():
raise SystemExit(
f"{args.input} not found — run `legex-analysis` first to generate it."
)
agg = _aggregate(args.input)
tex = render_section(agg)
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)
if __name__ == "__main__":
main()