Search Tutorials
--Ads--Building a Universal Document Loader and Content Processing Architecture
One loader for every file type with detection, fallbacks, error handling and a pluggable processing architecture.
An enterprise corpus contains every file type imaginable: PDFs (digital and scanned), Word, Excel, PowerPoint, HTML, Markdown, email, images, archives and plain text in different encodings. Writing a separate script for each source quickly becomes unmanageable. This lesson builds a universal document loader: one entry point that detects the file type, picks the right parser, falls back gracefully, and returns the same document format for everything. It then shows how that loader fits into a pluggable content processing architecture.
What you will learn
- How to detect file types reliably from content, not just extensions
- How to build a registry of parsers with fallbacks and a common output format
- How to isolate failures, enforce limits and record what happened to every file
- How to organise ingestion as a pipeline of pluggable stages
Prerequisites
Installation
pip install pymupdf python-docx openpyxl python-pptx beautifulsoup4 charset-normalizer
Step 1: A common document format
from dataclasses import dataclass, field
@dataclass
class LoadedDocument:
source: str # path or URL
text: str # extracted text (Markdown where structure is known)
mime_type: str
parser: str # which parser produced it
metadata: dict = field(default_factory=dict)
warnings: list[str] = field(default_factory=list)
Everything downstream (cleaning, classification, chunking) works on this one type, whatever the original file was.
Step 2: Detect the file type
Extensions can be missing or wrong. Most binary formats start with a recognisable signature ("magic bytes"), so check the content first and fall back to the extension:
import zipfile
from pathlib import Path
SIGNATURES = [
(b"%PDF", "application/pdf"),
(b"\x89PNG", "image/png"),
(b"\xff\xd8\xff", "image/jpeg"),
(b"\xd0\xcf\x11\xe0", "application/x-ole-storage"), # old .doc/.xls/.ppt and Outlook .msg
]
OFFICE_ZIP = {"word/": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xl/": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ppt/": "application/vnd.openxmlformats-officedocument.presentationml.presentation"}
EXTENSIONS = {".md": "text/markdown", ".txt": "text/plain", ".html": "text/html", ".htm": "text/html",
".csv": "text/csv", ".json": "application/json", ".eml": "message/rfc822"}
def detect_type(path: Path) -> str:
head = path.read_bytes()[:8] if path.stat().st_size else b""
for signature, mime in SIGNATURES:
if head.startswith(signature):
return mime
if head.startswith(b"PK"): # ZIP container: Office Open XML or other
with zipfile.ZipFile(path) as z:
names = z.namelist()
for prefix, mime in OFFICE_ZIP.items():
if any(n.startswith(prefix) for n in names):
return mime
return "application/zip"
return EXTENSIONS.get(path.suffix.lower(), "application/octet-stream")
Step 3: Parsers in a registry
Each parser takes a path and returns text plus metadata. Registering them by MIME type, with an ordered list per type, gives you fallbacks for free:
from collections.abc import Callable
Parser = Callable[[Path], tuple[str, dict]]
REGISTRY: dict[str, list[tuple[str, Parser]]] = {}
def parser(mime: str, name: str):
def register(fn: Parser) -> Parser:
REGISTRY.setdefault(mime, []).append((name, fn))
return fn
return register
@parser("application/pdf", "pymupdf")
def parse_pdf(path: Path) -> tuple[str, dict]:
import fitz # PyMuPDF
with fitz.open(path) as doc:
pages = [page.get_text("text") for page in doc]
meta = {"pages": doc.page_count, "title": (doc.metadata or {}).get("title") or ""}
text = "\n\n".join(pages)
if len(text.strip()) < 20 * max(meta["pages"], 1): # almost no text: probably scanned
meta["needs_ocr"] = True
return text, meta
@parser(OFFICE_ZIP["word/"], "python-docx")
def parse_docx(path: Path) -> tuple[str, dict]:
import docx
document = docx.Document(str(path))
lines = []
for p in document.paragraphs:
style = (p.style.name or "") if p.style is not None else ""
if style.startswith("Heading") and p.text.strip():
level = int(style.split()[-1]) if style.split()[-1].isdigit() else 1
lines.append("#" * level + " " + p.text.strip())
elif p.text.strip():
lines.append(p.text.strip())
return "\n\n".join(lines), {"title": document.core_properties.title or ""}
@parser(OFFICE_ZIP["xl/"], "openpyxl")
def parse_xlsx(path: Path) -> tuple[str, dict]:
import openpyxl
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
parts = []
for ws in wb.worksheets:
rows = [" | ".join("" if v is None else str(v) for v in row) for row in ws.iter_rows(values_only=True)]
parts.append(f"## Sheet: {ws.title}\n" + "\n".join(r for r in rows if r.strip(" |")))
return "\n\n".join(parts), {"sheets": len(wb.worksheets)}
@parser(OFFICE_ZIP["ppt/"], "python-pptx")
def parse_pptx(path: Path) -> tuple[str, dict]:
from pptx import Presentation
deck = Presentation(str(path))
slides = []
for i, slide in enumerate(deck.slides, start=1):
texts = [s.text_frame.text for s in slide.shapes if s.has_text_frame and s.text_frame.text.strip()]
slides.append(f"## Slide {i}\n" + "\n".join(texts))
return "\n\n".join(slides), {"slides": len(deck.slides)}
@parser("text/html", "beautifulsoup")
def parse_html(path: Path) -> tuple[str, dict]:
from bs4 import BeautifulSoup
soup = BeautifulSoup(read_text(path), "html.parser")
for tag in soup(["script", "style", "nav", "footer"]):
tag.decompose()
return soup.get_text("\n", strip=True), {"title": soup.title.get_text(strip=True) if soup.title else ""}
def read_text(path: Path) -> str:
"""Decode text files in any common encoding."""
from charset_normalizer import from_bytes
best = from_bytes(path.read_bytes()).best()
return str(best) if best is not None else path.read_bytes().decode("utf-8", errors="replace")
for mime in ("text/plain", "text/markdown", "text/csv", "application/json"):
REGISTRY.setdefault(mime, []).append(("text", lambda p: (read_text(p), {})))
Add more parsers the same way: an OCR parser for scanned PDFs, a layout-aware parser registered before PyMuPDF for complex documents, the email loader from Email Ingestion, or an archive handler that extracts ZIP files and loads each member.
Step 4: The loader with limits and fallbacks
MAX_BYTES = 200 * 1024 * 1024 # skip files larger than 200 MB
def load(path_str: str) -> LoadedDocument | None:
path = Path(path_str)
if path.stat().st_size > MAX_BYTES:
print(f"skip (too large): {path}")
return None
mime = detect_type(path)
errors = []
for name, parse in REGISTRY.get(mime, []):
try:
text, meta = parse(path)
except Exception as error: # one bad file must not stop the pipeline
errors.append(f"{name}: {type(error).__name__}: {error}")
continue
doc = LoadedDocument(str(path), text, mime, name, meta, warnings=errors)
if meta.get("needs_ocr"):
doc.warnings.append("little extractable text; route to OCR")
return doc
print(f"unsupported or failed: {path} ({mime}) {errors}")
return None
for f in sorted(Path("documents").rglob("*")):
if f.is_file():
doc = load(str(f))
if doc:
print(f"{doc.parser:<12} {doc.mime_type.split('/')[-1][:30]:<30} {len(doc.text):>7} chars {f.name}")
pymupdf pdf 48211 chars annual-report.pdf
python-docx vnd.openxmlformats-officedocu 9120 chars leave-policy.docx
openpyxl vnd.openxmlformats-officedocu 3312 chars price-list.xlsx
text markdown 2140 chars README.md
unsupported or failed: documents/scan-001.tiff (application/octet-stream) []
For untrusted uploads, also run parsers in a separate process with a time limit and memory limit, because a malformed file can make a parser hang or exhaust memory.
Step 5: A content processing architecture
The loader is the first stage of a pipeline. Making each stage a small function with the same signature lets you add, remove or reorder stages per source by configuration:
Stage = Callable[[LoadedDocument], LoadedDocument | None] # None = drop the document
def clean(doc: LoadedDocument) -> LoadedDocument:
doc.text = "\n".join(line.rstrip() for line in doc.text.splitlines())
return doc
def drop_empty(doc: LoadedDocument) -> LoadedDocument | None:
return doc if len(doc.text.split()) >= 20 else None
PIPELINES: dict[str, list[Stage]] = {
"default": [clean, drop_empty], # add: classify, redact_pii, chunk, embed, index
}
def process(path: str, pipeline: str = "default") -> LoadedDocument | None:
doc = load(path)
for stage in PIPELINES[pipeline]:
if doc is None:
return None
doc = stage(doc)
return doc
In production the same stages run as workers reading from a queue, each document's status (loaded, failed, needs OCR, indexed) is recorded in a table, and failed files are retried or sent for review. That record is what lets you answer "why is this document not in the index?".
Common errors and troubleshooting
- Old
.doc,.xlsor.pptfiles: the libraries above read only the newer XML formats; convert legacy files (for example with LibreOffice in headless mode) or use a parser that supports them. - Password-protected files: they fail to open; record and skip them.
- Huge spreadsheets: use read-only mode and consider loading them as tables instead of text (Question Answering over Excel and CSV).
- Garbled text: wrong encoding; decode text files with a detector as shown.
Key takeaways
- Use one document format for every file type.
- Detect types from content signatures, then the extension.
- Register parsers by type with fallbacks; isolate failures and enforce size and time limits.
- Compose ingestion from pluggable stages and record each document's processing status.
Frequently asked questions
Should I use a library that handles all formats?
Libraries such as Unstructured or Docling cover many formats and are good defaults. Wrapping them in your own registry still helps: you can add fallbacks, limits, status tracking and source-specific parsers.
How do I handle images?
Run OCR for text in images, or describe them with a vision model; see RAG over Images, Charts and Diagrams.
Practice exercises
- Add an archive parser that extracts ZIP files to a temporary folder and loads each file, keeping the archive path in metadata.
- Run the loader over a real shared drive and report counts per MIME type, parser and failure reason.