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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
from __future__ import annotations
import csv
import json
import math
import re
from collections.abc import Mapping, Sequence
from typing import Any
from jsonschema import Draft202012Validator, ValidationError
from . import ar, html_rows, printed_numbers

LOCAL_SCOPE_INPUT = (
    "The row to classify is provided in the requested field instructions."
)


def _column(value: str) -> str:
    return re.sub("[\\W_]+", "", value.casefold())


def _header_keys(cells: Sequence[str], names: Mapping[str, str]) -> list[str]:
    keys = [_column(cell) for cell in cells]
    return [
        "quantity"
        if key == "qty" and "qty" not in names and ("quantity" in names)
        else key
        for key in keys
    ]


def join_wrapped_descriptions(instructions: str) -> bool:
    positive = False
    for clause in re.split("[.;\\n]", instructions):
        wrapped = re.search(
            "\\b(?:wrapped|multiline|multi-line|continuation)\\b", clause, re.IGNORECASE
        )
        joining = re.search("\\b(?:join|combine|merge)\\b", clause, re.IGNORECASE)
        negative = re.search(
            "\\b(?:not|no|never|without|separate\\w*|independent\\w*)\\b|\\b\\w+n['’]t\\b",
            clause,
            re.IGNORECASE,
        )
        if negative and (wrapped or joining):
            return False
        positive |= bool(
            re.search(
                "\\b(?:join|combine)\\b[^.;\\n]*\\b(?:wrapped|multiline|multi-line|continuation)\\b[^.;\\n]*\\b(?:descriptions?|lines?|text)\\b",
                clause,
                re.IGNORECASE,
            )
        )
    return positive


def _wrapped_rows(
    rows: list[dict[str, Any]], properties: dict[str, dict[str, Any]]
) -> list[dict[str, Any]] | None:
    texts = [name for (name, spec) in properties.items() if spec["type"] == "text"]
    numbers = [name for (name, spec) in properties.items() if spec["type"] == "number"]
    if len(texts) != 1 or not numbers:
        return rows
    text = texts[0]
    joined: list[dict[str, Any]] = []
    for row in rows:
        previous = joined[-1] if joined else None
        if (
            previous
            and previous["values"][text]
            and row["values"][text]
            and (previous["spans"][text] is not None)
            and (row["spans"][text] is not None)
            and all((previous["values"][key] is None for key in numbers))
            and any((row["values"][key] is not None for key in numbers))
            and (
                row["line"].find(row["values"][text])
                >= previous["line"].find(previous["values"][text]) + 2
            )
        ):
            value = previous["values"][text] + " " + row["values"][text]
            if not Draft202012Validator(ar.schema(properties[text])).is_valid(value):
                return None
            joined[-1] = {
                "line": previous["line"] + "\n" + row["line"],
                "values": {**row["values"], text: value},
                "spans": {**row["spans"], text: None},
            }
        else:
            joined.append(row)
    return joined


def _source_row(
    cells: Sequence[str],
    keys: Sequence[str],
    line: str,
    offset: int,
    properties: dict[str, dict[str, Any]],
    names: Mapping[str, str],
) -> dict[str, Any] | None:
    value: str | int | float | None
    (values, spans) = ({}, {})
    for key, cell in zip(keys, cells, strict=True):
        name = names[key]
        spec = properties[name]
        if not cell:
            value = None
        elif spec["type"] == "number":
            try:
                value = printed_numbers.normalize(cell, spec)
            except (ValueError, TypeError, OverflowError, ValidationError):
                return None
        else:
            value = cell
        if not Draft202012Validator(ar.schema(spec)).is_valid(value):
            return None
        values[name] = value
        start = line.find(cell) if cell and line.count(cell) == 1 else -1
        spans[name] = (
            [offset + start, offset + start + len(cell)] if start >= 0 else None
        )
    for name, spec in properties.items():
        if name not in values:
            if not Draft202012Validator(ar.schema(spec)).is_valid(None):
                return None
            (values[name], spans[name]) = (None, None)
    return {"line": line.rstrip("\r\n"), "values": values, "spans": spans}


def _html_candidates(
    source: str, properties: dict[str, dict[str, Any]], names: Mapping[str, str]
) -> list[dict[str, Any]] | None:
    tables = html_rows.tables(source)
    if tables is None or len(tables) != 1 or len(tables[0]) < 2:
        return None
    (header, *body) = tables[0]
    keys = [_column(cell) for cell in header["cells"]]
    if (
        len(keys) < 2
        or len(set(keys)) != len(keys)
        or any((key not in names for key in keys))
    ):
        return None
    rows = []
    for row in body:
        if len(row["cells"]) != len(keys) or not any(row["cells"]):
            return None
        parsed = _source_row(
            row["cells"], keys, row["line"], row["offset"], properties, names
        )
        if parsed is None:
            return None
        for key, span in zip(keys, row["spans"], strict=True):
            parsed["spans"][names[key]] = span
        rows.append(parsed)
    return rows


