File size: 10,399 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
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
"""Compare the two Legora runs (legora-1 vs legora-2) in structure and performance.

The 2026-08-01 Legora export carried the full question set twice; the ingest
stores the left group as ``legora-1`` and the right group as ``legora-2``.
This script contrasts the two runs — coverage, per-field fill rates, inter-run
agreement, accuracy against the Goldensets, and example disagreements — and
writes a markdown report.

    uv run python scripts/compare_legora_runs.py \
        [--out data/analysis/legora_run_comparison.md]

Run it after `legex-refusals-apply` so the report reflects the cleaned data.
"""

import argparse
import sys
from collections import Counter, defaultdict
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from legex import published  # noqa: E402
from legex.config import settings  # noqa: E402
from legex.evaluation.comparison import (  # noqa: E402
    derived,
    normalise,
    values_agree,
)
from legex.evaluation.scoring import _read_goldenset_rows, score_country  # noqa: E402
from legex.legora import LEGORA_FIELDS  # noqa: E402
from legex.utils import inference_path, read_inference_jsonl  # noqa: E402

MODEL_A, MODEL_B = "legora-1", "legora-2"
FIELDS = tuple(f for f in LEGORA_FIELDS if f != "case_id")
DEFAULT_OUT = Path("data/analysis/legora_run_comparison.md")
MAX_EXAMPLES_PER_FIELD = 3


def _inference_file(cc: str, prompt_version: str, source: str, model: str,
                    inference_dir: Path | None) -> Path:
    if inference_dir is not None:
        return published.inference_file(inference_dir, cc, model)
    return inference_path(cc, prompt_version, source, model)


def _ccs(prompt_version: str, source: str, inference_dir: Path | None) -> list[str]:
    root = inference_dir if inference_dir is not None else settings.data_dir
    out = []
    for d in sorted(Path(root).iterdir()):
        if not d.is_dir():
            continue
        cc = d.name
        if all(_inference_file(cc, prompt_version, source, m, inference_dir).exists()
               for m in (MODEL_A, MODEL_B)):
            out.append(cc)
    return out


def _by_case(cc: str, prompt_version: str, source: str, model: str,
             inference_dir: Path | None) -> dict[str, dict]:
    rows = read_inference_jsonl(_inference_file(cc, prompt_version, source, model, inference_dir))
    return {str(r.get("case_id")): r for r in rows if r.get("case_id")}


