File size: 12,138 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
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
"""Validates and cleans the inference (Gemini, ChatGPT, Harvey) JSONL data.

We try to auto-recover values that do not match our model, else we review it by hand.
Every non-empty prediction cell is resolved to one of:

  * valid     — a good value already → kept,
  * recovered — a value parseable from prose (e.g. `20'000`→`20000`, `1.0\n\n…`→`1.0`)
                → canonicalised automatically (deterministic, score-neutral),
  * review    — non-empty but neither valid nor recoverable (refusal, prose with no
                value, misattribution, bad ISIC) → sent to the review XLSX for a human.

We perform this in two steps to allow for manual review.

  1. `legex-refusals-scan`  Write every review cell to a review XLSX.
  2. `legex-refusals-apply` Applies the decisions to the JSONL.

Traceability fields on every inference record show the original values:

* comment: one sentence per changed field, or null if none: "The <field> was sanitized from '<old>' to '<new>'."
  (removals use "empty (removed)" as the new value)
* original_input: JSON object mapping each changed field to its 1:1 original value, the string "{}" when nothing changed.

This is the same format as for the goldenset workbooks.
"""

import argparse
import json
import logging
import re
import sys
from collections import defaultdict
from pathlib import Path

import openpyxl

from legex.config import settings
from legex.evaluation.comparison import classify_cell, is_label_column, normalise, resolve
from legex.utils import goldenset_path, goldenset_sheet, read_inference_jsonl

log = logging.getLogger(__name__)

_INFERENCE_RE = re.compile(r"^Goldenset_.+_v\d+_(?:full_text|pdf)_(.+)\.jsonl$")
DEFAULT_XLSX = Path("data/analysis/quality/inference_data_review.xlsx")
CHANGELOG = Path("data/analysis/quality/inference_cleaning_changelog.jsonl")
_XLSX_HEADER = [
    "model", "country", "case_id", "field", "current_value", "reason",
    "gold_value", "before_bucket", "after_if_emptied", "corrected_value",
]


def format_comment(changes: dict[str, tuple[str, str]]) -> str | None:
    """Human note for changed fields (field -> (old, new)); None if nothing changed."""
    if not changes:
        return None
    return " ".join(
        f"The {field} was sanitized from '{old}' to "
        f"'{new if new else 'empty (removed)'}'."
        for field, (old, new) in changes.items()
    )


def format_original_input(changes: dict[str, tuple[str, str]]) -> str:
    """JSON of {field: original value} for changed fields; '{}' when none."""
    return json.dumps({f: old for f, (old, _) in changes.items()}, ensure_ascii=False) if changes else "{}"


def _inference_files(models: set[str] | None = None) -> list[Path]:
    """All inference JSONL files, optionally restricted to the given model models."""
    return sorted(
        p for p in settings.data_dir.glob("*/Goldenset_*_v*_*.jsonl")
        if _INFERENCE_RE.match(p.name)
        and (models is None or _model_slug(p) in models)
    )


def _model_slug(path: Path) -> str:
    return _INFERENCE_RE.match(path.name).group(1)


def _gold_labels(cc: str) -> dict[str, dict[str, str]]:
    """case_id -> {field: normalised gold value}, or {} if no goldenset."""
    gs = goldenset_path(cc)
    if not gs or not gs.exists():
        return {}
    ws = goldenset_sheet(openpyxl.load_workbook(gs, read_only=True, data_only=True))
    rows = ws.iter_rows(values_only=True)
    header = [str(c) if c is not None else "" for c in next(rows)]
    ci = header.index("case_id")
    out: dict[str, dict[str, str]] = {}
    for row in rows:
        if row[ci] in (None, ""):
            continue
        cells = dict(zip(header, row))
        out[str(row[ci]).strip()] = {c: normalise(cells.get(c)) for c in header if is_label_column(c)}
    return out