def candidates(
    source: str, properties: dict[str, dict[str, Any]], *, wrapped: bool = False
) -> list[dict[str, Any]] | None:
    if any(
        (
            spec["type"] not in ("text", "number") or spec.get("knowledge")
            for spec in properties.values()
        )
    ):
        return None
    names = {_column(name): name for name in properties}
    if len(names) != len(properties):
        return None
    if re.search("<table\\b", source, re.IGNORECASE):
        return _html_candidates(source, properties, names)
    lines = source.splitlines(keepends=True)
    (offsets, offset) = ([], 0)
    for line in lines:
        offsets.append(offset)
        offset += len(line)
    tables = []
    for delimiter in ("|", "\t", ",", ";"):
        for index, line in enumerate(lines):
            if delimiter not in line:
                continue
            try:
                header = next(csv.reader([line], delimiter=delimiter, strict=True))
            except csv.Error:
                continue
            header = [cell.strip() for cell in header]
            leading = delimiter == "|" and len(header) > 2 and (not header[0])
            trailing = delimiter == "|" and len(header) > 2 and (not header[-1])
            if trailing:
                header = header[:-1]
            if leading:
                header = header[1:]
            keys = _header_keys(header, names)
            if (
                len(keys) < 2
                or len(set(keys)) != len(keys)
                or any((key not in names for key in keys))
            ):
                continue
            rows: list[dict[str, Any]] = []
            for row_index in range(index + 1, len(lines)):
                text = lines[row_index]
                if delimiter not in text:
                    break
                try:
                    cells = next(csv.reader([text], delimiter=delimiter, strict=True))
                except csv.Error:
                    return None
                cells = [cell.strip() for cell in cells]
                if trailing and cells and (not cells[-1]):
                    cells = cells[:-1]
                if leading and cells and (not cells[0]):
                    cells = cells[1:]
                if len(cells) != len(keys):
                    return None
                if not rows and all(
                    (re.fullmatch(":?-{3,}:?", cell) for cell in cells)
                ):
                    continue
                if not any(cells):
                    return None
                row = _source_row(
                    cells, keys, text, offsets[row_index], properties, names
                )
                if row is None:
                    return None
                rows.append(row)
            tables.append(_wrapped_rows(rows, properties) if wrapped else rows)
    return tables[0] if len(tables) == 1 else None


def _scope_instruction(instructions: str) -> str | None:
    requested = re.split(
        "[.\\n]|\\bExclude\\b", instructions, maxsplit=1, flags=re.IGNORECASE
    )[0]
    roles = [
        bool(re.search(pattern, requested, re.IGNORECASE))
        for pattern in (
            "\\bfees?\\b",
            "\\btax(?:es)?\\b",
            "\\b(?:charges?|goods|products?|services?)\\b",
        )
    ]
    if sum(roles) != 1:
        return None
    priority = "Evaluate exclusions first for this exact row; an exclusion overrides a general category match. "
    if roles[0]:
        return (
            priority
            + "Include only a separately printed fee or surcharge. A billed product or service charge, tax, total or payment is not a fee merely because it has a monetary amount. The row label must explicitly establish that it is a fee or surcharge. "
        )
    if roles[1]:
        return (
            priority
            + "Include only an explicitly identified tax, such as sales tax, VAT or GST. A product, service charge, fee, total or payment is not a tax merely because it has an amount. "
        )
    if roles[2]:
        return (
            priority
            + "Include only billed goods or service charges. A separately identified tax, fee, surcharge, payment, subtotal or total is excluded, even though it is a monetary charge. "
        )
    return None


