"""Evidence-linked, deterministic entity recognition for common business documents."""
from __future__ import annotations
import re
from collections.abc import Iterator
from datetime import datetime
from re import Pattern
from ..models import DocumentElement, ParsedDocument
from .models import Evidence, ExtractedEntity
_PATTERNS: tuple[tuple[str, Pattern[str], float], ...] = (
(
"email",
re.compile(
r"(?<![\w.+-])[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}(?![\w.-])",
re.IGNORECASE,
),
0.99,
),
("url", re.compile(r"https?://[^\s<>\]\[()]+", re.IGNORECASE), 0.99),
(
"currency",
re.compile(
r"(?<!\w)(?:USD|EUR|GBP|INR|\$|€|£|₹)\s?\(?-?\d[\d,]*(?:\.\d{1,2})?\)?",
re.IGNORECASE,
),
0.94,
),
("percentage", re.compile(r"(?<!\w)\d+(?:\.\d+)?\s?%"), 0.96),
(
"date",
re.compile(
r"\b(?:\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\d{4}-\d{2}-\d{2}|\d{1,2}(?:st|nd|rd|th)?\s+(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{4}|(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{1,2}(?:st|nd|rd|th)?,?\s+\d{4})\b",
re.IGNORECASE,
),
0.90,
),
(
"invoice_number",
re.compile(
r"\b(?:invoice|inv)\s*(?:number|no\.?|#|id)\s*[:#-]?\s*([A-Z0-9][A-Z0-9/_-]{2,})",
re.IGNORECASE,
),
0.94,
),
(
"purchase_order_number",
re.compile(
r"\b(?:purchase order|po)\s*(?:number|no\.?|#)\s*[:#-]?\s*([A-Z0-9][A-Z0-9/_-]{2,})",
re.IGNORECASE,
),
0.93,
),
(
"phone",
re.compile(
r"(?<!\w)(?:\+?\d{1,3}[ .-]?)?(?:\(?\d{2,4}\)?[ .-]?)?\d{3,4}[ .-]?\d{4}(?!\w)"
),
0.76,
),
(
"tax_id",
re.compile(
r"\b(?:GSTIN|VAT(?:\s+number)?|tax\s+id|EIN)\s*[:#-]?\s*([A-Z0-9-]{6,20})\b",
re.IGNORECASE,
),
0.92,
),
(
"person",
re.compile(
r"\b(?:contact person|prepared by|authorized by|attention|name)\s*[:#-]\s*([A-Z][\w'’-]+(?:[ \t]+[A-Z][\w'’-]+){1,3})",
re.IGNORECASE,
),
0.82,
),
(
"organization",
re.compile(
r"\b(?:company|organization|organisation|vendor|supplier|employer)\s*[:#-]\s*([A-Z][^\r\n,;]{1,70})",
re.IGNORECASE,
),
0.84,
),
(
"address",
re.compile(
r"\b(?:billing address|registered address|address|ship to)\s*[:#-]\s*([^\r\n]{5,120})",
re.IGNORECASE,
),
0.82,
),
)
def _element_spans(
document: ParsedDocument,
) -> Iterator[tuple[int, int, int, DocumentElement]]:
cursor = 0
for index, element in enumerate(document.elements):
if not element.text:
continue
start = cursor
end = start + len(element.text)
yield start, end, index, element
cursor = end + 2
def _evidence_for_span(
document: ParsedDocument,
start: int,
end: int,
quote: str,
*,
element_spans: list[tuple[int, int, int, DocumentElement]] | None = None,
) -> Evidence:
spans = element_spans or list(_element_spans(document))
for element_start, element_end, index, element in spans:
if element_start <= start <= element_end and end <= element_end:
return Evidence(
quote=quote,
source=document.source,
element_index=index,
page_number=element.page_number,
bbox=element.bbox,
start_offset=start,
end_offset=end,
)
return Evidence(quote, document.source, start_offset=start, end_offset=end)
def _normalize(entity_type: str, value: str) -> str:
cleaned = value.strip().rstrip(".,;:")
if entity_type == "email":
return cleaned.casefold()
if entity_type == "url":
return cleaned.rstrip(")").rstrip(".,;")
if entity_type == "currency":
match = re.search(r"-?\d[\d,]*(?:\.\d{1,2})?", cleaned)
if not match:
return cleaned
amount = float(match.group(0).replace(",", ""))
currency = cleaned[: match.start()].strip().upper()
currency = {"$": "USD", "€": "EUR", "£": "GBP", "₹": "INR"}.get(
currency, currency
)
return f"{currency} {amount:.2f}" if currency else f"{amount:.2f}"
if entity_type == "date":
numeric_date = re.fullmatch(r"(\d{1,2})[/-](\d{1,2})[/-](\d{4})", cleaned)
if (
numeric_date
and int(numeric_date.group(1)) <= 12
and int(numeric_date.group(2)) <= 12
and numeric_date.group(1) != numeric_date.group(2)
):
return cleaned # Do not guess the locale for an ambiguous numeric date.
cleaned = re.sub(r"(?<=\d)(st|nd|rd|th)\b", "", cleaned, flags=re.IGNORECASE)
for date_format in (
"%d/%m/%Y",
"%m/%d/%Y",
"%d-%m-%Y",
"%m-%d-%Y",
"%Y-%m-%d",
"%B %d, %Y",
"%B %d %Y",
"%b %d, %Y",
"%b %d %Y",
"%d %B %Y",
"%d %b %Y",
):
try:
return datetime.strptime(cleaned, date_format).date().isoformat()
except ValueError:
continue
if entity_type == "phone":
return re.sub(r"\D", "", cleaned)
return cleaned