Draft a PDF/Doc canonical surrogate pipeline: content extraction, anchors, and…
- User
Draft a PDF/Doc canonical surrogate pipeline: content extraction, anchors, and conversions.
Assistant
Draft a PDF/Doc canonical surrogate pipeline: content extraction, anchors, and conversions.
The user wants a "canonical surrogate pipeline" for handling PDF and Doc files. The key components requested are:
What is a "canonical surrogate pipeline"?
Target Audience/Context: Likely a developer or architect building a RAG system, document search engine, or data processing pipeline. The tone should be technical, structured, and actionable.
Key Pipeline Stages:
Detailed Design:
Stage 1: Ingestion & Pre-processing
Stage 2: Content Extraction (The heavy lifting)
unstructured.io is the current gold standard for open source. PyMuPDF is fast. LlamaParse or Adobe Extract API for premium/complex layouts.Stage 3: Structural Enrichment & Anchoring
Stage 4: Chunking (Surrogate Generation)
Stage 5: Output/Storage
Refining the "Surrogate" Concept: The user might mean "converting the binary doc to a text surrogate" (like Markdown) to save token cost or normalize inputs. I should explicitly cover converting PDF/Doc to Markdown/HTML as a surrogate step.
Drafting the Structure:
Self-Correction/Refinement during drafting:
page_number, bbox (x,y,w,h), xpath (for docs).Code Example:
I'll provide a Python skeleton using unstructured and langchain as these are the industry standard building blocks.
Let's write the response.
Focus on the flow: Binary -> Intermediate JSON (Canonical) -> Chunk (Surrogate) -> Vector/DB.
Anchors Specifics:
Conversions:
Let's structure the final output clearly.
(Self-Correction): Make sure to mention OCR specifically for scanned PDFs, as that's a huge pain point.
Anchor Strategy Detail: UUIDs are bad for versioning. Deterministic hashes (based on content + location) are better for updating documents without duplicating vectors. I will recommend Deterministic IDs.
Final Polish: Ensure the distinction between extraction (getting data out) and surrogate creation (making it usable for AI) is clear.
Let's assemble. This specification outlines a canonical pipeline for transforming binary documents (PDF, DOCX) into a structured, text-based "Surrogate" format (Markdown/JSON) optimized for RAG (Retrieval-Augmented Generation) and LLM processing.
The core philosophy is "Structure-Aware Processing": preserving headers, lists, and tables while generating "Anchors" to map generated text back to the original source.
[ Input Binary ] -> [ Phase 1: Normalization ] -> [ Phase 2: Canonicalization ] -> [ Phase 3: Surrogation ] -> [ Output ]
| | | |
PDF/DOCX Layout Analysis Schema Mapping Chunking &
(Blob) Text/Table/Image JSON Intermediate Vectorization
Extraction
The goal is not just to extract text, but to extract structure. We convert unstructured binary formats into a Canonical Intermediate Representation (CIR), typically a JSON object.
PDFs are display formats, not semantic documents. You must choose between Text-Based (digital native) and Vision-Based (scanned) strategies.
PyMuPDF (fast) or Unstructured.io (comprehensive).extractText() yields low confidence or empty results, route the page image through an OCR engine (Tesseract, PaddleOCR).DOCX files are XML archives, making structure extraction easier.
python-docx or mammoth.w:p for paragraphs, w:tbl for tables).Heading 1, Title) to semantic tags.Every document converts to this standard JSON structure:
{
"meta": {
"filename": "contract_v2.pdf",
"file_hash": "sha256:abc...",
"page_count": 12
},
"elements": [
{
"id": "elem_001",
"type": "header",
"level": 1,
"text": "Executive Summary",
"bbox": [50, 100, 500, 120], // x0, y0, x1, y1
"page": 1
},
{
"id": "elem_002",
"type": "table",
"text": "Revenue | Cost\n$100 | $50",
"html": "<table>...</table>", // Rich format preservation
"page": 1,
"bbox": [50, 130, 500, 200]
}
]
}
Anchors connect the LLM's output back to the specific location in the source file. This is critical for citation verification ("Where did you find this answer?").
p. 12).[x1, y1, x2, y2]). Used for highlighting PDFs in UI./document/body/table[1]/tr[2]).We embed anchors into the text metadata or, if required for simple RAG contexts, into the text itself using invisible unicode or specific tokens.
Recommended Approach: Store anchors in the Chunk Metadata, not the visible text.
We convert the CIR (JSON) into formats suitable for specific tasks: Markdown (for context windows) and Chunks (for vector stores).
LLMs understand Markdown natively. We convert the JSON elements into a clean MD string.
type: header to # Title.type: table to Markdown Grid Tables or HTML tables (if the model supports it).[IMAGE: description of image] (using Vision LLMs to caption) or generic placeholders.<loc p="1" x="50">.Text must be split for Vector DB storage.
{
"id": "chunk_8a9b",
"text": "## Executive Summary\nThe revenue grew by 20%...",
"metadata": {
"source_page": 1,
"source_bbox": [50, 100, 500, 250], // Bounding box covering the whole chunk
"header_path": ["Executive Summary"], // Breadcrumbs
"doc_type": "pdf"
}
}
This example uses unstructured (industry standard for this architecture) and langchain for chunking.
from unstructured.partition.pdf import partition_pdf
from unstructured.partition.docx import partition_docx
from unstructured.staging.base import elements_to_json, elements_to_text
from langchain.text_splitter import MarkdownHeaderTextSplitter
class DocumentPipeline:
def __init__(self, file_path):
self.file_path = file_path
self.elements = []
def extract(self):
"""
Phase 1 & 2: Extraction and Canonicalization
"""
if self.file_path.endswith('.pdf'):
# strategy="hi_res" uses layout models (Detectron2) for tables/headers
# infer_table_structure=True extracts table HTML
self.elements = partition_pdf(
filename=self.file_path,
strategy="hi_res",
infer_table_structure=True
)
elif self.file_path.endswith('.docx'):
self.elements = partition_docx(filename=self.file_path)
return self.elements
def generate_surrogate_markdown(self):
"""
Phase 3: Conversion to Markdown Surrogate
"""
# Convert extracted elements to a clean Markdown string
return elements_to_text(self.elements)
def generate_chunks(self, markdown_text):
"""
Phase 3: Conversion to Vector-ready Chunks with Anchors
"""
headers_to_split_on = [
("#", "Header 1"),
("##", "Header 2"),
("###", "Header 3"),
]
splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=headers_to_split_on,
strip_headers=False
)
# This creates chunks while preserving header context
md_chunks = splitter.split_text(markdown_text)
# Map chunks back to page numbers (requires post-processing
# unstructured metadata which is attached to elements)
final_chunks = []
# Note: In a real prod env, you iterate self.elements to calculate
# the aggregate bbox and page range for the text in md_chunks.
for chunk in md_chunks:
final_chunks.append({
"content": chunk.page_content,
"metadata": {
"breadcrumbs": chunk.metadata, # H1/H2 context
"source": self.file_path
# Add page number logic here by finding the element
# matching the chunk text start.
}
})
return final_chunks
# --- Usage ---
pipeline = DocumentPipeline("report.pdf")
pipeline.extract() # 1. Extract + Canonicalize
surrogate_md = pipeline.generate_surrogate_markdown() # 2. Convert to MD
chunks = pipeline.generate_chunks(surrogate_md) # 3. Chunk with Anchors
# Output
print(surrogate_md) # Feed this to LLM context
# print(chunks) # Feed this to Vector DB
| Component | PDF Strategy | DOCX Strategy | Output Format |
|---|---|---|---|
| Extraction | Layout Analysis (Detectron2/YOLO) | XML Parsing (python-docx) | List of Elements (JSON) |
| Table Handling | OCR/Grid Detection | XML Table Extract | HTML or Markdown Table |
| Anchor | (Page, BBox) | (XPath, Page) | Metadata Dictionary |
| Surrogate | Markdown (text) + JSON (tables) | Markdown | .md or List[Documents] |