Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 21. Naive RAG
  4. 21.4

Lesson 21.4 · 4 of 5 · 7 min read · Reviewed 24 Nov 2026

Document loaders and parsers

By the end, you can

  • Choose a loading and parsing approach for PDF, HTML, Office and Markdown files.
  • Decide which metadata to keep with each parsed chunk.
  • Spot parsing failures before they reach the index.

The first step of RAGRetrieval-augmented generation (RAG): Retrieving relevant documents at request time and adding them to the prompt so the answer is grounded in them. in 48.1 says “chunkChunking: Splitting documents into smaller passages before embedding and indexing them. the documents”, as if documents were already clean text. They rarely are. A loader fetches a file and its basic facts (path, size, type, modified date). A parser turns the bytes into structured text: headings, paragraphs, lists, tables, plus metadata. Retrieval can only find what the parser produced.

Each format fails differently

Format What is inside What to do Typical failure
PDF, born digital Characters placed at positions on a page, not paragraphs Rebuild reading order; drop running headers and footers; rejoin hyphenated words Two columns read straight across, mixing sentences
PDF, scanned Page images, no text layer Detect it (almost no characters per page), then run OCR Silently indexes nothing
HTML Content mixed with navigation, menus, cookie banners and scripts Keep the main content and its headings, lists and tables; drop the rest Every chunk starts with the site menu
Office (DOCX, PPTX, XLSX) Zipped XML with styles and structure DOCX: map heading styles to sections. PPTX: one record per slide, with speaker notes. XLSX: rows as records with their column headers A spreadsheet becomes a wall of numbers with no labels
Markdown Plain text with headings already marked Split on headings, keep code blocks whole, read front matter as metadata Code blocks cut in half

General toolkits such as Apache Tika detect and extract text and metadata from many formats behind one interface. That is a good default for breadth, but check the output on your hardest files.

Layout-aware parsing

A plain text extractor reads characters in the order the file stores them. A layout-aware parser first finds regions on the page: title, heading, paragraph, list, table, figure, caption, header, footer. It then orders them as a person would read them. Open-source projects such as Docling combine a layout model with a table-structure model and export Markdown or JSON that keeps headings and tables.

Tables need special care. A flattened table turns “Plan B, 30 days, 50 GB” into number soup. Keep it as a Markdown or HTML table, or write each row as a sentence with its headers: “Plan B: notice period 30 days, storage 50 GB.”

OCR

Use optical character recognition when a page has no text layer, or when its text layer is garbage. Quality depends on the image. The Tesseract documentation recommends at least 300 DPI, straightened (deskewed) pages, and sensible borders. Handwriting, stamps and low-contrast faxes stay hard. Record that a page was OCRed, with a confidence score if your engine gives one, so you can review weak pages and treat their answers with care.

Metadata to keep

Field Why
Source id and URI Citations and links back (21.2)
Title and section path, such as “Leave policy > Parental leave” Context for the chunk; better ranking
Page or slide number Precise citations
Version or modified date Re-index changed files; prefer current policy
Access control: tenant, groups Filtering and isolation (22.4, 22.7)
Language Route to the right embedding model or reranker
Parser name and version, OCR flag Find and re-parse everything a buggy parser touched
Content hash Skip unchanged files; spot duplicates

Catch failures early

Run cheap checks on every parsed document before it is chunked:

  • Characters per page near zero: probably a scan. Send it to OCR.
  • The same line on most pages, such as “Confidential, page 3 of 40”: a running header. Strip it.
  • A high share of odd symbols, or text like “paymént”: an encoding problem.
  • Words split by hyphens at line ends, such as “pay-” then “ment”: rejoin them.
  • Hidden text, such as white text on white: remove it. It can carry instructions aimed at the model, so treat all document text as data.
  • Password-protected or corrupt files: log them as failures. Never skip them silently.

Read a random sample of parsed output by eye, especially from your worst formats. Ten minutes of reading catches problems that no retrieval metric will explain.

Key points

  • Retrieval can only find what the parser produced: scrambled or missing text becomes scrambled or missing answers.
  • Each format needs its own care: PDFs need reading order rebuilt, HTML needs boilerplate removed, Office files need their structure kept, scans need OCR.
  • Keep source, section path, page, version, access control and parser details with every chunk, so answers can be cited, filtered and re-parsed.
  • Check every document after parsing: empty pages, repeated headers, garbled characters and flattened tables are the usual failures.
Hands-on labRuns in the Playground

Clean extracted PDF pages before chunking

Turn raw text from a PDF extractor into clean page records with metadata, and flag the pages that need OCR.

You will have: A cleaning script that strips running headers and footers, rejoins hyphenated words, flags scanned pages and prints one record per page.

Steps

  1. Write repeated_lines() to find lines that appear on most pages, ignoring page numbers.
  2. Write needs_ocr() to flag pages with almost no characters.
  3. Write clean_page() to drop repeated lines and rejoin words split across lines with a hyphen.
  4. Print one record per page with source, page, section and an OCR flag.

