Sub topic 7
Combining detectors into one pipeline
This chapter assumes you can write the regex detector, the Luhn checksum validator and a named-entity recognition (NER) call from the earlier chapters. You also need Python dataclasses and list sorting. By the end you will have one function that takes text and returns a clean, non-overlapping list of labelled spans.
Why one detector is not enough
Each detector has a blind spot.
- Regex finds anything with a fixed shape, such as an email address, but cannot recognise a name.
- A checksum rejects random digit strings, but only for identifiers that have a checksum.
- NER finds names and places from context, but gives fuzzy boundaries and misses unusual names.
A pipeline runs all of them on the same text and merges what they find. The merge step is where most of the bugs live. Two detectors can report the same characters with different labels. They can report overlapping ranges, or give scores that are not comparable.
The shared span shape
Every detector must return the same structure. The earlier chapters used (start, end, label) tuples. A pipeline also needs a confidence score and the name of the detector that produced the span, so you can debug conflicts later.
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class Span:
start: int # index of first character
end: int # index after last character (exclusive)
label: str # e.g. EMAIL, PERSON
score: float # 0.0 to 1.0
source: str # detector name, kept for debugging
@property
def length(self):
return self.end - self.startOffsets are character positions in the original string, and end is exclusive, so text[span.start:span.end] is the matched value. Every detector must follow this convention, or the merge step compares numbers that mean different things.
Wrapping the detectors
Each detector becomes a function from text to a list of Span objects. The scores are your own estimates of how trustworthy each detector is. The values below are starting points, not standards.
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
CARD_RE = re.compile(r"\b\d(?:[ -]?\d){12,18}\b")
PHONE_RE = re.compile(r"\+?\d[\d ()-]{7,}\d")
NAME_RE = re.compile(r"\b(?:Ana|Bob|John)\s+[A-Z][a-z]+\b") # toy stand-in for NER
def luhn_valid(number: str) -> bool:
digits = [int(c) for c in number if c.isdigit()]
if not 13 <= len(digits) <= 19:
return False
total = 0
for i, d in enumerate(reversed(digits)):
if i % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def email_detector(text):
return [Span(m.start(), m.end(), "EMAIL", 0.95, "regex_email")
for m in EMAIL_RE.finditer(text)]
def card_detector(text):
return [Span(m.start(), m.end(), "CREDIT_CARD", 0.9, "regex_luhn")
for m in CARD_RE.finditer(text) if luhn_valid(m.group())]
def phone_detector(text):
return [Span(m.start(), m.end(), "PHONE", 0.6, "regex_phone")
for m in PHONE_RE.finditer(text)]
def name_detector(text):
return [Span(m.start(), m.end(), "PERSON", 0.7, "toy_ner")
for m in NAME_RE.finditer(text)]The phone pattern is deliberately loose. It also matches a 16-digit card number, so the two detectors will disagree about the same characters. That conflict is the case the merge step has to handle.
For real NER, use an adapter with the same shape. spaCy's small models give no per-entity probability, so the adapter assigns a fixed score and maps spaCy's labels onto your own.
# pip install spacy && python -m spacy download en_core_web_sm
import spacy
nlp = spacy.load("en_core_web_sm")
LABEL_MAP = {"PERSON": "PERSON", "GPE": "LOCATION", "LOC": "LOCATION", "ORG": "ORGANIZATION"}
def spacy_detector(text):
return [Span(e.start_char, e.end_char, LABEL_MAP[e.label_], 0.7, "spacy")
for e in nlp(text).ents if e.label_ in LABEL_MAP]Mapping labels into one vocabulary is part of the job. If one detector says GPE and another says LOCATION, the later steps cannot tell they mean the same thing.
The merge stages
The pipeline has four stages after detection.
Filter by score
Dropping spans below a threshold trades recall for precision. A threshold of 0.5 keeps everything in this chapter's examples. Raising it to 0.8 would drop the phone and name spans. Choose the value by measuring on labelled data, which a later chapter covers.
Merge spans with the same label
Two detectors often find the same entity with slightly different boundaries. One finds Ana Silva and another finds Silva. Both are PERSON, so the right result is one span covering both.
def merge_same_label(spans):
merged = []
for s in sorted(spans, key=lambda s: (s.label, s.start)):
if merged and merged[-1].label == s.label and s.start <= merged[-1].end:
prev = merged.pop()
merged.append(Span(
prev.start, max(prev.end, s.end), prev.label,
max(prev.score, s.score), prev.source + "+" + s.source,
))
else:
merged.append(s)
return mergedThe union takes the widest range and the highest score. The comparison s.start <= merged[-1].end also merges spans that touch without overlapping. That is usually right for names split into tokens, but it would glue together two separate emails with nothing between them. Use < if you do not want adjacent spans merged.
Resolve overlaps between different labels
Now the card number and the phone match cover the same characters with different labels. Redaction needs one label per character, so you must pick a winner. The greedy rule below ranks spans by score, then by length, then by position, and keeps a span only if it overlaps nothing already kept.
def resolve_overlaps(spans):
ranked = sorted(spans, key=lambda s: (-s.score, -s.length, 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)The pipeline function
def detect(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(merge_same_label(spans))
text = "Ana Silva ([email protected]) paid with 4111 1111 1111 1111. Call +44 20 7946 0958."
detectors = [email_detector, card_detector, phone_detector, name_detector]
for s in detect(text, detectors):
print(s.label, repr(text[s.start:s.end]), s.score)Running it prints:
PERSON 'Ana Silva' 0.7
EMAIL '[email protected]' 0.95
CREDIT_CARD '4111 1111 1111 1111' 0.9
PHONE '+44 20 7946 0958' 0.6The phone detector also matched the card digits, but the card span scored 0.9 against 0.6, so the card label won. The real phone number has only 12 digits and fails the card pattern, so only the phone detector reports it.
Choosing an overlap policy
Highest score wins is only one option. Pick the policy that matches the cost of each kind of mistake.
| Policy | How it works | Good for | Weakness |
|---|---|---|---|
| Highest score | Keep the span with the larger score | Detectors with calibrated scores | Scores from different tools are not comparable |
| Longest span | Keep the wider range | Names and addresses with partial matches | A long loose match can hide a precise short one |
| Label priority | Fixed ranking such as CREDIT_CARD above PHONE | Validated identifiers beat guesses | Must be maintained by hand |
| Union | Replace both with one span covering both | Cases where over-redaction is cheap | Loses the label, so reversible placeholders get ambiguous |
Scores from a regex, a checksum and a statistical model are not on the same scale. A 0.9 from your own table is a judgement, while a 0.9 from a model is a probability. Many teams therefore rank by label priority first and use the score only to break ties. A checksum-validated card is stronger evidence than any NER guess.
Edge cases
- Shifted offsets. If a detector lowercases, strips whitespace or normalises Unicode before matching, its offsets refer to the changed string. Run every detector on the same original string, or map offsets back.
- Different indexing. Python indexes by code point. JavaScript uses UTF-16 units and Rust uses bytes. If a detector runs in another process or language, convert its offsets, or an emoji earlier in the text will shift every span after it.
- Chunked text. Long documents are often split before NER. Add each chunk's starting offset to its spans. An entity that straddles a chunk boundary is missed by both chunks, so use overlapping chunks and let the merge step combine the duplicates.
- Partial overlap across labels. A
LOCATIONspan might end inside anADDRESSspan. The greedy rule keeps only one, and the leftover characters may stay unredacted. Where the cost of a leak is high, union the spans and accept a coarser label. - Nested spans. An email inside a URL is detected twice. Decide whether the URL or the email should win, and test that case explicitly.
Checking the pipeline
Test the merge logic on its own, with hand-built spans, before you test the detectors. Write cases for exact overlap, partial overlap, nesting, adjacency and an empty list. Then run the full pipeline on a few sentences where you know the right answer. Counting hits and misses over a labelled set is the subject of a later chapter, and the same Span shape makes that comparison straightforward.
Exercise
Two detectors both flag the same 10 characters. One reports PHONE with score 0.6 and the other reports CREDIT_CARD with score 0.9. Under the greedy rule in this chapter, which label survives, and which rule would you add if a PHONE detector later produced a score of 0.95 for the same digits that fail the Luhn check?
Show answer
CREDIT_CARD survives because its score is higher. If a PHONE span scored 0.95 on digits that fail the Luhn check, it would win under score ranking, which is wrong for an unvalidated guess. Add a label-priority rule, or lower the phone detector's score, so a checksum-validated label ranks first and score only breaks ties.
Exercise
A spaCy detector returns PERSON for characters 0 to 9 and your regex name detector returns PERSON for characters 4 to 14 of the same string. What does mergesamelabel return?
Show answer
One PERSON span from 0 to 14 with the higher of the two scores, because the ranges overlap and the labels match.
Exercise
Your pipeline runs on a document after you lowercase it for matching, and the redaction step slices the original document using the spans. Explain what goes wrong and give one fix.
Show answer
Offsets from the lowercased copy only match the original if lowercasing preserves length. Some Unicode characters change length when lowercased, so spans can drift and cut the wrong characters. Fix it by running detectors on the original text (using case-insensitive patterns), or by keeping an index map from normalised positions back to original positions.