Skip to content

7502: PII Redaction & Privacy Filtering

⏱ 6 min read·📅 Last updated: 2026-10-17

Difficulty: ⭐⭐⭐ Advanced

Estimated Time: 3 hours

Table of Contents


Learning Objectives

After completing this lesson, you will be able to:

  • Classify a data element as direct identifier, indirect identifier, or sensitive context using the classification matrix
  • Run PIIDetector over a sample document and enumerate every entity type the regex layer catches
  • Redact one document with the partial and placeholder strategies and predict each redacted output
  • Wire PIIPipeline with injected NLP and storage layers so it runs without spaCy or cryptography installed
  • Compute the recall gap that regex-only detection leaves on person names, using the validator's F1 output
  • Execute the GDPR erasure cycle — store, access, delete — and audit the three compliance-log events

Abstract

Personally Identifiable Information (PII) in prompts, tool outputs, and logs is a compliance exposure (GDPR, CCPA, HIPAA) before it is a security one. This lesson builds the handling stack in layers: a regex detector, an NER-based detector (compile-checked — spaCy), a redactor with pluggable strategies, Presidio as the industry-standard upgrade, Fernet-encrypted storage, and an audit log for the GDPR erasure cycle. Six of the eight code fences execute in this repo with verified output; the two model-backed detectors are compile-checked, and the dependency-injected pipeline runs without them. The final metrics run is honest: regex-only detection misses the person name, and the recall number reports the gap.


PII Categories

┌─────────────────────────────────────────────────────────────────────────┐
│                      PII Classification Matrix                           │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │  DIRECT IDENTIFIERS (High Risk)                                  │   │
│  ├──────────────────────────────────────────────────────────────────┤   │
│  │  • Full Name          • Email Address                             │   │
│  │  • Phone Number       • SSN / Tax ID                              │   │
│  │  • Home Address       • Credit Card Number                        │   │
│  │  • Driver's License   • Passport Number                          │   │
│  │  • Bank Account       • IP Address (sometimes)                    │   │
│  └──────────────────────────────────────────────────────────────────┘   │
│                                                                         │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │  INDIRECT IDENTIFIERS (Medium Risk)                              │   │
│  ├──────────────────────────────────────────────────────────────────┤   │
│  │  • First/Last Name    • Date of Birth                            │   │
│  │  • Zip Code + City    • Job Title + Workplace                   │   │
│  │  • Vehicle Plate      • Medical Conditions                       │   │
│  │  • Race/Ethnicity     • Religious Affiliation                    │   │
│  └──────────────────────────────────────────────────────────────────┘   │
│                                                                         │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │  SENSITIVE CONTEXT (Low-Medium Risk)                            │   │
│  ├──────────────────────────────────────────────────────────────────┤   │
│  │  • Financial Data      • Health Records                          │   │
│  │  • Education Records  • Employment History                       │   │
│  │  • Criminal Records   • Biometric Data                           │   │
│  └──────────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────────┘

Modern Context (2026)

Four developments shape current practice; the code in this lesson implements each in minimal form:

  • Presidio is the reference implementation. Microsoft Presidio (analyzer + anonymizer) is the de-facto open-source PII stack. The regex layer below is a minimal version of its pattern recognizers, and the Presidio section shows the drop-in upgrade path.
  • Regex is the floor, not the ceiling. Names, addresses, and free-text identifiers need NER — spaCy, a transformer NER model, or Presidio's transformer recognizers. The validator's recall number at the end of this lesson quantifies exactly this gap on a real document.
  • Pseudonymization defaults. GDPR treats properly pseudonymized data as lower risk: hash with SHA-256 (salted/peppered) or replace with tokens. MD5 is legacy; the redactor's hash strategy and the storage layer below follow the SHA-256 rule.
  • LLM-era boundary. Redact before the prompt leaves your trust boundary — prompts, tool outputs, and logs are all PII channels. Never log raw prompts (the compliance logger below records event metadata only), and feed the same redaction rules to guardrail or PII-screening models that inspect traffic.

PII Detection

Pattern-Based Detection

Regex patterns are the deterministic, free first layer — exact for structured identifiers like emails, phones, SSNs, and cards.

# pii_detector.py
import re

from dataclasses import dataclass
from enum import Enum

