clairic-4bit / clairic_runtime /source_sums.py
lucataco's picture
Clairic, MLX 4-bit, with runtime, server and conversion script
1a48d6b verified
Raw History Blame Contribute Delete
12.3 kB
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