Intermediate 12 minDaily plan

Presidio: masking sensitive data in local

BestLLMfor — Presidio — Local text masking

Presidio is an open-source toolkit published by Microsoft that detects personal data in text (names, email addresses, phone numbers, IBANs…) and then replaces, masks, or encrypts it. It's often used under the label "presidio anonymisation," but what it produces is usually pseudonymization: the text stays linked to real people as long as a table or key lets you reverse the process. This guide walks through the complete pipeline on fictional data, running locally, along with its two blind spots: French and false negatives. QuelLLM did not run any tests for this guide: the examples are based on the official documentation accessed on 30/10/2026, and you'll need to validate the results on your own texts.

By Mohamed Meguedmi·Update 2026-12-03·Tested on Windows, macOS, and Linux
!
What this guide doesn't promise
No tool, Presidio included, guarantees complete anonymization or GDPR compliance. Presidio detects patterns and entities using statistical models: it misses some and invents others. The commands and code below have not been run by QuelLLM; no output or detection rate is given here. Check the installed versions and review every text before sharing it.

#Why mask sensitive data before processing it

Running an LLM locally solves part of the problem: the text doesn't go to an API provider. Yet there are still many points where a document leaves your machine or changes hands: a log excerpt sent to a contractor, a corpus added to a RAG index shared with the whole team, examples pasted into a ticket, a test set for a model, a question sent to a cloud API because the local model isn't enough. In all these cases, removing direct identifiers before sending reduces what can leak.

Presidio is built for this. It installs as a Python library, works offline once the models are downloaded, and does not rely on an external service to analyze text. It does not replace an impact assessment, a retention policy, or proofreading: it is an automated filter, useful for a first pass but not sufficient on its own.

Anonymisation
Under the GDPR (Recital 26), the data no longer allows a person to be identified by any means reasonably likely to be used. It then falls outside the scope of the regulation. This is a high bar: removing names isn't enough if the context (job title, city, date, event) makes it possible to identify the person.
Pseudonymization
Identifiers are replaced with substitutes, but information kept separately (mapping table, encryption key) makes re-identification possible. The data is still personal data and remains subject to the GDPR.
What Presidio does
It replaces or masks what it has detected. With a stored table or key, this is pseudonymization. Without a table, it is partial redaction: the result may remain re-identifiable through what it didn't catch.

#Detect, then transform: Presidio's two engines

The complete kit for building your own AI assistant.

Benefit from our experience and a guided path to build your local assistant and use your AI every day.

  • Lifetime online access
  • PDF + files
  • Refunded within 30 days

Presidio clearly separates two steps, distributed in two Python packages. Understanding them avoids most configuration errors.

presidio-analyzer
The detection engine. It runs the text through a series of "recognizers": regular expressions with validation (credit cards, IBANs, IP addresses…), word lists, and a named entity recognition (NER) model, spaCy's by default. It returns a list of results: entity type, start and end position, confidence score. It doesn't modify the text.
presidio-anonymizer
The transformation engine. It takes the text and the analysis results, and applies an operator to each entity: replace (replace with a label), redact (remove), mask (mask with characters), hash (fingerprint), encrypt (reversible encryption), keep (leave as is), or custom (your own function).
Context words
A recognizer can declare context words ("tél", "courriel", "IBAN") that boost the score when they appear near the detection. The default lists are designed for English.
Other modules
The documentation also describes a module for images (text extracted via OCR and then masked) and a module for structured data. This guide is limited to plain text.

This separation has a practical consequence: the quality of the result depends almost entirely on the analysis. The anonymizer only transforms what it is told about. An entity missed during detection stays in plain text in the final output, with no warning.

#Prerequisites