class PIIType(Enum):
    NAME = "name"
    EMAIL = "email"
    PHONE = "phone"
    SSN = "ssn"
    CREDIT_CARD = "credit_card"
    IP_ADDRESS = "ip_address"
    DATE_OF_BIRTH = "date_of_birth"
    ADDRESS = "address"
    PASSPORT = "passport"
    DRIVER_LICENSE = "driver_license"
    BANK_ACCOUNT = "bank_account"

@dataclass
class PIIEntity:
    """Detected PII entity"""
    type: PIIType
    text: str
    start: int
    end: int
    confidence: float
    redacted_text: str

class PIIDetector:
    """Detect PII in text using pattern matching"""

    def __init__(self):
        self.patterns = self._load_patterns()

    def _load_patterns(self) -> dict[PIIType, list[re.Pattern]]:
        """Load regex patterns for PII detection"""

        return {
            PIIType.EMAIL: [
                re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')
            ],

            PIIType.PHONE: [
                re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'),  # US format
                re.compile(r'\b\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b')  # International
            ],

            PIIType.SSN: [
                re.compile(r'\b\d{3}-\d{2}-\d{4}\b'),  # 123-45-6789
                re.compile(r'\b\d{3}\s\d{2}\s\d{4}\b')  # 123 45 6789
            ],

            PIIType.CREDIT_CARD: [
                re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'),  # 1234 5678 9012 3456
                re.compile(r'\b\d{16}\b')  # 1234567890123456
            ],

            PIIType.IP_ADDRESS: [
                re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
            ],

            PIIType.DATE_OF_BIRTH: [
                re.compile(r'\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s+\d{1,2},?\s+\d{4}\b', re.IGNORECASE),
                re.compile(r'\b\d{1,2}[/-]\d{1,2}[/-]\d{4}\b')
            ],

            PIIType.ADDRESS: [
                re.compile(r'\d+\s+[A-Z][a-z]+\s+(?:Street|St|Avenue|Ave|Road|Rd|Lane|Ln|Drive|Dr|Boulevard|Blvd)\b', re.IGNORECASE),
                re.compile(r'\d+\s+[A-Z][a-z]+,\s+[A-Z]{2}\s+\d{5}\b', re.IGNORECASE)
            ],

            PIIType.PASSPORT: [
                re.compile(r'\b[A-Z]{1,2}\d{6,9}\b')  # US: A1234567
            ],

            PIIType.DRIVER_LICENSE: [
                re.compile(r'\b[A-Z]{1}-\d{4}-\d{4}-\d{4}-\d{4}\b'),  # California format
                re.compile(r'\b\d{8,9}\b')  # Generic numeric
            ],

            PIIType.BANK_ACCOUNT: [
                re.compile(r'\b\d{10,12}\b'),  # US account numbers
                re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{2}\b')  # IBAN partial
            ]
        }

    def detect(self, text: str) -> list[PIIEntity]:
        """Detect all PII in text"""

        entities = []

        for pii_type, patterns in self.patterns.items():
            for pattern in patterns:
                matches = pattern.finditer(text)

                for match in matches:
                    entity = PIIEntity(
                        type=pii_type,
                        text=match.group(),
                        start=match.start(),
                        end=match.end(),
                        confidence=self._calculate_confidence(match.group(), pii_type),
                        redacted_text=self._get_redaction(match.group(), pii_type)
                    )

                    entities.append(entity)

        # Remove overlaps (keep longest match)
        entities = self._remove_overlaps(entities)

        return entities

    def _calculate_confidence(self, text: str, pii_type: PIIType) -> float:
        """Calculate confidence score for detection"""

        base_confidence = 0.8

        # Adjust based on type
        if pii_type == PIIType.EMAIL:
            return 0.95  # Email is very reliable
        elif pii_type == PIIType.SSN:
            return 0.90  # SSN pattern is specific
        elif pii_type == PIIType.PHONE:
            return 0.85  # Phone can have false positives
        elif pii_type == PIIType.CREDIT_CARD:
            return 0.95 if self._luhn_check(text) else 0.70

        return base_confidence

    def _luhn_check(self, card_number: str) -> bool:
        """Luhn algorithm for credit card validation"""

        digits = re.sub(r'\D', '', card_number)

        if len(digits) < 13:
            return False

        total = 0
        reverse_digits = digits[::-1]

        for i, digit in enumerate(reverse_digits):
            n = int(digit)

            if i % 2 == 1:
                n *= 2
                if n > 9:
                    n -= 9

            total += n

        return total % 10 == 0

    def _get_redaction(self, text: str, pii_type: PIIType) -> str:
        """Get redacted version of text"""

        # Common redaction strategies
        if pii_type == PIIType.EMAIL:
            # john.doe@example.com -> j***@example.com
            username, domain = text.split('@')
            return f"{username[0]}***@{domain}"

        elif pii_type in [PIIType.PHONE, PIIType.SSN, PIIType.CREDIT_CARD]:
            # Show last 4 digits only
            return '*' * (len(text) - 4) + text[-4:]

        elif pii_type == PIIType.ADDRESS:
            return "[ADDRESS REDACTED]"

        else:
            return "[REDACTED]"

    def _remove_overlaps(self, entities: list[PIIEntity]) -> list[PIIEntity]:
        """Remove overlapping entities, keep longest"""

        if not entities:
            return []

        # Sort by start position, then by length (descending)
        entities.sort(key=lambda e: (e.start, -(e.end - e.start)))

        filtered = [entities[0]]

        for entity in entities[1:]:
            last = filtered[-1]

            # Check for overlap
            if entity.start < last.end:
                # Keep the longer one
                if (entity.end - entity.start) > (last.end - last.start):
                    filtered[-1] = entity
            else:
                filtered.append(entity)

        return filtered


