File size: 8,947 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
243
244
245
246
247
248
249
250
251
252
253
254
255
"""Compare Goldenset gold labels against inference output.

Reads each country's gold labels — from ``Goldenset_*.xlsx`` (the maintainers'
workbooks) or, with ``--gold-dir``, from the published goldenset JSONL — and
the matching predictions JSONL, then reports per-field agreement.
"""

import argparse
import logging
import sys
from pathlib import Path

from openpyxl import load_workbook

from legex import published
from legex.evaluation.comparison import (
    BUCKETS,
    classify_cell,
    derived,
    is_label_column,
    normalise,
)
from legex.inference import inference_output_path
from legex.utils import (
    countries_with_goldenset,
    goldenset_path,
    goldenset_sheet,
    read_inference_jsonl,
)

log = logging.getLogger(__name__)


def _read_goldenset_rows(cc: str) -> tuple[list[str], dict[str, dict[str, str]]]:
    """Return (label_columns, rows_by_case_id) for a country's Goldenset."""
    wb = load_workbook(goldenset_path(cc), read_only=True, data_only=True)
    ws = goldenset_sheet(wb)
    rows = ws.iter_rows(values_only=True)
    header = [str(c) if c is not None else "" for c in next(rows)]
    if "case_id" not in header:
        raise ValueError(f"{goldenset_path(cc)} GOLDENSET sheet missing case_id column")
    label_columns = [h for h in header if is_label_column(h)]

    by_id: dict[str, dict[str, str]] = {}
    for row in rows:
        if not any(row):
            continue
        cells = dict(zip(header, row))
        case_id = normalise(cells.get("case_id"))
        if not case_id:
            continue
        labels = {col: normalise(cells.get(col)) for col in label_columns}
        if not any(labels.values()):
            continue
        by_id[case_id] = labels
    return label_columns, by_id


def _read_predictions(path: Path) -> dict[str, dict[str, str]]:
    by_id: dict[str, dict[str, str]] = {}
    for row in read_inference_jsonl(path):
        case_id = normalise(row.get("case_id"))
        if not case_id:
            continue
        # Rows whose inference failed are treated like absent inference
        if normalise(row.get("error")):
            continue
        labels = {k: normalise(v) for k, v in row.items() if is_label_column(k)}
        if not any(labels.values()):
            continue
        by_id[case_id] = {k: normalise(v) for k, v in row.items()}
    return by_id


def _coverage(
    gold: dict[str, dict[str, str]], preds: dict[str, dict[str, str]]
) -> dict[str, int]:
    gold_ids, pred_ids = set(gold), set(preds)
    return {
        "gold": len(gold_ids),
        "pred": len(pred_ids),
        "overlap": len(gold_ids & pred_ids),
        "missing": len(gold_ids - pred_ids),
        "extra": len(pred_ids - gold_ids),
    }


def score_country(
    cc: str,
    prompt_version: str,
    source: str,
    model: str,
    verbose: bool = True,
    *,
    gold_dir: Path | None = None,
    inference_dir: Path | None = None,
) -> tuple[dict[str, dict[str, int]], dict[str, int]] | None:
    """Return (per-column counters, case coverage stats).

    ``gold_dir`` / ``inference_dir`` switch the respective input to the
    published JSONL bundles (see ``legex.published``); by default the
    maintainers' XLSX workbooks and working inference files are read.
    """
    pred_path = (
        published.inference_file(inference_dir, cc, model)
        if inference_dir is not None
        else inference_output_path(cc, prompt_version, source, model)
    )
    if not pred_path.exists():
        if verbose:
            log.warning(f"[{cc}] missing predictions {pred_path}, skipping")
        return None
    gold_path = published.gold_file(gold_dir, cc) if gold_dir is not None else goldenset_path(cc)
    if not gold_path.exists():
        if verbose:
            log.warning(f"[{cc}] missing goldenset {gold_path}, skipping")
        return None

    if gold_dir is not None:
        label_columns, gold = published.load_gold_labels(gold_dir, cc)
    else:
        label_columns, gold = _read_goldenset_rows(cc)
    preds = _read_predictions(pred_path)
    stats = _coverage(gold, preds)

    counters: dict[str, dict[str, int]] = {col: {b: 0 for b in BUCKETS} for col in label_columns}
    if verbose:
        print()
        log.info(
            f"[{cc}] gold={stats['gold']} pred={stats['pred']} overlap={stats['overlap']} "
            f"missing={stats['missing']} extra={stats['extra']}"
        )

    for case_id in (cid for cid in gold if cid in preds):
        g, p = gold[case_id], preds[case_id]
        for col in label_columns:
            counters[col][classify_cell(g.get(col, ""), p.get(col, ""), col)] += 1
    return counters, stats


