Sub topic 10
Using Presidio instead of writing everything yourself
This chapter assumes you can write basic Python, know what a regular expression is, and have read the earlier chapters on regex detection, checksums, NER, and combining detectors into one pipeline. Here you will see how Microsoft Presidio packages those ideas, what it does for you, and where you still have to make decisions.
Why use a toolkit
In the previous chapters you wrote an email regex, a card detector with a Luhn check, and a function that replaces spans with placeholders. That works for a few identifier types. Production systems need more: dozens of entity types, several languages, overlap resolution, confidence scores, context words, and tests. Writing and maintaining all of that yourself is slow and easy to get wrong.
Presidio is an open-source library for detecting and anonymizing personal data. It is split into two packages:
presidio-analyzerfinds entities in text. It returns a list of results, each with an entity type, a start and end offset, and a score.presidio-anonymizertakes the text and those results and applies an operator to each span, such as replacing, masking, hashing, or redacting.
This split matches the pipeline you already know: detect spans, then redact them. The two packages communicate through plain data (spans and labels), so you can use the analyzer with your own redaction code, or feed the anonymizer spans from a detector you wrote.
How the analyzer works internally
The analyzer runs a set of recognizers over the text. Each recognizer is responsible for one or more entity types. There are three common kinds:
- Pattern recognizers hold one or more regular expressions with a base score. Examples are email addresses, IP addresses, and phone numbers.
- Pattern recognizers with validation add a check after the match, such as a Luhn checksum for credit cards. This is the same idea as the card detector you wrote earlier.
- NER-based recognizers use a language model pipeline, by default spaCy, to find names, locations, and organizations.
After all recognizers run, the analyzer merges results. It removes duplicates and resolves some overlaps, and it can raise a score when context words appear near a match. For example, a nine-digit number scores higher when the word "ssn" is nearby. The result is one list of RecognizerResult objects.
A first run
The example below installs the packages, downloads a spaCy model, detects entities, and anonymizes them with default settings.
# 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)The output is similar to My name is <PERSON> and my email is <EMAIL_ADDRESS>. By default the anonymizer replaces each span with its entity type in angle brackets.
Printing the analyzer results shows what the detectors found:
from presidio_analyzer import AnalyzerEngine
text = "My name is John Smith and my email is [email protected]"
analyzer = AnalyzerEngine()
for r in analyzer.analyze(text=text, language="en"):
print(r.entity_type, text[r.start:r.end], round(r.score, 2))Each result has an entity_type, start, end, and score. Treat the score as a ranking signal, not a probability. An email pattern match scores very high, while a NER match for a person name is lower and depends on the model.
Choosing entities and thresholds
By default the analyzer looks for every entity type it has a recognizer for. In an application you usually narrow this. Restricting entities reduces false positives and cost, and a score threshold lets you trade precision against recall.
from presidio_analyzer import AnalyzerEngine
analyzer = AnalyzerEngine()
text = "Call Maria Lopez at 212-555-0147 or write to [email protected]"
results = analyzer.analyze(
text=text,
language="en",
entities=["PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER"],
score_threshold=0.4,
)
for r in results:
print(r.entity_type, text[r.start:r.end], round(r.score, 2))Choose the threshold from data, not by guessing. The measurement chapter shows how to compute precision and recall on a labelled set. Lowering the threshold finds more real entities and also more false ones. For a model call that sends text to a third party, many teams prefer higher recall and accept some over-redaction.
Choosing operators in the anonymizer
The anonymizer applies an operator per entity type. Operators map to the strategies from the redaction chapter:
| Operator | Effect | Typical use |
|---|---|---|
| `replace` | Substitutes a fixed string such as `<PERSON>` | Prompts where the model needs to know a name was there |
| `redact` | Removes the span entirely | Logs where the type does not matter |
| `mask` | Overwrites characters with a mask character | Showing the last four digits of a card |
| `hash` | Replaces with a SHA-256 or similar digest | Joining records without exposing values |
| `encrypt` | Encrypts with a key; `decrypt` reverses it | Reversible pseudonymization |
You pass operators as a dictionary keyed by entity type. The key DEFAULT applies to any type you do not list.
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
text = "Pay with card 4111 1111 1111 1111. Contact [email protected]"
analyzer = AnalyzerEngine()
results = analyzer.analyze(
text=text,
language="en",
entities=["CREDIT_CARD", "EMAIL_ADDRESS"],
)
operators = {
"CREDIT_CARD": OperatorConfig(
"mask",
{"masking_char": "*", "chars_to_mask": 12, "from_end": False},
),
"EMAIL_ADDRESS": OperatorConfig("replace", {"new_value": "<EMAIL>"}),
"DEFAULT": OperatorConfig("replace", {"new_value": "<REDACTED>"}),
}
anonymizer = AnonymizerEngine()
out = anonymizer.anonymize(
text=text, analyzer_results=results, operators=operators
)
print(out.text)The card number keeps only its last four digits, and the email becomes <EMAIL>.
Reversible pseudonymization with encrypt
The earlier chapter built a mapping from placeholders to originals and kept it in memory. Presidio offers a different approach: the encrypt operator replaces each value with ciphertext, and a DeanonymizeEngine decrypts it later. The key must be 128, 192, or 256 bits (16, 24, or 32 characters).
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine, DeanonymizeEngine
from presidio_anonymizer.entities import OperatorConfig, OperatorResult
KEY = "WmZq4t7w!z%C&F)J" # demo only; load a real key from a secrets store
text = "Email [email protected] about the invoice."
analyzer = AnalyzerEngine()
results = analyzer.analyze(text=text, language="en", entities=["EMAIL_ADDRESS"])
anonymized = AnonymizerEngine().anonymize(
text=text,
analyzer_results=results,
operators={"EMAIL_ADDRESS": OperatorConfig("encrypt", {"key": KEY})},
)
print(anonymized.text)
restored = DeanonymizeEngine().deanonymize(
text=anonymized.text,
entities=anonymized.items,
operators={"DEFAULT": OperatorConfig("decrypt", {"key": KEY})},
)
print(restored.text)Encrypted values are long and unreadable to a model. A model cannot reason about "this is an email at the same company as the other one" from ciphertext, and it may mangle the string in its reply, which breaks decryption. The placeholder approach (<EMAIL_1>) from the reversible pseudonymization chapter is usually better for LLM prompts. Use encrypt when the redacted text is stored or passed between systems and you need a keyed way back, not when a model must read it.
Adding your own recognizer
Presidio will not know your internal identifiers, such as an employee ID like EMP-123456. You add a pattern recognizer and register it.
from presidio_analyzer import AnalyzerEngine, Pattern, PatternRecognizer
employee_pattern = Pattern(
name="employee_id", regex=r"\bEMP-\d{6}\b", score=0.8
)
employee_recognizer = PatternRecognizer(
supported_entity="EMPLOYEE_ID",
patterns=[employee_pattern],
context=["employee", "staff", "badge"],
)
analyzer = AnalyzerEngine()
analyzer.registry.add_recognizer(employee_recognizer)
text = "Badge issued to EMP-123456 yesterday."
for r in analyzer.analyze(text=text, language="en"):
print(r.entity_type, text[r.start:r.end], round(r.score, 2))The context list raises the score when those words appear near the match. The same mechanism lets you add deny lists, which are fixed lists of terms such as project code names.
Gotchas and failure modes
- Model download and startup time.
AnalyzerEngine()loads a spaCy model, which can take seconds and hundreds of megabytes. Create the engine once at application start, not per request. - Language support. The default configuration is for English. Other languages need a matching NER model and recognizers that support that language code. Passing
language="de"without configuration raises an error. - Score is not a probability. Scores from different recognizers are not calibrated against each other. Compare them only after measuring on your own data.
- Overlaps. A phone number and a date may overlap on the same digits. The analyzer resolves some of these, but check the output on your data rather than assuming.
- NER misses and false hits. Lowercase names, unusual names, and product names that look like people are common errors. Regex-based types are far more predictable than
PERSONorLOCATION. - Offsets refer to the original text. If you modify the text between analysis and anonymization, the spans no longer line up.
- Defaults are generic. Built-in recognizers target common formats, such as US-style identifiers. Verify that the ones you rely on cover your region.
Build or adopt: decision criteria
| Situation | Suggestion |
|---|---|
| A few structured types (email, one ID format), strict dependency limits | Your own regex and checksum code |
| Many entity types, names and places needed | Presidio |
| Several languages or custom NER models | Presidio with a configured NLP engine |
| Hard latency budget on every request | Measure first; NER dominates cost, so consider restricting entities or using a smaller model |
| Need for custom identifiers | Presidio with custom recognizers |
A common middle path is to use Presidio as the engine and keep a thin wrapper of your own. The wrapper from the earlier chapter still applies: detect, redact, call the model, restore. Only the detect function changes.
from presidio_analyzer import AnalyzerEngine
analyzer = AnalyzerEngine()
def detect(text):
results = analyzer.analyze(
text=text,
language="en",
entities=["PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "CREDIT_CARD"],
score_threshold=0.4,
)
return [(r.start, r.end, r.entity_type) for r in results]
print(detect("Reach John Smith at [email protected]"))Because detect returns (start, end, label) tuples, it plugs directly into the redact and answer_with_redaction functions you wrote earlier. If two spans overlap, remove the lower-scoring one before passing them to redact, since that function expects non-overlapping spans.
Exercise
You run the analyzer with the default settings on user messages and see false positives on product names that look like people. You also need to restore the original values in the model's reply. Which two changes would you make, and which anonymizer operator would you choose for the restore requirement?
Show answer
Restrict the entities list and raise score_threshold (after measuring precision and recall on labelled examples) to cut false positives, and optionally add a deny list or allow list for known product names. For restoring values in the reply, use replace with numbered placeholders and a local mapping (as in the earlier wrapper), because a model can read and reuse <PERSON_1>. The encrypt operator produces ciphertext that the model cannot use well and may alter, which would break decryption.
Exercise
Write a Presidio custom recognizer for ticket numbers of the form TCK- followed by eight digits, with the entity name TICKET_ID, and state where it must be registered for analyzer.analyze to use it.
Show answer
Create PatternRecognizer(supported_entity="TICKET_ID", patterns=[Pattern(name="ticket", regex=r"\bTCK-\d{8}\b", score=0.8)]) and register it with analyzer.registry.add_recognizer(recognizer) on the AnalyzerEngine instance that you call. Add it before analyzing, and include TICKET_ID in the entities argument if you restrict entities.