SAMPLE_TEXT = ("Contact Jane Doe at jane.doe@example.com or 555-123-4567. "
               "SSN: 123-45-6789")

detector = PIIDetector()
entities = detector.detect(SAMPLE_TEXT)
print(len(entities), sorted(e.type.value for e in entities))
# Output: 3 ['email', 'phone', 'ssn']

SAMPLE_TEXT is the shared corpus for the rest of the lesson — the redactor and the pipeline re-detect the same three entities.

NLP-Based Detection

Regex cannot find names — the highest-value indirect identifier. Named-entity recognition can. Install once with uv: uv pip install spacy, then python -m spacy download en_core_web_lg. This fence is compile-checked only: executing it loads a spaCy model.

# pii_nlp_detector.py
# Not executed in this repo: loads a spaCy NER model. Compile-checked only.
import spacy


class NLPPIIDetector:
    """PII detection using NLP models"""

    def __init__(self):
        # Load spaCy model
        self.nlp = spacy.load("en_core_web_lg")

        # PII-related entity labels
        self.pii_labels = {
            'PERSON',      # Names
            'ORG',         # Organizations (workplace)
            'GPE',         # Geopolitical entities (locations)
            'DATE',        # Dates (DOB)
            'TIME',        # Times
            'CARDINAL',    # Numbers (account numbers)
            'EMAIL',       # Emails (if model supports)
            'PHONE',       # Phones (if model supports)
        }

    def detect(self, text: str) -> list[PIIEntity]:
        """Detect PII using NLP"""

        doc = self.nlp(text)
        entities = []

        for ent in doc.ents:
            if ent.label_ in self.pii_labels:
                pii_type = self._map_spacy_to_pii(ent.label_)
                confidence = self._calculate_confidence(ent)

                entity = PIIEntity(
                    type=pii_type,
                    text=ent.text,
                    start=ent.start_char,
                    end=ent.end_char,
                    confidence=confidence,
                    redacted_text=self._get_redaction(ent.text, pii_type)
                )

                entities.append(entity)

        return entities

    def _map_spacy_to_pii(self, spacy_label: str) -> PIIType:
        """Map spaCy labels to PII types"""

        mapping = {
            'PERSON': PIIType.NAME,      # names and employers are indirect identifiers
            'ORG': PIIType.NAME,
            'GPE': PIIType.ADDRESS,
            'DATE': PIIType.DATE_OF_BIRTH,
            'EMAIL': PIIType.EMAIL,
            'PHONE': PIIType.PHONE
        }

        return mapping.get(spacy_label, PIIType.ADDRESS)

    def _calculate_confidence(self, ent) -> float:
        """Calculate confidence based on NLP confidence"""

        # Base confidence from NLP model
        base = 0.70

        # Adjust based on context
        text = ent.text

        if text[0].isupper() and text[-1].isupper():
            base += 0.10  # Acronym-like

        if ent.label_ == 'PERSON' and len(text.split()) >= 2:
            base += 0.15  # Full name

        return min(base, 0.95)

    def _get_redaction(self, text: str, pii_type: PIIType) -> str:
        """Get redacted version"""

        if pii_type == PIIType.DATE_OF_BIRTH:
            return "[DATE REDACTED]"

        # Show first letter for names
        return text[0] + '*' * (len(text) - 1)

