| """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", |
| ) |
|
|
| |
| 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): |
| 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: 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(): |
| 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() |
|
|