File size: 10,411 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
"""Ingest Legora tabular-review extractions from a single xlsx into per-country JSONL.
"""

import argparse
import html
import json
import logging
import re
import sys
from collections import defaultdict
from csv import DictReader
from datetime import date, datetime
from pathlib import Path

from openpyxl import load_workbook

from legex.config import settings
from legex.harvey import _gold_case_id_index
from legex.inference import _output_columns
from legex.utils import inference_path, norm_case_id, write_inference_jsonl

log = logging.getLogger(__name__)

LEGORA_FIELDS: tuple[str, ...] = (
    "case_id",
    "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",
)

# n-th occurrence of the field headers gives run name
GROUP_MODELS: dict[int, str] = {1: "legora-1", 2: "legora-2"}

CONFLICTS_PATH = Path("data/analysis/quality/legora_duplicate_conflicts.jsonl")
_EMPTY_LITERALS = {"", "—"}
_DATE_IN_NAME_RE = re.compile(r"(\d{4}-\d{2}-\d{2})")


def loose_name(s: str) -> str:
    """Filename key tolerant of separator mangling: unescape HTML entities,
    lowercase, collapse every non-alphanumeric run to one underscore."""
    return re.sub(r"[^0-9a-zà-￿]+", "_", html.unescape(str(s)).lower()).strip("_")


def tight_name(s: str) -> str:
    """Last-resort filename key: drop every non-alphanumeric character, so
    names differing only in punctuation placement compare equal."""
    return re.sub(r"[^0-9a-zà-￿]", "", html.unescape(str(s)).lower())


def load_manifest(csv_path: Path) -> dict[str, dict[str, tuple[str, str]]]:
    """Bundle manifest -> {"exact"|"loose"|"tight": {key: (cc, case_id)}}.
    """
    lookups: dict[str, dict[str, tuple[str, str]]] = {"exact": {}, "loose": {}, "tight": {}}
    ambiguous: dict[str, set[str]] = {"exact": set(), "loose": set(), "tight": set()}
    with open(csv_path, encoding="utf-8") as f:
        for rec in DictReader(f):
            target = (rec["cc"], rec["case_id"])
            for pass_, key in (
                ("exact", rec["file"]),
                ("loose", loose_name(rec["file"])),
                ("tight", tight_name(rec["file"])),
            ):
                table = lookups[pass_]
                if key in table and table[key] != target:
                    ambiguous[pass_].add(key)
                table.setdefault(key, target)
    for pass_, keys in ambiguous.items():
        for key in keys:
            del lookups[pass_][key]
        if keys:
            log.warning(f"manifest: dropped {len(keys)} ambiguous {pass_} key(s)")
    return lookups


def match_document(name: str, lookups: dict[str, dict[str, tuple[str, str]]]) -> tuple[str, str] | None:
    """(cc, case_id) for an exported document name, or None (junk/unknown)."""
    return (
        lookups["exact"].get(str(name))
        or lookups["loose"].get(loose_name(name))
        or lookups["tight"].get(tight_name(name))
    )


def _group_value_columns(header: list[str]) -> dict[int, dict[str, int]]:
    """{group -> {field -> column index}} from the header row.
    """
    occurrences: dict[str, list[int]] = defaultdict(list)
    for idx, cell in enumerate(header):
        name = str(cell).strip() if cell is not None else ""
        if name in LEGORA_FIELDS:
            occurrences[name].append(idx)
    counts = {f: len(occurrences[f]) for f in LEGORA_FIELDS}
    n_groups = min(counts.values())
    if n_groups < 1:
        missing = [f for f, n in counts.items() if n == 0]
        raise ValueError(f"export header is missing field column(s): {missing}")
    if len(set(counts.values())) != 1:
        raise ValueError(f"unbalanced field-column groups: {counts}")
    return {
        g: {f: occurrences[f][g - 1] for f in LEGORA_FIELDS}
        for g in range(1, n_groups + 1)
    }


def _clean(value: object) -> str:
    """Format-level canonicalisation of one cell (no value-level cleaning)."""
    if value is None:
        return ""
    if isinstance(value, datetime):  # Excel date cells arrive as datetimes
        return value.date().isoformat()
    if isinstance(value, date):
        return value.isoformat()
    if isinstance(value, float) and value.is_integer():
        return str(int(value))
    s = str(value).strip()
    if s in _EMPTY_LITERALS:
        return ""
    if s.lower() == "nonpecuniary":
        return "nonpecuniary"
    return s


def _infer_date_from_name(xlsx: Path) -> str | None:
    m = _DATE_IN_NAME_RE.search(xlsx.name)
    return m.group(1) if m else None


