Sub topic 4
Loading and cleaning source documents
This chapter covers the first stage of a RAG pipeline: getting raw files into clean text. It assumes you know basic Python, can read JSON, and have the pipeline overview from the earlier chapter. Everything downstream (chunking, embeddings, retrieval) can only be as good as the text you produce here.
Why this stage matters
An embedding model sees only the text you give it. If a PDF extraction leaves "Page 3 of 40" in the middle of every paragraph, or a web page includes its navigation menu, that noise lands in your chunks and in your vectors. Retrieval then matches on boilerplate instead of content. Most "the model ignored my document" bugs start here.
Loading: one format at a time
Each source type needs its own loader. Each loader should return the same shape, so later stages don't care where text came from.
- Plain text and Markdown: read the file. Check the encoding, because a wrong guess produces garbled characters.
- HTML: strip scripts, styles, navigation, and footers. Keep headings, since they carry structure.
- PDF: text extraction can break line order in multi-column layouts and drops text in scanned pages. Scanned PDFs need OCR (optical character recognition).
- Tables and spreadsheets: flattening rows into text often loses the column meaning. Consider writing each row as "column: value" pairs.
Always keep metadata with the text: source path or URL, title, page number, and a last-modified date. You need it later for citations and filtering.
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class Document:
text: str
metadata: dict = field(default_factory=dict)
def load_text_file(path):
p = Path(path)
text = p.read_text(encoding="utf-8", errors="replace")
return Document(
text=text,
metadata={"source": str(p), "title": p.stem, "modified": p.stat().st_mtime},
)Cleaning
Cleaning should be conservative. Remove what is clearly noise, and keep content you might need.
import re
import unicodedata
def clean_text(text):
text = unicodedata.normalize("NFKC", text) # unify look-alike characters
text = text.replace("\u00ad", "") # soft hyphens from PDFs
text = re.sub(r"(\w)-\n(\w)", r"\1\2", text) # rejoin words split across lines
text = re.sub(r"[ \t]+", " ", text) # collapse runs of spaces
text = re.sub(r"\n{3,}", "\n\n", text) # keep paragraph breaks, drop extras
return text.strip()
raw = "Retrieval-aug-\nmented generation\n\n\n\nworks well."
print(clean_text(raw))The de-hyphenation rule is a trade-off. It repairs "aug-\nmented", but it also joins legitimate compounds that happen to break at a hyphen. Test rules like this on real samples from your corpus.
Other common steps:
- Remove repeated headers, footers, and page numbers by finding lines that recur on many pages.
- Drop duplicate documents. Exact duplicates can be found by hashing the cleaned text. Duplicates waste index space and fill your top-k with copies of the same passage.
- Preserve paragraph breaks. The chunker in the next chapter uses them as natural split points.
Pipeline shape
Check your output
Before moving on, print a few cleaned documents and read them. Search them for leftover menu text, odd characters, and empty files. Ten minutes of reading here saves hours of debugging retrieval later.
Exercise
A PDF loader returns text where every page ends with the line "Confidential - Internal Use Only". Why is this a problem for retrieval, and how would you find and remove it?
Show answer
The line appears in many chunks, so those chunks all look similar to each other and to queries mentioning "internal" or "confidential", which adds noise to the vectors. To remove it, count how often each line occurs across pages, treat lines that repeat on most pages as headers or footers, and delete them during cleaning. Keep the page number in metadata if you need it for citations.