Sub topic 10
Using Presidio instead of writing everything yourself
This chapter assumes you have read the earlier chapters on regex detection, checksum validation, NER, and redaction strategies. You should also be comfortable with Python and installing packages with pip. Here you will see how Microsoft Presidio packages those same ideas, and when it is worth using.
What Presidio gives you
Presidio is an open-source library with two parts:
- The analyzer finds personal data. It runs a set of recognizers: regex recognizers with checksums, an NER recognizer backed by spaCy, and context-word boosters. It returns a list of results, each with an entity type, a start and end offset, and a confidence score.
- The anonymizer takes the text and those results, then applies an operator to each span. Operators include
replace,mask,hash, andredact.
These match the span, label, and score model from the hybrid pipeline chapter. Presidio also resolves overlapping spans for you.
The default run
# pip install presidio-analyzer presidio-anonymizer
# python -m spacy download en_core_web_lg
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
text = "My name is John Smith and my email is [email protected]"
analyzer = AnalyzerEngine()
results = analyzer.analyze(text=text, language="en")
anonymizer = AnonymizerEngine()
result = anonymizer.anonymize(text=text, analyzer_results=results)
print(result.text)With default settings, each span is replaced by its entity label, so you should see <PERSON> and <EMAIL_ADDRESS> in the output. The name comes from the NER model, and the email comes from a pattern recognizer.
Custom recognizers and per-entity operators
Built-in recognizers do not know your internal formats. Add your own with PatternRecognizer, then choose an operator for each entity type.
from presidio_analyzer import AnalyzerEngine, Pattern, PatternRecognizer
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
employee_id = PatternRecognizer(
supported_entity="EMPLOYEE_ID",
patterns=[Pattern(name="emp_id", regex=r"\bEMP-\d{6}\b", score=0.8)],
)
analyzer = AnalyzerEngine()
analyzer.registry.add_recognizer(employee_id)
text = "Ticket from EMP-204518, reply to [email protected]"
results = analyzer.analyze(text=text, language="en", score_threshold=0.5)
for r in results:
print(r.entity_type, r.start, r.end, round(r.score, 2))
operators = {
"EMAIL_ADDRESS": OperatorConfig("mask", {"masking_char": "*", "chars_to_mask": 8, "from_end": False}),
"EMPLOYEE_ID": OperatorConfig("replace", {"new_value": "<EMPLOYEE_ID>"}),
"DEFAULT": OperatorConfig("replace"),
}
anonymizer = AnonymizerEngine()
print(anonymizer.anonymize(text=text, analyzer_results=results, operators=operators).text)score_threshold drops low-confidence results. The DEFAULT key covers any entity without its own operator.
Common errors
- Missing spaCy model.
AnalyzerEngine()fails or downloads a small model ifen_core_web_lgis absent. Install the model you intend to use, and keep it the same across environments. - Wrong language. The
languageargument must match a loaded model. Text in another language will be analyzed with English rules and miss entities. - Threshold too high or too low. A high threshold misses real data. A low one floods the output with false positives. Pick it by measuring, as the evaluation chapter describes.
- Irreversible operators. Presidio's
replaceoperator inserts the same label for every match, so you cannot tell two people apart or restore values later. If you need the numbered, reversible placeholders from the previous chapter, build the mapping yourself from the analyzer results, or use Presidio's operator output offsets (result.items) to record what was replaced. - Latency. Loading the NER model is slow. Create the engines once at startup, not per request.
Library or hand-written?
| Situation | Better choice |
|---|---|
| One or two well-defined formats | Your own regex and checksum |
| Many entity types, names, locations | Presidio |
| Strict latency or tiny dependency budget | Your own detectors |
| Internal IDs on top of standard types | Presidio plus custom recognizers |
Exercise
You add a PatternRecognizer for ticket numbers like TKT-00123 and the analyzer returns no result for them. Name two likely causes.
Show answer
Likely causes: the recognizer was not added to the analyzer's registry (for example, addrecognizer was never called on the engine you analyze with), or the regex does not match the text (for example, a missing \b boundary or the wrong digit count). The pattern's score could also be below the scorethreshold passed to analyze, which filters the match out.