Source code for automated_document_parser.intelligence.extraction
"""Schema-guided field extraction with evidence and pluggable backends."""
from __future__ import annotations
import re
from collections.abc import Mapping
from typing import Any, Protocol
from ..models import ParsedDocument
from .entities import _element_spans, _evidence_for_span, extract_entities
from .models import FieldExtraction, StructuredExtraction
[docs]
class SchemaExtractionBackend(Protocol):
"""Interface for deterministic or model-backed schema extraction engines."""
[docs]
def extract(
self, document: ParsedDocument, schema: Mapping[str, Any]
) -> StructuredExtraction:
"""Extract values and source evidence for the supplied JSON schema."""
_DEFAULT_ALIASES: dict[str, tuple[str, ...]] = {
"invoice_number": ("invoice number", "invoice no", "invoice #", "inv no"),
"purchase_order_number": (
"purchase order",
"purchase order number",
"po number",
"po no",
),
"invoice_date": ("invoice date", "date of invoice", "issued on"),
"due_date": ("due date", "payment due", "pay by"),
"vendor": ("vendor", "supplier", "seller", "from"),
"customer": ("customer", "bill to", "billed to", "buyer"),
"total": ("total", "total amount", "grand total", "amount due", "invoice total"),
"subtotal": ("subtotal", "sub total", "net amount"),
"tax": ("tax", "vat", "gst", "sales tax"),
"currency": ("currency",),
"email": ("email", "e-mail"),
"phone": ("phone", "telephone", "mobile"),
}
def _field_aliases(name: str, definition: Mapping[str, Any]) -> tuple[str, ...]:
aliases = list(_DEFAULT_ALIASES.get(name.casefold(), ()))
configured_aliases = definition.get("aliases", ())
if isinstance(configured_aliases, str):
configured_aliases = (configured_aliases,)
if not isinstance(configured_aliases, (list, tuple)):
raise TypeError(f"aliases for '{name}' must be a string or list of strings")
if any(not isinstance(alias, str) for alias in configured_aliases):
raise TypeError(f"aliases for '{name}' must contain only strings")
aliases.extend(configured_aliases)
aliases.append(name.replace("_", " ").replace("-", " "))
# Longer aliases first avoids matching a short label inside a more specific one.
return tuple(
sorted(
{str(alias).strip() for alias in aliases if str(alias).strip()},
key=len,
reverse=True,
)
)
def _coerce(value: str, field_type: str) -> tuple[Any, bool]:
raw = value.strip()
if field_type == "string":
return raw, True
if field_type in {"number", "integer"}:
numeric = raw.strip()
negative_parentheses = numeric.startswith("(") and numeric.endswith(")")
numeric = numeric.strip("() ")
numeric = re.sub(r"^(?:USD|EUR|GBP|INR)\s*", "", numeric, flags=re.IGNORECASE)
numeric = re.sub(r"\s*(?:USD|EUR|GBP|INR)$", "", numeric, flags=re.IGNORECASE)
numeric = (
numeric.replace(",", "")
.replace("$", "")
.replace("£", "")
.replace("€", "")
.replace("₹", "")
)
if negative_parentheses:
numeric = "-" + numeric
try:
if not re.fullmatch(r"[+-]?\d+(?:\.\d+)?", numeric):
return raw, False
return (float(numeric) if field_type == "number" else int(numeric)), (
field_type != "integer" or float(numeric).is_integer()
)
except ValueError:
return raw, False
if field_type == "boolean":
lowered = raw.casefold()
if lowered in {"true", "yes", "y"}:
return True, True
if lowered in {"false", "no", "n"}:
return False, True
return raw, False
return raw, True
[docs]
class RuleBasedSchemaExtractor:
"""Extract fields from explicit labels and recognized entities, without an LLM."""
[docs]
def extract(
self, document: ParsedDocument, schema: Mapping[str, Any]
) -> StructuredExtraction:
if not isinstance(schema, Mapping):
raise TypeError("schema must be a mapping")
properties = schema.get("properties")
if not isinstance(properties, Mapping):
raise TypeError("schema must define a 'properties' object")
raw_required = schema.get("required", ())
if not isinstance(raw_required, (list, tuple)) or any(
not isinstance(name, str) for name in raw_required
):
raise ValueError("schema 'required' must be a list of property names")
required = set(raw_required)
if not properties:
raise ValueError("schema must define a non-empty 'properties' object")
unknown_required = required.difference(properties)
if unknown_required:
raise ValueError(
"required fields are not defined in properties: "
+ ", ".join(sorted(unknown_required))
)
text = document.content
entities = extract_entities(document)
element_spans = list(_element_spans(document))
fields: dict[str, FieldExtraction] = {}
values: dict[str, Any] = {}
for field_name, raw_definition in properties.items():
if not isinstance(field_name, str) or not field_name:
raise ValueError("schema property names must be non-empty strings")
definition = (
raw_definition
if isinstance(raw_definition, Mapping)
else {"type": raw_definition}
)
field_type = str(definition.get("type", "string"))
if field_type not in {"string", "number", "integer", "boolean"}:
raise ValueError(
f"unsupported type '{field_type}' for field '{field_name}'; "
"supported types are string, number, integer and boolean"
)
aliases = _field_aliases(field_name, definition)
matches: list[tuple[str, int, int, float]] = []
for alias in aliases:
pattern = re.compile(
rf"(?im)(?<![\w]){re.escape(alias)}\s*(?:[:#]|\s+-)\s*([^\r\n|]+)"
)
for match in pattern.finditer(text):
candidate = match.group(1).strip().strip("|;,")
candidate = re.split(r"\s{3,}", candidate, maxsplit=1)[0].strip()
if candidate:
matches.append((candidate, match.start(1), match.end(1), 0.93))
if not matches:
entity_types = {
"email": {"email"},
"phone": {"phone"},
"date": {"date"},
"invoice_number": {"invoice_number"},
"purchase_order_number": {"purchase_order_number"},
}.get(field_name.casefold(), set())
matches.extend(
(
entity.value,
entity.evidence.start_offset or 0,
entity.evidence.end_offset or 0,
entity.confidence,
)
for entity in entities
if entity.entity_type in entity_types
)
# Deduplicate overlapping aliases that identify the same exact value.
unique: dict[tuple[int, int, str], tuple[str, int, int, float]] = {}
for candidate in matches:
unique[(candidate[1], candidate[2], candidate[0])] = candidate
matches = sorted(unique.values(), key=lambda item: item[1])
if not matches:
fields[field_name] = FieldExtraction()
values[field_name] = None
continue
if len(matches) > 1:
evidence = tuple(
_evidence_for_span(
document, start, end, value, element_spans=element_spans
)
for value, start, end, _ in matches
)
fields[field_name] = FieldExtraction(
value=None,
confidence=max(item[3] for item in matches),
status="ambiguous",
evidence=evidence,
)
values[field_name] = None
continue
raw_value, start, end, confidence = matches[0]
parsed_value, valid = _coerce(raw_value, field_type)
enum = definition.get("enum")
if enum is not None and not isinstance(enum, list):
raise TypeError(f"enum for '{field_name}' must be a list")
if valid and isinstance(enum, list) and parsed_value not in enum:
valid = False
evidence = _evidence_for_span(
document,
start,
end,
text[start:end].strip(),
element_spans=element_spans,
)
status = "extracted" if valid else "type_mismatch"
fields[field_name] = FieldExtraction(
value=parsed_value if valid else None,
confidence=confidence if valid else min(confidence, 0.5),
status=status,
evidence=(evidence,),
)
values[field_name] = parsed_value if valid else None
missing_required = tuple(
sorted(
name
for name in required
if name not in fields or fields[name].status != "extracted"
)
)
return StructuredExtraction(
values=values,
fields=fields,
schema_name=schema.get("title"),
missing_required=missing_required,
)