File size: 12,610 Bytes
dc7d8aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import json
import math
import re
import unicodedata
from collections.abc import Callable
from typing import Any, cast
from . import MAX_OUTPUT_TOKENS
from .schema import MAX_LIST_ITEMS

INVENTORY_OUTPUT_TOKENS = 2048
_ROW_REQUEST = re.compile(
    "\\bone\\s+(?:object|entry|record)\\s+(?:per|for\\s+each)\\b[^.\\n]*\\brow\\b",
    re.IGNORECASE,
)
LABEL = {
    "type": "text",
    "nullable": False,
    "instructions": "Brief exact printed identifier of this requested row, without secondary description or numeric cells. Follow the requested field scope: the label may name a product, service, tax, fee, payment or other row.",
}


def prepare(
    record: dict[str, Any], *, has_media: bool, share_description: bool = False
) -> dict[str, Any]:
    if not has_media:
        return record
    annotations = record["_meta"]["extraction_contract"]["fields"]
    for name, spec in record["fields"].items():
        annotation = annotations.get(name, {})
        if (
            spec.get("type") != "list"
            or not isinstance(spec.get("items"), dict)
            or spec["items"].get("type") != "object"
            or (not annotation.get("query_fields"))
            or annotation.get("source_fields")
            or (not _ROW_REQUEST.search(spec.get("instructions", "")))
        ):
            continue
        spec.update(nullable=True, _image_row_inventory=True)
        annotation["image_row_fields"] = annotation.pop("query_fields")
        for index, child in enumerate(annotation["image_row_fields"], 1):
            row = record["fields"][child]
            row.update(nullable=False, _image_row_proposal=True)
            if share_description:
                row["_share_image_row_description"] = True
            row["instructions"] = (
                f"Item {index} of {name} in the supplied document. "
                + spec.get("instructions", "")
                + " Return null for each missing cell, including absent entire columns. If this physical row does not exist return an object with every cell null."
            )
    return record


def is_inventory(spec: dict[str, Any]) -> bool:
    return bool(spec.get("_image_row_inventory"))


def inventory_schema(spec: dict[str, Any]) -> dict[str, Any]:
    return {
        "type": ["array", "null"],
        "minItems": 1,
        "maxItems": spec.get("max_items", MAX_LIST_ITEMS) + 1,
        "items": {
            "type": "object",
            "properties": {"label": {"type": "string"}},
            "required": ["label"],
            "additionalProperties": False,
        },
    }