PII Redaction

Redaction Strategies

Redaction strength is a policy choice: partial keeps utility for support workflows, placeholder keeps structure for pipelines, full is the compliance default.

# pii_redactor.py
from typing import Literal
import re
import hashlib

RedactionStrategy = Literal[
    'full',           # Complete redaction: [REDACTED]
    'partial',        # Partial redaction: j***@example.com
    'mask',           # Masking: ****-****-****-1234
    'hash',           # Hash replacement: [HASH:abc123]
    'placeholder'     # Generic placeholder: [EMAIL]
]

class PIIRedactor:
    """Redact PII from text"""

    def __init__(
        self,
        detector: PIIDetector,
        default_strategy: RedactionStrategy = 'partial'
    ):
        self.detector = detector
        self.default_strategy = default_strategy

    def redact(
        self,
        text: str,
        strategy: RedactionStrategy | None = None,
        custom_placeholders: dict[PIIType, str] | None = None
    ) -> tuple[str, list[PIIEntity]]:
        """Redact PII from text"""

        # Detect PII
        entities = self.detector.detect(text)

        if not entities:
            return text, []

        # Sort by position (reverse order for replacement)
        entities.sort(key=lambda e: e.start, reverse=True)

        # Apply redaction
        redacted_text = text

        for entity in entities:
            redaction_strategy = strategy or self.default_strategy
            redacted_value = self._apply_redaction(
                entity,
                redaction_strategy,
                custom_placeholders
            )

            # Replace in text
            redacted_text = (
                redacted_text[:entity.start] +
                redacted_value +
                redacted_text[entity.end:]
            )

        return redacted_text, entities

    def _apply_redaction(
        self,
        entity: PIIEntity,
        strategy: RedactionStrategy,
        custom_placeholders: dict[PIIType, str] | None
    ) -> str:

        if custom_placeholders and entity.type in custom_placeholders:
            return custom_placeholders[entity.type]

        if strategy == 'full':
            return "[REDACTED]"

        elif strategy == 'partial':
            return entity.redacted_text

        elif strategy == 'mask':
            # Show only last 4
            return '*' * (len(entity.text) - 4) + entity.text[-4:]

        elif strategy == 'hash':
            # SHA-256, not MD5: GDPR pseudonymization wants a
            # collision-resistant digest, and unsalted MD5 is reversible
            # for low-entropy PII such as emails and phone numbers
            hash_value = hashlib.sha256(entity.text.encode()).hexdigest()[:6]
            return f"[HASH:{hash_value}]"

        elif strategy == 'placeholder':
            return f"[{entity.type.value.upper()}]"

        return entity.redacted_text


redactor = PIIRedactor(PIIDetector())

partial_text, _ = redactor.redact(SAMPLE_TEXT)
print(partial_text)
# Output: Contact Jane Doe at j***@example.com or ********4567. SSN: *******6789

placeholder_text, _ = redactor.redact(SAMPLE_TEXT, strategy="placeholder")
print(placeholder_text)
# Output: Contact Jane Doe at [EMAIL] or [PHONE]. SSN: [SSN]

Both strategies operate on the same three spans the detector found; reversing replacement order keeps earlier offsets valid while later spans are substituted.

Presidio Integration

Presidio replaces the homegrown detector + redactor pair with maintained recognizers and operators. Install once with uv: uv pip install presidio-analyzer presidio-anonymizer (it reuses the spaCy model from the NLP section). Compile-checked only in this repo.

# presidio_redactor.py
# Not executed in this repo: requires the Presidio packages and the spaCy
# model above. Compile-checked only.
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine


class PresidioPIIRedactor:
    """PII redaction using Microsoft Presidio"""

    def __init__(self):
        self.analyzer = AnalyzerEngine()
        self.anonymizer = AnonymizerEngine()

    def redact(
        self,
        text: str,
        operators: dict[str, str] | None = None
    ) -> str:
        """Redact PII using Presidio"""

        # Default operators — operator keys are Presidio entity labels
        # (EMAIL_ADDRESS, US_SSN, ...), and Presidio ships these operators:
        # replace, redact, mask, hash, encrypt, keep, custom
        if operators is None:
            operators = {
                "EMAIL_ADDRESS": "mask",
                "PHONE_NUMBER": "mask",
                "US_SSN": "replace",
                "CREDIT_CARD": "mask",
                "IP_ADDRESS": "hash",
                "PERSON": "redact",
                "LOCATION": "redact"
            }

        # Analyze text
        results = self.analyzer.analyze(
            text=text,
            language='en'
        )

        # Anonymize
        anonymized = self.anonymizer.anonymize(
            text=text,
            analyzer_results=results,
            operators=operators
        )

        return anonymized.text

