Search Tutorials
--Ads--Building a Document Preprocessing Pipeline
Combine loading, cleaning, chunking and metadata enrichment into one reusable, testable pipeline.
Earlier lessons covered loading, cleaning, metadata and chunking as separate techniques. In a real project they must run together, in the same order, for every document, every time. This lesson combines them into one reusable preprocessing pipeline: a sequence of small, testable steps that turns raw files into clean, enriched, ready-to-embed chunks.
What you will learn
- How to structure preprocessing as a pipeline of small steps
- How to pass documents and metadata through load, clean, filter, chunk and enrich stages
- How to make the pipeline configurable, versioned and testable
- How to produce a report of what happened to every file
Prerequisites
Pipeline design
- Load: files become
Documentobjects (text plus metadata). - Clean: fix encoding, remove boilerplate, normalise whitespace.
- Filter: drop empty, too-short and duplicate documents.
- Enrich documents: add document-level metadata (title, type, dates, language).
- Chunk: split by structure, with size limits.
- Enrich chunks: contextual headers, chunk IDs, positions, pipeline version.
Each step is a plain function that takes a list and returns a list. That makes steps easy to test, reorder and replace.
The pipeline
import hashlib
import re
import unicodedata
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
PIPELINE_VERSION = "2026.11-1" # bump whenever a step changes, then re-index
@dataclass
class Document:
text: str
metadata: dict = field(default_factory=dict)
@dataclass
class Chunk:
id: str
text: str
metadata: dict
Step = Callable[[list], list]
# ---------- steps ----------
def load_folder(folder: str, suffixes=(".txt", ".md")) -> list[Document]:
docs = []
for path in sorted(Path(folder).rglob("*")):
if path.suffix.lower() in suffixes:
docs.append(Document(path.read_text(encoding="utf-8", errors="replace"),
{"source": path.as_posix(), "file_type": path.suffix.lstrip(".")}))
return docs
def clean(docs: list[Document]) -> list[Document]:
for d in docs:
t = unicodedata.normalize("NFKC", d.text).replace(" ", " ")
t = re.sub(r"^\s*page \d+( of \d+)?\s*$", "", t, flags=re.I | re.M) # page numbers
t = re.sub(r"[ \t]+", " ", t)
d.text = re.sub(r"\n{3,}", "\n\n", t).strip()
return docs
def drop_short_and_duplicates(docs: list[Document], min_words: int = 20) -> list[Document]:
seen, kept = set(), []
for d in docs:
digest = hashlib.sha256(" ".join(d.text.lower().split()).encode()).hexdigest()
if len(d.text.split()) >= min_words and digest not in seen:
seen.add(digest)
d.metadata["content_hash"] = digest
kept.append(d)
return kept
def add_title(docs: list[Document]) -> list[Document]:
for d in docs:
heading = re.search(r"^#\s+(.+)$", d.text, re.M)
d.metadata["title"] = heading.group(1).strip() if heading else Path(d.metadata["source"]).stem
return docs
def chunk_by_headings(docs: list[Document], max_chars: int = 1200) -> list[Chunk]:
chunks = []
for d in docs:
sections = re.split(r"(?m)^(?=#{1,3} )", d.text) # split before Markdown headings
n = 0
for section in sections:
section = section.strip()
for start in range(0, len(section), max_chars):
piece = section[start:start + max_chars].strip()
if piece:
chunks.append(Chunk(f"{d.metadata['source']}:{n}", piece, dict(d.metadata)))
n += 1
return chunks
def add_context_and_version(chunks: list[Chunk]) -> list[Chunk]:
for i, c in enumerate(chunks):
c.text = f"[{c.metadata['title']}]\n{c.text}" # contextual header
c.metadata.update({"pipeline_version": PIPELINE_VERSION, "chunk_order": i})
return chunks
# ---------- runner ----------
DEFAULT_STEPS: list[Step] = [clean, drop_short_and_duplicates, add_title,
chunk_by_headings, add_context_and_version]
def run_pipeline(folder: str, steps: list[Step] = DEFAULT_STEPS) -> list[Chunk]:
items = load_folder(folder)
print(f"{'load':28} {len(items):5} items")
for step in steps:
items = step(items)
print(f"{step.__name__:28} {len(items):5} items")
return items
if __name__ == "__main__":
chunks = run_pipeline("docs")
print(chunks[0].id, chunks[0].metadata)
print(chunks[0].text[:200])
load 3 items
clean 3 items
drop_short_and_duplicates 3 items
add_title 3 items
chunk_by_headings 5 items
add_context_and_version 5 items
docs/expenses.txt:0 {'source': 'docs/expenses.txt', 'file_type': 'txt', 'content_hash': '9f2c...', 'title': 'expenses', 'pipeline_version': '2026.11-1', 'chunk_order': 0}
[expenses]
Zentrix Labs Travel and Expense Policy ...
The step-by-step counts are a cheap but valuable report: a sudden drop at one step (for example, half the files removed as "short") points straight to a problem.
Testing the steps
Because each step is a pure function on lists, unit tests are short:
def test_drop_duplicates():
docs = [Document("same text " * 20, {"source": "a"}), Document("same text " * 20, {"source": "b"})]
assert len(drop_short_and_duplicates(docs)) == 1
def test_chunk_ids_are_stable():
doc = Document("# Title\n" + "word " * 500, {"source": "x.md", "title": "Title"})
first = [c.id for c in chunk_by_headings([doc])]
second = [c.id for c in chunk_by_headings([doc])]
assert first == second
Configuration and versioning
- Keep sizes, thresholds and the step list in a config file, not scattered constants.
- Store
pipeline_versionwith every chunk. When you change a step, bump the version and rebuild the index, so old and new chunks are never mixed. - Cache expensive steps (LLM metadata extraction, contextual retrieval, embeddings) by content hash.
From pipeline to index
The output chunks are ready for embedding and storage: id, text and metadata map directly onto vector database upserts (Updating and Re-Indexing Vectors). For large collections, run the same steps in parallel workers (Scaling Ingestion).
Key takeaways
- Structure preprocessing as small, ordered steps that take and return lists.
- Log item counts after each step to spot problems instantly.
- Unit-test steps, keep configuration in one place, and version the pipeline in chunk metadata.
Frequently asked questions
Should I use a framework's ingestion pipeline instead?
LlamaIndex's ingestion pipeline and LangChain's loaders and splitters offer the same idea with ready-made steps. A small pipeline of your own is often clearer to debug; either way, keep the step structure.
Where do OCR and layout parsing fit?
In the load step: different loaders per file type, as in Parsing Complex Documents.
Practice exercises
- Add a language-detection step that stores the language in metadata.
- Add a step that writes a CSV report of every file and how many chunks it produced.