def _print_report(
    cc: str, counters: dict[str, dict[str, int]], coverage: dict[str, int] | None = None
) -> None:
    name_width = max(max((len(c) for c in counters), default=0), len("column"))
    print(f"=== {cc} ===")
    if coverage is not None:
        print(
            f"cases: gold={coverage['gold']} pred={coverage['pred']} "
            f"overlap={coverage['overlap']} missing={coverage['missing']} "
            f"extra={coverage['extra']}"
        )
    print(
        f"{'column'.ljust(name_width)}  "
        f"{'TP':>5}  {'Mism':>5}  {'Miss':>5}  {'Hallu':>5}  {'TN':>5}  "
        f"{'P':>7}  {'R':>7}  {'F1':>5}"
    )
    for col, c in counters.items():
        p, r, f1 = derived(c)
        f1_s = f"{f1:.2f}" if (p + r) else "   - "
        print(
            f"{col.ljust(name_width)}  "
            f"{c['tp']:>5}  {c['mismatch']:>5}  {c['missed']:>5}  "
            f"{c['hallucinated']:>5}  {c['tn']:>5}  "
            f"{p:>7.2%}  {r:>7.2%}  {f1_s:>5}"
        )


def evaluate(
    countries: list[str] | None,
    model: str,
    prompt_version: str,
    source: str,
    gold_dir: Path | None = None,
    inference_dir: Path | None = None,
) -> None:
    overall: dict[str, dict[str, int]] = {
        col: {b: 0 for b in BUCKETS} for col in published.LABEL_FIELDS
    }
    overall_coverage = {"gold": 0, "pred": 0, "overlap": 0, "missing": 0, "extra": 0}

    if countries is None:
        countries = (
            published.countries_with_gold(gold_dir)
            if gold_dir is not None
            else countries_with_goldenset()
        )
    seen_any = False
    for cc in countries:
        result = score_country(
            cc, prompt_version, source, model,
            gold_dir=gold_dir, inference_dir=inference_dir,
        )
        if result is None:
            continue
        counters, coverage = result
        seen_any = True
        _print_report(cc, counters, coverage)
        for key in overall_coverage:
            overall_coverage[key] += coverage[key]
        for col, c in counters.items():
            overall.setdefault(col, {b: 0 for b in BUCKETS})
            for b in BUCKETS:
                overall[col][b] += c[b]

    if seen_any:
        _print_report("ALL", overall, overall_coverage)


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-evaluate",
        description="Compare Goldenset labels against LLM inference output.",
    )
    parser.add_argument(
        "--country", action="extend", nargs="+", dest="countries",
        help="Country code(s). Repeatable and/or space-separated. Defaults to all with a Goldenset.",
    )
    parser.add_argument(
        "--model", required=True,
        help="Model id of the predictions to evaluate (must match the classify run).",
    )
    parser.add_argument("--prompt_version", default="v3", help="Prompt version (default: v3).")
    parser.add_argument(
        "--gold-dir", type=Path, default=None,
        help="Read gold labels from published goldenset JSONL under this directory "
             "instead of the XLSX workbooks.",
    )
    parser.add_argument(
        "--inference-dir", type=Path, default=None,
        help="Read predictions from published inference JSONL under this directory "
             "instead of the working files.",
    )
    source = parser.add_mutually_exclusive_group()
    source.add_argument("--full_text", dest="source", action="store_const", const="full_text",
                        help="Evaluate predictions made from the full_text column.")
    source.add_argument("--pdf", dest="source", action="store_const", const="pdf",
                        help="Evaluate predictions made from PDFs.")
    args = parser.parse_args()
    if args.inference_dir is None and args.source is None:
        parser.error("one of --full_text / --pdf is required (unless --inference-dir is used)")
    evaluate(
        countries=args.countries, model=args.model,
        prompt_version=args.prompt_version, source=args.source,
        gold_dir=args.gold_dir, inference_dir=args.inference_dir,
    )


if __name__ == "__main__":
    main()