Sub topic 4
Loading and Cleaning Source Documents
This chapter assumes you can write basic Python (functions, dataclasses, pathlib), and that you know the RAG pipeline stages from the overview chapter. Ingestion is the first stage. It turns files, web pages, and exports into clean text records that the chunking stage can split.
Why ingestion sets the ceiling
Every later stage works on the text you produce here. If a PDF extractor emits page numbers in the middle of sentences, the chunker will split on them. The embedding model will encode them, and the generator may quote them. Retrieval cannot find text that was dropped during loading, and no reranker can repair a garbled passage.
Ingestion bugs are also hard to see. The pipeline still runs and still returns answers, but they are worse. So you inspect the loaded text directly instead of trusting the output of later stages.
What a loaded document is
Define one record type and use it for every source format. It needs three things:
- A stable
doc_id, such as a file path or URL. Updates and deletions depend on it later. - The cleaned
text. - A
metadatadictionary: source, format, title, last-modified date, access group, and a content hash.
Capture metadata now, because you cannot recover it after chunking. Metadata filtering, citations, and access control all read these fields later in the pipeline.
Loading by format
Each format has its own failure modes.
| Format | Typical problem | What to do |
|---|---|---|
| Plain text, Markdown | Unknown encoding, stray control characters | Decode as UTF-8, replace bad bytes, strip control characters |
| HTML | Navigation, scripts, cookie banners, footers | Drop non-content tags, keep block structure as line breaks |
| Headers and footers on every page, hyphenated line breaks, two-column text read in the wrong order, scanned pages with no text | Use a layout-aware extractor, remove repeated lines, flag pages with no text for OCR | |
| Office files, wikis, tickets | Markup and macros, comment threads mixed with content | Export through the vendor API when possible instead of scraping |
| Tables and spreadsheets | Rows lose meaning without their headers | Render each row with its column names, such as `name: X; price: Y` |
Keep headings when you can. A line like ## Refund policy helps the chunker keep sections together and gives the embedding model context.
Cleaning rules
Clean conservatively. Each rule below fixes a common problem, but each can also damage text if you apply it blindly.
- Normalize Unicode. NFKC normalization turns non-breaking spaces into plain spaces and ligatures such as "fi" into "fi". Without it, the same word can embed differently or fail an exact keyword match.
- Normalize line endings and whitespace. Collapse runs of spaces and tabs, and limit blank lines to one.
- Remove invisible characters. Zero-width spaces and control characters inflate token counts and break exact matching.
- Repair hyphenation. PDF extraction often leaves
inter-\nnational. Joining these lines helps, but it also joins legitimate compounds likestate-\nof-the-art. Accept a small error rate, or limit the rule to lowercase letters on both sides. - Strip boilerplate. Remove navigation, repeated page headers, and legal footers. Boilerplate that appears in thousands of documents makes chunks look alike and wastes index space.
- Remove duplicates. Hash the cleaned text and skip repeats. Duplicates fill your top-k results with the same passage.
Do not lowercase text, remove punctuation, or strip stop words. Those steps were common for older keyword systems. Modern embedding models and rerankers use case, punctuation, and word order as signals.
A working loader
The program below loads .txt, .md, and .html files, cleans them, drops empty and duplicate documents, and attaches metadata. It uses only the standard library, and the demo at the bottom creates its own sample files.
import hashlib
import re
import tempfile
import unicodedata
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
@dataclass
class Document:
doc_id: str
text: str
metadata: dict = field(default_factory=dict)
class _TextExtractor(HTMLParser):
SKIP = {"script", "style", "nav", "footer", "header", "aside"}
BLOCK = {"p", "div", "br", "li", "tr", "section", "article",
"h1", "h2", "h3", "h4", "h5", "h6"}
def __init__(self):
super().__init__()
self.parts = []
self.skip_depth = 0
def handle_starttag(self, tag, attrs):
if tag in self.SKIP:
self.skip_depth += 1
elif tag in self.BLOCK:
self.parts.append("\n\n")
def handle_endtag(self, tag):
if tag in self.SKIP:
self.skip_depth = max(0, self.skip_depth - 1)
elif tag in self.BLOCK:
self.parts.append("\n")
def handle_data(self, data):
if self.skip_depth == 0:
self.parts.append(data)
def html_to_text(raw):
parser = _TextExtractor()
parser.feed(raw)
parser.close()
return "".join(parser.parts)
def clean_text(text):
text = unicodedata.normalize("NFKC", text)
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"([a-z])-\n([a-z])", r"\1\2", text) # join hyphenated words
text = re.sub(r"[^\S\n]+", " ", text) # collapse spaces and tabs
text = "".join(
ch for ch in text
if ch == "\n" or unicodedata.category(ch)[0] != "C"
) # drop control/invisible chars
text = re.sub(r" ?\n ?", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def load_directory(root):
docs, seen = [], set()
for path in sorted(Path(root).rglob("*")):
suffix = path.suffix.lower()
if suffix not in {".txt", ".md", ".html", ".htm"}:
continue
raw = path.read_text(encoding="utf-8", errors="replace")
if suffix in {".html", ".htm"}:
raw = html_to_text(raw)
text = clean_text(raw)
if not text:
continue
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
if digest in seen:
continue
seen.add(digest)
docs.append(Document(
doc_id=path.as_posix(),
text=text,
metadata={
"source": path.as_posix(),
"format": suffix.lstrip("."),
"content_hash": digest,
"modified": path.stat().st_mtime,
},
))
return docs
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "a.html").write_text(
"<nav>Home | About</nav><h1>Refunds</h1>"
"<p>Refunds are issued within 14\u00a0days.</p>"
"<script>track()</script><footer>(c) Acme</footer>",
encoding="utf-8",
)
(root / "b.txt").write_text(
"Refunds are issued\nwithin 14 days.", encoding="utf-8"
)
(root / "c.txt").write_text(" \n\n ", encoding="utf-8")
for doc in load_directory(root):
print(doc.doc_id.split("/")[-1], repr(doc.text))Running it prints one record for a.html: the navigation, script, and footer are gone, and the non-breaking space is now a plain space. It prints another for b.txt, which keeps its line break because the cleaner does not join ordinary lines. It prints nothing for c.txt, which is empty after cleaning.
How the stage fits together
Common errors
- Cleaning too much. Removing all newlines destroys paragraph and list structure. The chunker then has no natural boundaries.
- Losing tables and code. Whitespace collapsing can break code blocks and aligned tables. If your corpus has them, handle those blocks separately and leave them unchanged.
- Silent extraction failures. A scanned PDF returns an empty string, not an error. Log every document that cleans to empty and count them per run.
- Dropping metadata. If you do not store the access group or source URL now, you cannot filter or cite by them later.
- Unstable ids. If
doc_idchanges when a file moves, re-ingestion creates duplicates in the index. Choose an id that survives renames, such as a document-system id. - Never looking at the output. Print a few random cleaned documents after every change to the loader. Reading 20 records catches most problems.
Exercises
Exercise
A PDF extractor leaves the line "Acme Corp Confidential - Page 7" at the top of every page. Why is this a problem for RAG, and how would you remove it without deleting real content?
Show answer
The line is repeated hundreds of times, so many chunks contain it. It adds noise to their embeddings, and it can be retrieved or quoted as if it were content. To remove it safely, count how often each line appears across a document's pages. Delete lines that repeat on most pages, after replacing the page number with a placeholder so "Page 7" and "Page 8" count as the same line. A fixed regex for this one line would also work, but it breaks when the footer changes.
Exercise
Your loader reports 2,000 documents loaded, but retrieval never returns anything from 300 scanned PDFs. What is the likely cause, and what change makes the problem visible?
Show answer
Scanned PDFs contain images, not text, so the extractor returns an empty string. The loader then drops them as empty, and they never reach the index. Log each discarded document with its path and reason, report the count at the end of every run, and send those files to an OCR step.