Sub topic 7
Combining detectors into one pipeline
This chapter assumes you can write basic Python and regular expressions, and that you have seen the regex and checksum detectors from the earlier chapters. Here you combine several detectors into one function that returns a single clean list of labelled spans.
Why one pipeline
Each detector sees a different part of the problem. Regexes find emails and card numbers. A named-entity recognition (NER) model finds names and places. If the rest of your application had to call each one and merge the results by hand, every caller would repeat the same fragile logic.
Give every detector the same output shape: a span with a start offset, an end offset, a label, and a score. The pipeline runs all detectors, merges their spans, and returns one list. Redaction code only ever sees that list.
A common span type
A small dataclass keeps the detectors consistent. The score says how confident the detector is, from 0 to 1. Rule-based detectors with a checksum can report a high score. A broad pattern with no validation should report a lower one.
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class Span:
start: int
end: int
label: str
score: float
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
PHONE_RE = re.compile(r"\+?\d[\d ()-]{7,}\d")
def detect_email(text):
return [Span(m.start(), m.end(), "EMAIL", 0.95) for m in EMAIL_RE.finditer(text)]
def detect_phone(text):
return [Span(m.start(), m.end(), "PHONE", 0.6) for m in PHONE_RE.finditer(text)]Overlaps are the main problem
Detectors disagree. The phone pattern above can match part of a card number. An NER model may label an email's local part as a person. If you redact both spans, the text gets corrupted, because the second replacement works from offsets that no longer match.
A simple, predictable rule resolves this:
- Sort spans by score, highest first. Break ties by longer span, then by earlier start.
- Keep a span only if it does not overlap a span you already kept.
- Sort the kept spans by start offset.
def resolve_overlaps(spans):
ranked = sorted(spans, key=lambda s: (-s.score, -(s.end - s.start), s.start))
kept = []
for span in ranked:
if all(span.end <= k.start or span.start >= k.end for k in kept):
kept.append(span)
return sorted(kept, key=lambda s: s.start)
def detect_all(text, detectors, min_score=0.5):
spans = []
for detector in detectors:
spans.extend(detector(text))
spans = [s for s in spans if s.score >= min_score]
return resolve_overlaps(spans)
text = "Call +44 20 7946 0958 or write to [email protected]"
for s in detect_all(text, [detect_email, detect_phone]):
print(s.label, repr(text[s.start:s.end]), s.score)Running this prints one PHONE span and one EMAIL span, each with its text and score.
Thresholds and recall
The min_score threshold trades precision against recall. A low threshold keeps more weak matches, so you miss fewer real identifiers but redact more harmless text. A high threshold does the opposite. For privacy, missing a real identifier usually costs more than redacting an extra word, so start low and tune using the evaluation method in a later chapter.
Common errors
- Offsets from different texts. If one detector normalizes the text first (for example, lowercasing or trimming), its offsets no longer match the original. Always run detectors on the same original string.
- Merging after redacting. Detect on the original text, resolve overlaps, and only then replace. Never detect again on partly redacted text.
- Hidden duplicates. Two detectors can return the identical span. The overlap rule keeps one, which is the intended behavior, but check that the surviving label is the one you want.
- Different label names. An NER model may say
PERSONwhere your rules sayNAME. Map labels to one vocabulary inside each detector.
Exercise
Two detectors return overlapping spans for the same text. Detector A returns (10, 25, "PHONE", 0.6). Detector B returns (8, 22, "CREDITCARD", 0.9). Using the rule in this chapter, which spans does `resolveoverlaps` keep, and why?
Show answer
It keeps only the CREDIT_CARD span (8, 22). The spans overlap, since 10 < 22 and 25 > 8. The card span has the higher score, so it is ranked first and kept. The phone span overlaps a kept span, so it is dropped.
Exercise
Why should all detectors run on the same original string rather than on text that an earlier detector has already redacted?
Show answer
Redacting changes the length of the text, so offsets from later detectors would no longer point to the right characters. Placeholders such as <EMAIL_1> could also be matched as data. Running every detector on the original text keeps all offsets consistent, so they can be compared and merged.