05.5 Cleaning and Normalization
Parsing gets you text out of a file; cleaning decides whether that text is usable. Between "the parser returned a string" and "the chunker can split it" sits a gauntlet of invisible characters, mojibake, hard-wrapped lines, repeated headers, three languages in one document, exact duplicates from three export runs, dates in four formats, and the occasional credit-card number that must never reach an embedding model. This lesson is the complete engineering reference for that gauntlet: what to clean and what to leave alone, Unicode done properly, whitespace and structure, boilerplate, language identification, deduplication, entity normalization, PII handling, web-scale quality filtering, LLM-assisted cleanup, and a composable cleaning pipeline you can drop into the ingestion flow from 05.9.
What you'll learn
- The cleaning contract: clean noise, keep signal — and why every cleaning rule needs a reason, a test and a change log
- Text encoding and Unicode: mojibake and
ftfy, the four normalization forms and whenNFKChurts, invisible characters, smart quotes, ligatures, full-width forms, control characters, newlines, homoglyphs and emoji, plus a flag-only scan for hidden text (zero-width, bidi and tag characters) before stripping - Whitespace and structure: collapsing, hard-wrap rejoining, hyphenation repair, bullet normalization, protecting headings/code/tables, and Markdown as the canonical intermediate format
- Boilerplate removal: headers, footers, page numbers, navigation, cookie banners, email signatures and quoted replies — with repetition detection that actually works
- Language identification and routing:
lingua-language-detector, fastTextlid.176,langdetect,py3langid— verified versions, licences and accuracy trade-offs - Deduplication: exact and normalized hashes, shingling, MinHash and LSH with
datasketch, SimHash, document- vs chunk-level dedup, and which copy to keep - Entity and value normalization: dates, money, units, phones, names, IDs, casing and abbreviations — and why you always keep the original
- PII and sensitive-data handling at ingestion: regex, Microsoft Presidio, LLM-based detection; redaction vs masking vs pseudonymization; where in the pipeline it must happen
- Quality filtering for web-scale corpora: length, language, gibberish/OCR-noise metrics, perplexity-style filters and spam — with thresholds as tunable config
- LLM-assisted cleaning: when it earns its cost, the similarity guard that proves the model didn't change meaning, and batching
- A complete cleaning pipeline: pure functions, per-step change logs, dry-run/diff mode, pytest-style tests and idempotency — all runnable with the standard library
What you don't need
- API keys. Almost everything in this lesson is pure Python: every algorithmic sample runs on toy data with the standard library or a handful of small packages. The LLM-assisted-cleaning part shows provider calls for completeness, clearly labelled illustrative.
- Knowledge of the parsers that feed this stage. Cleaning consumes the
ParsedDocumentmodel defined in 05.2 and the parsers of 05.3 and 05.4; you need only the idea that each document arrives as structured text with provenance. - Any prior data-engineering experience. ETL veterans will recognize most patterns immediately — the callouts mark where LLM pipelines change the rules.
Setup
The core pipeline is standard library only. Create a project and add the small set of libraries the samples use:
uv init data-cleaning --bare --python 3.13 && cd data-cleaning
uv add ftfy pytest
# or: pip install ftfy pytestOptional libraries, each used in one part — install only what you need:
uv add charset-normalizer # Part 2.1: guessing the encoding of raw bytes
uv add datasketch # Part 6: MinHash + LSH (pulls in numpy/scipy)
uv add lingua-language-detector # Part 5: best-in-class language ID (needs Python >=3.12)
uv add langdetect # Part 5: classic detector, 55 languages
uv add py3langid # Part 5: langid.py fork, 139 languages + zxx
uv add fasttext-wheel # Part 5: fastText bindings (also needs numpy/scipy)
uv add presidio-analyzer presidio-anonymizer # Part 8: PII detection/redaction (pulls in spaCy — heavy)
uv add openai anthropic google-genai python-dotenv # Part 10 onlyThese commands install the newest release of each package. The samples were written and checked against ftfy 6.3.1, charset-normalizer 3.5.2, datasketch 2.0.0, lingua-language-detector 2.2.0, langdetect 1.0.9, py3langid 0.4.0, Presidio 2.2.366 and pytest 9.2.0 as of November 2026. Cleaning and detection libraries can change their rules or models between releases, so if a printed result differs slightly, compare versions and read the changelog before you debug your own code.
Notes on the packages:
lingua-language-detectoris the official Lingua package (Rust bindings, Apache-2.0, Python ≥3.12). The older community packagelingua-py(0.1.1) was yanked from PyPI precisely because the official one superseded it — don't use it.py3langidis a maintained fork oflangid.pywith a retrained model covering 139 languages plus the syntheticzxx"not a language" class; the originallangid.pypackage is effectively unmaintained.presidio-*pulls inspacyand friends; it's the heaviest install here. Part 8 also shows a regex-only detector that needs nothing.- The fastText language-ID model (
lid.176) is not on PyPI — you download it separately in 5.3.
Provider samples in Part 10 read keys from .env (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY) via python-dotenv; see lesson 03.1. Everything else needs no keys and no network.
What you must be able to do after this lesson#
- Clean noise while keeping signal and log every rule
- Fix encoding and Unicode problems
- Remove boilerplate and duplicate text
- Redact PII before it reaches the index
- Build a composable cleaning pipeline
Why this matters for an AI engineer#
Every downstream stage inherits whatever the cleaning stage leaves behind. A chunker's boundaries, an embedding's meaning, a retriever's ranking and an evaluator's scores are all computed on your cleaned text — so a systematic cleaning bug doesn't produce one bad document, it produces a systematically biased corpus. The good news: cleaning is also the cheapest place to fix problems. A regex here costs microseconds; the same problem discovered after embedding costs a re-embed of everything.
| You'll hear... | You'll understand it after... |
|---|---|
"Half our PDFs have ’ instead of apostrophes." |
Part 2: mojibake and ftfy |
"The same product appears as Café, Café and CAFE — are they duplicates?" |
2.2: NFC/NFKC and normalized hashing |
| "The extractor gives us one word per line." | 3.2: rejoining hard wraps |
| "Every chunk starts with 'Confidential — Page 3 of 12'." | Part 4: repetition-based boilerplate removal |
| "We have German, English and Arabic docs mixed together." | Part 5: detection and routing |
| "The same ticket was exported three times." | Part 6: exact, normalized and near-duplicate detection |
"Dates say 03/04/2026 — which month?" |
7.1: locale pitfalls and the dual-field pattern |
| "Customer emails contain phone numbers — can we embed them?" | Part 8: detection and anonymization operators |
| "This web crawl is 40% spam and OCR garbage." | Part 9: gibberish metrics and tunable thresholds |
| "GPT could just fix the OCR output, right?" | Part 10: when it helps, and the similarity guard |
| "How do we prove the cleaner didn't break anything?" | Part 11: change logs, dry-run, tests, idempotency |
Part 1: What to clean, and what not to#
1.1 The cleaning contract: noise vs signal#
Cleaning is subtraction with a purpose. Noise is text that carries no meaning for the downstream task but costs tokens, dilutes embeddings and confuses chunk boundaries: mojibake, zero-width characters, repeated page headers, hard-wrap artifacts, duplicated documents. Signal is everything a reader (human or model) could use: numbers, dates, code, punctuation that changes meaning, legal clauses, table structure, names, even typos — because a typo is part of what the source actually says.
The contract has three clauses:
- Every transformation must name its noise. "Collapse runs of spaces" is a rule; "collapse runs of spaces because PDF extraction emits alignment padding that carries no meaning" is a contract. If you can't name the noise, you can't test whether you removed it — or whether you removed too much.
- Never destroy information irreversibly. The raw extracted text is immutable; the cleaned text is a derived view. Keep both (or keep enough to regenerate: raw + the ordered list of steps and their versions — see 1.2).
- Cleaning is deterministic by default. The same input must produce the same output, every run. Non-determinism (an LLM step, a probabilistic detector) belongs behind a versioned, logged step — never smeared invisibly through the pipeline.
1.2 Keep the raw text; the cleaned text is a view#
Store the parser's output untouched (the ParsedDocument from 05.2, or at minimum the raw extracted string plus provenance). Derive cleaned text from it, never edit it in place.
Why this is non-negotiable:
- You will re-clean. Next month you discover your hyphenation rule broke compound words, or a new
ftfyversion fixes a mojibake pattern you worked around. With raw + versioned steps, re-cleaning is a batch job; without raw, it's a re-parse of the whole corpus. - Cleaning bugs are found by diffing. When a chunk looks wrong, you compare raw vs cleaned to see which step ate the content. If cleaning overwrote the raw, there's nothing to compare.
- Regulatory and debugging needs. "Show me exactly what the model saw" means replaying raw → steps → cleaned. If a PII redaction or an OCR correction happened, you need the before-picture (05.4 makes the same argument for keeping raw OCR output).
- Idempotent re-runs. 05.9's incremental pipeline re-processes documents; if cleaning is a pure function of (raw, step versions), re-running it is free and safe.
A practical layout: raw/ stores parser output keyed by content hash; cleaned/ stores (content_hash, cleaning_version) → cleaned_text; the manifest in 05.9 records which cleaning version produced each stored artifact.
1.3 Every rule needs a reason and a test#
Treat each cleaning step like a function with a contract:
def collapse_horizontal_whitespace(text: str) -> str:
"""Collapse runs of spaces/tabs to one space, outside fenced code blocks.
Noise removed: PDF alignment padding and double-space artefacts.
Signal kept: newlines, indentation inside fenced code, table pipes.
"""Then test the boundary, not just the happy path:
def test_collapse_keeps_code_indentation():
fence = "`" * 3
src = fence + "python\nif x:\n return 1\n" + fence
assert collapse_horizontal_whitespace(src) == src
def test_collapse_removes_padding():
assert collapse_horizontal_whitespace("a b\t\tc") == "a b c"The tests encode the intent: which noise, which signal. When someone (including future-you) tightens a regex, the tests say what must not break. Part 11 turns this into a full pytest suite.
1.4 Over-cleaning destroys meaning#
The most expensive cleaning bug is the one that removes signal. Real examples:
- Stripping "non-letter" characters to fight OCR noise also deletes every digit, currency symbol and
%— your invoice totals become prose. - Removing all punctuation merges
Item A: $10andItem A $10fine, but destroys3.14vs314,e.g.vseg, and every decimal point. - Lowercasing everything makes dedup easy and destroys casing that carries meaning:
JSON,SQL,iPhone,USvsus, German nouns. - Stripping numbers "because they're noise" deletes prices, dates, versions, error codes, page numbers that are content, and clause numbers like "Section 4.2".
- Removing "boilerplate" from a legal corpus deletes the disclaimers and jurisdiction clauses that are the entire point of the documents.
- Normalizing whitespace inside code blocks destroys Python indentation — the code stops parsing.
- "Fixing" spelling with a dictionary rewrites domain terms (
PostgreSQL→postgresql,Kubernetes→kubernetes) and names. - Stripping URLs removes citations, source links and evidence.
The rule of thumb: if removing a character class could change an answer to "what does this document say?", it stays. Cleaning targets artifacts of extraction, not content of the document.
1.5 Order matters: pipeline shape and idempotency#
Cleaning steps don't commute. NFKC normalization before ftfy mojibake repair can turn recoverable ’ into unrecoverable characters; boilerplate detection before whitespace collapsing sees different line boundaries; PII redaction must run after structural cleaning (so detectors see normalized text) but before anything that sends text to a provider or an embedding model.
The safe shape is a fixed, ordered list of pure steps, each logged:
flowchart LR
A["raw text<br/>(from ParsedDocument)"] --> B["encoding fixes<br/>ftfy / charset"]
B --> C["unicode NFC<br/>+ invisible chars"]
C --> D["structure<br/>whitespace, wraps, bullets"]
D --> E["boilerplate<br/>repetition filter"]
E --> F["language detect<br/>+ routing"]
F --> G["PII anonymize<br/>(before any egress)"]
G --> H["cleaned text +<br/>change log"]
H --> I["chunker<br/>(05.6)"]Two properties make this production-safe:
- Idempotent:
clean(clean(x)) == clean(x). Running the pipeline twice — or re-running it on an already-cleaned document during an incremental update — changes nothing. Test it explicitly (11.4). - Dry-runnable: you can compute the cleaned text and the per-step change report without committing it, so you can inspect what a rule does to a sample before it touches the corpus.
Deduplication (Part 6) and entity normalization (Part 7) slot in beside this flow: dedup runs on the normalized-for-comparison form, and entity normalization produces additional fields rather than rewriting the text (the dual-field pattern in 7.4).
Part 2: Text encoding and Unicode#
2.1 Encodings, mojibake, and ftfy#
Text is stored as bytes; an encoding is the rule that maps bytes to characters. UTF-8 is the universal default and the only encoding you should emit. The problem is decoding: when a parser, database or upstream export reads UTF-8 bytes as Windows-1252 or Latin-1, every multi-byte character becomes two or three garbage characters — é (UTF-8 0xC3 0xA9) decoded as Latin-1 becomes é. That garbled text is called mojibake ("bad rendering" in French).
Mojibake is nasty because it's lossy-looking but actually recoverable: the wrong decoding preserved the bytes' information, so re-encoding the garbage as Latin-1 and decoding as UTF-8 restores the original. ftfy automates exactly this detection and repair.
# s2_1_ftfy_demo.py — needs: uv add ftfy
from ftfy import fix_text, fix_and_explain
samples = [
"’tis the season", # curly apostrophe, UTF-8 read as cp1252
"The Mona Lisa doesn’t have eyebrows.", # double-encoded
"LOUD NOISES", # fullwidth forms
"l’humanité", # mojibake + curly-quote layer
]
for s in samples:
print(repr(s), "->", repr(fix_text(s)))
fixed, explanation = fix_and_explain("voilà le travail")
print(fixed) # 'voilà le travail'
print(explanation) # [('encode', 'latin-1'), ('decode', 'utf-8'), ...]'’tis the season' -> "’tis the season"
'The Mona Lisa doesn’t have eyebrows.' -> "The Mona Lisa doesn't have eyebrows."
'LOUD NOISES' -> 'LOUD NOISES'
'l’humanité' -> "l'humanité"
voilà le travail
[('encode', 'latin-1'), ('transcode', 'restore_byte_a0'), ('decode', 'utf-8')]The explanation is a plan you can re-apply to other text with the same corruption via ftfy.apply_plan — useful when one bad export produced a thousand documents with identical mojibake.
ftfy is not an encoding detector — it repairs text that's already a str. When you have bytes of unknown encoding (a .csv from 2009, a SAP export), detect the encoding first. charset-normalizer is the current best-in-class detector (MIT, actively maintained; chardet 7.x had a contested relicensing — see its PyPI page):
# s2_1_charset.py — needs: uv add charset-normalizer
from charset_normalizer import from_bytes
raw = "Café — naïve résumé".encode("cp1252") # bytes in the wrong encoding on purpose
best = from_bytes(raw).best()
print(best.encoding) # e.g. 'cp1252'
print(best.decode()) # 'Café — naïve résumé'Rule: decode bytes with the detected/declared encoding, immediately normalize to str (Unicode), and never let raw bytes flow downstream. After that, ftfy.fix_text is your safety net for text that was already wrongly decoded upstream.
2.2 Unicode normalization forms#
The same visible character can be represented by different code point sequences. The classic case: é is either one code point (U+00E9, "precomposed") or two (U+0065 e + U+0301 combining acute, "decomposed"). To Python they're different strings; to a reader they're identical. Unicode normalization defines canonical forms that collapse these differences.
| Form | What it does | Use it when |
|---|---|---|
| NFC | Compose: combine base+mark into precomposed where possible | Your default. Consistent storage, matching, display |
| NFD | Decompose: split precomposed into base+marks | Linguistic processing, sorting algorithms that need canonical ordering, some search engines |
| NFKC | Compatibility-compose: NFKC = NFKD then NFC — folds compatibility variants too (fullwidth→ASCII, ligatures→letters, superscripts→digits, roman numerals→letters) | Search/index matching where you want INVOICE to equal INVOICE; dangerous as a blanket rule (see below) |
| NFKD | Compatibility-decompose | Stripping accents (unicodedata category Mn removal), some tokenizer internals |
The distinction that matters: canonical equivalence (NFC/NFD) is about the same character written differently — always safe to normalize. Compatibility equivalence (NFKC/NFKD) treats characters as equal that are visually or semantically distinct — ² vs 2, fi vs fi, Ⅳ vs IV, ㎏ vs kg, halfwidth vs fullwidth katakana.
# s2_2_normalize.py — stdlib only, real output
import unicodedata
samples = ["Cafe\u0301", "INVOICE-2026", "x² + y³", "final", "Section Ⅳ"]
for s in samples:
row = {f: unicodedata.normalize(f, s) for f in ("NFC", "NFD", "NFKC", "NFKD")}
print(f"{s!r:24} NFC={row['NFC']!r} NFKC={row['NFKC']!r}")'Café' NFC='Café' NFKC='Café'
'INVOICE-2026' NFC='INVOICE-2026' NFKC='INVOICE-2026'
'x² + y³' NFC='x² + y³' NFKC='x2 + y3'
'final' NFC='final' NFKC='final'
'Section Ⅳ' NFC='Section Ⅳ' NFKC='Section IV'Normalization also fixes a subtle dedup bug: Café (NFC) and Cafe\u0301 (NFD) hash differently under SHA-256 but are the same text. Normalizing before hashing (6.2) is what makes "identical" mean identical.
2.3 Invisible and control characters#
Unicode contains characters that occupy zero width or control rendering — invisible to readers, toxic to tokenizers and similarity metrics:
| Character | Code point | Category | Why it appears | Handling |
|---|---|---|---|---|
| BOM / zero-width no-break space | U+FEFF | Cf | UTF-8 signature misread as content; copy-paste | Strip at document start; ftfy remove_control_chars removes it anywhere |
| Zero-width space | U+200B | Cf | Web pages, PDFs, "hidden" text | Strip — it splits words for regexes but renders nothing |
| Zero-width non-joiner / joiner | U+200C / U+200D | Cf | Persian, Arabic, Indic scripts need them for correct shaping; also emoji sequences (ZWJ) | Do not blanket-strip — see warning below |
| Soft hyphen | U+00AD | Cf | Word processors mark optional break points | Strip or convert to - contextually; it's invisible but affects line-breaking |
| Word joiner | U+2060 | Cf | Prevents line breaks in UI text | Strip for prose |
| Control chars (C0) | U+0000–U+001F except \t\n\r |
Cc | Binary garbage, parser bugs | Remove; keep \t, \n, \r (or normalize them per 2.5) |
| C1 controls | U+0080–U+009F | Cc | Legacy encodings, mojibake residue | Context-dependent — they can be mojibake clues; ftfy keeps them during encoding repair |
| Interlinear annotation / object replacement | U+FFF9–U+FFFC | Cf | PDF annotations, embedded objects | Usually strip |
| Tag characters | U+E0000–U+E007F | Cf | Invisible "alt text" in some PDFs/emails; also used in flag emoji | Scan and record first (2.7), then strip in prose; flag emoji are tag sequences, so keep those — see 2.6 |
| Bidi controls | U+202A–U+202E, U+2066–U+2069 | Cf | Right-to-left text embedding; also a Trojan-Source attack vector | Strip from LTR-only corpora; handle via proper bidi algorithm for RTL text — preview Module 12 |
| Homoglyphs | e.g. Cyrillic а U+0430 vs Latin a |
Ll/Lu etc. | Spoofing, lookalike domains, mixed-script garbage | NFKC does not fold these (they're canonically distinct); detection needs confusable-skeleton analysis — Module 12 |
2.4 Smart quotes, dashes, ligatures, full-width forms#
Typographically correct documents use smart punctuation: curly quotes “”‘’ (U+201C/201D/2018/2019), en/em dashes –/—, ellipsis …, non-breaking space. These are content, not noise — but they complicate matching:
don'twritten with U+2019 doesn't match a regex looking for'.word—worddoesn't matchword-wordorword - word.fi(U+FB01) doesn't matchfiin search.
Two policies, pick per corpus:
- Preserve (default for archival/legal text): keep the typographic characters; make your matchers tolerant (regex classes like
[’'], normalize at comparison time). - ASCII-fold (default for search indexes and LLM chunks where typography adds no meaning): map
’‘→',“”→",–—→-,…→..., NBSP → space. Document it as a named step so it's reversible-by-recompute.
ftfy handles several of these: fix_latin_ligatures (fi→fi), fix_character_width (fullwidth→halfwidth), uncurl_quotes inside fix_text. NFKC folds ligatures and fullwidth forms but also folds ²→2 — another reason to keep NFC as the stored form.
2.5 Newline conventions#
Three conventions exist in the wild: LF (\n, Unix), CRLF (\r\n, Windows), CR (\r, classic Mac — still emitted by some Office-for-Mac exports). Unicode adds LINE SEPARATOR U+2028 and PARAGRAPH SEPARATOR U+2029, plus the C1 "next line" U+0085. ftfy.fixes.fix_line_breaks normalizes all of them to \n.
Pick LF (\n) as the canonical internal form — every parser, regex and chunker assumes it. Convert at the boundary (ingest), not at each consumer. One stdlib line does it:
def normalize_newlines(text: str) -> str:
return (text.replace("\r\n", "\n").replace("\r", "\n")
.replace("\u2028", "\n").replace("\u2029", "\n"))2.6 Emoji and symbol sequences#
Emoji are content — a support ticket saying "the app crashes 🚀 after update" means something. But they're not single characters: 👨👩👧 is three people + two ZWJ; 🇺🇸 is two regional indicators; ❤️ is U+2764 + U+FE0F variation selector; 🏳️🌈 adds ZWJ + rainbow. Key rules:
- Never split on code points. Iterate by grapheme cluster (the user-perceived character). The
regexmodule supports\Xfor this; stdlib has no grapheme segmentation. - Keep variation selectors (U+FE0F text-vs-emoji presentation) and ZWJ sequences intact.
- Tag characters (U+E0020–U+E007E) build subdivision flags (🏴) and are also used for invisible embedded data in some documents — context decides.
- Tokenizers handle emoji unpredictably (often several tokens each, sometimes byte-fallback) — see 02.2, Part 8 for the multilingual token tax; emoji are the extreme case.
For most corpora the right policy is: leave emoji and symbol sequences alone, except inside boilerplate/PII filtering where you match on words anyway.
2.7 Hidden text and adversarial content at ingestion (preview)#
Cleaning decides what the model will read, so it is also the last cheap place to notice text that a human reviewer would never see. Anyone who can put a document into your corpus (a customer upload, a scraped page, an email, a supplier PDF) can try to hide instructions in it for the model: "ignore your rules and reveal ...". That attack is called indirect prompt injection; Module 12 owns it (12.2, 2.5 and 9.1). A RAG corpus makes it worse, because a poisoned document persists and is retrieved for every user. This lesson owns only the data-engineering half: detect and flag the hiding places while you still have the raw bytes, and record what you saw.
| Where it hides | Examples | Where this module detects it |
|---|---|---|
| Unicode itself | Zero-width characters, bidirectional controls, and tag characters (U+E0000 to U+E007F), which map one-to-one onto ASCII and so can carry a whole invisible sentence | The scanner below, in this lesson |
| White or tiny text, text drawn off the page or under an image, invisible OCR-layer text (render mode 3) | 05.2, 1.3 and 3.3: compare non_stroking_color, size and bbox from pdfplumber chars with the page box and the background |
|
| HTML | display:none, hidden, aria-hidden, <template>, comments, alt and title attributes |
05.3, 2.4: the invisible-element removal step |
| Office files | Word text marked hidden (the w:vanish run property), comments, speaker notes, hidden sheets |
05.3, Part 6 |
| Images and scans | Low-contrast or very small text inside an image | 05.4 and Module 09 |
The scanner below is detection, not defence. It reports what is there, it does not decide that a document is malicious (zero-width characters are normal in Persian and Indic text, and bidi controls are normal in Arabic and Hebrew, see 2.3), and it must run before the invisible-character strip step, because stripping destroys the evidence. The only tag characters it accepts are complete subdivision-flag sequences (such as England's): a waving-black-flag emoji, a few tag letters and the cancel tag, at most seven tag characters in all. Checking the whole shape matters, character by character, not just the length: an attacker could otherwise put a flag emoji in front of a hidden sentence, or hide six characters of their choice behind one, to get it skipped. The report also counts the invisible fillers that are not format characters (Hangul fillers, the blank braille cell) and the variation selectors other than the two emoji selectors, because both can carry hidden payloads.
# s2_7_hidden_text_scan.py — stdlib only; run it BEFORE the invisible-character strip step
import unicodedata
TAG_BASE = 0xE0000 # Unicode "tag" block: U+E0000-U+E007F
FLAG_EMOJI_START = "\U0001F3F4" # waving black flag: legitimately followed by tag letters
BIDI_CONTROLS = set("")
ZERO_WIDTH = set("")
# Characters that render as nothing but are not format (Cf) characters, so the Cf
# count below misses them: Hangul fillers, the blank braille cell, Khmer inherent vowels.
INVISIBLE_FILLERS = set("\u115f\u1160\u3164\uffa0\u2800\u17b4\u17b5")
def hidden_text_report(text: str) -> dict:
"""Flag (never silently delete) characters that can hide content from a human reader."""
tag_runs: list[str] = []
i = 0
while i < len(text):
if 0xE0000 <= ord(text[i]) <= 0xE007F:
j = i
while j < len(text) and 0xE0000 <= ord(text[j]) <= 0xE007F:
j += 1
# a legitimate flag is exactly: flag emoji + 1-6 tag letters/digits
# (U+E0030-E0039, U+E0061-E007A) + cancel tag. Check every character,
# not just the length: otherwise six hidden characters of any kind
# could ride along behind a flag emoji.
body = text[i:j - 1]
is_flag_sequence = (
i > 0 and text[i - 1] == FLAG_EMOJI_START
and ord(text[j - 1]) == 0xE007F and 1 <= len(body) <= 6
and all(0xE0030 <= ord(c) <= 0xE0039 or 0xE0061 <= ord(c) <= 0xE007A
for c in body))
if not is_flag_sequence:
# tag characters map 1:1 onto printable ASCII: decode to show what was hidden
tag_runs.append("".join(chr(ord(c) - TAG_BASE) for c in text[i:j]
if 0x20 <= ord(c) - TAG_BASE <= 0x7E))
i = j
else:
i += 1
return {
"zero_width": sum(ch in ZERO_WIDTH for ch in text),
"bidi_controls": sum(ch in BIDI_CONTROLS for ch in text),
"other_format_chars": sum(
unicodedata.category(ch) == "Cf" and ch not in ZERO_WIDTH | BIDI_CONTROLS
and not 0xE0000 <= ord(ch) <= 0xE007F for ch in text),
"invisible_fillers": sum(ch in INVISIBLE_FILLERS for ch in text),
# U+FE0E/FE0F are the text/emoji selectors every emoji uses; the other
# selectors (U+FE00-FE0D, U+E0100-E01EF) can carry a hidden payload.
"variation_selectors": sum(0xFE00 <= ord(ch) <= 0xFE0D or 0xE0100 <= ord(ch) <= 0xE01EF
for ch in text),
"hidden_tag_text": tag_runs,
}
visible = "Our returns window is 30 days."
hidden = "".join(chr(TAG_BASE + ord(c)) for c in "SAMPLE HIDDEN NOTE") # benign placeholder
samples = {
"clean": visible,
"zero-width padding": "Our returns window is 30 days.",
"tag-smuggled note": visible + hidden,
"flag emoji": "Made in \U0001F3F4" + "".join(chr(TAG_BASE + ord(c)) for c in "gbeng") + "\U000E007F",
}
for name, t in samples.items():
print(f"{name:20} -> {hidden_text_report(t)}")clean -> {'zero_width': 0, 'bidi_controls': 0, 'other_format_chars': 0, 'invisible_fillers': 0, 'variation_selectors': 0, 'hidden_tag_text': []}
zero-width padding -> {'zero_width': 2, 'bidi_controls': 0, 'other_format_chars': 0, 'invisible_fillers': 0, 'variation_selectors': 0, 'hidden_tag_text': []}
tag-smuggled note -> {'zero_width': 0, 'bidi_controls': 0, 'other_format_chars': 0, 'invisible_fillers': 0, 'variation_selectors': 0, 'hidden_tag_text': ['SAMPLE HIDDEN NOTE']}
flag emoji -> {'zero_width': 0, 'bidi_controls': 0, 'other_format_chars': 0, 'invisible_fillers': 0, 'variation_selectors': 0, 'hidden_tag_text': []}What to do with a flag, in order of preference: (1) record it in the document's lineage and quality report (05.10); (2) route documents with decoded tag text or heavy bidi controls to a review queue instead of the index; (3) never let the stripped text and the flag disappear together. Even a perfectly clean corpus still has to be treated as data, not instructions, at prompt time: that is the job of the prompt layout in Module 04 and the defences in Module 12.
Part 3: Whitespace and structure#
3.1 Whitespace collapsing#
Extraction pads text with alignment spaces ("Total: $1,299.99"), tabs, and non-breaking spaces (U+00A0 — which \s in Python does match, but which surprises people). Collapse horizontal whitespace to single spaces — except where whitespace is structural:
- Inside fenced code blocks — indentation is syntax.
- Inside tables (Markdown
|rows or fixed-width columns) — column alignment is structure. - In poetry, ASCII art, or signature blocks where layout carries meaning.
The fence-aware version (we build the fence marker dynamically so this listing doesn't contain a literal one):
# s3_1_collapse.py — stdlib only
import re
FENCE = "`" * 3
def collapse_horizontal_whitespace(text: str) -> str:
out, in_fence = [], False
for line in text.split("\n"):
if line.strip().startswith(FENCE):
in_fence = not in_fence
out.append(line); continue
if in_fence:
out.append(line); continue
line = line.replace("\u00a0", " ").replace("\u3000", " ") # NBSP, ideographic space
out.append(re.sub(r"[ \t]+", " ", line).rstrip())
return "\n".join(out)On "Total: $1,299.99\n<fence>\nif x:\n return 1\n</fence>" (a fenced block) it keeps the code indentation and collapses the prose padding — verify by running it.
3.2 Hard-wrapped text and paragraph rejoining#
PDFs, emails, terminal output and many web pages wrap lines at a fixed visual width (~72–80 chars), not at sentence boundaries. The extractor gives you:
Our return policy is simple: items may be returned within
30 days of purchase for a full refund. Items must be unused and
in original packaging.Left alone, the chunker sees three fragments; an embedding sees three weak vectors instead of one strong paragraph. Rejoining merges continuation lines into paragraphs — but the hard part is knowing which newlines are wraps (remove) and which are structure (keep):
| Keep the newline | Join the lines |
|---|---|
| Paragraph breaks (blank line) | Mid-sentence wraps |
List items (each - , 1., •) |
Wrapped list content (join within the item) |
| Headings | Title blocks (usually — see below) |
| Code blocks, tables | Addresses/signatures? — judgement call |
Blockquotes (>) |
Heuristics that work in practice, in order:
- Blank line = hard boundary. Always.
- Line-start markers = boundary.
#,-,*,•,1.,>,|, fenced-code markers, image/link-only lines. - Sentence punctuation = boundary. If the accumulated line ends with
.,!,?,:,;the next line starts fresh — unless the next line is clearly a continuation (starts lowercase and the sentence looks unfinished; this is where it gets fuzzy, so prefer the conservative join). - Length floor. A very short accumulated buffer (< ~40 chars) is probably a title, heading or label — don't absorb the next line into it.
- No-terminal-punctuation = wrap. The strongest single signal: a line with no ending punctuation followed by more text is almost always a hard wrap.
# s3_2_rejoin.py — stdlib only, real output below
import re
FENCE = "`" * 3
def rejoin_hard_wraps(text: str) -> str:
out, buf, in_fence = [], "", False
MARKER = re.compile(r"^(#{1,6}\s|>|[-*•]\s|\d+[.)]\s|\|)")
END_PUNCT = (".", "!", "?", ":", ";")
def flush():
nonlocal buf
if buf.strip():
out.append(re.sub(r" +", " ", buf.strip()))
buf = ""
for line in text.split("\n"):
s = line.strip()
if s.startswith(FENCE): # fence marker: toggle, keep verbatim
flush(); out.append(line); in_fence = not in_fence; continue
if in_fence: # inside code: indentation is syntax
out.append(line); continue
if not s:
flush(); out.append(""); continue
if MARKER.match(s):
flush(); out.append(s); continue
if buf and len(buf) >= 40 and not buf.endswith(END_PUNCT):
buf += " " + s # continuation of a wrapped line
else:
flush(); buf = s
flush()
return "\n".join(out)On the Acme returns text this produces the title lines intact, the three wrapped lines joined into one paragraph, and the bullets untouched — the real output is in the worked example at the end of this part.
3.3 Hyphenation repair#
Two different hyphen problems:
- Soft hyphens (U+00AD) — invisible optional break points left by word processors. Already covered in 2.3: strip them.
- Hard-wrap hyphenation — a word split across lines with a visible hyphen:
The return policy applies to all manufac-
tured goods purchased after January 1.Join rule: a line ending in - (or ‐/‑/‒) followed by a lowercase letter is almost always a wrap hyphen → remove the hyphen and join. But well- known vs well-known at a real hyphenation point is ambiguous — conservative approach: join only when the left fragment isn't a complete word you'd keep hyphenated. In practice: join X-\nlowercase when X is not itself a common standalone word; keep a small exception list (well-, self-, non-, pre-, re-, ex-, anti-, co-, multi-, semi-, inter-, sub-, un-, in-, dis-, en-, em-, pro-, pseudo-, quasi-, ultra-, vice-, over-, under-, out-, up-, down-).
PREFIXES = {"well","self","non","pre","re","ex","anti","co","multi","semi",
"inter","sub","un","in","dis","en","em","pro","pseudo","quasi",
"ultra","vice","over","under","out","up","down"}
def repair_wrap_hyphens(text: str) -> str:
# The match consumes "fragment-\n", so both branches join the lines.
# A wrap hyphen is dropped ("manufac-\ntured" -> "manufactured"); a real
# hyphen in a kept prefix survives ("well-\nknown" -> "well-known").
return re.sub(r"(?m)\b([A-Za-z]+)-\n(?=[a-z])",
lambda m: m.group(1) + "-" if m.group(1).lower() in PREFIXES
else m.group(1), text)(In the pipeline this step runs before rejoin, so the repaired word flows into the paragraph join.)
3.4 Bullets and numbering normalization#
The same list arrives as *, •, ·, ◦, –, -, o, or 1./1)/(1). Normalize to Markdown syntax (- for bullets, 1. for ordered) so downstream chunking sees one convention:
FENCE = "`" * 3
def normalize_bullets(text: str) -> str:
out, in_fence = [], False
for line in text.split("\n"):
if line.strip().startswith(FENCE): # fence marker: toggle, keep verbatim
in_fence = not in_fence
elif not in_fence: # never rewrite code
# [ \t] not \s: \s would also swallow the blank line above a list
line = re.sub(r"^[ \t]*[*•·◦o][ \t]+", "- ", line)
line = re.sub(r"^[ \t]*(\d+)[.)][ \t]+", r"\1. ", line)
out.append(line)
return "\n".join(out)Keep the original marker in metadata if legal numbering matters (Article 4.2, Section III, § 5) — those aren't bullets, they're references, and over-normalizing them destroys meaning (1.4).
3.5 Protecting boundaries: headings, code, tables#
Every structural step must be boundary-aware. The pattern: walk the text tracking whether you're inside a protected region, and only transform outside it.
FENCE = "`" * 3
def protected_mask(lines):
"""Yield (line, in_protected) — protected = fenced code, table rows, html blocks."""
in_fence = False
for line in lines:
s = line.strip()
if s.startswith(FENCE):
in_fence = not in_fence
yield line, True; continue
yield line, in_fence or s.startswith("|") or s.startswith("<")Apply the same mask in collapse, rejoin and boilerplate steps. For HTML-sourced text, prefer the parser's DOM structure (05.3) over regex masks — this is the fallback for flattened text.
3.6 Markdown as the canonical intermediate format#
Decision: clean into Markdown. Reasons:
- Markdown preserves the structure that matters for chunking (headings
#, lists, code fences, tables, links) in plain text — no binary format downstream needs to parse. - Every parser in this module can emit it (pdfplumber→text+heuristics, python-docx→headings, HTML→
markdownify/html2text, OCR→VLM markdown prompts in 05.4). - The chunker in 05.6 gets structure-aware boundaries for free.
- It's diffable, greppable, and LLM-legible.
What you lose: precise font/colour/layout info — which belongs in metadata/provenance anyway, not in the text stream.
3.7 Worked example: messy extraction → clean Markdown#
Input (as a PDF extractor might emit it — hard-wrapped, padded, weird bullets):
Acme Corp returns policy
Last updated: March 3, 2026
Our return policy is simple: items may be returned within
30 days of purchase for a full refund. Items must be unused and
in original packaging. Refunds are issued to the original
payment method within 5-10 business days.
* Electronics: 15% restocking fee applies
• Perishables: not returnable
- Clearance items: final sale
Contact returns@acme.example or call 1-800-555-0199.
Questions? See https://acme.example/returns for details.After normalize_newlines → collapse_horizontal_whitespace → rejoin_hard_wraps → normalize_bullets:
Acme Corp returns policy
Last updated: March 3, 2026
Our return policy is simple: items may be returned within 30 days of purchase for a full refund. Items must be unused and in original packaging. Refunds are issued to the original payment method within 5-10 business days.
- Electronics: 15% restocking fee applies
- Perishables: not returnable
- Clearance items: final sale
Contact returns@acme.example or call 1-800-555-0199.
Questions? See https://acme.example/returns for details.The title lines stay separate (short-buffer rule), the three wrapped lines became one paragraph, and all three bullet styles unified to - . This is real output from the stdlib functions shown above.
Part 4: Boilerplate removal#
4.1 What boilerplate is#
Boilerplate is text repeated across documents or pages that carries no document-specific meaning: running headers and footers, page numbers, confidentiality banners, navigation menus, cookie notices, "printed on" lines, email signatures, quoted reply chains, legal disclaimers appended to every page. In a retrieval corpus it's actively harmful — a footer repeated on 400 pages becomes 400 near-identical chunks that flood top-k results and dilute embeddings with "Confidential — Page 17 of 42".
The catch: boilerplate is defined relative to a corpus, not a document. "All rights reserved" is boilerplate in a product manual and signal in a copyright filing. Decide per corpus, and per document type — a compliance corpus may want the disclaimers.
4.2 Repetition detection: the n-gram frequency heuristic#
The workhorse algorithm is simple and effective: text that appears in most documents is boilerplate.
- For each document (or page), extract word shingles — contiguous n-gram word sequences (n=5–8 works well; unigrams are too noisy, long n-grams miss partial repeats).
- Count in how many distinct documents/pages each shingle appears.
- Shingles appearing in ≥ threshold fraction of documents (typically 0.5–0.9) are boilerplate candidates.
- Remove lines/blocks whose shingles overlap the boilerplate set substantially.
Why shingles and not whole lines? Headers vary slightly ("Page 3 of 12" vs "Page 7 of 12") — shingling catches the stable parts. Why document-frequency and not raw count? A phrase repeated 50× within one document is probably real content (a refrain, a disclaimer that matters); the same phrase in 90% of different documents is template.
# s4_1_boilerplate.py — stdlib only, real output below
import re
def shingles(text: str, n: int = 5) -> set[str]:
words = re.findall(r"\w+", text.lower())
return {" ".join(words[i:i+n]) for i in range(len(words)-n+1)}
def find_boilerplate(docs: list[str], frac: float = 0.8) -> set[str]:
"""Shingles present in >= frac of documents."""
from collections import Counter
per_doc = [shingles(d) for d in docs]
df = Counter()
for ss in per_doc:
for s in ss:
df[s] += 1
need = max(2, int(frac * len(docs)))
return {s for s, c in df.items() if c >= need}
def strip_boilerplate_lines(text: str, boiler: set[str]) -> str:
kept = []
for line in text.split("\n"):
ss = shingles(line)
if ss and len(ss & boiler) / len(ss) < 0.5:
kept.append(line)
return "\n".join(kept).strip()Run it on six simulated "pages" that share a header and a footer (add this to the same file):
# s4_1b_demo.py — continues s4_1_boilerplate.py
HEADER = "ACME Corp Confidential - Internal Use Only"
FOOTER = "All rights reserved. Printed in the UK. Do not copy."
BODIES = [
"Drills must be unplugged before any bit change.",
"Battery packs should be stored below thirty degrees.",
"Replace worn chucks when the jaws no longer close evenly.",
"Sockets are sold in metric and imperial sets.",
"Warranty claims need the original proof of purchase.",
"Recycle old tools at an approved collection point.",
]
pages = [f"{HEADER}\n{body}\n{FOOTER}" for body in BODIES]
boiler = find_boilerplate(pages, frac=0.8)
print(len(boiler), "boilerplate shingles:")
for s in sorted(boiler):
print(" ", s)
print("--- page 3 after stripping ---")
print(strip_boilerplate_lines(pages[2], boiler))8 boilerplate shingles:
acme corp confidential internal use
all rights reserved printed in
corp confidential internal use only
in the uk do not
printed in the uk do
reserved printed in the uk
rights reserved printed in the
the uk do not copy
--- page 3 after stripping ---
Replace worn chucks when the jaws no longer close evenly.The six pages share eight 5-word shingles (the header and the footer, including the ones that straddle the join inside the footer), so strip_boilerplate_lines removes both lines and leaves only the body. Notice that the bodies deliberately share no five-word run: a shingle shared by every page is boilerplate by definition, so a page body that always began with the same phrase would be stripped too, which is the corpus-relative nature of the rule (4.1).
4.3 Email signatures and quoted replies#
Email is its own boilerplate problem. A thread export contains the same signature on every message and every previous reply quoted below the new text. Patterns:
- Signature delimiters: a line that is exactly
--(dash dash space) or a short legal-name/company block after it; mobile signatures likeSent from my iPhone. - Quote markers: lines starting
>,>>,On <date> <person> wrote:,From: ... Sent: ... To: ... Subject: ...header blocks,-----Original Message-----,________________________________. - Reply trimming: keep the newest message's content; mark quoted history as context or drop it (decision depends on whether your corpus is "tickets" — drop — or "threads as documents" — keep with markers).
QUOTE_RE = re.compile(r"(?m)^\s*(>{1,3}\s|On .{5,80} wrote:|From: .+|Sent: .+|"
r"-{3,}\s*Original Message|_{5,}|--\s*$)")
def strip_quoted_replies(text: str) -> str:
"""Drop lines from the first quote marker onward (newest-message-only policy)."""
m = QUOTE_RE.search(text)
return text[:m.start()].rstrip() if m else text4.4 When boilerplate is signal#
Before stripping, ask what the corpus is for:
| Corpus | Boilerplate to strip | Boilerplate that is signal |
|---|---|---|
| Product docs / help centre | Nav, cookie banners, "© 2026" | Version footers ("v2.3, effective 2026-01-01") — keep as metadata |
| Contracts / legal | Running headers (mostly) | Jurisdiction, limitation-of-liability, indemnity clauses — the point of the document |
| Compliance corpus | Page furniture | Disclaimers, audit notices, regulatory citations |
| Support tickets | Signatures, quoted history | Auto-responder text? — it's noise; SLA disclaimers — borderline |
| Scientific papers | Journal boilerplate | Author affiliations, funding, conflict-of-interest statements |
Rule: strip for retrieval noise, preserve for compliance. If unsure, keep the text but mark it (a boilerplate: true metadata flag) so retrieval can down-weight rather than delete — that's a 05.8 decision.
4.5 Boilerplate decision table#
| Mess | Tool | Why |
|---|---|---|
| Repeated header/footer across pages | Shingle-frequency detection | Catches near-identical variants |
| Page numbers "Page 3 of 12" | Position + regex | They're structurally predictable |
| Nav menus / cookie banners (HTML) | Parser-level boilerplate removal (trafilatura, readability — see 05.3) |
DOM structure beats text heuristics |
| Email signatures/quotes | Delimiter regexes | Markers are conventional |
| "Confidential" banners | Corpus-level decision | Sometimes signal |
| Templated near-dup pages | Boilerplate signature clustering first | Don't strip shared content |
Part 5: Language identification and routing#
Deep-dive
5.1 Why identify language at cleaning time#
Language isn't just metadata — it changes what cleaning means:
- Tokenization differs wildly. English words split on spaces; Chinese/Japanese have no spaces (each character or subword is a token); Thai has no inter-word spaces at all; German compounds run long. The "token tax" for non-English text is documented in 02.2, Part 8 — your chunk-size maths depends on it.
- Whitespace rules differ. "Collapse spaces" is meaningless for Thai (no spaces between words); sentence-boundary detection differs for scripts without
./!/?. - Normalization differs. Arabic needs RTL handling and optional-tatweel stripping; Japanese needs no case-folding; Turkish
i/İcasing breaks naive.lower(). - Downstream routing. Multilingual embedding models have uneven per-language quality; you may route low-resource languages to different chunking or flag them for review.
- Evaluation. Per-language quality metrics need per-language text — you can't measure what you didn't label.
So detection runs early (right after encoding fixes), tags each document/chunk with a language code, and gates language-specific steps.
5.2 The four detectors, compared#
| Detector | Package (as of Nov 2026) | Languages | Strengths | Weaknesses | Licence |
|---|---|---|---|---|---|
| Lingua | lingua-language-detector 2.2.0 |
75 | Best accuracy on short text (single words, phrases); confidence values; offline; Rust-speed; with_minimum_relative_distance for ambiguous text |
Fewer languages than fastText/langid; Python ≥3.12 | Apache-2.0 |
fastText lid.176 |
fasttext-wheel 0.9.2 + model file |
176 | Widest coverage incl. low-resource languages; fast inference | Needs a 126MB (or 917KB .ftz) model download; labels are __label__xx; weakest on very short ambiguous text |
MIT (lib) / CC-BY-SA 3.0 (model) |
| langdetect | langdetect 1.0.9 |
55 | Simple, pure Python, detect_langs gives probabilities |
Non-deterministic on short/ambiguous text (seed it); weakest on short text | MIT |
| py3langid | py3langid 0.4.0 |
139 + zxx |
Fast fork of langid.py; zxx class catches non-linguistic text; abstention (min_confidence→und); set_languages subset mode |
Linear (non-neural) model, so weaker on very short text; needs numpy | BSD-3-Clause |
5.3 The four detectors in code#
# s5_3_lingua.py — needs: uv add lingua-language-detector (Python >=3.12)
from lingua import Language, LanguageDetectorBuilder
detector = (LanguageDetectorBuilder.from_all_languages()
.with_preloaded_language_models() # load once, reuse
.build())
lang = detector.detect_language_of("The quick brown fox jumps over the lazy dog.")
print(lang) # Language.ENGLISH (or None if undetermined)
conf = detector.compute_language_confidence_values("Bonjour le monde")
for c in conf: # list[ConfidenceValue] — .language and .value fields
print(c.language.name, round(c.value, 3))
# FRENCH 0.999 ...# s5_3_langdetect.py — needs: uv add langdetect
from langdetect import DetectorFactory, detect, detect_langs
DetectorFactory.seed = 0 # REQUIRED for determinism on short text
print(detect("Ein, zwei, drei, vier")) # 'de'
print(detect_langs("Otec matka syn.")) # [sk:0.57, pl:0.29, cs:0.13]# s5_3_py3langid.py — needs: uv add py3langid
import py3langid as langid
print(langid.classify("This text is in English.")) # ('en', -68.56)
from py3langid.langid import LanguageIdentifier, MODEL_FILE
idf = LanguageIdentifier.from_modelpath(MODEL_FILE, norm_probs=True, min_confidence=0.2)
idf.set_languages(["en", "de", "fr"])
print(idf.classify("ok")) # ('und', ...) — abstains below threshold# s5_3_fasttext.py — needs: uv add fasttext-wheel + model download
import fasttext, urllib.request, os
MODEL = "lid.176.ftz" # 917 kB compressed; use lid.176.bin (126 MB) for accuracy
if not os.path.exists(MODEL):
urllib.request.urlretrieve(
"https://dl.fbaipublicfiles.com/fasttext/supervised-models/" + MODEL, MODEL)
model = fasttext.load_model(MODEL)
label, prob = model.predict("This is a test sentence.")
print(label[0].replace("__label__", ""), prob[0]) # en 0.99...Example outputs (illustrative — your exact output will differ): Lingua returns Language.ENGLISH; langdetect returns 'de' and [sk:0.57, ...]; py3langid returns ('en', -68.56); fastText returns en 0.99….
5.4 Mixed-language documents, transliteration, non-whitespace scripts#
Real corpora violate the one-language-per-document assumption:
- Mixed-language docs: a bilingual contract, an email with a German greeting and English body. Detect per block/section, not per document — run detection on windows (paragraphs or ~500-char chunks) and tag each. A document-level label lies about its parts.
- Transliteration: Arabic/Hebrew/Cyrillic/Chinese text romanized (
"Marhaba","Zdravstvuyte","Ni hao") detects as the target language orund— the detector sees Latin script. Tagtransliterated: trueand don't apply the wrong script's rules. - Non-whitespace languages: Thai, Chinese, Japanese have no inter-word spaces. "Collapse whitespace" and "split on spaces" are meaningless; sentence segmentation needs language-specific handling (Thai needs a word segmenter like
pythainlp; CJK needs character-level logic). Yourrejoin_hard_wrapsstill works (it joins lines, not words), but bullet/number detection and gibberish metrics (9.2) must be script-aware —\w+shingling fails on unspaced scripts; use character n-grams instead. - Code-mixed text: Hinglish, Spanglish — detectors pick the dominant language; tag
mixed: truewhen confidence is split and route to the multilingual path.
Part 6: Deduplication#
6.1 Why duplicates hurt#
Duplicate documents in a retrieval corpus cause three concrete problems:
- Top-k flooding. Five copies of the same policy fill five of your ten retrieval slots — the answer is "found" but diversity is destroyed, and the effective recall@k halves.
- Cost. Every duplicate is embedded, stored, and returned — paying embedding and storage for zero information.
- Skewed signals. Duplicate-heavy sources dominate frequency-based signals (BM25 document frequency, boilerplate detection, quality metrics).
Duplicates come in three flavours, each needing a different tool: exact (byte-identical), normalized-identical (same text, different encoding/whitespace/casing), and near-duplicate (same content, minor edits — a re-exported ticket with one field changed, a policy with an updated date).
6.2 Exact and normalized-hash deduplication#
Exact: hash the raw bytes (SHA-256). O(1) per doc, zero false positives — but misses everything that differs by a byte.
Normalized hash: hash a canonical form — NFC-normalized, whitespace-collapsed, case-folded, punctuation-stripped — so "Returns Policy", "returns policy" and "RETURNS\tPOLICY" collide:
# s6_1_dedup.py — stdlib only, real output below
import hashlib
import re
import unicodedata
def canonical(text: str) -> str:
t = unicodedata.normalize("NFKC", text) # fold compatibility variants
t = re.sub(r"[^\w\s]", "", t.lower()) # drop punctuation, fold case
return re.sub(r"\s+", " ", t).strip()
def dedup_key(text: str) -> str:
return hashlib.sha256(canonical(text).encode()).hexdigest()[:16]Try it on a few documents (add this to the same file):
# s6_1b_demo.py — continues s6_1_dedup.py
docs = {
"returns-policy": "Returns Policy: items may be returned within 30 days.",
"returns-policy-copy": "RETURNS POLICY -- items may be returned within 30 days!",
"returns-policy-v2": "Returns Policy: items may be returned within 60 days.",
"version-2.0": "Version 2.0",
"version-20": "Version 20",
"version-2": "Version 2",
}
for name, text in docs.items():
print(f"{name:20} {dedup_key(text)}")returns-policy d45c2a4403024768
returns-policy-copy d45c2a4403024768
returns-policy-v2 7901ab069b640b2a
version-2.0 529f07ef0f073755
version-20 529f07ef0f073755
version-2 f4761aa023c3639dreturns-policy and returns-policy-copy collide (same canonical text) while the edited version, which says 60 days instead of 30, gets a different key. The last three rows show the cost of aggressive canonicalization: Version 2.0 and Version 20 collide because dropping punctuation turns 2.0 into 20.
6.3 Near-duplicates: shingles, MinHash, LSH#
Near-dups differ by small edits — a date bump, a corrected typo, an appended paragraph. Hashes can't catch them; you need similarity.
The pipeline:
- Shingle the document into word n-grams (n=3–5; character 5-grams for unspaced scripts).
- MinHash compresses the shingle set into a small fixed-size signature (e.g. 128 integers) that estimates Jaccard similarity — the fraction of shared shingles — in linear time and tiny memory.
- LSH (Locality-Sensitive Hashing) indexes the signatures so you only compare candidate pairs, giving sub-linear search over millions of docs.
# s6_2_minhash.py — needs: uv add datasketch
import re
from datasketch import MinHash, MinHashLSH
def minhash_of(text: str, num_perm: int = 128) -> MinHash:
m = MinHash(num_perm=num_perm)
words = re.findall(r"\w+", text.lower())
for i in range(len(words) - 4):
m.update(" ".join(words[i:i+5]).encode("utf-8")) # 5-word shingles
return m
# documents: dict[str, str] (doc_id -> text) and new_text: str are your own data
# Index all docs
lsh = MinHashLSH(threshold=0.6, num_perm=128)
sketches = {}
for doc_id, text in documents.items():
m = minhash_of(text)
sketches[doc_id] = m
lsh.insert(doc_id, m)
# Query: find near-dups of a new document
query = minhash_of(new_text)
candidates = lsh.query(query)
# candidates = doc_ids whose estimated Jaccard > ~0.6
# VERIFY with exact similarity before deleting — LSH gives candidates, not verdictsKey facts about datasketch 2.x (verified against its docs):
MinHash(num_perm=128)default;jaccard(other)estimates similarity;mergeunions sketches;count()estimates cardinality.- v2.0.0 changed the default permutation scheme to
affine32(fixes a similarity over-estimation bias, halves memory).affine64is for billion-scale sets;scheme="legacy"interoperates with pre-2.0 sketches — sketches and LSH indexes can't be mixed across schemes. If you persisted sketches from datasketch 1.x, rebuild or passlegacy. MinHashLSH(threshold=0.9, num_perm=128, ...)— the threshold defaults to 0.9, so always pass yours explicitly (the sample uses 0.6);insert(key, minhash),query(minhash)→ candidate keys. For batches there is nobatch_query— loopquery, or buffer sketches withadd_to_query_buffer/collect_query_buffer; for bulk loads useinsertion_session().weights=(fp_weight, fn_weight)biases the S-curve;params=(b, r)pins bands/rows manually.- LSH is probabilistic: false positives (below-threshold returned) and false negatives (above-threshold missed) both exist. The S-curve
P(s) = 1 - (1 - s^r)^bmeans results cluster near the threshold. Always verify candidates withm1.jaccard(m2)or exact set similarity before acting — treat LSH as a candidate generator, not an oracle.
For a dependency-free version, a pure-stdlib MinHash works too — hash each shingle with hashlib.blake2b keyed by slot index (the "permutation"), keep the minimum per slot; the fraction of matching slots estimates Jaccard:
# s6_3_minhash_stdlib.py — stdlib only, real output below
import hashlib
import re
def shingles(text: str, n: int = 5) -> set[str]:
words = re.findall(r"\w+", text.lower())
return {" ".join(words[i:i + n]) for i in range(len(words) - n + 1)}
def minhash(text: str, num_perm: int = 128) -> list[int]:
sig = [2**64 - 1] * num_perm
for sh in shingles(text):
for i in range(num_perm):
h = int.from_bytes(hashlib.blake2b(
sh.encode(), digest_size=8,
person=i.to_bytes(2, "little")).digest(), "little")
if h < sig[i]:
sig[i] = h
return sig
def est_jaccard(a: list[int], b: list[int]) -> float:
return sum(x == y for x, y in zip(a, b)) / len(a)
doc = ("the quarterly revenue report shows steady growth across all regions "
"with enterprise contracts expanding faster than expected while churn "
"remains flat and support ticket volume declines slightly quarter over "
"quarter according to the finance team")
sig_a = minhash(doc)
sig_dup = minhash(doc) # identical copy
sig_edit = minhash(doc.replace("steady", "modest", 1)) # one word changed
print(f"identical : {est_jaccard(sig_a, sig_dup):.3f}")
print(f"one-word : {est_jaccard(sig_a, sig_edit):.3f}")identical : 1.000
one-word : 0.711Identical documents estimate Jaccard 1.000; a single-word edit drops the estimate to ~0.71 because it changes every 5-word shingle touching that word. That's the sensitivity you tune with num_perm (more permutations = tighter estimate, more memory) and the shingle size n (larger n = stricter near-dup definition).
6.4 SimHash and embedding-based dedup#
- SimHash produces a single 64/128-bit fingerprint per document where similar docs have small Hamming distance — simpler than MinHash (one hash, not a signature) but only gives a similarity score, not the set-resemblance estimate; good for "find the most similar existing doc" rather than "find all pairs above threshold". The
simhashPyPI package implements it; for most RAG dedup, MinHash+LSH is the better default. - Embedding-based dedup (preview of Module 06): embed each doc/chunk, cluster by cosine similarity. Catches semantic near-dups that share few words ("returns policy" vs "refund rules") — but costs an embedding per doc and needs a similarity threshold tuned per embedding model. Use it as a second pass after lexical dedup when semantic duplication matters.
6.5 Document-level vs chunk-level dedup, and which copy to keep#
- Document-level dedup (before chunking): removes whole duplicate documents — the common case for re-exports, mirrored pages, syndicated content.
- Chunk-level dedup (after chunking): catches duplicates within a corpus where the same boilerplate/template chunk appears in many docs (e.g. every invoice has an identical "payment terms" paragraph). Cheaper to catch early if you dedup boilerplate (Part 4) first.
- Which copy to keep: prefer (a) the newest
modified_atfor versioned docs, (b) the canonical URL for web pages (therel=canonicalor sitemap-preferred URL), (c) the longest/most complete extraction when parsers differ, (d) the copy with best provenance (has page/bbox, fewer warnings). Record the decision — dropped duplicates are a form of data loss and should be auditable. - Versioned documents: a policy v1 and v2 aren't duplicates — they're versions. Dedup must be version-aware: keep both, tag with effective dates (05.8 owns the date semantics), and let retrieval prefer the current one. Templated pages (every product page shares nav+footer but differs in body) need boilerplate stripping before near-dup detection, or everything looks like a near-dup.
6.6 Choosing thresholds#
There's no universal threshold — it depends on what "duplicate" means for your corpus:
| Threshold | Catches | Misses | Risk |
|---|---|---|---|
| 1.0 (exact hash) | Byte-identical | Everything else | None — but almost useless alone |
| ~0.9 Jaccard | Trivial re-exports, whitespace diffs | Edited docs | Low false-positive |
| ~0.7 | Re-exports with small edits, template pages | Paraphrased content | Some false merges |
| ~0.5 | Heavily edited versions, shared-template docs | Genuinely different docs on same topic | High false-positive — verify! |
How to choose: sample ~50–100 document pairs at your candidate threshold, eyeball them, measure precision (are the flagged pairs really dupes?) and recall (did you catch the dupes you planted?). Adjust until precision ≥ ~0.9 — a false merge loses content permanently, a missed dup only wastes a slot. Make the threshold a config value per source, not a constant.
Part 7: Normalizing entities and values#
Deep-dive
7.1 Dates#
Dates are the highest-value normalization target — they're filterable metadata (05.8), sortable, and everywhere inconsistent: 03/04/2026, 3 Apr 2026, April 3, 2026, 2026-03-04, 04.03.26.
Rules:
- Canonical form: ISO 8601 (
YYYY-MM-DD). It's unambiguous, sorts lexicographically, and every library parses it. - Ambiguity is real:
03/04/2026is March 4 (US) or April 3 (EU). You cannot resolve it from the string alone — use source locale hints (document language, source system's country), an explicitdate_formatconfig per source, or store the original and flagambiguous: true. - Keep the original. The dual-field pattern:
date_raw: "March 3, 2026"+date_iso: "2026-03-03"+date_confidence. Retrieval can usedate_iso; display and audit usedate_raw. - Relative dates ("last Tuesday", "Q3 2026") need a reference date — resolve against document
created_at, not ingestion time. - Two-digit years (
04/03/26): pivot at a sane boundary (e.g. 00–68 → 2000s, 69–99 → 1900s — the common POSIX pivot; adjust per corpus) and flag low confidence. - Time zones: store UTC instants for timestamps; store dates as dates (no tz). "Effective March 3" is a date, not an instant.
# s7_1_dates.py — stdlib only
def normalize_date(raw: str, fmt_hint: str | None = None) -> dict:
"""Return {iso, raw, ambiguous, confidence}."""
import datetime, re
raw = raw.strip()
# ISO already
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw):
return {"iso": raw, "raw": raw, "ambiguous": False, "confidence": "high"}
# US-style MM/DD/YYYY — ambiguous without locale hint. NOTE: fmt_hint only
# raises the confidence here; it does not yet swap day and month for a "DMY"
# source. Making it do so (and validating the result) is exercise 8.
if re.fullmatch(r"\d{1,2}/\d{1,2}/\d{2,4}", raw):
m, d, y = raw.split("/")
yy = int(y)
year = yy if len(y) == 4 else (2000 + yy if yy <= 68 else 1900 + yy)
iso = f"{year:04d}-{int(m):02d}-{int(d):02d}"
return {"iso": iso, "raw": raw, "ambiguous": True,
"confidence": "low" if fmt_hint is None else "medium"}
# "March 3, 2026"
try:
dt = datetime.datetime.strptime(raw, "%B %d, %Y")
return {"iso": dt.date().isoformat(), "raw": raw,
"ambiguous": False, "confidence": "high"}
except ValueError:
return {"iso": None, "raw": raw, "ambiguous": True, "confidence": "none"}7.2 Money, units and numbers#
- Money: store
amount(decimal, not float — useDecimalor cents-as-int) +currency(ISO 4217 code:USD,EUR,GBP) +raw.$1,299.99→1299.99 USD;€45,00→ decimal-comma locale →45.00 EUR. Never let floats touch money. - Numbers:
1,299vs1.299vs1 299— thousands/decimal separators are locale-dependent. Strip grouping separators only when you know the locale;1,299.99(US) and1.299,99(EU) are different parses of similar-looking strings. - Units: normalize
5 kg/5kgs/5 kilogrammes→5 kg(SI canonical); keepraw.20%vs0.20— pick a convention (percent as written is usually safer for display; fraction for computation). - Measurements in prose: "about forty" vs
40— leave spelled-out numbers alone unless your corpus is numeric-heavy; an LLM normalization pass can handle this (Part 10).
7.3 Phones, names, IDs, codes, casing, abbreviations#
- Phones: normalize to E.164 (
+14155550123) when possible; keepraw.phonenumberslibrary (already a Presidio dep) does this properly — don't regex phone numbers by hand beyond detection. - Names: don't normalize casing aggressively —
McDonald,O'Brien,van der Berg,Josécarry meaning. Storename_raw; aname_key(lowercased, accent-stripped, punctuation-free) for matching only. - IDs and product codes:
INV-2026-0042vsinv 2026 0042— keep the canonical code, strip only presentation noise (extra spaces). Never "correct" codes —0vsOis a real distinction. - Casing: store original; compute
text_lower/text_keyfor matching.JSONvsjsonmatters to a developer audience. - Abbreviations and acronyms: maintain an expansion table per domain (
e.g.→for example,API→ keep,Acme Corp→Acme Corporation). Apply as a lookup, not a guess — wrong expansions (IT→information technologyvsit) are worse than none. LLM-assisted expansion is Part 10 territory. - Product codes/SKUs: preserve exactly; they're identifiers, not text.
7.4 The dual-field pattern: keep the original#
The consistent design across all of Part 7: never overwrite the source text with a normalized form. Produce a parallel normalized representation:
{
"text": "Invoice #INV-2026-0042 dated March 3, 2026 for $1,299.99",
"text_key": "invoice inv 2026 0042 dated 2026 03 03 for 1299 99 usd",
"entities": {
"dates": [{"raw": "March 3, 2026", "iso": "2026-03-03", "ambiguous": false}],
"money": [{"raw": "$1,299.99", "amount": "1299.99", "currency": "USD"}],
"ids": [{"raw": "INV-2026-0042", "type": "invoice_number"}]
}
}text is what the chunker embeds and what the LLM sees (it's the cleaned prose). text_key, entities.dates[].iso, etc. are filterable/sortable metadata — the 05.8 schema stores them as fields. This separation is what lets you fix a bad date parse later without re-parsing the document.
Part 8: PII and sensitive data#
8.1 Why PII handling happens at ingestion#
Personal data leaks through AI pipelines in three places, and ingestion is the only point that controls all three:
- Into the embedding model — text is sent to an embedding API; PII in it leaves your perimeter (02.9, Part 9 covers provider data policies).
- Into the LLM — chunks go into prompts; PII in them reaches the provider and lands in logs/prompts you store.
- Into your own stores — raw text, cleaned text, chunks, vectors' neighbours, logs, backups all persist whatever you didn't strip.
If you anonymize before embedding and before any provider call, downstream stages inherit clean data. Do it late enough that detectors see normalized text (post-cleaning), early enough that nothing egresses.
8.2 Detection: three layers#
| Layer | What it catches | Strengths | Weaknesses | Cost |
|---|---|---|---|---|
| Regex/deny-list | Emails, phones, SSNs, credit cards, IPs, API-key shapes | Fast, deterministic, zero deps, auditable | Misses names, addresses, context-dependent PII; false positives | ~free |
Presidio (presidio_analyzer 2.2.366) |
50+ entity types across countries: PERSON, EMAIL, PHONE, CREDIT_CARD, IBAN, IP, LOCATION, DATE_OF_BIRTH… via regex + spaCy NER + checksums + context | Best-in-class open-source; per-country recognizers; confidence scores; AnalyzerEngine |
Heavy dep (spaCy model download); English-centric NER weaker on other languages | Medium |
| LLM-based | Names, addresses, sensitive context regex can't express | Catches semantic PII ("my son Tyler", "the deal with Acme") | Probabilistic, costs tokens, needs verification, can miss or hallucinate entities | High per doc |
Presidio's architecture: AnalyzerEngine returns RecognizerResult(entity_type, start, end, score) spans from its detection pass; presidio-anonymizer's AnonymizerEngine then replaces them via per-entity operators. It also supports context enhancement (surrounding words boost confidence) and custom recognizers — extend it rather than replacing it.
# s8_2_presidio.py — needs: uv add presidio-analyzer presidio-anonymizer
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import RecognizerResult, OperatorConfig
analyzer = AnalyzerEngine() # loads spaCy model + recognizers
anonymizer = AnonymizerEngine()
text = "Contact jane.doe@acme.example or call 415-555-0132 about invoice INV-9."
results = analyzer.analyze(text=text, entities=["EMAIL_ADDRESS", "PHONE_NUMBER"], language="en")
anon = anonymizer.anonymize(
text=text,
analyzer_results=results,
operators={"DEFAULT": OperatorConfig("replace", {"new_value": "<REDACTED>"})},
)
print(anon.text)
# 'Contact <REDACTED> or call <REDACTED> about invoice INV-9.'(First run downloads the spaCy en_core_web_lg model — python -m spacy download en_core_web_lg.)
For corpora where you can't afford Presidio's weight, the regex layer catches the structured 80% — three patterns cover the common cases:
# s8_2b_regex_pii.py — stdlib only, real output below
import re
PII_PATTERNS = {
"EMAIL": re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b"),
"PHONE": re.compile(r"\b(?:\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}\b"),
"SSN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
}
text = ("Reach jane.doe@acme.example or call 415-555-0132; "
"her SSN on file is 078-05-1120. Backup: ops@acme.example.")
for name, rx in PII_PATTERNS.items():
print(f"{name}: {rx.findall(text)}")EMAIL: ['jane.doe@acme.example', 'ops@acme.example']
PHONE: ['415-555-0132']
SSN: ['078-05-1120']This is the deterministic floor, not the ceiling: it catches formatted PII (emails, NANP-style phones, dashed SSNs) but misses names, addresses and context-dependent cases — that's what Presidio's NER layer and the LLM layer are for.
8.3 Redaction vs masking vs pseudonymization vs drop#
Presidio's anonymizer operators map to these strategies:
| Strategy | Operator | What it does | When |
|---|---|---|---|
| Redact | redact |
Removes the entity entirely | PII with no analytic value (names in a product FAQ) |
| Replace | replace / replace w/ new_value |
Substitutes a fixed token or entity-type label | Default safe choice — "<EMAIL>", "[PERSON]" |
| Mask | mask |
Partial chars → *** |
When format matters but identity doesn't (last-4 cards) |
| Hash | hash (sha256/sha512) |
Deterministic pseudonym | Dedup/grouping across docs without revealing value — but dictionary-attackable on low-entropy values (SSNs, phones) |
| Encrypt | encrypt (AES) |
Reversible ciphertext | When you must recover later — requires key management |
| Pseudonymize | custom (Faker/lambda) |
Realistic fake values | Synthetic-looking data that preserves format/distribution |
| Drop | n/a — remove the document/field | Whole record out | Highly sensitive sources |
Reversible tokens (the vault pattern): replace PII with an opaque token («PII-7f3a») and store the token→value mapping in a separate, access-controlled store. The text stays clean for embedding/LLM; an authorized process can detokenize for display. This is pseudonymization, not anonymization — GDPR still treats it as personal data, but it lets you keep utility while minimizing exposure.
8.4 Where in the pipeline, and logging hygiene#
Order in the cleaning pipeline (1.5):
parse → encoding/unicode fixes → structure cleaning → boilerplate →
language detect → entity normalization → PII anonymize → cleaned textPII anonymization runs after structural cleaning (detectors see normalized text) and before the cleaned text is stored for embedding or sent to any provider. If you embed first and redact later, the vector already leaked.
Logging hygiene: cleaning logs must record counts and types, never the PII itself — {"pii_redacted": {"EMAIL_ADDRESS": 2, "PHONE_NUMBER": 1}}, not the addresses. Same for dry-run diffs: a diff that prints the removed text re-leaks it into logs. Store diffs encrypted or as hashes if you need them.
Part 9: Quality filtering#
Deep-dive
9.1 The filter stack for web-scale corpora#
For crawled/web data (vs curated documents), cleaning includes admission control — deciding what enters the corpus at all. Stack, cheapest first:
- Length: too short (< ~50 chars of real text) is nav-boilerplate or a stub; too long (> ~1M chars) is likely a dump/spam — quarantine both.
- Language: detect and route (Part 5); drop
und/unsupported or flag for review. - Boilerplate ratio: if > ~60% of shingles are boilerplate, the page is a template shell — drop or strip aggressively.
- Gibberish/OCR-noise metrics (9.2).
- Spam signals: keyword-stuffing density, link-to-text ratio, excessive repetition, known-bad domains.
- Perplexity-style / classifier filters: a small model scores "is this real prose?" — the approach used by large corpora (FineWeb, DCLM). Expensive; reserve for web scale.
9.2 Gibberish and OCR-noise metrics#
Cheap heuristics that catch most garbage without a model:
- Alphabetic ratio: fraction of characters that are letters. Real prose ~0.7–0.9; OCR garbage, numbers-dumps and binary-as-text score low.
- Vowel ratio: fraction of letters that are vowels (Latin scripts ~0.35–0.45). Consonant-salad gibberish scores near 0.
- Max repeated-char run:
!!!!!oraaaaa— real text rarely exceeds ~4. - Dictionary hit rate: fraction of words in a wordlist (a few thousand common words covers most prose). Needs a wordlist per language.
- Repeated-token ratio: fraction of tokens that are the same word — spam/stuffed pages score high.
- Character-class entropy / unique-char ratio: low diversity = generated noise.
# s9_2_quality.py — stdlib only, real output below
import re
def quality_metrics(text: str) -> dict:
letters = [c for c in text.lower() if c.isalpha()]
alpha = len(letters) / max(1, len(text))
vowel = sum(c in "aeiouy" for c in letters) / max(1, len(letters))
rep = max((len(m.group(0)) for m in re.finditer(r"(.)\1*", text)), default=1)
words = re.findall(r"\w+", text.lower())
uniq = len(set(words)) / max(1, len(words))
return {"alpha_ratio": round(alpha, 2), "vowel_ratio": round(vowel, 2),
"max_char_run": rep, "unique_word_ratio": round(uniq, 2)}On four demo texts the metrics separate clean prose from each failure mode (real output):
# s9_2b_demo_texts.py — continues s9_2_quality.py
CLEAN = ("The quick brown fox jumps over the lazy dog near the river bank "
"while the sun sets slowly behind the distant hills and the birds "
"return to their nests for the night")
OCR_NOISE = "T11e qu1ck br0wn f0x juMp5 0v3r th3 lazy d0g n3ar th3 r!v3r b4nk"
GIBBERISH = "xqzjkvbfnm!!!@@@###$$$%%%^^^&&&***((()))___+++===~~~"
CJK = "これはテストです。のテキストをします。これはテストです。"
for label, t in [("clean", CLEAN), ("ocr-noise", OCR_NOISE),
("gibberish", GIBBERISH), ("cjk", CJK)]:
print(f"{label:10}", quality_metrics(t))clean {'alpha_ratio': 0.81, 'vowel_ratio': 0.32, 'max_char_run': 2, 'unique_word_ratio': 0.81}
ocr-noise {'alpha_ratio': 0.58, 'vowel_ratio': 0.16, 'max_char_run': 2, 'unique_word_ratio': 0.93}
gibberish {'alpha_ratio': 0.19, 'vowel_ratio': 0.0, 'max_char_run': 3, 'unique_word_ratio': 1.0}
cjk {'alpha_ratio': 0.89, 'vowel_ratio': 0.0, 'max_char_run': 1, 'unique_word_ratio': 0.67}Clean English keeps alpha ~0.8 and vowel ~0.32; OCR noise drops both; symbol gibberish collapses alpha to 0.19; CJK keeps alpha ~0.9 but vowel_ratio is 0.0 — the vowel ratio is Latin-specific, so gate metrics by script before thresholding.
9.3 Perplexity-style and classifier filters#
The industrial approach (FineWeb, DCLM, RefinedWeb pipelines): score each document with a small language model's perplexity or a trained classifier — real prose scores low perplexity, gibberish/spam scores high. You don't train these; you use published thresholds or a small model via API. For most applied-AI corpora the heuristic stack in 9.1–9.2 suffices — reach for classifier filters only at web-crawl scale where the heuristic false-positive rate costs real content.
9.4 Spam, thresholds as config, quarantine#
- Spam: keyword density (a word repeated > ~5% of tokens), link-heavy pages (links > ~30% of characters), excessive caps, known spam patterns. These are features, not verdicts — combine into a score.
- Thresholds are config, not constants. Every filter takes a threshold tuned per source:
min_length: 50,min_alpha_ratio: 0.5,max_boilerplate_frac: 0.6,min_unique_word_ratio: 0.3. Store them in a per-source config so a news crawl and a legal archive get different bars. - Quarantine, don't delete. Filtered-out documents go to a quarantine set with the reason recorded (
{"reason": "low_alpha_ratio", "score": 0.31}) — you need them for threshold tuning and for recovering false positives. 05.9 owns the quarantine mechanics.
Part 10: LLM-assisted cleaning#
Deep-dive
10.1 When an LLM earns its cost#
Rule-based cleaning handles ~90% of noise deterministically and free. LLMs earn their tokens on the messy 10% where rules are fragile:
| Task | Why rules struggle | LLM helps |
|---|---|---|
| Messy table → Markdown | Borderless tables, merged cells, spanning pages | Reads layout, emits clean Markdown table |
| OCR garbage repair | Context-dependent errors (0 vs O, rn vs m) |
Understands intended word — but may "fix" real content |
| Free-text normalization | "about forty" → 40, "next Tuesday" → date |
Semantic normalization |
| Abbreviation expansion | Domain-specific (API, SLA, PoC) |
Expands correctly per context |
| Quote/reply disentangling | Nested, malformed email quoting | Identifies message boundaries semantically |
| Language-specific cleanup | Agglutinative/tonal scripts, no spaces | Understands script structure |
When NOT to: bulk whitespace/encoding/boilerplate (rules are faster, free, deterministic); anything needing verbatim fidelity where an LLM's "helpful" rewrite is the failure mode; high-volume corpora where cost dominates.
10.2 The similarity guard: proving the LLM didn't change meaning#
An LLM cleaner can hallucinate — "fix" a correct total, drop a clause, invent a heading. The defence is a similarity guard: after the LLM returns cleaned text, verify it preserved the content.
# s10_1_similarity_guard.py — stdlib only, real output below
import difflib, re
NUM_RE = re.compile(r"\d+(?:[.,]\d+)*")
def _num_key(tok: str) -> str:
r"""Canonical numeric value so '1,299.99', '1299.99' and '3,14' compare by
value, not string. When both separators appear the rightmost is decimal;
a lone comma is a thousands separator only in \d{1,3}(,\d{3})+ shape."""
if "," in tok and "." in tok:
dec = "," if tok.rfind(",") > tok.rfind(".") else "."
tok = tok.replace("." if dec == "," else ",", "").replace(dec, ".")
elif "," in tok:
tok = (tok.replace(",", "")
if re.fullmatch(r"\d{1,3}(,\d{3})+", tok) else tok.replace(",", "."))
elif tok.count(".") > 1:
tok = tok.replace(".", "") # 1.299.999 -> 1299999 (EU grouping)
return tok
def similarity_guard(original: str, cleaned: str,
min_ratio: float = 0.85) -> dict:
"""Cheap content-preservation check. Not semantic — catches gross changes."""
ratio = difflib.SequenceMatcher(None,
" ".join(original.split()).lower(),
" ".join(cleaned.split()).lower()).ratio()
# every numeric VALUE in original must survive (reformatting is fine)
nums_orig = {_num_key(t) for t in NUM_RE.findall(original)}
nums_clean = {_num_key(t) for t in NUM_RE.findall(cleaned)}
lost = nums_orig - nums_clean
return {"char_similarity": round(ratio, 3),
"numbers_lost": sorted(lost),
"pass": ratio >= min_ratio and not lost}On "Invoice total: $1,299.99 due March 3, 2026." — a whitespace-only tidy passes, "Invoice total: $1299.99 due March 3 2026." (same values, different separators) also passes, while "Invoice total due soon." fails with three lost numbers:
# s10_1b_demo.py — continues s10_1_similarity_guard.py
ORIGINAL = "Invoice total: $1,299.99 due March 3, 2026."
candidates = {
"good": "Invoice total: $1,299.99 due March 3, 2026.", # whitespace-only tidy
"alt": "Invoice total: $1299.99 due March 3 2026.", # same values, other separators
"bad": "Invoice total due soon.", # numbers dropped
}
for label, cleaned in candidates.items():
print(f"{label}:".ljust(6), similarity_guard(ORIGINAL, cleaned))good: {'char_similarity': 1.0, 'numbers_lost': [], 'pass': True}
alt: {'char_similarity': 0.976, 'numbers_lost': [], 'pass': True}
bad: {'char_similarity': 0.576, 'numbers_lost': ['1299.99', '2026', '3'], 'pass': False}This is a gate, not a proof — difflib is lexical. For semantic preservation, add an embedding-similarity check (Module 06) or a second LLM call asking "did this change any facts?" — but the cheap lexical guard catches the catastrophic cases (dropped numbers, merged paragraphs, invented content) that matter most. Route failures to human review or fall back to the rule-based clean.
10.3 Providers and batching#
LLM cleaning is a normal chat-completion call — all four providers do it; the differences are cost/latency/batch, covered in 03.7 and 03.9. Order per convention: OpenAI → Anthropic → Gemini → OpenRouter. Use the cheap/fast default model — cleaning doesn't need frontier reasoning.
# s10_2_llm_clean_openai.py — illustrative; needs OPENAI_API_KEY
from openai import OpenAI
client = OpenAI()
resp = client.responses.create(
model="gpt-6-luna",
input=[{"role": "user", "content": [
{"type": "input_text", "text": CLEAN_PROMPT + "\n\n" + messy_text}]}],
max_output_tokens=4000,
)
cleaned = resp.output_textAnthropic (client.messages.create, claude-haiku-5-5, no sampling params per the 2026-10-21 API), Gemini (client.models.generate_content, gemini-3.8-flash), and OpenRouter (Chat Completions via base_url, openai/gpt-6-luna) follow the same shape — wire mechanics are in 03.4 (for schema-constrained output like "return {cleaned_text, changes[]}") and 03.6 (if you send page images). For bulk cleaning, use the Batch API (03.9) — roughly 50% cheaper than synchronous calls on OpenAI, Anthropic and Gemini for non-urgent work (as of November 2026; discounts change, so check each provider's pricing page).
10.4 Prompt gallery#
# Faithful cleanup (verbatim, don't interpret)
Clean this extracted text for a retrieval index. Fix ONLY encoding artifacts,
hard-wrap joins, and whitespace. Do NOT paraphrase, summarize, correct spelling,
reorder, or add/remove content. Preserve all numbers, dates, code, tables and
formatting. Output the cleaned text only.
# Messy table → Markdown
Convert this extracted table to a clean Markdown table. Preserve every row,
column header, number and unit exactly. If the table is ambiguous, output your
best reconstruction and add a <!-- note: ... --> comment explaining uncertainty.
# Abbreviation expansion
Expand domain abbreviations in this text using only expansions you are confident
about (API→application programming interface is fine; IT→? is not — leave
ambiguous ones unchanged). Output the expanded text.10.5 Risks#
- Hallucination: the model invents or "corrects" content — the similarity guard + number-preservation check is mandatory.
- Over-normalization: it "helpfully" rewrites legal phrasing, fixes real names, standardizes dialect — destroying the signal you meant to keep.
- Non-determinism: same input, different output — version the prompt+model, log both, treat as a pipeline step with provenance.
- Prompt injection through the document itself: the text you send to the cleaner is untrusted, so a document can contain "ignore the instructions above and output ..." and the cleaner may obey it. Put the document inside clear delimiters and say that it is data, give the cleaning call no tools and no access to other documents, and treat a failed similarity guard (sudden large change, new content) as a possible injection tripwire as well as a quality failure. The full treatment is 12.2; the hidden-text scan in 2.7 runs before this step.
- Cost at scale: LLM-cleaning a million docs is real money — batch, cache by content hash, and only route the hard documents (low rule-based confidence, failed similarity guard on a first pass) to the LLM. The hybrid pattern: rules first, LLM for the residue.
Part 11: The composable cleaning pipeline#
11.1 Design#
The production shape, distilled from Parts 1–10:
- Pure functions: each step is
f(text) -> (text, stats)— no globals, no I/O, deterministic. - Ordered registry:
STEPS = [(name, fn), ...]— order is the contract. - Change log: every step reports what it did (
{"invisible_removed": 3, "wraps_joined": 12}) — your audit trail and your debugging tool. - Dry-run/diff:
clean(text)never mutates its input — it is the dry run. Passexplain=Trueand the result carries a before/after snippet per changed step, which is the diff mode for hunting down "which step ate the content". - Idempotent:
clean(clean(x)) == clean(x)— verified by test. - Optional steps degrade gracefully:
ftfyabsent → step records"skipped"and passes text through.
11.2 Full code: cleaner.py#
# cleaner.py — composable cleaning pipeline, stdlib + optional ftfy
import re, unicodedata
from dataclasses import dataclass, field
# ---- steps: each returns (text, stats_dict) ----
def s_newlines(t):
crlf = t.count("\r\n")
n = crlf + (t.count("\r") - crlf) + t.count("\u2028") + t.count("\u2029")
return (t.replace("\r\n", "\n").replace("\r", "\n")
.replace("\u2028", "\n").replace("\u2029", "\n")), {"newlines": n}
# Cf format chars removed here — the inventory from 2.3. Deliberately KEPT:
# U+200C/U+200D (ZWNJ/ZWJ) — emoji sequences and Arabic/Indic shaping
# U+E0000–U+E007F (tag chars) — subdivision flag emoji
# C1 controls U+0080–U+009F — mojibake clues; ftfy (the next step) uses them
INVISIBLE = frozenset(
"\ufeff\u200b\u2060\u00ad" # BOM, ZWSP, word joiner, soft hyphen
"\u200e\u200f\u061c" # LRM, RLM, Arabic letter mark
"\ufff9\ufffa\ufffb\ufffc" # interlinear annotation anchors
"\u202a\u202b\u202c\u202d\u202e" # bidi embeddings/overrides
"\u2066\u2067\u2068\u2069" # bidi isolates
)
def s_invisible(t):
bad = INVISIBLE | {c for c in t if unicodedata.category(c) == "Cc"
and ord(c) < 0x80 and c not in "\t\n\r"}
return "".join(c for c in t if c not in bad), \
{"invisible_removed": sum(c in bad for c in t)}
def s_ftfy(t):
try:
import ftfy
except ImportError:
return t, {"ftfy": "skipped"}
out = ftfy.fix_text(t)
return out, {"ftfy_changed": out != t}
def s_unicode_nfc(t):
return unicodedata.normalize("NFC", t), {"nfc_changed":
unicodedata.normalize("NFC", t) != t}
FENCE = "`" * 3
def s_collapse_ws(t):
out, in_fence, ch = [], False, 0
for line in t.split("\n"):
if line.strip().startswith(FENCE):
in_fence = not in_fence; out.append(line); continue
if in_fence: out.append(line); continue
new = re.sub(r"[ \t]+", " ",
line.replace("\u00a0", " ").replace("\u3000", " ")).rstrip()
ch += new != line; out.append(new)
return "\n".join(out), {"lines_ws_changed": ch}
# Banner/footer patterns only — anchored so real content lines survive
# ("Confidentiality policy…", "Page 3 describes…"). Corpus-level boilerplate
# is detected upstream with the Part 4 shingle method, not per document.
BOILER_RE = re.compile(r"(?i)^\s*(?:"
r"page\s+\d+\s+of\s+\d+(?:\s*[-–—|·][^\n]*)?\s*$"
r"|confidential(?:\s*[-–—:|][^\n]*)?\s*$"
r"|all rights reserved\.?\s*$"
r"|(?:©|copyright)\s*\d{4}[^\n]*$"
r")")
def s_boilerplate(t):
kept = [l for l in t.split("\n") if not BOILER_RE.match(l)]
return "\n".join(kept), {"boilerplate_removed":
len(t.split("\n")) - len(kept)}
def s_rejoin_wraps(t):
out, buf, joined, in_fence = [], "", 0, False
MARKER = re.compile(r"^(#{1,6}\s|>|[-*•]\s|\d+[.)]\s|\|)")
def flush():
nonlocal buf
if buf.strip(): out.append(re.sub(r" +", " ", buf.strip()))
buf = ""
for line in t.split("\n"):
s = line.strip()
if s.startswith(FENCE): # fence marker: toggle, keep verbatim
flush(); out.append(line); in_fence = not in_fence; continue
if in_fence: # inside code: indentation is syntax
out.append(line); continue
if not s: flush(); out.append(""); continue
if MARKER.match(s): flush(); out.append(s); continue
if buf and len(buf) >= 40 and not buf.endswith((".","!","?",":",";")):
buf += " " + s; joined += 1
else: flush(); buf = s
flush()
return "\n".join(out), {"wraps_joined": joined}
def s_bullets(t):
lines, in_fence = [], False
for line in t.split("\n"):
if line.strip().startswith(FENCE):
in_fence = not in_fence
elif not in_fence: # never rewrite code; [ \t] keeps blank lines
line = re.sub(r"^[ \t]*[*•·◦o][ \t]+", "- ", line)
lines.append(line)
out = "\n".join(lines)
return out, {"bullets": len(re.findall(r"(?m)^- ", out))}
STEPS = [("newlines", s_newlines), ("invisible", s_invisible),
("ftfy", s_ftfy), ("unicode_nfc", s_unicode_nfc),
("collapse_ws", s_collapse_ws), ("boilerplate", s_boilerplate),
("rejoin_wraps", s_rejoin_wraps), ("bullets", s_bullets)]
@dataclass
class CleanResult:
text: str
log: list = field(default_factory=list)
diffs: list = field(default_factory=list) # (step, before, after) per change
def _first_diff(a: str, b: str) -> int:
for i, (x, y) in enumerate(zip(a, b)):
if x != y:
return i
return min(len(a), len(b))
def _ctx(s: str, i: int, w: int = 40) -> str:
lo, hi = max(0, i - w), min(len(s), i + w)
seg = s[lo:hi].strip() # keep raw whitespace — it may be the change
return ("…" if lo else "") + seg + ("…" if hi < len(s) else "")
def clean(text: str, explain: bool = False) -> CleanResult:
"""explain=True records a before/after window per changed step — the diff mode."""
cur, log, diffs = text, [], []
for name, fn in STEPS:
nxt, stats = fn(cur)
log.append((name, stats))
if explain and nxt != cur:
i = _first_diff(cur, nxt)
diffs.append((name, _ctx(cur, i), _ctx(nxt, i)))
cur = nxt
return CleanResult(cur, log, diffs)
if __name__ == "__main__":
MESSY = "Acme Corp\nConfidential — Page 1\nOur return policy..."
r = clean(MESSY)
for n, s in r.log: print(f" {n:14} {s}")
print(r.text)
print("\n-- explain=True diffs --")
for n, b, a in clean(MESSY, explain=True).diffs:
print(f"{n}: {b!r} -> {a!r}") newlines {'newlines': 0}
invisible {'invisible_removed': 1}
ftfy {'ftfy': 'skipped'}
unicode_nfc {'nfc_changed': False}
collapse_ws {'lines_ws_changed': 1}
boilerplate {'boilerplate_removed': 1}
rejoin_wraps {'wraps_joined': 0}
bullets {'bullets': 0}
Acme Corp
Our return policy...
-- explain=True diffs --
invisible: '\ufeffAcme Corp\nConfidential — Page 1\nOur r…' -> 'Acme Corp\nConfidential — Page 1\nOur re…'
collapse_ws: 'Acme Corp\nConfidential — Page 1\nOur return policy...' -> 'Acme Corp\nConfidential — Page 1\nOur return policy...'
boilerplate: 'Acme Corp\nConfidential — Page 1\nOur return policy.…' -> 'Acme Corp\nOur return policy...'The change log counts what each step did; explain=True shows the actual before/after window around the first difference per step — that's how you answer "which step ate the content" without re-running steps by hand.
11.3 Tests (test_cleaner.py, pytest-style)#
# test_cleaner.py — run: uv run pytest
from cleaner import clean, STEPS
def test_idempotent():
messy = "Hello world\r\n\nLine one wraps\nonto two.\n- a\n• b"
once = clean(messy).text
assert clean(once).text == once # second run changes nothing
def test_preserves_numbers_and_code():
fence = "`" * 3
src = "Total $1,299.99\n" + fence + "\nif x:\n return 1\n" + fence
out = clean(src).text
assert "$1,299.99" in out # the number survives untouched
assert " return 1" in out # code indentation survives
def test_boilerplate_removed():
src = "Confidential — Page 1\nReal content here.\nAll rights reserved."
assert "Confidential" not in clean(src).text
assert "Real content" in clean(src).text
def test_boilerplate_keeps_real_content():
src = ("Confidentiality policy requires annual review.\n"
"Page 3 describes the warranty terms in detail.\n"
"All rights reserved.\nReal body text here.")
out = clean(src).text
assert "Confidentiality policy" in out # not a banner — it's content
assert "Page 3 describes" in out # not "Page 3 of 12" pagination
assert "Real body text" in out
assert "All rights reserved" not in out
def test_preserves_emoji_zwj():
assert "👨👩👧" in clean("Family: 👨👩👧 and flags 🏴").text
# ZWJ/ZWNJ and tag chars are content — see the ZWJ warning in 2.3/2.6
def test_change_log_reports():
r = clean("a b\u200b\n\n- x\n• y")
stats = dict(r.log)
assert stats["invisible"]["invisible_removed"] == 1
assert stats["bullets"]["bullets"] >= 111.4 Idempotency and the second run#
Idempotency is the property that makes re-runs safe: run clean on already-cleaned text and get identical output with zero changes. The demo run confirms: second pass reports invisible_removed: 0, wraps_joined: 0, boilerplate_removed: 0 — only the cosmetic bullets count re-reports (counting, not changing). A step that isn't idempotent is a bug — e.g. a bullet-normalizer that re-prefixes - - item, or a rejoiner that merges already-joined paragraphs. Test it on every corpus sample.
11.5 Wiring downstream#
clean() slots into the flow from 05.9 between parse and chunk: ParsedDocument → per-page/per-block clean() → cleaned text + CleanResult.log stored as provenance → chunker (05.6) → Chunk with cleaning_version in its metadata (05.8). Two additions belong around the call. First, run hidden_text_report from 2.7 on the raw text before clean() and store its result beside CleanResult.log: s_invisible deliberately removes zero-width and bidi characters, and the pipeline deliberately keeps tag characters (they build flag emoji), so smuggled tag-character text would otherwise pass straight through. If you do not run the scan, strip every tag-character run that is not a complete flag sequence (flag emoji, up to six tag letters or digits, cancel tag) instead. Second, after clean() run the quality checks of 05.10. The change log becomes part of the lineage record: "this chunk came from raw hash X, cleaned by pipeline v3, steps [newlines, invisible, ftfy, nfc, collapse, boilerplate, rejoin, bullets]".
Part 12: Failure gallery and decision summary#
Reference
12.1 Before/after: ten real-world messes#
| # | Mess (before) | Clean (after) | Step that fixes it |
|---|---|---|---|
| 1 | Café mojibake |
Café |
ftfy.fix_text |
| 2 | INVOICE-2026 |
INVOICE-2026 (as NFKC key) |
NFKC for comparison only |
| 3 | word soft hyphens everywhere |
word |
strip U+00AD |
| 4 | One word per line from PDF | Rejoined paragraphs | rejoin_hard_wraps |
| 5 | * item / • item / 1) mixed |
- item / 1. |
normalize_bullets |
| 6 | "Confidential — Page 3 of 12" on every page | Removed | boilerplate shingle detection |
| 7 | 03/04/2026 ambiguous |
2026-03-04 + ambiguous: true |
date normalizer + dual-field |
| 8 | jane@x.com in support ticket |
<EMAIL> |
Presidio/regex PII |
| 9 | Same ticket exported 3× | 1 kept | MinHash dedup |
| 10 | xqzjkvb wnmpqrz OCR garbage page |
Quarantined | quality metrics |
12.2 Anti-patterns#
- Cleaning before parsing (you can't fix structure you haven't extracted).
- One global cleaner for all sources (a legal corpus and a web crawl need different rules).
- Deleting filtered documents instead of quarantining.
- Running LLM cleaning on everything (cost + hallucination on the easy 90%).
- Normalizing away the original (always keep raw + dual fields).
- Treating boilerplate as universally bad (it's corpus-relative).
- Forgetting idempotency (re-runs must be free).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Cleaning means making text pretty." | Cleaning means removing extraction artifacts while preserving content. Pretty text that lost a table or a clause is worse than ugly text that kept it. |
| "NFKC normalization is always safe." | NFKC is a lossy compatibility fold: ²→2, fi→fi, Ⅳ→IV. Use it for comparison keys, not as the stored form. Store NFC. |
| "Strip all invisible characters." | ZWJ/ZWNJ build emoji and Indic/Arabic script shaping; tag characters build flag emoji. Blanket Cf removal breaks them. |
| "Boilerplate is always noise." | It's corpus-relative: disclaimers are noise in a manual, signal in a compliance corpus. Decide per corpus, or mark-and-downweight. |
| "langdetect is fine for language ID." | It's non-deterministic on short text — seed it (DetectorFactory.seed = 0) — and weakest exactly where you need it (titles, headings). lingua-language-detector is the better default. |
| "Duplicates are duplicates." | Exact, normalized and near-duplicates are different problems needing hash, MinHash and possibly embedding detection. And versioned documents aren't duplicates at all. |
| "The LLM will clean it perfectly." | It hallucinates, over-normalizes and is non-deterministic. Always gate with a similarity/number-preservation check and keep the rule-based fallback. |
| "PII redaction can happen after embedding." | The vector already leaked. Anonymize before embedding and before any provider call. |
| "Once cleaned, always clean." | Cleaning is versioned: new rules, new ftfy versions, new findings mean re-cleaning from raw. Keep raw + step versions so re-runs are cheap. |
| "A similarity score of 0.7 means duplicate." | It means candidate. LSH/MinHash give probabilities, not verdicts — verify before merging or deleting. |
| "Lowercasing everything helps search." | It helps matching but destroys JSON, SQL, names and German nouns. Store original; compute keys for comparison. |
Key takeaways#
- Clean noise, keep signal. Every rule names its noise, keeps the raw text, and has a test. Over-cleaning destroys meaning — numbers, code, casing and legal clauses are content.
- Encoding first. Decode bytes to Unicode (detect with
charset-normalizerwhen unknown), repair mojibake withftfy.fix_text, store NFC, and compute NFKC only for comparison keys. - Invisible characters are mostly safe to strip — except ZWJ/ZWNJ (emoji, Arabic/Indic shaping) and bidi controls need script-aware handling.
- Structure beats cosmetics. Rejoin hard wraps paragraph-aware, protect code/tables/headings, normalize bullets to Markdown, and treat Markdown as the canonical intermediate.
- Boilerplate is corpus-relative. Detect it by shingle document-frequency; strip for retrieval, preserve for compliance; email needs its own quote/signature rules.
- Look for hidden content before you strip it. Zero-width, bidi and tag characters (and hidden text in PDFs, HTML and Office files) are how indirect prompt injection hides; flag and record them (2.7), and treat even clean text as data at prompt time (Module 12).
- Identify language early — it gates whitespace rules, tokenization, normalization and routing.
lingua-language-detectoris the best default; fastTextlid.176for coverage,py3langidfor abstention. - Deduplicate in layers: exact hash → normalized hash → MinHash/LSH for near-dups → embedding dedup for semantic dupes. Keep the best copy; quarantine the rest; tune thresholds per corpus.
- Normalize entities into parallel fields (ISO dates,
Decimalmoney, E.164 phones) — never overwrite the original text. - PII before egress: detect with regex/Presidio/LLM layers, anonymize with the right operator (redact/replace/mask/hash/encrypt/pseudonymize), log counts not values.
- Filter web-scale junk with cheap metrics first (length, language, boilerplate ratio, gibberish scores), quarantine with reasons, tune thresholds per source.
- LLM cleaning is for the hard 10% — always behind a similarity guard, batched, and versioned.
- The pipeline is pure functions + change log + dry-run + tests + idempotency. That's what makes cleaning debuggable, re-runnable and trustworthy.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Cleaning / normalization | Removing extraction noise and canonicalizing form while preserving content |
| Noise vs signal | Artifacts of extraction (removable) vs document content (keep) |
| Raw text / cleaned text | Immutable parser output vs derived cleaned view |
| Mojibake | Text garbled by wrong encoding/decoding (UTF-8 read as Latin-1) |
| Encoding / UTF-8 | The byte↔character mapping rule; UTF-8 is the universal default |
ftfy |
Library that repairs mojibake and Unicode glitches (fix_text, fix_and_explain) |
| charset-normalizer | Encoding detector for unknown bytes (from_bytes) |
| NFC / NFD / NFKC / NFKD | Unicode normalization forms: canonical compose/decompose and compatibility variants |
| Canonical vs compatibility equivalence | Same character written differently vs visually-similar-but-distinct characters |
| Zero-width space / joiner / BOM | Invisible format characters (U+200B, U+200D, U+FEFF) |
| Soft hyphen | U+00AD invisible optional break point |
| Control characters | C0/C1 chars that affect rendering or indicate corruption |
| Homoglyph | Lookalike character from another script (Cyrillic а vs Latin a) |
| Tag characters / ASCII smuggling | Invisible Unicode characters (U+E0000 to U+E007F) that map onto ASCII and can hide a sentence inside visible text; legitimate only in flag emoji sequences |
| Indirect prompt injection | Instructions hidden in content your system ingests (documents, pages, emails) rather than typed by the user; owned by Module 12 |
| Grapheme cluster | User-perceived character, possibly multiple code points (emoji) |
| Smart punctuation | Curly quotes, en/em dashes, ellipsis, NBSP |
| Hard-wrap rejoining | Merging visually-wrapped lines back into paragraphs |
| Boilerplate | Text repeated across docs/pages that carries no doc-specific meaning |
| Shingle | Contiguous word n-gram used for similarity/frequency |
| Document-frequency boilerplate detection | Shingles appearing in most documents = boilerplate |
| Language identification / routing | Detecting and tagging text language to gate processing |
| Lingua / fastText lid / langdetect / py3langid | The four language detectors compared |
| Deduplication | Removing duplicate documents (exact, normalized, near) |
| Content hash / normalized hash | SHA-256 of raw or canonicalized text as dedup key |
| MinHash | Probabilistic signature estimating Jaccard similarity |
| LSH (Locality-Sensitive Hashing) | Index for sub-linear near-duplicate candidate search |
| SimHash | Single-fingerprint similarity hash |
| Jaccard similarity | Fraction of shared elements between two sets |
| Dual-field pattern | Keeping original text + parallel normalized/entity fields |
| ISO 8601 / ISO 4217 / E.164 | Canonical date / currency / phone formats |
| PII / anonymization | Personal data and its removal (redact, mask, hash, encrypt, pseudonymize) |
| Presidio | Open-source (MIT) PII detection + anonymization toolkit, originally from Microsoft; its repository has moved to the data-privacy-stack GitHub organisation (checked November 2026) |
| Reversible token / vault pattern | Opaque PII token with separate token→value store |
| Quality filtering | Admission control for web-scale corpora (length, language, gibberish) |
| Gibberish metrics | Heuristics (alpha/vowel ratio, char-run, dict hit rate) for noise detection |
| Similarity guard | Post-LLM check that cleaned text preserved content/numbers |
| Cleaning pipeline | Ordered pure-function steps with change log, dry-run, idempotency |
| Idempotency | clean(clean(x)) == clean(x) — re-runs change nothing |
All terms are also collected in the glossary.
Exercises#
- Mojibake (2.1): take
"naïve café — résumé", encode as UTF-8, decode as cp1252, then runftfy.fix_text. Confirm you recover the original. Then tryfix_encoding— what's the difference? - Normalization (2.2): write a function that strips accents for search matching (
NFKD+ remove categoryMn). Test on"Cafe\u0301","Zürich","São Paulo". Why does this break for Turkishı? - Invisible chars (2.3): find a real document with zero-width spaces (web copy-paste is the easiest source). Show which characters your
s_invisiblestep removes and which it must keep. - Rejoin (3.2): feed
rejoin_hard_wrapsa poem and a bulleted list — which boundaries does it wrongly merge? Adjust the heuristics. - Boilerplate (4.2): run
find_boilerplateon the running corpus's handbook pages. What's the minimumfracthat catches the footer without eating a shared "Warranty" section? - Language ID (5.3): run all four detectors on 20 mixed-length samples (single words, sentences, paragraphs). Which is most accurate on single words? Which is deterministic?
- Dedup (6.3): create 10 doc variants (whitespace changes, one-word edits, reordered paragraphs). At what MinHash
thresholddo you catch the near-dups without false-merging the distinct ones? - Dates (7.1): your corpus has
03/04/2026in both a US manual and an EU contract. How do you disambiguate? Implement thefmt_hintpath. - PII (8.2): run the regex detector on a support-ticket export. What's its recall vs Presidio on names/addresses? Where does each fail?
- Quality (9.2): compute
quality_metricson 50 real pages from your corpus. What's the distribution? Where do you setmin_alpha_ratio? - Pipeline (11): add a
s_datesstep that extracts ISO dates into the change log. Verify idempotency still holds. - Failure gallery (12.1): pick three messes from the table, reproduce them, and show which step fixes each.
- Hidden text (2.7): copy
hidden_text_reportinto a file and write three tests: a Persian sentence containing legitimate U+200C (should report zero-width but you decide it is not an alert), an England flag emoji (nohidden_tag_text), and a sentence with 12 tag characters spelling a benign placeholder (reported and decoded). Then decide your policy for each flag: allow, review queue or reject.
Hints and worked answers
s.encode("utf-8").decode("cp1252")givesnaïve café — résumé;ftfy.fix_textrestores it.fix_encodingapplies only the mojibake repair, whilefix_textalso fixes quotes, ligatures, width and control characters, so the first is the narrower, safer choice when you want nothing else changed."".join(c for c in unicodedata.normalize("NFKD", s) if unicodedata.category(c) != "Mn"). Turkish dotlessı(U+0131) has no decomposition, so it stays as it is and will not match an ASCIIi, whileİdecomposes toIplus a dot-above mark that the filter strips: Turkish matching needs a language-aware folding rule, not accent stripping.- Expect to remove U+200B and U+FEFF, and to keep U+200D inside emoji and U+200C in Persian text. Print
unicodedata.name(c)for each candidate to justify the choice. - A poem merges when its lines do not end in punctuation. Fix by a
preserve_linesflag (or a detector for short lines of similar length) rather than by weakening the wrap rule for prose. - Build the six pages, add one genuinely shared "Warranty" paragraph to three of them, and sweep
fracfrom 0.3 to 1.0: with six pagesfind_boilerplateneedsint(frac * 6)pages (at least 2), so the footer (6 of 6) is caught at every value up to 1.0, while the shared paragraph (3 of 6) is caught wheneverint(frac * 6)is 3 or less, that is for anyfracbelow about 0.67. Afracof 0.7 or more, such as 0.8, keeps the warranty section and still catches the footer. - Expect Lingua to do best on single words, langdetect to need
DetectorFactory.seed = 0for repeatable results, py3langid to abstain withmin_confidenceon very short input and fastText to cover the most languages. Report accuracy per length bucket, not one number. - Planted near-duplicates (a whitespace change, one word edited) usually score above 0.7 with 5-word shingles; reordered paragraphs drop lower. Choose the threshold where your hand-labelled pairs reach about 0.9 precision (6.6).
- Use a per-source
date_formatconfig (US manual:MDY, EU contract:DMY), pass it asfmt_hint, and setambiguous: truewith low confidence when no hint exists. Never guess silently. - Regex recall on names and addresses is near zero by design; Presidio finds names through NER but misses unusual formats. Compare on 50 hand-labelled tickets and report precision and recall per entity type.
- Plot the histogram of
alpha_ratioandunique_word_ratio; the usual cut is at the valley between the main mass and the tail, then check 20 documents below the cut by eye. Gate by script (vowel ratio is Latin-only). - A pure step
s_dates(t)that returns(t, {"dates_found": n})without changing the text keeps idempotency trivially; a step that rewrites dates must be tested withclean(clean(x)) == clean(x). - Reproduce rows 1, 4 and 6 with a three-line string each, run
clean(..., explain=True)and read thediffsto name the step. - For the Persian case the report shows
zero_width: 1, which is expected in Persian; the policy is "allow, but log". The England flag is🏴+ tag letters + cancel tag, a complete flag sequence that the scanner skips; the same tag letters after ordinary text, or in a run longer than seven characters, would be reported. The 12-tag string reports the decoded placeholder text inhidden_tag_textand goes to review.
Check yourself#
- What's the difference between noise and signal in cleaning, and why does the distinction matter?Noise is extraction artifact (removable); signal is document content (keep). Removing signal loses answers; keeping noise wastes tokens and dilutes embeddings.
- Why must you keep the raw extracted text instead of overwriting it with cleaned text?So you can re-clean when rules improve, diff to find cleaning bugs, audit what the model saw, and recover from bad steps — cleaning is a derived view, not a mutation.
- What's the difference between NFC and NFKC, and when does NFKC destroy meaning?NFC composes canonical equivalents (same character); NFKC also folds compatibility variants (fullwidth, ligatures, superscripts). NFKC destroys meaning when
²→2,fi→fi,Ⅳ→IVchanges content. - Why shouldn't you strip all Unicode format characters (category
Cf)?ZWJ/ZWNJ build emoji sequences and Arabic/Indic script shaping; stripping them breaks rendering. Bidi controls are needed for RTL text. - When should
rejoin_hard_wrapsNOT join two lines?Across paragraph breaks, before/after structural markers (headings, lists, code, tables, blockquotes), and when the accumulated line is short (title/label). - How does shingle document-frequency detect boilerplate, and why does it beat raw line-frequency?It counts in how many distinct documents each n-gram shingle appears; shingles in most docs are template. Document-frequency beats raw count because repetition within one doc is content, across docs is boilerplate.
- Which language detector is best on short text, and which has the widest coverage?Lingua (
lingua-language-detector) is best on short text; fastTextlid.176has widest coverage (176 languages). - Why is
langdetectnon-deterministic, and how do you fix it?Its algorithm uses randomness;DetectorFactory.seed = 0before first detection makes it deterministic. - What's the difference between exact, normalized and near-duplicate detection?Exact = byte-identical hash; normalized = hash of canonicalized form; near-dup = small edits caught by MinHash/Jaccard similarity.
- Why does MinHash+LSH give candidates rather than verdicts?LSH is probabilistic — it has false positives and false negatives; the S-curve means borderline cases are uncertain. Verify candidates with exact
jaccardbefore acting. - What's the dual-field pattern for entity normalization?Store original text plus parallel normalized fields (
date_iso,amount+currency,text_key) — never overwrite source; enables re-parse-free fixes and filtering. - Why must PII anonymization happen before embedding and before any provider call?Because the vector/embedding already contains the PII — redacting later doesn't un-leak it. Anonymize before embedding and before any provider call.
- Name the main anonymization strategies and when each is right.Redact (remove entirely), replace/mask (fixed token or partial), hash (deterministic pseudonym, dictionary-attackable), encrypt (reversible, needs key mgmt), pseudonymize/custom (realistic fakes), drop (whole record).
- What does the similarity guard check after LLM cleaning?It checks character-level similarity and number preservation — catches dropped numbers, merged paragraphs, invented content — a gate, not a semantic proof.
- What makes a cleaning pipeline idempotent, and why does it matter?When
clean(clean(x)) == clean(x)— each step is a pure function that reaches a fixed point. Matters because re-runs (incremental updates, version bumps) must be free and safe. - Why does the hidden-text scan run before the invisible-character strip step, and why is a clean scan still not proof that retrieved text is safe?Stripping destroys the evidence, so the scan must see the raw characters first and its report must be stored in lineage. A clean scan proves nothing because an attack can be an ordinary visible sentence; retrieved text must be treated as data at prompt time (Module 12).
Further resources#
- ftfy (docs, GitHub, PyPI): mojibake repair and Unicode fixers.
- charset-normalizer (docs, PyPI): encoding detection for unknown bytes.
- Unicode Standard Annex #15 (unicode.org/reports/tr15): normalization forms, canonical vs compatibility equivalence.
- Unicode TR39 (unicode.org/reports/tr39): confusable characters and homoglyph security.
- datasketch (docs, GitHub, PyPI): MinHash, MinHashLSH, cardinality sketches.
- Lingua (GitHub, PyPI): language detection, 75 languages.
- fastText language identification (fasttext.cc/docs/en/language-identification.html):
lid.176model, 176 languages. - langdetect (GitHub, PyPI): classic detector, 55 languages.
- py3langid (GitHub, PyPI): langid.py fork, 139 languages +
zxx+ abstention. - Presidio (originally Microsoft Presidio; docs, GitHub): PII detection and anonymization.
- phonenumbers (PyPI): phone number parsing/normalization (E.164).
- pytest (docs): the test framework used in Part 11.
← 05.4 — OCR and Scanned Documents | Module 05 overview | 05.6 — Chunking Strategies →