Document Loading and Text Extraction
Load PDFs, Word documents, and plain text files using Python libraries, clean the extracted text, and prepare it for chunking and embedding.
Document Loading and Text Extraction is a free AI Engineering Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Engineering Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Document Loading Is Non-Trivial
The first stage of any RAG pipeline is getting raw text out of your documents. This sounds simple but is surprisingly tricky in practice. PDF files may embed text as characters, as images, or as a mix of both. Word documents contain formatting markup you must strip. HTML pages include navigation menus and ads alongside the real content. A robust loader must handle all these cases and produce clean, coherent text for chunking.
Loading PDFs with pypdf
pypdf is the standard Python library for reading PDF files that contain embedded text. It extracts text page by page, preserving the original page boundaries which are valuable metadata. However, pypdf cannot read scanned PDFs (images of text) — those require OCR. Always extract page numbers alongside text so you can cite the exact page in your RAG citations.
from pypdf import PdfReader
def load_pdf(file_path):
reader = PdfReader(file_path)
pages = []
for page_num, page in enumerate(reader.pages, start=1):
text = page.extract_text()
if text and text.strip(): # skip blank pages
pages.append({
'text': text,
'metadata': {
'source': file_path,
'page': page_num,
'doc_type': 'pdf'
}
})
return pages
docs = load_pdf('annual_report.pdf')
print(f'Loaded {len(docs)} non-empty pages')Loading Word Documents with python-docx
Microsoft Word files (.docx) store content in XML format. The python-docx library parses this XML and exposes paragraphs, tables, and headings as Python objects. Extract paragraph text sequentially and capture heading levels to preserve document structure — section headings are valuable context that improves chunking and retrieval quality when included with the text they introduce.
from docx import Document
def load_docx(file_path):
doc = Document(file_path)
sections = []
current_section = {'heading': '', 'text': ''}
for para in doc.paragraphs:
if para.style.name.startswith('Heading'):
if current_section['text'].strip():
sections.append(current_section.copy())
current_section = {'heading': para.text, 'text': ''}
else:
current_section['text'] += para.text + '\n'
if current_section['text'].strip():
sections.append(current_section)
return [{'text': f"{s['heading']}\n{s['text']}",
'metadata': {'source': file_path, 'section': s['heading']}}
for s in sections]Loading Web Pages and HTML
HTML pages contain a lot of noise: navigation bars, footers, cookie banners, and advertisement blocks. Use BeautifulSoup to parse the HTML and extract only the main content area. Target elements like <article>, <main>, or content-specific CSS classes. Remove script, style, and nav tags before extracting text to avoid polluting your chunks with JavaScript code or menu items.
import requests
from bs4 import BeautifulSoup
def load_url(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Remove noise elements
for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside']):
tag.decompose()
# Try to find main content
main = soup.find('article') or soup.find('main') or soup.find('body')
text = main.get_text(separator='\n', strip=True)
return [{'text': text, 'metadata': {'source': url, 'doc_type': 'html'}}]Handling Scanned PDFs with OCR
Scanned PDFs store pages as images with no embedded text. To extract text you need Optical Character Recognition (OCR). The pytesseract library wraps Google's Tesseract OCR engine. OCR is slower and less accurate than text extraction (80-95% character accuracy on good scans), so always prefer digital PDFs when available. Signal when OCR was used in the metadata so you can review low-confidence extractions.
import pytesseract
from pdf2image import convert_from_path
def load_scanned_pdf(file_path):
# Convert PDF pages to PIL images
pages_as_images = convert_from_path(file_path, dpi=300)
results = []
for page_num, img in enumerate(pages_as_images, start=1):
text = pytesseract.image_to_string(img, lang='eng')
results.append({
'text': text,
'metadata': {
'source': file_path,
'page': page_num,
'ocr': True # flag for quality review
}
})
return resultsUsing Unstructured for Any Format
The unstructured library is a Swiss army knife for document loading that handles PDFs, Word, Excel, PowerPoint, HTML, emails, and more with a unified API. It uses heuristics to identify document elements (title, narrative text, table, header) and returns them as structured objects. This is especially useful when your corpus contains mixed document types and you want element-level metadata without writing format-specific parsers.
from unstructured.partition.auto import partition
def load_any_document(file_path):
elements = partition(filename=file_path)
docs = []
for element in elements:
docs.append({
'text': str(element),
'metadata': {
'source': file_path,
'element_type': type(element).__name__,
'category': element.category
}
})
return docs
# Works on .pdf, .docx, .pptx, .html, .eml, .xlsx
docs = load_any_document('presentation.pptx')Text Cleaning After Extraction
Raw extracted text is rarely clean. PDF extraction often produces hyphenated line breaks from column layouts, extra whitespace, page headers repeated on every page, and garbled special characters. Apply a cleaning pipeline: remove excessive whitespace, rejoin hyphenated words across line breaks, strip page headers and footers identified by pattern matching, and normalize Unicode characters. Clean text leads to dramatically better chunk coherence.
import re
def clean_text(text):
# Rejoin hyphenated line breaks (PDF column artifacts)
text = re.sub(r'-(\n)([a-z])', r'\2', text)
# Normalize whitespace
text = re.sub(r' +', ' ', text)
text = re.sub(r'\n{3,}', '\n\n', text)
# Remove page numbers standing alone on a line
text = re.sub(r'^\d+$', '', text, flags=re.MULTILINE)
# Strip leading/trailing whitespace from each line
lines = [line.strip() for line in text.split('\n')]
return '\n'.join(lines).strip()Loading from Databases and APIs
Not all knowledge lives in files. Internal databases, CRM systems, ticketing tools, and REST APIs are also sources. Load structured database rows by joining relevant tables and concatenating field values into natural-language paragraphs that the embedding model can understand. For APIs, fetch paginated results and serialize each record as a text document with key-value pairs.
import psycopg2
def load_from_database(conn_string, query):
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute(query)
columns = [desc[0] for desc in cursor.description]
docs = []
for row in cursor.fetchall():
# Convert row to natural language text
parts = [f'{col}: {val}' for col, val in zip(columns, row) if val]
text = '\n'.join(parts)
docs.append({'text': text, 'metadata': {'source': 'database'}})
conn.close()
return docsTracking Document Provenance
Every loaded document should carry provenance metadata throughout the entire pipeline: source URL or file path, document title, author, creation date, and last modified date. This metadata travels with each chunk into the vector store and surfaces in LLM citations. Without provenance, you cannot tell users where an answer came from, you cannot update specific documents in the index, and you cannot filter retrieval by source attributes.
import os
from datetime import datetime
def load_pdf_with_provenance(file_path):
from pypdf import PdfReader
reader = PdfReader(file_path)
stat = os.stat(file_path)
base_metadata = {
'source': file_path,
'title': reader.metadata.get('/Title', os.path.basename(file_path)),
'author': reader.metadata.get('/Author', 'Unknown'),
'doc_type': 'pdf',
'file_size_kb': stat.st_size // 1024,
'loaded_at': datetime.utcnow().isoformat()
}
pages = []
for i, page in enumerate(reader.pages, 1):
text = page.extract_text()
if text and text.strip():
pages.append({'text': text, 'metadata': {**base_metadata, 'page': i}})
return pagesBatch Loading Large Document Collections
When indexing thousands of documents, load them in parallel using concurrent.futures to saturate I/O and CPU resources. Implement a progress tracker and error log so failed document loads do not silently drop content from your index. Never let a single corrupt file crash the entire loading job — catch exceptions per document and continue to the next one.
from concurrent.futures import ThreadPoolExecutor, as_completed
def batch_load_documents(file_paths, max_workers=8):
all_docs = []
errors = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_path = {
executor.submit(load_pdf_with_provenance, p): p
for p in file_paths
}
for future in as_completed(future_to_path):
path = future_to_path[future]
try:
docs = future.result()
all_docs.extend(docs)
print(f'Loaded {len(docs)} pages from {path}')
except Exception as e:
errors.append({'path': path, 'error': str(e)})
return all_docs, errorsValidating Loaded Content Quality
After loading, validate that you extracted meaningful content. Check for: minimum text length (skip chunks with fewer than 50 characters), language detection (if your RAG is English-only, filter non-English pages), and garbled text detection (high ratio of non-ASCII characters may indicate OCR failure or encoding issues). Log statistics like pages loaded, average page length, and error rate to catch loading problems early.
def validate_documents(docs, min_length=100):
valid = []
skipped = 0
for doc in docs:
text = doc['text']
if len(text) < min_length:
skipped += 1
continue
# Check for high non-ASCII ratio (garbled OCR)
non_ascii = sum(1 for c in text if ord(c) > 127)
if non_ascii / max(len(text), 1) > 0.3:
skipped += 1
continue
valid.append(doc)
print(f'Valid: {len(valid)}, Skipped: {skipped}')
return validQuick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
In this lesson you learned: format-specific loaders for PDFs with pypdf, Word documents with python-docx, HTML with BeautifulSoup, and scanned documents with OCR, the unstructured library as a unified multi-format loader, and production best practices including text cleaning, provenance metadata, batch parallel loading, and content validation. Next up we tackle chunking strategies that determine how retrieved text maps to model context.
Frequently asked questions
Is the “Document Loading and Text Extraction” lesson free?
Yes — the full text of “Document Loading and Text Extraction” is free to read here on the web, and the AI Engineering Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Engineering Academy course, upgrade to CoddyKit PRO.
What will I learn in “Document Loading and Text Extraction”?
Load PDFs, Word documents, and plain text files using Python libraries, clean the extracted text, and prepare it for chunking and embedding. You practise AI Engineering Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Engineering Academy?
No prior experience is required. AI Engineering Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Document Loading and Text Extraction” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Engineering Academy lesson?
Yes. Every AI Engineering Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Document Loading and Text Extraction
- Chunking Strategies: Fixed vs Sentence vs Recursive
- Indexing: Embedding and Storing Chunks
- Query, Retrieve, and Generate