File size: 7,471 Bytes
870b63c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")