Secure Data Handling

Encryption at Rest

When redaction is not enough and the original PII must be kept (support refunds, legal holds), encrypt it and keep only a reference in the working system. Install once with uv: uv pip install cryptography.

# secure_storage.py
from cryptography.fernet import Fernet

import hashlib
import json

class SecurePIIStorage:
    """Securely store PII data with encryption"""

    def __init__(self, encryption_key: bytes):
        self.cipher = Fernet(encryption_key)
        self.storage = {}

    def store(
        self,
        user_id: str,
        pii_data: dict[str, str],
        redacted_text: str
    ) -> str:
        """Store encrypted PII"""

        # Encrypt PII data
        pii_json = json.dumps(pii_data)
        encrypted_pii = self.cipher.encrypt(pii_json.encode())

        # Deterministic reference id: hash() is process-randomized in
        # Python and would change across restarts; SHA-256 is stable
        reference_id = f"{user_id}_{hashlib.sha256(encrypted_pii).hexdigest()[:12]}"
        self.storage[reference_id] = {
            'encrypted_pii': encrypted_pii,
            'redacted_text': redacted_text
        }

        return reference_id

    def retrieve(self, reference_id: str) -> dict[str, str]:
        """Retrieve and decrypt PII"""

        if reference_id not in self.storage:
            raise ValueError("Reference not found")

        data = self.storage[reference_id]
        decrypted_pii = self.cipher.decrypt(data['encrypted_pii'])
        pii_data = json.loads(decrypted_pii.decode())

        return pii_data

    def delete(self, reference_id: str) -> bool:
        """Delete PII (GDPR right to be forgotten)"""

        if reference_id in self.storage:
            del self.storage[reference_id]
            return True

        return False


storage = SecurePIIStorage(Fernet.generate_key())
ref = storage.store("user_42", {"email": "jane@example.com"}, "j***@example.com")
print(storage.retrieve(ref) == {"email": "jane@example.com"})
print(storage.delete(ref), storage.delete(ref))
# Output: True
# Output: True False

The round trip decrypts to the original dict, and the second delete returns False — the erasure is verifiable, which is what a GDPR auditor asks for.

Compliance Logging

Every detection, access, and deletion is an auditable event. The log records metadata only — never the raw PII or the raw prompt.

# compliance_logger.py
import logging
from datetime import datetime

import json

class ComplianceLogger:
    """Log PII access for compliance"""

    def __init__(self, log_file: str = "pii_access.log"):
        self.log_file = log_file
        self.logger = logging.getLogger("pii_compliance")
        self.logger.setLevel(logging.INFO)
        self.logger.propagate = False

        # File handler
        handler = logging.FileHandler(log_file)
        handler.setFormatter(
            logging.Formatter('%(asctime)s - %(message)s')
        )
        self.logger.addHandler(handler)

    def log_detection(
        self,
        pii_entities: list[PIIEntity],
        user_id: str,
        document_id: str
    ):
        """Log PII detection event"""

        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'event': 'pii_detection',
            'user_id': user_id,
            'document_id': document_id,
            'pii_count': len(pii_entities),
            'pii_types': [e.type.value for e in pii_entities],
            'action': 'redacted'
        }

        self.logger.info(json.dumps(log_entry))

    def log_access(
        self,
        reference_id: str,
        user_id: str,
        purpose: str
    ):
        """Log PII access event"""

        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'event': 'pii_access',
            'reference_id': reference_id,
            'user_id': user_id,
            'purpose': purpose
        }

        self.logger.info(json.dumps(log_entry))

    def log_deletion(
        self,
        reference_id: str,
        user_id: str,
        reason: str
    ):
        """Log PII deletion event (GDPR)"""

        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'event': 'pii_deletion',
            'reference_id': reference_id,
            'user_id': user_id,
            'reason': reason,
            'gdpr_request': True
        }

        self.logger.info(json.dumps(log_entry))


