from __future__ import annotations import hashlib import html import re from src.domain import PolicyAction, RULESET_ID from src.normalize import fold_digits from src.schemas import Span def fingerprint(value: str) -> str: digest = hashlib.sha256(f"{RULESET_ID}:{value}".encode("utf-8")).hexdigest() return digest[:10] def mask_token(span: Span) -> str: return f"[{span.entity_type.value}:{fingerprint(span.surface)}]" def apply_text(text: str, spans: list[Span], action: PolicyAction) -> str: if not text: return "" ordered = sorted(spans, key=lambda item: item.start) chunks: list[str] = [] cursor = 0 for item in ordered: if item.start < cursor or item.end > len(text) or item.start >= item.end: continue chunks.append(text[cursor : item.start]) chunks.append("" if action is PolicyAction.REMOVE else mask_token(item)) cursor = item.end chunks.append(text[cursor:]) return "".join(chunks) def leftover_values(export_text: str, values: list[str]) -> list[str]: haystack = fold_digits(export_text or "") leaked: list[str] = [] for value in values: needle = fold_digits(value or "") if needle and len(needle) >= 4 and needle in haystack: leaked.append(value) return leaked def highlight_html(text: str, spans: list[Span], rtl: bool = False) -> str: direction = "rtl-mode" if rtl else "" if not text: return f"
" ordered = sorted(spans, key=lambda item: (item.start, item.end)) chunks: list[str] = [] cursor = 0 for item in ordered: if item.start < cursor or item.end > len(text): continue chunks.append(html.escape(text[cursor : item.start])) title = html.escape(f"{item.entity_type.value} {item.confidence:.2f}") chunks.append(f"{html.escape(text[item.start:item.end])}") cursor = item.end chunks.append(html.escape(text[cursor:])) return f"{''.join(chunks)}"
def redact_csv_cells(text: str, spans: list[Span], action: PolicyAction) -> str:
return apply_text(text, spans, action)
TOKEN_RE = re.compile(r"\[[A-Z_]+:[0-9a-f]{10}\]")
def highlight_redacted_html(text: str, rtl: bool = False) -> str:
direction = "rtl-mode" if rtl else ""
escaped = html.escape(text or "")
marked = TOKEN_RE.sub(lambda match: f"{match.group(0)}", escaped)
return f"{marked}"