Download legex/evaluation/comparison.py from legexbenchmark/code: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/datasets/legexbenchmark/code/resolve/main/legex/evaluation/comparison.py
- Command line
-
hf download hf://datasets/legexbenchmark/code/legex/evaluation/comparison.py
-
curl -L -o comparison.py https://huggingface.co/datasets/legexbenchmark/code/resolve/main/legex/evaluation/comparison.py
14.8 kB
| """Value comparison and refusal detection for gold vs. prediction cells. | |
| Used by scoring (`evaluation.scoring`), the refusal cleaning workflow (`evaluation.cleaning`) and | |
| the analysis package. Refusal detection is heuristic and English-only. | |
| """ | |
| import re | |
| from datetime import date, datetime | |
| from enum import Enum | |
| from typing import get_args | |
| from legex.models.classification import Classification | |
| # Columns that carry no label to score against. | |
| NON_LABEL_COLUMNS = { | |
| "case_id", "link", "full_text", "translated_full_text", "comment", "original_input", | |
| "model", "error", "inference_date", | |
| } | |
| # Sentinels that mean "no value". | |
| EMPTY_LITERALS = frozenset({"", "none", "null", "nan"}) | |
| # Real controlled answers that must never be read as empty or as a refusal. | |
| VALID_TOKENS = frozenset({"nonpecuniary", "no_allocation_possible"}) | |
| # Columns whose Classification field is numeric / a date. Loose parsing 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,))) | |
| ) | |
| 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,))) | |
| ) | |
| BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn") | |
| _NUM_TOKEN_RE = re.compile(r"-?\d[\d',. ]*") | |
| _DATE_SEP_RE = re.compile(r"[_/.\s]+") | |
| _DATE_FALLBACK_FORMATS = ("%d-%m-%Y", "%m-%d-%Y", "%Y%m%d") | |
| _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") | |
| def is_label_column(name: str) -> bool: | |
| if not name or name.lower() in NON_LABEL_COLUMNS: | |
| return False | |
| return not name.startswith("Currency_") | |
| def normalise(value: object) -> str: | |
| """Make gold and prediction cells comparable as strings.""" | |
| if value is None: | |
| return "" | |
| if isinstance(value, datetime): # Excel stores dates as datetimes | |
| return value.date().isoformat() | |
| if isinstance(value, date): | |
| return value.isoformat() | |
| 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 | |
| class RefusalReason(str, Enum): | |
| BARE_TOKEN = "bare non-value token" | |
| REFUSAL_PHRASE = "refusal phrase" | |
| LEADING_NONE = "leading None/N-A + explanation" | |
| TRAILING_NA = "prose ending in N/A" | |
| _REFUSAL_BARE = frozenset({ | |
| "n/a", "na", "n.a.", "unknown", "undetermined", "tbd", "-", "—", | |
| "not available", "not specified", "not stated", "not applicable", | |
| "not provided", "not mentioned", "not determinable", "not disclosed", | |
| }) | |
| _REFUSAL_PHRASE = re.compile( | |
| r"not\s+(?:stated|mentioned|specified|provided|indicated|available|determinable|" | |
| r"applicable|found|listed|given|disclosed|reported|clearly\s+\w+)" | |
| r"|(?:cannot|could\s+not|can'?t|couldn'?t|unable\s+to|not\s+able\s+to)\s+(?:be\s+)?" | |
| r"(?:determine|determined|calculate|calculated|establish|established|ascertain|found|identif)" | |
| r"|does\s+not\s+(?:state|contain|specify|mention|provide|indicate|list|disclose|appear)" | |
| r"|no\s+(?:specific|explicit|clear)\s+\w+" | |
| r"|insufficient\s+(?:information|data|detail)", | |
| re.I, | |
| ) | |
| _REFUSAL_LEADING = re.compile( | |
| r"^\s*(?:none|n/?a|null|unknown|not\s+available|not\s+specified|not\s+stated)\b", re.I | |
| ) | |
| _REFUSAL_TRAILING_NA = re.compile(r"(?:^|[\s\n>)\].])n/?a\.?\s*$", re.I) | |
| _PROSE = re.compile(r"[A-Za-z]{3,}\s+[A-Za-z]{3,}") # two consecutive words → a sentence | |
| def refusal_reason(value: object, column: str | None = None) -> RefusalReason | None: | |
| """Classify `value` as a long-form refusal, or None if it is a usable answer. | |
| A refusal must (a) match a refusal marker and (b) carry no extractable value of | |
| the expected type — if the loose parser can still pull a number/date out of the | |
| prose it is an answer-with-explanation, which the scorer handles, not a refusal. | |
| """ | |
| if value is None: | |
| return None | |
| s = str(value).strip() | |
| if not s or s.lower() in VALID_TOKENS: | |
| return None | |
| bare = s.lower().strip(" .") in _REFUSAL_BARE | |
| if bare: | |
| reason = RefusalReason.BARE_TOKEN | |
| elif _REFUSAL_LEADING.match(s) and _PROSE.search(s): | |
| reason = RefusalReason.LEADING_NONE | |
| elif _REFUSAL_TRAILING_NA.search(s) and _PROSE.search(s): | |
| reason = RefusalReason.TRAILING_NA | |
| elif _REFUSAL_PHRASE.search(s): | |
| reason = RefusalReason.REFUSAL_PHRASE | |
| else: | |
| return None | |
| if column in NUMERIC_COLUMNS and _numeric_value(s, column) is not None: | |
| return None | |
| if column in DATE_COLUMNS and _parse_loose_date(s) is not None: | |
| return None | |
| return reason | |
| def is_refusal(value: object, column: str | None = None) -> bool: | |
| return refusal_reason(value, column) is not None | |
| _ISIC_COLUMNS = frozenset({ | |
| "plaintiff_no1_ISIC1_industry_category", | |
| "defendant_no1_ISIC1_industry_category", | |
| }) | |
| _ISIC_TOKEN = re.compile(r"^[a-v]_[a-z_]+$") | |
| def _canonical_number(n: float) -> str: | |
| return str(int(n)) if float(n).is_integer() else repr(float(n)) | |
| _DATE_CLEAN_RE = re.compile(r"[\d/._\-\s]+") # a date with only separator noise (no citations/prose) | |
| _CITATION_RE = re.compile(r"\[\d+\]") # Harvey citation markers, anywhere | |
| # Match prose with dates | |
| _MONTHS = {m: i + 1 for i, m in enumerate(( | |
| "january", "february", "march", "april", "may", "june", | |
| "july", "august", "september", "october", "november", "december", | |
| ))} | |
| _PROSE_DATE_RE = re.compile( | |
| r"^([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})$|^(\d{1,2})\.?\s+([A-Za-z]+)\s+(\d{4})$" | |
| ) | |
| # A cell that is exactly one number decorated with a currency token and/or a | |
| # Swiss ".--" suffix ("CHF 20'000.--", "5.000 €"). | |
| _CUR = r"(?:[€$£¥₹₩₪₾]|[A-Z]{2,3}\.?|(?i:fr|frs|euros?|francs?|dollars?|pounds?)\.?)" | |
| _DECORATED_AMOUNT_RE = re.compile( | |
| rf"^\s*{_CUR}?\s*(?P<num>-?[\d'\u2019,.\u00a0\u202f ]*\d)\s*{_CUR}?" | |
| rf"\s*(?:[.,]?\s*(?:-{{1,2}}|\u2013|\u2014))?\s*$" | |
| ) | |
| # '5.000' — 5000 (EU) or 5.0 (US)? '538,183' — 538183 (US) or 538.183 (EU)? | |
| # Either way ambiguous without a decimal part → a human decides. | |
| _AMBIGUOUS_GROUPED_RE = re.compile(r"^-?\d{1,3}([.,]\d{3})+$") | |
| def _strict_number(s: str) -> float | None: | |
| """A single clean number with formatting noise only (apostrophe/space/EU-US separators). | |
| Returns None for anything else — prose, citations (`[1]`), newlines, multiple numbers — | |
| so recovery never scrapes a stray digit out of junk.""" | |
| t = s.strip().replace("'", "").replace("’", "").replace(" ", "").replace(" ", "") | |
| if not t or re.search(r"[^\d.,+\-]", t): | |
| return None | |
| if re.fullmatch(r"-?\d{1,3}(\.\d{3})+,\d+", t): # 1.000.000,50 (EU) | |
| t = t.replace(".", "").replace(",", ".") | |
| elif re.fullmatch(r"-?\d+,\d+", t): # 1234,56 | |
| t = t.replace(",", ".") | |
| elif re.fullmatch(r"-?\d{1,3}(,\d{3})+(\.\d+)?", t): # 1,000,000.50 (US) | |
| t = t.replace(",", "") | |
| try: | |
| f = float(t) | |
| except ValueError: | |
| return None | |
| return f if f == f and f not in (float("inf"), float("-inf")) else None | |
| def _strip_noise(s: str) -> str: | |
| """Remove citation markers (`[1]`, anywhere) and markdown backticks/fences, then trim.""" | |
| return _CITATION_RE.sub(" ", s).replace("`", " ").strip() | |
| def _parse_prose_date(s: str) -> date | None: | |
| """A cell that is exactly one prose date with an English month name, else None.""" | |
| m = _PROSE_DATE_RE.match(s.strip()) | |
| if not m: | |
| return None | |
| month_name, day, year = (m.group(1), m.group(2), m.group(3)) if m.group(1) else ( | |
| m.group(5), m.group(4), m.group(6)) | |
| month = _MONTHS.get(month_name.lower()) | |
| if month is None: | |
| return None | |
| try: | |
| return date(int(year), month, int(day)) | |
| except ValueError: | |
| return None | |
| def _decorated_amount(s: str) -> float | None: | |
| """A cell that is exactly one currency-decorated clean number, else None. | |
| Grouped integers without a decimal part (`'5.000 €'`, `'538,183 euro'`) are | |
| left to a human — thousands- vs decimal-separator is ambiguous there.""" | |
| m = _DECORATED_AMOUNT_RE.match(s) | |
| if not m: | |
| return None | |
| num = m.group("num") | |
| if _AMBIGUOUS_GROUPED_RE.match(num.strip()): | |
| return None | |
| return _strict_number(num) | |
| def _review_reason(s: str, column: str | None) -> str: | |
| r = refusal_reason(s, column) | |
| return r.value if r else "no recoverable value" | |
| def resolve(value: object, column: str | None) -> tuple[str, str, str | None]: | |
| """Resolve a cell to ``(status, canonical_value, reason)``. | |
| status is one of: | |
| * ``valid`` — a good value already (kept as-is; also the case for empty), | |
| * ``recovered`` — a value parseable from prose, canonicalised (score-neutral), | |
| * ``review`` — non-empty but neither valid nor recoverable → human review. | |
| Recovery reuses the scorer's own loose parsers so the canonical value scores | |
| identically to the raw one (`values_agree` stays a tolerant safety net). | |
| """ | |
| s = normalise(value) | |
| if not s: | |
| return "valid", "", None | |
| if column in NUMERIC_COLUMNS: | |
| if column == "dispute_value_nominal" and s.lower() == "nonpecuniary": | |
| return "valid", "nonpecuniary", None | |
| if _try_float(s) is not None: # already a clean number | |
| return "valid", s, None | |
| # Recover a single number once citations/backticks/whitespace are stripped — never a | |
| # digit scraped from surviving prose, which would write garbage. | |
| cand = _strip_noise(s) | |
| n = _strict_number(cand) | |
| if n is not None: | |
| return "recovered", _canonical_number(n), None | |
| n = _decorated_amount(cand) | |
| if n is not None: | |
| return "recovered", _canonical_number(n), None | |
| return "review", s, _review_reason(s, column) | |
| if column in DATE_COLUMNS: | |
| cand = _strip_noise(s) | |
| if _ISO_DATE_RE.match(cand): | |
| return ("valid" if cand == s else "recovered"), cand, None | |
| if _DATE_CLEAN_RE.fullmatch(cand) and (d := _parse_loose_date(cand)) is not None: | |
| return "recovered", d.isoformat(), None | |
| if (d := _parse_prose_date(cand)) is not None: | |
| return "recovered", d.isoformat(), None | |
| return "review", s, _review_reason(s, column) | |
| if column in _ISIC_COLUMNS: | |
| low = s.lower() | |
| if low == "no_allocation_possible" or _ISIC_TOKEN.match(low): | |
| # Canonicalise case: gold and the comparator are exact-match. | |
| return ("valid", s, None) if s == low else ("recovered", low, None) | |
| return "review", s, "unrecognized ISIC code" | |
| r = refusal_reason(s, column) | |
| if r is not None: | |
| return "review", s, r.value | |
| return "valid", s, None | |
| 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: | |
| """First numeric token from `s`, tolerating apostrophe/space thousand separators | |
| (`20'000`), EU decimal commas (`1.000,50`), and trailing prose. None if no digit.""" | |
| 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: | |
| 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, treating `_`, `/`, `.`, whitespace as `-`; ISO plus a small fallback.""" | |
| 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 | |
| # Controlled tokens carry no case information: annotators occasionally capitalise | |
| # them (gold "Nonpecuniary" vs the schema literal "nonpecuniary"). | |
| if gv.lower() == pv.lower() and pv.lower() in VALID_TOKENS: | |
| 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 | |
| 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 - both filled, differ; missed - gold | |
| filled, pred empty; hallucinated - gold empty, pred filled; tn - both empty. | |
| """ | |
| gold_filled = bool(gv) | |
| if values_agree(gv, pv, column): | |
| return "tp" if gold_filled else "tn" | |
| if gold_filled and bool(pv): | |
| 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 | |