PII Masking & Sanitization Filter
Write a function mask_pii(text) that detects and replaces sensitive Personally Identifiable Information (PII) before sending prompts to external model APIs.
Your function must identify:
- Emails: Strings matching standard email formats.
- SSNs: Social Security Numbers in the format
XXX-XX-XXXX. - Phones: US Phone numbers in forms like
(XXX) XXX-XXXX,XXX-XXX-XXXX, orXXX.XXX.XXXX.
Replace occurrences sequentially per type starting from 1 (e.g., [EMAIL_1], [EMAIL_2], [SSN_1], [PHONE_1]). Duplicate values of the same PII item must be replaced by the same placeholder.
Return a tuple (masked_text: str, mapping: Dict[str, str]) containing the scrubbed text and the dictionary mapping the placeholders back to their original values.
Example
text = "Contact Alice at alice@hospital.org or call 555-123-4567."
mask_pii(text)
# Returns: ("Contact Alice at [EMAIL_1] or call [PHONE_1].", {"[EMAIL_1]": "alice@hospital.org", "[PHONE_1]": "555-123-4567"})