File size: 13,732 Bytes
6f5156a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | """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 whose inference outputs are evaluated.
SYSTEMS: tuple[str, ...] = ("harvey", "gemini", "gpt")
log = logging.getLogger(__name__)
# Columns that don't carry a label to evaluate against (matched case-insensitively).
_NON_LABEL_COLUMNS = {"case_id", "link", "full_text"}
# Goldenset / inference sentinels for “no value” (non_empty as empty).
_EMPTY_LITERALS = frozenset({"", "none", "null", "nan"})
# CSV columns whose Classification field is numeric (int / float). Loose
# parsing (apostrophe thousand separators, leading number + trailing prose)
# applies only to these.
_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',. ]*")
# CSV columns whose Classification field is a date. Separator normalisation
# (treat `_`, `/`, `.` as `-`) plus a small format fallback applies only here.
_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: # NaN
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:
# Whichever appears last is the decimal mark.
if cleaned.rfind(",") > cleaned.rfind("."):
cleaned = cleaned.replace(".", "").replace(",", ".")
else:
cleaned = cleaned.replace(",", "")
elif "," in cleaned:
parts = cleaned.split(",")
# Single trailing group of 1-2 digits → decimal comma; else thousands.
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:
# Gold is zero: empty pred or any zero form (0, 0.0, …) counts as match.
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()
|