File size: 10,386 Bytes
f65336d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import json
import math
from decimal import ROUND_HALF_UP, Decimal, DecimalException, localcontext
from typing import Any
from . import image_rows

VERSION = "parallel-ar-json-scalar-v1"
EOS = "<|im_end|>"
EXTRACTION_INSTRUCTION = "Extract the requested value from the supplied input, following the field instructions and scope."
MEDIA_EVIDENCE_INSTRUCTION = "The attached images are the document pages and contain extraction evidence. Use all attached pages together with the accompanying text, following the field instructions and requested scope."
COMPUTATION_INSTRUCTION = "Answer the requested field using the supplied input and field instructions. Perform any required arithmetic, reasoning, normalization, or unit conversion. A computable answer is available even when it is not written literally in the source."
KNOWLEDGE_INSTRUCTION = "Answer the requested field using reliable prior knowledge and any relevant supplied input. This field explicitly permits knowledge: true. The answer does not need to appear in the document. Missing source evidence does not make a known factual answer unavailable. Return null only when neither reliable prior knowledge nor the input determines the answer. Follow the field instructions and scope."
RECOVERY_INSTRUCTION = "Answer the requested field using the supplied input and field instructions. Copy the matching source value exactly. Check labels, surrounding context and requested entity. Do not calculate, convert units, complete a name, or substitute a related field. Return the value if it is explicitly present; return null if it is absent."
BOOLEAN_INSTRUCTION = " This field is a Boolean statement about the input. Evaluate its condition using the supplied evidence: return true when the condition is affirmed, false when the condition is explicitly negated, and null only when evidence does not determine whether it holds. The literal words true and false do not need to be printed."


def normalize_number(value: Any, spec: dict[str, Any]) -> Any:
    decimals = 0 if spec.get("integer") else spec.get("decimals")
    if value is None or spec["type"] != "number":
        return value
    if isinstance(value, bool):
        raise TypeError("A boolean is not a numeric answer")
    if decimals is None:
        if isinstance(value, Decimal):
            if not value.is_finite():
                raise ValueError("Nonfinite number")
            value = int(value) if value == value.to_integral_value() else float(value)
        if isinstance(value, float) and (not math.isfinite(value)):
            raise ValueError("Nonfinite number")
        return value
    number = value if isinstance(value, Decimal) else Decimal(str(value))
    if not number.is_finite():
        raise ValueError("Nonfinite number")
    try:
        with localcontext() as context:
            context.prec = max(context.prec, number.adjusted() + decimals + 2)
            number = number.quantize(
                Decimal(1).scaleb(-decimals), rounding=ROUND_HALF_UP
            )
    except DecimalException as error:
        raise ValueError(
            "Cannot represent numeric answer at the requested precision"
        ) from error
    return int(number) if decimals == 0 else float(number)


def names(record: dict[str, Any]) -> list[str]:
    return [
        n
        for (n, s) in record["fields"].items()
        if s["type"] in ("text", "number", "boolean", "enum", "object")
        or image_rows.is_inventory(s)
    ]


def schema(spec: dict[str, Any]) -> dict[str, Any]:
    if image_rows.is_inventory(spec):
        return image_rows.inventory_schema(spec)
    if spec["type"] == "object":
        return {
            "type": ["object", "null"] if spec.get("nullable", True) else "object",
            "properties": {
                name: schema(child) for (name, child) in spec["properties"].items()
            },
            "required": list(spec["properties"]),
            "additionalProperties": False,
        }
    if spec["type"] == "boolean":
        return {
            "type": ["boolean", "null"] if spec.get("nullable", True) else "boolean"
        }
    if spec["type"] == "enum":
        values = list(spec["enum"])
        if spec.get("nullable", True) and None not in values:
            values.append(None)
        return {"enum": values}
    kind = (
        "string"
        if spec["type"] == "text"
        else "integer"
        if spec.get("integer")
        else "number"
    )
    result = {"type": [kind, "null"] if spec.get("nullable", True) else kind}
    if kind == "string":
        for key in ["minLength", "maxLength", "pattern", "enum"]:
            if key in spec:
                result[key] = spec[key]
    elif kind in ("number", "integer"):
        for key in [
            "minimum",
            "maximum",
            "exclusiveMinimum",
            "exclusiveMaximum",
            "enum",
        ]:
            if key in spec:
                result[key] = spec[key]
    return result


