"""Scoring for typed extraction. A prediction for one field is ``{"value": ..., "confidence": c, "p_null": p}``: ``value`` None (an empty list for lists) means "not in the state", ``confidence`` is the predictor's probability that the answer it returned -- value or null -- is correct, and ``p_null`` its probability that the field is absent. Every field gets an exact score in {0, 1} (lists: exact set match) plus a partial score (text: token F1; lists: multiset F1). Three things are reported separately because a single blended number hides them: * **hallucination rate** -- on fields whose gold is null, the share answered with a value anyway. This is the safety number for an extractor. * **miss rate** -- on fields with a value, the share answered null. * **accuracy at 90% coverage** -- answer only the 90% most confident fields; extraction products tell users to route on confidence, so it has to mean something. numpy only, so the scorer is testable without a model. """ from __future__ import annotations import datetime as dt import math import re import string from collections import Counter, defaultdict from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple import numpy as np from .schema import (DATE, DATETIME, DURATION, LIST, NUMBER, TEXT, TIME, Case, Field, Gold) REL_TOL = 1e-3 # ---------------------------------------------------------------- normalisers _ARTICLES = re.compile(r"\b(a|an|the)\b", re.UNICODE) _PUNCT = set(string.punctuation) def norm_text(s: str) -> str: """SQuAD's answer normalisation: lower, no punctuation/articles, one space.""" s = "".join(ch for ch in s.lower() if ch not in _PUNCT) return " ".join(_ARTICLES.sub(" ", s).split()) def token_f1(pred: str, gold: str) -> float: p, g = norm_text(pred).split(), norm_text(gold).split() if not p or not g: return float(p == g) common = sum((Counter(p) & Counter(g)).values()) if common == 0: return 0.0 prec, rec = common / len(p), common / len(g) return 2 * prec * rec / (prec + rec) def _num(v: Any) -> Optional[float]: if isinstance(v, bool): return None if isinstance(v, (int, float)): return float(v) return None def same_number(p: Any, g: Any, decimals: Optional[int] = None) -> bool: a, b = _num(p), _num(g) if a is None or b is None: return False if decimals is not None: return round(a, decimals) == round(b, decimals) return math.isclose(a, b, rel_tol=REL_TOL, abs_tol=1e-9) def same_temporal(t: str, p: Any, g: Any) -> bool: if not isinstance(p, str) or not isinstance(g, str): return False try: if t == DATE: return dt.date.fromisoformat(p) == dt.date.fromisoformat(g) if t == TIME: return dt.time.fromisoformat(p) == dt.time.fromisoformat(g) return dt.datetime.fromisoformat(p) == dt.datetime.fromisoformat(g) except ValueError: return False def same_scalar(t: str, p: Any, g: Any, options: Mapping[str, Any]) -> bool: if t == TEXT: return isinstance(p, str) and norm_text(p) == norm_text(g) if t in (NUMBER, DURATION): return same_number(p, g, options.get("decimals")) if t in (DATE, TIME, DATETIME): return same_temporal(t, p, g) return False def _is_null(v: Any) -> bool: return v is None or v == [] # ---------------------------------------------------------------- one field def score_field(f: Field, gold: Gold, value: Any) -> Tuple[float, float]: """(exact, partial) for one predicted value against the gold.""" if gold.null or _is_null(value): s = float(gold.null and _is_null(value)) return s, s if f.type == LIST: if not isinstance(value, list): return 0.0, 0.0 best = max((_list_f1(f, value, g) for g in gold.accepted() if g), default=0.0) return float(best >= 1.0 - 1e-9), best exact = any(same_scalar(f.type, value, g, f.options) for g in gold.accepted()) partial = float(exact) if f.type == TEXT and isinstance(value, str): partial = max(token_f1(value, g) for g in gold.accepted()) return float(exact), partial #: A text list item matches a gold item at this token Jaccard or above -- CUAD's own #: convention. List gold is often whole clauses (CUAD, citations), and exact clause #: boundaries are not what extraction is about. LIST_TEXT_JACCARD = 0.5 def _jaccard(a: str, b: str) -> float: x, y = set(norm_text(a).split()), set(norm_text(b).split()) return len(x & y) / len(x | y) if x | y else 1.0 def _item_match(t: str, p: Any, g: Any, options: Mapping[str, Any]) -> bool: if t == TEXT and isinstance(p, str) and isinstance(g, str): return norm_text(p) == norm_text(g) or _jaccard(p, g) >= LIST_TEXT_JACCARD return same_scalar(t, p, g, options) def _list_f1(f: Field, pred: Sequence[Any], gold: Sequence[Any]) -> float: t = f.item_type unmatched = list(gold) hit = 0 for p in pred: for i, g in enumerate(unmatched): if _item_match(t, p, g, f.options): hit += 1 unmatched.pop(i) break if hit == 0: return 0.0 prec, rec = hit / len(pred), hit / len(gold) return 2 * prec * rec / (prec + rec) # ---------------------------------------------------------------- aggregate def score_cases(cases: Sequence[Case], preds: Sequence[Mapping[str, Mapping[str, Any]]] ) -> Dict[str, Any]: rows: List[Dict[str, Any]] = [] for case, pred in zip(cases, preds): for name, f in case.fields.items(): g = case.gold[name] p = pred.get(name) or {} value = p.get("value") exact, partial = score_field(f, g, value) rows.append({ "case": case.id, "family": case.family, "type": f.type, "gold_null": g.null, "pred_null": _is_null(value), "source": g.source, "exact": exact, "partial": partial, "confidence": p.get("confidence"), "p_null": p.get("p_null")}) return summarise(rows) def summarise(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]: if not rows: return {"fields": 0} exact = np.array([r["exact"] for r in rows]) out: Dict[str, Any] = {"fields": len(rows), "cases": len({r["case"] for r in rows}), "exact": float(exact.mean()), "partial": float(np.mean([r["partial"] for r in rows]))} by_type: Dict[str, List[float]] = defaultdict(list) for r in rows: by_type[r["type"]].append(r["exact"]) out["by_type"] = {t: {"n": len(v), "exact": float(np.mean(v))} for t, v in sorted(by_type.items())} out["macro_exact"] = float(np.mean([v["exact"] for v in out["by_type"].values()])) by_family: Dict[str, List[Mapping[str, Any]]] = defaultdict(list) for r in rows: by_family[r["family"]].append(r) out["by_family"] = {k: _family(v) for k, v in sorted(by_family.items())} # Families differ ~10x in field count (CUAD asks 41 clauses per contract), so the # headline averages families rather than fields. out["macro_family_exact"] = float(np.mean([v["exact"] for v in out["by_family"].values()])) present = [v["exact_present"] for v in out["by_family"].values() if v.get("exact_present") is not None] out["macro_family_exact_present"] = float(np.mean(present)) if present else None by_source: Dict[str, List[float]] = defaultdict(list) for r in rows: if not r["gold_null"]: by_source[r["source"]].append(r["exact"]) out["by_source"] = {k: {"n": len(v), "exact": float(np.mean(v))} for k, v in sorted(by_source.items())} out.update(_null_metrics(rows)) out.update(_confidence_metrics(rows)) return out def _family(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]: d = {"n": len(rows), "exact": float(np.mean([r["exact"] for r in rows])), "partial": float(np.mean([r["partial"] for r in rows]))} d.update(_null_metrics(rows)) return d def _null_metrics(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]: null = [r for r in rows if r["gold_null"]] full = [r for r in rows if not r["gold_null"]] out: Dict[str, Any] = { "null_share": len(null) / len(rows), "hallucination": (float(np.mean([not r["pred_null"] for r in null])) if null else None), "miss": (float(np.mean([r["pred_null"] for r in full])) if full else None), "exact_present": (float(np.mean([r["exact"] for r in full])) if full else None), } scored = [r for r in rows if r.get("p_null") is not None] if null and full and len(scored) == len(rows): out["p_null_auroc"] = auroc([r["p_null"] for r in rows], [r["gold_null"] for r in rows]) return out def _confidence_metrics(rows: Sequence[Mapping[str, Any]]) -> Dict[str, Any]: conf = [r["confidence"] for r in rows] if any(c is None for c in conf): return {} c = np.clip(np.array(conf, dtype=float), 0.0, 1.0) y = np.array([r["exact"] for r in rows], dtype=float) order = np.argsort(-c, kind="stable") k = max(1, int(round(0.9 * len(rows)))) return {"ece": ece(c, y), "brier": float(np.mean((c - y) ** 2)), "exact_at_90_coverage": float(y[order[:k]].mean()), "aurc": aurc(c, y)} def ece(conf: np.ndarray, correct: np.ndarray, bins: int = 10) -> float: edges = np.linspace(0.0, 1.0, bins + 1) idx = np.clip(np.digitize(conf, edges[1:-1]), 0, bins - 1) total = 0.0 for b in range(bins): m = idx == b if m.any(): total += m.mean() * abs(conf[m].mean() - correct[m].mean()) return float(total) def aurc(conf: np.ndarray, correct: np.ndarray) -> float: """Area under the risk-coverage curve (lower is better).""" order = np.argsort(-conf, kind="stable") risk = np.cumsum(1.0 - correct[order]) / np.arange(1, len(order) + 1) return float(risk.mean()) def auroc(scores: Sequence[float], labels: Sequence[bool]) -> Optional[float]: s = np.asarray(scores, dtype=float) y = np.asarray(labels, dtype=bool) pos, neg = s[y], s[~y] if len(pos) == 0 or len(neg) == 0: return None ranks = _rankdata(np.concatenate([pos, neg])) return float((ranks[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg))) def _rankdata(a: np.ndarray) -> np.ndarray: order = np.argsort(a, kind="mergesort") ranks = np.empty(len(a), dtype=float) sa = a[order] i = 0 while i < len(a): j = i while j + 1 < len(a) and sa[j + 1] == sa[i]: j += 1 ranks[order[i:j + 1]] = (i + j) / 2 + 1 i = j + 1 return ranks