def scoped_pairs(source: str, spec: dict[str, Any]) -> list[dict[str, Any]] | None:
    instructions = spec.get("instructions", "")
    scope_instruction = _scope_instruction(instructions)
    properties = spec["items"]["properties"]
    if (
        len(properties) != 2
        or scope_instruction is None
        or (not re.match("\\s*Only\\b[^.\\n]*\\brows\\b", instructions, re.IGNORECASE))
        or re.search(
            "\\b(?:summar\\w*|calculat\\w*|combin\\w*|group\\w*|aggregat\\w*|deduplicat\\w*)\\b|\\buse\\b[^.\\n]*\\bas\\b",
            instructions,
            re.IGNORECASE,
        )
    ):
        return None
    texts = [
        name for (name, child) in properties.items() if child.get("type") == "text"
    ]
    numbers = [
        name for (name, child) in properties.items() if child.get("type") == "number"
    ]
    if (
        len(texts) != 1
        or len(numbers) != 1
        or any((child.get("knowledge") for child in properties.values()))
    ):
        return None
    if not re.search(
        "\\b(?:exact|verbatim)\\b[^.\\n]*\\b(?:printed|row)\\b[^.\\n]*\\blabel\\b",
        properties[texts[0]].get("instructions", ""),
        re.IGNORECASE,
    ):
        return None
    names = {_column(name): name for name in properties}
    if len(names) != len(properties):
        return None
    keys = [_column(texts[0]), _column(numbers[0])]
    tables = []
    for delimiter in ("|", "\t", ";"):
        (rows, offset) = ([], 0)
        for line in source.splitlines(keepends=True):
            if delimiter in line:
                try:
                    cells = [
                        cell.strip()
                        for cell in next(
                            csv.reader([line], delimiter=delimiter, strict=True)
                        )
                    ]
                except csv.Error:
                    return None
                if len(cells) != 2 or not all(cells):
                    return None
                row = _source_row(cells, keys, line, offset, properties, names)
                if row is None:
                    return None
                row["eligibility_only"] = True
                row["scope_instruction"] = scope_instruction
                rows.append(row)
            offset += len(line)
        if len(rows) >= 2:
            tables.append(rows)
    return tables[0] if len(tables) == 1 else None


def prepare(
    source: str,
    fields: dict[str, dict[str, Any]],
    *,
    has_media: bool = False,
    allow_scoped_pairs: bool = False,
) -> dict[str, list[dict[str, Any]]]:
    if has_media:
        return {}
    result = {}
    for name, spec in fields.items():
        item = spec.get("items")
        if (
            spec.get("type") != "list"
            or not isinstance(item, dict)
            or item.get("type") != "object"
        ):
            continue
        explicit_rows = re.search(
            "\\bone\\s+(?:object|entry|record)\\s+(?:per|for\\s+each)\\b[^.\\n]*\\brow\\b",
            spec.get("instructions", ""),
            re.IGNORECASE,
        )
        wrapped = join_wrapped_descriptions(spec.get("instructions", ""))
        rows = (
            candidates(source, item["properties"], wrapped=wrapped)
            if explicit_rows
            else scoped_pairs(source, spec)
            if allow_scoped_pairs
            else None
        )
        if rows and len(rows) <= spec.get("max_items", 32):
            missing_columns = [
                key
                for (key, child) in item["properties"].items()
                if child.get("type") == "number"
                and all((row["values"][key] is None for row in rows))
            ]
            if missing_columns:
                for row in rows:
                    row["eligibility_only"] = True
            result[name] = rows
    return result


def membership_instructions(instructions: str) -> str:
    if re.search(
        "[\\r\\n`\\\"“”]|(?<!\\w)'[^'\\r\\n]+'(?!\\w)|‘[^’]+’|\\b(?:literal|verbatim|quoted|quote|quotation|code|snippet|block|note|label|phrase)\\b",
        instructions,
        re.IGNORECASE,
    ):
        return instructions
    target = "(?:(?:wrapped|multiline|multi-line|continuation)\\s+)?(?:descriptions?(?:\\s+lines?)?|lines?|(?:distinct|separate|duplicate|repeated|physical)\\s+rows?)"
    negative_join = re.compile(
        "\\s*(?:do\\s+not|don't|never)\\s+(?:join|combine|merge)\\s+"
        + target
        + "(?:\\s+or\\s+(?:join|combine|merge)\\s+"
        + target
        + ")*\\s*[.;]?\\s*",
        re.IGNORECASE,
    )
    clauses = re.split("(?<=[.;])(?=\\s|$)|(?<=\\n)", instructions)
    if not any((negative_join.fullmatch(clause) for clause in clauses)):
        return instructions
    return "".join(
        (clause for clause in clauses if not negative_join.fullmatch(clause))
    ).strip()