def instruction(
    record: dict[str, Any],
    name: str,
    schema: Callable[[dict[str, Any]], dict[str, Any]],
) -> str | None:
    spec = record["fields"][name]
    if is_inventory(spec):
        return (
            "Extract the requested value from the supplied input, following the field instructions and scope. Return all matching rows together as one JSON array. Return null only if there are no matching rows. Each object describes one physical row. Missing cells are null inside that object; they do not make the row absent. Keep wrapped text in its row and preserve distinct duplicate rows. Stop after the last matching row and close the array. End immediately after the array or null."
            + "\nField: "
            + name
            + "\nSchema: "
            + json.dumps(
                inventory_schema(spec), ensure_ascii=False, separators=(",", ":")
            )
            + "\nInstructions: "
            + spec.get("instructions", "")
            + "\nProperty instructions: "
            + json.dumps({"label": LABEL}, ensure_ascii=False)
        )
    if spec.get("_image_row_proposal"):
        if spec.get("_share_image_row_description"):
            shared = shared_description_instruction(record, name, schema)
            if shared is not None:
                return shared
        return (
            "Extract one complete requested row from the supplied document. Return one JSON object matching the schema. Keep all properties on the same physical row. 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."
            + "\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 None


def shared_description_instruction(
    record: dict[str, Any],
    name: str,
    schema: Callable[[dict[str, Any]], dict[str, Any]],
) -> str | None:
    spec = record["fields"][name]
    if not spec.get("_image_row_proposal"):
        return None
    annotation = (
        record.get("_meta", {})
        .get("extraction_contract", {})
        .get("fields", {})
        .get(name, {})
    )
    (parent, index) = (annotation.get("parent"), annotation.get("index"))
    if (
        not isinstance(parent, str)
        or not parent
        or type(index) is not int
        or (index < 1)
    ):
        return None
    properties = spec.get("properties", {})
    description = properties.get("description", {})
    if description.get("type") != "text" or not description.get("instructions"):
        return None
    ordinal = f"Item {index} of {parent} in the supplied document. "
    scope = spec.get("instructions", "")
    if not scope.startswith(ordinal):
        return None
    return (
        "Extract one complete requested row from the supplied document. Return one JSON object matching the schema. Keep all properties on the same physical row. 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."
        + "\nSchema: "
        + json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
        + "\nInstructions: "
        + scope[len(ordinal) :]
        + "\nProperty instructions: "
        + json.dumps(properties, ensure_ascii=False)
        + "\nRequested row: "
        + ordinal.rstrip()
        + "\nField: "
        + name
        + "\nProperty instructions: "
        + json.dumps({"description": description}, ensure_ascii=False)
    )


def output_limit(record: dict[str, Any], name: str, length: int, max_input: int) -> int:
    desired = (
        INVENTORY_OUTPUT_TOKENS
        if is_inventory(record["fields"][name])
        else MAX_OUTPUT_TOKENS
    )
    return min(desired, max_input + MAX_OUTPUT_TOKENS - length)


def _words(value: str) -> str:
    return " ".join(re.findall("\\w+", unicodedata.normalize("NFKC", value).casefold()))


def _assignment(costs: list[list[float]]) -> list[int]:
    if not costs:
        return []
    (count, width) = (len(costs), len(costs[0]))
    (u, v, p, way) = (
        [0.0] * (count + 1),
        [0.0] * (width + 1),
        [0] * (width + 1),
        [0] * (width + 1),
    )
    for index in range(1, count + 1):
        (p[0], column) = (index, 0)
        (minimum, used) = ([math.inf] * (width + 1), [False] * (width + 1))
        while True:
            used[column] = True
            (row, delta, next_column) = (p[column], math.inf, 0)
            for candidate in range(1, width + 1):
                if not used[candidate]:
                    cost = costs[row - 1][candidate - 1] - u[row] - v[candidate]
                    if cost < minimum[candidate]:
                        (minimum[candidate], way[candidate]) = (cost, column)
                    if minimum[candidate] < delta:
                        (delta, next_column) = (minimum[candidate], candidate)
            for candidate in range(width + 1):
                if used[candidate]:
                    u[p[candidate]] += delta
                    v[candidate] -= delta
                else:
                    minimum[candidate] -= delta
            column = next_column
            if p[column] == 0:
                break
        while column:
            previous = way[column]
            (p[column], column) = (p[previous], previous)
    result: list[int | None] = [None] * count
    for column in range(1, width + 1):
        if p[column]:
            result[p[column] - 1] = column - 1
    return cast(list[int], result)


def _select(
    labels: list[str], proposals: list[dict[str, Any]], text_keys: list[str]
) -> tuple[list[dict[str, Any] | None], list[int]]:
    if not text_keys:
        return (
            [
                proposals[index] if index < len(proposals) else None
                for index in range(len(labels))
            ],
            [],
        )
    costs = []
    for index, label in enumerate(labels):
        label = _words(label)
        row_costs = []
        for position, proposal in enumerate(proposals):
            value = proposal.get("value") if proposal.get("valid") else None
            texts = (
                [value.get(key) for key in text_keys] if isinstance(value, dict) else []
            )
            matches = label and any(
                (
                    isinstance(text, str) and f" {label} " in f" {_words(text)} "
                    for text in texts
                )
            )
            row_costs.append(abs(position - index) * 10 if matches else 1000000000.0)
        costs.append(row_costs + [100000000.0] * len(labels))
    chosen = _assignment(costs)
    conflicts = [
        index
        for (index, column) in enumerate(chosen)
        if column >= len(proposals) or costs[index][column] >= 100000000.0
    ]
    return (
        [
            None if index in conflicts else proposals[column]
            for (index, column) in enumerate(chosen)
        ],
        conflicts,
    )


def assemble(
    record: dict[str, Any], predictions: dict[str, dict[str, Any]]
) -> dict[str, dict[str, Any]]:
    answers = {}
    annotations = record["_meta"]["extraction_contract"]["fields"]
    for name, annotation in annotations.items():
        queries = annotation.get("image_row_fields")
        if not queries:
            continue
        (spec, inventory) = (record["fields"][name], predictions[name])
        labels = [row["label"] for row in inventory.get("value") or []]
        maximum = spec.get("max_items", MAX_LIST_ITEMS)
        inventory_complete = (
            inventory.get("valid", False)
            and inventory.get("complete", False)
            and (len(labels) <= maximum)
        )
        properties = spec["items"]["properties"]
        text_keys = [
            key for (key, child) in properties.items() if child["type"] == "text"
        ]
        (selected, conflicts) = _select(
            labels[:maximum], [predictions[child] for child in queries], text_keys
        )
        complete = inventory_complete and all(
            (row and row.get("complete", False) for row in selected)
        )
        valid = (
            complete
            and (not conflicts)
            and all(
                (
                    row
                    and row.get("valid")
                    and isinstance(row.get("value"), dict)
                    and any((value is not None for value in row["value"].values()))
                    for row in selected
                )
            )
        )
        answer = {
            "value": [row["value"] if row else None for row in selected],
            "valid": valid,
            "complete": complete,
            "confidence": 0.0,
            "confidences": [
                row.get("confidence", 0.0) if row else 0.0 for row in selected
            ],
            "confidence_method": "ar_sequence_probability_with_source_row_labels",
            "p_null": inventory["p_null"],
            "p_null_method": "source_row_labels_null_probability",
            "spans": [None] * len(selected),
        }
        scores = [inventory, *selected]
        if valid and all((row and "log_probability" in row for row in scores)):
            probability = sum(
                (row["log_probability"] for row in cast(list[dict[str, Any]], scores))
            )
            if math.isfinite(probability):
                answer.update(
                    log_probability=probability,
                    confidence=math.exp(min(0.0, probability)),
                )
        if conflicts:
            answer["failure_reason"] = "source_row_alignment"
        answers[name] = answer
    return answers