import tempfile
from pathlib import Path

demo_log = Path(tempfile.gettempdir()) / "pii_compliance_demo.log"
demo_log.unlink(missing_ok=True)  # fresh file so the readback is deterministic

logger = ComplianceLogger(str(demo_log))
logger.log_detection([], "user_42", "doc_2026_001")
logger.log_access("user_42_abc123", "user_42", "support ticket")
logger.log_deletion("user_42_abc123", "user_42", "GDPR erasure request")

lines = demo_log.read_text(encoding="utf-8").strip().split("\n")
# Each record is '<asctime> - <json>' — strip the prefix before parsing
print(len(lines), [json.loads(line.split(" - ", 1)[1])["event"] for line in lines])
# Output: 3 ['pii_detection', 'pii_access', 'pii_deletion']

The demo writes to the OS temp directory, not the repo, and reads the log back to prove all three GDPR-cycle events landed in order.


Production Implementation

End-to-End Pipeline

The pipeline composes detection, redaction, storage, and logging. The NLP detector and the encrypted storage are dependency-injected: wire them when spaCy / cryptography are available, and the pipeline still runs on the regex layer without them — the same graceful degradation the 7501 defense layers use.

# pii_pipeline.py
from datetime import datetime

class PIIPipeline:
    """End-to-end PII handling pipeline.

    nlp_detector and storage are dependency-injected (NLPPIIDetector,
    SecurePIIStorage) so the pipeline executes on stdlib-only pattern
    detection when spaCy / cryptography are absent.
    """

    def __init__(
        self,
        nlp_detector=None,
        storage=None,
        log_file: str | None = None
    ):
        self.detector = PIIDetector()
        self.nlp_detector = nlp_detector
        self.redactor = PIIRedactor(self.detector)
        self.storage = storage
        self.logger = ComplianceLogger(log_file or "pii_access.log")

    def process_input(
        self,
        text: str,
        user_id: str,
        store_pii: bool = False
    ) -> dict:
        """Process input containing potential PII"""

        # Detect PII using multiple methods
        pattern_entities = self.detector.detect(text)
        nlp_entities = self.nlp_detector.detect(text) if self.nlp_detector else []

        # Merge results
        all_entities = self._merge_entities(pattern_entities, nlp_entities)

        # Redact PII
        redacted_text, _ = self.redactor.redact(text)

        result = {
            'original_text': text,
            'redacted_text': redacted_text,
            'pii_count': len(all_entities),
            'pii_types': list(set(e.type for e in all_entities))
        }

        # Optionally store encrypted PII
        if store_pii and all_entities:
            if self.storage is None:
                raise ValueError("store_pii=True requires an injected SecurePIIStorage")
            pii_data = {e.type.value: e.text for e in all_entities}
            reference_id = self.storage.store(user_id, pii_data, redacted_text)
            result['reference_id'] = reference_id

        # Log for compliance
        self.logger.log_detection(
            all_entities,
            user_id,
            f"doc_{datetime.now().strftime('%Y%m%d%H%M%S')}"
        )

        return result

    def _merge_entities(
        self,
        entities1: list[PIIEntity],
        entities2: list[PIIEntity]
    ) -> list[PIIEntity]:
        """Merge entities from multiple detectors"""

        # Combine all entities
        all_entities = entities1 + entities2

        # Remove duplicates
        seen = set()
        unique = []

        for entity in all_entities:
            key = (entity.start, entity.end, entity.type)
            if key not in seen:
                seen.add(key)
                unique.append(entity)

        # Remove overlaps
        return self.detector._remove_overlaps(unique)


import tempfile
from pathlib import Path

demo_log = str(Path(tempfile.gettempdir()) / "pii_pipeline_demo.log")
pipeline = PIIPipeline(log_file=demo_log)
result = pipeline.process_input(SAMPLE_TEXT, "user_42")
print(result["pii_count"], result["redacted_text"])
# Output: 3 Contact Jane Doe at j***@example.com or ********4567. SSN: *******6789

Without spaCy installed, nlp_detector is None, the NLP merge contributes nothing, and the pipeline still redacts all three structured entities — and without an injected storage, store_pii=True fails loudly instead of silently dropping the data.


Testing & Validation

Accuracy Metrics

