WebAssembly API Reference
WebAssembly API Reference v5.0.0-rc.3¶
Functions¶
extractBytes()¶
Extract content from a byte array.
This is the main entry point for in-memory extraction. It performs the following steps:
- Validate MIME type
- Handle legacy format conversion if needed
- Select appropriate extractor from registry
- Extract content
- Run post-processing pipeline
Returns:
An ExtractionResult containing the extracted content and metadata.
Errors:
Returns KreuzbergError.Validation if MIME type is invalid.
Returns KreuzbergError.UnsupportedFormat if MIME type is not supported.
Signature:
function extractBytes(content: Buffer, mimeType: string, config: ExtractionConfig): Promise<ExtractionResult>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
Buffer |
Yes | The byte array to extract |
mimeType |
string |
Yes | MIME type of the content |
config |
ExtractionConfig |
Yes | Extraction configuration |
Returns: ExtractionResult
Errors: Throws Error with a descriptive message.
extractFile()¶
Extract content from a file.
This is the main entry point for file-based extraction. It performs the following steps:
- Check cache for existing result (if caching enabled)
- Detect or validate MIME type
- Select appropriate extractor from registry
- Extract content
- Run post-processing pipeline
- Store result in cache (if caching enabled)
Returns:
An ExtractionResult containing the extracted content and metadata.
Errors:
Returns KreuzbergError.Io if the file doesn't exist (NotFound) or for other file I/O errors.
Returns KreuzbergError.UnsupportedFormat if MIME type is not supported.
Signature:
function extractFile(path: string, mimeType?: string, config: ExtractionConfig): Promise<ExtractionResult>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
string |
Yes | Path to the file to extract |
mimeType |
string \| null |
No | Optional MIME type override. If None, will be auto-detected |
config |
ExtractionConfig |
Yes | Extraction configuration |
Returns: ExtractionResult
Errors: Throws Error with a descriptive message.
extractFileSync()¶
Synchronous wrapper for extract_file.
This is a convenience function that blocks the current thread until extraction completes.
For async code, use extract_file directly.
Uses the global Tokio runtime for 100x+ performance improvement over creating a new runtime per call. Always uses the global runtime to avoid nested runtime issues.
This function is only available with the tokio-runtime feature. For WASM targets,
use a truly synchronous extraction approach instead.
Signature:
function extractFileSync(path: string, mimeType?: string, config: ExtractionConfig): ExtractionResult
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
string |
Yes | Path to the file |
mimeType |
string \| null |
No | The mime type |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: ExtractionResult
Errors: Throws Error with a descriptive message.
extractBytesSync()¶
Synchronous wrapper for extract_bytes.
Uses the global Tokio runtime for 100x+ performance improvement over creating a new runtime per call.
With the tokio-runtime feature, this blocks the current thread using the global
Tokio runtime. Without it (WASM), this calls a truly synchronous implementation.
Signature:
function extractBytesSync(content: Buffer, mimeType: string, config: ExtractionConfig): ExtractionResult
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
Buffer |
Yes | The content to process |
mimeType |
string |
Yes | The mime type |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: ExtractionResult
Errors: Throws Error with a descriptive message.
batchExtractFilesSync()¶
Synchronous wrapper for batch_extract_files.
Uses the global Tokio runtime for optimal performance.
Only available with tokio-runtime (WASM has no filesystem).
Signature:
function batchExtractFilesSync(items: Array<BatchFileItem>, config: ExtractionConfig): Array<ExtractionResult>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
Array<BatchFileItem> |
Yes | The items |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: Array<ExtractionResult>
Errors: Throws Error with a descriptive message.
batchExtractBytesSync()¶
Synchronous wrapper for batch_extract_bytes.
Uses the global Tokio runtime for optimal performance.
With the tokio-runtime feature, this blocks the current thread using the global
Tokio runtime. Without it (WASM), this calls a truly synchronous implementation
that iterates through items and calls extract_bytes_sync().
Signature:
function batchExtractBytesSync(items: Array<BatchBytesItem>, config: ExtractionConfig): Array<ExtractionResult>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
Array<BatchBytesItem> |
Yes | The items |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: Array<ExtractionResult>
Errors: Throws Error with a descriptive message.
batchExtractFiles()¶
Extract content from multiple files concurrently.
This function processes multiple files in parallel, automatically managing
concurrency to prevent resource exhaustion. The concurrency limit can be
configured via ExtractionConfig.max_concurrent_extractions or defaults
to (num_cpus * 1.5).ceil().
Each file can optionally specify a FileExtractionConfig that overrides specific
fields from the batch-level config. Pass null for a file to use the batch defaults.
Batch-level settings like max_concurrent_extractions and use_cache are always
taken from the batch-level config.
per-file configuration overrides.
config- Batch-level extraction configuration (provides defaults and batch settings)
Returns:
A vector of ExtractionResult in the same order as the input items.
Errors:
Individual file errors are captured in the result metadata. System errors (IO, RuntimeError equivalents) will bubble up and fail the entire batch.
Simple usage with no per-file overrides:
Per-file configuration overrides:
Signature:
function batchExtractFiles(items: Array<BatchFileItem>, config: ExtractionConfig): Promise<Array<ExtractionResult>>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
Array<BatchFileItem> |
Yes | Vector of BatchFileItem structs, each containing a path and optional |
config |
ExtractionConfig |
Yes | Batch-level extraction configuration (provides defaults and batch settings) |
Returns: Array<ExtractionResult>
Errors: Throws Error with a descriptive message.
batchExtractBytes()¶
Extract content from multiple byte arrays concurrently.
This function processes multiple byte arrays in parallel, automatically managing
concurrency to prevent resource exhaustion. The concurrency limit can be
configured via ExtractionConfig.max_concurrent_extractions or defaults
to (num_cpus * 1.5).ceil().
Each item can optionally specify a FileExtractionConfig that overrides specific
fields from the batch-level config. Pass null as the config to use
the batch-level defaults for that item.
MIME type, and optional per-item configuration overrides.
config- Batch-level extraction configuration
Returns:
A vector of ExtractionResult in the same order as the input items.
Simple usage with no per-item overrides:
Per-item configuration overrides:
Signature:
function batchExtractBytes(items: Array<BatchBytesItem>, config: ExtractionConfig): Promise<Array<ExtractionResult>>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
Array<BatchBytesItem> |
Yes | Vector of BatchBytesItem structs, each containing content bytes, |
config |
ExtractionConfig |
Yes | Batch-level extraction configuration |
Returns: Array<ExtractionResult>
Errors: Throws Error with a descriptive message.
detectMimeTypeFromBytes()¶
Detect MIME type from raw file bytes.
Uses magic byte signatures to detect file type from content.
Falls back to infer crate for comprehensive detection.
For ZIP-based files, inspects contents to distinguish Office Open XML formats (DOCX, XLSX, PPTX) from plain ZIP archives.
Returns:
The detected MIME type string.
Errors:
Returns KreuzbergError.UnsupportedFormat if MIME type cannot be determined.
Signature:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
Buffer |
Yes | Raw file bytes |
Returns: string
Errors: Throws Error with a descriptive message.
getExtensionsForMime()¶
Get file extensions for a given MIME type.
Returns all known file extensions that map to the specified MIME type.
Returns:
A vector of file extensions (without leading dot) for the MIME type.
Signature:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
mimeType |
string |
Yes | The MIME type to look up |
Returns: Array<string>
Errors: Throws Error with a descriptive message.
clearEmbeddingBackends()¶
Clear all embedding backends from the global registry.
Calls shutdown() on every registered backend, then empties the registry.
Errors:
- Any error returned by a backend's
shutdown()method. The first error encountered stops processing of remaining backends.
Signature:
Returns: void
Errors: Throws Error with a descriptive message.
listEmbeddingBackends()¶
List the names of all registered embedding backends.
Used by kreuzberg-cli and the api/mcp endpoints; excluded from the
language bindings via alef.toml [exclude].functions.
Signature:
Returns: Array<string>
Errors: Throws Error with a descriptive message.
listDocumentExtractors()¶
List names of all registered document extractors.
Signature:
Returns: Array<string>
Errors: Throws Error with a descriptive message.
clearDocumentExtractors()¶
Clear all document extractors from the global registry.
Calls shutdown() on every registered extractor, then empties the registry.
Errors:
- Any error returned by an extractor's
shutdown()method. The first error encountered stops processing of remaining extractors.
Signature:
Returns: void
Errors: Throws Error with a descriptive message.
listOcrBackends()¶
List all registered OCR backends.
Returns the names of all OCR backends currently registered in the global registry.
Returns:
A vector of OCR backend names.
Signature:
Returns: Array<string>
Errors: Throws Error with a descriptive message.
clearOcrBackends()¶
Clear all OCR backends from the global registry.
Removes all OCR backends and calls their shutdown() methods.
Returns:
Ok(())if all backends were cleared successfullyErr(...)if any shutdown method failed
Signature:
Returns: void
Errors: Throws Error with a descriptive message.
listPostProcessors()¶
List all registered post-processor names.
Returns a vector of all post-processor names currently registered in the global registry.
Returns:
Ok(Vec<String>)- Vector of post-processor namesErr(...)if the registry lock is poisoned
Signature:
Returns: Array<string>
Errors: Throws Error with a descriptive message.
clearPostProcessors()¶
Remove all registered post-processors.
Signature:
Returns: void
Errors: Throws Error with a descriptive message.
listRenderers()¶
List names of all registered renderers.
Errors:
Returns an error if the registry lock is poisoned.
Signature:
Returns: Array<string>
Errors: Throws Error with a descriptive message.
clearRenderers()¶
Clear all renderers from the global registry.
Removes every renderer, including the built-in defaults (markdown, html, djot, plain). After calling this no renderers are registered; re-register as needed.
Errors:
Returns an error if the registry lock is poisoned.
Signature:
Returns: void
Errors: Throws Error with a descriptive message.
listValidators()¶
List names of all registered validators.
Signature:
Returns: Array<string>
Errors: Throws Error with a descriptive message.
clearValidators()¶
Remove all registered validators.
Signature:
Returns: void
Errors: Throws Error with a descriptive message.
embedTextsAsync()¶
Generate embeddings asynchronously for a list of text strings.
This is the async counterpart to embed_texts. It offloads the blocking
ONNX inference work to a dedicated blocking thread pool via Tokio's
spawn_blocking, keeping the async executor free.
Returns one embedding vector per input text in the same order.
Errors:
KreuzbergError.MissingDependencyif ONNX Runtime is not installedKreuzbergError.Embeddingif the preset name is unknown, model download fails, or the blocking inference task panics
Signature:
function embedTextsAsync(texts: Array<string>, config: EmbeddingConfig): Promise<Array<Array<number>>>
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
texts |
Array<string> |
Yes | Vec of strings to embed (owned, sent to blocking thread) |
config |
EmbeddingConfig |
Yes | Embedding configuration specifying model, batch size, and normalization |
Returns: Array<Array<number>>
Errors: Throws Error with a descriptive message.
renderPdfPageToPng()¶
Render a single PDF page to PNG bytes.
Returns raw PNG-encoded bytes for the specified page at the given DPI. Uses pdf_oxide with tiny-skia for pure-Rust rendering.
Errors:
Returns KreuzbergError.Parsing if the PDF cannot be opened, authenticated,
or rendered, or if page_index is out of range.
Signature:
function renderPdfPageToPng(pdfBytes: Buffer, pageIndex: number, dpi?: number, password?: string): Buffer
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
pdfBytes |
Buffer |
Yes | Raw PDF file bytes |
pageIndex |
number |
Yes | Zero-based page index |
dpi |
number \| null |
No | Resolution in dots per inch (default: 150) |
password |
string \| null |
No | Optional password for encrypted PDFs |
Returns: Buffer
Errors: Throws Error with a descriptive message.
detectMimeType()¶
Detect the MIME type of a file at the given path.
Uses the file extension and optionally the file content to determine the MIME type.
Set check_exists to true to verify the file exists before detection.
Signature:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
string |
Yes | Path to the file |
checkExists |
boolean |
Yes | The check exists |
Returns: string
Errors: Throws Error with a descriptive message.
getEmbeddingPreset()¶
Get an embedding preset by name.
Returns null if no preset with the given name exists. Returns an owned
clone so the value is safe to pass across FFI boundaries.
Signature:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
string |
Yes | The name |
Returns: EmbeddingPreset | null
listEmbeddingPresets()¶
List the names of all available embedding presets.
Returns owned Strings so the values are safe to pass across FFI boundaries.
Signature:
Returns: Array<string>
Types¶
AccelerationConfig¶
Hardware acceleration configuration for ONNX Runtime models.
Controls which execution provider (CPU, CoreML, CUDA, TensorRT) is used for inference in layout detection and embedding generation.
| Field | Type | Default | Description |
|---|---|---|---|
provider |
ExecutionProviderType |
ExecutionProviderType.Auto |
Execution provider to use for ONNX inference. |
deviceId |
number |
— | GPU device ID (for CUDA/TensorRT). Ignored for CPU/CoreML/Auto. |
ArchiveEntry¶
A single file extracted from an archive.
When archives (ZIP, TAR, 7Z, GZIP) are extracted with recursive extraction
enabled, each processable file produces its own full ExtractionResult.
| Field | Type | Default | Description |
|---|---|---|---|
path |
string |
— | Archive-relative file path (e.g. "folder/document.pdf"). |
mimeType |
string |
— | Detected MIME type of the file. |
result |
ExtractionResult |
— | Full extraction result for this file. |
ArchiveMetadata¶
Archive (ZIP/TAR/7Z) metadata.
Extracted from compressed archive files containing file lists and size information.
| Field | Type | Default | Description |
|---|---|---|---|
format |
string |
— | Archive format ("ZIP", "TAR", "7Z", etc.) |
fileCount |
number |
— | Total number of files in the archive |
fileList |
Array<string> |
[] |
List of file paths within the archive |
totalSize |
number |
— | Total uncompressed size in bytes |
compressedSize |
number \| null |
null |
Compressed size in bytes (if available) |
BatchBytesItem¶
Batch item for byte array extraction.
Used with batch_extract_bytes and batch_extract_bytes_sync
to represent a single item in a batch extraction job.
| Field | Type | Default | Description |
|---|---|---|---|
content |
Buffer |
— | The content bytes to extract from |
mimeType |
string |
— | MIME type of the content (e.g., "application/pdf", "text/html") |
config |
FileExtractionConfig \| null |
null |
Per-item configuration overrides (None uses batch-level defaults) |
BatchFileItem¶
Batch item for file extraction.
Used with batch_extract_files and batch_extract_files_sync
to represent a single file in a batch extraction job.
| Field | Type | Default | Description |
|---|---|---|---|
path |
string |
— | Path to the file to extract from |
config |
FileExtractionConfig \| null |
null |
Per-file configuration overrides (None uses batch-level defaults) |
BibtexMetadata¶
BibTeX bibliography metadata.
| Field | Type | Default | Description |
|---|---|---|---|
entryCount |
number |
— | Number of entries in the bibliography. |
citationKeys |
Array<string> |
[] |
Citation keys |
authors |
Array<string> |
[] |
Authors |
yearRange |
YearRange \| null |
null |
Year range (year range) |
entryTypes |
Record<string, number> \| null |
{} |
Entry types |
BoundingBox¶
Bounding box coordinates for element positioning.
| Field | Type | Default | Description |
|---|---|---|---|
x0 |
number |
— | Left x-coordinate |
y0 |
number |
— | Bottom y-coordinate |
x1 |
number |
— | Right x-coordinate |
y1 |
number |
— | Top y-coordinate |
Chunk¶
A text chunk with optional embedding and metadata.
Chunks are created when chunking is enabled in ExtractionConfig. Each chunk
contains the text content, optional embedding vector (if embedding generation
is configured), and metadata about its position in the document.
| Field | Type | Default | Description |
|---|---|---|---|
content |
string |
— | The text content of this chunk. |
chunkType |
ChunkType |
/* serde(default) */ |
Semantic structural classification of this chunk. Assigned by the heuristic classifier based on content patterns and heading context. Defaults to ChunkType.Unknown when no rule matches. |
embedding |
Array<number> \| null |
null |
Optional embedding vector for this chunk. Only populated when EmbeddingConfig is provided in chunking configuration. The dimensionality depends on the chosen embedding model. |
metadata |
ChunkMetadata |
— | Metadata about this chunk's position and properties. |
ChunkMetadata¶
Metadata about a chunk's position in the original document.
| Field | Type | Default | Description |
|---|---|---|---|
byteStart |
number |
— | Byte offset where this chunk starts in the original text (UTF-8 valid boundary). |
byteEnd |
number |
— | Byte offset where this chunk ends in the original text (UTF-8 valid boundary). |
tokenCount |
number \| null |
null |
Number of tokens in this chunk (if available). This is calculated by the embedding model's tokenizer if embeddings are enabled. |
chunkIndex |
number |
— | Zero-based index of this chunk in the document. |
totalChunks |
number |
— | Total number of chunks in the document. |
firstPage |
number \| null |
null |
First page number this chunk spans (1-indexed). Only populated when page tracking is enabled in extraction configuration. |
lastPage |
number \| null |
null |
Last page number this chunk spans (1-indexed, equal to first_page for single-page chunks). Only populated when page tracking is enabled in extraction configuration. |
headingContext |
HeadingContext \| null |
/* serde(default) */ |
Heading context when using Markdown chunker. Contains the heading hierarchy this chunk falls under. Only populated when ChunkerType.Markdown is used. |
imageIndices |
Array<number> |
/* serde(default) */ |
Indices into ExtractionResult.images for images on pages covered by this chunk. Contains zero-based indices into the top-level images collection for every image whose page_number falls within [first_page, last_page]. Empty when image extraction is disabled or the chunk spans no pages with images. |
ChunkingConfig¶
Chunking configuration.
Configures text chunking for document content, including chunk size, overlap, trimming behavior, and optional embeddings.
Use ..the default constructor when constructing to allow for future field additions:
| Field | Type | Default | Description |
|---|---|---|---|
maxCharacters |
number |
1000 |
Maximum size per chunk (in units determined by sizing). When sizing is Characters (default), this is the max character count. When using token-based sizing, this is the max token count. Default: 1000 |
overlap |
number |
200 |
Overlap between chunks (in units determined by sizing). Default: 200 |
trim |
boolean |
true |
Whether to trim whitespace from chunk boundaries. Default: true |
chunkerType |
ChunkerType |
ChunkerType.Text |
Type of chunker to use (Text or Markdown). Default: Text |
embedding |
EmbeddingConfig \| null |
null |
Optional embedding configuration for chunk embeddings. |
preset |
string \| null |
null |
Use a preset configuration (overrides individual settings if provided). |
sizing |
ChunkSizing |
ChunkSizing.Characters |
How to measure chunk size. Default: Characters (Unicode character count). Enable chunking-tiktoken or chunking-tokenizers features for token-based sizing. |
prependHeadingContext |
boolean |
false |
When true and chunker_type is Markdown, prepend the heading hierarchy path (e.g. "# Title > ## Section\n\n") to each chunk's content string. This is useful for RAG pipelines where each chunk needs self-contained context about its position in the document structure. Default: false |
topicThreshold |
number \| null |
null |
Optional cosine similarity threshold for semantic topic boundary detection. Only used when chunker_type is Semantic and an EmbeddingConfig is provided. You almost never need to set this. When omitted, defaults to 0.75 which works well for most documents. Lower values detect more topic boundaries (more, smaller chunks); higher values detect fewer. Range: 0.0..=1.0. |
Methods¶
default()¶
Signature:
CitationMetadata¶
Citation file metadata (RIS, PubMed, EndNote).
| Field | Type | Default | Description |
|---|---|---|---|
citationCount |
number |
— | Number of citations |
format |
string \| null |
null |
Format |
authors |
Array<string> |
[] |
Authors |
yearRange |
YearRange \| null |
null |
Year range (year range) |
dois |
Array<string> |
[] |
Dois |
keywords |
Array<string> |
[] |
Keywords |
ContentFilterConfig¶
Cross-extractor content filtering configuration.
Controls whether "furniture" content (headers, footers, page numbers, watermarks, repeating text) is included in or stripped from extraction results. Applies across all extractors (PDF, DOCX, RTF, ODT, HTML, etc.) with format-specific implementation.
When null on ExtractionConfig, each extractor uses its current
default behavior unchanged.
| Field | Type | Default | Description |
|---|---|---|---|
includeHeaders |
boolean |
false |
Include running headers in extraction output. - PDF: Disables top-margin furniture stripping and prevents the layout model from treating PageHeader-classified regions as furniture. - DOCX: Includes document headers in text output. - RTF/ODT: Headers already included; this is a no-op when true. - HTML/EPUB: Keeps <header> element content. Default: false (headers are stripped or excluded). |
includeFooters |
boolean |
false |
Include running footers in extraction output. - PDF: Disables bottom-margin furniture stripping and prevents the layout model from treating PageFooter-classified regions as furniture. - DOCX: Includes document footers in text output. - RTF/ODT: Footers already included; this is a no-op when true. - HTML/EPUB: Keeps <footer> element content. Default: false (footers are stripped or excluded). |
stripRepeatingText |
boolean |
true |
Enable the heuristic cross-page repeating text detector. When true (default), text that repeats verbatim across a supermajority of pages is classified as furniture and stripped. Disable this if brand names or repeated headings are being incorrectly removed by the heuristic. Note: when a layout-detection model is active, the model may independently classify page-header / page-footer regions as furniture on a per-page basis. To preserve those regions, set include_headers = true, include_footers = true, or both, in addition to disabling this flag. Primarily affects PDF extraction. Default: true. |
includeWatermarks |
boolean |
false |
Include watermark text in extraction output. - PDF: Keeps watermark artifacts and arXiv identifiers. - Other formats: No effect currently. Default: false (watermarks are stripped). |
Methods¶
default()¶
Signature:
ContributorRole¶
JATS contributor with role.
| Field | Type | Default | Description |
|---|---|---|---|
name |
string |
— | The name |
role |
string \| null |
null |
Role |
CoreProperties¶
Dublin Core metadata from docProps/core.xml
Contains standard metadata fields defined by the Dublin Core standard and Office-specific extensions.
| Field | Type | Default | Description |
|---|---|---|---|
title |
string \| null |
null |
Document title |
subject |
string \| null |
null |
Document subject/topic |
creator |
string \| null |
null |
Document creator/author |
keywords |
string \| null |
null |
Keywords or tags |
description |
string \| null |
null |
Document description/abstract |
lastModifiedBy |
string \| null |
null |
User who last modified the document |
revision |
string \| null |
null |
Revision number |
created |
string \| null |
null |
Creation timestamp (ISO 8601) |
modified |
string \| null |
null |
Last modification timestamp (ISO 8601) |
category |
string \| null |
null |
Document category |
contentStatus |
string \| null |
null |
Content status (Draft, Final, etc.) |
language |
string \| null |
null |
Document language |
identifier |
string \| null |
null |
Unique identifier |
version |
string \| null |
null |
Document version |
lastPrinted |
string \| null |
null |
Last print timestamp (ISO 8601) |
CsvMetadata¶
CSV/TSV file metadata.
| Field | Type | Default | Description |
|---|---|---|---|
rowCount |
number |
— | Number of rows |
columnCount |
number |
— | Number of columns |
delimiter |
string \| null |
null |
Delimiter |
hasHeader |
boolean |
— | Whether header |
columnTypes |
Array<string> \| null |
[] |
Column types |
DbfFieldInfo¶
dBASE field information.
| Field | Type | Default | Description |
|---|---|---|---|
name |
string |
— | The name |
fieldType |
string |
— | Field type |
DbfMetadata¶
dBASE (DBF) file metadata.
| Field | Type | Default | Description |
|---|---|---|---|
recordCount |
number |
— | Number of records |
fieldCount |
number |
— | Number of fields |
fields |
Array<DbfFieldInfo> |
[] |
Fields |
DetectResponse¶
MIME type detection response.
| Field | Type | Default | Description |
|---|---|---|---|
mimeType |
string |
— | Detected MIME type |
filename |
string \| null |
null |
Original filename (if provided) |
DjotContent¶
Comprehensive Djot document structure with semantic preservation.
This type captures the full richness of Djot markup, including:
- Block-level structures (headings, lists, blockquotes, code blocks, etc.)
- Inline formatting (emphasis, strong, highlight, subscript, superscript, etc.)
- Attributes (classes, IDs, key-value pairs)
- Links, images, footnotes
- Math expressions (inline and display)
- Tables with full structure
Available when the djot feature is enabled.
| Field | Type | Default | Description |
|---|---|---|---|
plainText |
string |
— | Plain text representation for backwards compatibility |
blocks |
Array<FormattedBlock> |
— | Structured block-level content |
metadata |
Metadata |
— | Metadata from YAML frontmatter |
tables |
Array<Table> |
— | Extracted tables as structured data |
images |
Array<DjotImage> |
— | Extracted images with metadata |
links |
Array<DjotLink> |
— | Extracted links with URLs |
footnotes |
Array<Footnote> |
— | Footnote definitions |
attributes |
Array<string> |
/* serde(default) */ |
Attributes mapped by element identifier (if present) |
DjotImage¶
Image element in Djot.
| Field | Type | Default | Description |
|---|---|---|---|
src |
string |
— | Image source URL or path |
alt |
string |
— | Alternative text |
title |
string \| null |
null |
Optional title |
attributes |
string \| null |
null |
Element attributes |
DjotLink¶
Link element in Djot.
| Field | Type | Default | Description |
|---|---|---|---|
url |
string |
— | Link URL |
text |
string |
— | Link text content |
title |
string \| null |
null |
Optional title |
attributes |
string \| null |
null |
Element attributes |
DocumentExtractor¶
Trait for document extractor plugins.
Implement this trait to add support for new document formats or to override built-in extraction behavior with custom logic.
Return Type¶
Extractors return InternalDocument, a flat intermediate representation.
The pipeline converts this into the public ExtractionResult via the
derivation step.
Priority System¶
When multiple extractors support the same MIME type, the registry selects the extractor with the highest priority value. Use this to:
- Override built-in extractors (priority > 50)
- Provide fallback extractors (priority < 50)
- Implement specialized extractors for specific use cases
Default priority is 50.
Thread Safety¶
Extractors must be thread-safe (Send + Sync) to support concurrent extraction.
Methods¶
extractBytes()¶
Extract content from a byte array.
This is the core extraction method that processes in-memory document data.
Returns:
An InternalDocument containing the extracted elements, metadata, and tables.
The pipeline will convert this into the public ExtractionResult.
Errors:
KreuzbergError.Parsing- Document parsing failedKreuzbergError.Validation- Invalid document structureKreuzbergError.Io- I/O errors (these always bubble up)KreuzbergError.MissingDependency- Required dependency not available
Signature:
extractFile()¶
Extract content from a file.
Default implementation reads the file and calls extract_bytes.
Override for custom file handling, streaming, or memory optimizations.
Returns:
An InternalDocument containing the extracted elements, metadata, and tables.
Errors:
Same as extract_bytes, plus file I/O errors.
Signature:
supportedMimeTypes()¶
Get the list of MIME types supported by this extractor.
Can include exact MIME types and prefix patterns:
- Exact:
"application/pdf","text/plain" - Prefix:
"image/*"(matches any image type)
Returns:
A slice of MIME type strings.
Signature:
priority()¶
Get the priority of this extractor.
Higher priority extractors are preferred when multiple extractors support the same MIME type.
Priority Guidelines¶
- 0-25: Fallback/low-quality extractors
- 26-49: Alternative extractors
- 50: Default priority (built-in extractors)
- 51-75: Premium/enhanced extractors
- 76-100: Specialized/high-priority extractors
Returns:
Priority value (default: 50)
Signature:
canHandle()¶
Optional: Check if this extractor can handle a specific file.
Allows for more sophisticated detection beyond MIME types.
Defaults to true (rely on MIME type matching).
Returns:
true if the extractor can handle this file, false otherwise.
Signature:
asSyncExtractor()¶
Attempt to get a reference to this extractor as a SyncExtractor.
Returns None if the extractor doesn't support synchronous extraction. This is used for WASM and other sync-only environments.
Signature:
DocumentNode¶
A single node in the document tree.
Each node has deterministic id, typed content, optional parent/children
for tree structure, and metadata like page number, bounding box, and content layer.
| Field | Type | Default | Description |
|---|---|---|---|
id |
string |
— | Deterministic identifier (hash of content + position). |
content |
NodeContent |
— | Node content — tagged enum, type-specific data only. |
parent |
number \| null |
null |
Parent node index (null = root-level node). |
children |
Array<number> |
/* serde(default) */ |
Child node indices in reading order. |
contentLayer |
ContentLayer |
/* serde(default) */ |
Content layer classification. |
page |
number \| null |
null |
Page number where this node starts (1-indexed). |
pageEnd |
number \| null |
null |
Page number where this node ends (for multi-page tables/sections). |
bbox |
BoundingBox \| null |
null |
Bounding box in document coordinates. |
annotations |
Array<TextAnnotation> |
/* serde(default) */ |
Inline annotations (formatting, links) on this node's text content. Only meaningful for text-carrying nodes; empty for containers. |
attributes |
Record<string, string> \| null |
null |
Format-specific key-value attributes. Extensible bag for miscellaneous data without a dedicated typed field: CSS classes, LaTeX environment names, Excel cell formulas, slide layout names, etc. |
DocumentRelationship¶
A resolved relationship between two nodes in the document tree.
| Field | Type | Default | Description |
|---|---|---|---|
source |
number |
— | Source node index (the referencing node). |
target |
number |
— | Target node index (the referenced node). |
kind |
RelationshipKind |
— | Semantic kind of the relationship. |
DocumentStructure¶
Top-level structured document representation.
A flat array of nodes with index-based parent/child references forming a tree.
Root-level nodes have parent: None. Use body_roots() and furniture_roots()
to iterate over top-level content by layer.
Validation¶
Call validate() after construction to verify all node indices are in bounds
and parent-child relationships are bidirectionally consistent.
| Field | Type | Default | Description |
|---|---|---|---|
nodes |
Array<DocumentNode> |
[] |
All nodes in document/reading order. |
sourceFormat |
string \| null |
null |
Origin format identifier (e.g. "docx", "pptx", "html", "pdf"). Allows renderers to apply format-aware heuristics when converting the document tree to output formats. |
relationships |
Array<DocumentRelationship> |
[] |
Resolved relationships between nodes (footnote refs, citations, anchor links, etc.). Populated during derivation from the internal document representation. Empty when no relationships are detected. |
nodeTypes |
Array<string> |
[] |
Sorted, deduplicated list of node type names present in this document. Each value is the snake_case node_type tag of the corresponding NodeContent variant (e.g. "paragraph", "heading", "table", …). Computed from nodes via DocumentStructure.finalize_node_types. Empty until that method is called (internal construction paths call it at the end of derivation). |
Methods¶
finalizeNodeTypes()¶
Compute and populate the node_types field from the current nodes.
Call this after all nodes have been added to the structure. Internal construction paths (builder, derivation) call this automatically.
Signature:
isEmpty()¶
Check if the document structure is empty.
Signature:
default()¶
Signature:
DocxAppProperties¶
Application properties from docProps/app.xml for DOCX
Contains Word-specific document statistics and metadata.
| Field | Type | Default | Description |
|---|---|---|---|
application |
string \| null |
null |
Application name (e.g., "Microsoft Office Word") |
appVersion |
string \| null |
null |
Application version |
template |
string \| null |
null |
Template filename |
totalTime |
number \| null |
null |
Total editing time in minutes |
pages |
number \| null |
null |
Number of pages |
words |
number \| null |
null |
Number of words |
characters |
number \| null |
null |
Number of characters (excluding spaces) |
charactersWithSpaces |
number \| null |
null |
Number of characters (including spaces) |
lines |
number \| null |
null |
Number of lines |
paragraphs |
number \| null |
null |
Number of paragraphs |
company |
string \| null |
null |
Company name |
docSecurity |
number \| null |
null |
Document security level |
scaleCrop |
boolean \| null |
null |
Scale crop flag |
linksUpToDate |
boolean \| null |
null |
Links up to date flag |
sharedDoc |
boolean \| null |
null |
Shared document flag |
hyperlinksChanged |
boolean \| null |
null |
Hyperlinks changed flag |
DocxMetadata¶
Word document metadata.
Extracted from DOCX files using shared Office Open XML metadata extraction.
Integrates with office_metadata module for core/app/custom properties.
| Field | Type | Default | Description |
|---|---|---|---|
coreProperties |
CoreProperties \| null |
null |
Core properties from docProps/core.xml (Dublin Core metadata) Contains title, creator, subject, keywords, dates, etc. Shared format across DOCX/PPTX/XLSX documents. |
appProperties |
DocxAppProperties \| null |
null |
Application properties from docProps/app.xml (Word-specific statistics) Contains word count, page count, paragraph count, editing time, etc. DOCX-specific variant of Office application properties. |
customProperties |
Record<string, unknown> \| null |
{} |
Custom properties from docProps/custom.xml (user-defined properties) Contains key-value pairs defined by users or applications. Values can be strings, numbers, booleans, or dates. |
Element¶
Semantic element extracted from document.
Represents a logical unit of content with semantic classification, unique identifier, and metadata for tracking origin and position.
| Field | Type | Default | Description |
|---|---|---|---|
elementId |
string |
— | Unique element identifier |
elementType |
ElementType |
— | Semantic type of this element |
text |
string |
— | Text content of the element |
metadata |
ElementMetadata |
— | Metadata about the element |
ElementMetadata¶
Metadata for a semantic element.
| Field | Type | Default | Description |
|---|---|---|---|
pageNumber |
number \| null |
null |
Page number (1-indexed) |
filename |
string \| null |
null |
Source filename or document name |
coordinates |
BoundingBox \| null |
null |
Bounding box coordinates if available |
elementIndex |
number \| null |
null |
Position index in the element sequence |
additional |
Record<string, string> |
— | Additional custom metadata |
EmailAttachment¶
Email attachment representation.
Contains metadata and optionally the content of an email attachment.
| Field | Type | Default | Description |
|---|---|---|---|
name |
string \| null |
null |
Attachment name (from Content-Disposition header) |
filename |
string \| null |
null |
Filename of the attachment |
mimeType |
string \| null |
null |
MIME type of the attachment |
size |
number \| null |
null |
Size in bytes |
isImage |
boolean |
— | Whether this attachment is an image |
data |
Buffer \| null |
null |
Attachment data (if extracted). Uses bytes.Bytes for cheap cloning of large buffers. |
EmailConfig¶
Configuration for email extraction.
| Field | Type | Default | Description |
|---|---|---|---|
msgFallbackCodepage |
number \| null |
null |
Windows codepage number to use when an MSG file contains no codepage property. Defaults to null, which falls back to windows-1252. If an unrecognized or invalid codepage number is supplied (including 0), the behavior silently falls back to windows-1252 — the same as when the MSG file itself contains an unrecognized codepage. No error or warning is emitted. Users should verify output when supplying unusual values. Common values: - 1250: Central European (Polish, Czech, Hungarian, etc.) - 1251: Cyrillic (Russian, Ukrainian, Bulgarian, etc.) - 1252: Western European (default) - 1253: Greek - 1254: Turkish - 1255: Hebrew - 1256: Arabic - 932: Japanese (Shift-JIS) - 936: Simplified Chinese (GBK) |
EmailExtractionResult¶
Email extraction result.
Complete representation of an extracted email message (.eml or .msg) including headers, body content, and attachments.
| Field | Type | Default | Description |
|---|---|---|---|
subject |
string \| null |
null |
Email subject line |
fromEmail |
string \| null |
null |
Sender email address |
toEmails |
Array<string> |
— | Primary recipient email addresses |
ccEmails |
Array<string> |
— | CC recipient email addresses |
bccEmails |
Array<string> |
— | BCC recipient email addresses |
date |
string \| null |
null |
Email date/timestamp |
messageId |
string \| null |
null |
Message-ID header value |
plainText |
string \| null |
null |
Plain text version of the email body |
htmlContent |
string \| null |
null |
HTML version of the email body |
content |
string |
— | Cleaned/processed text content. Aliased as cleaned_text for back-compat. |
attachments |
Array<EmailAttachment> |
— | List of email attachments |
metadata |
Record<string, string> |
— | Additional email headers and metadata |
EmailMetadata¶
Email metadata extracted from .eml and .msg files.
Includes sender/recipient information, message ID, and attachment list.
| Field | Type | Default | Description |
|---|---|---|---|
fromEmail |
string \| null |
null |
Sender's email address |
fromName |
string \| null |
null |
Sender's display name |
toEmails |
Array<string> |
[] |
Primary recipients |
ccEmails |
Array<string> |
[] |
CC recipients |
bccEmails |
Array<string> |
[] |
BCC recipients |
messageId |
string \| null |
null |
Message-ID header value |
attachments |
Array<string> |
[] |
List of attachment filenames |
EmbeddedFile¶
Embedded file descriptor extracted from the PDF name tree.
| Field | Type | Default | Description |
|---|---|---|---|
name |
string |
— | The filename as stored in the PDF name tree. |
data |
Buffer |
— | Raw file bytes from the embedded stream. |
mimeType |
string \| null |
null |
MIME type if specified in the filespec, otherwise null. |
EmbeddingBackend¶
Trait for in-process embedding backend plugins.
Async to match the convention used by OcrBackend,
DocumentExtractor, and PostProcessor.
Host-language bridges (PyO3, napi-rs, Rustler, extendr, magnus, ext-php-rs,
C FFI, etc.) wrap their synchronous host callables in spawn_blocking or the
equivalent to satisfy the async signature.
Thread safety¶
Backends must be Send + Sync + 'static. They are stored in
Arc<dyn EmbeddingBackend> and called concurrently from kreuzberg's chunking
pipeline. If the backend's underlying model isn't thread-safe, the backend
itself must serialize access internally (e.g. via Mutex<Inner>).
Contract¶
-
embed(texts)MUST return exactlytexts.len()vectors, each of lengthself.dimensions(). The dispatcher inembed_textsvalidates this before returning to downstream consumers; a non-conforming backend surfaces as aKreuzbergError.Validation, not a panic. -
embedmay be called from any thread. Its future must beSend(enforced byasync_traitwhen#[async_trait]is used on non-WASM targets). -
dimensions()is called exactly once at registration, immediately afterinitialize()succeeds. The returned value is cached by the registry and used for all subsequent shape validation. Lazy-loading implementations can defer model loading intoinitialize()and report the real dimension afterwards. Later mutations of the backend's reported dimension are not observed by kreuzberg — implementations that need to change dimension must unregister and re-register. -
shutdown()(inherited fromPlugin) may be invoked concurrently with an in-flightembed()call. Implementations must tolerate this — e.g. by letting in-flight calls finish using resources held via theArc<dyn EmbeddingBackend>reference, and only releasing shared state that isn't needed byembed.
Runtime¶
The synchronous embed_texts entry uses
tokio.task.block_in_place to await the trait's async embed, which
requires a multi-thread tokio runtime. Callers running inside a
current_thread runtime (e.g. #[tokio.test] without flavor = "multi_thread",
or tokio.runtime.Builder.new_current_thread()) must use
embed_texts_async instead, which awaits directly without
block_in_place.
Methods¶
dimensions()¶
Embedding vector dimension. Must be > 0 and must match the length of
every vector returned by embed.
Signature:
embed()¶
Embed a batch of texts, returning one vector per input in order.
Errors:
Implementations should return Plugin for
backend-specific failures. The dispatcher layers its own validation
(length, per-vector dimension) on top.
Signature:
EmbeddingPreset¶
Preset configurations for common RAG use cases.
Each preset combines chunk size, overlap, and embedding model to provide an optimized configuration for specific scenarios.
All string fields are owned String for FFI compatibility — instances
are safe to clone and pass across language boundaries.
| Field | Type | Default | Description |
|---|---|---|---|
name |
string |
— | The name |
chunkSize |
number |
— | Chunk size |
overlap |
number |
— | Overlap |
modelRepo |
string |
— | HuggingFace repository name for the model. |
pooling |
string |
— | Pooling strategy: "cls" or "mean". |
modelFile |
string |
— | Path to the ONNX model file within the repo. |
dimensions |
number |
— | Dimensions |
description |
string |
— | Human-readable description |
EpubMetadata¶
EPUB metadata (Dublin Core extensions).
| Field | Type | Default | Description |
|---|---|---|---|
coverage |
string \| null |
null |
Coverage |
dcFormat |
string \| null |
null |
Dc format |
relation |
string \| null |
null |
Relation |
source |
string \| null |
null |
Source |
dcType |
string \| null |
null |
Dc type |
coverImage |
string \| null |
null |
Cover image |
ErrorMetadata¶
Error metadata (for batch operations).
| Field | Type | Default | Description |
|---|---|---|---|
errorType |
string |
— | Error type |
message |
string |
— | Message |
ExcelMetadata¶
Excel/spreadsheet format metadata.
Identifies the document as a spreadsheet source via the FormatMetadata.Excel
discriminant. Sheet count and sheet names are stored inside this struct.
| Field | Type | Default | Description |
|---|---|---|---|
sheetCount |
number \| null |
null |
Number of sheets in the workbook. |
sheetNames |
Array<string> \| null |
[] |
Names of all sheets in the workbook. |
ExcelSheet¶
Single Excel worksheet.
Represents one sheet from an Excel workbook with its content converted to Markdown format and dimensional statistics.
| Field | Type | Default | Description |
|---|---|---|---|
name |
string |
— | Sheet name as it appears in Excel |
markdown |
string |
— | Sheet content converted to Markdown tables |
rowCount |
number |
— | Number of rows |
colCount |
number |
— | Number of columns |
cellCount |
number |
— | Total number of non-empty cells |
tableCells |
Array<Array<string>> \| null |
null |
Pre-extracted table cells (2D vector of cell values) Populated during markdown generation to avoid re-parsing markdown. None for empty sheets. |
ExcelWorkbook¶
Excel workbook representation.
Contains all sheets from an Excel file (.xlsx, .xls, etc.) with extracted content and metadata.
| Field | Type | Default | Description |
|---|---|---|---|
sheets |
Array<ExcelSheet> |
— | All sheets in the workbook |
metadata |
Record<string, string> |
— | Workbook-level metadata (author, creation date, etc.) |
ExtractedImage¶
Extracted image from a document.
Contains raw image data, metadata, and optional nested OCR results. Raw bytes allow cross-language compatibility - users can convert to PIL.Image (Python), Sharp (Node.js), or other formats as needed.
| Field | Type | Default | Description |
|---|---|---|---|
data |
Buffer |
— | Raw image data (PNG, JPEG, WebP, etc. bytes). Uses bytes.Bytes for cheap cloning of large buffers. |
format |
string |
— | Image format (e.g., "jpeg", "png", "webp") Uses Cow<'static, str> to avoid allocation for static literals. |
imageIndex |
number |
— | Zero-indexed position of this image in the document/page |
pageNumber |
number \| null |
null |
Page/slide number where image was found (1-indexed) |
width |
number \| null |
null |
Image width in pixels |
height |
number \| null |
null |
Image height in pixels |
colorspace |
string \| null |
null |
Colorspace information (e.g., "RGB", "CMYK", "Gray") |
bitsPerComponent |
number \| null |
null |
Bits per color component (e.g., 8, 16) |
isMask |
boolean |
/* serde(default) */ |
Whether this image is a mask image |
description |
string \| null |
null |
Optional description of the image |
ocrResult |
ExtractionResult \| null |
null |
Nested OCR extraction result (if image was OCRed) When OCR is performed on this image, the result is embedded here rather than in a separate collection, making the relationship explicit. |
boundingBox |
BoundingBox \| null |
/* serde(default) */ |
Bounding box of the image on the page (PDF coordinates: x0=left, y0=bottom, x1=right, y1=top). Only populated for PDF-extracted images when position data is available from the PDF extractor. |
sourcePath |
string \| null |
/* serde(default) */ |
Original source path of the image within the document archive (e.g., "media/image1.png" in DOCX). Used for rendering image references when the binary data is not extracted. |
imageKind |
ImageKind \| null |
/* serde(default) */ |
Heuristic classification of what this image likely depicts. null if classification was disabled or inconclusive. |
kindConfidence |
number \| null |
/* serde(default) */ |
Confidence score for image_kind, in the range 0.0 to 1.0. |
clusterId |
number \| null |
/* serde(default) */ |
Identifier shared across images that form a single logical figure (e.g. all raster tiles of one technical drawing). null for singletons. |
ExtractedImageMetadata¶
Image metadata extracted from an image file.
| Field | Type | Default | Description |
|---|---|---|---|
width |
number |
— | Image width in pixels |
height |
number |
— | Image height in pixels |
format |
string |
— | Image format (e.g., "PNG", "JPEG") |
exifData |
Record<string, string> |
— | EXIF data if available |
ExtractionConfig¶
Main extraction configuration.
This struct contains all configuration options for the extraction process. It can be loaded from TOML, YAML, or JSON files, or created programmatically.
| Field | Type | Default | Description |
|---|---|---|---|
useCache |
boolean |
true |
Enable caching of extraction results |
enableQualityProcessing |
boolean |
true |
Enable quality post-processing |
ocr |
OcrConfig \| null |
null |
OCR configuration (None = OCR disabled) |
forceOcr |
boolean |
false |
Force OCR even for searchable PDFs |
forceOcrPages |
Array<number> \| null |
null |
Force OCR on specific pages only (1-indexed page numbers, must be >= 1). When set, only the listed pages are OCR'd regardless of text layer quality. Unlisted pages use native text extraction. Ignored when force_ocr is true. Only applies to PDF documents. Duplicates are automatically deduplicated. An ocr config is recommended for backend/language selection; defaults are used if absent. |
disableOcr |
boolean |
false |
Disable OCR entirely, even for images. When true, OCR is skipped for all document types. Images return metadata only (dimensions, format, EXIF) without text extraction. PDFs use only native text extraction without OCR fallback. Cannot be true simultaneously with force_ocr. Added in v4.7.0. |
chunking |
ChunkingConfig \| null |
null |
Text chunking configuration (None = chunking disabled) |
contentFilter |
ContentFilterConfig \| null |
null |
Content filtering configuration (None = use extractor defaults). Controls whether document "furniture" (headers, footers, watermarks, repeating text) is included in or stripped from extraction results. See ContentFilterConfig for per-field documentation. |
images |
ImageExtractionConfig \| null |
null |
Image extraction configuration (None = no image extraction) |
pdfOptions |
PdfConfig \| null |
null |
PDF-specific options (None = use defaults) |
tokenReduction |
TokenReductionOptions \| null |
null |
Token reduction configuration (None = no token reduction) |
languageDetection |
LanguageDetectionConfig \| null |
null |
Language detection configuration (None = no language detection) |
pages |
PageConfig \| null |
null |
Page extraction configuration (None = no page tracking) |
keywords |
KeywordConfig \| null |
null |
Keyword extraction configuration (None = no keyword extraction) |
postprocessor |
PostProcessorConfig \| null |
null |
Post-processor configuration (None = use defaults) |
htmlOptions |
string \| null |
null |
HTML to Markdown conversion options (None = use defaults) Configure how HTML documents are converted to Markdown, including heading styles, list formatting, code block styles, and preprocessing options. |
htmlOutput |
HtmlOutputConfig \| null |
null |
Styled HTML output configuration. When set alongside output_format = OutputFormat.Html, the extraction pipeline uses StyledHtmlRenderer which emits stable kb-* CSS class hooks on every structural element and optionally embeds theme CSS or user-supplied CSS in a <style> block. When null, the existing plain comrak-based HTML renderer is used. |
extractionTimeoutSecs |
number \| null |
null |
Default per-file timeout in seconds for batch extraction. When set, each file in a batch will be canceled after this duration unless overridden by FileExtractionConfig.timeout_secs. null means no timeout (unbounded extraction time). |
maxConcurrentExtractions |
number \| null |
null |
Maximum concurrent extractions in batch operations (None = (num_cpus × 1.5).ceil()). Limits parallelism to prevent resource exhaustion when processing large batches. Defaults to (num_cpus × 1.5).ceil() when not set. |
resultFormat |
ResultFormat |
ResultFormat.Unified |
Result structure format Controls whether results are returned in unified format (default) with all content in the content field, or element-based format with semantic elements (for Unstructured-compatible output). |
securityLimits |
SecurityLimits \| null |
null |
Security limits for archive extraction. Controls maximum archive size, compression ratio, file count, and other security thresholds to prevent decompression bomb attacks. Also caps nesting depth, iteration count, entity / token length, total content size, and table cell count for every extraction path that ingests user-controlled bytes. When null, default limits are used. |
outputFormat |
OutputFormat |
OutputFormat.Plain |
Content text format (default: Plain). Controls the format of the extracted content: - Plain: Raw extracted text (default) - Markdown: Markdown formatted output - Djot: Djot markup format (requires djot feature) - Html: HTML formatted output When set to a structured format, extraction results will include formatted output. The formatted_content field may be populated when format conversion is applied. |
layout |
LayoutDetectionConfig \| null |
null |
Layout detection configuration (None = layout detection disabled). When set, PDF pages and images are analyzed for document structure (headings, code, formulas, tables, figures, etc.) using RT-DETR models via ONNX Runtime. For PDFs, layout hints override paragraph classification in the markdown pipeline. For images, per-region OCR is performed with markdown formatting based on detected layout classes. Requires the layout-detection feature to run inference; the field is present whenever the layout-types feature is active (which includes layout-detection as well as the no-ORT target groups). |
useLayoutForMarkdown |
boolean |
false |
Run layout detection on the non-OCR PDF markdown path. When true and layout is Some(_), layout regions inform heading, table, list, and figure detection in the structure pipeline that would otherwise rely on font-clustering heuristics alone. Significantly improves SF1 (structural F1) at the cost of inference latency (~150-300ms/page CPU, ~20-50ms/page GPU). Default: false. Requires the layout-detection feature. |
includeDocumentStructure |
boolean |
false |
Enable structured document tree output. When true, populates the document field on ExtractionResult with a hierarchical DocumentStructure containing heading-driven section nesting, table grids, content layer classification, and inline annotations. Independent of result_format — can be combined with Unified or ElementBased. |
acceleration |
AccelerationConfig \| null |
null |
Hardware acceleration configuration for ONNX Runtime models. Controls execution provider selection for layout detection and embedding models. When null, uses platform defaults (CoreML on macOS, CUDA on Linux, CPU on Windows). |
cacheNamespace |
string \| null |
null |
Cache namespace for tenant isolation. When set, cache entries are stored under {cache_dir}/{namespace}/. Must be alphanumeric, hyphens, or underscores only (max 64 chars). Different namespaces have isolated cache spaces on the same filesystem. |
cacheTtlSecs |
number \| null |
null |
Per-request cache TTL in seconds. Overrides the global max_age_days for this specific extraction. When 0, caching is completely skipped (no read or write). When null, the global TTL applies. |
email |
EmailConfig \| null |
null |
Email extraction configuration (None = use defaults). Currently supports configuring the fallback codepage for MSG files that do not specify one. See EmailConfig for details. |
concurrency |
string \| null |
null |
Concurrency limits for constrained environments (None = use defaults). Controls Rayon thread pool size, ONNX Runtime intra-op threads, and (when max_concurrent_extractions is unset) the batch concurrency semaphore. See ConcurrencyConfig for details. |
maxArchiveDepth |
number |
— | Maximum recursion depth for archive extraction (default: 3). Set to 0 to disable recursive extraction (legacy behavior). |
treeSitter |
TreeSitterConfig \| null |
null |
Tree-sitter language pack configuration (None = tree-sitter disabled). When set, enables code file extraction using tree-sitter parsers. Controls grammar download behavior and code analysis options. |
structuredExtraction |
StructuredExtractionConfig \| null |
null |
Structured extraction via LLM (None = disabled). When set, the extracted document content is sent to an LLM with the provided JSON schema. The structured response is stored in ExtractionResult.structured_output. |
cancelToken |
string \| null |
null |
Cancellation token for this extraction (None = no external cancellation). Pass a CancellationToken clone here and call CancellationToken.cancel from another thread / task to abort the extraction in progress. The extractor checks the token at safe checkpoints (before lock acquisition, between pages, between batch items) and returns KreuzbergError.Cancelled when set. The field is excluded from serialization because CancellationToken is a runtime handle, not a configuration value. |
Methods¶
default()¶
Signature:
needsImageProcessing()¶
Check if image processing is needed by examining OCR and image extraction settings.
Returns true if either OCR is enabled or image extraction is configured,
indicating that image decompression and processing should occur.
Returns false if both are disabled, allowing optimization to skip unnecessary
image decompression for text-only extraction workflows.
Optimization Impact¶
For text-only extractions (no OCR, no image extraction), skipping image decompression can improve CPU utilization by 5-10% by avoiding wasteful image I/O and processing when results won't be used.
Signature:
ExtractionResult¶
General extraction result used by the core extraction API.
This is the main result type returned by all extraction functions.
| Field | Type | Default | Description |
|---|---|---|---|
content |
string |
— | The extracted text content |
mimeType |
string |
— | The detected MIME type |
metadata |
Metadata |
— | Document metadata |
extractionMethod |
ExtractionMethod \| null |
null |
Extraction strategy used to produce the returned text. Populated when the extractor can reliably distinguish native text extraction, OCR-only extraction, or mixed native/OCR output. |
tables |
Array<Table> |
[] |
Tables extracted from the document |
detectedLanguages |
Array<string> \| null |
[] |
Detected languages |
chunks |
Array<Chunk> \| null |
[] |
Text chunks when chunking is enabled. When chunking configuration is provided, the content is split into overlapping chunks for efficient processing. Each chunk contains the text, optional embeddings (if enabled), and metadata about its position. |
images |
Array<ExtractedImage> \| null |
[] |
Extracted images from the document. When image extraction is enabled via ImageExtractionConfig, this field contains all images found in the document with their raw data and metadata. Each image may optionally contain a nested ocr_result if OCR was performed. |
pages |
Array<PageContent> \| null |
[] |
Per-page content when page extraction is enabled. When page extraction is configured, the document is split into per-page content with tables and images mapped to their respective pages. |
elements |
Array<Element> \| null |
[] |
Semantic elements when element-based result format is enabled. When result_format is set to ElementBased, this field contains semantic elements with type classification, unique identifiers, and metadata for Unstructured-compatible element-based processing. |
djotContent |
DjotContent \| null |
null |
Rich Djot content structure (when extracting Djot documents). When extracting Djot documents with structured extraction enabled, this field contains the full semantic structure including: - Block-level elements with nesting - Inline formatting with attributes - Links, images, footnotes - Math expressions - Complete attribute information The content field still contains plain text for backward compatibility. Always null for non-Djot documents. |
ocrElements |
Array<OcrElement> \| null |
[] |
OCR elements with full spatial and confidence metadata. When OCR is performed with element extraction enabled, this field contains the structured representation of detected text including: - Bounding geometry (rectangles or quadrilaterals) - Confidence scores (detection and recognition) - Rotation information - Hierarchical relationships (Tesseract only) This field preserves all metadata that would otherwise be lost when converting to plain text or markdown output formats. Only populated when OcrElementConfig.include_elements is true. |
document |
DocumentStructure \| null |
null |
Structured document tree (when document structure extraction is enabled). When include_document_structure is true in ExtractionConfig, this field contains the full hierarchical representation of the document including: - Heading-driven section nesting - Table grids with cell-level metadata - Content layer classification (body, header, footer, footnote) - Inline text annotations (formatting, links) - Bounding boxes and page numbers Independent of result_format — can be combined with Unified or ElementBased. |
extractedKeywords |
Array<Keyword> \| null |
[] |
Extracted keywords when keyword extraction is enabled. When keyword extraction (RAKE or YAKE) is configured, this field contains the extracted keywords with scores, algorithm info, and position data. Previously stored in metadata.additional["keywords"]. |
qualityScore |
number \| null |
null |
Document quality score from quality analysis. A value between 0.0 and 1.0 indicating the overall text quality. Previously stored in metadata.additional["quality_score"]. |
processingWarnings |
Array<ProcessingWarning> |
[] |
Non-fatal warnings collected during processing pipeline stages. Captures errors from optional pipeline features (embedding, chunking, language detection, output formatting) that don't prevent extraction but may indicate degraded results. Previously stored as individual keys in metadata.additional. |
annotations |
Array<PdfAnnotation> \| null |
[] |
PDF annotations extracted from the document. When annotation extraction is enabled via PdfConfig.extract_annotations, this field contains text notes, highlights, links, stamps, and other annotations found in PDF documents. |
children |
Array<ArchiveEntry> \| null |
[] |
Nested extraction results from archive contents. When extracting archives, each processable file inside produces its own full extraction result. Set to null for non-archive formats. Use max_archive_depth in config to control recursion depth. |
uris |
Array<Uri> \| null |
[] |
URIs/links discovered during document extraction. Contains hyperlinks, image references, citations, email addresses, and other URI-like references found in the document. Always extracted when present in the source document. |
structuredOutput |
unknown \| null |
null |
Structured extraction output from LLM-based JSON schema extraction. When structured_extraction is configured in ExtractionConfig, the extracted document content is sent to a VLM with the provided JSON schema. The response is parsed and stored here as a JSON value matching the schema. |
codeIntelligence |
unknown \| null |
null |
Code intelligence results from tree-sitter analysis. Populated when extracting source code files with the tree-sitter feature. Contains metrics, structural analysis, imports/exports, comments, docstrings, symbols, diagnostics, and optionally chunked code segments. Stored as an opaque JSON value so that all language bindings (Go, Java, C#, …) can deserialize it as a raw JSON object rather than a typed struct. The underlying type is tree_sitter_language_pack.ProcessResult. |
llmUsage |
Array<LlmUsage> \| null |
[] |
LLM token usage and cost data for all LLM calls made during this extraction. Contains one entry per LLM call. Multiple entries are produced when VLM OCR, structured extraction, or LLM embeddings run during the same extraction. null when no LLM was used. |
formattedContent |
string \| null |
null |
Pre-rendered content in the requested output format. Populated during derive_extraction_result before tree derivation consumes element data. apply_output_format swaps this into content at the end of the pipeline, after post-processors have operated on plain text. |
ocrInternalDocument |
string \| null |
null |
Structured hOCR document for the OCR+layout pipeline. When tesseract produces hOCR output, the parsed InternalDocument carries paragraph structure with bounding boxes and confidence scores. The layout classification step enriches these elements before final rendering. |
Methods¶
fromOcr()¶
Convert from an OCR result.
Signature:
FictionBookMetadata¶
FictionBook (FB2) metadata.
| Field | Type | Default | Description |
|---|---|---|---|
genres |
Array<string> |
[] |
Genres |
sequences |
Array<string> |
[] |
Sequences |
annotation |
string \| null |
null |
Annotation |
FileExtractionConfig¶
Per-file extraction configuration overrides for batch processing.
All fields are Option<T> — null means "use the batch-level default."
This type is used with batch_extract_files and
batch_extract_bytes to allow heterogeneous
extraction settings within a single batch.
Excluded Fields¶
The following ExtractionConfig fields are batch-level only and
cannot be overridden per file:
max_concurrent_extractions— controls batch parallelismuse_cache— global caching policyacceleration— shared ONNX execution providersecurity_limits— global archive security policy
| Field | Type | Default | Description |
|---|---|---|---|
enableQualityProcessing |
boolean \| null |
null |
Override quality post-processing for this file. |
ocr |
OcrConfig \| null |
null |
Override OCR configuration for this file (None in the Option = use batch default). |
forceOcr |
boolean \| null |
null |
Override force OCR for this file. |
forceOcrPages |
Array<number> \| null |
[] |
Override force OCR pages for this file (1-indexed page numbers). |
disableOcr |
boolean \| null |
null |
Override disable OCR for this file. |
chunking |
ChunkingConfig \| null |
null |
Override chunking configuration for this file. |
contentFilter |
ContentFilterConfig \| null |
null |
Override content filtering configuration for this file. |
images |
ImageExtractionConfig \| null |
null |
Override image extraction configuration for this file. |
pdfOptions |
PdfConfig \| null |
null |
Override PDF options for this file. |
tokenReduction |
TokenReductionOptions \| null |
null |
Override token reduction for this file. |
languageDetection |
LanguageDetectionConfig \| null |
null |
Override language detection for this file. |
pages |
PageConfig \| null |
null |
Override page extraction for this file. |
keywords |
KeywordConfig \| null |
null |
Override keyword extraction for this file. |
postprocessor |
PostProcessorConfig \| null |
null |
Override post-processor for this file. |
htmlOptions |
string \| null |
null |
Override HTML conversion options for this file. |
resultFormat |
ResultFormat \| null |
null |
Override result format for this file. |
outputFormat |
OutputFormat \| null |
null |
Override output content format for this file. |
includeDocumentStructure |
boolean \| null |
null |
Override document structure output for this file. |
layout |
LayoutDetectionConfig \| null |
null |
Override layout detection for this file. |
timeoutSecs |
number \| null |
null |
Override per-file extraction timeout in seconds. When set, the extraction for this file will be canceled after the specified duration. A timed-out file produces an error result without affecting other files in the batch. |
treeSitter |
TreeSitterConfig \| null |
null |
Override tree-sitter configuration for this file. |
structuredExtraction |
StructuredExtractionConfig \| null |
null |
Override structured extraction configuration for this file. When set, enables LLM-based structured extraction with a JSON schema for this specific file. The extracted content is sent to a VLM/LLM and the response is parsed according to the provided schema. |
Footnote¶
Footnote in Djot.
| Field | Type | Default | Description |
|---|---|---|---|
label |
string |
— | Footnote label |
content |
Array<FormattedBlock> |
— | Footnote content blocks |
FormattedBlock¶
Block-level element in a Djot document.
Represents structural elements like headings, paragraphs, lists, code blocks, etc.
| Field | Type | Default | Description |
|---|---|---|---|
blockType |
BlockType |
— | Type of block element |
level |
number \| null |
null |
Heading level (1-6) for headings, or nesting level for lists |
inlineContent |
Array<InlineElement> |
— | Inline content within the block |
attributes |
string \| null |
null |
Element attributes (classes, IDs, key-value pairs) |
language |
string \| null |
null |
Language identifier for code blocks |
code |
string \| null |
null |
Raw code content for code blocks |
children |
Array<FormattedBlock> |
/* serde(default) */ |
Nested blocks for containers (blockquotes, list items, divs) |
GridCell¶
Individual grid cell with position and span metadata.
| Field | Type | Default | Description |
|---|---|---|---|
content |
string |
— | Cell text content. |
row |
number |
— | Zero-indexed row position. |
col |
number |
— | Zero-indexed column position. |
rowSpan |
number |
/* serde(default) */ |
Number of rows this cell spans. |
colSpan |
number |
/* serde(default) */ |
Number of columns this cell spans. |
isHeader |
boolean |
/* serde(default) */ |
Whether this is a header cell. |
bbox |
BoundingBox \| null |
null |
Bounding box for this cell (if available). |
HeaderMetadata¶
Header/heading element metadata.
| Field | Type | Default | Description |
|---|---|---|---|
level |
number |
— | Header level: 1 (h1) through 6 (h6) |
text |
string |
— | Normalized text content of the header |
id |
string \| null |
null |
HTML id attribute if present |
depth |
number |
— | Document tree depth at the header element |
htmlOffset |
number |
— | Byte offset in original HTML document |
HeadingContext¶
Heading context for a chunk within a Markdown document.
Contains the heading hierarchy from document root to this chunk's section.
| Field | Type | Default | Description |
|---|---|---|---|
headings |
Array<HeadingLevel> |
— | The heading hierarchy from document root to this chunk's section. Index 0 is the outermost (h1), last element is the most specific. |
HeadingLevel¶
A single heading in the hierarchy.
| Field | Type | Default | Description |
|---|---|---|---|
level |
number |
— | Heading depth (1 = h1, 2 = h2, etc.) |
text |
string |
— | The text content of the heading. |
HierarchicalBlock¶
A text block with hierarchy level assignment.
Represents a block of text with semantic heading information extracted from font size clustering and hierarchical analysis.
| Field | Type | Default | Description |
|---|---|---|---|
text |
string |
— | The text content of this block |
fontSize |
number |
— | The font size of the text in this block |
level |
string |
— | The hierarchy level of this block (H1-H6 or Body) Levels correspond to HTML heading tags: - "h1": Top-level heading - "h2": Secondary heading - "h3": Tertiary heading - "h4": Quaternary heading - "h5": Quinary heading - "h6": Senary heading - "body": Body text (no heading level) |
bbox |
Array<number> \| null |
null |
Bounding box information for the block Contains coordinates as (left, top, right, bottom) in PDF units. |
HierarchyConfig¶
Hierarchy extraction configuration for PDF text structure analysis.
Enables extraction of document hierarchy levels (H1-H6) based on font size clustering and semantic analysis. When enabled, hierarchical blocks are included in page content.
| Field | Type | Default | Description |
|---|---|---|---|
enabled |
boolean |
true |
Enable hierarchy extraction |
kClusters |
number |
3 |
Number of font size clusters to use for hierarchy levels (1-7) Default: 6, which provides H1-H6 heading levels with body text. Larger values create more fine-grained hierarchy levels. |
includeBbox |
boolean |
true |
Include bounding box information in hierarchy blocks |
ocrCoverageThreshold |
number \| null |
null |
OCR coverage threshold for smart OCR triggering (0.0-1.0) Determines when OCR should be triggered based on text block coverage. OCR is triggered when text blocks cover less than this fraction of the page. Default: 0.5 (trigger OCR if less than 50% of page has text) |
Methods¶
default()¶
Signature:
HtmlMetadata¶
HTML metadata extracted from HTML documents.
Includes document-level metadata, Open Graph data, Twitter Card metadata, and extracted structural elements (headers, links, images, structured data).
| Field | Type | Default | Description |
|---|---|---|---|
title |
string \| null |
null |
Document title from <title> tag |
description |
string \| null |
null |
Document description from <meta name="description"> tag |
keywords |
Array<string> |
[] |
Document keywords from <meta name="keywords"> tag, split on commas |
author |
string \| null |
null |
Document author from <meta name="author"> tag |
canonicalUrl |
string \| null |
null |
Canonical URL from <link rel="canonical"> tag |
baseHref |
string \| null |
null |
Base URL from <base href=""> tag for resolving relative URLs |
language |
string \| null |
null |
Document language from lang attribute |
textDirection |
TextDirection \| null |
null |
Document text direction from dir attribute |
openGraph |
Record<string, string> |
{} |
Open Graph metadata (og:* properties) for social media Keys like "title", "description", "image", "url", etc. |
twitterCard |
Record<string, string> |
{} |
Twitter Card metadata (twitter:* properties) Keys like "card", "site", "creator", "title", "description", "image", etc. |
metaTags |
Record<string, string> |
{} |
Additional meta tags not covered by specific fields Keys are meta name/property attributes, values are content |
headers |
Array<HeaderMetadata> |
[] |
Extracted header elements with hierarchy |
links |
Array<LinkMetadata> |
[] |
Extracted hyperlinks with type classification |
images |
Array<ImageMetadataType> |
[] |
Extracted images with source and dimensions |
structuredData |
Array<StructuredData> |
[] |
Extracted structured data blocks |
HtmlOutputConfig¶
Configuration for styled HTML output.
When set on ExtractionConfig.html_output alongside
output_format = OutputFormat.Html, the pipeline builds a
StyledHtmlRenderer instead of
the plain comrak-based renderer.
| Field | Type | Default | Description |
|---|---|---|---|
css |
string \| null |
null |
Inline CSS string injected into the output after the theme stylesheet. Concatenated after css_file content when both are set. |
cssFile |
string \| null |
null |
Path to a CSS file loaded once at renderer construction time. Concatenated before css when both are set. |
theme |
HtmlTheme |
HtmlTheme.Unstyled |
Built-in colour/typography theme. Default: HtmlTheme.Unstyled. |
classPrefix |
string |
— | CSS class prefix applied to every emitted class name. Default: "kb-". Change this if your host application already uses classes that start with kb-. |
embedCss |
boolean |
true |
When true (default), write the resolved CSS into a <style> block immediately after the opening <div class="{prefix}doc">. Set to false to emit only the structural markup and wire up your own stylesheet targeting the kb-* class names. |
Methods¶
default()¶
Signature:
ImageExtractionConfig¶
Image extraction configuration.
| Field | Type | Default | Description |
|---|---|---|---|
extractImages |
boolean |
true |
Extract images from documents |
targetDpi |
number |
300 |
Target DPI for image normalization |
maxImageDimension |
number |
4096 |
Maximum dimension for images (width or height) |
injectPlaceholders |
boolean |
true |
Whether to inject image reference placeholders into markdown output. When true (default), image references like  are appended to the markdown. Set to false to extract images as data without polluting the markdown output. |
autoAdjustDpi |
boolean |
true |
Automatically adjust DPI based on image content |
minDpi |
number |
72 |
Minimum DPI threshold |
maxDpi |
number |
600 |
Maximum DPI threshold |
maxImagesPerPage |
number \| null |
null |
Maximum number of image objects to extract per PDF page. Some PDFs (e.g. technical diagrams stored as thousands of raster fragments) can trigger extremely long or indefinite extraction times when every image object on a dense page is decoded individually via the PDF extractor. Setting this limit causes kreuzberg to stop collecting individual images once the count per page reaches the cap and emit a warning instead. null (default) means no limit — all images are extracted. |
classify |
boolean |
true |
When true (default), extracted images are classified by kind and grouped into clusters where they appear to belong to one figure. |
Methods¶
default()¶
Signature:
ImageMetadata¶
Image metadata extracted from image files.
Includes dimensions, format, and EXIF data.
| Field | Type | Default | Description |
|---|---|---|---|
width |
number |
— | Image width in pixels |
height |
number |
— | Image height in pixels |
format |
string |
— | Image format (e.g., "PNG", "JPEG", "TIFF") |
exif |
Record<string, string> |
{} |
EXIF metadata tags |
ImageMetadataType¶
Image element metadata.
| Field | Type | Default | Description |
|---|---|---|---|
src |
string |
— | Image source (URL, data URI, or SVG content) |
alt |
string \| null |
null |
Alternative text from alt attribute |
title |
string \| null |
null |
Title attribute |
dimensions |
Array<number> \| null |
null |
Image dimensions as (width, height) if available |
imageType |
ImageType |
— | Image type classification |
attributes |
Array<Array<string>> |
— | Additional attributes as key-value pairs |
ImagePreprocessingConfig¶
Image preprocessing configuration for OCR.
These settings control how images are preprocessed before OCR to improve text recognition quality. Different preprocessing strategies work better for different document types.
| Field | Type | Default | Description |
|---|---|---|---|
targetDpi |
number |
300 |
Target DPI for the image (300 is standard, 600 for small text). |
autoRotate |
boolean |
true |
Auto-detect and correct image rotation. |
deskew |
boolean |
true |
Correct skew (tilted images). |
denoise |
boolean |
false |
Remove noise from the image. |
contrastEnhance |
boolean |
false |
Enhance contrast for better text visibility. |
binarizationMethod |
string |
"otsu" |
Binarization method: "otsu", "sauvola", "adaptive". |
invertColors |
boolean |
false |
Invert colors (white text on black → black on white). |
Methods¶
default()¶
Signature:
ImagePreprocessingMetadata¶
Image preprocessing metadata.
Tracks the transformations applied to an image during OCR preprocessing, including DPI normalization, resizing, and resampling.
| Field | Type | Default | Description |
|---|---|---|---|
originalDimensions |
Array<number> |
— | Original image dimensions (width, height) in pixels |
originalDpi |
Array<number> |
— | Original image DPI (horizontal, vertical) |
targetDpi |
number |
— | Target DPI from configuration |
scaleFactor |
number |
— | Scaling factor applied to the image |
autoAdjusted |
boolean |
— | Whether DPI was auto-adjusted based on content |
finalDpi |
number |
— | Final DPI after processing |
newDimensions |
Array<number> \| null |
null |
New dimensions after resizing (if resized) |
resampleMethod |
string |
— | Resampling algorithm used ("LANCZOS3", "CATMULLROM", etc.) |
dimensionClamped |
boolean |
— | Whether dimensions were clamped to max_image_dimension |
calculatedDpi |
number \| null |
null |
Calculated optimal DPI (if auto_adjust_dpi enabled) |
skippedResize |
boolean |
— | Whether resize was skipped (dimensions already optimal) |
resizeError |
string \| null |
null |
Error message if resize failed |
InlineElement¶
Inline element within a block.
Represents text with formatting, links, images, etc.
| Field | Type | Default | Description |
|---|---|---|---|
elementType |
InlineType |
— | Type of inline element |
content |
string |
— | Text content |
attributes |
string \| null |
null |
Element attributes |
metadata |
Record<string, string> \| null |
null |
Additional metadata (e.g., href for links, src/alt for images) |
JatsMetadata¶
JATS (Journal Article Tag Suite) metadata.
| Field | Type | Default | Description |
|---|---|---|---|
copyright |
string \| null |
null |
Copyright |
license |
string \| null |
null |
License |
historyDates |
Record<string, string> |
{} |
History dates |
contributorRoles |
Array<ContributorRole> |
[] |
Contributor roles |
Keyword¶
Extracted keyword with metadata.
| Field | Type | Default | Description |
|---|---|---|---|
text |
string |
— | The keyword text. |
score |
number |
— | Relevance score (higher is better, algorithm-specific range). |
algorithm |
KeywordAlgorithm |
— | Algorithm that extracted this keyword. |
positions |
Array<number> \| null |
null |
Optional positions where keyword appears in text (character offsets). |
KeywordConfig¶
Keyword extraction configuration.
| Field | Type | Default | Description |
|---|---|---|---|
algorithm |
KeywordAlgorithm |
KeywordAlgorithm.Yake |
Algorithm to use for extraction. |
maxKeywords |
number |
10 |
Maximum number of keywords to extract (default: 10). |
minScore |
number |
0 |
Minimum score threshold (0.0-1.0, default: 0.0). Keywords with scores below this threshold are filtered out. Note: Score ranges differ between algorithms. |
ngramRange |
Array<number> |
[] |
N-gram range for keyword extraction (min, max). (1, 1) = unigrams only (1, 2) = unigrams and bigrams (1, 3) = unigrams, bigrams, and trigrams (default) |
language |
string \| null |
null |
Language code for stopword filtering (e.g., "en", "de", "fr"). If None, no stopword filtering is applied. |
yakeParams |
YakeParams \| null |
null |
YAKE-specific tuning parameters. |
rakeParams |
RakeParams \| null |
null |
RAKE-specific tuning parameters. |
Methods¶
default()¶
Signature:
LanguageDetectionConfig¶
Language detection configuration.
| Field | Type | Default | Description |
|---|---|---|---|
enabled |
boolean |
true |
Enable language detection |
minConfidence |
number |
0.8 |
Minimum confidence threshold (0.0-1.0) |
detectMultiple |
boolean |
false |
Detect multiple languages in the document |
Methods¶
default()¶
Signature:
LayoutRegion¶
A detected layout region on a page.
When layout detection is enabled, each page may have layout regions identifying different content types (text, pictures, tables, etc.) with confidence scores and spatial positions.
| Field | Type | Default | Description |
|---|---|---|---|
className |
string |
— | Layout class name (e.g. "picture", "table", "text", "section_header"). |
confidence |
number |
— | Confidence score from the layout detection model (0.0 to 1.0). |
boundingBox |
BoundingBox |
— | Bounding box in document coordinate space. |
areaFraction |
number |
— | Fraction of the page area covered by this region (0.0 to 1.0). |
LinkMetadata¶
Link element metadata.
| Field | Type | Default | Description |
|---|---|---|---|
href |
string |
— | The href URL value |
text |
string |
— | Link text content (normalized) |
title |
string \| null |
null |
Optional title attribute |
linkType |
LinkType |
— | Link type classification |
rel |
Array<string> |
— | Rel attribute values |
attributes |
Array<Array<string>> |
— | Additional attributes as key-value pairs |
LlmConfig¶
Configuration for an LLM provider/model via liter-llm.
Each feature (VLM OCR, VLM embeddings, structured extraction) carries
its own LlmConfig, allowing different providers per feature.
| Field | Type | Default | Description |
|---|---|---|---|
model |
string |
— | Provider/model string using liter-llm routing format. Examples: "openai/gpt-4o", "anthropic/claude-sonnet-4-20250514", "groq/llama-3.1-70b-versatile". |
apiKey |
string \| null |
null |
API key for the provider. When null, liter-llm falls back to the provider's standard environment variable (e.g., OPENAI_API_KEY). |
baseUrl |
string \| null |
null |
Custom base URL override for the provider endpoint. |
timeoutSecs |
number \| null |
null |
Request timeout in seconds (default: 60). |
maxRetries |
number \| null |
null |
Maximum retry attempts (default: 3). |
temperature |
number \| null |
null |
Sampling temperature for generation tasks. |
maxTokens |
number \| null |
null |
Maximum tokens to generate. |
LlmUsage¶
Token usage and cost data for a single LLM call made during extraction.
Populated when VLM OCR, structured extraction, or LLM-based embeddings are used. Multiple entries may be present when multiple LLM calls occur within one extraction (e.g. VLM OCR + structured extraction).
| Field | Type | Default | Description |
|---|---|---|---|
model |
string |
— | The LLM model identifier (e.g. "openai/gpt-4o", "anthropic/claude-sonnet-4-20250514"). |
source |
string |
— | The pipeline stage that triggered this LLM call (e.g. "vlm_ocr", "structured_extraction", "embeddings"). |
inputTokens |
number \| null |
null |
Number of input/prompt tokens consumed. |
outputTokens |
number \| null |
null |
Number of output/completion tokens generated. |
totalTokens |
number \| null |
null |
Total tokens (input + output). |
estimatedCost |
number \| null |
null |
Estimated cost in USD based on the provider's published pricing. |
finishReason |
string \| null |
null |
Why the model stopped generating (e.g. "stop", "length", "content_filter"). |
Metadata¶
Extraction result metadata.
Contains common fields applicable to all formats, format-specific metadata via a discriminated union, and additional custom fields from postprocessors.
| Field | Type | Default | Description |
|---|---|---|---|
title |
string \| null |
null |
Document title |
subject |
string \| null |
null |
Document subject or description |
authors |
Array<string> \| null |
[] |
Primary author(s) - always Vec for consistency |
keywords |
Array<string> \| null |
[] |
Keywords/tags - always Vec for consistency |
language |
string \| null |
null |
Primary language (ISO 639 code) |
createdAt |
string \| null |
null |
Creation timestamp (ISO 8601 format) |
modifiedAt |
string \| null |
null |
Last modification timestamp (ISO 8601 format) |
createdBy |
string \| null |
null |
User who created the document |
modifiedBy |
string \| null |
null |
User who last modified the document |
pages |
PageStructure \| null |
null |
Page/slide/sheet structure with boundaries |
format |
FormatMetadata \| null |
null |
Format-specific metadata (discriminated union) Contains detailed metadata specific to the document format. Serialized as a nested "format" object with a format_type discriminator field. |
imagePreprocessing |
ImagePreprocessingMetadata \| null |
null |
Image preprocessing metadata (when OCR preprocessing was applied) |
jsonSchema |
unknown \| null |
null |
JSON schema (for structured data extraction) |
error |
ErrorMetadata \| null |
null |
Error metadata (for batch operations) |
extractionDurationMs |
number \| null |
null |
Extraction duration in milliseconds (for benchmarking). This field is populated by batch extraction to provide per-file timing information. It's null for single-file extraction (which uses external timing). |
category |
string \| null |
null |
Document category (from frontmatter or classification). |
tags |
Array<string> \| null |
[] |
Document tags (from frontmatter). |
documentVersion |
string \| null |
null |
Document version string (from frontmatter). |
abstractText |
string \| null |
null |
Abstract or summary text (from frontmatter). |
outputFormat |
string \| null |
null |
Output format identifier (e.g., "markdown", "html", "text"). Set by the output format pipeline stage when format conversion is applied. Previously stored in metadata.additional["output_format"]. |
ocrUsed |
boolean |
— | Whether OCR was used during extraction. Set to true whenever the extraction pipeline ran an OCR backend (Tesseract, PaddleOCR, VLM, etc.) and used that output as the primary or fallback text. false means native text extraction was used exclusively. |
additional |
Record<string, unknown> |
{} |
Additional custom fields from postprocessors. Serialized as a nested "additional" object (not flattened at root level). Uses Cow<'static, str> keys so static string keys avoid allocation. |
Methods¶
isEmpty()¶
Returns true when no metadata fields, format-specific metadata, or
additional postprocessor fields are populated.
Signature:
OcrBackend¶
Trait for OCR backend plugins.
Implement this trait to add custom OCR capabilities. OCR backends can be:
- Native Rust implementations (like Tesseract)
- FFI bridges to Python libraries (like EasyOCR, PaddleOCR)
- Cloud-based OCR services (Google Vision, AWS Textract, etc.)
Thread Safety¶
OCR backends must be thread-safe (Send + Sync) to support concurrent processing.
Methods¶
processImage()¶
Process an image and extract text via OCR.
Returns:
An ExtractionResult containing the extracted text and metadata.
Errors:
KreuzbergError.Ocr- OCR processing failedKreuzbergError.Validation- Invalid image format or configurationKreuzbergError.Io- I/O errors (these always bubble up)
Reading backend_options¶
Backends that support runtime tuning can read config.backend_options and
deserialize only the keys they care about. Unknown keys are silently ignored,
so multiple backends can coexist in a pipeline without key conflicts.
Signature:
processImageFile()¶
Process a file and extract text via OCR.
Default implementation reads the file and calls process_image.
Override for custom file handling or optimizations.
Errors:
Same as process_image, plus file I/O errors.
Signature:
supportsLanguage()¶
Check if this backend supports a given language code.
Returns:
true if the language is supported, false otherwise.
Signature:
backendType()¶
Get the backend type identifier.
Returns:
The backend type enum value.
Signature:
supportedLanguages()¶
Optional: Get a list of all supported languages.
Defaults to empty list. Override to provide comprehensive language support info.
Signature:
supportsTableDetection()¶
Optional: Check if the backend supports table detection.
Defaults to false. Override if your backend can detect and extract tables.
Signature:
supportsDocumentProcessing()¶
Check if the backend supports direct document-level processing (e.g. for PDFs).
Defaults to false. Override if the backend has optimized document processing.
Signature:
processDocument()¶
Process a document file directly via OCR.
Only called if supports_document_processing returns true.
Signature:
OcrConfidence¶
Confidence scores for an OCR element.
Separates detection confidence (how confident that text exists at this location) from recognition confidence (how confident about the actual text content).
| Field | Type | Default | Description |
|---|---|---|---|
detection |
number \| null |
null |
Detection confidence: how confident the OCR engine is that text exists here. PaddleOCR provides this as box_score, Tesseract doesn't have a direct equivalent. Range: 0.0 to 1.0 (or None if not available). |
recognition |
number |
— | Recognition confidence: how confident about the text content. Range: 0.0 to 1.0. |
OcrConfig¶
OCR configuration.
| Field | Type | Default | Description |
|---|---|---|---|
enabled |
boolean |
true |
Whether OCR is enabled. Setting enabled: false is a shorthand for disable_ocr: true on the parent ExtractionConfig. Images return metadata only; PDFs use native text extraction without OCR fallback. Defaults to true. When false, all other OCR settings are ignored. |
backend |
string |
— | OCR backend: tesseract, easyocr, paddleocr |
language |
string |
— | Language code (e.g., "eng", "deu") |
tesseractConfig |
TesseractConfig \| null |
null |
Tesseract-specific configuration (optional) |
outputFormat |
OutputFormat \| null |
null |
Output format for OCR results (optional, for format conversion) |
paddleOcrConfig |
unknown \| null |
null |
PaddleOCR-specific configuration (optional, JSON passthrough) |
backendOptions |
unknown \| null |
null |
Arbitrary per-call options passed through to the backend unchanged. Custom OCR backends and built-in backends that support runtime tuning can read this value and deserialize the keys they care about. Keys unknown to the backend are silently ignored. This is the recommended extension point for per-call parameters that are not covered by the typed fields above (e.g. mode switching, preprocessing flags, inference batch size). Scope: when pipeline is null, this value is propagated to the primary stage of the auto-constructed pipeline. When pipeline is explicitly set, this field has no effect — the caller must set OcrPipelineStage.backend_options directly on the relevant stage(s) instead. Example: json { "mode": "fast", "enable_layout": true, "timeout_ms": 5000 } |
elementConfig |
OcrElementConfig \| null |
null |
OCR element extraction configuration |
qualityThresholds |
OcrQualityThresholds \| null |
null |
Quality thresholds for the native-text-to-OCR fallback decision. When None, uses compiled defaults (matching previous hardcoded behavior). |
pipeline |
OcrPipelineConfig \| null |
null |
Multi-backend OCR pipeline configuration. When set, enables weighted fallback across multiple OCR backends based on output quality. When None, uses the single backend field (same as today). |
autoRotate |
boolean |
false |
Enable automatic page rotation based on orientation detection. When enabled, uses Tesseract's DetectOrientationScript() to detect page orientation (0/90/180/270 degrees) before OCR. If the page is rotated with high confidence, the image is corrected before recognition. This is critical for handling rotated scanned documents. |
vlmConfig |
LlmConfig \| null |
null |
VLM (Vision Language Model) OCR configuration. Required when backend is "vlm". Uses liter-llm to send page images to a vision model for text extraction. |
vlmPrompt |
string \| null |
null |
Custom Jinja2 prompt template for VLM OCR. When null, uses the default template. Available variables: - {{ language }} — The document language code (e.g., "eng", "deu"). |
acceleration |
AccelerationConfig \| null |
null |
Hardware acceleration for ONNX Runtime models (e.g. PaddleOCR, layout detection). Not user-configurable via config files — injected at runtime from ExtractionConfig.acceleration before each process_image call. |
tessdataBytes |
Record<string, Buffer> \| null |
null |
Caller-supplied Tesseract traineddata bytes per language code. Primary use case is the WASM build, which has no filesystem and cannot download tessdata at runtime. Native builds typically rely on TessdataManager and ignore this field. When present, the WASM Tesseract backend prefers these bytes over its compile-time-bundled English data. Skipped by serde to keep config files small — supply via the typed API at runtime. |
Methods¶
default()¶
Signature:
OcrElement¶
A unified OCR element representing detected text with full metadata.
This is the primary type for structured OCR output, preserving all information from both Tesseract and PaddleOCR backends.
| Field | Type | Default | Description |
|---|---|---|---|
text |
string |
— | The recognized text content. |
geometry |
OcrBoundingGeometry |
OcrBoundingGeometry.Rectangle |
Bounding geometry (rectangle or quadrilateral). |
confidence |
OcrConfidence |
— | Confidence scores for detection and recognition. |
level |
OcrElementLevel |
OcrElementLevel.Line |
Hierarchical level (word, line, block, page). |
rotation |
OcrRotation \| null |
null |
Rotation information (if detected). |
pageNumber |
number |
— | Page number (1-indexed). |
parentId |
string \| null |
null |
Parent element ID for hierarchical relationships. Only used for Tesseract output which has word -> line -> block hierarchy. |
backendMetadata |
Record<string, unknown> |
{} |
Backend-specific metadata that doesn't fit the unified schema. |
OcrElementConfig¶
Configuration for OCR element extraction.
Controls how OCR elements are extracted and filtered.
| Field | Type | Default | Description |
|---|---|---|---|
includeElements |
boolean |
— | Whether to include OCR elements in the extraction result. When true, the ocr_elements field in ExtractionResult will be populated. |
minLevel |
OcrElementLevel |
OcrElementLevel.Line |
Minimum hierarchical level to include. Elements below this level (e.g., words when min_level is Line) will be excluded. |
minConfidence |
number |
— | Minimum recognition confidence threshold (0.0-1.0). Elements with confidence below this threshold will be filtered out. |
buildHierarchy |
boolean |
— | Whether to build hierarchical relationships between elements. When true, parent_id fields will be populated based on spatial containment. Only meaningful for Tesseract output. |
OcrExtractionResult¶
OCR extraction result.
Result of performing OCR on an image or scanned document, including recognized text and detected tables.
| Field | Type | Default | Description |
|---|---|---|---|
content |
string |
— | Recognized text content |
mimeType |
string |
— | Original MIME type of the processed image |
metadata |
Record<string, unknown> |
— | OCR processing metadata (confidence scores, language, etc.) |
tables |
Array<OcrTable> |
— | Tables detected and extracted via OCR |
ocrElements |
Array<OcrElement> \| null |
/* serde(default) */ |
Structured OCR elements with bounding boxes and confidence scores. Available when TSV output is requested or table detection is enabled. |
internalDocument |
string \| null |
null |
Structured document produced from hOCR parsing. Carries paragraph structure, bounding boxes, and confidence scores that the flattened content string discards. |
OcrMetadata¶
OCR processing metadata.
Captures information about OCR processing configuration and results.
| Field | Type | Default | Description |
|---|---|---|---|
language |
string |
— | OCR language code(s) used |
psm |
number |
— | Tesseract Page Segmentation Mode (PSM) |
outputFormat |
string |
— | Output format (e.g., "text", "hocr") |
tableCount |
number |
— | Number of tables detected |
tableRows |
number \| null |
null |
Table rows |
tableCols |
number \| null |
null |
Table cols |
OcrPipelineConfig¶
Multi-backend OCR pipeline with quality-based fallback.
Backends are tried in priority order (highest first). After each backend
produces output, quality is evaluated. If it meets quality_thresholds.pipeline_min_quality,
the result is accepted. Otherwise the next backend is tried.
| Field | Type | Default | Description |
|---|---|---|---|
stages |
Array<OcrPipelineStage> |
— | Ordered list of backends to try. Sorted by priority (descending) at runtime. |
qualityThresholds |
OcrQualityThresholds |
/* serde(default) */ |
Quality thresholds for deciding whether to accept a result or try the next backend. |
OcrPipelineStage¶
A single backend stage in the OCR pipeline.
| Field | Type | Default | Description |
|---|---|---|---|
backend |
string |
— | Backend name: "tesseract", "paddleocr", "easyocr", or a custom registered name. |
priority |
number |
/* serde(default) */ |
Priority weight (higher = tried first). Stages are sorted by priority descending. |
language |
string \| null |
/* serde(default) */ |
Language override for this stage (None = use parent OcrConfig.language). |
tesseractConfig |
TesseractConfig \| null |
/* serde(default) */ |
Tesseract-specific config override for this stage. |
paddleOcrConfig |
unknown \| null |
/* serde(default) */ |
PaddleOCR-specific config for this stage. |
vlmConfig |
LlmConfig \| null |
/* serde(default) */ |
VLM config override for this pipeline stage. |
backendOptions |
unknown \| null |
/* serde(default) */ |
Arbitrary per-call options passed through to the backend unchanged. Backends that support runtime tuning (mode switching, preprocessing flags, inference parameters, etc.) read this value and deserialize the keys they care about. Keys unknown to the backend are silently ignored, so options from different backends can coexist in the same config without conflict. Example (custom backend): json { "mode": "fast", "enable_layout": true } |
OcrQualityThresholds¶
Quality thresholds for OCR fallback decisions and pipeline quality gating.
All fields default to the values that match the previous hardcoded behavior,
so OcrQualityThresholds.default() preserves existing semantics exactly.
| Field | Type | Default | Description |
|---|---|---|---|
minTotalNonWhitespace |
number |
64 |
Minimum total non-whitespace characters to consider text substantive. |
minNonWhitespacePerPage |
number |
32 |
Minimum non-whitespace characters per page on average. |
minMeaningfulWordLen |
number |
4 |
Minimum character count for a word to be "meaningful". |
minMeaningfulWords |
number |
3 |
Minimum count of meaningful words before text is accepted. |
minAlnumRatio |
number |
0.3 |
Minimum alphanumeric ratio (non-whitespace chars that are alphanumeric). |
minGarbageChars |
number |
5 |
Minimum Unicode replacement characters (U+FFFD) to trigger OCR fallback. |
maxFragmentedWordRatio |
number |
0.6 |
Maximum fraction of short (1-2 char) words before text is considered fragmented. |
criticalFragmentedWordRatio |
number |
0.8 |
Critical fragmentation threshold — triggers OCR regardless of meaningful words. Normal English text has ~20-30% short words. 80%+ is definitive garbage. |
minAvgWordLength |
number |
2 |
Minimum average word length. Below this with enough words indicates garbled extraction. |
minWordsForAvgLengthCheck |
number |
50 |
Minimum word count before average word length check applies. |
minConsecutiveRepeatRatio |
number |
0.08 |
Minimum consecutive word repetition ratio to detect column scrambling. |
minWordsForRepeatCheck |
number |
50 |
Minimum word count before consecutive repetition check is applied. |
substantiveMinChars |
number |
100 |
Minimum character count for "substantive markdown" OCR skip gate. |
nonTextMinChars |
number |
20 |
Minimum character count for "non-text content" OCR skip gate. |
alnumWsRatioThreshold |
number |
0.4 |
Alphanumeric+whitespace ratio threshold for skip decisions. |
pipelineMinQuality |
number |
0.5 |
Minimum quality score (0.0-1.0) for a pipeline stage result to be accepted. If the result from a backend scores below this, try the next backend. |
Methods¶
default()¶
Signature:
OcrRotation¶
Rotation information for an OCR element.
| Field | Type | Default | Description |
|---|---|---|---|
angleDegrees |
number |
— | Rotation angle in degrees (0, 90, 180, 270 for PaddleOCR). |
confidence |
number \| null |
null |
Confidence score for the rotation detection. |
OcrTable¶
Table detected via OCR.
Represents a table structure recognized during OCR processing.
| Field | Type | Default | Description |
|---|---|---|---|
cells |
Array<Array<string>> |
— | Table cells as a 2D vector (rows × columns) |
markdown |
string |
— | Markdown representation of the table |
pageNumber |
number |
— | Page number where the table was found (1-indexed) |
boundingBox |
OcrTableBoundingBox \| null |
/* serde(default) */ |
Bounding box of the table in pixel coordinates (from OCR word positions). |
OcrTableBoundingBox¶
Bounding box for an OCR-detected table in pixel coordinates.
| Field | Type | Default | Description |
|---|---|---|---|
left |
number |
— | Left x-coordinate (pixels) |
top |
number |
— | Top y-coordinate (pixels) |
right |
number |
— | Right x-coordinate (pixels) |
bottom |
number |
— | Bottom y-coordinate (pixels) |
PageBoundary¶
Byte offset boundary for a page.
Tracks where a specific page's content starts and ends in the main content string, enabling mapping from byte positions to page numbers. Offsets are guaranteed to be at valid UTF-8 character boundaries when using standard String methods (push_str, push, etc.).
| Field | Type | Default | Description |
|---|---|---|---|
byteStart |
number |
— | Byte offset where this page starts in the content string (UTF-8 valid boundary, inclusive) |
byteEnd |
number |
— | Byte offset where this page ends in the content string (UTF-8 valid boundary, exclusive) |
pageNumber |
number |
— | Page number (1-indexed) |
PageConfig¶
Page extraction and tracking configuration.
Controls how pages are extracted, tracked, and represented in the extraction results.
When null, page tracking is disabled.
Page range tracking in chunk metadata (first_page/last_page) is automatically enabled when page boundaries are available and chunking is configured.
| Field | Type | Default | Description |
|---|---|---|---|
extractPages |
boolean |
false |
Extract pages as separate array (ExtractionResult.pages) |
insertPageMarkers |
boolean |
false |
Insert page markers in main content string |
markerFormat |
string |
`" |
"` | Page marker format (use {page_num} placeholder) Default: "\n\n\n\n" |
Methods¶
default()¶
Signature:
PageContent¶
Content for a single page/slide.
When page extraction is enabled, documents are split into per-page content with associated tables and images mapped to each page.
Performance¶
Uses Arc-wrapped tables and images for memory efficiency:
Vec<Arc<Table>>enables zero-copy sharing of table dataVec<Arc<ExtractedImage>>enables zero-copy sharing of image data- Maintains exact JSON compatibility via custom Serialize/Deserialize
This reduces memory overhead for documents with shared tables/images by avoiding redundant copies during serialization.
| Field | Type | Default | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pageNumber |
number |
— | Page number (1-indexed) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content |
string |
— | Text content for this page | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
tables |
Array<Table> |
/* serde(default) */ |
Tables found on this page (uses Arc for memory efficiency) Serializes as Vec
PageHierarchy¶Page hierarchy structure containing heading levels and block information. Used when PDF text hierarchy extraction is enabled. Contains hierarchical blocks with heading levels (H1-H6) for semantic document structure.
PageInfo¶Metadata for individual page/slide/sheet. Captures per-page information including dimensions, content counts, and visibility state (for presentations).
PageStructure¶Unified page structure for documents. Supports different page types (PDF pages, PPTX slides, Excel sheets) with character offset boundaries for chunk-to-page mapping.
PdfAnnotation¶A PDF annotation extracted from a document page.
PdfConfig¶PDF-specific configuration.
Methods¶default()¶Signature: PdfMetadata¶PDF-specific metadata. Contains metadata fields specific to PDF documents that are not in the common
Plugin¶Base trait that all plugins must implement. This trait provides common functionality for plugin lifecycle management, identification, and metadata. Thread Safety¶All plugins must be Methods¶name()¶Returns the unique name/identifier for this plugin. The name should be:
Signature: version()¶Returns the semantic version of this plugin. Should follow semver format: Defaults to the kreuzberg crate version. Signature: initialize()¶Initialize the plugin. Called once when the plugin is registered. Use this to:
Thread Safety¶This method takes Errors: Should return an error if initialization fails. The plugin will not be registered if this method returns an error. Defaults to a no-op for stateless plugins. Signature: shutdown()¶Shutdown the plugin. Called when the plugin is being unregistered or the application is shutting down. Use this to:
Thread Safety¶This method takes Errors: Errors during shutdown are logged but don't prevent the shutdown process. Defaults to a no-op for stateless plugins. Signature: description()¶Optional plugin description for debugging and logging. Defaults to empty string if not overridden. Signature: author()¶Optional plugin author information. Defaults to empty string if not overridden. Signature: PostProcessor¶Trait for post-processor plugins. Post-processors transform or enrich extraction results after the initial extraction is complete. They can:
Processing Order¶Post-processors are executed in stage order:
Within each stage, processors are executed in registration order. Error Handling¶Post-processor errors are non-fatal by default - they're captured in metadata
and execution continues. To make errors fatal, return an error from Thread Safety¶Post-processors must be thread-safe ( Methods¶process()¶Process an extraction result. Transform or enrich the extraction result. Can modify:
Returns:
Errors: Return errors for fatal processing failures. Non-fatal errors should be captured in metadata directly on the result. Performance¶This signature avoids unnecessary cloning of large extraction results by taking a mutable reference instead of ownership. Processors modify the result in place. Example - Language Detection¶Example - Text Cleaning¶Signature: processingStage()¶Get the processing stage for this post-processor. Determines when this processor runs in the pipeline. Returns: The Signature: shouldProcess()¶Optional: Check if this processor should run for a given result. Allows conditional processing based on MIME type, metadata, or content.
Defaults to Returns:
Signature: estimatedDurationMs()¶Optional: Estimate processing time in milliseconds. Used for logging and debugging. Defaults to 0 (unknown). Returns: Estimated processing time in milliseconds. Signature: priority()¶Execution priority within the processing stage. Higher values run first within the same Signature: PostProcessorConfig¶Post-processor configuration.
Methods¶default()¶Signature: PptxAppProperties¶Application properties from docProps/app.xml for PPTX Contains PowerPoint-specific document metadata.
PptxExtractionResult¶PowerPoint (PPTX) extraction result. Contains extracted slide content, metadata, and embedded images/tables.
PptxMetadata¶PowerPoint presentation metadata. Extracted from PPTX files containing slide counts and presentation details.
PstMetadata¶Outlook PST archive metadata.
RakeParams¶RAKE-specific parameters.
Methods¶default()¶Signature: Renderer¶Trait for document renderers that convert Renderers are typically stateless converters that transform the internal
document representation into a specific output format (Markdown, HTML,
Djot, plain text, etc.). They participate in the standard The format name is exposed via Thread Safety¶Renderers must be Methods¶render()¶Render an Returns: The rendered output as a string. Errors: Returns an error if rendering fails. Signature: SecurityLimits¶Configuration for security limits across extractors. All limits are intentionally conservative to prevent DoS attacks while still supporting legitimate documents.
Methods¶default()¶Signature: ServerConfig¶API server configuration. This struct holds all configuration options for the Kreuzberg API server, including host/port settings, CORS configuration, and upload limits. Defaults¶
Methods¶default()¶Signature: listenAddr()¶Get the server listen address (host:port). Signature: corsAllowsAll()¶Check if CORS allows all origins. Returns Signature: isOriginAllowed()¶Check if a given origin is allowed by CORS configuration. Returns
Signature: maxRequestBodyMb()¶Get maximum request body size in megabytes (rounded up). Signature: maxMultipartFieldMb()¶Get maximum multipart field size in megabytes (rounded up). Signature: StructuredData¶Structured data (Schema.org, microdata, RDFa) block.
StructuredDataResult¶
StructuredExtractionConfig¶Configuration for LLM-based structured data extraction. Sends extracted document content to a VLM with a JSON schema, returning structured data that conforms to the schema.
SupportedFormat¶A supported document format entry. Represents a file extension and its corresponding MIME type that Kreuzberg can process.
Table¶Extracted table structure. Represents a table detected and extracted from a document (PDF, image, etc.). Tables are converted to both structured cell data and Markdown format.
TableCell¶Individual table cell with content and optional styling. Future extension point for rich table support with cell-level metadata.
TableGrid¶Structured table grid with cell-level metadata. Stores row/column dimensions and a flat list of cells with position info.
TextAnnotation¶Inline text annotation — byte-range based formatting and links. Annotations reference byte offsets into the node's text content, enabling precise identification of formatted regions.
TextExtractionResult¶Plain text and Markdown extraction result. Contains the extracted text along with statistics and, for Markdown files, structural elements like headers and links.
TextMetadata¶Text/Markdown metadata. Extracted from plain text and Markdown files. Includes word counts and, for Markdown, structural elements like headers and links.
TokenReductionConfig¶
Methods¶default()¶Signature: TokenReductionOptions¶Token reduction configuration.
Methods¶default()¶Signature: TreeSitterConfig¶Configuration for tree-sitter language pack integration. Controls grammar download behavior and code analysis options. Example (TOML)¶
Methods¶default()¶Signature: TreeSitterProcessConfig¶Processing options for tree-sitter code analysis. Controls which analysis features are enabled when extracting code files.
Methods¶default()¶Signature: Uri¶A URI extracted from a document. Represents any link, reference, or resource pointer found during extraction.
The
Validator¶Trait for validator plugins. Validators check extraction results for quality, completeness, or correctness. Unlike post-processors, validator errors fail fast - if a validator returns an error, the extraction fails immediately. Use Cases¶
Error Handling¶Validator errors are fatal - they cause the extraction to fail and bubble up to the caller. Use validators for hard requirements that must be met. For non-fatal checks, use post-processors instead. Thread Safety¶Validators must be thread-safe ( Methods¶validate()¶Validate an extraction result. Check the extraction result and return Returns:
Errors:
Example - Content Length Validation¶Example - Quality Score Validation¶Example - Security Validation¶Signature: shouldValidate()¶Optional: Check if this validator should run for a given result. Allows conditional validation based on MIME type, metadata, or content.
Defaults to Returns:
Signature: priority()¶Optional: Get the validation priority. Higher priority validators run first. Useful for ordering validation checks (e.g., run cheap validations before expensive ones). Default priority is 50. Returns: Priority value (higher = runs earlier). Signature: XlsxAppProperties¶Application properties from docProps/app.xml for XLSX Contains Excel-specific document metadata.
XmlExtractionResult¶XML extraction result. Contains extracted text content from XML files along with structural statistics about the XML document.
XmlMetadata¶XML metadata extracted during XML parsing. Provides statistics about XML document structure.
YakeParams¶YAKE-specific parameters.
Methods¶default()¶Signature: YearRange¶Year range for bibliographic metadata.
Enums¶ExecutionProviderType¶ONNX Runtime execution provider type. Determines which hardware backend is used for model inference.
OutputFormat¶Output format for extraction results. Controls the format of the
HtmlTheme¶Built-in HTML theme selection.
ChunkerType¶Type of text chunker to use. Variants¶
EmbeddingModelType¶Embedding model types supported by Kreuzberg.
CodeContentMode¶Content rendering mode for code extraction. Controls how extracted code content is represented in the
ListType¶Type of list detection.
FracType¶
OcrBackendType¶OCR backend types.
ProcessingStage¶Processing stages for post-processors. Post-processors are executed in stage order (Early → Middle → Late). Use stages to control the order of post-processing operations.
ReductionLevel¶
PdfAnnotationType¶Type of PDF annotation.
BlockType¶Types of block-level elements in Djot.
InlineType¶Types of inline elements in Djot.
RelationshipKind¶Semantic kind of a relationship between document elements.
ContentLayer¶Content layer classification for document nodes. Replaces separate body/furniture arrays with per-node granularity.
NodeContent¶Tagged enum for node content. Each variant carries only type-specific data. Uses
AnnotationKind¶Types of inline text annotations.
ExtractionMethod¶How the extracted text was produced.
ChunkType¶Semantic structural classification of a text chunk. Assigned by the heuristic classifier in
ImageKind¶Heuristic classification of what an image likely depicts.
ResultFormat¶Result-shape selection for extraction results. Distinct from
ElementType¶Semantic element type classification. Categorizes text content into semantic units for downstream processing. Supports the element types commonly found in Unstructured documents.
FormatMetadata¶Format-specific metadata (discriminated union). Only one format type can exist per extraction result. This provides type-safe, clean metadata without nested optionals.
TextDirection¶Text direction enumeration for HTML documents.
LinkType¶Link type classification.
ImageType¶Image type classification.
StructuredDataType¶Structured data type classification.
OcrBoundingGeometry¶Bounding geometry for an OCR element. Supports both axis-aligned rectangles (from Tesseract) and 4-point quadrilaterals (from PaddleOCR and rotated text detection).
OcrElementLevel¶Hierarchical level of an OCR element. Maps to Tesseract's page segmentation hierarchy and provides equivalent semantics for PaddleOCR.
PageUnitType¶Type of paginated unit in a document. Distinguishes between different types of "pages" (PDF pages, presentation slides, spreadsheet sheets).
UriKind¶Semantic classification of an extracted URI.
KeywordAlgorithm¶Keyword algorithm selection.
Errors¶KreuzbergError¶Main error type for all Kreuzberg operations. All errors in Kreuzberg use this enum, which preserves error chains and provides context for debugging. Variants¶
Errors are thrown as plain
|