def _pct(num: int, den: int) -> str:
    return f"{100 * num / den:.1f}%" if den else "–"


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--prompt_version", default="v3")
    parser.add_argument("--source", choices=("full_text", "pdf"), default="full_text")
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    parser.add_argument("--gold-dir", type=Path, default=None,
                        help="published goldenset data directory (XLSX workbooks otherwise)")
    parser.add_argument("--inference-dir", type=Path, default=None,
                        help="published inference data directory (working files otherwise)")
    args = parser.parse_args()

    ccs = _ccs(args.prompt_version, args.source, args.inference_dir)
    if not ccs:
        raise SystemExit("no country has both legora-1 and legora-2 files")

    # ---- collect ------------------------------------------------------------
    coverage_rows: list[tuple[str, int, int, int]] = []          # cc, n_a, n_b, overlap
    fill = {m: Counter() for m in (MODEL_A, MODEL_B)}            # field -> filled
    n_pairs = Counter()                                          # field -> paired rows
    identical = Counter()                                        # field -> normalised equal
    tolerant = Counter()                                         # field -> values_agree
    both_filled = Counter()
    both_filled_agree = Counter()
    only_a = Counter()
    only_b = Counter()
    examples: dict[str, list[tuple[str, str, str, str, str]]] = defaultdict(list)
    inference_dates = set()

    for cc in ccs:
        a = _by_case(cc, args.prompt_version, args.source, MODEL_A, args.inference_dir)
        b = _by_case(cc, args.prompt_version, args.source, MODEL_B, args.inference_dir)
        shared = sorted(set(a) & set(b))
        coverage_rows.append((cc, len(a), len(b), len(shared)))
        gold_lookup: dict[str, dict[str, str]] = {}
        if shared:
            if args.gold_dir is not None:
                _, gold_lookup = published.load_gold_labels(args.gold_dir, cc)
            else:
                _, gold_lookup = _read_goldenset_rows(cc)
        for cid in shared:
            ra, rb = a[cid], b[cid]
            inference_dates.update(filter(None, (ra.get("inference_date"), rb.get("inference_date"))))
            for field in FIELDS:
                va, vb = normalise(ra.get(field)), normalise(rb.get(field))
                n_pairs[field] += 1
                fill[MODEL_A][field] += bool(va)
                fill[MODEL_B][field] += bool(vb)
                if va and not vb:
                    only_a[field] += 1
                if vb and not va:
                    only_b[field] += 1
                if va == vb:
                    identical[field] += 1
                if values_agree(va, vb, field):
                    tolerant[field] += 1
                if va and vb:
                    both_filled[field] += 1
                    if values_agree(va, vb, field):
                        both_filled_agree[field] += 1
                    elif len(examples[field]) < MAX_EXAMPLES_PER_FIELD:
                        gv = gold_lookup.get(normalise(cid), {}).get(field, "")
                        examples[field].append((cc, cid, va, vb, gv))

    # ---- vs gold ------------------------------------------------------------
    counters = {m: {f: Counter() for f in FIELDS} for m in (MODEL_A, MODEL_B)}
    per_cc_acc: dict[str, dict[str, tuple[int, int]]] = defaultdict(dict)  # cc -> model -> (correct, n)
    for cc in ccs:
        for m in (MODEL_A, MODEL_B):
            scored = score_country(cc, args.prompt_version, args.source, m, verbose=False,
                                   gold_dir=args.gold_dir, inference_dir=args.inference_dir)
            if scored is None:
                continue
            col_counters, _stats = scored
            correct = n = 0
            for field in FIELDS:
                c = col_counters.get(field)
                if c is None:
                    continue
                counters[m][field].update(c)
                correct += c["tp"] + c["tn"]
                n += sum(c.values())
            per_cc_acc[cc][m] = (correct, n)

    # ---- render -------------------------------------------------------------
    lines: list[str] = []
    w = lines.append
    dates = ", ".join(sorted(inference_dates)) or "unknown"
    w("# Legora run comparison: legora-1 vs legora-2")
    w("")
    w(f"The 2026-08-01 Legora tabular-review export (`data/raw/legora_2026-08-01.xlsx`, "
      f"inference_date {dates}) contains the question set twice; `legora-1` is the left "
      f"column group, `legora-2` the right one. Generated by `scripts/compare_legora_runs.py`.")
    w("")

    w("## Coverage per country")
    w("")
    w("| cc | legora-1 rows | legora-2 rows | shared |")
    w("|---|---|---|---|")
    for cc, na, nb, sh in coverage_rows:
        w(f"| {cc} | {na} | {nb} | {sh} |")
    total_a = sum(r[1] for r in coverage_rows)
    total_b = sum(r[2] for r in coverage_rows)
    total_s = sum(r[3] for r in coverage_rows)
    w(f"| **total** | **{total_a}** | **{total_b}** | **{total_s}** |")
    w("")

    w("## Per-field fill rates and inter-run agreement")
    w("")
    w("Agreement uses the evaluation's tolerant comparator (`values_agree`); "
      "*identical* is exact string equality after normalisation. *only 1/only 2* "
      "count cells filled by one run and empty in the other.")
    w("")
    w("| field | filled 1 | filled 2 | identical | agree (tolerant) | agree when both filled | only 1 | only 2 |")
    w("|---|---|---|---|---|---|---|---|")
    for f in FIELDS:
        n = n_pairs[f]
        w(f"| {f} | {_pct(fill[MODEL_A][f], n)} | {_pct(fill[MODEL_B][f], n)} "
          f"| {_pct(identical[f], n)} | {_pct(tolerant[f], n)} "
          f"| {_pct(both_filled_agree[f], both_filled[f])} "
          f"| {only_a[f]} | {only_b[f]} |")
    w("")

    w("## Accuracy against the Goldensets")
    w("")
    w("Cell buckets from the standard scoring (`classify_cell`): accuracy = (tp+tn)/n, "
      "precision/recall/F1 as in the analysis pipeline.")
    w("")
    w("| field | acc 1 | acc 2 | Δ acc | F1 1 | F1 2 | recall 1 | recall 2 |")
    w("|---|---|---|---|---|---|---|---|")
    for f in FIELDS:
        accs = {}
        stats = {}
        for m in (MODEL_A, MODEL_B):
            c = counters[m][f]
            n = sum(c.values())
            accs[m] = (c["tp"] + c["tn"]) / n if n else 0.0
            stats[m] = derived(c)
        w(f"| {f} | {accs[MODEL_A]:.3f} | {accs[MODEL_B]:.3f} "
          f"| {accs[MODEL_B] - accs[MODEL_A]:+.3f} "
          f"| {stats[MODEL_A][2]:.3f} | {stats[MODEL_B][2]:.3f} "
          f"| {stats[MODEL_A][1]:.3f} | {stats[MODEL_B][1]:.3f} |")
    w("")

    w("### Per-country accuracy (all fields pooled)")
    w("")
    w("| cc | acc legora-1 | acc legora-2 | Δ |")
    w("|---|---|---|---|")
    for cc in ccs:
        accs = {}
        for m in (MODEL_A, MODEL_B):
            correct, n = per_cc_acc.get(cc, {}).get(m, (0, 0))
            accs[m] = correct / n if n else 0.0
        w(f"| {cc} | {accs[MODEL_A]:.3f} | {accs[MODEL_B]:.3f} | {accs[MODEL_B] - accs[MODEL_A]:+.3f} |")
    w("")

    w("## Example disagreements (both runs filled, values differ)")
    w("")
    w("| field | cc | case_id | legora-1 | legora-2 | gold |")
    w("|---|---|---|---|---|---|")
    def _md(s: str) -> str:
        return s.replace("|", "\\|").replace("\n", " ")[:80]
    for f in FIELDS:
        for cc, cid, va, vb, gv in examples[f]:
            w(f"| {f} | {cc} | {_md(cid)} | {_md(va)} | {_md(vb)} | {_md(gv)} |")
    w("")

    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text("\n".join(lines), encoding="utf-8")
    print(f"wrote {args.out} ({len(ccs)} countries, {total_s} shared rows)")


if __name__ == "__main__":
    main()