dlp-lab / demo /src /recognizers.py
alirezaaminzadeh's picture
Publish AriaDLP synthetic Persian/English redaction lab
eef4eed verified
Raw History Blame Contribute Delete
10.4 kB
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"(?<!\d)(?:\+98|0098|0)9\d{9}(?!\d)")
PHONE_LOOSE_RE = re.compile(r"(?<!\d)(?:\+\d{1,3}[\s-]?)?(?:0?9\d{2}[\s-]?\d{3}[\s-]?\d{4})(?!\d)")
NID_RE = re.compile(r"(?<!\d)\d{10}(?!\d)")
CARD_RE = re.compile(r"(?<!\d)(?:\d[ -]?){13,19}(?!\d)")
IBAN_RE = re.compile(r"\b[A-Za-z]{2}\d{2}[A-Za-z0-9]{11,30}\b")
EMPLOYEE_RE = re.compile(r"\b(?:ARIA|EMP)-\d{4,6}\b", re.I)
ISBN_RE = re.compile(r"\b97[89](?:-?\d){10}\b")
VERSION_RE = re.compile(r"\bv?\d+\.\d+\.\d+\b", re.I)
INVOICE_RE = re.compile(r"\b(?:INV|ORD|SKU|TRK)[-_A-Za-z0-9]{3,20}\b", re.I)
DATE_RE = re.compile(r"\b(?:13|14|19|20)\d{2}[/-]\d{1,2}[/-]\d{1,2}\b")
PROTOCOL_NAME_RE = re.compile(r"\bMr\.?\s+Protocol\b", re.I)
HONORIFIC_EN = re.compile(r"\b(?:Mr|Ms|Mrs|Dr)\.?\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,2})")
HONORIFIC_FA = re.compile(r"(?:آقای|خانم|دکتر)\s+([\u0600-\u06FF\u200c]+(?:\s+[\u0600-\u06FF\u200c]+){0,2})")
LABEL_NAME_EN = re.compile(r"(?i)\b(?:name|employee name|full name)\s*[::]\s*([A-Z][A-Za-z\s]{2,40})")
LABEL_NAME_FA = re.compile(r"(?:نام(?:\s+و\s+نام\s+خانوادگی)?|نام\s+کارمند)\s*[::]\s*([\u0600-\u06FF\u200c\s]{2,40})")
NID_CONTEXT_RE = re.compile(r"(?:کد[\u200c\s]*ملی|national\s+id|national\s+code)\s*[::]?\s*", re.I)
LAB_FIRST = {
"Ava",
"Noah",
"Leila",
"Omar",
"Helen",
"Nima",
"سارا",
"نیما",
"لیلا",
"امید",
"هلن",
"رضا",
}
LAB_LAST = {
"Labian",
"Fixture",
"Rahimi",
"Azadi",
"نمونه‌ای",
"آزمایشی",
"رحیمی",
"آزادی",
}
@dataclass(frozen=True)
class Recognizer:
recognizer_id: str
entity_type: EntityType
language: str = "all"
def analyze(self, text: str) -> 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(),
]