Python 3 and venv
A Python version supported by Presidio: check the range listed on the presidio-analyzer PyPI page at install time, as it changes between releases.
A French spaCy model
fr_core_news_lg is the most complete of spaCy's standard French models; fr_core_news_md or sm are lighter and generally less accurate. Expect several hundred MB for the large model, downloaded once.
No GPU required
The spaCy models in this guide run on CPU. A local LLM (Ollama on http://localhost:11434) is only useful for the optional step of sending the pseudonymized text.
Fictitious data
For your first tuning runs, never use real files. Create texts with made-up names, addresses at exemple.test, and numbers reserved for fiction (for example, ARCEP reserves ranges starting with 01 99 00 for works of fiction).

#Installing Presidio locally

The documentation installs Presidio with pip. A dedicated virtual environment avoids conflicts with other projects and lets you record exactly which versions you're using.

Terminal — isolated environment and French model
python3 -m venv ~/venvs/presidio
source ~/venvs/presidio/bin/activate
pip install --upgrade pip
pip install presidio-analyzer presidio-anonymizer

# Modèle NER français de spaCy (téléchargé une seule fois)
python -m spacy download fr_core_news_lg

# Noter les versions réellement installées
pip show presidio-analyzer presidio-anonymizer spacy | grep -E '^(Name|Version)'

Keep the output of the last command with your notes: the behavior of the default recognizers has changed from one version to another, and a configuration validated on one version must be rechecked after an update. For long-term use, pin the versions in a requirements.txt file.

i
English by default
When created without configuration, AnalyzerEngine() uses the English model en_core_web_lg and the language "en". It can't analyze French until you provide it with an NLP engine and the language "fr". The documentation also offers Docker images for the analyzer and the anonymizer; check their language configuration before using them on French text.

#Step 1: Detect entities in a fictitious text

The following script creates an analyzer configured for French, then prints each detection with its type, score, and the matching fragment. The text is entirely made up.

detecter.py
from presidio_analyzer import AnalyzerEngine
from presidio_analyzer.nlp_engine import NlpEngineProvider

configuration = {
    'nlp_engine_name': 'spacy',
    'models': [{'lang_code': 'fr', 'model_name': 'fr_core_news_lg'}],
}
moteur_nlp = NlpEngineProvider(nlp_configuration=configuration).create_engine()
analyzer = AnalyzerEngine(nlp_engine=moteur_nlp, supported_languages=['fr'])

texte = (
    "Bonjour, je suis Camille Fictif, joignable au 01 99 00 12 34 "
    "ou à camille.fictif@exemple.test. Je passerai à Lyon le 12 mars "
    "pour voir Maître Durandeau au sujet du dossier de Camille."
)

# Quels recognizers sont actifs pour le français ?
for rec in analyzer.get_recognizers(language='fr'):
    print('recognizer :', rec.name, rec.supported_entities)

# Détections, triées par position
for r in sorted(analyzer.analyze(text=texte, language='fr'), key=lambda r: r.start):
    print(r.entity_type, round(r.score, 2), repr(texte[r.start:r.end]))

The first loop matters most for a first try: it shows which detectors are actually loaded for the language "fr". Depending on the version, you may find that only the spaCy recognizer appears, and that the email, card, or IBAN detectors, declared for English, aren't active. In that case, the email in the sample text won't be flagged, even though it would have been in English.

The second loop displays the results. Read them while asking yourself three questions: was every piece of personal data in the text found? Are the boundaries exact (the full name, not just the first name)? Are there any nonsensical detections? Only set a score threshold (the score_threshold parameter of analyze) after observing these scores on a representative sample: a threshold that is too high increases misses.

#Presidio in French: languages and false negatives

Language support in Presidio relies on two separate things: an NLP model capable of recognizing entities in that language, and recognizers registered for that language. The French spaCy model mainly recognizes people, places, and organizations (PER, LOC, ORG, MISC labels), which Presidio converts according to its mapping table; some labels may be ignored by the default configuration. Numbers, email addresses, and identifiers have to come from pattern-based recognizers.

To fill the gaps, you register recognizers for "fr". The predefined recognizers generally accept a supported_language parameter; a PatternRecognizer lets you add a French-specific pattern, such as a national phone number. Check the class signatures in your installed version.

ajouter_recognizers_fr.py — place after the analyzer is created
from presidio_analyzer import Pattern, PatternRecognizer
from presidio_analyzer.predefined_recognizers import (
    EmailRecognizer, IbanRecognizer, CreditCardRecognizer,
)

# Réutiliser les détecteurs à motifs existants, déclarés pour le français
analyzer.registry.add_recognizer(
    EmailRecognizer(supported_language='fr', context=['courriel', 'mail', 'adresse'])
)
analyzer.registry.add_recognizer(
    IbanRecognizer(supported_language='fr', context=['iban', 'rib', 'virement'])
)
analyzer.registry.add_recognizer(
    CreditCardRecognizer(supported_language='fr', context=['carte', 'cb', 'paiement'])
)

# Téléphone français : 10 chiffres commençant par 0, séparateurs facultatifs
telephone_fr = PatternRecognizer(
    supported_entity='PHONE_NUMBER',
    supported_language='fr',
    name='TelephoneFrRecognizer',
    patterns=[Pattern(name='tel_fr', regex=r'\b0[1-9](?:[ .-]?\d{2}){4}\b', score=0.5)],
    context=['tél', 'téléphone', 'portable', 'joignable', 'appeler'],
)
analyzer.registry.add_recognizer(telephone_fr)

This phone pattern is intentionally simple: it covers neither the international format (+33) nor numbers written out in words or split differently. It may also catch other ten-digit sequences. Adapt it to your documents, then rerun detecter.py to confirm that the new recognizer does appear for "fr".

#Where false negatives come from

Rare or ambiguous names
A surname that is also a common word, a gender-neutral first name, a foreign name, a name in all lowercase in a quick message: the NER model may fail to recognize it as a person.
Repetitions
A person named in full once and then only by first name later on (“Camille” at the end of the sample text): each occurrence is evaluated separately, so the second one may be missed.
Unexpected formats
Numbers with unusual separators, an IBAN split across two lines, an obfuscated email address (“firstname [at] domain”). Checksum validation also rejects numbers that were copied incorrectly.
Indirect identifiers
A unique job title (“the CFO of the Brest site”), a license plate, an internal case number, a forum username: Presidio doesn't know about these without a dedicated recognizer, and context alone may be enough to identify someone.
Out-of-domain text
The spaCy model is trained mostly on written text. Speech transcripts, text messages, technical logs, or text mixing French and English deviate from it.
Wrong language
Analyzing English text with language='fr', or vice versa, degrades detection without raising an error.

False positives also occur (a city mistaken for a person, an order number mistaken for a phone number). They hinder readability, but it's false negatives that expose people. Tune your thresholds to favor recall, then manually fix anything that was masked by mistake.

#Step 2: Pseudonymize with Presidio

The anonymizer's default operator replaces each entity with its type in angle brackets, for example <PERSON>. It's readable, but two different people become indistinguishable, which makes the text unusable for many tasks (summarization, analyzing a conversation). Consistent pseudonymization assigns a stable substitute to each value: <PERSON_1> wherever the same person appears, <PERSON_2> for the next one.

pseudonymiser.py — following detecter.py
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig

resultats = analyzer.analyze(text=texte, language='fr')

# 1. Construire la table AVANT la transformation : (type, valeur) -> pseudonyme
table = {}
for r in sorted(resultats, key=lambda r: r.start):
    cle = (r.entity_type, texte[r.start:r.end])
    if cle not in table:
        rang = sum(1 for (t, _) in table if t == r.entity_type) + 1
        table[cle] = f'<{r.entity_type}_{rang}>'

# 2. Un opérateur custom par type d'entité, qui lit la table sans la modifier
operateurs = {
    t: OperatorConfig('custom', {'lambda': lambda v, t=t: table.get((t, v), f'<{t}>')})
    for t in {r.entity_type for r in resultats}
}

anonymizer = AnonymizerEngine()
sortie = anonymizer.anonymize(text=texte, analyzer_results=resultats, operators=operateurs)
print(sortie.text)

The table is built separately, before calling the anonymizer, for a specific reason: the function passed to the custom operator may be called during parameter validation, with a test value. A function that populates the table on the fly could end up adding spurious entries. Here, it only reads, and returns a generic label if the value is unknown.

Limitation of this method: “Camille Fictif” and “Camille” are two different values, and therefore two pseudonyms. Matching variants of the same name requires an additional rule, which you have to write and verify yourself. For simple masking without a table, replace the custom operators with OperatorConfig('replace', {'new_value': '<PERSONNE>'}) or with the redact operator.

#Optional: send the pseudonymized text to a local LLM

Once the text is pseudonymized, you can hand it to a model served by Ollama, then put the real values back into the response, on your machine. The reverse replacement is reliable only if the model copies the labels verbatim: check the response before reusing it.

resumer_avec_ollama.py — follows pseudonymiser.py
import json
import urllib.request

MODELE = 'qwen3.5:9b'  # remplacez par un modèle présent dans `ollama list`

corps = json.dumps({
    'model': MODELE,
    'prompt': 'Résume ce message en une phrase. Conserve les étiquettes entre chevrons telles quelles.\n\n' + sortie.text,
    'stream': False,
}).encode()
requete = urllib.request.Request(
    'http://localhost:11434/api/generate', data=corps,
    headers={'Content-Type': 'application/json'},
)
reponse = json.loads(urllib.request.urlopen(requete).read())['response']

# Ré-identification locale, uniquement pour l'affichage sur ce poste
inverse = {pseudo: valeur for (_, valeur), pseudo in table.items()}
for pseudo, valeur in inverse.items():
    reponse = reponse.replace(pseudo, valeur)
print(reponse)

This setup makes the most sense when the pseudonymized text has to leave the machine (cloud API, service provider, shared index). With a purely local model, pseudonymization mainly protects the logs, conversation histories, and prompt copies that pile up.

#Protecting the mapping table

As soon as a table or key lets you recover the real values, it concentrates all the risk: it is the list of people in the corpus, along with where they appear. It deserves protection at least equal to that of the original documents.

  1. 01
    Keep it only if it serves a purpose
    If no one needs to recover the real values, never write it to disk: keep it in memory for the duration of processing, or use a non-reversible replacement.
  2. 02
    Keep it separate from the pseudonymized text
    Never in the same folder, the same Git repository, the same archive, or the same attachment. Anyone receiving the text must not be able to access it.
  3. 03
    Restrict access and encrypt
    Read permissions limited to the single account that needs them, storage on an encrypted disk, no copies in a sync service or an unencrypted backup.
  4. 04
    Set a retention period
    Record why the table exists, who has access to it, and when it will be destroyed. Delete it when that date arrives, backups included.
  5. 05
    Log re-identifications
    If someone needs to recover the real values, record who, when, and for what reason.

Presidio's encrypt operator offers an alternative to the table: each entity is AES-encrypted with a key you provide, and DeanonymizeEngine, with the decrypt operator and the same key, restores the values. The table is then replaced by a key, which must be protected in exactly the same way. The encrypted text is no longer readable by a human or usable by an LLM, which limits the value of this option for downstream processing.

chiffrer.py — key-based reversible variant (adapt to your version)
import os
from presidio_anonymizer import AnonymizerEngine, DeanonymizeEngine
from presidio_anonymizer.entities import OperatorConfig

# Clé AES fournie par l'environnement, jamais écrite dans le code
# (longueur attendue : 128, 192 ou 256 bits, voir la documentation)
cle = os.environ['PRESIDIO_CLE']

chiffre = AnonymizerEngine().anonymize(
    text=texte, analyzer_results=resultats,
    operators={'DEFAULT': OperatorConfig('encrypt', {'key': cle})},
)

clair = DeanonymizeEngine().deanonymize(
    text=chiffre.text, entities=chiffre.items,
    operators={'DEFAULT': OperatorConfig('decrypt', {'key': cle})},
)
!
Pseudonymized data = personal data
As long as a table or key exists somewhere, the pseudonymized text remains subject to the GDPR, with the same obligations (legal basis, notice, security, retention period). Pseudonymization is a recommended security measure, not a way out of the regulation. For high-risk processing, have your approach validated by your DPO or a legal advisor.

#Limits of Presidio anonymization and human review

Presidio reduces manual redaction work; it doesn't eliminate it. Plan for human review proportionate to the risk: a full read-through for a document going outside your organization, regular sampling for an automated pipeline.

Building a test set
A set of fictitious but realistic texts, representative of your documents, in which all personal data has been flagged by hand. Rerun it after every change of version, spaCy model, or recognizer, and count the misses.
Review what remains in plain text
A useful review doesn't focus on the labels but on the remaining text: missed names, contextual details, combinations of criteria that point to a single person.
Don't forget metadata
File name, document author, email headers, revision history: Presidio only analyzes the text you pass to it.
Don't publish anything based on the tool alone
No version and no setting guarantees the absence of personal data. A text that has been “run through Presidio” is not an anonymous text.

#Troubleshooting

Error about unsupported language "fr"
The AnalyzerEngine was created without a French NLP engine, or supported_languages does not contain 'fr'. Go back to the configuration in detecter.py.
spaCy model not found
The model was downloaded into a different Python environment. Activate the venv, then rerun python -m spacy download fr_core_news_lg.
Email addresses or IBANs never detected in French
The pattern recognizers aren't declared for 'fr'. Add them with supported_language='fr' and verify with get_recognizers(language='fr').
Recognizer added but has no effect
The recognizer's language doesn't match the one passed to analyze, or the pattern doesn't match the actual format. Test the regular expression on its own against a few examples.
Too many false positives
Raise score_threshold slightly, remove an overly broad recognizer, or restrict the types analyzed with the entities parameter. Then check that recall hasn't dropped on your test set.
Pseudonyms change from one document to the next
The table is recreated on every run. For a corpus, build a shared table, following the protection rules above.

#Go further

Data masking is only one layer. The site's privacy checklist verifies that your local setup sends nothing outside; the GDPR guide places the local LLM in its legal context; securing the Ollama server prevents a text, even a pseudonymized one, from being readable by anyone on the network.

Privacy checklist
Telemetry, open ports, logs: what to check so that local processing stays local.
Local LLM and GDPR
Legal basis, AI Act, CNIL recommendations for business use.
Secure your Ollama server
Authentication, reverse proxy, and network exposure of port 11434.
Did this guide help you?

Feedback, an error, or a clarification? Let us know—it improves the guide for everyone.