Redacting Documents Before AI Processing: Data Minimisation That You Can Test
Redaction is more than a regular expression over visible text. Handle scanned pages, hidden layers, filenames and output leaks while measuring what your detection process misses.

A document can look redacted and still contain the original text underneath a black rectangle. It can also carry a person's name in the filename, metadata or a scanned image that your text extractor never inspected. Sending that document to a model because the preview looks clean is not a defensible privacy control.
Data minimisation starts with asking what the model needs. If the task is to classify the type of invoice, it may not need the customer address or bank details at all. Removing unnecessary data is usually more reliable than hoping a prompt will keep it confidential.
Define the task's minimum input
List the fields required for the outcome. Separate essential context from information included merely because the original document contains it. Decide whether you can send a derived structured record instead of the whole file.
For example, expense categorisation may need vendor category, date, currency and a description. It may not need a personal phone number or full payment account. A contract comparison may need named roles but can often substitute consistent labels for individual names.
Confirm the provider's retention, training and processing terms through the actual product agreement and configuration. Do not assume that every API, consumer chat product and enterprise plan has identical terms.
Inspect all the layers
Text PDFs can contain selectable text, annotations, attachments and metadata. Scanned PDFs need OCR. Word-processing files can contain comments and tracked changes. Images may carry metadata or handwritten details that OCR misses.
Route each file type through an appropriate, maintained parser in a restricted processing environment. Limit file size and decompression depth, and treat document parsing as untrusted input handling. Reject unsupported or encrypted files with a clear manual-review path.
A parser that extracts no text has not established that a document contains no private data. It may simply have encountered an image-only page. Keep extraction confidence and missing-page indicators with the processing result.
Use layered detection
Regular expressions can help find familiar patterns such as email addresses, but they do not reliably detect names, international addresses or every account format. Combine format-based checks, contextual detection and human review according to the sensitivity of the workflow.
A narrow email example is useful as a demonstration, not as a claim of comprehensive redaction:
import re
EMAIL = re.compile(rclass="text-code-string">"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def replace_detected_emails(text):
mapping = {}
def token(match):
value = match.group(0)
if value not in mapping:
mapping[value] = fclass="text-code-string">"[EMAIL_{len(mapping) + 1}]"
return mapping[value]
return EMAIL.sub(token, text), mappingThe mapping contains sensitive values. Keep it in your controlled environment, with access restrictions and a defined expiry. Never send it alongside the redacted text; that defeats the separation immediately.
This pattern will miss some valid formats and may match irrelevant strings. Measure those limitations on examples from your actual document population before relying on it.
Keep substitutions consistent
If the same person appears in several sections, a stable placeholder such as PERSON_1 preserves the relationship. Replacing every name with the word REDACTED can destroy the context needed for the task.
Scope placeholder maps to the job or approved document group. A global placeholder dictionary can become another cross-customer identifier store. Do not reuse mappings broadly without a reviewed need.
Ask the model to preserve placeholders in structured output. Validate that any returned placeholder exists in the current job. Restoring original values should occur only in an authorised downstream step, not in a public report view.
Redact the file, not just the preview
If you must send an actual PDF, use a redaction process that removes underlying content rather than drawing opaque shapes. Then re-extract text from the resulting file, inspect metadata and attachments, and review relevant rendered pages.
For sensitive workflows, a safer option may be sending only vetted extracted text or a derived record. That trades layout information for a more inspectable input boundary. Decide based on the task rather than assuming the original file is always necessary.
Temporary files and thumbnails count too. Define cleanup and storage access rules for the original, intermediate OCR output, redacted version and result. An excellent model input policy is undermined if raw documents sit in a broadly readable upload directory.
Measure misses and over-redaction
Create a reviewed test set with known sensitive spans across your common formats and languages. Measure recall for sensitive data and precision for detected spans. False negatives expose data; false positives can make the model's answer unusable.
Track results by category rather than reporting one average score. Detecting emails well says little about handwritten account numbers. Include rotated pages, low-resolution scans, tables, headers and footers.
Use synthetic sensitive values in automated tests where possible. Real samples require the same access controls and retention discipline as production documents. Test reviewers should not become an informal archive of customer files.
Check the output boundary too
A model can reproduce details that survived the input filter, infer information from context or return an unexpected field. Validate the output schema and run appropriate sensitive-data checks before releasing it.
Do not ask another unrestricted model to decide whether the first model leaked information and call that a guarantee. Independent detection and human review can add evidence, but the decision still depends on your risk threshold and test results.
Give uncertain files a review state instead of silently declaring them safe. Document redaction is a process with measurable failure modes, not a visual effect. The best workflow sends less data, retains less data and can show exactly how it checked the remainder.
Paj Digital Labs
The engineering journal of Paj Digital Solutions — hosting, server infrastructure and web engineering, written by the people who run the servers.
Related reading

Streaming AI Responses: Partial Text Is Not a Completed Result
Streaming improves perceived speed but adds cancellation and partial-output states. Keep tool actions, structured results and saved answers behind a verified completion boundary.

Human Review Queues for AI: Confidence Is Not a Permission Slip
A model’s self-reported confidence does not establish accuracy. Route uncertain and consequential cases using tested rules, show reviewers the evidence and record their decisions without rubber-stamping.

AI Evaluation Sets: Keep the Test Data Out of the Tuning Loop
An evaluation stops being independent when every prompt revision is shaped around its answers. Separate development examples from held-out cases and measure meaningful failure categories.