def scan(
    out: Path = DEFAULT_XLSX,
    models: set[str] | None = None,
    conflicts: Path | None = None,
) -> int:
    """Write every `review` cell across the inference JSONL to a review XLSX.
    """
    gold_cache: dict[str, dict] = {}
    rows_out: list[list] = []
    seen_cells: set[tuple[str, str, str, str]] = set()
    for path in _inference_files(models):
        cc = path.parent.name
        model = _model_slug(path)
        gold = gold_cache.setdefault(cc, _gold_labels(cc))
        for rec in read_inference_jsonl(path):
            cid = (rec.get("case_id") or "").strip()
            for field, value in rec.items():
                if not is_label_column(field):
                    continue
                status, _canon, reason = resolve(value, field)
                if status != "review":
                    continue
                gv = gold.get(cid, {}).get(field, "")
                rows_out.append([
                    model, cc, cid, field, str(value), reason, gv,
                    classify_cell(gv, normalise(value), field),
                    classify_cell(gv, "", field), "",
                ])
                seen_cells.add((model, cc, cid, field))
    if conflicts is not None and conflicts.exists():
        with open(conflicts, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                c = json.loads(line)
                model, cc, cid, field = c["model"], c["country"], c["case_id"], c["field"]
                if models is not None and model not in models:
                    continue
                if (model, cc, cid, field) in seen_cells:
                    continue  # already flagged by resolve(); one row per cell
                gold = gold_cache.setdefault(cc, _gold_labels(cc))
                gv = gold.get(cid, {}).get(field, "")
                kept = c["kept"]
                rows_out.append([
                    model, cc, cid, field, kept,
                    f"duplicate-run conflict; alternative: '{c['alternative']}'", gv,
                    classify_cell(gv, normalise(kept), field),
                    classify_cell(gv, "", field), kept,
                ])
    rows_out.sort(key=lambda r: (r[0], r[5], r[1], r[2]))
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "review"
    ws.append(_XLSX_HEADER)
    for r in rows_out:
        ws.append(r)
    out.parent.mkdir(parents=True, exist_ok=True)
    wb.save(out)
    log.info(f"flagged {len(rows_out)} cell(s) for review -> {out}")
    return len(rows_out)


def _load_review(xlsx: Path) -> dict[tuple[str, str], dict[str, dict[str, str]]]:
    """Reviewed XLSX -> {(model, country): {case_id: {field: corrected_value}}}.

    corrected_value is "" when the reviewer left it blank (⇒ empty the cell)."""
    ws = openpyxl.load_workbook(xlsx, read_only=True).active
    rows = ws.iter_rows(values_only=True)
    hdr = list(next(rows))
    mi, ci, ii, fi, cv = (hdr.index(x) for x in
                          ("model", "country", "case_id", "field", "corrected_value"))
    out: dict[tuple[str, str], dict[str, dict[str, str]]] = defaultdict(lambda: defaultdict(dict))
    for r in rows:
        if r[mi] is None:
            continue
        out[(str(r[mi]), str(r[ci]))][str(r[ii])][str(r[fi])] = "" if r[cv] is None else str(r[cv])
    return out


def apply(xlsx: Path = DEFAULT_XLSX, models: set[str] | None = None) -> None:
    """Auto-canonicalise recovered cells, apply reviewed decisions, stamp provenance.
    """
    reviewed = _load_review(xlsx) if xlsx.exists() else {}
    log_rows: list[list[str]] = []
    n_recovered = n_reviewed = 0
    for path in _inference_files(models):
        cc, model = path.parent.name, _model_slug(path)
        decisions = reviewed.get((model, cc), {})
        records = read_inference_jsonl(path)
        for rec in records:
            cid = (rec.get("case_id") or "").strip()
            try:
                prev_orig = json.loads(rec.get("original_input") or "{}")
            except (ValueError, TypeError):
                prev_orig = {}
            row_decisions = decisions.get(cid, {})
            changes: dict[str, tuple[str, str]] = {}
            for field in list(rec):
                if not is_label_column(field):
                    continue
                raw = prev_orig[field] if field in prev_orig else rec.get(field)  # true original
                if raw in (None, ""):
                    rec[field] = None
                    continue
                if field in row_decisions:                         # human decision
                    new = row_decisions[field]
                    rec[field] = new or None
                    if str(raw) != (new or ""):
                        changes[field] = (str(raw), new)
                        n_reviewed += 1
                    continue
                status, canon, _ = resolve(raw, field)             # auto path
                if status == "recovered":
                    rec[field] = canon
                    if str(raw) != canon:
                        changes[field] = (str(raw), canon)
                        n_recovered += 1
                else:
                    rec[field] = raw                               # valid / undecided review → keep
            rec.pop("comment", None)
            rec.pop("original_input", None)
            rec["comment"] = format_comment(changes)
            rec["original_input"] = format_original_input(changes)
            for f, (old, new) in changes.items():
                log_rows.append({
                    "model": model, "country": cc, "case_id": cid, "field": f,
                    "before": old, "after": new,
                    "kind": "reviewed" if f in row_decisions else "recovered",
                })
        with open(path, "w", encoding="utf-8") as fh:
            for rec in records:
                fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
    if models is not None and CHANGELOG.exists():  # keep other models' history
        with open(CHANGELOG, encoding="utf-8") as f:
            log_rows.extend(
                row for row in map(json.loads, filter(str.strip, f))
                if row.get("model") not in models
            )
    log_rows.sort(key=lambda r: (r["model"], r["country"], r["case_id"], r["field"]))
    CHANGELOG.parent.mkdir(parents=True, exist_ok=True)
    with open(CHANGELOG, "w", encoding="utf-8") as f:
        for row in log_rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")
    log.info(f"cleaning applied: {n_recovered} recovered, {n_reviewed} reviewed; "
             f"{len(log_rows)} changes -> {CHANGELOG}")


def _basic_logging() -> None:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.StreamHandler(sys.stderr)],
    )


def scan_main() -> None:
    _basic_logging()
    parser = argparse.ArgumentParser(
        prog="legex-refusals-scan",
        description="Flag inference cells that need human review (not auto-recoverable).",
    )
    parser.add_argument("--out", type=Path, default=DEFAULT_XLSX)
    parser.add_argument(
        "--model", action="append", dest="models", metavar="SLUG",
        help="Restrict to this model slug (repeatable). Default: all models.",
    )
    parser.add_argument(
        "--conflicts", type=Path, default=None,
        help="Duplicate-run conflict sidecar (JSONL) to fold into the workbook.",
    )
    args = parser.parse_args()
    scan(args.out, set(args.models) if args.models else None, args.conflicts)


def apply_main() -> None:
    _basic_logging()
    parser = argparse.ArgumentParser(
        prog="legex-refusals-apply",
        description="Canonicalise recoverable values, apply reviewed decisions, stamp provenance.",
    )
    parser.add_argument("--xlsx", type=Path, default=DEFAULT_XLSX)
    parser.add_argument(
        "--model", action="append", dest="models", metavar="SLUG",
        help="Restrict to this model slug (repeatable); other models keep their "
             "files and changelog history. Default: all models.",
    )
    args = parser.parse_args()
    apply(args.xlsx, set(args.models) if args.models else None)


if __name__ == "__main__":
    scan()