"""Entity F1 on character spans: strict span and type, micro over all entities. Gold and outputs are JSONL rows {"id", "entities": [[start, end, type], ...]} over the same texts; gold rows also carry "text". Offsets count characters of the text (Python string indices), end exclusive. A predicted span is first trimmed of whitespace and zero-width characters at its edges, as the gold spans were when the set was built, so no system gains or loses by such characters. An entity counts when its span and its type both match (strict, as the strict mode of seqeval on IOB2). A paired bootstrap over texts (10,000 resamples, seed 0) gives a difference of micro F1 its 95% interval. This is the scorer of the published numbers, unchanged. """ from __future__ import annotations import json from pathlib import Path import numpy as np EDGE = set("​‌‍⁠") # zero-width characters, trimmed at entity edges like spaces def trim(text: str, a: int, b: int) -> tuple[int, int]: """A span without whitespace or zero-width characters at its edges.""" while a < b and (text[a].isspace() or text[a] in EDGE): a += 1 while b > a and (text[b - 1].isspace() or text[b - 1] in EDGE): b -= 1 return a, b def read(path: str | Path) -> dict[str, dict]: return {r["id"]: r for r in (json.loads(x) for x in Path(path).open(encoding="utf-8"))} def counts(gold: dict, pred: dict) -> tuple[np.ndarray, list[str], dict]: """Per text and type: [true positives, predicted, gold], plus span-only counts per text.""" types = sorted({e[2] for r in gold.values() for e in r["entities"]}) ids = sorted(gold) tix = {t: i for i, t in enumerate(types)} c = np.zeros((len(ids), len(types) + 1, 3), np.int64) # the last type row: types not in gold span_only = np.zeros((len(ids), 3), np.int64) missing = 0 for k, i in enumerate(ids): text = gold[i]["text"] g = {(a, b, t) for a, b, t in gold[i]["entities"]} if i not in pred: missing += 1 p = set() for a, b, t in pred.get(i, {"entities": []})["entities"]: a2, b2 = trim(text, a, b) if a2 < b2: p.add((a2, b2, t)) for (a, b, t) in g: c[k, tix[t], 2] += 1 for (a, b, t) in p: c[k, tix.get(t, len(types)), 1] += 1 for (a, b, t) in g & p: c[k, tix[t], 0] += 1 gs, ps = {(a, b) for a, b, _ in g}, {(a, b) for a, b, _ in p} span_only[k] = (len(gs & ps), len(ps), len(gs)) return c, types, {"texts": len(ids), "texts_without_prediction": missing, "span_only": span_only} def prf(tp: float, np_: float, ng: float) -> tuple[float, float, float]: p = float(tp) / float(np_) if np_ else 0.0 r = float(tp) / float(ng) if ng else 0.0 return p, r, (2 * p * r / (p + r) if p + r else 0.0) def summary(c: np.ndarray, types: list[str], extra: dict) -> dict: tot = c.sum(axis=(0, 1)) p, r, f = prf(*tot) per = {} for j, t in enumerate(types): tp, n_p, n_g = c[:, j].sum(axis=0) per[t] = {"p": round(100 * prf(tp, n_p, n_g)[0], 2), "r": round(100 * prf(tp, n_p, n_g)[1], 2), "f1": round(100 * prf(tp, n_p, n_g)[2], 2), "gold": int(n_g)} so = extra["span_only"].sum(axis=0) return {"micro": {"p": round(100 * p, 2), "r": round(100 * r, 2), "f1": round(100 * f, 2)}, "macro_f1": round(float(np.mean([v["f1"] for v in per.values()])), 2), "spans_only_f1": round(100 * prf(*so)[2], 2), "per_type": per, "entities": {"gold": int(tot[2]), "predicted": int(tot[1]), "correct": int(tot[0])}, "texts": extra["texts"], "texts_without_prediction": extra["texts_without_prediction"]} def bootstrap(ca: np.ndarray, cb: np.ndarray, n: int = 10000, seed: int = 0) -> dict: """Micro F1 of A minus B, resampling texts (the same draw for both).""" a, b = ca.sum(axis=1), cb.sum(axis=1) # per text: tp, predicted, gold rng = np.random.default_rng(seed) idx = rng.integers(0, len(a), size=(n, len(a))) def f1(x): s = x[idx].sum(axis=1) p = np.divide(s[:, 0], s[:, 1], out=np.zeros(n), where=s[:, 1] > 0) r = np.divide(s[:, 0], s[:, 2], out=np.zeros(n), where=s[:, 2] > 0) return np.divide(2 * p * r, p + r, out=np.zeros(n), where=(p + r) > 0) d = 100 * (f1(a) - f1(b)) full = 100 * (prf(*a.sum(axis=0))[2] - prf(*b.sum(axis=0))[2]) lo, hi = np.percentile(d, [2.5, 97.5]) return {"diff": round(float(full), 2), "lo": round(float(lo), 2), "hi": round(float(hi), 2), "tie": bool(lo <= 0 <= hi), "resamples": n}