Extraction Pipeline Patterns
Kreuzberg's format detection -> extraction -> fallback orchestration for 75+ file formats
Core Pipeline Architecture
The extraction pipeline (crates/kreuzberg/src/core/pipeline.rs, crates/kreuzberg/src/extraction/) orchestrates:
- Format Detection - MIME type inference + extension validation -> select appropriate extractor
- Intelligent Extraction - Route to format-specific extractors (PDF, DOCX, Excel, HTML, images, archives, etc.)
- Fallback Strategies - Password-protected PDFs, OCR for images, nested archive handling, corrupted file recovery
- Post-Processing Pipeline - Validators, quality processing, chunking, custom hooks (see
core/pipeline.rs)
Format Detection Strategy
Location: crates/kreuzberg/src/core/mime.rs, crates/kreuzberg/src/core/formats.rs
Pattern: detect via magic bytes, validate extension alignment (prevent spoofing), route to extractor. Multiple extractors for same format -> choose highest confidence/specificity.
// Pseudocode: core/mime.rs
match (magic_bytes(content), extension) {
(Some(fmt), Some(ext)) if aligned -> Ok(fmt),
(Some(fmt), Some(ext)) if misaligned -> Err(FormatMismatch),
(Some(fmt), None) -> Ok(fmt), // magic bytes only
(None, Some(ext)) -> Ok(from_extension(ext)),
_ -> Err(UnknownFormat),
}
Extraction Modules (75 Formats)
| Category |
Extractors |
Key Modules |
| Office |
DOCX, XLSX, XLSM, XLSB, XLS, PPTX, ODP, ODS |
extraction/{docx,excel,pptx}.rs |
| PDF |
Standard + encrypted, password attempts |
pdf/ subdirectory (13 files) |
| Images |
PNG, JPG, TIFF, WebP, JP2, SVG (OCR-enabled) |
extraction/image.rs + ocr/ |
| Web |
HTML, XHTML, XML, SVG (DOM parsing) |
extraction/html.rs (67KB - complex table handling) |
| Email |
EML, MSG (headers, body, attachments, threading) |
extraction/email.rs |
| Archives |
ZIP, TAR, GZ, 7Z (recursive extraction) |
extraction/archive.rs (31KB) |
| Markdown |
MD, TXT, RST, Org Mode, RTF |
extraction/markdown.rs |
| Academic |
LaTeX, BibTeX, JATS, Jupyter, DocBook |
extraction/{structured,xml}.rs |
Extraction Dispatcher
// Pseudocode: extraction/mod.rs
let format = detect_format(source.bytes, source.extension);
let result = match format {
Pdf -> extract_pdf(source, config),
Docx -> extract_docx(source, config),
Image -> extract_image_with_ocr_fallback(source, config),
Archive -> extract_archive_recursive(source, config),
_ -> extract_with_plugin(format, source, config),
};
run_pipeline(result, config) // post-processing always runs
Fallback Strategies
- Password-Protected PDFs: Try primary password -> secondary password list -> return
is_encrypted=true in metadata on failure
- OCR Fallback: If image text extraction confidence < threshold, trigger OCR backend; return both results with scores
- Nested Archives: Recursive extraction with configurable depth limit; flatten or preserve hierarchy
- Corrupted File Recovery: Stream-based parsing, emit content up to error point, include error location in metadata
Configuration Integration
Location: crates/kreuzberg/src/core/config.rs, crates/kreuzberg/src/core/config_validation.rs
ExtractionConfig holds format-specific configs (pdf, image, html, office), fallback orchestration (fallback), and post-processing (postprocessor, chunking, keywords). See struct definition in config.rs.
Plugin System Integration
Location: crates/kreuzberg/src/plugins/
- CustomExtractor: Override built-in format extractors
- PostProcessor: Modify results after extraction (Early/Middle/Late stages)
- Validator: Fail-fast validation (e.g., minimum text length)
- OCRBackend: Swap OCR engine
Plugin registry loaded at startup, cached for zero-cost lookup.
Feature Flag Strategy
Location: Cargo.toml (workspace), crates/kreuzberg/Cargo.toml, FEATURE_MATRIX.md
20+ features across 9 language bindings. Key feature groups:
| Group |
Features |
Notes |
| OCR |
tesseract (default), tesseract-static, ocr-minimal |
Mutually exclusive recommendation |
| Formats |
pdf, pdf-minimal, office, office-minimal |
|
| AI/ML |
embeddings (requires ONNX), keywords-yake, keywords-rake, language-detection |
|
| Server |
api (Axum), mcp, tokio-runtime, lite-runtime |
|
| Bindings |
python-bindings, ruby-bindings, php-bindings, node-bindings, wasm |
|
Conditional compilation: modules gated with #[cfg(feature = "...")]. Runtime validate_config() warns if requested feature not compiled in.
Feature Flag Critical Rules
- Never mix conflicting features - e.g.,
ocr-minimal + tesseract should error at compile time
- Always provide feature diagnostics - Config validation must warn if feature unavailable
- Default to maximum feature set - Unless embedded/minimal specifically requested
- Test all feature combinations - Matrix testing in CI catches regressions
- WASM incompatible with embeddings, keywords, OCR
Critical Rules
- Always use format detection before routing to extractors (prevent confusion attacks)
- Stream-based parsing for PDFs/archives to handle multi-GB files
- Post-pipeline is mandatory: All extraction results flow through
run_pipeline() for validators/hooks
- Plugin overrides are order-dependent: Plugins registered first take priority
- Fallback timeouts: Set reasonable OCR/archive extraction timeouts (config-driven)
- Metadata preservation: Include format detection confidence, extraction method used, any fallbacks applied
Related Skills
- ocr-backend-management - OCR engine selection and image preprocessing
- chunking-embeddings - Post-extraction text splitting with FastEmbed
- api-server-mcp - Axum endpoint for extraction pipeline exposure and MCP server
1---2name: extraction-pipeline-patterns3description: extraction pipeline patterns4---56# Extraction Pipeline Patterns78**Kreuzberg's format detection -> extraction -> fallback orchestration for 75+ file formats**910## Core Pipeline Architecture1112The extraction pipeline (`crates/kreuzberg/src/core/pipeline.rs`, `crates/kreuzberg/src/extraction/`) orchestrates:13141. **Format Detection** - MIME type inference + extension validation -> select appropriate extractor152. **Intelligent Extraction** - Route to format-specific extractors (PDF, DOCX, Excel, HTML, images, archives, etc.)163. **Fallback Strategies** - Password-protected PDFs, OCR for images, nested archive handling, corrupted file recovery174. **Post-Processing Pipeline** - Validators, quality processing, chunking, custom hooks (see `core/pipeline.rs`)1819## Format Detection Strategy2021**Location**: `crates/kreuzberg/src/core/mime.rs`, `crates/kreuzberg/src/core/formats.rs`2223Pattern: detect via magic bytes, validate extension alignment (prevent spoofing), route to extractor. Multiple extractors for same format -> choose highest confidence/specificity.2425```rust26// Pseudocode: core/mime.rs27match (magic_bytes(content), extension) {28 (Some(fmt), Some(ext)) if aligned -> Ok(fmt),29 (Some(fmt), Some(ext)) if misaligned -> Err(FormatMismatch),30 (Some(fmt), None) -> Ok(fmt), // magic bytes only31 (None, Some(ext)) -> Ok(from_extension(ext)),32 _ -> Err(UnknownFormat),33}34```3536## Extraction Modules (75 Formats)3738| Category | Extractors | Key Modules |39|----------|-----------|------------|40| **Office** | DOCX, XLSX, XLSM, XLSB, XLS, PPTX, ODP, ODS | `extraction/{docx,excel,pptx}.rs` |41| **PDF** | Standard + encrypted, password attempts | `pdf/` subdirectory (13 files) |42| **Images** | PNG, JPG, TIFF, WebP, JP2, SVG (OCR-enabled) | `extraction/image.rs` + `ocr/` |43| **Web** | HTML, XHTML, XML, SVG (DOM parsing) | `extraction/html.rs` (67KB - complex table handling) |44| **Email** | EML, MSG (headers, body, attachments, threading) | `extraction/email.rs` |45| **Archives** | ZIP, TAR, GZ, 7Z (recursive extraction) | `extraction/archive.rs` (31KB) |46| **Markdown** | MD, TXT, RST, Org Mode, RTF | `extraction/markdown.rs` |47| **Academic** | LaTeX, BibTeX, JATS, Jupyter, DocBook | `extraction/{structured,xml}.rs` |4849## Extraction Dispatcher5051```rust52// Pseudocode: extraction/mod.rs53let format = detect_format(source.bytes, source.extension);54let result = match format {55 Pdf -> extract_pdf(source, config),56 Docx -> extract_docx(source, config),57 Image -> extract_image_with_ocr_fallback(source, config),58 Archive -> extract_archive_recursive(source, config),59 _ -> extract_with_plugin(format, source, config),60};61run_pipeline(result, config) // post-processing always runs62```6364## Fallback Strategies6566- **Password-Protected PDFs**: Try primary password -> secondary password list -> return `is_encrypted=true` in metadata on failure67- **OCR Fallback**: If image text extraction confidence < threshold, trigger OCR backend; return both results with scores68- **Nested Archives**: Recursive extraction with configurable depth limit; flatten or preserve hierarchy69- **Corrupted File Recovery**: Stream-based parsing, emit content up to error point, include error location in metadata7071## Configuration Integration7273**Location**: `crates/kreuzberg/src/core/config.rs`, `crates/kreuzberg/src/core/config_validation.rs`7475`ExtractionConfig` holds format-specific configs (`pdf`, `image`, `html`, `office`), fallback orchestration (`fallback`), and post-processing (`postprocessor`, `chunking`, `keywords`). See struct definition in `config.rs`.7677## Plugin System Integration7879**Location**: `crates/kreuzberg/src/plugins/`8081- **CustomExtractor**: Override built-in format extractors82- **PostProcessor**: Modify results after extraction (Early/Middle/Late stages)83- **Validator**: Fail-fast validation (e.g., minimum text length)84- **OCRBackend**: Swap OCR engine8586Plugin registry loaded at startup, cached for zero-cost lookup.8788## Feature Flag Strategy8990**Location**: `Cargo.toml` (workspace), `crates/kreuzberg/Cargo.toml`, `FEATURE_MATRIX.md`919220+ features across 9 language bindings. Key feature groups:9394| Group | Features | Notes |95|-------|----------|-------|96| OCR | `tesseract` (default), `tesseract-static`, `ocr-minimal` | Mutually exclusive recommendation |97| Formats | `pdf`, `pdf-minimal`, `office`, `office-minimal` | |98| AI/ML | `embeddings` (requires ONNX), `keywords-yake`, `keywords-rake`, `language-detection` | |99| Server | `api` (Axum), `mcp`, `tokio-runtime`, `lite-runtime` | |100| Bindings | `python-bindings`, `ruby-bindings`, `php-bindings`, `node-bindings`, `wasm` | |101102Conditional compilation: modules gated with `#[cfg(feature = "...")]`. Runtime `validate_config()` warns if requested feature not compiled in.103104### Feature Flag Critical Rules1051061. **Never mix conflicting features** - e.g., `ocr-minimal` + `tesseract` should error at compile time1072. **Always provide feature diagnostics** - Config validation must warn if feature unavailable1083. **Default to maximum feature set** - Unless embedded/minimal specifically requested1094. **Test all feature combinations** - Matrix testing in CI catches regressions1105. **WASM incompatible** with embeddings, keywords, OCR111112## Critical Rules1131141. **Always use format detection** before routing to extractors (prevent confusion attacks)1152. **Stream-based parsing** for PDFs/archives to handle multi-GB files1163. **Post-pipeline is mandatory**: All extraction results flow through `run_pipeline()` for validators/hooks1174. **Plugin overrides are order-dependent**: Plugins registered first take priority1185. **Fallback timeouts**: Set reasonable OCR/archive extraction timeouts (config-driven)1196. **Metadata preservation**: Include format detection confidence, extraction method used, any fallbacks applied120121## Related Skills122123- **ocr-backend-management** - OCR engine selection and image preprocessing124- **chunking-embeddings** - Post-extraction text splitting with FastEmbed125- **api-server-mcp** - Axum endpoint for extraction pipeline exposure and MCP server