The validator runs a fixed corpus through the pipeline and reports precision, recall, and F1. The metric is a span-count simplification (real evaluation uses span overlap), but the corpus is honest: it includes a person entity the regex layer cannot find, and the numbers say so.

# pii_validator.py
import tempfile
from pathlib import Path

PII_TEST_CASES = [
    {
        'text': 'Contact John Doe at john.doe@example.com or 555-123-4567',
        'expected_pii': [
            {'type': 'email', 'text': 'john.doe@example.com'},
            {'type': 'phone', 'text': '555-123-4567'},
            {'type': 'person', 'text': 'John Doe'}
        ]
    },
    {
        'text': 'SSN: 123-45-6789, DOB: Jan 15, 1985',
        'expected_pii': [
            {'type': 'ssn', 'text': '123-45-6789'},
            {'type': 'date_of_birth', 'text': 'Jan 15, 1985'}
        ]
    }
]

class PIIValidator:
    """Validate PII detection accuracy"""

    def __init__(self, pipeline: PIIPipeline):
        self.pipeline = pipeline
        self.results = []

    def run_all_tests(self):
        """Run all test cases"""

        for i, test_case in enumerate(PII_TEST_CASES, 1):
            print(f"\nTest Case {i}")

            result = self.pipeline.process_input(
                test_case['text'],
                'test_user'
            )

            # Calculate metrics
            metrics = self._calculate_metrics(
                test_case['expected_pii'],
                result
            )

            self.results.append({
                'test_case': i,
                'metrics': metrics
            })

            print(f"Precision: {metrics['precision']:.2f}")
            print(f"Recall: {metrics['recall']:.2f}")
            print(f"F1: {metrics['f1']:.2f}")

        self._print_summary()

    def _calculate_metrics(self, expected, result):
        """Calculate precision, recall, F1"""

        # Span-count simplification of the real span-overlap metric
        expected_count = len(expected)
        detected_count = result['pii_count']

        # True positives (simplified)
        tp = min(expected_count, detected_count)

        precision = tp / detected_count if detected_count > 0 else 0
        recall = tp / expected_count if expected_count > 0 else 0

        f1 = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0

        return {
            'precision': precision,
            'recall': recall,
            'f1': f1
        }

    def _print_summary(self):
        """Print test summary"""

        avg_precision = sum(r['metrics']['precision'] for r in self.results) / len(self.results)
        avg_recall = sum(r['metrics']['recall'] for r in self.results) / len(self.results)
        avg_f1 = sum(r['metrics']['f1'] for r in self.results) / len(self.results)

        print(f"\n{'='*50}")
        print(f"AVERAGE METRICS")
        print(f"{'='*50}")
        print(f"Precision: {avg_precision:.3f}")
        print(f"Recall: {avg_recall:.3f}")
        print(f"F1 Score: {avg_f1:.3f}")


validator_log = str(Path(tempfile.gettempdir()) / "pii_validator_demo.log")
validator = PIIValidator(PIIPipeline(log_file=validator_log))
validator.run_all_tests()
# Output: Test Case 1
# Output: Precision: 1.00
# Output: Recall: 0.67
# Output: F1: 0.80
# Output: Test Case 2
# Output: Precision: 1.00
# Output: Recall: 1.00
# Output: F1: 1.00
# Output: ==================================================
# Output: AVERAGE METRICS
# Output: ==================================================
# Output: Precision: 1.000
# Output: Recall: 0.833
# Output: F1 Score: 0.900

Read the recall line: Test Case 1 expects three entities, the regex pipeline finds two — john.doe@example.com and 555-123-4567 — and misses John Doe entirely. Recall drops to 0.67 and drags F1 to 0.80. That miss is the argument for the NLP layer and Presidio: wire NLPPIIDetector into the pipeline and the same corpus closes the gap. Test Case 2 scores 1.00 because both SSN and month-name DOB patterns are exact matches. A PII demo that reports perfect scores with a person name in the corpus is a demo that never counted the miss.


Summary

PII in prompts, tool outputs, and logs is a compliance exposure - GDPR, CCPA, HIPAA - before it is a security one, and this lesson builds the handling stack in layers: a regex detector for the patterns you can name, an NER-based detector for the ones you cannot, a redactor with pluggable policies, and the audit trail that proves the handling happened. The rule it leaves: redaction is a pipeline stage, not a promise - if sensitive data can enter a log, assume it will, and strip it before storage, not after discovery.

References


Next Steps