File size: 12,291 Bytes
1a48d6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
from __future__ import annotations
import hashlib
import json
import re
import unicodedata
from collections import defaultdict
from collections.abc import Iterable, Sequence
from copy import deepcopy
from decimal import Decimal, localcontext
from typing import Any
from . import ar, grounding

MAX_SOURCE_CANDIDATES = 512
MAX_OPERANDS = 32
_SUM = re.compile("^\\s*(?:the\\s+)?sum\\s+of\\b", re.IGNORECASE)
_PROTECTED = re.compile(
    "\\b(?:not|never|no|without|don't|avoid|unless|if|copy|copies|copied|printed|verbatim|literal|quoted|label|named|called)\\b",
    re.IGNORECASE,
)
_CURRENCY_CODES = frozenset(
    {
        "USD",
        "EUR",
        "GBP",
        "JPY",
        "CNY",
        "INR",
        "AUD",
        "CAD",
        "CHF",
        "HKD",
        "NZD",
        "SGD",
        "SEK",
        "NOK",
        "DKK",
        "KRW",
        "BRL",
        "MXN",
        "ZAR",
    }
)
_AMOUNT_PREFIX = re.compile(
    "(?P<open>\\()?[ \\t]*(?P<before>[+-]?)[ \\t]*(?P<currency>\\$|[A-Z]{3})?[ \\t]*(?P<after>[+-]?)[ \\t]*$"
)
INSTRUCTION = "Select the printed numeric source occurrences that are operands of the requested sum. Follow the field instructions to identify the requested entities, rows, scope and inclusions. Return exactly one compact JSON array of candidate IDs in their source order. Include every matching occurrence once, even when different occurrences have equal amounts. Select the final amount for each requested record; do not also select its component amounts when those components are already included in that final amount. Exclude unrelated amounts, dates, identifiers and aggregate totals outside the requested scope. Do not calculate the sum, invent an amount, deduplicate equal source occurrences or reuse an ID. The original document is reproduced verbatim below; candidate contexts are source excerpts. Return null if no requested operands are present or the operand scope cannot be determined. A printed zero or negative amount is present. End immediately after the array or null."


def canonical(value: object) -> bytes:
    return json.dumps(
        value,
        sort_keys=True,
        ensure_ascii=False,
        separators=(",", ":"),
        allow_nan=False,
    ).encode()


def eligible(record: dict[str, Any], name: str, *, has_media: bool = False) -> bool:
    spec = record["fields"][name]
    annotation = (
        record.get("_meta", {})
        .get("extraction_contract", {})
        .get("fields", {})
        .get(name, {})
    )
    instructions = spec.get("instructions", "")
    return (
        not has_media
        and (not record.get("images"))
        and (not record.get("documents"))
        and (not record.get("_media_payload"))
        and (spec.get("type") == "number")
        and (not spec.get("source_only"))
        and (not spec.get("knowledge"))
        and (not spec.get("_physical_row_scope"))
        and (not annotation.get("parent"))
        and (name not in record.get("_source_row_gates", ()))
        and (not grounding.state_only(spec))
        and (not grounding.document_only(spec))
        and isinstance(instructions, str)
        and bool(_SUM.search(instructions))
        and (not _PROTECTED.search(instructions))
    )


def _signed_readings(
    source: str, start: int, end: int, values: Iterable[Decimal]
) -> set[Decimal]:
    from .model import NUMERAL_RUN

    numeral = NUMERAL_RUN.search(source, start, end)
    if numeral is None:
        return set()
    left = numeral.start()
    prefix_start = left
    while prefix_start > max(0, left - 64):
        char = source[prefix_start - 1]
        if char in " \t(+-−" or unicodedata.category(char) == "Sc":
            prefix_start -= 1
        elif source[
            max(0, prefix_start - 3) : prefix_start
        ].upper() in _CURRENCY_CODES and (
            prefix_start == 3 or not source[prefix_start - 4].isalnum()
        ):
            prefix_start -= 3
        else:
            break
    prefix = source[prefix_start:left]
    first = prefix_start + len(prefix) - len(prefix.lstrip())
    if prefix.strip() in ("-", "−") and re.match(
        "\\d{4}-\\d{2}-\\d{2}(?!\\d)", source[left:]
    ):
        return {value.copy_abs() for value in values}
    if (
        first < left
        and source[first] in "+-−"
        and first
        and source[first - 1].isalnum()
    ):
        if prefix.strip() in ("+", "-", "−"):
            return {value.copy_abs() for value in values}
        return set()
    normalized = "".join(
        (
            "$"
            if unicodedata.category(char) == "Sc"
            else "-"
            if char == "−"
            else char.upper()
            for char in prefix
        )
    ).lstrip()
    match = _AMOUNT_PREFIX.fullmatch(normalized)
    if match is None or (match["before"] and match["after"]):
        return set()
    explicit_sign = match["before"] or match["after"]
    negative = explicit_sign == "-"
    if match["open"]:
        after = source[end:] if source[end - 1 : end] != ")" else source[end - 1 :]
        closing = re.match("[ \\t]*\\)", after)
        if closing is None or explicit_sign:
            return set()
        rest = after[closing.end() :].split("\n", 1)[0].strip(" \t.;,")
        negative = bool(
            match["currency"] or any((c in numeral[0] for c in ".,")) or (not rest)
        )
    return {
        value.copy_abs().copy_negate() if negative else value.copy_abs()
        for value in values
    }


def _source_candidates(source: str) -> list[dict[str, Any]] | None:
    readings = defaultdict(set)
    for value, spans in grounding.numbers(source).items():
        for span in spans:
            readings[tuple(span)].add(value)
    ordered = sorted(readings)
    if not ordered or len(ordered) > MAX_SOURCE_CANDIDATES:
        return None
    previous_end = 0
    candidates = []
    for index, (start, end) in enumerate(ordered):
        if start < previous_end or not 0 <= start < end <= len(source):
            return None
        previous_end = end
        line_start = source.rfind("\n", 0, start) + 1
        line_end = source.find("\n", end)
        if line_end < 0:
            line_end = len(source)
        (context_start, context_end) = (
            max(line_start, start - 64),
            min(line_end, end + 64),
        )
        values = _signed_readings(source, start, end, readings[start, end])
        candidates.append(
            {
                "id": f"N{index}",
                "span": [start, end],
                "printed": source[start:end],
                "decimal": str(next(iter(values))) if len(values) == 1 else None,
                "decimal_options": sorted((str(value) for value in values)),
                "context": source[context_start:context_end],
            }
        )
    return candidates


def _grammar(candidates: Sequence[dict[str, Any]]) -> str:
    lines = ['root ::= "null" | "[" p0 "]"']
    for index, item in enumerate(candidates):
        literal = json.dumps(json.dumps(item["id"]))
        rule = f"p{index} ::= {literal}"
        if index + 1 < len(candidates):
            rule += f' | {literal} "," p{index + 1} | p{index + 1}'
        lines.append(rule)
    return "\n".join(lines)


