Learning path: Build and Measure a RAG System · Step 6 of 12
Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
Every later RAG step only sees what the loader hands over. Load one travel policy as a 3-page PDF and as an intranet page: the quick loaders give 6 and 4 boilerplate hits and 0 of 6 table rows whole; the careful pymupdf and main-element loaders give 0 noise and 6 of 6 rows, proven by a scorecard and 5 tests.
What you will learn
- See what pypdf and BeautifulSoup get_text really hand to a RAG pipeline
- Drop PDF headers and footers by position and rejoin wrapped lines with pymupdf
- Keep every table row whole as a markdown row, in PDF and HTML
- Measure a parse with a small scorecard instead of judging it by eye
Before you start
- The RAG Pipeline Explained
- Basic Python and pip
Before anything gets chunked or embedded, somebody has to turn your files into text. That step, the loader, decides a lot more than people think. Every later stage of a RAG system only sees what the loader hands over.
We'll take one real policy, as a PDF and as an intranet page, run a quick loader and a careful loader on each, and prove the difference with a small scorecard. No API key is needed.
Copy it, or read it?
Say you need to get a big policy binder into a new system. One option is the photocopier. It copies every page exactly: the header on every page, the page numbers, and it reads a table one cell at a time. Nothing is lost, but nothing is understood either.
The other option is a careful assistant who retypes the binder. They skip the repeated header, join the broken lines, keep each table row together, and write the page number in the margin. In a RAG pipeline, that's the Load step, right at the front, before chunk, embed, retrieve and answer. If the loader is a photocopier, the whole system inherits the mess.
Where real files hurt
Our example is the Brightfield travel and expenses policy, once as a three-page PDF (data/travel-policy.pdf) and once as a page on the company intranet (data/travel-policy.html). Four problems hide in them:
- Header and footer. The same two lines sit on every PDF page, so they show up in the text again and again.
- Wrapped lines. Page two is in two columns, so sentences break in the middle.
- Tables. Page three has hotel and meal rates per city, and a rate only makes sense next to its city.
- Page chrome. The HTML page has a menu, a cookie banner, related links and a footer around the actual policy.
Each one ends up inside your chunks unless the loader deals with it.
One shape for every loader
loaders.py has four loaders: a quick one and a careful one for PDF, and the same pair for HTML. The docstring is the contract: every loader returns a list of documents, each with a source, a page and the text. Same shape from all four, so we can compare them fairly. The versions are pinned in requirements.txt: pypdf 6.1.1, pymupdf 1.26.4 and beautifulsoup4 4.13.5.
"""Four loaders for the same travel policy: a naive and a careful one for PDF, and the same for HTML.
Every loader returns a list of documents: {"source": file name, "page": number or None, "text": str}."""
import pathlib
import re
import fitz # pymupdf
from bs4 import BeautifulSoup
from pypdf import PdfReader
DATA = pathlib.Path(__file__).parent / "data"
PDF, HTML = DATA / "travel-policy.pdf", DATA / "travel-policy.html"
# ---------- PDF ----------
def pdf_naive(path=PDF):
"""pypdf: one string per page, exactly as extracted"""
reader = PdfReader(path)
return [{"source": path.name, "page": i + 1, "text": p.extract_text()}
for i, p in enumerate(reader.pages)]
First attempt: pypdf
pdf_naive opens the file with PdfReader and keeps extract_text() for every page exactly as it comes out. Here is page three, the rates table:
python demo.py pypdf
--- page 3, as pypdf sees it ---
Brightfield GmbH - Travel and Expenses Policy - Internal
Page 3 of 3 - Confidential - version 2026-10
Hotel and meal rates
City
Hotel cap per night
Meal allowance per day
Berlin
EUR 150
EUR 40
Paris
EUR 190
EUR 45
London
GBP 170
GBP 40
...
score: {'noise': 6, 'rows_whole': 0, 'chunks_with_noise': 3, 'chunks': 7}
The first two lines are the company header and "Page 3 of 3 - Confidential". That's decoration, not policy, and it's now part of the page text. Then the table comes out one cell per line: Berlin, then EUR 150, then EUR 40. If a chunk boundary falls in the wrong place, a chunk can hold "Paris" without its rate.
The score line puts numbers on it: six boilerplate hits, zero of the six table rows whole, and when the text is cut into 300-character chunks, three of the seven chunks carry that noise. Those chunks get embedded and retrieved like anything else.
The fix: positions with pymupdf
The big idea: pymupdf gives us blocks of text together with their position on the page. Headers and footers always sit in the same place, and tables have a box.
def table_md(table):
rows = table.extract()
lines = ["| " + " | ".join(c or "" for c in r) + " |" for r in rows]
lines.insert(1, "|" + " --- |" * len(rows[0]))
return "\n".join(lines)
def pdf_clean(path=PDF, margin=45):
"""pymupdf: drop header/footer by position, rejoin wrapped lines, tables as markdown rows"""
docs = []
for page in fitz.open(path):
h = page.rect.height
tables = page.find_tables().tables
boxes = [fitz.Rect(t.bbox) for t in tables]
parts, pending = [], sorted(tables, key=lambda t: t.bbox[1])
for x0, y0, x1, y1, text, *_ in page.get_text("blocks"):
if y1 < margin or y0 > h - margin: # running header or footer
continue
if any(fitz.Rect(x0, y0, x1, y1).intersects(b) for b in boxes):
continue # table cells: added once, as rows
while pending and pending[0].bbox[1] < y0: # a table that sits above this block
parts.append(table_md(pending.pop(0)))
parts.append(re.sub(r"\s*\n\s*", " ", text).strip()) # rejoin wrapped lines
parts += [table_md(t) for t in pending]
docs.append({"source": path.name, "page": page.number + 1, "text": "\n\n".join(parts)})
return docs
page.find_tables()finds the rates table and gives us its box.- The header and footer rule: a block in the top 45 points or the bottom 45 points of the page is skipped.
- Any block inside a table box is skipped too, because the table is added once, as rows, by
table_md. - The
while pendingloop puts each table back where it sits, above the next block of text, so the reading order stays right. re.sub(r"\s*\n\s*", " ", text)joins the wrapped lines: a line break inside a block becomes a space.
Same pages, clean
python demo.py pymupdf
--- page 3 ---
Hotel and meal rates
| City | Hotel cap per night | Meal allowance per day |
| --- | --- | --- |
| Berlin | EUR 150 | EUR 40 |
| Paris | EUR 190 | EUR 45 |
| London | GBP 170 | GBP 40 |
| Lisbon | EUR 120 | EUR 35 |
| Warsaw | PLN 480 | PLN 150 |
| New York | USD 260 | USD 70 |
...
score: {'noise': 0, 'rows_whole': 6, 'chunks_with_noise': 0, 'chunks': 7}
On page two, the approval rule reads as one sentence again: Any trip that costs more than two hundred euros in total needs written approval from your manager before you book. The two columns no longer break it up. On page three, every city travels with both of its rates, so any chunk that has the city also has the numbers. Zero noise, six of six rows whole, and none of the seven chunks carry boilerplate.
HTML: keep only the content
def html_naive(path=HTML):
"""every piece of text on the page, menus and scripts included"""
soup = BeautifulSoup(path.read_text(encoding="utf-8"), "html.parser")
return [{"source": path.name, "page": None, "text": soup.get_text(" ", strip=True)}]
def html_clean(path=HTML):
"""only <main>, script/style removed, tables as markdown rows"""
soup = BeautifulSoup(path.read_text(encoding="utf-8"), "html.parser")
main = soup.find("main")
for tag in main(["script", "style"]):
tag.decompose()
for table in main.find_all("table"):
rows = [[c.get_text(strip=True) for c in tr.find_all(["th", "td"])] for tr in table.find_all("tr")]
md = ["| " + " | ".join(r) + " |" for r in rows]
md.insert(1, "|" + " --- |" * len(rows[0]))
table.replace_with("\n" + "\n".join(md) + "\n")
blocks = [b.get_text(" ", strip=True) if hasattr(b, "get_text") else str(b).strip() for b in main.children]
return [{"source": path.name, "page": None, "text": "\n\n".join(b for b in blocks if b)}]
The quick loader takes every piece of text on the page with get_text: menu, cookie banner, footer, all of it. The careful one starts by finding the <main> element, where the policy lives. The menu, banner and footer sit outside it, so they're simply gone. It removes any script and style tags inside main, so no tracking code sneaks into the text, and it turns each table into markdown rows.
python demo.py html
--- naive: get_text() on the whole page (first 400 characters) ---
Travel policy - Brightfield intranet Home People IT desk Travel
Search We use cookies to improve the intranet. Accept all Settings
Travel and Expenses Policy This policy explains how Brightfield
staff book and claim work travel. It applies ...
score: {'noise': 4, 'rows_whole': 0, 'chunks_with_noise': 2, 'chunks': 6}
--- clean: <main> only, table as rows ---
| City | Hotel cap per night | Meal allowance per day |
| --- | --- | --- |
| Berlin | EUR 150 | EUR 40 |
| Paris | EUR 190 | EUR 45 |
...
score: {'noise': 0, 'rows_whole': 6, 'chunks_with_noise': 0, 'chunks': 6}
The naive text starts with the menu and the cookie banner before a single word of policy, and get_text squashes the whole table into one long line. The clean version is just the policy, with the rates as rows. Same file, very different input for the rest of the pipeline.
Prove it with a number
Looking at text and saying "it looks better" is not enough. quality.py turns it into three counts:
"""Turn "the parse looks better" into numbers: noise lines, broken lines, table rows kept whole."""
CITIES = ["Berlin", "Paris", "London", "Lisbon", "Warsaw", "New York"]
NOISE = ["Confidential", "Page ", "Accept all", "dataLayer", "Imprint", "IT desk", "Related pages"]
def chunks(docs, size=300):
"""the plain fixed-size chunker a first RAG system would use"""
out = []
for d in docs:
t = d["text"]
out += [t[i:i + size] for i in range(0, len(t), size)]
return out
def score(docs):
text = "\n".join(d["text"] for d in docs)
lines = [l for l in text.split("\n") if l.strip()]
money = lambda l: sum(l.count(m) for m in ("EUR", "GBP", "PLN", "USD")) # noqa: E731
# a row is whole when one line holds its city, both amounts, and no other city
rows_whole = sum(any(c in l and money(l) == 2 and sum(o in l for o in CITIES) == 1 for l in lines)
for c in CITIES)
return {
"noise": sum(text.count(n) for n in NOISE),
"rows_whole": rows_whole,
"chunks_with_noise": sum(any(n in c for n in NOISE) for c in chunks(docs)),
"chunks": len(chunks(docs)),
}
A row is whole when one line holds its city, both amounts and no other city. Noise counts the boilerplate phrases. Noisy chunks counts the 300-character chunks that carry any of it. The scorecard runs all four loaders through the same function:
python demo.py scorecard
loader noise hits rows whole noisy chunks
pdf naive 6 0 / 6 3 / 7
pdf clean 0 6 / 6 0 / 7
html naive 4 0 / 6 2 / 6
html clean 0 6 / 6 0 / 6
And the project's five tests pass, so if someone changes a loader later, the check catches it.
Common mistakes
- Chunking before you look. Print what your loader produced first. Most RAG bugs that look like retrieval problems start here.
- Keeping running headers and footers. They repeat on every page and end up in many chunks, pulling unrelated searches towards them.
- Splitting table cells onto separate lines. A rate without its city can't answer "what is the hotel cap in Paris?".
- Calling
get_text()on the whole HTML page. Menus, cookie banners and scripts become part of your knowledge base. - Dropping the page number. Keep source and page on every document; citations need them later.
Quick recap
| Problem | Fix in the careful loader |
|---|---|
| Header and footer on every PDF page | Skip blocks in the top and bottom 45 points |
| Wrapped lines in two columns | re.sub(r"\s*\n\s*", " ", text) inside each block |
| Table read one cell per line | find_tables(), then one markdown row per city |
| Menu, cookie banner, footer in HTML | Keep only <main>, remove script and style |
| "Looks better" | A scorecard: noise 6 and 4 down to 0, rows whole 0 up to 6 of 6 |
Once the text is clean, the next decision is where to cut it: see Chunking Strategies for RAG.
Try it yourself
Run the whole project once and read page three from both PDF loaders. Then change the margin in pdf_clean from 45 to 20 and run the scorecard again: does the header still get through? Finally, point the loaders at one PDF of your own and see what comes out.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.