"""Local PII detection and non-destructive redaction."""
from __future__ import annotations
import re
from collections.abc import Iterable
from ..models import DocumentElement, ParsedDocument
from .models import PIIMatch, RedactionResult
_PATTERNS: tuple[tuple[str, re.Pattern[str], float], ...] = (
(
"email",
re.compile(
r"(?<![\w.+-])[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}(?![\w.-])",
re.IGNORECASE,
),
0.99,
),
(
"us_ssn",
re.compile(r"(?<!\d)(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}(?!\d)"),
0.99,
),
("credit_card", re.compile(r"(?<!\d)(?:\d[ -]?){13,19}(?!\d)"), 0.90),
("ipv4", re.compile(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?![\d.])"), 0.94),
(
"phone",
re.compile(
r"(?<!\w)(?:\+\d{1,3}[ .()-]?)?(?:\(?\d{2,4}\)?[ .-]?)?\d{3,4}[ .-]\d{4}(?!\w)"
),
0.82,
),
)
def _luhn_valid(value: str) -> bool:
digits = [int(char) for char in value if char.isdigit()]
if not 13 <= len(digits) <= 19:
return False
checksum = 0
parity = len(digits) % 2
for index, digit in enumerate(digits):
if index % 2 == parity:
digit *= 2
if digit > 9:
digit -= 9
checksum += digit
return checksum % 10 == 0
def _element_spans(document: ParsedDocument):
cursor = 0
for index, element in enumerate(document.elements):
if not element.text:
continue
start, end = cursor, cursor + len(element.text)
yield start, end, index, element
cursor = end + 2
def _selected_categories(categories: Iterable[str] | None) -> set[str]:
if categories is None:
return {item[0] for item in _PATTERNS}
if isinstance(categories, str):
return {categories}
return set(categories)
[docs]
def detect_pii(
document: ParsedDocument,
*,
categories: Iterable[str] | None = None,
) -> tuple[PIIMatch, ...]:
"""Detect common PII locally and return source offsets and page provenance."""
selected = _selected_categories(categories)
unknown = selected.difference(item[0] for item in _PATTERNS)
if unknown:
raise ValueError("unsupported PII categories: " + ", ".join(sorted(unknown)))
spans = list(_element_spans(document))
if (
document.elements
and "\n\n".join(item.text for item in document.elements if item.text)
!= document.content
):
spans = []
found: list[PIIMatch] = []
for category, pattern, confidence in _PATTERNS:
if category not in selected:
continue
for match in pattern.finditer(document.content):
value = match.group(0)
if category == "credit_card" and not _luhn_valid(value):
continue
if category == "ipv4" and any(int(part) > 255 for part in value.split(".")):
continue
if category == "phone":
digits = re.sub(r"\D", "", value)
prefix = document.content[
max(0, match.start() - 16) : match.start()
].casefold()
if len(digits) < 10 or not (
value.lstrip().startswith("+")
or re.search(r"\b(phone|mobile|tel|fax)\s*[:#-]?\s*$", prefix)
):
continue
element_index = None
page_number = None
for start, end, index, element in spans:
if start <= match.start() and match.end() <= end:
element_index, page_number = index, element.page_number
break
found.append(
PIIMatch(
category,
value,
match.start(),
match.end(),
confidence,
document.source,
element_index,
page_number,
)
)
# Prefer higher-priority, longer matches when patterns overlap.
priority = {"credit_card": 0, "us_ssn": 1, "email": 2, "phone": 3, "ipv4": 4}
found.sort(
key=lambda item: (
item.start_offset,
priority.get(item.category, 99),
-(item.end_offset - item.start_offset),
)
)
filtered: list[PIIMatch] = []
for item in found:
if filtered and item.start_offset < filtered[-1].end_offset:
continue
filtered.append(item)
return tuple(filtered)
[docs]
def redact_document(
document: ParsedDocument,
*,
categories: Iterable[str] | None = None,
replacement: str = "[REDACTED]",
) -> RedactionResult:
"""Return a redacted copy without changing the original document.
The result's audit metadata records categories and source spans but never
copies the sensitive values into the redaction report.
"""
if not replacement:
raise ValueError("replacement must not be empty")
selected_categories = (
_selected_categories(categories) if categories is not None else None
)
matches = detect_pii(document, categories=selected_categories)
def apply(text: str, offsets: list[tuple[int, int, str]] | None = None) -> str:
if offsets is None:
offsets = [
(item.start_offset, item.end_offset, replacement) for item in matches
]
for start, end, token in reversed(offsets):
text = text[:start] + token + text[end:]
return text
redacted_content = apply(document.content)
redacted_elements: list[DocumentElement] = []
aligned_elements = (
not document.elements
or "\n\n".join(item.text for item in document.elements if item.text)
== document.content
)
cursor = 0
for index, element in enumerate(document.elements):
if not element.text:
redacted_elements.append(
DocumentElement(
text="",
element_type=element.element_type,
page_number=element.page_number,
bbox=element.bbox,
reading_order=element.reading_order,
confidence=element.confidence,
metadata={"redacted": True},
)
)
continue
element_start = cursor
element_end = element_start + len(element.text)
if aligned_elements:
local = [
(
max(0, item.start_offset - element_start),
min(len(element.text), item.end_offset - element_start),
replacement,
)
for item in matches
if item.element_index == index
]
else:
local_matches = detect_pii(
ParsedDocument(source=document.source, content=element.text),
categories=selected_categories,
)
local = [
(item.start_offset, item.end_offset, replacement)
for item in local_matches
]
redacted_elements.append(
DocumentElement(
text=apply(element.text, local),
element_type=element.element_type,
page_number=element.page_number,
bbox=element.bbox,
reading_order=element.reading_order,
confidence=element.confidence,
metadata={"redacted": True},
)
)
cursor = element_end + 2
redacted_document = ParsedDocument(
source=document.source,
content=redacted_content,
metadata={
"source": document.source,
"element_count": len(redacted_elements) if document.elements else 0,
"redaction": {
"count": len(matches),
"categories": sorted({item.category for item in matches}),
"replacement": replacement,
"original_values_retained": False,
},
},
elements=tuple(redacted_elements) if document.elements else (),
)
audit = tuple(
{
"category": item.category,
"start_offset": item.start_offset,
"end_offset": item.end_offset,
"page_number": item.page_number,
"element_index": item.element_index,
"confidence": item.confidence,
}
for item in matches
)
return RedactionResult(
redacted_content,
redacted_document,
audit,
len(matches),
document.source,
replacement,
)