def ingest(
    xlsx: Path,
    manifest_csv: Path,
    prompt_version: str = "v3",
    source: str = "full_text",
    inference_date: str | None = None,
    conflicts_out: Path = CONFLICTS_PATH,
) -> None:
    inference_date = inference_date or _infer_date_from_name(xlsx)
    if not inference_date:
        raise ValueError(f"cannot derive inference date from {xlsx.name}; pass --inference_date")

    columns = _output_columns()
    columns.insert(columns.index("model") + 1, "inference_date")

    lookups = load_manifest(manifest_csv)
    wb = load_workbook(xlsx, read_only=True, data_only=True)
    if "Sheet1" not in wb.sheetnames:
        raise ValueError(f"{xlsx} missing Sheet1 (found {wb.sheetnames})")
    ws = wb["Sheet1"]
    rows_iter = ws.iter_rows(values_only=True)
    header = [c for c in next(rows_iter)]
    group_cols = _group_value_columns(header)

    # by_cc[model][cc] -> case_id -> {field: cleaned value}; export order kept.
    by_cc: dict[str, dict[str, dict[str, dict[str, str]]]] = {
        model: defaultdict(dict) for model in GROUP_MODELS.values()
    }
    conflicts: list[dict] = []
    unmatched: list[str] = []
    for row in rows_iter:
        if not row or row[0] is None:
            continue
        name = str(row[0])
        target = match_document(name, lookups)
        if target is None:
            unmatched.append(name)
            log.info(f"no manifest match for {name!r}, skipping")
            continue
        cc, case_id = target
        for group, model in GROUP_MODELS.items():
            values = {
                field: _clean(row[idx]) if idx < len(row) else ""
                for field, idx in group_cols[group].items()
                if field != "case_id"
            }
            seen = by_cc[model][cc].get(case_id)
            if seen is None:
                by_cc[model][cc][case_id] = values
                continue
            for field, alt in values.items():  # duplicate run of the same document
                if seen[field] != alt:
                    conflicts.append({
                        "model": model, "country": cc, "case_id": case_id,
                        "field": field, "kept": seen[field], "alternative": alt,
                    })
    if unmatched:
        log.warning(f"{len(unmatched)} document(s) had no manifest match: {unmatched[:5]} …")

    gold_indices = {
        cc: _gold_case_id_index(cc)
        for model_rows in by_cc.values()
        for cc in model_rows
    }
    for model, model_rows in by_cc.items():
        for cc, cases in sorted(model_rows.items()):
            index = gold_indices[cc]
            if index is None:
                log.info(f"[{cc}] no Goldenset on disk, skipping {len(cases)} Legora row(s)")
                continue
            out = inference_path(cc, prompt_version, source, model)
            out_rows: list[dict] = []
            dropped = 0
            for case_id, values in cases.items():
                gold = index.get(norm_case_id(case_id))
                if gold is None:
                    dropped += 1
                    log.info(f"[{cc}] manifest case_id {case_id!r} not in Goldenset, skipping")
                    continue
                out_row = {col: "" for col in columns}
                out_row["case_id"] = gold
                out_row["model"] = model
                out_row["inference_date"] = inference_date
                out_row.update(values)
                out_rows.append(out_row)
            write_inference_jsonl(out, out_rows, columns)
            log.info(f"[{cc}] wrote {len(out_rows)} {model} row(s) → {out} ({dropped} dropped)")

    conflicts.sort(key=lambda c: (c["model"], c["country"], c["case_id"], c["field"]))
    conflicts_out.parent.mkdir(parents=True, exist_ok=True)
    with open(conflicts_out, "w", encoding="utf-8") as f:
        for c in conflicts:
            f.write(json.dumps(c, ensure_ascii=False) + "\n")
    log.info(f"{len(conflicts)} duplicate-run conflict(s) -> {conflicts_out}")


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-legora-ingest",
        description="Convert a Legora tabular-review export into per-country Goldenset_*_legora-{1,2}.jsonl files.",
    )
    parser.add_argument(
        "--xlsx",
        type=Path,
        default=settings.raw_dir / "legora_2026-08-01.xlsx",
        help="Path to the Legora export xlsx (default: data/raw/legora_2026-08-01.xlsx).",
    )
    parser.add_argument(
        "--manifest",
        type=Path,
        default=settings.raw_dir / "legora_bundle_manifest.csv",
        help="Bundle manifest mapping filenames to (country, case_id).",
    )
    parser.add_argument("--prompt_version", default="v3")
    parser.add_argument(
        "--source",
        choices=("full_text", "pdf"),
        default="full_text",
        help="Source bucket label used in the output filename (default: full_text).",
    )
    parser.add_argument(
        "--inference_date",
        default=None,
        help="ISO date the vendor ran the extraction (default: parsed from the xlsx filename).",
    )
    parser.add_argument("--conflicts", type=Path, default=CONFLICTS_PATH)
    args = parser.parse_args()
    ingest(
        xlsx=args.xlsx,
        manifest_csv=args.manifest,
        prompt_version=args.prompt_version,
        source=args.source,
        inference_date=args.inference_date,
        conflicts_out=args.conflicts,
    )


if __name__ == "__main__":
    main()