| """Compare Goldenset gold labels against inference output. |
| |
| Reads each country's goldenset_<cc>.jsonl (the human-labelled truth, produced |
| by ``convert_goldenset_to_jsonl.py``) and the matching ``inference_<system>.csv`` |
| file from one of the evaluated systems (``harvey``, ``gemini``, ``gpt``), then |
| reports per-field agreement. |
| """ |
|
|
| import argparse |
| import csv |
| import json |
| import logging |
| import re |
| import sys |
| from datetime import date, datetime |
| from pathlib import Path |
| from typing import get_args |
|
|
| from legex.config import settings |
| from legex.models.classification import Classification |
| from legex.utils import ( |
| EXCLUDED_FOR_EVAL, |
| countries_with_goldenset_jsonl, |
| evaluable_countries, |
| goldenset_jsonl_path, |
| inference_csv_path, |
| ) |
|
|
| |
| SYSTEMS: tuple[str, ...] = ("harvey", "gemini", "gpt") |
|
|
| log = logging.getLogger(__name__) |
|
|
| |
| _NON_LABEL_COLUMNS = {"case_id", "link", "full_text"} |
|
|
| |
| _EMPTY_LITERALS = frozenset({"", "none", "null", "nan"}) |
|
|
| |
| |
| |
| _NUMERIC_COLUMNS = frozenset( |
| (info.alias or name) |
| for name, info in Classification.model_fields.items() |
| if any(a is int or a is float for a in (get_args(info.annotation) or (info.annotation,))) |
| ) |
|
|
| _NUM_TOKEN_RE = re.compile(r"-?\d[\d',. ]*") |
|
|
| |
| |
| _DATE_COLUMNS = frozenset( |
| (info.alias or name) |
| for name, info in Classification.model_fields.items() |
| if any(a is date for a in (get_args(info.annotation) or (info.annotation,))) |
| ) |
|
|
| _DATE_SEP_RE = re.compile(r"[_/.\s]+") |
| _DATE_FALLBACK_FORMATS = ("%d-%m-%Y", "%m-%d-%Y", "%Y%m%d") |
|
|
|
|
| def _is_label_column(name: str) -> bool: |
| if not name or name.lower() in _NON_LABEL_COLUMNS: |
| return False |
| if name.startswith("Currency_"): |
| return False |
| return True |
|
|
| def _normalise(value: object) -> str: |
| """Make gold and prediction cells comparable as strings.""" |
| if value is None: |
| return "" |
| if isinstance(value, float): |
| if value != value: |
| return "" |
| if value.is_integer(): |
| return str(int(value)) |
| s = str(value).strip() |
| if s.lower() in _EMPTY_LITERALS: |
| return "" |
| return s |
|
|
|
|
| def _try_float(s: str) -> float | None: |
| if not s: |
| return None |
| try: |
| return float(s) |
| except ValueError: |
| return None |
|
|
|
|
| def _parse_loose_number(s: str) -> float | None: |
| """Extract the first numeric token from `s`, tolerating apostrophe/space |
| thousand separators (`20'000`, `20 000`), EU decimal commas (`1.000,50`), |
| and trailing prose (`150 GEL state fee awarded …`, `0%, motion satisfied`). |
| Returns None when no digit appears. |
| """ |
| if not s: |
| return None |
| m = _NUM_TOKEN_RE.search(s) |
| if not m: |
| return None |
| tok = m.group(0).strip().rstrip(",.' ") |
| if not tok: |
| return None |
| cleaned = tok.replace("'", "").replace(" ", "") |
| if "," in cleaned and "." in cleaned: |
| |
| if cleaned.rfind(",") > cleaned.rfind("."): |
| cleaned = cleaned.replace(".", "").replace(",", ".") |
| else: |
| cleaned = cleaned.replace(",", "") |
| elif "," in cleaned: |
| parts = cleaned.split(",") |
| |
| if len(parts) == 2 and 1 <= len(parts[1]) <= 2: |
| cleaned = parts[0] + "." + parts[1] |
| else: |
| cleaned = cleaned.replace(",", "") |
| try: |
| return float(cleaned) |
| except ValueError: |
| return None |
|
|
|
|
| def _numeric_value(s: str, column: str | None) -> float | None: |
| """Strict float for any column, plus loose parse for numeric columns.""" |
| n = _try_float(s) |
| if n is not None: |
| return n |
| if column in _NUMERIC_COLUMNS: |
| return _parse_loose_number(s) |
| return None |
|
|
|
|
| def _parse_loose_date(s: str) -> date | None: |
| """Parse a date string, treating `_`, `/`, `.`, whitespace as `-`. |
| |
| Accepts ISO `YYYY-MM-DD` (after separator collapse), and as a fallback |
| `DD-MM-YYYY`, `MM-DD-YYYY`, `YYYYMMDD`. |
| """ |
| if not s: |
| return None |
| t = _DATE_SEP_RE.sub("-", s.strip()).strip("-") |
| if not t: |
| return None |
| try: |
| return date.fromisoformat(t) |
| except ValueError: |
| pass |
| for fmt in _DATE_FALLBACK_FORMATS: |
| try: |
| return datetime.strptime(t, fmt).date() |
| except ValueError: |
| continue |
| return None |
|
|
|
|
| def _values_agree(gv: str, pv: str, column: str | None = None) -> bool: |
| """Compare normalised gold vs prediction cell values.""" |
| if gv == pv: |
| return True |
| if column in _DATE_COLUMNS: |
| gd, pd_ = _parse_loose_date(gv), _parse_loose_date(pv) |
| if gd is not None and pd_ is not None and gd == pd_: |
| return True |
| gn = _numeric_value(gv, column) |
| if gn is not None and gn == 0: |
| |
| if not pv: |
| return True |
| pn = _numeric_value(pv, column) |
| return pn is not None and pn == 0 |
| if gn is not None: |
| pn = _numeric_value(pv, column) |
| if pn is not None: |
| return gn == pn |
| return False |
|
|
|
|
| _BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn") |
|
|
|
|
| def _classify_cell(gv: str, pv: str, column: str | None) -> str: |
| """Bucket a (gold, pred) cell. `gv`/`pv` must already be `_normalise()`-d. |
| |
| tp - gold filled, values agree |
| mismatch - gold filled, pred filled, values differ (FP_wrong) |
| missed - gold filled, pred empty (FN) |
| hallucinated - gold empty, pred filled (FP on a not-filled gold field) |
| tn - both empty |
| """ |
| gold_filled = bool(gv) |
| pred_filled = bool(pv) |
| if _values_agree(gv, pv, column): |
| return "tp" if gold_filled else "tn" |
| if gold_filled and pred_filled: |
| return "mismatch" |
| if gold_filled: |
| return "missed" |
| return "hallucinated" |
|
|
|
|
| def _derived(c: dict[str, int]) -> tuple[float, float, float]: |
| """Per-column precision, recall, F1 from a bucket counter.""" |
| tp, mism, miss, hallu = c["tp"], c["mismatch"], c["missed"], c["hallucinated"] |
| p_denom = tp + mism + hallu |
| r_denom = tp + mism + miss |
| p = tp / p_denom if p_denom else 0.0 |
| r = tp / r_denom if r_denom else 0.0 |
| f1 = 2 * p * r / (p + r) if (p + r) else 0.0 |
| return p, r, f1 |
|
|
|
|
| def _read_goldenset_rows(cc: str) -> tuple[list[str], dict[str, dict[str, str]]]: |
| """Return (label_columns, rows_by_case_id) for a country's JSONL goldenset.""" |
| path = goldenset_jsonl_path(cc) |
| if not path.exists(): |
| raise FileNotFoundError(f"{path} does not exist") |
|
|
| label_columns: list[str] | None = None |
| by_id: dict[str, dict[str, str]] = {} |
| with path.open(encoding="utf-8") as f: |
| for line in f: |
| if not line.strip(): |
| continue |
| record = json.loads(line) |
| if label_columns is None: |
| label_columns = [k for k in record.keys() if _is_label_column(k)] |
| case_id = _normalise(record.get("case_id")) |
| if not case_id: |
| continue |
| labels = {col: _normalise(record.get(col)) for col in label_columns} |
| if not any(labels.values()): |
| continue |
| by_id[case_id] = labels |
| return label_columns or [], by_id |
|
|
|
|
| def _read_predictions(cc: str, system: str) -> dict[str, dict[str, str]]: |
| path = inference_csv_path(cc, system) |
| by_id: dict[str, dict[str, str]] = {} |
| with open(path, encoding="utf-8", newline="") as f: |
| reader = csv.DictReader(f) |
| for row in reader: |
| case_id = _normalise(row.get("case_id")) |
| if not case_id: |
| continue |
| by_id[case_id] = {k: _normalise(v) for k, v in row.items()} |
| return by_id |
|
|
|
|
| def _coverage( |
| gold: dict[str, dict[str, str]], preds: dict[str, dict[str, str]] |
| ) -> dict[str, int]: |
| gold_ids = set(gold) |
| pred_ids = set(preds) |
| overlap = len(gold_ids & pred_ids) |
| return { |
| "gold": len(gold_ids), |
| "pred": len(pred_ids), |
| "overlap": overlap, |
| "missing": len(gold_ids - pred_ids), |
| "extra": len(pred_ids - gold_ids), |
| } |
|
|
|
|
| def score_country( |
| cc: str, system: str, verbose: bool = True |
| ) -> tuple[dict[str, dict[str, int]], dict[str, int]] | None: |
| """Return (per-column counters, case coverage stats) for one (country, system).""" |
| pred_path = inference_csv_path(cc, system) |
| gs_path = goldenset_jsonl_path(cc) |
| if not pred_path.exists(): |
| if verbose: |
| log.warning(f"[{cc}/{system}] missing predictions {pred_path}, skipping") |
| return None |
| if not gs_path.exists(): |
| if verbose: |
| log.warning(f"[{cc}] missing goldenset {gs_path}, skipping") |
| return None |
|
|
| label_columns, gold = _read_goldenset_rows(cc) |
| preds = _read_predictions(cc, system) |
| stats = _coverage(gold, preds) |
|
|
| counters: dict[str, dict[str, int]] = { |
| col: {b: 0 for b in _BUCKETS} for col in label_columns |
| } |
| overlap_ids = [cid for cid in gold if cid in preds] |
| if verbose: |
| print() |
| log.info( |
| f"[{cc}/{system}] gold={stats['gold']} pred={stats['pred']} " |
| f"overlap={stats['overlap']} missing={stats['missing']} extra={stats['extra']}" |
| ) |
|
|
| for case_id in overlap_ids: |
| g = gold[case_id] |
| p = preds[case_id] |
| for col in label_columns: |
| bucket = _classify_cell(g.get(col, ""), p.get(col, ""), col) |
| counters[col][bucket] += 1 |
| return counters, stats |
|
|
|
|
| def _print_report( |
| cc: str, counters: dict[str, dict[str, int]], coverage: dict[str, int] | None = None |
| ) -> None: |
| name_width = max((len(c) for c in counters), default=0) |
| name_width = max(name_width, len("column")) |
| print(f"=== {cc} ===") |
| if coverage is not None: |
| print( |
| f"cases: gold={coverage['gold']} pred={coverage['pred']} " |
| f"overlap={coverage['overlap']} missing={coverage['missing']} " |
| f"extra={coverage['extra']}" |
| ) |
| print( |
| f"{'column'.ljust(name_width)} " |
| f"{'TP':>5} {'Mism':>5} {'Miss':>5} {'Hallu':>5} {'TN':>5} " |
| f"{'P':>7} {'R':>7} {'F1':>5}" |
| ) |
| for col, c in counters.items(): |
| p, r, f1 = _derived(c) |
| f1_s = f"{f1:.2f}" if (p + r) else " - " |
| print( |
| f"{col.ljust(name_width)} " |
| f"{c['tp']:>5} {c['mismatch']:>5} {c['missed']:>5} " |
| f"{c['hallucinated']:>5} {c['tn']:>5} " |
| f"{p:>7.2%} {r:>7.2%} {f1_s:>5}" |
| ) |
|
|
|
|
| def _schema_label_columns() -> list[str]: |
| """The 14 label columns derived from the Classification pydantic model.""" |
| return [ |
| (info.alias or name) |
| for name, info in Classification.model_fields.items() |
| if _is_label_column(info.alias or name) |
| ] |
|
|
|
|
| def evaluate( |
| countries: list[str] | None, |
| systems: list[str] | None, |
| ) -> None: |
| overall: dict[str, dict[str, int]] = { |
| col: {b: 0 for b in _BUCKETS} for col in _schema_label_columns() |
| } |
| overall_coverage = {"gold": 0, "pred": 0, "overlap": 0, "missing": 0, "extra": 0} |
|
|
| targets = countries or evaluable_countries() |
| chosen_systems = systems or list(SYSTEMS) |
|
|
| seen_any = False |
| for system in chosen_systems: |
| print(f"\n########## SYSTEM: {system} ##########") |
| for cc in targets: |
| result = score_country(cc, system) |
| if result is None: |
| continue |
| counters, coverage = result |
| seen_any = True |
| _print_report(f"{cc} / {system}", counters, coverage) |
| for key in overall_coverage: |
| overall_coverage[key] += coverage[key] |
| for col, c in counters.items(): |
| if col not in overall: |
| overall[col] = {b: 0 for b in _BUCKETS} |
| for b in _BUCKETS: |
| overall[col][b] += c[b] |
|
|
| if seen_any: |
| _print_report("ALL", overall, overall_coverage) |
|
|
|
|
| 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-evaluate", |
| description="Compare Goldenset JSONL labels against system inference CSV outputs.", |
| ) |
| parser.add_argument( |
| "--country", |
| action="extend", |
| nargs="+", |
| dest="countries", |
| help=( |
| "Country code(s). Repeatable and/or space-separated. " |
| f"Defaults to the {len(SYSTEMS)}-system evaluation set " |
| "(all jurisdictions with a goldenset JSONL minus " |
| f"{sorted(EXCLUDED_FOR_EVAL)})." |
| ), |
| ) |
| parser.add_argument( |
| "--system", |
| action="extend", |
| nargs="+", |
| dest="systems", |
| choices=list(SYSTEMS), |
| help=f"Inference system(s). Repeatable. Default: all of {list(SYSTEMS)}.", |
| ) |
| args = parser.parse_args() |
| evaluate( |
| countries=args.countries, |
| systems=args.systems, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|