File size: 15,076 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""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_<system>.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_<cc>.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()