Library

Volume 2 · RAG Architecture

Notebook
Sign in

Section 18

Data Ingestion & Document Processing

661 words · about 3 min

18.1 Enterprise Document Processing Pipeline

class DocumentProcessor:
    """Production document processing pipeline."""
    def process(self, document: Document) -> list[Chunk]:
        raw_text, structure = self.extract(document)          # 1. Format detection & extraction
        cleaned = self.clean(raw_text)                         # 2. Remove headers/footers/watermarks
        pii_masked = self.mask_pii(cleaned)                     # 3. PII detection & redaction
        sections = self.extract_structure(structure)            # 4. Preserve headings/tables/lists
        chunks = self.chunk(pii_masked, sections, document.doc_type)  # 5. Adaptive chunking
        enriched = self.enrich_metadata(chunks, document)       # 6. Metadata enrichment
        validated = self.validate_quality(enriched)             # 7. Quality gate
        return validated

18.2 Parser Selection by Document Type

Document Type Recommended Parser Key Considerations
PDF (text-based) PyMuPDF + Unstructured Fastest, handles most PDFs
PDF (scanned/images) Cloud Document Intelligence (OCR) Best OCR + layout analysis
PDF (complex tables) Document Intelligence + VLM Tables need special handling
Word (.docx) python-docx Preserve styles, embedded images
PowerPoint (.pptx) python-pptx Slide-level chunking, speaker notes
HTML Trafilatura / BeautifulSoup Boilerplate removal is critical
Code Tree-sitter + AST parsers Preserve function/class boundaries
Structured (CSV/JSON) Pandas + schema inference Don’t chunk — preserve structure
Email Custom parser Thread structure, attachments
Audio/Video Whisper, AssemblyAI Transcript + timestamp alignment

18.3 Preprocessing Steps

  1. Format Detection & Extraction: Identify file type, extract raw text/structure
  2. Cleaning: Remove headers/footers, page numbers, watermarks, boilerplate
  3. Structure Preservation: Maintain headings, tables, lists as metadata
  4. Language Detection: Route to language-specific processing
  5. PII Detection & Masking: Identify and redact sensitive information before storage/embedding
  6. Metadata Extraction: Author, date, document type, section hierarchy

18.4 Table Handling — the #1 Pain Point

Approach 1: Table-to-Text. Convert a table into a natural-language description via LLM:

Table: Q3 Revenue by Region
| Region | Revenue | Growth |
| NA     | $50M    | 12%    |
| EMEA   | $30M    | 8%     |

→ "Q3 revenue was $50M in North America (12% growth) and $30M in EMEA (8% growth)."

Approach 2: Keep as Structured Chunk. Store the entire table as one chunk with markdown formatting — good for small tables. Approach 3: Table Embedding (Advanced). Use specialized embeddings that understand row/column relationships.

18.5 PII Handling Pipeline

Document Ingestion
       │
       ▼
┌──────────────────┐
│ PII Detection     │ ─ Named-entity + regex based (SSN, emails, phones, addresses)
└────────┬─────────┘
         │
    ┌────┴────┐
    ▼         ▼
 Redact    Pseudonymize
 (Replace  (Replace with
  with      consistent
  [PERSON]) placeholder)
    │         │
    └────┬────┘
         ▼
  Embed & Store (PII-free chunks)
         ▼
  At Query Time:
  - Generate response from PII-free context
  - Re-hydrate display names for authorized users only

Section 18 — Interview Q&A

Q: How do you handle different data types (documents, structured data, code, multimedia) in a RAG system? A: Documents (PDF/DOCX/HTML) are parsed with layout-aware tools, chunked by section/paragraph with heading hierarchy preserved as metadata; tables are the main challenge and should be kept intact or converted to text descriptions rather than split. Structured data (databases, CSV, JSON) generally should not be chunked at all — instead use text-to-SQL for databases, or embed schema/column descriptions for retrieval, preserving relational structure rather than fragmenting rows. Code should be chunked using AST-based parsing (tree-sitter) at function/class boundaries, never split mid-function, with signatures and docstrings included as metadata. Multimedia (images/audio/video) gets converted to text representations first — VLM-generated descriptions for images, Whisper transcripts for audio, keyframe + transcript alignment for video — while preserving modality metadata so citations can point back to the original asset.

Q: Walk through your PII handling strategy for a RAG pipeline. A: Three-layer protection. At ingestion, detect and de-identify PII before embedding — replace names/SSNs/etc. with consistent placeholder tokens, and store the PII mapping separately in an encrypted, access-controlled store (never in the vector DB alongside embeddings). At query time, if a user’s query itself contains PII, detect and use reference IDs rather than embedding raw PII as a search query. At response time, run a PHI/PII scanner on the generated output before returning it — if PII that shouldn’t be disclosed to this user appears, redact it — and log every response for audit. This layered approach means no single failure point exposes sensitive data.