PII Redactor — Python source
Paste text and automatically detect and mask personal data — emails, phone numbers, IP addresses, SSNs, credit card numbers, and dates.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
r"""pii-redactor — PII detection & redaction (email, phone, IPs, SSN, cards, dates).
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `pii-redactor` tool, ported from
src/lib/pii-redactor.ts (the canonical TypeScript implementation).
Every regex candidate passes a structural validator (octet ranges, Luhn
checksum, month/day bounds, E.164 digit count) before it is kept, and
re.ASCII keeps \d / \w / \b byte-faithful to the JavaScript reference
even on non-ASCII input. Never raises.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import re
# All PII types, in display order.
PII_TYPES = ["email", "phone", "ipv4", "ipv6", "ssn", "credit-card", "date"]
_A = re.ASCII
def is_valid_luhn(digits: str) -> bool:
"""Luhn checksum. `digits` must be a non-empty string of 0-9."""
if not re.fullmatch(r"\d+", digits, _A):
return False
total, double = 0, False
for ch in reversed(digits):
d = ord(ch) - 48
if double:
d *= 2
if d > 9:
d -= 9
total += d
double = not double
return total % 10 == 0
# --- Per-type structural validators (regex candidates pass through these) ---
def _is_valid_ipv4(candidate: str) -> bool:
"""Octets 0-255 each; the regex already bounds the shape to a dotted quad."""
return all(int(o) <= 255 for o in candidate.split("."))
def _is_valid_ipv6(candidate: str) -> bool:
"""Full 8-group form, or a compressed `::` form expanding to exactly 8."""
if not re.search(r"[A-Fa-f0-9]", candidate):
return False # lone ":" / "::" (URL scheme separators) carry no hex digits
groups = candidate.split(":")
if "" not in groups:
return len(groups) == 8 and all(re.fullmatch(r"[A-Fa-f0-9]{1,4}", g, _A) for g in groups)
parts = candidate.split("::") # compressed: at most one "::", sides hold < 8 groups
if len(parts) > 2:
return False
left = parts[0].split(":") if parts[0] else []
right = parts[1].split(":") if len(parts) > 1 and parts[1] else []
if len(left) + len(right) > 7:
return False
return all(re.fullmatch(r"[A-Fa-f0-9]{1,4}", g, _A) for g in left + right)
def _is_valid_date(candidate: str) -> bool:
"""ISO calendar plausibility: month 01-12, day 01-31."""
m = re.fullmatch(r"\d{4}-(\d{2})-(\d{2})", candidate, _A)
return bool(m) and "01" <= m.group(1) <= "12" and "01" <= m.group(2) <= "31"
def _is_valid_phone(candidate: str) -> bool:
"""E.164 digit budget (7-15) and structural guards for the fuzzy phone shape."""
digits = re.sub(r"\D", "", candidate, flags=_A)
if not 7 <= len(digits) <= 15:
return False
# A dotted quad is IP-shaped (already claimed by ipv4); a YYYY-MM-DD
# shape (even an impossible date) is never a phone number.
return not re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", candidate, _A) and not re.fullmatch(
r"\d{4}-\d{2}-\d{2}", candidate, _A
)
def _is_valid_card(candidate: str) -> bool:
"""13-19 digits with optional space/dash grouping, plus a Luhn checksum."""
digits = re.sub(r"\D", "", candidate, flags=_A)
return 13 <= len(digits) <= 19 and is_valid_luhn(digits)
# --- Detectors: a global candidate regex + an optional structural validator.
# List order IS the overlap priority (index 0 claims spans first).
_DETECTORS: list[tuple[str, re.Pattern[str], "object"]] = [
("email", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", _A), None), # RFC 5322 simplified
("credit-card", re.compile(r"\d(?:[ -]?\d){11,}", _A), _is_valid_card),
("ssn", re.compile(r"\b\d{3}-\d{2}-\d{4}\b", _A), None),
("ipv6", re.compile(r"(?<![:\w])[A-Fa-f0-9]{0,4}(?::[A-Fa-f0-9]{0,4}){1,7}(?![:\w])", _A), _is_valid_ipv6),
("ipv4", re.compile(r"(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?!\.?\d)(?!\w)", _A), _is_valid_ipv4),
("date", re.compile(r"(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)", _A), _is_valid_date),
# Fuzziest pattern - lowest priority: optional +country, optional (area),
# then 1-4 groups of 2-4 digits separated by spaces, dashes, or dots.
("phone", re.compile(r"(?<![\d(])(?:\+\d{1,3}[ .-]?)?(?:\(\d{1,4}\)|\d{1,4})(?:[ .-]?\d{2,4}){1,4}(?!\d)", _A), _is_valid_phone),
]
def detect_pii(text: str, types: "list[str] | None" = None) -> "list[dict]":
"""Detect personal data in `text`; pass `types` to scan for a subset.
Returns matches in document order, non-overlapping, each a dict with
`type`, `start`, `end` and `original` keys.
"""
source = text or ""
active = set(types) if types is not None else None
candidates: "list[dict]" = []
for pii_type, rx, validate in _DETECTORS:
if active is not None and pii_type not in active:
continue
for m in rx.finditer(source):
if m.group() and (validate is None or validate(m.group())): # zero-length safety
candidates.append({"type": pii_type, "start": m.start(), "end": m.end(), "original": m.group()})
# Highest-priority (lowest index) candidates claim their span first.
order = {t: i for i, (t, _, _) in enumerate(_DETECTORS)}
candidates.sort(key=lambda c: (order[c["type"]], c["start"]))
kept: "list[dict]" = []
for c in candidates:
if not any(c["start"] < k["end"] and k["start"] < c["end"] for k in kept):
kept.append(c)
return sorted(kept, key=lambda c: c["start"])
def redact_pii(text: str, mask: str = "[REDACTED]", types: "list[str] | None" = None) -> str:
"""Redact personal data from `text`, replacing every detected span with `mask`."""
out = text or ""
for m in reversed(detect_pii(out, types)):
out = out[: m["start"]] + mask + out[m["end"] :] # right-to-left keeps indices valid
return out
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →