Find personal data¶
At the end of this guide you will find personal data in customer messages, mask it by its position before the text goes anywhere else, add names and addresses with a model, switch on the opt-in number formats, and tune the result when it reports too much or too little.
The running example: a support chatbot must not forward customer personal data (IBANs, phone numbers, e-mail addresses, tax IDs, names) to the language model. Every customer message is scanned first, and every finding is replaced by its label.
Before you start¶
- Install the Python package (
pip install patronus-ark) or add the Rust cratespatronus-arkandpatronus-ark-core; see Installation. - Steps 1 to 5 and 7 use only L1: fast rules with validators (check digits, formats), no model files and no network. Step 6 downloads a model of about 130 MB from Hugging Face on first use.
- Two terms used throughout:
- A category is one kind of risk the scanner checks. This guide uses
pii(personal identifiers found by rules) anddynamic-pii(names, places and other free-text entities found by a model). See Categories. - A level is how much work the scanner spends: L1 rules, L2 small classifier
models, L3 larger transformer models.
piiruns at L1 only;dynamic-piiruns at L3 only. See Analysis framework.
- A category is one kind of risk the scanner checks. This guide uses
All test data on this page is made up. The IBAN DE89370400440532013000 is the common German
example IBAN.
What pii finds¶
pii reports identifiers with a fixed form: values a rule can recognize and, where the format
has one, verify with a check digit. Each finding has a label:
| Group | Labels (examples) |
|---|---|
| Contact and network | EMAIL, PHONE, IP_ADDRESS, MAC_ADDRESS, USERNAME |
| Payment and banking | IBAN, CREDITCARD, CREDITCARD_CVV, CREDITCARD_EXPIRY, FINANCIAL_ACCOUNT_NUMBER, SWIFT_CODE, CRYPTO |
| National and tax IDs | STEUERID, TAX_NUMBER_DE, SOCIALID, SSN, NATIONALID (UK NINO), CA_SIN, FR_NIR, NL_BSN, ES_NIF, IT_FISCAL_CODE, PL_PESEL, IN_AADHAAR, … |
| Health | HEALTH_INSURANCE_NUMBER, PHYSICIAN_NUMBER_LANR, FACILITY_NUMBER_BSNR, NHS_NUMBER, US_NPI, PATIENT_ID |
| Documents and vehicles | PASSPORT_NUMBER, IDENTITY_CARD_NUMBER, DRIVER_LICENSE_NUMBER, LICENSEPLATE, VIN |
| Business and records | VAT_ID_DE and the other EU VAT IDs, COMMERCIAL_REGISTER_DE, CUSTOMER_ID, EMPLOYEE_ID, DOB, … |
| Devices | IMEI, MEID, ICCID, IMSI |
That is 107 labels from 213 rules; 83 identifier types have check-digit validation. The full list with every rule, its check and its default state is in L1 capabilities: PII coverage.
pii does not find names, places, organisations or street addresses: they have no fixed form.
Step 6 adds them with dynamic-pii.
Step 1: Scan a customer message¶
Create a gateway for the pii category at max_level l1 and scan one message. The gateway is
built once and reused for every message.
from patronus_ark import SecurityGateway
scanner = SecurityGateway({"categories": ["pii"], "max_level": "l1"})
message = (
"Hi, this is Jane Doe. My order 4711 never arrived. "
"Please refund it to DE89370400440532013000 or call me at +49 30 901820. "
"My e-mail is jane.doe@example.com."
)
report = scanner.scan_all(message)
for result in report["native"]:
print(result["category"], result["level"], result["class_name"], result["confidence"])
for span in result["evidence_spans"]:
print(" ", span["label"], "characters", span["start_char"], "to", span["end_char"])
use patronus_ark::{GatewayConfig, SecurityGateway};
use patronus_ark_core::{cascade::SecurityLevel, SecurityCategory};
fn main() {
let config = GatewayConfig::new(vec![SecurityCategory::Pii], SecurityLevel::L1);
let scanner = SecurityGateway::new(config).expect("valid config");
let message = "Hi, this is Jane Doe. My order 4711 never arrived. \
Please refund it to DE89370400440532013000 or call me at +49 30 901820. \
My e-mail is jane.doe@example.com.";
for result in scanner.scan_all(message).native {
for span in &result.evidence_spans {
println!("{} bytes {}-{}", span.label, span.start_byte, span.end_byte);
}
}
}
Output (Python):
Output (Rust):
There is one result for the category. class_name is not safe, so the message contains personal
data; it names one label (here EMAIL), not all of them. Read evidence_spans for every
finding: each span has the label, the matched text, a score and its position as
character offsets (start_char/end_char) and byte offsets (start_byte/end_byte). The
order number 4711 and the name Jane Doe are not reported: the first is not personal data, the
second has no fixed form (see Step 6).
In the default mode strict, every finding has confidence and score 1.0: the rule and its
validator decide alone. Step 4 shows the scored modes.
Step 2: Mask the findings before forwarding¶
The chatbot replaces every finding with its label and sends only the masked text to the language
model. Use character offsets with Python strings and byte offsets with Rust strings (they differ
as soon as the text has non-ASCII characters such as ö). Spans of different labels can overlap
(for example digits inside an IBAN that also pass another validator), so sort them and skip any
span that starts inside one that is already masked.
from patronus_ark import SecurityGateway
def mask(text, spans):
"""Replace every finding with its label, e.g. [EMAIL]. Overlapping spans are merged."""
merged = [] # longest span first among those that start together
for span in sorted(spans, key=lambda s: (s["start_char"], -s["end_char"])):
if merged and span["start_char"] < merged[-1][1]:
merged[-1][1] = max(merged[-1][1], span["end_char"]) # overlap: extend
else:
merged.append([span["start_char"], span["end_char"], span["label"]])
out, pos = [], 0
for start, end, label in merged:
out.append(text[pos:start])
out.append(f"[{label}]")
pos = end
out.append(text[pos:])
return "".join(out)
scanner = SecurityGateway({"categories": ["pii"], "max_level": "l1"})
message = (
"Hi, this is Jane Doe. My order 4711 never arrived. "
"Please refund it to DE89370400440532013000 or call me at +49 30 901820. "
"My e-mail is jane.doe@example.com."
)
spans = []
for result in scanner.scan_all(message)["native"]:
spans.extend(result["evidence_spans"])
print(mask(message, spans))
use patronus_ark::{GatewayConfig, SecurityGateway};
use patronus_ark_core::{cascade::SecurityLevel, SecurityCategory};
/// Replace every finding with its label, e.g. `[EMAIL]`. Spans may overlap, so they
/// are sorted and merged first. Rust strings are sliced by byte offsets.
fn mask(text: &str, mut spans: Vec<(usize, usize, String)>) -> String {
// Longest span first among those that start together.
spans.sort_by_key(|(start, end, _)| (*start, std::cmp::Reverse(*end)));
let mut merged: Vec<(usize, usize, String)> = Vec::new();
for (start, end, label) in spans {
match merged.last_mut() {
Some(last) if start < last.1 => last.1 = last.1.max(end), // overlap: extend
_ => merged.push((start, end, label)),
}
}
let mut out = String::new();
let mut pos = 0;
for (start, end, label) in merged {
out.push_str(&text[pos..start]);
out.push_str(&format!("[{label}]"));
pos = end;
}
out.push_str(&text[pos..]);
out
}
fn main() {
let config = GatewayConfig::new(vec![SecurityCategory::Pii], SecurityLevel::L1);
let scanner = SecurityGateway::new(config).expect("valid config");
let message = "Hi, this is Jane Doe. My order 4711 never arrived. \
Please refund it to DE89370400440532013000 or call me at +49 30 901820. \
My e-mail is jane.doe@example.com.";
let mut spans = Vec::new();
for result in scanner.scan_all(message).native {
for span in &result.evidence_spans {
spans.push((span.start_byte, span.end_byte, span.label.clone()));
}
}
println!("{}", mask(message, spans));
}
Output (Python and Rust):
Hi, this is Jane Doe. My order 4711 never arrived. Please refund it to [IBAN] or call me at [PHONE]. My e-mail is [EMAIL].
The language model still sees what the customer wants, but not the identifiers. Keep the original text only where you must (for example in your own ticket system), and log only the masked one.
Step 3: Scan German messages¶
The rules and the context words they use are German and English, so the same gateway handles both languages; there is no language setting. German identifiers such as the tax ID (Steuer-ID), the tax number, the pension insurance number or the doctor number (LANR) have their own rules with check digits.
from patronus_ark import SecurityGateway
scanner = SecurityGateway({"categories": ["pii"], "max_level": "l1"})
message = (
"Hallo, hier ist Erika Mustermann. Für die Rückerstattung: "
"IBAN DE89370400440532013000, Steuer-ID 86095742719, Telefon 030 901820."
)
for result in scanner.scan_all(message)["native"]:
for span in result["evidence_spans"]:
print(span["label"], "characters", span["start_char"], "to", span["end_char"])
Output:
The Steuer-ID is reported as STEUERID because it follows its field name and passes the check
digit. A German phone number without a country code, such as 030 901820, needs a phone word
or phrase next to it (Telefon, Tel., erreichbar unter, Sie erreichen mich unter,
Meine Nummer ist, bitte melden:, gerne unter … anrufen, … ist meine Handynummer); in a
phrasing without any of them it can stay unreported. Text in other languages still gets every identifier with a fixed form (an IBAN or a
card number looks the same in every language), but the field names and context words that some
rules need are German and English only.
Step 4: Find numbers without a field name (balanced)¶
Customers do not always write the field name directly before the value. In the default mode
strict, many rules need it; in the mode balanced the scanner also scores a value by its
validator and by nearby words, and reports it when the score reaches 0.50. Set the mode with the
pii_mode key.
from patronus_ark import SecurityGateway
message = "Meine Steuer-ID lautet 86 095 742 719, bitte für die Rechnung verwenden."
for mode in ["strict", "balanced"]:
scanner = SecurityGateway({"categories": ["pii"], "max_level": "l1", "pii_mode": mode})
for result in scanner.scan_all(message)["native"]:
print(mode, result["class_name"], result["confidence"])
for span in result["evidence_spans"]:
print(" ", span["label"], "characters", span["start_char"], "to", span["end_char"], "score", span["score"])
Output:
strict does not report the grouped Steuer-ID, because the word lautet stands between field name
and value. balanced reports it with score 0.8: the check digit is valid and Steuer-ID is near.
In the scored modes confidence is the highest span score, so you can set your own cut-off on top.
pii_mode |
Reports | Score |
|---|---|---|
strict (default) |
Rule matches only. Lowest false-positive rate. | always 1.0 |
balanced |
Also values found by validator and context. Findings below 0.50 are dropped. |
0–1 |
recall |
Like balanced with the cut-off at 0.30, plus spelled-out forms such as jane [at] example [dot] com. |
0–1 |
How the score is computed (rule base, validator strength, context words and counter-words such as
"order number") is described in PII score and modes.
In Rust, set ScanGateMatrix { pii_mode: ScoreMode::Balanced, ..Default::default() } and pass it
with GatewayConfig::with_gates.
Step 5: Switch on bare number formats¶
Some identifiers are plain digits, or letters and digits, that look like any other number when
they stand alone: a US passport number, a nine-digit Canadian SIN or US SSN, a German BSNR. The
default rules, even in balanced, report them only with their field name or a word of their
label nearby, because a bare nine-digit number is usually an order, invoice or record number. For
data where such numbers do stand alone, each of these forms has an opt-in bare rule
(<rule>_bare), off in every mode.
The repository ships two ready-made gate files that switch them on:
| File | Contents |
|---|---|
pii-bare-formats.gates.json |
pii_mode balanced plus all 23 bare rules (German Steuer-ID, tax number, LANR, BSNR and driver's licence; US SSN, ABA routing number and passport; Canadian SIN, Aadhaar, PAN, PESEL, UK and Indian plates, and more). |
pii-presidio-compat.gates.json |
The bare profile plus three compatibility rules that report values the default rules reject on purpose: loopback addresses such as 127.0.0.1 and never-assigned US SSNs. Meant for comparisons with Presidio, which reports such values. |
A gate file is plain JSON in the shape of the gateway's gate keys (pii_mode, rules). Download
it from the repository (for example
curl -O https://raw.githubusercontent.com/patronus-protect/patronus-security/main/docs/how-to/pii-bare-formats.gates.json)
and merge it into the gateway config:
import json
from patronus_ark import SecurityGateway
with open("pii-bare-formats.gates.json") as f:
bare_gates = json.load(f)
messages = [
"Please add A12803456 to my booking.",
"Please put 435418165 on the form.",
]
for name, gates in [("default", {}), ("bare formats", bare_gates)]:
scanner = SecurityGateway({"categories": ["pii"], "max_level": "l1", **gates})
for message in messages:
for result in scanner.scan_all(message)["native"]:
labels = [(s["label"], s["start_char"], s["end_char"], s["score"]) for s in result["evidence_spans"]]
print(f"{name:<13}", result["class_name"], labels)
use patronus_ark::{GatewayConfig, SecurityGateway};
use patronus_ark_core::{cascade::{ScanGateMatrix, SecurityLevel}, SecurityCategory};
fn main() {
let json = std::fs::read_to_string("pii-bare-formats.gates.json").expect("gate file");
let gates: ScanGateMatrix = serde_json::from_str(&json).expect("valid gates");
let config = GatewayConfig::new(vec![SecurityCategory::Pii], SecurityLevel::L1).with_gates(gates);
let scanner = SecurityGateway::new(config).expect("valid config");
for message in ["Please add A12803456 to my booking.", "Please put 435418165 on the form."] {
for result in scanner.scan_all(message).native {
for span in &result.evidence_spans {
println!("{} bytes {}-{} score {:.2}", span.label, span.start_byte, span.end_byte, span.score);
}
}
}
}
Add serde_json to Cargo.toml (cargo add serde_json).
Output (Python):
default safe []
default safe []
bare formats PASSPORT_NUMBER [('PASSPORT_NUMBER', 11, 20, 0.5)]
bare formats FACILITY_NUMBER_BSNR [('FACILITY_NUMBER_BSNR', 11, 20, 0.5), ('SSN', 11, 20, 0.5), ('CA_SIN', 11, 20, 0.5)]
Output (Rust):
PASSPORT_NUMBER bytes 11-20 score 0.50
FACILITY_NUMBER_BSNR bytes 11-20 score 0.50
SSN bytes 11-20 score 0.50
CA_SIN bytes 11-20 score 0.50
With the profile, the passport number is found without its field name. The second line shows
the price: nine bare digits fit three formats at once (a BSNR, a US SSN and a Canadian SIN), and
every bare finding scores exactly the balanced threshold 0.50. Bare rules still refuse values
inside longer numbers, under a key that names another value, or next to words such as "order" or
"invoice"; the exact rules are in Bare formats.
Enable only the forms your data actually holds. One bare rule can be switched on by its id in
rules, without the rest of the profile and in any mode:
from patronus_ark import SecurityGateway
scanner = SecurityGateway(
{"categories": ["pii"], "max_level": "l1", "rules": {"pii_passport_number_us_bare": True}}
)
for result in scanner.scan_all("Please add A12803456 to my booking.")["native"]:
print(result["class_name"], [(s["label"], s["start_char"], s["end_char"], s["score"]) for s in result["evidence_spans"]])
Output:
In strict the finding scores 1.0, like every strict finding.
Step 6: Add names and addresses (dynamic-pii)¶
Names, cities and street addresses have no fixed form, so no rule can find them reliably.
dynamic-pii runs a GLiNER model at L3: a small transformer that finds entities for labels
you choose at runtime (person, city, street address, organization, date, …). It runs
next to pii, which keeps finding the structured identifiers.
dynamic-pii needs max_level l3 and its model files (about 130 MB, downloaded once with
"download": "missing"). Call warmup() before the first scan; without the loaded model, Python
raises an error instead of silently returning no result.
from patronus_ark import SecurityGateway
scanner = SecurityGateway(
{
"categories": ["pii", "dynamic-pii"],
"max_level": "l3",
"download": "missing",
"dynamic_pii": {"labels": ["person", "street address", "city"], "threshold": 0.5},
}
)
scanner.warmup()
messages = [
"Hi, this is Jane Doe. My order 4711 never arrived at Example Street 12, Springfield. "
"Please call me at +49 30 901820.",
"Hallo, hier ist Erika Mustermann aus Köln, Musterstraße 5. Telefon: 030 901820.",
]
for message in messages:
print("---")
for result in scanner.scan_all(message)["native"]:
for span in result["evidence_spans"]:
print(f'{result["category"]:<12} {span["label"]:<15} characters {span["start_char"]}-{span["end_char"]} score {span["score"]:.3f}')
use patronus_ark::{GatewayConfig, SecurityGateway};
use patronus_ark_core::{cascade::SecurityLevel, DownloadPolicy, SecurityCategory};
fn main() {
let mut config = GatewayConfig::new(
vec![SecurityCategory::Pii, SecurityCategory::DynamicPii],
SecurityLevel::L3,
);
config.core.download = DownloadPolicy::Missing;
config.dynamic_pii.labels = ["person", "street address", "city"].map(String::from).to_vec();
config.dynamic_pii.threshold = 0.5;
let mut scanner = SecurityGateway::new(config).expect("valid config");
scanner.warmup().expect("warmup");
let messages = [
"Hi, this is Jane Doe. My order 4711 never arrived at Example Street 12, Springfield. \
Please call me at +49 30 901820.",
"Hallo, hier ist Erika Mustermann aus Köln, Musterstraße 5. Telefon: 030 901820.",
];
for message in messages {
println!("---");
for result in scanner.scan_all(message).native {
for span in &result.evidence_spans {
println!(
"{:<12} {:<15} bytes {}-{} score {:.3}",
result.category, span.label, span.start_byte, span.end_byte, span.score
);
}
}
}
}
Output (Python):
---
pii PHONE characters 103-116 score 1.000
dynamic-pii person characters 12-20 score 0.988
dynamic-pii street address characters 53-70 score 0.948
dynamic-pii city characters 72-83 score 0.955
---
pii PHONE characters 68-78 score 1.000
dynamic-pii person characters 16-32 score 0.989
dynamic-pii city characters 37-41 score 0.947
dynamic-pii street address characters 43-57 score 0.932
dynamic-pii street address characters 68-78 score 0.640
Output (Rust):
---
pii PHONE bytes 103-116 score 1.000
dynamic-pii person bytes 12-20 score 0.988
dynamic-pii street address bytes 53-70 score 0.948
dynamic-pii city bytes 72-83 score 0.955
---
pii PHONE bytes 70-80 score 1.000
dynamic-pii person bytes 16-32 score 0.989
dynamic-pii city bytes 37-42 score 0.947
dynamic-pii street address bytes 44-59 score 0.932
dynamic-pii street address bytes 70-80 score 0.640
The dynamic-pii result has the class entities; its spans carry your labels and the model's
score. The model handles English and German text. In the German message the byte offsets
(Rust) are larger than the character offsets (Python) after Köln, because ö takes two bytes.
The last line is a mistake of the model: it also reads the phone number as a street address, with
a lower score (0.640). For masking this does no harm, since pii already covers the same range
and the mask function merges overlaps; Step 7 shows how to raise the threshold for one label.
What it costs. pii alone took well under a millisecond per short chat message in our runs
(Apple M1 CPU). With dynamic-pii the same messages took a median of 70 to 240 ms, depending on
the run, plus a few seconds of warmup and about 130 MB of model files on disk and in memory. A
repeated identical text is answered from the result cache (see
Configure caching). Use dynamic-pii where free-text entities matter, and
consider gating it: its execution_gate key runs it only when another category's result
matches (example in Dynamic PII).
dynamic_pii key |
Meaning |
|---|---|
labels |
The entity labels to find, in plain words. Default: organization, date, person, city, country. |
threshold |
Lowest score to report (default 0.5). |
label_thresholds |
Per-label thresholds, e.g. {"street address": 0.8}. |
execution_gate |
always (default), or run only if_result_in / if_no_result of another category. |
Chunking, size limits and timeouts are in Dynamic PII.
Step 7: Tune false positives¶
A finding you do not want has one of three causes, each with its own fix.
A rule matches something that is not personal data. A version number with four parts looks
like an IPv4 address when no word such as version, build or release stands right before
it. Find the rule id in the result's matched_rules and switch it off with
rules:
from patronus_ark import SecurityGateway
message = "I updated the app to 10.2.0.1 and now it crashes at start."
scanner = SecurityGateway({"categories": ["pii"], "max_level": "l1"})
result = scanner.scan_all(message)["native"][0]
print(result["class_name"])
for rule in result["layers"][0]["details"]["matched_rules"]:
print(" rule", rule["rule_id"], "bytes", rule["start_byte"], "to", rule["end_byte"])
tuned = SecurityGateway({"categories": ["pii"], "max_level": "l1", "rules": {"pii_ipv4": False}})
print("with pii_ipv4 off:", tuned.scan_all(message)["native"][0]["class_name"])
Output:
Switching a rule off removes it for every text, so do it only for labels your use case does not
need (a support chatbot for a shop may not care about IP addresses). The ids of all rules are in
the L1 rule catalog. Rule switches can also be
sent per request (enqueue(text, execution_gates={"rules": {...}})).
A scored mode or a bare rule reports too much. Go back one step: from recall to balanced,
from balanced to strict, or enable fewer bare rules (Steps 4 and 5). strict with no bare
rules is the default because it has the fewest false positives.
The model reports a wrong entity. Raise the threshold of that label. With
"label_thresholds": {"street address": 0.8} the German message of Step 6 loses the misread
phone number and keeps the real address:
from patronus_ark import SecurityGateway
scanner = SecurityGateway(
{
"categories": ["pii", "dynamic-pii"],
"max_level": "l3",
"download": "missing",
"dynamic_pii": {
"labels": ["person", "street address", "city"],
"threshold": 0.5,
"label_thresholds": {"street address": 0.8},
},
}
)
scanner.warmup()
message = "Hallo, hier ist Erika Mustermann aus Köln, Musterstraße 5. Telefon: 030 901820."
for result in scanner.scan_all(message)["native"]:
for span in result["evidence_spans"]:
print(f'{result["category"]:<12} {span["label"]:<15} characters {span["start_char"]}-{span["end_char"]} score {span["score"]:.3f}')
Output:
pii PHONE characters 68-78 score 1.000
dynamic-pii person characters 16-32 score 0.989
dynamic-pii city characters 37-41 score 0.947
dynamic-pii street address characters 43-57 score 0.932
Something is missing. If a value is not reported, check whether it has a field name or a
context word near it (Step 3), try balanced (Step 4), or enable its bare rule (Step 5). The
accuracy per identifier shows where L1
is strong and where it is weak.
What's next¶
- Find secrets and confidential data: API keys,
passwords and classification markings with the
dlpcategory. - Choose categories & levels: combine
piiwith attack detection. - L1 capabilities: accuracy and coverage of
piicompared with Presidio. - Deploy the HTTP API: the same scans as a service.