def complete_spec(record: dict[str, Any], name: str) -> dict[str, Any]:
    spec = dict(record["fields"][name])
    annotation = (
        record.get("_meta", {})
        .get("extraction_contract", {})
        .get("fields", {})
        .get(name, {})
    )
    parent = annotation.get("parent")
    if parent:
        parent_spec = record["fields"].get(parent)
        if not parent_spec or parent_spec["type"] != "list":
            raise ValueError("Missing parent list definition: " + name)
        spec["instructions"] = (
            "Parent list "
            + parent
            + ": "
            + parent_spec.get("instructions", "")
            + "\nRequested element: "
            + spec.get("instructions", "")
        )
    return spec


def instruction(
    record: dict[str, Any], name: str, *, compact_lists: bool = True
) -> str:
    image_instruction = image_rows.instruction(record, name, schema)
    if image_instruction is not None:
        return image_instruction
    spec = complete_spec(record, name)
    annotation = (
        record.get("_meta", {})
        .get("extraction_contract", {})
        .get("fields", {})
        .get(name, {})
    )
    if (
        spec["type"] == "boolean"
        and (not annotation.get("parent"))
        and (not spec.get("_physical_row_scope"))
        and (name not in record.get("_source_row_gates", ()))
    ):
        spec["instructions"] = spec.get("instructions", "") + BOOLEAN_INSTRUCTION
    numeric_instructions = ""
    if spec["type"] == "number":
        if spec.get("unit"):
            numeric_instructions += " Return the value in " + str(spec["unit"]) + "."
    intro = (
        (KNOWLEDGE_INSTRUCTION if spec.get("knowledge") else EXTRACTION_INSTRUCTION)
        + " Return exactly one JSON scalar matching the field schema: quote and escape strings, write numbers without digit-group separators, and use null only when the value is unavailable and null is allowed. Zero is a present number. Preserve repeated source words and list entries. End immediately after the value."
    )
    parent = annotation.get("parent")
    source_bound = spec.get("_physical_row_scope") or (
        parent
        and name
        in record.get("_meta", {})
        .get("extraction_contract", {})
        .get("fields", {})
        .get(parent, {})
        .get("source_fields", [])
    )
    if parent and compact_lists and (spec["type"] != "object") and (not source_bound):
        return (
            intro
            + "\nSchema: "
            + json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
            + "\nInstructions: "
            + record["fields"][parent].get("instructions", "")
            + numeric_instructions
            + f"\nList: {parent}\nRequested element: Item {annotation['index']} of {parent}, "
            + "following requested order and duplicate policy. Return null if this item does not exist.\nField: "
            + name
        )
    if spec["type"] == "object":
        row_instruction = (
            "Check whether this exact physical source row satisfies the requested row scope and exclusions. Return null if this physical row does not match the requested scope, even though it exists. If it qualifies, return one JSON object matching the schema, using only this row's cells. "
            if source_bound
            else "Extract one complete requested row from the supplied document. Return one JSON object matching the schema, or null only if that row does not exist. Keep all properties on the same physical row. "
        )
        return (
            row_instruction
            + "Use null for a missing cell in an existing row. Preserve distinct rows with identical values. Follow the requested row scope and exclusions. End immediately after the object or null."
            + "\nField: "
            + name
            + "\nSchema: "
            + json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
            + "\nInstructions: "
            + spec.get("instructions", "")
            + "\nProperty instructions: "
            + json.dumps(spec["properties"], ensure_ascii=False)
        )
    return (
        intro
        + "\nField: "
        + record.get("_source_row_names", {}).get(name, name)
        + "\nSchema: "
        + json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
        + "\nInstructions: "
        + spec.get("instructions", "")
        + numeric_instructions
    )


def typed_record(record: dict[str, Any]) -> dict[str, Any] | None:
    active = set(names(record))
    annotations = (
        record.get("_meta", {}).get("extraction_contract", {}).get("fields", {})
    )
    omitted = set(active)
    for name, spec in record["fields"].items():
        annotation = annotations.get(name, {})
        queries = annotation.get("query_fields", annotation.get("source_fields", []))
        if spec["type"] == "list" and queries and all((n in active for n in queries)):
            omitted.add(name)
    fields = {
        n: {**s, "type": "number"} if s["type"] == "compute" else s
        for (n, s) in record["fields"].items()
        if n not in omitted
    }
    if not fields:
        return None
    result = {**record, "fields": fields}
    if "answers" in record:
        result["answers"] = {n: record["answers"][n] for n in fields}
    return result