File size: 11,010 Bytes
6f5156a | 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | """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()
|