from __future__ import annotations from src.domain import SPECIFICITY, EntityType, Method, Workflow from src.recognizers import default_recognizers from src.schemas import Span def merge_spans(spans: list[Span]) -> list[Span]: ordered = sorted(spans, key=lambda item: (item.start, -(item.end - item.start), -SPECIFICITY.get(item.entity_type, 0))) kept: list[Span] = [] for item in ordered: overlap = next((other for other in kept if item.start < other.end and item.end > other.start), None) if overlap is None: kept.append(item) continue item_score = (SPECIFICITY.get(item.entity_type, 0), item.confidence) other_score = (SPECIFICITY.get(overlap.entity_type, 0), overlap.confidence) if item_score > other_score: kept.remove(overlap) kept.append(item) kept.sort(key=lambda item: (item.start, item.end)) for index, item in enumerate(kept, start=1): item.finding_id = item.finding_id or f"SPAN-{index:03d}" return kept def analyze_policy(text: str) -> list[Span]: raw: list[Span] = [] for recognizer in default_recognizers(): raw.extend(recognizer.analyze(text or "")) return merge_spans(raw) def redactable(spans: list[Span], suppressed: set[str] | None = None) -> list[Span]: blocked = suppressed or set() kept = [] for item in spans: if item.finding_id in blocked: item.workflow = Workflow.SUPPRESSED continue if item.entity_type is EntityType.UNKNOWN or item.workflow is Workflow.REVIEW: continue if item.method == Method.BASELINE.value: kept.append(item) continue kept.append(item) return kept