Detecting and Masking PII with Amazon Comprehend Before You Call a Model
Learn how to detect and mask personal data with Amazon Comprehend before text reaches a model. Find PII, replace it with reversible placeholders, call Amazon Bedrock with the cleaned text, restore the real values and test for misses.
Series: Amazon Bedrock (18 articles)
- …
- 15Detecting and Masking PII with Amazon Comprehend Before You Call a Model This article
Find names, emails, card numbers and other personal details in text, replace them with placeholders, send the cleaned text to the model, and put the real values back afterwards.
Most text that people feed into AI apps contains personal information: support emails with names and addresses, meeting notes with phone numbers, forms with account details. Sending all of that to a model, and storing it in prompts and logs, widens the number of places where it can leak.
Often the model doesn't need those details to do its job. A reply drafter doesn't need to know the customer's real phone number. A summariser works just as well with "[NAME_1]" as with a real name. So a good habit is to strip personal data out first.
Amazon Comprehend can find it for you. In this article we'll detect personal data in text, mask it with simple code, swap it for reversible placeholders, and then talk honestly about what this approach can't do.
What you need
- The setup from the earlier articles: Python, boto3 and AWS credentials
- Permission to call Amazon Comprehend
- Test text that contains made-up personal details. Don't test with real customer data.
- About forty-five minutes
What counts as PII
PII means personally identifiable information: details that can identify a person. Comprehend's PII detection looks for many types, including names, email addresses, phone numbers, street addresses, credit card and bank account numbers, government ID numbers and a long list of country-specific identifiers, as well as things like passwords and access keys.
It returns where each one sits in the text, what type it is and how confident it is. Notably, it doesn't hand back the sensitive text itself, only its position. That's handy for safety, and it means you use the positions to cut and replace the text yourself.
What counts as personal data, and what you're required to protect, depends on the law where you operate and the kind of data you hold. This article shows a technique, not legal advice.
Step 1: Detect PII
The real-time operation is
DetectPiiEntities . You send a string and a language code.import boto3
comprehend = boto3.client("comprehend", region_name="us-east-1")
text = ( "Hello, this is Jane Citizen. Please send my statement to " "12 Example Street, Springfield, and call me on 555-0142. " "My email is jane.citizen@example.com.")
response = comprehend.detect_pii_entities(Text=text, LanguageCode="en")
for entity in response["Entities"]: found = text[entity["BeginOffset"]:entity["EndOffset"]] print(entity["Type"], round(entity["Score"], 3), repr(found))The output shows each finding, for example a
NAME , an ADDRESS , a PHONE and an EMAIL , with a confidence score between 0 and 1. We cut the matched text out of the original string using the offsets, and print it here just to see what was found. In real code, don't print or log it.Two limits to know about:
- Size. The text must be under 100 KB. Larger inputs are rejected, so split them up or use the asynchronous route later in this article.
- Languages. Comprehend lists a set of languages for general analysis, but its real-time PII detection is documented for English and Spanish at the time of writing. Check the current documentation for your language, and don't assume support.
Step 2: Mask what you find
The simplest approach is to replace each finding with its type, such as
[EMAIL] . The one trick is that you must replace from the end of the text towards the start, so earlier positions don't shift as you edit.def mask(text, threshold=0.9): response = comprehend.detect_pii_entities(Text=text, LanguageCode="en") entities = [e for e in response["Entities"] if e["Score"] >= threshold] for e in sorted(entities, key=lambda e: e["BeginOffset"], reverse=True): text = text[:e["BeginOffset"]] + f"[{e['Type']}]" + text[e["EndOffset"]:] return text
print(mask(text))Expected result, give or take what Comprehend finds in your text: "Hello, this is [NAME]. Please send my statement to [ADDRESS], and call me on [PHONE]. My email is [EMAIL]."
The
threshold is a trade-off. A higher value means fewer false alarms but a greater chance of missing something. For privacy, you usually want to lean toward masking more, so test a lower value on your own text and see what it does.Step 3: Use reversible placeholders
Masking with plain types loses information. If three different people are mentioned, they all become
[NAME] , and the model can't tell them apart. For most tasks it's better to give each distinct value its own numbered placeholder, and remember the mapping so you can restore the real values afterwards.def pseudonymise(text, threshold=0.9): response = comprehend.detect_pii_entities(Text=text, LanguageCode="en") entities = sorted( (e for e in response["Entities"] if e["Score"] >= threshold), key=lambda e: e["BeginOffset"], )
seen = {} # original value -> placeholder counts = {} spans = [] for e in entities: original = text[e["BeginOffset"]:e["EndOffset"]] if original not in seen: counts[e["Type"]] = counts.get(e["Type"], 0) + 1 seen[original] = f"[{e['Type']}_{counts[e['Type']]}]" spans.append((e["BeginOffset"], e["EndOffset"], seen[original]))
for begin, end, token in reversed(spans): text = text[:begin] + token + text[end:]
mapping = {token: original for original, token in seen.items()} return text, mapping
def restore(text, mapping): for token, original in mapping.items(): text = text.replace(token, original) return textNow the whole flow looks like this:
bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")MODEL_ID = "YOUR_MODEL_ID"
message = ( "Hi, I'm Jane Citizen (jane.citizen@example.com). My order arrived late " "and Jane Citizen would like the refund sent to the card on file.")
safe_text, mapping = pseudonymise(message)
response = bedrock.converse( modelId=MODEL_ID, messages=[{ "role": "user", "content": [{"text": "Draft a short, polite reply to this customer message. " "Use the placeholders exactly as written.\n\n" f"<message>\n{safe_text}\n</message>"}], }], inferenceConfig={"maxTokens": 300, "temperature": 0.3},)
reply = response["output"]["message"]["content"][0]["text"]print(restore(reply, mapping))The model only ever sees
[NAME_1] and [EMAIL_1] . The mapping stays in your own code, and the final reply has the real values put back. Notice the same name appearing twice gets the same placeholder, so the model can still tell it's one person.Two cautions:
- Keep the mapping safe. It's a lookup table of real personal data. Hold it in memory for the length of the request, or store it encrypted with a short expiry. Don't log it.
- Tell the model to keep the placeholders unchanged. Models sometimes rephrase "[NAME_1]" into something else, which breaks the restore. Check the output, and handle placeholders that went missing.
Step 4: Long text and bulk jobs
Long text. If a document is over 100 KB, split it into chunks at natural boundaries, such as paragraphs, and process each one. Be careful about a personal detail that straddles a chunk boundary, and keep one shared mapping across chunks so the same value gets the same placeholder.
Bulk processing. For a large collection of files in S3, Comprehend offers an asynchronous job that can detect PII and, if you ask for it, write out redacted copies, where you choose whether to mask with a character or replace with the entity type. The job reads from and writes to S3 and needs an IAM role it can use. The setting names have a few options, so follow the current documentation. It's a good fit for cleaning a document collection before you build a knowledge base from it, as in the OpenSearch and knowledge base articles.
Step 5: Test it with awkward text
Personal data isn't always tidy. Build a small test set, in the spirit of the prompt testing article, and include:
- Names that are also common words
- Phone numbers and dates in unusual formats
- Addresses written across several lines
- Text with non-English names or accented characters. Check that the replacement lands in the right place.
- Card numbers with spaces or dashes
- Personal details inside a longer sentence or a code snippet
- Text with no personal data at all, to see whether it invents any
For each, write down what you expect to be masked, run the function and compare. Count two kinds of error. Misses are personal details that got through, which are the dangerous ones. False alarms are harmless words that were masked, which hurt usefulness.
What this approach can't do
Be honest with yourself about the limits.
- It isn't perfect. Any detector misses some things and flags others wrongly. Treat it as reducing risk, not removing it.
- It finds listed types of data. Something that identifies a person in a way the detector doesn't recognise, such as an unusual nickname plus a job title plus a town, can slip through.
- Context can identify people. Even with every name removed, a detailed story can still point to one individual.
- Language coverage is limited. If your text is in an unsupported language, this won't work.
- Models and logs aren't the only risk. Your database, your backups and your analytics also hold the original text.
- It's not a compliance certificate. Whether it satisfies a legal requirement is a question for the people responsible for your obligations.
Use it as one layer
This is one defence among several. Combine it with:
- Amazon Bedrock Guardrails, which has sensitive information filters that can block or mask personal data in both prompts and responses, as in the guardrails article.
- Amazon Macie, which scans S3 buckets to discover sensitive data you didn't know you were storing.
- Least-privilege access, short retention and encryption, as in the S3, DynamoDB and IAM articles.
- Careful logging. Log that masking happened and how many items were found, not the values.
- Minimising what you collect in the first place. The best protection for personal data is not having it.
What it costs
Comprehend's PII detection is billed by the amount of text analysed, in small units of characters, with a minimum per request, and the asynchronous jobs are priced separately. Check the current pricing page. For high-volume use, consider whether to run detection on everything or only on text from sources that are likely to contain personal data. Measure the cost with a sample before you decide.
Common mistakes
- Printing or logging the detected values.
- Replacing from the start of the text, so the offsets shift and the wrong characters get cut. Go from the end backwards.
- Using a threshold you never tested.
- Forgetting that the mapping itself is sensitive.
- Assuming every language is supported.
- Assuming masked text is anonymous.
- Never testing for misses.
A checklist
- Does the model really need the personal details? If not, mask them.
- Is your text in a supported language and under the size limit?
- Do you replace from the end of the text backwards?
- Do you use numbered placeholders and a protected mapping when the model needs to tell people apart?
- Have you tested for misses and false alarms on awkward text?
- Do you avoid logging detected values and mappings?
- Is this one layer among several?
Where we go next
Next, we'll compare Amazon Kendra and Amazon Bedrock Knowledge Bases, two ways to give an assistant access to your documents, and when each makes sense.
Comprehend's supported languages, entity types, limits and pricing change often. Check the current Amazon Comprehend documentation before you follow any step here, and don't test with real personal data. This article is technical guidance and not legal advice.
Series: Amazon Bedrock (18 articles)
- …
- 15Detecting and Masking PII with Amazon Comprehend Before You Call a Model This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article