clairic-flash / clairic_runtime /image_rows.py
areneau's picture
Add complete Clairic Transformers package
dc7d8aa verified
Raw History Blame Contribute Delete
12.6 kB
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