code / legex /harvey.py
anonymous
[code] Initial release of the code.
6f5156a
"""Ingest Harvey-AI extractions from a single xlsx into per-country CSVs.
`data/raw/harvey.xlsx` (Sheet1) holds Harvey's outputs for 23 jurisdictions
with 4 columns per question (Value / Reasoning / Citations / Comments). We
keep only the Value columns, clean them, match each row to a Goldenset
case_id via the PDF filename, and write a CSV that looks exactly like the
output of `legex.inference` — so `legex-evaluate`, `legex-analysis`, and
`legex-plots` treat Harvey as just another model.
"""
import argparse
import csv
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 (
classified_csv_path,
goldenset_path,
goldenset_sheet,
norm_case_id,
)
log = logging.getLogger(__name__)
HARVEY_FOLDER_TO_CC: dict[str, str] = {
"Armenia": "am",
"Australia": "au",
"Belgium": "be",
"Brazil": "br",
"China": "cn",
"Dominican_Republic": "do",
"France": "fr",
"Georgia": "ge",
"Germany": "de",
"Hong_Kong": "hk",
"India": "in",
"Nepal": "np",
"New_Zealand": "nz",
"Philippines": "ph",
"Russia": "ru",
"Schweiz_final": "ch",
"Singapore": "sg",
"South_Korea fixed": "kr",
"Spain": "es",
"Taiwan": "tw",
"Ukraine": "ua",
"United_Kingdom": "uk",
"United_States": "us",
}
# Harvey Sheet1 value-column index → Goldenset header name.
HARVEY_COL_TO_GOLD: dict[int, str] = {
7: "legal_subject_judgement",
11: "trial_start_date",
15: "trial_end_date",
19: "dispute_value_nominal",
23: "plaintiff_loosing_share",
27: "court_cost_awarded_nominal",
31: "party_compensation_awarded_nominal",
35: "plaintiffs_all_count",
39: "defendants_all_count",
43: "plaintiff_no1_ISIC1_industry_category",
47: "defendant_no1_ISIC1_industry_category",
}
_CITATION_RE = re.compile(r"\s*(?:\[\d+\])+\s*$")
_EMPTY_LITERALS = {"", "—"}
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",
) -> None:
columns = _output_columns()
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)
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 = HARVEY_FOLDER_TO_CC.get(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 = classified_csv_path(cc, prompt_version, source, model)
out.parent.mkdir(parents=True, exist_ok=True)
matched = 0
unmatched = 0
with open(out, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
writer.writeheader()
for row in rows:
stem = Path(str(row[0])).stem
gold = index.get(norm_case_id(stem))
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
for harvey_idx, gold_col in HARVEY_COL_TO_GOLD.items():
if harvey_idx < len(row):
out_row[gold_col] = _clean(row[harvey_idx])
writer.writerow(out_row)
matched += 1
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 data/raw/harvey.xlsx into per-country Goldenset_*_harvey.csv files.",
)
parser.add_argument(
"--xlsx",
type=Path,
default=settings.raw_dir / "harvey.xlsx",
help="Path to harvey.xlsx (default: data/raw/harvey.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 CSV filename (default: full_text).",
)
parser.add_argument("--model", default="harvey", help="Model slug for the CSV filename.")
args = parser.parse_args()
ingest(
xlsx=args.xlsx,
prompt_version=args.prompt_version,
source=args.source,
model=args.model,
)
if __name__ == "__main__":
main()