def prepare_task(
    record: dict[str, Any], field_name: str, *, has_media: bool = False
) -> dict[str, Any] | None:
    if not eligible(record, field_name, has_media=has_media):
        return None
    source = record["input"]
    candidates = _source_candidates(source)
    if not candidates:
        return None
    spec = deepcopy(record["fields"][field_name])
    displayed = [
        {"id": item["id"], "printed": item["printed"], "context": item["context"]}
        for item in candidates
    ]
    schema = {
        "anyOf": [
            {"type": "null"},
            {
                "type": "array",
                "minItems": 1,
                "maxItems": MAX_OPERANDS,
                "uniqueItems": True,
                "items": {
                    "type": "string",
                    "enum": [item["id"] for item in candidates],
                },
            },
        ]
    }
    prompt = (
        INSTRUCTION
        + "\nField: "
        + field_name
        + "\nField instructions: "
        + spec.get("instructions", "")
        + "\nCandidates in source order: "
        + json.dumps(displayed, ensure_ascii=False, separators=(",", ":"))
        + "\n\nOriginal document:\n"
        + source
    )
    return {
        "version": 2,
        "kind": "source-occurrence-sum-v2",
        "field": field_name,
        "input_text": source,
        "prompt": prompt,
        "grammar": {"ebnf": _grammar(candidates)},
        "json_schema": schema,
        "candidates": candidates,
        "field_spec": spec,
        "max_operands": MAX_OPERANDS,
        "source_sha256": hashlib.sha256(source.encode()).hexdigest(),
        "field_spec_sha256": hashlib.sha256(canonical(spec)).hexdigest(),
        "semantic_completeness_proven_by_grounding": False,
    }


def validate_result(
    task: dict[str, Any], raw_json: str, *, complete: bool = True
) -> dict[str, Any]:
    result: dict[str, Any] = {
        "valid": False,
        "value": None,
        "operands": [],
        "decimal_sum": None,
        "operand_count": 0,
        "error": None,
        "semantic_completeness_proven_by_grounding": False,
    }
    try:
        if not complete:
            raise ValueError("incomplete_generation")
        source = task["input_text"]
        if hashlib.sha256(source.encode()).hexdigest() != task["source_sha256"]:
            raise ValueError("source_changed")
        if (
            hashlib.sha256(canonical(task["field_spec"])).hexdigest()
            != task["field_spec_sha256"]
        ):
            raise ValueError("field_spec_changed")
        ids = json.loads(
            raw_json,
            parse_constant=lambda _: (_ for _ in ()).throw(
                ValueError("nonfinite_json")
            ),
        )
        if ids is None:
            from jsonschema import Draft202012Validator

            Draft202012Validator(ar.schema(task["field_spec"])).validate(None)
            result.update(valid=True, error=None)
            return result
        if not isinstance(ids, list) or not ids or len(ids) > task["max_operands"]:
            raise ValueError("invalid_operand_count")
        if any((not isinstance(identifier, str) for identifier in ids)):
            raise ValueError("operand_id_not_string")
        if len(set(ids)) != len(ids):
            raise ValueError("reused_source_occurrence")
        source_candidates = _source_candidates(source)
        if source_candidates != task["candidates"]:
            raise ValueError("source_candidate_mapping_changed")
        indexed = {
            item["id"]: (index, item) for (index, item) in enumerate(source_candidates)
        }
        if any((identifier not in indexed for identifier in ids)):
            raise ValueError("unknown_source_occurrence")
        indices = [indexed[identifier][0] for identifier in ids]
        if indices != sorted(indices):
            raise ValueError("source_order_changed")
        operands = [deepcopy(indexed[identifier][1]) for identifier in ids]
        if any((item["decimal"] is None for item in operands)):
            raise ValueError("ambiguous_operand_spelling")
        amounts = [Decimal(item["decimal"]) for item in operands]
        highest = max((amount.adjusted() for amount in amounts))
        lowest: int = min((amount.as_tuple().exponent for amount in amounts))
        with localcontext() as context:
            context.prec = max(
                context.prec, highest - lowest + len(str(len(amounts))) + 3
            )
            total = sum(amounts, Decimal(0))
        value = ar.normalize_number(total, task["field_spec"])
        from jsonschema import Draft202012Validator

        Draft202012Validator(ar.schema(task["field_spec"])).validate(value)
        result.update(
            valid=True,
            value=value,
            operands=operands,
            decimal_sum=str(total),
            operand_count=len(operands),
        )
    except Exception as error:
        result["error"] = str(error) or type(error).__name__
    return result