"""Legora ingest: filename matching, header groups, dedup, and the end-to-end write.""" import json from datetime import datetime from pathlib import Path import pytest from openpyxl import Workbook from legex.config import settings from legex.legora import ( GROUP_MODELS, LEGORA_FIELDS, _clean, _group_value_columns, _infer_date_from_name, ingest, load_manifest, loose_name, match_document, tight_name, ) FIELDS = [f for f in LEGORA_FIELDS if f != "case_id"] GOLD_HEADER = ["case_id", "link", "full_text", *FIELDS, "Currency_dispute_value_nominal"] @pytest.mark.parametrize( "raw,expected", [ ("A.C._No._14000_[Formerly_CBD].pdf", "a_c_no_14000_formerly_cbd_pdf"), ("G.R.Nos._274778,_275405&_276233.pdf", "g_r_nos_274778_275405_276233_pdf"), ("最高法院_115_年度.txt", "最高法院_115_年度_txt"), ], ) def test_loose_name(raw, expected): assert loose_name(raw) == expected def test_tight_name_drops_all_separators(): # Harvey drops the ",_" between id segments, joining "…4" and "3.19…" into # "43.19…"; loose keeps a separator there, so only the tight pass matches. bundle, mangled = "Rev_18654_3.19.1.4,_3.19.1.3_rev.pdf", "Rev_18654_3.19.1.43.19.1.3_rev.pdf" assert tight_name(bundle) == tight_name(mangled) assert loose_name(bundle) != loose_name(mangled) def test_infer_date_from_name(): assert _infer_date_from_name(Path("legora_2026-08-01.xlsx")) == "2026-08-01" assert _infer_date_from_name(Path("legora.xlsx")) is None @pytest.mark.parametrize( "value,expected", [ (None, ""), ("—", ""), (" 1 ", "1"), (datetime(2025, 5, 26), "2025-05-26"), (130.0, "130"), (0.5, "0.5"), (54167951, "54167951"), ("Nonpecuniary", "nonpecuniary"), ], ) def test_clean(value, expected): assert _clean(value) == expected def _manifest(tmp_path: Path) -> Path: p = tmp_path / "manifest.csv" p.write_text( "country,cc,file,case_id,harvey_answer\n" 'Testland,zz,"AB-1_2020.pdf","AB-1/2020",yes\n' 'Testland,zz,"CD_2_2021.pdf","CD 2/2021",yes\n' 'Testland,zz,"X_&_Y.pdf","X & Y",no\n', encoding="utf-8", ) return p def test_match_document_passes(tmp_path): lookups = load_manifest(_manifest(tmp_path)) assert match_document("AB-1_2020.pdf", lookups) == ("zz", "AB-1/2020") # exact assert match_document("X_&_Y.pdf", lookups) == ("zz", "X & Y") # loose assert match_document("CD2_2021.pdf", lookups) == ("zz", "CD 2/2021") # tight assert match_document("MANIFEST.csv", lookups) is None # junk def _header(groups: int = 2) -> list[str]: cols = ["Document", "Document ID"] for _ in range(groups): for f in LEGORA_FIELDS: cols += [f, f"{f} (reasoning)"] return cols def test_group_value_columns_two_groups(): cols = _group_value_columns(_header(2)) assert set(cols) == {1, 2} assert cols[1]["case_id"] == 2 assert cols[1]["legal_subject_judgement"] == 4 assert cols[2]["case_id"] == 2 + 2 * len(LEGORA_FIELDS) assert cols[2]["defendant_no1_ISIC1_industry_category"] == len(_header(2)) - 2 def test_group_value_columns_missing_field_raises(): header = [c for c in _header(1) if c != "trial_start_date"] with pytest.raises(ValueError, match="missing field"): _group_value_columns(header) def test_group_value_columns_unbalanced_raises(): header = _header(2) + ["case_id"] with pytest.raises(ValueError, match="unbalanced"): _group_value_columns(header) @pytest.fixture def env(tmp_path, monkeypatch): monkeypatch.setattr(settings, "data_dir", tmp_path) wb = Workbook() ws = wb.active ws.title = "GOLDENSET" ws.append(GOLD_HEADER) wb.save(tmp_path / "Vorlage.xlsx") (tmp_path / "zz").mkdir() gs = Workbook() ws = gs.active ws.title = "GOLDENSET" ws.append(GOLD_HEADER) ws.append(["AB-1/2020", "", "text", *[""] * len(FIELDS), ""]) ws.append(["CD 2/2021", "", "text", *[""] * len(FIELDS), ""]) gs.save(tmp_path / "zz" / "Goldenset_Testland.xlsx") return tmp_path def _export_row(doc: str, g1: dict, g2: dict) -> list: row = [doc, f"uuid-{doc}"] for values in (g1, g2): for f in LEGORA_FIELDS: row += [values.get(f, "—"), "reasoning text"] return row def _write_export(path: Path, rows: list[list]) -> None: wb = Workbook() ws = wb.active ws.title = "Sheet1" ws.append(_header(2)) for r in rows: ws.append(r) wb.save(path) def test_ingest_end_to_end(env): xlsx = env / "legora_2026-08-01.xlsx" _write_export(xlsx, [ _export_row( "AB-1_2020.pdf", {"legal_subject_judgement": "Contract_Law", "trial_end_date": datetime(2025, 5, 26), "plaintiffs_all_count": 130.0}, {"legal_subject_judgement": "Tort_Law", "dispute_value_nominal": "nonpecuniary"}, ), # duplicate run of the same document: g2 disagrees on one field _export_row( "AB-1_2020.pdf", {"legal_subject_judgement": "Contract_Law", "trial_end_date": datetime(2025, 5, 26), "plaintiffs_all_count": 130.0}, {"legal_subject_judgement": "Property_Law", "dispute_value_nominal": "nonpecuniary"}, ), _export_row("CD2_2021.pdf", {"plaintiff_loosing_share": 0.5}, {}), # tight match _export_row("MANIFEST.csv", {}, {}), # junk, dropped ]) conflicts = env / "conflicts.jsonl" ingest(xlsx, _manifest(env), conflicts_out=conflicts) for model in GROUP_MODELS.values(): out = env / "zz" / f"Goldenset_Testland_v3_full_text_{model}.jsonl" recs = [json.loads(l) for l in out.read_text(encoding="utf-8").splitlines()] assert [r["case_id"] for r in recs] == ["AB-1/2020", "CD 2/2021"] # gold ids, junk gone assert all(r["model"] == model for r in recs) assert all(r["inference_date"] == "2026-08-01" for r in recs) keys = list(recs[0]) assert keys.index("inference_date") == keys.index("model") + 1 recs1 = [json.loads(l) for l in (env / "zz" / "Goldenset_Testland_v3_full_text_legora-1.jsonl").read_text().splitlines()] assert recs1[0]["legal_subject_judgement"] == "Contract_Law" # first occurrence kept assert recs1[0]["trial_end_date"] == "2025-05-26" # datetime -> ISO assert recs1[0]["plaintiffs_all_count"] == "130" # integral float -> int assert recs1[0]["trial_start_date"] is None # em-dash -> null assert recs1[1]["plaintiff_loosing_share"] == "0.5" clashes = [json.loads(l) for l in conflicts.read_text(encoding="utf-8").splitlines()] assert clashes == [{ "model": "legora-2", "country": "zz", "case_id": "AB-1/2020", "field": "legal_subject_judgement", "kept": "Tort_Law", "alternative": "Property_Law", }] def test_ingest_discovered_by_models_present(env): from legex.analysis.aggregate import models_present xlsx = env / "legora_2026-08-01.xlsx" _write_export(xlsx, [_export_row("AB-1_2020.pdf", {}, {})]) ingest(xlsx, _manifest(env), conflicts_out=env / "conflicts.jsonl") assert models_present("zz") == ["legora-1", "legora-2"]