from __future__ import annotations import re from dataclasses import dataclass from src.checksums import iban_ok, iran_national_id_ok, luhn_ok from src.domain import EntityType, Method, Workflow from src.normalize import compact, fold_digits, only_digits from src.schemas import Span EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b") PHONE_ASCII_RE = re.compile(r"(? list[Span]: raise NotImplementedError def _span( text: str, start: int, end: int, entity_type: EntityType, rule_id: str, confidence: float, reason: str, workflow: Workflow = Workflow.DETECTED, language: str = "en", ) -> Span: return Span( start=start, end=end, entity_type=entity_type, surface=text[start:end], confidence=confidence, method=Method.POLICY.value, rule_id=rule_id, language=language, workflow=workflow, reason=reason, ) def _window(text: str, start: int, radius: int = 32) -> str: return text[max(0, start - radius) : min(len(text), start + radius)] class EmailRecognizer(Recognizer): def __init__(self) -> None: super().__init__("email", EntityType.EMAIL) def analyze(self, text: str) -> list[Span]: found = [] for match in EMAIL_RE.finditer(text): found.append( _span(text, match.start(), match.end(), EntityType.EMAIL, "email.rfc_like", 0.92, "Email pattern") ) return found class PhoneRecognizer(Recognizer): def __init__(self) -> None: super().__init__("phone", EntityType.PHONE) def analyze(self, text: str) -> list[Span]: folded = fold_digits(text) found = [] for match in PHONE_ASCII_RE.finditer(folded): found.append( _span( text, match.start(), match.end(), EntityType.PHONE, "phone.ir_mobile", 0.9, "Iranian mobile after digit fold", language="fa" if text[match.start() : match.end()] != folded[match.start() : match.end()] else "en", ) ) if not found: for match in PHONE_LOOSE_RE.finditer(compact(text)): raw = only_digits(match.group(0)) if len(raw) in {10, 11, 12, 13}: # Offsets on compact() can drift; fall back to digit fold alignment. continue return found class NationalIdRecognizer(Recognizer): def __init__(self) -> None: super().__init__("iran_national_id", EntityType.IR_NATIONAL_ID) def analyze(self, text: str) -> list[Span]: folded = fold_digits(text) found: list[Span] = [] for match in NID_RE.finditer(folded): value = match.group(0) left = _window(folded, match.start()) hinted = bool(NID_CONTEXT_RE.search(left)) if iran_national_id_ok(value): found.append( _span( text, match.start(), match.end(), EntityType.IR_NATIONAL_ID, "nid.iran_checksum", 0.96, "Iranian national ID checksum passed", language="fa", ) ) elif hinted: found.append( _span( text, match.start(), match.end(), EntityType.UNKNOWN, "nid.context_invalid", 0.35, "National-ID context with failed checksum; left for review", workflow=Workflow.REVIEW, language="fa", ) ) return found class CardRecognizer(Recognizer): def __init__(self) -> None: super().__init__("credit_card", EntityType.CREDIT_CARD) def analyze(self, text: str) -> list[Span]: found = [] for match in CARD_RE.finditer(fold_digits(text)): digits = only_digits(match.group(0)) if digits.startswith(("978", "979")): continue if 13 <= len(digits) <= 19 and luhn_ok(digits): found.append( _span( text, match.start(), match.end(), EntityType.CREDIT_CARD, "card.luhn", 0.95, "Luhn-valid laboratory PAN", ) ) return found class IbanRecognizer(Recognizer): def __init__(self) -> None: super().__init__("iban", EntityType.IBAN) def analyze(self, text: str) -> list[Span]: found = [] folded = fold_digits(text) for match in IBAN_RE.finditer(folded): if iban_ok(match.group(0)): found.append( _span(text, match.start(), match.end(), EntityType.IBAN, "iban.mod97", 0.95, "IBAN mod-97 passed") ) return found class EmployeeRecognizer(Recognizer): def __init__(self) -> None: super().__init__("employee_id", EntityType.EMPLOYEE_ID) def analyze(self, text: str) -> list[Span]: return [ _span(text, match.start(), match.end(), EntityType.EMPLOYEE_ID, "employee.aria", 0.88, "Laboratory employee id") for match in EMPLOYEE_RE.finditer(text) ] class PersonRecognizer(Recognizer): def __init__(self) -> None: super().__init__("person", EntityType.PERSON) def analyze(self, text: str) -> list[Span]: found: list[Span] = [] if PROTOCOL_NAME_RE.search(text): # Explicit hard negative: software protocol, not a person. pass for match in HONORIFIC_EN.finditer(text): surface = match.group(0) if PROTOCOL_NAME_RE.search(surface): continue found.append(_span(text, match.start(), match.end(), EntityType.PERSON, "person.honorific_en", 0.72, "English honorific")) for match in HONORIFIC_FA.finditer(text): found.append( _span( text, match.start(), match.end(), EntityType.PERSON, "person.honorific_fa", 0.74, "Persian honorific", language="fa", ) ) for match in LABEL_NAME_EN.finditer(text): start, end = match.start(1), match.end(1) found.append(_span(text, start, end, EntityType.PERSON, "person.label_en", 0.7, "Labeled English name")) for match in LABEL_NAME_FA.finditer(text): start, end = match.start(1), match.end(1) found.append( _span(text, start, end, EntityType.PERSON, "person.label_fa", 0.72, "Labeled Persian name", language="fa") ) for first in LAB_FIRST: for last in LAB_LAST: needle = f"{first} {last}" start = 0 while True: index = text.find(needle, start) if index < 0: break found.append( _span( text, index, index + len(needle), EntityType.PERSON, "person.lab_lexicon", 0.8, "Laboratory name lexicon", language="fa" if any(ord(ch) > 127 for ch in needle) else "en", ) ) start = index + len(needle) return found def hard_negative_surfaces(text: str) -> list[str]: surfaces: list[str] = [] for pattern in (ISBN_RE, VERSION_RE, INVOICE_RE, DATE_RE, PROTOCOL_NAME_RE): surfaces.extend(match.group(0) for match in pattern.finditer(text)) return surfaces def default_recognizers() -> list[Recognizer]: return [ EmailRecognizer(), PhoneRecognizer(), NationalIdRecognizer(), CardRecognizer(), IbanRecognizer(), EmployeeRecognizer(), PersonRecognizer(), ]