Done when

  • Two repeated lines are removed: the running header and the page footer.
  • Page 3 is flagged as needing OCR.
  • "payment being received" appears as one word, with no stray hyphen.

Open in the Playground No API key needed.

Starter code (Python)
import re
from collections import Counter

SOURCE = "contract-17.pdf"
# Text as a basic PDF extractor returned it, one string per page. Page 3 is a scanned image.
PAGES = [
    "Northwind Supplies | Confidential\nSection 1 Scope\nThe supplier delivers parts within 14 days of each pay-\nment being received.\nPage 1 of 4",
    "Northwind Supplies | Confidential\nSection 2 Prices\nPrices are fixed for 12 months and re-\nviewed each January.\nPage 2 of 4",
    "",
    "Northwind Supplies | Confidential\nSection 3 Termination\nEither party may end the contract with 60 days of written notice.\nPage 4 of 4",
]

def shape(line):
    return re.sub(r"\d+", "#", line.strip())          # "Page 2 of 4" -> "Page # of #"

def repeated_lines(pages, share=0.6):
    # TODO: return the set of line shapes that appear on at least `share` of the pages that have text
    return set()

def needs_ocr(text, min_chars=20):
    # TODO: a page with almost no characters is probably a scan
    return False

def clean_page(text, repeated):
    # TODO: drop lines whose shape is in `repeated`, then rejoin words split as "pay-\nment"
    return text

repeated = repeated_lines(PAGES)
print(f"removed {len(repeated)} repeated lines:", sorted(repeated))

records, section = [], None
for number, raw in enumerate(PAGES, start=1):
    if needs_ocr(raw):
        records.append({"source": SOURCE, "page": number, "section": section, "ocr_needed": True, "text": ""})
        print(f"page {number}: needs OCR ({len(raw.strip())} characters)")
        continue
    text = clean_page(raw, repeated)
    for line in text.splitlines():
        if line.startswith("Section "):
            section = line
    records.append({"source": SOURCE, "page": number, "section": section, "ocr_needed": False,
                    "text": " ".join(text.split())})

for r in records:
    print(r["page"], "|", r["section"], "|", "OCR" if r["ocr_needed"] else r["text"])
print("pages ready to chunk:", sum(not r["ocr_needed"] for r in records), "of", len(records))
Show a solution
import re
from collections import Counter

SOURCE = "contract-17.pdf"
# Text as a basic PDF extractor returned it, one string per page. Page 3 is a scanned image.
PAGES = [
    "Northwind Supplies | Confidential\nSection 1 Scope\nThe supplier delivers parts within 14 days of each pay-\nment being received.\nPage 1 of 4",
    "Northwind Supplies | Confidential\nSection 2 Prices\nPrices are fixed for 12 months and re-\nviewed each January.\nPage 2 of 4",
    "",
    "Northwind Supplies | Confidential\nSection 3 Termination\nEither party may end the contract with 60 days of written notice.\nPage 4 of 4",
]

def shape(line):
    return re.sub(r"\d+", "#", line.strip())          # "Page 2 of 4" -> "Page # of #"

def repeated_lines(pages, share=0.6):
    with_text = [p for p in pages if p.strip()]
    counts = Counter(s for p in with_text for s in {shape(l) for l in p.splitlines() if l.strip()})
    return {s for s, c in counts.items() if c >= share * len(with_text)}

def needs_ocr(text, min_chars=20):
    return len(text.strip()) < min_chars

def clean_page(text, repeated):
    lines = [l for l in text.splitlines() if shape(l) not in repeated]
    body = "\n".join(lines)
    body = re.sub(r"(\w)-\n(\w)", r"\1\2", body)       # rejoin words hyphenated at line ends
    return body

repeated = repeated_lines(PAGES)
print(f"removed {len(repeated)} repeated lines:", sorted(repeated))

records, section = [], None
for number, raw in enumerate(PAGES, start=1):
    if needs_ocr(raw):
        records.append({"source": SOURCE, "page": number, "section": section, "ocr_needed": True, "text": ""})
        print(f"page {number}: needs OCR ({len(raw.strip())} characters)")
        continue
    text = clean_page(raw, repeated)
    for line in text.splitlines():
        if line.startswith("Section "):
            section = line
    records.append({"source": SOURCE, "page": number, "section": section, "ocr_needed": False,
                    "text": " ".join(text.split())})

for r in records:
    print(r["page"], "|", r["section"], "|", "OCR" if r["ocr_needed"] else r["text"])
print("pages ready to chunk:", sum(not r["ocr_needed"] for r in records), "of", len(records))
Quick checkA team indexes 2,000 supplier contracts as PDFs. Search never finds anything from about 300 of them, and the parser reports almost no characters for those files. What is the most likely cause and fix?
How sure are you?
Pick an answer and how sure you are