Sub topic 2
Reducing False Positives with Checksums
Assume you know basic Python, regular expressions, prompts, model responses, and logs. This chapter uses those ideas to improve personal-data detection.
Checksums Validate Candidates
A regular expression can find strings that look like card numbers. It cannot prove that a string is a real card number. A checksum is a calculation used to detect errors in an identifier.
The Luhn algorithm is a checksum commonly used with payment-card numbers. It rejects many random digit strings while accepting valid test values.
import re
CARD_RE = re.compile(r"\b(?:\d[ -]?){13,19}\b")
def luhn_valid(value):
digits = [int(c) for c in value if c.isdigit()]
if not 13 <= len(digits) <= 19:
return False
total = 0
for index, digit in enumerate(reversed(digits)):
if index % 2:
digit *= 2
if digit > 9:
digit -= 9
total += digit
return total % 10 == 0
text = "Card 4111 1111 1111 1111 and code 1234567890123"
matches = [
(m.start(), m.end(), "CREDIT_CARD")
for m in CARD_RE.finditer(text)
if luhn_valid(m.group())
]
print(matches)A checksum reduces false positives. It does not prove ownership, activity, or that the value is safe to send to a model.
Detecting Names and Places with NER
Named-entity recognition (NER) is a model-based technique that labels names, places, organizations, and other entities in text. Unlike a regular expression, NER can find names without a fixed format. It can also make mistakes when context is unclear.
For example, “Jordan” might be a person or a country. Treat the model's label and confidence as evidence, not certainty.
Combining Detectors
A practical pipeline combines rules and NER. Each detector should return spans containing a start position, end position, and label. Resolve overlapping spans using a documented rule, such as preferring the higher-confidence result.
Choosing a Redaction Strategy
| Strategy | Keeps useful structure | Can restore the value |
|---|---|---|
| Masking, such as `****1234` | Sometimes | No |
| Placeholder, such as `<EMAIL_1>` | Yes | Only with a mapping |
| Hashing | For exact matching | No |
| Removal | No | No |
Use removal when the model does not need the value. Use placeholders when the model must discuss relationships between entities. Keep reversible mappings inside your application, and never include them in prompts or logs.
Exercise
Why should a checksum follow a regular-expression match instead of replacing it?
Show answer
The regular expression finds possible candidates, while the checksum filters out many candidates that only look like valid identifiers.