def row_spec(
    spec: dict[str, Any], row: dict[str, Any], *, eligibility: bool = False
) -> dict[str, Any]:
    missing = [name for (name, value) in row["values"].items() if value is None]
    missing_instruction = (
        "Missing cells or entire columns do not exclude an otherwise matching row. These source cells are missing and must remain null: "
        + ", ".join(missing)
        + ". "
        if missing
        else ""
    )
    scope = membership_instructions(spec.get("instructions", ""))
    if eligibility:
        return {
            "type": "boolean",
            "nullable": False,
            "instructions": "Classify exactly this physical source row for inclusion in the requested list. Return true if and only if this row satisfies the requested list instructions. Return false if the row is excluded, unrelated, or does not belong to the requested list, even though it exists. This is an eligibility decision, not a request to copy its cells. "
            + missing_instruction
            + row.get("scope_instruction", "")
            + "Requested list instructions: "
            + scope
            + "\nExact physical source row: "
            + row["line"],
        }
    properties = {}
    for name, child in spec["items"]["properties"].items():
        value = row["values"][name]
        properties[name] = {**child, "nullable": value is None, "enum": [value]}
    return {
        **spec["items"],
        "properties": properties,
        "nullable": True,
        "instructions": scope
        + "\nRead only this exact physical source row: "
        + json.dumps(row["line"], ensure_ascii=False)
        + "\nReturn null if this row does not satisfy the requested scope. Otherwise copy its cells together. "
        + missing_instruction
        + "Do not substitute a different row. Missing cells are null. This query has no list ordinal to count.",
    }


def local_scope_context(
    rows: Sequence[dict[str, Any]], queries: Sequence[str], *, offset: int = 0
) -> tuple[dict[str, str], dict[str, str]]:
    if not rows or not all((row.get("scope_instruction") for row in rows)):
        return ({}, {})
    pairs = list(zip(queries, rows, strict=True))
    inputs = dict.fromkeys(queries, LOCAL_SCOPE_INPUT)
    names = {
        query: f"source_scope_{offset + index}"
        for (index, (query, _)) in enumerate(pairs, 1)
    }
    return (inputs, names)


def assemble(
    predictions: dict[str, dict[str, Any]],
    rows: Sequence[dict[str, Any]],
    queries: Sequence[str],
    *,
    eligibility: bool = False,
) -> dict[str, Any]:
    checks = [predictions[name] for name in queries]
    selected = [
        (row, answer)
        for (row, answer) in zip(rows, checks, strict=True)
        if (
            answer.get("value") is True
            if eligibility
            else answer.get("value") is not None
        )
    ]
    valid = all(
        (
            answer.get("valid", False) and answer.get("complete", False)
            for answer in checks
        )
    )
    scored = True
    if eligibility:
        valid &= all((type(answer.get("value")) is bool for answer in checks))
        scored = all(
            (
                isinstance((score := answer.get("p_excluded")), (int, float))
                and (not isinstance(score, bool))
                and math.isfinite(score)
                and (0 <= score <= 1)
                for answer in checks
            )
        )
        valid &= scored
        p_null = (
            math.exp(sum((math.log(answer["p_excluded"]) for answer in checks)))
            if scored and all((answer["p_excluded"] > 0 for answer in checks))
            else 0.0
        )
        p_null_method = (
            "product_source_row_exclusion_probabilities"
            if scored
            else "unavailable_source_row_exclusion_probability"
        )
    else:
        p_null = min((answer.get("p_null", 0.0) for answer in checks))
        p_null_method = "minimum_source_row_null_probability"
    log_probability = sum(
        (answer.get("log_probability", -math.inf) for answer in checks)
    )
    if not math.isfinite(log_probability):
        log_probability = None
    result = {
        "value": [
            dict(row["values"]) if eligibility else answer["value"]
            for (row, answer) in selected
        ],
        "valid": valid,
        "complete": valid,
        "confidence": math.exp(min(0, log_probability))
        if valid and log_probability is not None
        else 0.0,
        "confidence_method": "ar_source_row_eligibility_probability"
        if eligibility
        else "ar_source_row_sequence_probability",
        "p_null": p_null,
        "p_null_method": p_null_method,
        "confidences": [answer.get("confidence", 0.0) for (row, answer) in selected],
        "p_nulls": [
            answer.get("p_excluded" if eligibility else "p_null", 0.0)
            for (row, answer) in selected
        ],
        "spans": [None] * len(selected),
        "property_spans": [row["spans"] for (row, answer) in selected],
    }
    if log_probability is not None:
        result["log_probability"] = log_probability
    if eligibility and (not scored):
        result.pop("p_nulls")
    if not valid:
        result["failure_reason"] = (
            "source_row_eligibility_unscored"
            if eligibility and (not scored)
            else "source_row_read_incomplete"
        )
    return result