Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 35/ 160
02. RAG

Document Parsing

PDF/HTML/table extraction quality that makes or breaks every downstream RAG stage.

IntermediatePDF Extract · Tables3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Before the AI can use a document, a tool has to read it correctly, keeping paragraphs, headings and tables in the right order and ignoring page numbers.

Think of it like…

Photocopying a magazine and asking someone to read it aloud: a naive reader goes straight across both columns mid-sentence, reads the page number in the middle, and turns a price table into a stream of numbers. A good reader follows the layout and understands what each part is.

Where you’ve seen it

A procurement assistant ingests 12,000 supplier contracts as PDFs. The first parser (plain text extraction) reads two-column pages across the columns, so clauses interleave, and splits pricing tables into lines with no headers. After switching to a layout-aware parser with table extraction (tables stored as Markdown with captions) and removing repeated headers and footers, retrieval recall on 200 clause questions rises from 62 to 85 percent with no change to the embedding model.

Words you’ll hear

Layout analysis
Detecting regions such as paragraphs, headings, tables, figures and reading order.
OCR
Optical character recognition: turning scanned images of text into text.
Reading order
The sequence in which text should be read, especially for multi-column pages.
Table extraction
Recovering rows, columns and headers as structured data or Markdown/HTML.

Visual diagram

Loading interactive diagram

Theory & deep dive

Document types and parser choices

Digital PDFs have a text layer: libraries such as PyMuPDF and pdfplumber extract text quickly, but reading order, columns and tables need layout logic. Layout-aware tools (Docling, Unstructured, Marker, LlamaParse, Azure Document Intelligence, AWS Textract, Google Document AI) detect blocks, order them, and return headings, lists and tables as structured elements. Scanned PDFs and images have no text layer and need OCR (Tesseract, PaddleOCR, or cloud OCR) or a vision-language model that reads the page image directly and outputs Markdown, which handles complex layouts, handwriting and charts at higher cost. HTML needs boilerplate removal (trafilatura, readability) to drop navigation, ads and footers, while keeping headings and tables. Office files (DOCX, PPTX, XLSX) have explicit structure you can use via python-docx or converters.

Pick by document mix, volume, accuracy needs and privacy: libraries for clean digital files at scale, cloud document AI for forms and invoices, vision models for the hardest pages, and a router that sends each page to the cheapest parser that handles it.

A routing rule

If a PDF page has a text layer and a single column, use PyMuPDF; if it has tables or columns, use a layout-aware parser; if it has no text layer or text coverage under 20 percent, send the page image to OCR or a vision model.

Key takeaway: Match the parser to the document type; route pages by difficulty.

Tables, cleaning and quality control

Tables are where RAG often fails. A flattened table ("Region Q1 Q2 North 120 135 South 98 110") loses which number belongs to which column. Extract tables as Markdown or HTML with headers, keep the caption and page, and either embed each table as one chunk (when small) or chunk by rows with the header repeated. For numeric analysis, store the table as structured data and let the LLM query it, instead of embedding digits. Describe charts and figures with a vision model and index the description with a pointer to the image.

Clean aggressively but safely: remove repeating headers, footers and page numbers (detect strings that repeat across pages), fix hyphenation at line ends, normalise Unicode and whitespace, merge broken paragraphs, and keep headings as structure for chunking. Preserve provenance: page number, bounding box and section path for each element, so citations can point to the right place. Then measure quality: sample 20 to 50 documents, compare parsed output with the page image, and track error classes (order, tables, missing text, noise). Re-evaluate retrieval after parser changes, and version the parsing pipeline so you can re-ingest consistently.

A table that survives parsing

"| Region | Q1 | Q2 |\n| North | 120 | 135 |\n| South | 98 | 110 |" keeps the column mapping, so "What were South's Q2 sales?" can be answered correctly from the chunk.

Key takeaway: Preserve tables with headers, strip boilerplate, keep provenance, and inspect samples.

How it works, step by step

Step 1 of 4
Inventory

1. Profile your documents

Count types (digital, scanned, HTML, Office), layouts (columns, tables, forms) and languages in a sample.

70% digital · 20% scanned · 10% HTML
Key numbers at this step
Sample
of real files

When to use it & trade-offs

What it is

Document parsing turns files such as PDFs, scans, Word documents, slides and web pages into clean, structured text for chunking and embedding. Real documents are hard: PDFs store positioned glyphs, not paragraphs; multi-column layouts scramble reading order; tables become jumbled lines; scans need OCR; and headers, footers and navigation menus pollute every chunk. Parsing quality sets a ceiling on everything downstream, since an answer lost or garbled at ingestion can't be retrieved or generated.

Why it matters: "Garbage in, garbage out" is most true in RAG ingestion. Teams spend weeks tuning embeddings and prompts, then discover the PDF parser merged two columns, dropped table headers and kept "Page 3 of 40" in every chunk. Inspecting parser output on a sample of your documents is the cheapest and most effective RAG debugging step, and choosing between text extraction, layout-aware parsers and vision models is an important design decision.

When to reach for it

  • Contract, report and manual ingestion for RAG
  • Invoice and form extraction
  • Web and knowledge-base crawling with boilerplate removal

When to avoid or be careful

  • Extracting plain text from every PDF and trusting it
  • Embedding flattened tables without headers
  • Leaving page headers and footers in every chunk

Parsing approaches

Text-layer libraries (PyMuPDF, pdfplumber)
Best for: Clean digital PDFs at high volume

Strengths: Very fast and cheap.

Watch out: Weak on columns, tables and scans.

Layout-aware parsers / cloud document AI
Best for: Mixed business documents with tables and forms

Strengths: Structured elements, reading order and tables.

Watch out: Slower; cost; setup.

OCR / vision-language models
Best for: Scans, handwriting, charts and complex layouts

Strengths: Handles anything visible on the page.

Watch out: Highest cost and latency; can hallucinate characters.

Interview signals & numbers to know

When this topic comes up

  • “RAG works on some PDFs but not others”
  • “Tables come back as nonsense”
  • “Scanned documents return nothing”
  • OCR vs vision models
  • Parser selection

Benchmarks & rules of thumb

20 – 50 -
documents to inspect manually
62% → 85% -
recall gain from better parsing in the example
< 20% -
text coverage that suggests a scanned page

Common mistakes & follow-ups

Common interview mistakes

  • Never reading parser output, then spending weeks tuning embeddings for a parsing problem.
  • Using OCR on digital PDFs that already contain accurate text.
  • Dropping page numbers and sections, so answers can't be cited.

Likely interviewer follow-ups

  • How would you ingest a mix of scanned and digital PDFs?
  • How do you preserve tables for retrieval?
  • How do you measure parsing quality?
Interview tip: Say you'd look at parsed output for a sample of real documents before touching anything else. It's the most practical RAG debugging habit.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Document Parsing with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Parent-Child Chunking
Next topic
Citations