FastPII Docs
Reference

API Reference

Complete API reference for FastPII, including the engine, transformation strategies, data models, and registry.

API Reference

FastPII

The main engine class for PII detection, validation, and transformation.

from fastpii import FastPII, DEFAULT_PRIORITY

Constructor

FastPII(*, priority: dict[str, int], confidence_scorer: ConfidenceScorer | None = None)
ParameterTypeRequiredDescription
prioritydict[str, int]YesDetector type to priority mapping. Higher priority wins overlaps.
confidence_scorer`ConfidenceScorerNone`No

Methods

detect

detect(text: str, detector_names: list[str] | None = None) -> DetectionResult

Scan text for PII entities.

ParameterTypeDescription
textstrText to analyze
detector_names`list[str]None`

Returns: DetectionResult

validate

validate(value: str, detector_name: str) -> ValidationResult

Validate a single identifier value.

ParameterTypeDescription
valuestrValue to validate
detector_namestrDetector to use for validation

Returns: ValidationResult

Raises: KeyError if detector not registered

anonymize

anonymize(text: str, replacement: str = "[REDACTED]") -> str

Replace all PII with a fixed placeholder.

redact

redact(text: str) -> str

Replace all PII with type labels like [EMAIL], [RODNE_CISLO].

mask

mask(text: str) -> str

Replace all PII with asterisks preserving span length.

remove

remove(text: str) -> str

Remove all PII from text entirely.

register

register(pack: CountryPack) -> None

Register a country pack and its detectors.

register_many

register_many(packs: list[CountryPack]) -> None

Register multiple country packs.

register_detector

register_detector(detector: Detector) -> None

Register a custom detector.

list_detectors

list_detectors() -> list[Detector]

List all registered detectors.

get_detector

get_detector(name: str) -> Detector

Get a detector by name. Raises KeyError if not found.

Constants

DEFAULT_PRIORITY

DEFAULT_PRIORITY: dict[str, int] = {
    "rodne_cislo": 100, "pesel": 100, "steuer_id": 100, "siren": 100, "insee": 100,
    "ico": 95, "nip": 95, "ust_id": 95, "siret": 95,
    "dic": 90, "regon": 90, "handelsregister": 90,
    "bank_account": 85,
    "address": 80,
    "email": 70,
    "date_of_birth": 60, "date": 60,
    "name": 50,
    "postal_code": 40,
    "vehicle_plate": 30,
    "phone": 20,
}

DEFAULT_CONFIDENCE_SCORES

DEFAULT_CONFIDENCE_SCORES: dict[str, float] = {
    "checksum_validated": 1.0,
    "context_match": 0.95,
    "pattern_match": 0.85,
    "no_context": 0.70,
}

DEFAULT_CONTEXT_BOOST

DEFAULT_CONTEXT_BOOST: float = 0.10

ConfidenceScorer

from fastpii.core.confidence import ConfidenceScorer

Constructor

ConfidenceScorer(base_scores: dict[str, float], context_boost: float)
ParameterTypeDescription
base_scoresdict[str, float]Base confidence scores for each match type
context_boostfloatBoost amount when context matches

Methods

calculate

calculate(has_context: bool, has_checksum: bool = False, base_confidence: float | None = None) -> float

Calculate confidence score based on match context.

ParameterTypeDescription
has_contextboolWhether surrounding context matched
has_checksumboolWhether a checksum was validated
base_confidence`floatNone`

Returns: float between 0.0 and 1.0

TransformationEngine

from fastpii.core.transform import TransformationEngine, AnonymizeStrategy, RedactStrategy, MaskStrategy, RemoveStrategy

apply

TransformationEngine.apply(result: DetectionResult, strategy: TransformationStrategy) -> str

Apply a transformation strategy to all findings in a detection result.

ParameterTypeDescription
resultDetectionResultDetection result from engine.detect()
strategyTransformationStrategyStrategy to apply

Returns: Transformed text string

Built-in strategies

StrategyConstructorOutput
AnonymizeStrategyAnonymizeStrategy(replacement="[REDACTED]")Fixed placeholder
RedactStrategyRedactStrategy()Type label like [EMAIL]
MaskStrategyMaskStrategy()Asterisks preserving span length
RemoveStrategyRemoveStrategy()Empty string (deletes PII)

Custom strategy

from fastpii.core.transform import TransformationStrategy
from fastpii.models import Finding

class MyStrategy:
    def replace(self, finding: Finding, text: str) -> str:
        # Custom transformation logic
        return f"[{finding.type}]"

CountryRegistry

from fastpii.data.registry import CountryRegistry

Methods

MethodDescription
register(code, module_class)Register a country module
get(code)Get a module instance by country code
get_all()Get all registered modules
list_countries()List registered country codes
get_metadata(code)Get metadata for a country
clear()Clear all registrations (for testing)

CountryModule

from fastpii.data.base import CountryModule, CountryData, DataSource, CountryMetadata

Methods

MethodReturn TypeDescription
get_metadata()CountryMetadataCountry metadata
get_bank_codes()CountryData[dict[str, str]]Bank codes
get_cities()CountryData[set[str]]City names
get_postal_codes()CountryData[set[str]]Postal codes
get_names()CountryData[dict[str, set[str]]]Male/female names
get_insurance_codes()CountryData[dict[str, str]]Insurance codes
get_streets()CountryData[set[str]]Street names
get_surnames()CountryData[dict[str, set[str]]]Male/female surnames
get_all_data()dict[str, CountryData]All data types
validate_all()dict[str, bool]Validate all data types
benchmark_import_times()dict[str, float]Benchmark import times

CountryData

class CountryData(ABC, Generic[T]):
    @abstractmethod
    def get_data(self) -> T: ...

    @abstractmethod
    def get_source(self) -> DataSource: ...

    @abstractmethod
    def validate(self) -> bool: ...

    def get_import_time(self) -> float: ...

    def get_entry_count(self) -> int: ...

DataSource

@dataclass(frozen=True)
class DataSource:
    name: str
    url: str
    license: str
    last_updated: datetime
    entry_count: int

CountryMetadata

@dataclass(frozen=True)
class CountryMetadata:
    code: str
    name: str
    language_codes: tuple[str, ...] = ()
    currency_code: str = ""

On this page