"""Ingest Harvey-AI extractions from a single xlsx into per-country JSONL. A VAULT_REVIEW export (Sheet1) holds Harvey's answers grouped by Folder. Each question occupies a fixed block of columns: the older export used 4 columns per question (Value / Reasoning / Citations / Comments); the newer export uses 2 (Answer / Citations). We keep only the Answer column, clean it, match each row to a Goldenset case_id via the PDF filename, and write JSONL that looks exactly like `legex.inference` output — so evaluate/analysis treat Harvey as just another model. The per-question block width is detected from the sheet, so both export layouts work without per-file configuration. """ import argparse import logging import re import sys from collections import defaultdict from pathlib import Path from openpyxl import load_workbook from legex.config import settings from legex.inference import _output_columns from legex.utils import ( inference_path, write_inference_jsonl, goldenset_path, goldenset_sheet, norm_case_id, ) log = logging.getLogger(__name__) HARVEY_FOLDER_TO_CC: dict[str, str] = { "Albania": "al", "Armenia": "am", "Australia": "au", "Austria": "at", "Belgium": "be", "Brazil": "br", "China": "cn", "Dominican_Republic": "do", "France": "fr", "Georgia": "ge", "Germany": "de", "Hong_Kong": "hk", "India": "in", "Italy": "it", "Korea": "kr", "Kosovo": "xk", "Liechtenstein": "li", "Luxembourg": "lu", "Nepal": "np", "New_Zealand": "nz", "Philippines": "ph", "Russia": "ru", "Schweiz_final": "ch", "Switzerland": "ch", "Serbia": "rs", "Singapore": "sg", "South_Korea fixed": "kr", "Spain": "es", "Taiwan": "tw", "Ukraine": "ua", "United_Kingdom": "uk", "United_States": "us", } # The 12 review-table questions, in export order. Column 0 of each row is the # PDF name and column 1 the Folder. Thhe first question (case_id) starts at # column index 3 and each subsequent question sits one block-width further on. # We match rows by PDF filename with the Goldensets. HARVEY_FIELDS_ORDER: 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", ) _FIRST_ANSWER_COL = 3 # After Name (0), Folder (1), Document Classification (2) _CITATION_RE = re.compile(r"\s*(?:\[\d+\])+\s*$") _EMPTY_LITERALS = {"", "—"} _DATE_IN_NAME_RE = re.compile(r"(\d{4}-\d{2}-\d{2})") 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 _folder_to_cc(folder: str) -> str | None: """Map a VAULT export folder to a country code, tolerating the ``(new)`` suffix and spaces (e.g. ``'Hong Kong (new)'`` -> ``hk``).""" base = re.sub(r"\s*\(new\)\s*$", "", str(folder)).strip() return HARVEY_FOLDER_TO_CC.get(base) or HARVEY_FOLDER_TO_CC.get(base.replace(" ", "_")) def _value_columns(n_cols: int) -> dict[int, str]: """Answer-column index -> Goldenset field, for either export layout. Block width per question = (n_cols - 3) / 12 (4 for the old Value/Reasoning/ Citations/Comments layout, 2 for the new Answer/Citations layout).""" width = (n_cols - _FIRST_ANSWER_COL) // len(HARVEY_FIELDS_ORDER) if width < 1: raise ValueError(f"unexpected Harvey sheet width: {n_cols} columns") return { _FIRST_ANSWER_COL + j * width: field for j, field in enumerate(HARVEY_FIELDS_ORDER) if field != "case_id" } def _clean(value: object) -> str: if value is None: return "" s = str(value).strip() if s in _EMPTY_LITERALS: return "" s = _CITATION_RE.sub("", s).strip() if s.lower() == "nonpecuniary": return "nonpecuniary" return s def _gold_case_id_index(cc: str) -> dict[str, str] | None: """{ norm_case_id(gold) → gold case_id } for one country, or None if no Goldenset.""" gs = goldenset_path(cc) if not gs.exists(): return None wb = load_workbook(gs, 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)] try: cid_idx = header.index("case_id") except ValueError as e: raise ValueError(f"{gs}: GOLDENSET sheet has no case_id column") from e index: dict[str, str] = {} for row in rows: if not any(row): continue raw = row[cid_idx] if raw is None: continue gold = str(raw).strip() if not gold: continue index.setdefault(norm_case_id(gold), gold) return index def ingest( xlsx: Path, prompt_version: str = "v3", source: str = "full_text", model: str = "harvey", inference_date: str | None = None, ) -> 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") 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"] col_to_gold = _value_columns(ws.max_column) rows_iter = ws.iter_rows(values_only=True) next(rows_iter) # skip header by_folder: dict[str, list[tuple]] = defaultdict(list) for row in rows_iter: if not row or row[0] is None: continue folder = row[1] if folder is None: continue by_folder[str(folder)].append(row) for folder, rows in by_folder.items(): cc = _folder_to_cc(folder) if cc is None: log.warning(f"unknown folder {folder!r}, skipping {len(rows)} row(s)") continue index = _gold_case_id_index(cc) if index is None: log.info(f"[{cc}] no Goldenset on disk, skipping {len(rows)} Harvey row(s)") continue out = inference_path(cc, prompt_version, source, model) out.parent.mkdir(parents=True, exist_ok=True) matched = 0 unmatched = 0 out_rows: list[dict] = [] for row in rows: stem = Path(str(row[0])).stem key = norm_case_id(stem) gold = index.get(key) if gold is None: # Prefix pass: bundles sometimes shorten filenames # `NKP-11263.pdf` vs gold `NKP_11263_(078_NF_0004)`). cands = [k for k in index if k.startswith(key + "_")] if len(cands) == 1: gold = index[cands[0]] if gold is None: unmatched += 1 log.info(f"[{cc}] no Goldenset match for {row[0]!r}") continue out_row = {col: "" for col in columns} out_row["case_id"] = gold out_row["model"] = model out_row["inference_date"] = inference_date for harvey_idx, gold_col in col_to_gold.items(): if harvey_idx < len(row): out_row[gold_col] = _clean(row[harvey_idx]) out_rows.append(out_row) matched += 1 write_inference_jsonl(out, out_rows, columns) log.info( f"[{cc}] wrote {matched} Harvey row(s) → {out} " f"({unmatched} unmatched, {len(rows)} total)" ) 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-harvey-ingest", description="Convert a Harvey VAULT export into per-country Goldenset_*_harvey.jsonl files.", ) parser.add_argument( "--xlsx", type=Path, default=settings.raw_dir / "harvey_2026-06-30.xlsx", help="Path to the Harvey VAULT export xlsx (default: data/raw/harvey_2026-06-30.xlsx).", ) 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("--model", default="harvey", help="Model slug for the output filename.") parser.add_argument( "--inference_date", default=None, help="ISO date stamped on every record (default: parsed from the xlsx filename).", ) args = parser.parse_args() ingest( xlsx=args.xlsx, prompt_version=args.prompt_version, source=args.source, model=args.model, inference_date=args.inference_date, ) if __name__ == "__main__": main()