"""Typed Extraction record schema, in the System One extraction wire format. A request is a ``state`` (the text to read) and a named map of typed ``fields``; the answer is one typed value per field, or ``null`` when the state does not determine it. The shape follows Cloudflare's Clairic (``state``, ``fields``, ``reference_date``; answers with ``value``, ``span``, ``p_null``, ``confidence``) so a case is replayable against any API implementing it. It is an independent benchmark, not affiliated with Cloudflare. Unlike typed-decisions, the gold here is not a teacher's opinion. Every answer is a fact: a human-annotated span or value from an open dataset, or the record a constructed document was rendered from. ``Gold.value is None`` means the field is genuinely absent, and answering it anyway is a hallucination. """ from __future__ import annotations import datetime as dt import json from dataclasses import asdict, dataclass, field from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple TEXT, NUMBER, DATE, TIME, DATETIME, DURATION, LIST = ( "text", "number", "date", "time", "datetime", "duration", "list") TYPES = (TEXT, NUMBER, DATE, TIME, DATETIME, DURATION, LIST) ITEM_TYPES = (TEXT, NUMBER, DATE) #: How the gold value relates to the state. ``span``: written verbatim; #: ``computed``: arithmetic over values in the state; ``relative``: a date or #: time resolved against ``reference_date``; ``normalised``: present but in #: another surface form (``March 3rd`` for ``2026-03-03``). SOURCES = ("span", "computed", "relative", "normalised") class SchemaError(ValueError): """A field, gold answer or case violates the schema.""" @dataclass(frozen=True) class Field: name: str type: str instructions: str options: Dict[str, Any] = field(default_factory=dict) def __post_init__(self) -> None: if self.type not in TYPES: raise SchemaError(f"{self.name}: unknown field type {self.type!r}") if not self.instructions.strip(): raise SchemaError(f"{self.name}: instructions are empty") if self.type == LIST and self.options.get("items", TEXT) not in ITEM_TYPES: raise SchemaError(f"{self.name}: list items must be one of {ITEM_TYPES}") @property def item_type(self) -> str: return self.options.get("items", TEXT) if self.type == LIST else self.type @dataclass class Gold: """The correct answer to one field. ``value`` is None for an absent field (lists: an empty list). ``alts`` are further acceptable values (SQuAD and DROP carry several annotators' answers). ``spans`` are ``[start, end)`` character offsets into the state, one per value for a span-sourced answer. """ value: Any source: str = "span" alts: List[Any] = field(default_factory=list) spans: List[Tuple[int, int]] = field(default_factory=list) @property def null(self) -> bool: return self.value is None or self.value == [] def accepted(self) -> List[Any]: return [self.value] + [a for a in self.alts if a != self.value] @dataclass class Case: id: str family: str # e.g. squad2, drop, cuad, invoice origin: str # converted | constructed | distant split: str # train | test state: str fields: Dict[str, Field] gold: Dict[str, Gold] reference_date: Optional[str] = None meta: Dict[str, Any] = field(default_factory=dict) def validate(self) -> "Case": if not self.state: raise SchemaError(f"{self.id}: empty state") if set(self.fields) != set(self.gold): raise SchemaError(f"{self.id}: fields and gold disagree") if self.reference_date: dt.date.fromisoformat(self.reference_date) for name, f in self.fields.items(): g = self.gold[name] if g.source not in SOURCES: raise SchemaError(f"{self.id}/{name}: unknown source {g.source!r}") for v in g.accepted(): check_value(f, v, f"{self.id}/{name}") for s, e in g.spans: if not (0 <= s < e <= len(self.state)): raise SchemaError(f"{self.id}/{name}: span {s}:{e} out of range") if g.source == "span" and f.item_type == TEXT and not g.null: texts = g.value if f.type == LIST else [g.value] if len(g.spans) < len(texts): raise SchemaError(f"{self.id}/{name}: text answer without its spans") for t, (s, e) in zip(texts, g.spans): if self.state[s:e] != t: raise SchemaError(f"{self.id}/{name}: span {s}:{e} is " f"{self.state[s:e]!r}, gold says {t!r}") return self # -- serialisation --------------------------------------------------- def to_json(self) -> Dict[str, Any]: d = asdict(self) d["fields"] = {k: asdict(v) for k, v in self.fields.items()} d["gold"] = {k: asdict(v) for k, v in self.gold.items()} return d @classmethod def from_json(cls, d: Mapping[str, Any]) -> "Case": return cls( id=d["id"], family=d["family"], origin=d["origin"], split=d["split"], state=d["state"], fields={k: Field(**v) for k, v in d["fields"].items()}, gold={k: Gold(value=v["value"], source=v.get("source", "span"), alts=list(v.get("alts", [])), spans=[tuple(s) for s in v.get("spans", [])]) for k, v in d["gold"].items()}, reference_date=d.get("reference_date"), meta=dict(d.get("meta", {}))) def request(self) -> Dict[str, Any]: """The case as an extraction API request (no gold).""" req: Dict[str, Any] = { "state": self.state, "fields": {k: {"type": f.type, "instructions": f.instructions, **f.options} for k, f in self.fields.items()}} if self.reference_date: req["reference_date"] = self.reference_date return req def check_value(f: Field, v: Any, where: str) -> None: if v is None: return if f.type == LIST: if not isinstance(v, list): raise SchemaError(f"{where}: list gold must be a list") for x in v: _check_scalar(f.item_type, x, where) else: _check_scalar(f.type, v, where) def _check_scalar(t: str, v: Any, where: str) -> None: try: if t == TEXT: ok = isinstance(v, str) and v != "" elif t in (NUMBER, DURATION): ok = isinstance(v, (int, float)) and not isinstance(v, bool) elif t == DATE: dt.date.fromisoformat(v) ok = len(v) == 10 elif t == TIME: dt.time.fromisoformat(v) ok = True elif t == DATETIME: dt.datetime.fromisoformat(v) ok = "T" in v else: ok = False except (TypeError, ValueError): ok = False if not ok: raise SchemaError(f"{where}: {v!r} is not a valid {t}") def load(path) -> List[Case]: with open(path) as fh: return [Case.from_json(json.loads(line)) for line in fh if line.strip()] def dump(cases: Sequence[Case], path) -> None: with open(path, "w") as fh: for c in cases: fh.write(json.dumps(c.to_json(), ensure_ascii=False) + "\n")