lucataco's picture
Clairic Flash, MLX 4-bit, with runtime, server and conversion script
ae97c5d verified
Raw History Blame Contribute Delete
10.4 kB
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