Kotlin (Android) API Reference
Kotlin (Android) API Reference v5.0.0-rc.30¶
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:
@Throws(Error::class)
fun extractBytes(content: ByteArray, mimeType: String, config: ExtractionConfig): ExtractionResult
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
ByteArray |
Yes | The byte array to extract |
mimeType |
String |
Yes | MIME type of the content |
config |
ExtractionConfig |
Yes | Extraction configuration |
Returns: ExtractionResult
Errors: Throws Error.
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:
@Throws(Error::class)
fun extractFile(path: Path, mimeType: String? = null, config: ExtractionConfig): ExtractionResult
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | Path to the file to extract |
mimeType |
String? |
No | Optional MIME type override. If None, will be auto-detected |
config |
ExtractionConfig |
Yes | Extraction configuration |
Returns: ExtractionResult
Errors: Throws Error.
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:
@Throws(Error::class)
fun extractFileSync(path: Path, mimeType: String? = null, config: ExtractionConfig): ExtractionResult
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | Path to the file |
mimeType |
String? |
No | The mime type |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: ExtractionResult
Errors: Throws Error.
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:
@Throws(Error::class)
fun extractBytesSync(content: ByteArray, mimeType: String, config: ExtractionConfig): ExtractionResult
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
ByteArray |
Yes | The content to process |
mimeType |
String |
Yes | The mime type |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: ExtractionResult
Errors: Throws Error.
extractBytesSync()¶
Synchronous wrapper for extract_bytes (WASM-compatible version).
This is a truly synchronous implementation without tokio runtime dependency.
It calls extract_bytes_sync_impl() to perform the extraction.
Signature:
@Throws(Error::class)
fun extractBytesSync(content: ByteArray, mimeType: String, config: ExtractionConfig): ExtractionResult
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
ByteArray |
Yes | The content to process |
mimeType |
String |
Yes | The mime type |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: ExtractionResult
Errors: Throws Error.
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:
@Throws(Error::class)
fun batchExtractFilesSync(items: List<BatchFileItem>, config: ExtractionConfig): List<ExtractionResult>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
List<BatchFileItem> |
Yes | The items |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: List<ExtractionResult>
Errors: Throws Error.
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:
@Throws(Error::class)
fun batchExtractBytesSync(items: List<BatchBytesItem>, config: ExtractionConfig): List<ExtractionResult>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
List<BatchBytesItem> |
Yes | The items |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: List<ExtractionResult>
Errors: Throws Error.
batchExtractBytesSync()¶
Synchronous wrapper for batch_extract_bytes (WASM-compatible version).
Iterates through items sequentially, applying per-file config overrides.
Signature:
@Throws(Error::class)
fun batchExtractBytesSync(items: List<BatchBytesItem>, config: ExtractionConfig): List<ExtractionResult>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
List<BatchBytesItem> |
Yes | The items |
config |
ExtractionConfig |
Yes | The configuration options |
Returns: List<ExtractionResult>
Errors: Throws Error.
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:
@Throws(Error::class)
fun batchExtractFiles(items: List<BatchFileItem>, config: ExtractionConfig): List<ExtractionResult>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
List<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: List<ExtractionResult>
Errors: Throws Error.
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:
@Throws(Error::class)
fun batchExtractBytes(items: List<BatchBytesItem>, config: ExtractionConfig): List<ExtractionResult>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
items |
List<BatchBytesItem> |
Yes | Vector of BatchBytesItem structs, each containing content bytes, |
config |
ExtractionConfig |
Yes | Batch-level extraction configuration |
Returns: List<ExtractionResult>
Errors: Throws Error.
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
ByteArray |
Yes | Raw file bytes |
Returns: String
Errors: Throws Error.
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
mimeType |
String |
Yes | The MIME type to look up |
Returns: List<String>
Errors: Throws Error.
listSupportedFormats()¶
List all supported document formats.
Returns every file extension Kreuzberg recognizes together with its corresponding MIME type, derived from the central format registry. Formats that have no registered file extension (such as source code, which is detected dynamically) are not included.
The list is sorted alphabetically by file extension.
Returns:
A vector of SupportedFormat entries sorted by extension.
Signature:
Example:
Returns: List<SupportedFormat>
detectQrCodes()¶
Detect QR codes in the bytes of an ExtractedImage.
format_hint is currently unused — the image crate auto-detects the
container format from magic bytes — but the parameter is retained so future
backends (e.g. a WebP-via-webp-decoder variant) can use it without an API
break.
Returns an empty listtor on any of:
- Empty input.
- Image-decode failure.
- No QR grids detected.
- All detected grids fail to decode.
Successfully decoded QR codes carry their payload, a confidence of 1.0
(rqrr does not expose per-grid confidence; a successful decode is treated
as high-confidence by convention), and the pixel-space bounding box derived
from the four corner points of the grid.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
imageBytes |
ByteArray |
Yes | The image bytes |
formatHint |
String? |
No | The format hint |
Returns: List<QrCode>
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:
Example:
Returns: No return value.
Errors: Throws Error.
listEmbeddingBackends()¶
List the names of all registered embedding backends.
Used by kreuzberg-cli, the api/mcp endpoints, and generated language
bindings.
Signature:
Example:
Returns: List<String>
Errors: Throws Error.
listDocumentExtractors()¶
List names of all registered document extractors.
Signature:
Example:
Returns: List<String>
Errors: Throws Error.
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:
Example:
Returns: No return value.
Errors: Throws Error.
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:
Example:
Returns: List<String>
Errors: Throws Error.
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:
Example:
Returns: No return value.
Errors: Throws Error.
registerBuiltin()¶
Register every built-in post-processor enabled by the active feature set.
This is the single entry point that callers (including
register_default_post_processors) use to populate the global
post-processor registry with the in-tree built-ins. Each submodule's own
register function is gated by its feature flag so this aggregate stays
safe to call on any target.
Signature:
Example:
Returns: No return value.
Errors: Throws Error.
listPostProcessors()¶
List all registered post-processor names.
Returns a vector of all post-processor names currently registered in the global registry.
Returns:
Ok(List<String>)- Vector of post-processor namesErr(...)if the registry lock is poisoned
Signature:
Example:
Returns: List<String>
Errors: Throws Error.
clearPostProcessors()¶
Remove all registered post-processors.
Signature:
Example:
Returns: No return value.
Errors: Throws Error.
listRenderers()¶
List names of all registered renderers.
Errors:
Returns an error if the registry lock is poisoned.
Signature:
Example:
Returns: List<String>
Errors: Throws Error.
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:
Example:
Returns: No return value.
Errors: Throws Error.
clearRerankerBackends()¶
Clear all reranker 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.
Since v5.0.
Signature:
Example:
Returns: No return value.
Errors: Throws Error.
listRerankerBackends()¶
List the names of all registered reranker backends.
Used by kreuzberg-cli, the api/mcp endpoints, and generated language
bindings.
Since v5.0.
Signature:
Example:
Returns: List<String>
Errors: Throws Error.
listValidators()¶
List names of all registered validators.
Signature:
Example:
Returns: List<String>
Errors: Throws Error.
clearValidators()¶
Remove all registered validators.
Signature:
Example:
Returns: No return value.
Errors: Throws Error.
classifyPages()¶
Run page classification against an extraction result.
Mutates result.page_classifications with one entry per non-empty page and
appends every LLM call's usage to result.llm_usage.
Errors:
Returns the first error encountered when rendering the prompt or calling the LLM. Partially produced classifications are discarded so callers do not see a half-populated vector.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
result |
ExtractionResult |
Yes | The extraction result |
config |
PageClassificationConfig |
Yes | The configuration options |
Returns: No return value.
Errors: Throws Error.
classifyText()¶
Classify a single piece of text without requiring an ExtractionResult.
Use this when the caller already has plain text (e.g. a RAG ingest pipeline receiving documents off a queue) and wants a label list back without manufacturing extractor-side metadata.
Errors:
Same as classify_pages: a validation error when config.labels is empty,
or any error returned by prompt rendering or the underlying LLM call.
Signature:
@Throws(Error::class)
fun classifyText(text: String, config: PageClassificationConfig): List<ClassificationLabel>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text |
config |
PageClassificationConfig |
Yes | The configuration options |
Returns: List<ClassificationLabel>
Errors: Throws Error.
classifyDocument()¶
Classify a single document (as multiple pages or a single text block).
Aggregates classifications across all pages in the provided text, returning a combined label set that represents the document as a whole.
using the configured LLM, and results are aggregated.
config- Classification configuration including labels and LLM settings.
Returns:
A vector of ClassificationLabel entries representing the document's overall classification.
Errors:
Returns an error if config.labels is empty or if LLM calls fail.
Signature:
@Throws(Error::class)
fun classifyDocument(pages: List<String>, config: PageClassificationConfig): List<ClassificationLabel>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
pages |
List<String> |
Yes | Slice of page texts to classify. Each page is classified independently |
config |
PageClassificationConfig |
Yes | Classification configuration including labels and LLM settings. |
Returns: List<ClassificationLabel>
Errors: Throws Error.
downloadModel()¶
Eagerly download a NER model into the kreuzberg cache.
name is a HuggingFace repo id (e.g. urchade/gliner_multi-v2.1). The
CLI flag kreuzberg warm --ner delegates here.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
cacheDir |
Path? |
No | The cache dir |
Returns: Path
Errors: Throws Error.
downloadModel()¶
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
cacheDir |
Path? |
No | The cache dir |
Returns: Path
Errors: Throws Error.
defaultModelName()¶
Pinned default NER model identifier.
Signature:
Example:
Returns: String
defaultModelName()¶
Signature:
Example:
Returns: String
knownModels()¶
All NER models kreuzberg knows about (used by --all-ner-models).
Signature:
Example:
Returns: List<String>
knownModels()¶
Signature:
Example:
Returns: List<String>
downloadModel()¶
Download a NER model into the kreuzberg cache.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
cacheDir |
Path? |
No | The cache dir |
Returns: Path
Errors: Throws Error.
defaultModelName()¶
Default NER model identifier.
Signature:
Example:
Returns: String
knownModels()¶
All NER models kreuzberg knows about.
Signature:
Example:
Returns: List<String>
redact()¶
Run pattern redaction (and optional NER-driven redaction) over result and
rewrite every textual field. Populates result.redaction_report.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
result |
ExtractionResult |
Yes | The extraction result |
config |
RedactionConfig |
Yes | The configuration options |
Returns: No return value.
Errors: Throws Error.
summarize()¶
Score and return the top-N sentences from text, joined in original order.
language is an ISO 639 (or locale) code used to pick a stopword list;
pass null (or an unknown code) to fall back to English.
max_tokens bounds the summary length by whitespace-separated tokens;
null falls back to DEFAULT_MAX_TOKENS.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text |
language |
String? |
No | The language |
maxTokens |
Int? |
No | The max tokens |
Returns: String?
tokenCount()¶
Count whitespace-separated tokens (used for token-budget bookkeeping by callers).
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text |
Returns: Int
translateResult()¶
Translate the extraction result in place.
Populates result.translation with the translated content, optionally the
translated formatted_content (when preserve_markup = true), and rewrites
every chunk's content field. Every LLM call's usage is appended to
result.llm_usage.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
result |
ExtractionResult |
Yes | The extraction result |
config |
TranslationConfig |
Yes | The configuration options |
Returns: No return value.
Errors: Throws Error.
findFootnoteAnchors()¶
Find all footnote anchor references in markdown text.
Returns a vector of footnote anchors ([^label] use-sites), including byte offsets.
Footnote definitions ([^label]: ...) are NOT included in the results.
Returns:
A vector of FootnoteAnchor entries, each with the label and byte offset.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
markdown |
String |
Yes | The markdown text to search |
Returns: List<FootnoteAnchor>
parseFootnoteDefinitions()¶
Parse footnote definitions from markdown text.
Returns a vector of footnote definitions found in the markdown. Handles multi-line definitions with continuation/indented lines (CommonMark format).
Returns:
A vector of FootnoteDefinition entries, each with label, content, and byte offset.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
markdown |
String |
Yes | The markdown text to search |
Returns: List<FootnoteDefinition>
findInferenceMarkers()¶
Find inference markers in markdown text.
Returns byte offsets of every [*inference*] marker found in the text.
Returns:
A vector of byte offsets where inference markers appear.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
markdown |
String |
Yes | The markdown text to search |
Returns: List<Long>
findUnmarkedClaims()¶
Find unmarked claims in markdown text.
Returns lines that assert a claim but carry neither a footnote citation anchor ([^...])
nor an inference marker ([*inference*]).
The heuristic is simple: a line that contains alphabetic words, ends with sentence punctuation,
and is not a heading, blank line, or markup-only line is considered a claim.
Exclude lines that appear in the citation block (after --- + <!-- citations ... -->).
Returns:
A vector of trimmed line text strings for unmarked claims.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
markdown |
String |
Yes | The markdown text to search |
Returns: List<String>
parseCitations()¶
Parse the structured citation block from markdown.
Extracts citations from the block after a --- thematic break followed by
<!-- citations ... --> comment. Parses each entry as:
[^srcN]: <source>, <optional-locator>, excerpt: "<text>"
Returns parsed citations with source, optional locator, and optional excerpt.
Returns:
A vector of Citation entries parsed from the citation block.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
markdown |
String |
Yes | The markdown text to search |
Returns: List<Citation>
verifyExcerpt()¶
Verify that an excerpt appears verbatim in source text.
Performs exact matching by default. Also tries whitespace-normalized matching (collapsing runs of whitespace on both sides) since PDF-extracted text often has irregular spacing.
Returns:
true if the excerpt appears (exactly or with normalized whitespace), false otherwise.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
excerpt |
String |
Yes | The text snippet to find |
sourceText |
String |
Yes | The full source text to search |
Returns: Boolean
chunkForRag()¶
Chunk text for RAG retrieval, ensuring every chunk carries a heading_path.
Delegates to chunk_text using the caller's config (defaulting to
ChunkerType.Markdown when the config uses the default Text type, so that
heading hierarchy is resolved). After chunking, derives
ChunkMetadata.heading_path from each chunk's heading_context.
underlying splitter; use ChunkerType.Markdown for documents with ATX
headings.
Returns:
A ChunkingResult where every chunk's heading_path is populated from its
heading_context (empty when the chunk is not under any heading).
Errors:
Propagates any error from the underlying chunker (e.g. invalid overlap).
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text |
config |
ChunkingConfig |
Yes | The configuration options |
Returns: ChunkingResult
Errors: Throws Error.
compare()¶
Compare two extraction results and return a structured diff.
The comparison is purely structural — no I/O, no side effects. All fields
of ExtractionDiff are populated according to the provided DiffOptions.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
a |
ExtractionResult |
Yes | The extraction result |
b |
ExtractionResult |
Yes | The extraction result |
opts |
DiffOptions |
Yes | The options to use |
Returns: ExtractionDiff
extractRegionWithVlm()¶
Extract content from a pre-cropped image region using a VLM.
The caller is responsible for cropping the page image to the region's bounding
box before calling this function. The image_bytes parameter must contain the
raw bytes of the cropped region image (JPEG, PNG, WebP, etc.).
Returns:
Extracted Markdown text from the VLM, or an error if the VLM call fails.
Errors:
Ocrif the VLM call fails or returns no content.MissingDependencyif the liter-llm client cannot be initialised.
Signature:
@Throws(Error::class)
fun extractRegionWithVlm(imageBytes: ByteArray, imageMime: String, regionKind: RegionKind, llmConfig: LlmConfig, customPrompt: String? = null): String
Example:
val result = extractRegionWithVlm("data".toByteArray(), "value", RegionKind(), LlmConfig(), "value")
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
imageBytes |
ByteArray |
Yes | The image bytes |
imageMime |
String |
Yes | The image mime |
regionKind |
RegionKind |
Yes | The region kind |
llmConfig |
LlmConfig |
Yes | The llm config |
customPrompt |
String? |
No | The custom prompt |
Returns: String
Errors: Throws Error.
rerankAsync()¶
Rerank documents asynchronously.
Async counterpart to rerank. Offloads blocking ONNX inference to a
dedicated blocking thread pool via Tokio's spawn_blocking, keeping the
async executor free.
Since v5.0.
Signature:
@Throws(Error::class)
fun rerankAsync(query: String, documents: List<String>, config: RerankerConfig): List<RerankedDocument>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
query |
String |
Yes | The query |
documents |
List<String> |
Yes | The documents |
config |
RerankerConfig |
Yes | The configuration options |
Returns: List<RerankedDocument>
Errors: Throws Error.
extractKeywords()¶
Extract keywords from text using the specified algorithm.
This is the unified entry point for keyword extraction. The algorithm
used is determined by config.algorithm.
Returns:
A vector of keywords sorted by relevance (highest score first).
Errors:
Returns an error if:
- The specified algorithm feature is not enabled
- Keyword extraction fails
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text to extract keywords from |
config |
KeywordConfig |
Yes | Keyword extraction configuration |
Returns: List<Keyword>
Errors: Throws Error.
analyzeDocument()¶
Analyze a document and determine the optimal chunking strategy.
Decision logic (in priority order):
- If user provides
disable_chunking→ no chunking - If user provides page_ranges → use user overrides
- If chunking is not enabled → no chunking
- If format doesn't support chunking → no chunking
- If file is small (below both thresholds) and not force_chunking → no chunking
-
If PDF has a substantial text layer AND !force_ocr → no chunking (only when
heuristics-pdffeature is enabled; otherwise skipped) -
Otherwise → chunk the document
Errors:
Returns an error only when the heuristics-pdf feature is active and
the PDF text-layer analysis itself returns a hard error. In all other
cases the function returns a ChunkingDecision.
Signature:
@Throws(Error::class)
fun analyzeDocument(metadata: DocumentMetadata, config: HeuristicsConfig, documentBytes: ByteArray? = null): ChunkingDecision
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
metadata |
DocumentMetadata |
Yes | The document metadata |
config |
HeuristicsConfig |
Yes | The configuration options |
documentBytes |
ByteArray? |
No | The document bytes |
Returns: ChunkingDecision
Errors: Throws Error.
analyzeWithUserChunks()¶
Analyze a document with user-specified chunk ranges.
Creates a chunk plan based on user-provided page ranges.
Signature:
fun analyzeWithUserChunks(userRanges: List<PageRange>, totalPages: Int, sizeBytes: Long, config: HeuristicsConfig): ChunkingDecision
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
userRanges |
List<PageRange> |
Yes | The user ranges |
totalPages |
Int |
Yes | The total pages |
sizeBytes |
Long |
Yes | The size bytes |
config |
HeuristicsConfig |
Yes | The configuration options |
Returns: ChunkingDecision
scoreConfidence()¶
Score a ConfidenceSignals triple into an ExtractionConfidence using
the supplied weights.
When signals.ocr_aggregate is null, the OCR weight folds into
text_coverage so the weighted sum still totals 1.0.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
signals |
ConfidenceSignals |
Yes | The confidence signals |
weights |
ConfidenceWeights |
Yes | The confidence weights |
Returns: ExtractionConfidence
checkFormatLimits()¶
Decision returned for pre-extraction rejection based on XLSX/PPTX-specific
resource bounds. Returns Some(reason) to reject; null to proceed.
Callers must provide counts from a pre-extraction peek (e.g. parsing
xl/workbook.xml for sheet count).
Signature:
fun checkFormatLimits(mimeType: String, sheetCount: Int? = null, workbookCells: Long? = null, embeddedCount: Int? = null, config: HeuristicsConfig): String?
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
mimeType |
String |
Yes | The mime type |
sheetCount |
Int? |
No | The sheet count |
workbookCells |
Long? |
No | The workbook cells |
embeddedCount |
Int? |
No | The embedded count |
config |
HeuristicsConfig |
Yes | The configuration options |
Returns: String?
boundariesFromExtractionResult()¶
Derive document boundaries from an already-produced ExtractionResult.
Builds a MultidocInput from result.pages (one PageSignals per
PageContent entry), then delegates to detect_boundaries.
Fallback behaviour¶
- If
result.pagesisnullor empty the whole document is treated as a single document: returns[Start(1), End(1)], matching the contract ofdetect_boundariesfor a one-page input.
Text density¶
PageContent does not carry a pre-computed density score.
This function approximates density as
non_whitespace_chars / total_chars (clamped to [0.0, 1.0]), which is a
reasonable proxy for how text-dense a page is relative to itself. Pass a
custom MultidocInput to detect_boundaries directly when you need a
higher-fidelity density measurement (e.g. chars-per-pt² from a PDF extractor).
Signature:
fun boundariesFromExtractionResult(result: ExtractionResult, thresholds: MultidocThresholds): List<DocumentBoundary>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
result |
ExtractionResult |
Yes | The extraction result |
thresholds |
MultidocThresholds |
Yes | The multidoc thresholds |
Returns: List<DocumentBoundary>
detectBoundaries()¶
Detect document boundaries in a multi-document PDF.
Returns a list of detected boundaries, always including implicit boundaries
at start (page 1) and end (page_count). Boundaries are returned in ascending
order of start_page.
Returns:
Ordered list of document boundaries.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
input |
MultidocInput |
Yes | Page signals for the PDF |
thresholds |
MultidocThresholds |
Yes | Detection thresholds |
Returns: List<DocumentBoundary>
chooseCallMode()¶
Decide which call mode best fits this document.
Rules applied in order:
image/*→StructuredCallMode.VisionOnly(no text layer to start from).-
application/pdf→StructuredCallMode.TextOnlyregardless oftext_coverageor embedded image count. Kreuzberg's OCR + text-layer extraction produces text for scanned PDFs; the orchestrator's post-call confidence gate handles any vision escalation actually needed. -
DOCX /
text/html/text/*/application/json/application/xml/application/rtfwithavg_chars_per_page > docx_text_min_density→StructuredCallMode.TextOnly. -
Anything else →
StructuredCallMode.Skip.
After rule selection two post-rule promotions apply (in order):
-
user_force_visionpromotesTextOnly→TextPlusVision(SkipstaysSkip— caller meant to opt out). -
enable_vision_fallbackpromotesTextOnly→TextOnlyWithVisionFallback(does not upgradeTextPlusVisionorSkip).
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
input |
StructuredInput |
Yes | The input data |
t |
StructuredThresholds |
Yes | The structured thresholds |
Returns: StructuredCallMode
calculateChunkPlan()¶
Calculate a chunking plan for a document.
Returns:
A ChunkPlan with optimal chunk boundaries.
Signature:
fun calculateChunkPlan(pageCount: Int, sizeBytes: Long, needsOcr: Boolean, config: HeuristicsConfig): ChunkPlan
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
pageCount |
Int |
Yes | Total number of pages in the document |
sizeBytes |
Long |
Yes | File size in bytes |
needsOcr |
Boolean |
Yes | Whether OCR will be required |
config |
HeuristicsConfig |
Yes | Heuristics configuration |
Returns: ChunkPlan
calculatePlanFromOverrides()¶
Calculate a chunk plan from user-specified page ranges.
Validates and processes user overrides into a proper chunk plan.
Signature:
fun calculatePlanFromOverrides(userChunks: List<PageRange>, totalPages: Int, sizeBytes: Long, config: HeuristicsConfig): ChunkPlan
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
userChunks |
List<PageRange> |
Yes | The user chunks |
totalPages |
Int |
Yes | The total pages |
sizeBytes |
Long |
Yes | The size bytes |
config |
HeuristicsConfig |
Yes | The configuration options |
Returns: ChunkPlan
fingerprint()¶
Stable sha256 fingerprint of raw, formatted as sha256:<hex>.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
raw |
ByteArray |
Yes | The raw |
Returns: String
resolve()¶
Resolve (preset, custom_schema_override, context) into a ResolvedPreset.
custom_schemaoverridespreset.schemawhen set.contextsubstitutes{{key}}tokens inpreset.context_template; the rendered string is appended tosystem_promptso the model sees it.
Signature:
@Throws(ResolveError::class)
fun resolve(preset: Preset, customSchema: Any? = null, context: Map<String, String>): ResolvedPreset
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
preset |
Preset |
Yes | The preset |
customSchema |
Any? |
No | The custom schema |
context |
Map<String, String> |
Yes | The context |
Returns: ResolvedPreset
Errors: Throws ResolveError.
extractStructuredJson()¶
Extract structured JSON from a document using JSON-encoded preset spec and options.
This is the synchronous JSON-in / JSON-out entry point suitable for FFI and language-binding call paths.
cache). Pass "{}" to use all defaults.
Returns:
JSON-serialised StructuredOutput on success.
Errors:
Returns Validation when either JSON argument is
malformed. All other failures from the underlying
extract_structured_sync call are mapped onto KreuzbergError
via From<StructuredError>.
Signature:
@Throws(Error::class)
fun extractStructuredJson(bytes: ByteArray, mime: String, presetSpecJson: String, optionsJson: String): String
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
bytes |
ByteArray |
Yes | The bytes |
mime |
String |
Yes | The mime |
presetSpecJson |
String |
Yes | The preset spec json |
optionsJson |
String |
Yes | The options json |
Returns: String
Errors: Throws Error.
splitAndExtractJson()¶
Split a multi-document PDF and extract structured JSON from each segment,
returning a JSON array of StructuredOutput objects.
Non-PDF documents are passed through as a single-element array.
Same as extract_structured_json.
Returns:
JSON-serialised List<StructuredOutput> (a JSON array) on success.
Errors:
Returns Validation when either JSON argument is
malformed. All other failures from the underlying
split_and_extract_sync call are mapped onto KreuzbergError
via From<StructuredError>.
Signature:
@Throws(Error::class)
fun splitAndExtractJson(bytes: ByteArray, mime: String, presetSpecJson: String, optionsJson: String): String
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
bytes |
ByteArray |
Yes | The bytes |
mime |
String |
Yes | The mime |
presetSpecJson |
String |
Yes | The preset spec json |
optionsJson |
String |
Yes | The options json |
Returns: String
Errors: Throws Error.
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.
For pages with extreme dimensions (very wide vector diagrams, etc.) the effective DPI may be automatically reduced to avoid rasterizer failure. A warning is logged when this happens.
Errors:
Returns KreuzbergError.Parsing if the PDF cannot be opened, authenticated,
or rendered, or if page_index is out of range.
Signature:
@Throws(Error::class)
fun renderPdfPageToPng(pdfBytes: ByteArray, pageIndex: Long, dpi: Int? = null, password: String? = null): ByteArray
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
pdfBytes |
ByteArray |
Yes | Raw PDF file bytes |
pageIndex |
Long |
Yes | Zero-based page index |
dpi |
Int? |
No | Resolution in dots per inch (default: 150) |
password |
String? |
No | Optional password for encrypted PDFs |
Returns: ByteArray
Errors: Throws Error.
captionImage()¶
Caption a single image from bytes.
RegionKind.Caption prompt when null.
Returns:
The generated caption text.
Errors:
Returns an error if the VLM call fails or if image format detection fails.
Signature:
@Throws(Error::class)
fun captionImage(imageBytes: ByteArray, llmConfig: LlmConfig, customPrompt: String? = null): String
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
imageBytes |
ByteArray |
Yes | The image data. |
llmConfig |
LlmConfig |
Yes | LLM configuration for the VLM call. |
customPrompt |
String? |
No | Optional custom caption prompt. Uses the default |
Returns: String
Errors: Throws Error.
captionImageFile()¶
Caption a single image from a file path.
RegionKind.Caption prompt when null.
Returns:
The generated caption text.
Errors:
Returns an error if the file cannot be read, if image format detection fails, or if the VLM call fails.
Signature:
@Throws(Error::class)
fun captionImageFile(path: Path, llmConfig: LlmConfig, customPrompt: String? = null): String
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | Path to the image file. |
llmConfig |
LlmConfig |
Yes | LLM configuration for the VLM call. |
customPrompt |
String? |
No | Optional custom caption prompt. Uses the default |
Returns: String
Errors: Throws Error.
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
String |
Yes | Path to the file |
checkExists |
Boolean |
Yes | The check exists |
Returns: String
Errors: Throws Error.
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: EmbeddingPreset?
listEmbeddingPresets()¶
List the names of all available embedding presets.
Returns owned Strings so the values are safe to pass across FFI boundaries.
Signature:
Example:
Returns: List<String>
getEmbeddingPreset()¶
Returns null for builds without the embedding-presets feature.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: EmbeddingPreset?
listEmbeddingPresets()¶
Returns an empty list for builds without the embedding-presets feature.
Signature:
Example:
Returns: List<String>
rerank()¶
Rerank a list of documents by relevance to a query.
Returns documents sorted descending by score. Applies top_k truncation if
configured.
Errors:
KreuzbergError.Validationifqueryis empty or blank.KreuzbergError.MissingDependencyif ONNX Runtime is not installed (ONNX path).KreuzbergError.Rerankingif the preset is unknown or model download fails.
Since v5.0.
Signature:
@Throws(Error::class)
fun rerank(query: String, documents: List<String>, config: RerankerConfig): List<RerankedDocument>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
query |
String |
Yes | The query |
documents |
List<String> |
Yes | The documents |
config |
RerankerConfig |
Yes | The configuration options |
Returns: List<RerankedDocument>
Errors: Throws Error.
rerank()¶
Stub for builds without the reranker feature — keeps the symbol available
on no-ORT targets (Android x86_64 emulator, WASM) so language bindings compile.
Since v5.0.
Signature:
@Throws(Error::class)
fun rerank(query: String, documents: List<String>, config: RerankerConfig): List<RerankedDocument>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
query |
String |
Yes | The query |
documents |
List<String> |
Yes | The documents |
config |
RerankerConfig |
Yes | The reranker config |
Returns: List<RerankedDocument>
Errors: Throws Error.
rerankAsync()¶
Stub for builds without the reranker feature.
Since v5.0.
Signature:
@Throws(Error::class)
fun rerankAsync(query: String, documents: List<String>, config: RerankerConfig): List<RerankedDocument>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
query |
String |
Yes | The query |
documents |
List<String> |
Yes | The documents |
config |
RerankerConfig |
Yes | The reranker config |
Returns: List<RerankedDocument>
Errors: Throws Error.
getRerankerPreset()¶
Get a reranker 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.
Since v5.0.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: RerankerPreset?
listRerankerPresets()¶
List the names of all available reranker presets.
Returns owned Strings so the values are safe to pass across FFI boundaries.
Since v5.0.
Signature:
Example:
Returns: List<String>
getRerankerPreset()¶
Returns null for builds without the reranker-presets feature.
Since v5.0.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
name |
String |
Yes | The name |
Returns: RerankerPreset?
listRerankerPresets()¶
Returns an empty list for builds without the reranker-presets feature.
Since v5.0.
Signature:
Example:
Returns: List<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 |
Int |
— | 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 |
Int |
— | Total number of files in the archive |
fileList |
List<String> |
\[\] |
List of file paths within the archive |
totalSize |
Long |
— | Total uncompressed size in bytes |
compressedSize |
Long? |
null |
Compressed size in bytes (if available) |
AudioMetadata¶
Audio/video file metadata.
Populated from container tags (ID3v2, MP4 atoms, Vorbis comments, etc.) and
PCM decode properties. Available when the transcription-types feature is enabled.
| Field | Type | Default | Description |
|---|---|---|---|
durationMs |
Long? |
null |
Duration in milliseconds derived from the decoded audio stream. |
codec |
String? |
null |
Audio codec (e.g. "mp3", "aac", "opus", "flac"). |
container |
String? |
null |
Container format (e.g. "mpeg", "mp4", "ogg", "wav"). |
sampleRateHz |
Int? |
null |
Sample rate in Hz after decode (always 16000 when resampled for Whisper). |
channels |
Short? |
null |
Number of audio channels (1 = mono, 2 = stereo). |
bitrate |
Int? |
null |
Audio bitrate in kbps from the source file tags/properties. |
BBox¶
Bounding box in original image coordinates (x1, y1) top-left, (x2, y2) bottom-right.
| Field | Type | Default | Description |
|---|---|---|---|
x1 |
Float |
— | Left edge (x-coordinate of the top-left corner). |
y1 |
Float |
— | Top edge (y-coordinate of the top-left corner). |
x2 |
Float |
— | Right edge (x-coordinate of the bottom-right corner). |
y2 |
Float |
— | Bottom edge (y-coordinate of the bottom-right corner). |
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 |
ByteArray |
— | The content bytes to extract from |
mimeType |
String |
— | MIME type of the content (e.g., "application/pdf", "text/html") |
config |
FileExtractionConfig? |
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 |
Path |
— | Path to the file to extract from |
config |
FileExtractionConfig? |
null |
Per-file configuration overrides (None uses batch-level defaults) |
BibtexMetadata¶
BibTeX bibliography metadata.
| Field | Type | Default | Description |
|---|---|---|---|
entryCount |
Long |
— | Number of entries in the bibliography. |
citationKeys |
List<String> |
\[\] |
BibTeX citation keys (e.g. "knuth1984") for all entries. |
authors |
List<String> |
\[\] |
Author names collected across all bibliography entries. |
yearRange |
YearRange? |
null |
Earliest and latest publication years found in the bibliography. |
entryTypes |
Map<String, Long>? |
{} |
Count of entries grouped by BibTeX entry type (e.g. "article" → 5). |
BoundingBox¶
Bounding box coordinates for element positioning.
| Field | Type | Default | Description |
|---|---|---|---|
x0 |
Double |
— | Left x-coordinate |
y0 |
Double |
— | Bottom y-coordinate |
x1 |
Double |
— | Right x-coordinate |
y1 |
Double |
— | Top y-coordinate |
CacheStats¶
Aggregate statistics for a kreuzberg cache directory.
| Field | Type | Default | Description |
|---|---|---|---|
totalFiles |
Long |
— | Total number of files currently in the cache directory. |
totalSizeMb |
Double |
— | Combined size of all cache files in megabytes. |
availableSpaceMb |
Double |
— | Free disk space available on the cache volume, in megabytes. |
oldestFileAgeDays |
Double |
— | Age of the oldest cache file in days (0.0 if the cache is empty). |
newestFileAgeDays |
Double |
— | Age of the most recently written cache file in days (0.0 if the cache is empty). |
CaptioningConfig¶
Since: v5.0
Configuration for the VLM captioning post-processor.
| Field | Type | Default | Description |
|---|---|---|---|
llm |
LlmConfig |
— | LLM configuration used for the VLM call. |
prompt |
String? |
null |
Optional custom caption prompt. null uses the default RegionKind.Caption prompt that ships with crate.llm.region_extractor. |
minImageArea |
Int |
serde(default = "default_min_image_area") |
Skip images whose width * height is below this threshold (in pixels). Default 1_000 filters out icons and decorations. |
CaptioningEnrichmentConfig¶
Captioning enrichment knob: which LLM to use for image captions.
The enrichment stage calls caption_image for every
image in ExtractionResult.images that has non-empty data. Images with
empty byte data (e.g. reference-only images populated via source_path) are
skipped rather than forwarded to the VLM.
| Field | Type | Default | Description |
|---|---|---|---|
config |
LlmConfig |
— | LLM / VLM configuration forwarded verbatim to each caption_image call. |
customPrompt |
String? |
null |
Optional custom prompt override forwarded to every caption_image call. null uses the default RegionKind.Caption prompt. |
CellChange¶
A single changed cell within a table.
Defined here (rather than only in crate.diff) so RevisionDelta can
reference it unconditionally, without requiring the diff Cargo feature.
crate.diff re-exports this type verbatim.
| Field | Type | Default | Description |
|---|---|---|---|
row |
Long |
— | Zero-based row index. |
col |
Long |
— | Zero-based column index. |
from |
String |
— | Value before the change. |
to |
String |
— | Value after the change. |
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 |
List<Float>? |
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. |
ChunkInfo¶
Information about a single chunk.
| Field | Type | Default | Description |
|---|---|---|---|
index |
Int |
— | Zero-based chunk index. |
pages |
PageRange |
— | Page range for this chunk. |
estimatedTimeMs |
Long |
— | Estimated processing time for this chunk in milliseconds. |
ChunkMetadata¶
Metadata about a chunk's position in the original document.
| Field | Type | Default | Description |
|---|---|---|---|
byteStart |
Long |
— | Byte offset where this chunk starts in the original text (UTF-8 valid boundary). |
byteEnd |
Long |
— | Byte offset where this chunk ends in the original text (UTF-8 valid boundary). |
tokenCount |
Long? |
null |
Number of tokens in this chunk (if available). This is calculated by the embedding model's tokenizer if embeddings are enabled. |
chunkIndex |
Long |
— | Zero-based index of this chunk in the document. |
totalChunks |
Long |
— | Total number of chunks in the document. |
firstPage |
Int? |
null |
First page number this chunk spans (1-indexed). Only populated when page tracking is enabled in extraction configuration. |
lastPage |
Int? |
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? |
/* serde(default) */ |
Heading context when using Markdown chunker. Contains the heading hierarchy this chunk falls under. Only populated when ChunkerType.Markdown is used. |
headingPath |
List<String> |
/* serde(default) */ |
Flattened heading trail from document root to this chunk's section. Each element is a heading's text, outermost first. Derived from heading_context when present; empty otherwise. Provides a binding-friendly, RAG-shaped breadcrumb without requiring callers to walk the nested HeadingContext structure. |
imageIndices |
List<Int> |
/* 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. |
ChunkPlan¶
Complete chunking plan for a document.
| Field | Type | Default | Description |
|---|---|---|---|
totalChunks |
Int |
0 |
Total number of chunks. |
chunks |
List<ChunkInfo> |
\[\] |
Individual chunk information. |
totalEstimatedTimeMs |
Long |
0 |
Estimated total processing time in milliseconds. |
useDiskProcessing |
Boolean |
false |
Whether to use disk-based processing for large files. |
reason |
ChunkingReason |
ChunkingReason.LargeFile |
Reason for chunking. |
Methods¶
default()¶
An empty plan (no chunks). The reason is a placeholder since an empty plan
has no chunking rationale; callers always overwrite it when a real plan is built.
Signature:
Example:
Returns: ChunkPlan
totalPages()¶
Get the total number of pages across all chunks.
Signature:
Example:
Returns: Int
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 |
Long |
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 |
Long |
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 |
Optional embedding configuration for chunk embeddings. |
preset |
String? |
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 |
Float? |
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. |
tableChunking |
TableChunkingMode |
TableChunkingMode.Split |
How to handle markdown tables that exceed the chunk size limit. Only applies when chunker_type is Markdown. - Split (default) — tables are split at row boundaries; continuation chunks do not repeat the header. - RepeatHeader — the table header row and separator are prepended to every continuation chunk so each chunk is self-contained. Default: Split |
Methods¶
default()¶
Signature:
Example:
Returns: ChunkingConfig
ChunkingResult¶
Result of a text chunking operation.
Contains the generated chunks and metadata about the chunking.
| Field | Type | Default | Description |
|---|---|---|---|
chunks |
List<Chunk> |
— | List of text chunks |
chunkCount |
Long |
— | Total number of chunks generated |
Citation¶
A structured citation from a citation block.
Parsed from entries like:
[^srcN]: source, locator, excerpt: "text"
| Field | Type | Default | Description |
|---|---|---|---|
label |
String |
— | The label of the citation (e.g., "src1" in \[^src1\]: ...). |
source |
String |
— | The source reference (path, URL, or identifier). |
locator |
String? |
null |
Optional locator within the source (e.g., "page 3" or "section 2.1"). |
excerpt |
String? |
null |
Optional excerpt — quoted text from the source. |
CitationMetadata¶
Citation file metadata (RIS, PubMed, EndNote).
| Field | Type | Default | Description |
|---|---|---|---|
citationCount |
Long |
— | Total number of citation records in the file. |
format |
String? |
null |
Detected citation file format (e.g. "ris", "pubmed", "endnote"). |
authors |
List<String> |
\[\] |
Author names collected across all citation records. |
yearRange |
YearRange? |
null |
Earliest and latest publication years found in the file. |
dois |
List<String> |
\[\] |
DOI identifiers found in the citation records. |
keywords |
List<String> |
\[\] |
Keywords collected from all citation records. |
ClassificationEnrichmentConfig¶
Classification enrichment knob: how to label the document.
| Field | Type | Default | Description |
|---|---|---|---|
config |
PageClassificationConfig |
— | Label set and LLM settings for the classification stage. |
ClassificationLabel¶
A single label + confidence pair.
| Field | Type | Default | Description |
|---|---|---|---|
label |
String |
— | Label name as configured in PageClassificationConfig.labels. |
confidence |
Float? |
null |
Backend-reported confidence in \[0.0, 1.0\]. null when the backend (e.g. an LLM prompt without explicit confidence schema) did not report one. |
ConfidenceSignals¶
Input signals for confidence scoring.
Caller fills these from the extraction result and the LLM response.
| Field | Type | Default | Description |
|---|---|---|---|
textCoverage |
Float |
— | Fraction of pages with usable text in \[0, 1\]. |
ocrAggregate |
Float? |
null |
Mean OCR per-element recognition confidence; null when OCR did not run. |
schemaCompliance |
SchemaCompliance |
— | Schema-validation result of the merged output. |
Methods¶
fromExtractionResult()¶
Build ConfidenceSignals from an ExtractionResult.
result— The extraction result whoseocr_elementsare inspected.schema_compliance— Caller-supplied schema validation outcome.text_coverage— Caller-supplied fraction of pages with usable text (e.g. 1.0 for native text formats, value from PDF analysis for PDFs).
The ocr_aggregate is computed as the arithmetic mean of all
ocr_elements[].confidence.recognition values. When ocr_elements is
null or empty the field is set to null.
Signature:
@JvmStatic
fun fromExtractionResult(result: ExtractionResult, schemaCompliance: SchemaCompliance, textCoverage: Float): ConfidenceSignals
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
result |
ExtractionResult |
Yes | The extraction result |
schemaCompliance |
SchemaCompliance |
Yes | The schema compliance |
textCoverage |
Float |
Yes | The text coverage |
Returns: ConfidenceSignals
ConfidenceWeights¶
Tunable weights for the confidence scoring formula.
Defaults picked by inspection; callers tune them via config.
| Field | Type | Default | Description |
|---|---|---|---|
textCoverage |
Float |
0.3 |
Weight assigned to text_coverage. Default 0.30. |
ocrAggregate |
Float |
0.3 |
Weight assigned to ocr_aggregate when OCR ran. Default 0.30 — folds into text_coverage weight when OCR did not run. |
schemaCompliance |
Float |
0.4 |
Weight assigned to schema_compliance. Default 0.40. |
Methods¶
default()¶
Signature:
Example:
Returns: ConfidenceWeights
isNormalized()¶
Validate that weights sum to approximately 1.0.
Signature:
Example:
Returns: Boolean
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:
Example:
Returns: ContentFilterConfig
ContributorRole¶
JATS contributor with role.
| Field | Type | Default | Description |
|---|---|---|---|
name |
String |
— | Contributor display name. |
role |
String? |
null |
Contributor role (e.g. "author", "editor"). |
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 |
Document title |
subject |
String? |
null |
Document subject/topic |
creator |
String? |
null |
Document creator/author |
keywords |
String? |
null |
Keywords or tags |
description |
String? |
null |
Document description/abstract |
lastModifiedBy |
String? |
null |
User who last modified the document |
revision |
String? |
null |
Revision number |
created |
String? |
null |
Creation timestamp (ISO 8601) |
modified |
String? |
null |
Last modification timestamp (ISO 8601) |
category |
String? |
null |
Document category |
contentStatus |
String? |
null |
Content status (Draft, Final, etc.) |
language |
String? |
null |
Document language |
identifier |
String? |
null |
Unique identifier |
version |
String? |
null |
Document version |
lastPrinted |
String? |
null |
Last print timestamp (ISO 8601) |
CsvMetadata¶
CSV/TSV file metadata.
| Field | Type | Default | Description |
|---|---|---|---|
rowCount |
Int |
— | Total number of data rows (excluding the header row if present). |
columnCount |
Int |
— | Number of columns detected. |
delimiter |
String? |
null |
Field delimiter character (e.g. "," or "\t"). |
hasHeader |
Boolean |
— | Whether the first row was treated as a header. |
columnTypes |
List<String>? |
\[\] |
Inferred data type for each column (e.g. "string", "integer", "float"). |
DbfFieldInfo¶
dBASE field information.
| Field | Type | Default | Description |
|---|---|---|---|
name |
String |
— | Field (column) name. |
fieldType |
String |
— | dBASE field type character (e.g. "C" for character, "N" for numeric). |
DbfMetadata¶
dBASE (DBF) file metadata.
| Field | Type | Default | Description |
|---|---|---|---|
recordCount |
Long |
— | Total number of data records in the DBF file. |
fieldCount |
Long |
— | Number of field (column) definitions. |
fields |
List<DbfFieldInfo> |
\[\] |
Descriptor for each field in the table schema. |
DetectResponse¶
MIME type detection response.
| Field | Type | Default | Description |
|---|---|---|---|
mimeType |
String |
— | Detected MIME type |
filename |
String? |
null |
Original filename (if provided) |
DetectionResult¶
Page-level detection result containing all detections and page metadata.
| Field | Type | Default | Description |
|---|---|---|---|
pageWidth |
Int |
— | Page width in pixels (as seen by the model). |
pageHeight |
Int |
— | Page height in pixels (as seen by the model). |
detections |
List<LayoutDetection> |
— | All layout detections on this page after postprocessing. |
DiffHunk¶
A single contiguous hunk in a unified diff.
| Field | Type | Default | Description |
|---|---|---|---|
fromLine |
Long |
— | Starting line number in the old content (0-indexed). |
fromCount |
Long |
— | Number of lines from the old content in this hunk. |
toLine |
Long |
— | Starting line number in the new content (0-indexed). |
toCount |
Long |
— | Number of lines from the new content in this hunk. |
lines |
List<DiffLine> |
— | Lines that make up this hunk. |
DiffOptions¶
Options controlling how two ExtractionResult values are compared.
| Field | Type | Default | Description |
|---|---|---|---|
includeMetadata |
Boolean |
true |
Include metadata changes in the diff. Default: true. |
includeEmbedded |
Boolean |
true |
Include embedded-children changes in the diff. Default: true. |
maxContentChars |
Long? |
null |
Truncate content to this many characters before diffing. Useful for very large documents where only the first N characters matter. null means no truncation. |
Methods¶
default()¶
Signature:
Example:
Returns: DiffOptions
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 |
List<FormattedBlock> |
— | Structured block-level content |
metadata |
Metadata |
— | Metadata from YAML frontmatter |
tables |
List<Table> |
— | Extracted tables as structured data |
images |
List<DjotImage> |
— | Extracted images with metadata |
links |
List<DjotLink> |
— | Extracted links with URLs |
footnotes |
List<Footnote> |
— | Footnote definitions |
DjotImage¶
Image element in Djot.
| Field | Type | Default | Description |
|---|---|---|---|
src |
String |
— | Image source URL or path |
alt |
String |
— | Alternative text |
title |
String? |
null |
Optional title |
DjotLink¶
Link element in Djot.
| Field | Type | Default | Description |
|---|---|---|---|
url |
String |
— | Link URL |
text |
String |
— | Link text content |
title |
String? |
null |
Optional title |
DocumentBoundary¶
Detected document boundary within a PDF.
| Field | Type | Default | Description |
|---|---|---|---|
startPage |
Int |
— | 1-indexed start page (inclusive). |
endPage |
Int |
— | 1-indexed end page (inclusive). |
confidence |
Float |
— | Confidence in this boundary, \[0.0, 1.0\]. |
reason |
BoundaryReason |
— | Reason for the boundary detection. |
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:
@Throws(Error::class)
fun extractBytes(content: ByteArray, mimeType: String, config: ExtractionConfig): InternalDocument
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content |
ByteArray |
Yes | Raw document bytes |
mimeType |
String |
Yes | MIME type of the document (already validated) |
config |
ExtractionConfig |
Yes | Extraction configuration |
Returns: InternalDocument
Errors: Throws Error.
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:
@Throws(Error::class)
fun extractFile(path: Path, mimeType: String, config: ExtractionConfig): InternalDocument
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | Path to the document file |
mimeType |
String |
Yes | MIME type of the document (already validated) |
config |
ExtractionConfig |
Yes | Extraction configuration |
Returns: InternalDocument
Errors: Throws Error.
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:
Example:
Returns: List<String>
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:
Example:
Returns: Int
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | The path |
mimeType |
String |
Yes | The mime type |
Returns: Boolean
DocumentMetadata¶
Metadata about a document for analysis.
| Field | Type | Default | Description |
|---|---|---|---|
mimeType |
String |
— | MIME type of the document. |
sizeBytes |
Long |
— | File size in bytes. |
pageCount |
Int? |
null |
Page count (if known, e.g., from previous analysis). |
forceOcr |
Boolean |
— | Whether OCR is forced regardless of text layer. |
userChunkConfig |
UserChunkConfig? |
null |
User-provided chunk configuration overrides. |
chunkingEnabled |
Boolean |
— | Whether chunking is enabled for this job. |
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 |
|---|---|---|---|
content |
NodeContent |
— | Node content — tagged enum, type-specific data only. |
parent |
Int? |
null |
Parent node index (null = root-level node). |
children |
List<Int> |
/* serde(default) */ |
Child node indices in reading order. |
contentLayer |
ContentLayer |
/* serde(default) */ |
Content layer classification. Always serialised — Kotlin-Android (and any other typed binding) treats the field as non-nullable, so omitting it from the JSON wire would break consumer deserialisation. #\[serde(default)\] covers the missing-field case on inbound JSON. |
page |
Int? |
null |
Page number where this node starts (1-indexed). |
pageEnd |
Int? |
null |
Page number where this node ends (for multi-page tables/sections). |
bbox |
BoundingBox? |
null |
Bounding box in document coordinates. |
annotations |
List<TextAnnotation> |
/* serde(default) */ |
Inline annotations (formatting, links) on this node's text content. Only meaningful for text-carrying nodes; empty for containers. |
attributes |
Map<String, String>? |
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 |
Int |
— | Source node index (the referencing node). |
target |
Int |
— | Target node index (the referenced node). |
kind |
RelationshipKind |
— | Semantic kind of the relationship. |
DocumentRevision¶
A single tracked change embedded in a document.
Populated by per-format extractors that understand change-tracking metadata
(DOCX w:ins/w:del/w:rPrChange, ODT text:change-*, …). Every
extractor defaults to ExtractionResult.revisions = None until a
format-specific implementation is added.
| Field | Type | Default | Description |
|---|---|---|---|
revisionId |
String |
— | Format-specific revision identifier. For DOCX this is the w:id attribute value on the change element (e.g. "42"). When the attribute is absent a synthetic fallback is generated ("docx-ins-0", "docx-del-3", …). |
author |
String? |
null |
Display name of the author who made this change, when available. |
timestamp |
String? |
null |
ISO-8601 timestamp of the change, when available. Stored as a plain string so this type remains FFI-friendly and unconditionally available without the chrono optional dep. DOCX populates this from the w:date attribute (e.g. "2024-03-15T10:30:00Z"). |
kind |
RevisionKind |
— | Semantic kind of this revision. |
anchor |
RevisionAnchor? |
null |
Best-effort document location for this revision. Resolution is format-dependent and may be null when the location cannot be determined (e.g. changes inside table cells before table-cell anchor support is added). |
delta |
RevisionDelta |
— | The content changes that make up this revision. |
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 |
List<DocumentNode> |
\[\] |
All nodes in document/reading order. |
sourceFormat |
String? |
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 |
List<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 |
List<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:
Example:
Returns: No return value.
isEmpty()¶
Check if the document structure is empty.
Signature:
Example:
Returns: Boolean
default()¶
Signature:
Example:
Returns: DocumentStructure
DocumentSummary¶
Summary of an extracted document.
| Field | Type | Default | Description |
|---|---|---|---|
text |
String |
— | Summary text (plain prose). |
strategy |
SummaryStrategy |
— | Strategy that produced this summary. |
tokenCount |
Int? |
null |
Approximate token count of the summary, when known. |
DocxAppProperties¶
Application properties from docProps/app.xml for DOCX
Contains Word-specific document statistics and metadata.
| Field | Type | Default | Description |
|---|---|---|---|
application |
String? |
null |
Application name (e.g., "Microsoft Office Word") |
appVersion |
String? |
null |
Application version |
template |
String? |
null |
Template filename |
totalTime |
Int? |
null |
Total editing time in minutes |
pages |
Int? |
null |
Number of pages |
words |
Int? |
null |
Number of words |
characters |
Int? |
null |
Number of characters (excluding spaces) |
charactersWithSpaces |
Int? |
null |
Number of characters (including spaces) |
lines |
Int? |
null |
Number of lines |
paragraphs |
Int? |
null |
Number of paragraphs |
company |
String? |
null |
Company name |
docSecurity |
Int? |
null |
Document security level |
scaleCrop |
Boolean? |
null |
Scale crop flag |
linksUpToDate |
Boolean? |
null |
Links up to date flag |
sharedDoc |
Boolean? |
null |
Shared document flag |
hyperlinksChanged |
Boolean? |
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 |
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 |
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 |
Map<String, Any>? |
{} |
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 |
|---|---|---|---|
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 |
Int? |
null |
Page number (1-indexed) |
filename |
String? |
null |
Source filename or document name |
coordinates |
BoundingBox? |
null |
Bounding box coordinates if available |
elementIndex |
Long? |
null |
Position index in the element sequence |
additional |
Map<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 |
Attachment name (from Content-Disposition header) |
filename |
String? |
null |
Filename of the attachment |
mimeType |
String? |
null |
MIME type of the attachment |
size |
Long? |
null |
Size in bytes |
isImage |
Boolean |
— | Whether this attachment is an image |
data |
ByteArray? |
null |
Attachment data (if extracted). Uses bytes.Bytes for cheap cloning of large buffers. |
EmailConfig¶
Configuration for email extraction.
| Field | Type | Default | Description |
|---|---|---|---|
msgFallbackCodepage |
Int? |
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 |
Email subject line |
fromEmail |
String? |
null |
Sender email address |
toEmails |
List<String> |
— | Primary recipient email addresses |
ccEmails |
List<String> |
— | CC recipient email addresses |
bccEmails |
List<String> |
— | BCC recipient email addresses |
date |
String? |
null |
Email date/timestamp |
messageId |
String? |
null |
Message-ID header value |
plainText |
String? |
null |
Plain text version of the email body |
htmlContent |
String? |
null |
HTML version of the email body |
content |
String |
— | Cleaned/processed text content. Aliased as cleaned_text for back-compat. |
attachments |
List<EmailAttachment> |
— | List of email attachments |
metadata |
Map<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 |
Sender's email address |
fromName |
String? |
null |
Sender's display name |
toEmails |
List<String> |
\[\] |
Primary recipients |
ccEmails |
List<String> |
\[\] |
CC recipients |
bccEmails |
List<String> |
\[\] |
BCC recipients |
messageId |
String? |
null |
Message-ID header value |
attachments |
List<String> |
\[\] |
List of attachment filenames |
EmbeddedChanges¶
Changes to embedded archive children between two results.
| Field | Type | Default | Description |
|---|---|---|---|
added |
List<ArchiveEntry> |
\[\] |
Children present in b but not in a (matched by path). |
removed |
List<ArchiveEntry> |
\[\] |
Children present in a but not in b (matched by path). |
changed |
List<EmbeddedDiff> |
\[\] |
Children present in both but with differing content (matched by path). Each entry holds the diff of the nested ExtractionResult. |
EmbeddedDiff¶
Diff for a single embedded archive entry that appears in both results.
| Field | Type | Default | Description |
|---|---|---|---|
path |
String |
— | Archive-relative path identifying this entry. |
diff |
ExtractionDiff |
— | The recursive diff of the entry's extraction result. |
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 |
ByteArray |
— | Raw file bytes from the embedded stream (already decompressed by lopdf). |
compressedSize |
Long |
— | Compressed byte count of the original stream (before decompression). Used by callers to compute the decompression ratio and detect zip-bomb-style attacks that embed a tiny compressed stream expanding to gigabytes of data. |
mimeType |
String? |
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 incrate.embeddings.embed_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:
Example:
Returns: Long
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
texts |
List<String> |
Yes | The texts |
Returns: List<List<Float>>
Errors: Throws Error.
EmbeddingConfig¶
Embedding configuration for text chunks.
Configures embedding generation using ONNX models via the vendored embedding engine.
Requires the embeddings feature to be enabled.
| Field | Type | Default | Description |
|---|---|---|---|
model |
EmbeddingModelType |
EmbeddingModelType.Preset |
The embedding model to use (defaults to "balanced" preset if not specified) |
normalize |
Boolean |
true |
Whether to normalize embedding vectors (recommended for cosine similarity) |
batchSize |
Long |
32 |
Batch size for embedding generation |
showDownloadProgress |
Boolean |
false |
Show model download progress |
cacheDir |
Path? |
null |
Custom cache directory for model files Defaults to ~/.cache/kreuzberg/embeddings/ if not specified. Allows full customization of model download location. |
acceleration |
AccelerationConfig? |
null |
Hardware acceleration for the embedding ONNX model. When set, controls which execution provider (CPU, CUDA, CoreML, TensorRT) is used for inference. Defaults to null (auto-select per platform). |
maxEmbedDurationSecs |
Long? |
null |
Maximum wall-clock duration (in seconds) for a single embed() call when using EmbeddingModelType.Plugin. Applies only to the in-process plugin path — protects against hung host-language backends (e.g. a Python callback deadlocked on the GIL, a model stuck on CUDA OOM retries, etc.). On timeout, the dispatcher returns Plugin instead of blocking forever. null disables the timeout. The default (60 seconds) is conservative for common in-process inference; increase for large batches on slow hardware. |
Methods¶
default()¶
Signature:
Example:
Returns: EmbeddingConfig
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 |
— | Short identifier for this preset (e.g. "balanced", "fast", "quality"). |
chunkSize |
Long |
— | Target chunk size in characters. |
overlap |
Long |
— | Overlap between consecutive chunks in characters. |
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 |
Long |
— | Embedding vector dimension produced by this model. |
description |
String |
— | Human-readable description of the preset's intended use case. |
EnrichOptions¶
Which enrichment passes to run on a piece of text.
All fields default to false / empty so callers can opt in precisely.
| Field | Type | Default | Description |
|---|---|---|---|
keywords |
Boolean |
— | Run keyword extraction on the input text. When true, the enrichment backend identifies the most salient terms and returns them in EnrichResult.keywords. |
entities |
Boolean |
— | Run named-entity recognition (NER) on the input text. When true, the enrichment backend identifies named entities (persons, organisations, locations, etc.) and returns them in EnrichResult.entities. |
labels |
List<String> |
\[\] |
Custom labels to pass through to the result without modification. These are caller-supplied tags that the enrichment pipeline propagates verbatim into EnrichResult.labels. Useful for attaching project- or document-level metadata to every enrichment result. |
EnrichResult¶
Structured output produced by a completed enrichment pass.
Fields are populated only when the corresponding EnrichOptions flag was set.
| Field | Type | Default | Description |
|---|---|---|---|
keywords |
List<String> |
\[\] |
Salient terms extracted from the text. Populated when EnrichOptions.keywords was true. The ordering is backend-defined (typically by descending relevance score). |
entities |
List<Entity> |
\[\] |
Named entities found in the text. Populated when EnrichOptions.entities was true. Uses the shared OSS entity schema (Entity / EntityCategory) so consumers can pattern-match on entity categories without JSON gymnastics. |
labels |
List<String> |
\[\] |
Caller-supplied labels echoed from EnrichOptions.labels. |
Entity¶
A single named entity detected in the extracted text.
| Field | Type | Default | Description |
|---|---|---|---|
category |
EntityCategory |
— | Canonical category the entity belongs to (PERSON, ORG, LOCATION, etc.). |
text |
String |
— | Raw mention text exactly as it appeared in the source. |
start |
Int |
— | Byte-offset span in ExtractionResult.content where the mention starts. |
end |
Int |
— | Byte-offset span in ExtractionResult.content where the mention ends (exclusive). |
confidence |
Float? |
null |
Backend-reported confidence in \[0.0, 1.0\]. null when the backend does not expose confidence scores. |
EpubMetadata¶
EPUB metadata (Dublin Core extensions).
| Field | Type | Default | Description |
|---|---|---|---|
coverage |
String? |
null |
Dublin Core coverage field (geographic or temporal scope). |
dcFormat |
String? |
null |
Dublin Core format field (media type of the resource). |
relation |
String? |
null |
Dublin Core relation field (related resource identifier). |
source |
String? |
null |
Dublin Core source field (origin resource identifier). |
dcType |
String? |
null |
Dublin Core type field (nature or genre of the resource). |
coverImage |
String? |
null |
Path or identifier of the cover image within the EPUB container. |
ErrorMetadata¶
Error metadata (for batch operations).
| Field | Type | Default | Description |
|---|---|---|---|
errorType |
String |
— | Machine-readable error type identifier (e.g. "UnsupportedFormat"). |
message |
String |
— | Human-readable error description. |
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 |
Int? |
null |
Number of sheets in the workbook. |
sheetNames |
List<String>? |
\[\] |
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 |
Long |
— | Number of rows |
colCount |
Long |
— | Number of columns |
cellCount |
Long |
— | Total number of non-empty cells |
tableCells |
List<List<String>>? |
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 |
List<ExcelSheet> |
— | All sheets in the workbook |
metadata |
Map<String, String> |
— | Workbook-level metadata (author, creation date, etc.) |
revisions |
List<DocumentRevision>? |
/* serde(default) */ |
Collaborative-edit revision headers from xl/revisions/revisionHeaders.xml. Populated for legacy shared-workbook .xlsx files that contain the xl/revisions/ directory. Each <header> element maps to one DocumentRevision { kind: FormatChange } carrying the header's guid (→ revision_id), userName (→ author), and dateTime (→ timestamp). anchor and delta are null/empty for v1 (per-cell log parsing is a follow-up). null when xl/revisions/revisionHeaders.xml is absent. |
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 |
ByteArray |
— | 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 |
Int |
— | Zero-indexed position of this image in the document/page |
pageNumber |
Int? |
null |
Page/slide number where image was found (1-indexed) |
width |
Int? |
null |
Image width in pixels |
height |
Int? |
null |
Image height in pixels |
colorspace |
String? |
null |
Colorspace information (e.g., "RGB", "CMYK", "Gray") |
bitsPerComponent |
Int? |
null |
Bits per color component (e.g., 8, 16) |
isMask |
Boolean |
— | Whether this image is a mask image |
description |
String? |
null |
Optional description of the image |
ocrResult |
ExtractionResult? |
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 |
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 |
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 |
Heuristic classification of what this image likely depicts. null if classification was disabled or inconclusive. |
kindConfidence |
Float? |
null |
Confidence score for image_kind, in the range 0.0 to 1.0. |
clusterId |
Int? |
null |
Identifier shared across images that form a single logical figure (e.g. all raster tiles of one technical drawing). null for singletons. |
caption |
String? |
null |
VLM-generated caption describing the image, when captioning is configured. Populated by the captioning post-processor (crates/kreuzberg/src/plugins/processor/builtin/captioning.rs), which routes each image through crate.llm.region_extractor.extract_region_with_vlm in caption mode. null when captioning is disabled or the VLM declined to caption. |
qrCodes |
List<QrCode>? |
\[\] |
QR codes decoded from this image, when QR detection is enabled. Populated by the QR post-processor (crates/kreuzberg/src/extractors/qr.rs) via the pure-Rust rqrr decoder. null when QR detection is disabled; an empty Some(\[\]) when detection ran but found nothing. |
dataBase64 |
String? |
null |
Base64-encoded copy of data; populated when ImageExtractionConfig.include_data_base64 is true. Omitted from JSON by default; use instead of data in JSON-only clients. |
ExtractedUri¶
A URI extracted from a document.
Represents any link, reference, or resource pointer found during extraction.
The kind field classifies the URI semantically, while label carries
optional human-readable display text.
| Field | Type | Default | Description |
|---|---|---|---|
url |
String |
— | The URL or path string. |
label |
String? |
null |
Optional display text / label for the link. |
page |
Int? |
null |
Optional page number where the URI was found (1-indexed). |
kind |
UriKind |
— | Semantic classification of the URI. |
ExtractionConfidence¶
Combined confidence on [0, 1].
When OCR did not run, the ocr_aggregate weight folds into text_coverage
so the weighted sum still totals 1.0.
| Field | Type | Default | Description |
|---|---|---|---|
textCoverage |
Float |
— | Fraction of pages with a usable text layer. |
ocrAggregate |
Float? |
null |
Mean OCR per-element recognition confidence when OCR ran; null when it did not. |
schemaCompliance |
SchemaCompliance |
— | Whether the merged output validates against the preset schema. |
combined |
Float |
— | Weighted blend in \[0, 1\]. The value compared against the fallback threshold. |
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 |
OCR configuration (None = OCR disabled) |
forceOcr |
Boolean |
false |
Force OCR even for searchable PDFs |
forceOcrPages |
List<Int>? |
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 |
Text chunking configuration (None = chunking disabled) |
contentFilter |
ContentFilterConfig? |
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 |
Image extraction configuration (None = no image extraction) |
pdfOptions |
PdfConfig? |
null |
PDF-specific options (None = use defaults) |
tokenReduction |
TokenReductionOptions? |
null |
Token reduction configuration (None = no token reduction) |
languageDetection |
LanguageDetectionConfig? |
null |
Language detection configuration (None = no language detection) |
pages |
PageConfig? |
null |
Page extraction configuration (None = no page tracking) |
keywords |
KeywordConfig? |
null |
Keyword extraction configuration (None = no keyword extraction) |
postprocessor |
PostProcessorConfig? |
null |
Post-processor configuration (None = use defaults) |
htmlOutput |
HtmlOutputConfig? |
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 |
Long? |
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. Defaults to Some(60) to prevent pathological files (e.g. deeply nested archives, documents with millions of cells) from running indefinitely and exhausting caller resources. Set to null to disable the timeout for trusted input or long-running workloads. |
maxConcurrentExtractions |
Long? |
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 |
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. |
maxEmbeddedFileBytes |
Long? |
null |
Maximum uncompressed size in bytes for a single embedded file before recursive extraction is attempted (default: 50 MiB). Applies to embedded objects inside OOXML containers (DOCX, PPTX) and to email attachments processed via recursive extraction. Files that exceed this limit are skipped with a ProcessingWarning rather than passed to the extraction pipeline, preventing a single oversized embedded object from consuming unbounded memory or time. Set to null to disable the per-embedded-file cap (falls back to security_limits.max_archive_size as the only guard). |
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 |
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). |
transcription |
TranscriptionConfig? |
null |
Transcription (speech-to-text) configuration for audio/video files. When set and enabled, files with audio/video MIME types (mp3, mp4, m4a, wav, webm, etc.) are routed to the Whisper-based transcription pipeline. The actual heavy dependencies are only active under the transcription feature; the field is visible under transcription-types (including on WASM and Android targets that use the no-ORT preset). Default: null (transcription disabled). This is an additive, non-breaking change. |
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 |
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 |
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 |
Long? |
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 |
Email extraction configuration (None = use defaults). Currently supports configuring the fallback codepage for MSG files that do not specify one. See EmailConfig for details. |
maxArchiveDepth |
Long |
— | Maximum recursion depth for archive extraction (default: 3). Set to 0 to disable recursive extraction (legacy behavior). |
treeSitter |
TreeSitterConfig? |
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 |
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. |
ner |
NerConfig? |
null |
Named-entity recognition configuration. When set, the NER post-processor runs at the Middle stage and populates ExtractionResult.entities. |
redaction |
RedactionConfig? |
null |
Redaction / anonymisation configuration. When set, the redaction post-processor runs at the Late stage and rewrites every textual field in ExtractionResult, emitting an audit trail in ExtractionResult.redaction_report. |
summarization |
SummarizationConfig? |
null |
Summarisation configuration. When set, the summarisation post-processor runs at the Middle stage and populates ExtractionResult.summary. |
translation |
TranslationConfig? |
null |
Translation configuration. When set, the translation post-processor runs at the Middle stage and populates ExtractionResult.translation. |
pageClassification |
PageClassificationConfig? |
null |
Per-page classification configuration. When set, the classification post-processor runs at the Middle stage and populates ExtractionResult.page_classifications. |
captioning |
CaptioningConfig? |
null |
VLM captioning configuration for extracted images. When set, the captioning post-processor runs at the Middle stage and writes a caption into each ExtractedImage.caption. |
qrCodes |
Boolean? |
null |
Enable QR-code detection in extracted images. When true, the QR post-processor runs at the Middle stage and populates ExtractedImage.qr_codes. |
Methods¶
default()¶
Signature:
Example:
Returns: ExtractionConfig
needsImageData()¶
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.
Returns true when image binary data should be extracted.
True when config.images.extract_images is set or when captioning is
configured — captioning requires image bytes regardless of whether the caller
also requested images extraction.
Signature:
Example:
Returns: Boolean
needsImageProcessing()¶
Returns true when any image processing is needed during extraction.
Optimization Impact¶
For text-only extractions (no OCR, no image extraction, no captioning), 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:
Example:
Returns: Boolean
ExtractionDiff¶
The complete diff between two ExtractionResult values.
| Field | Type | Default | Description |
|---|---|---|---|
contentDiff |
List<DiffHunk> |
\[\] |
Unified-diff hunks for the content field. Empty when the content is identical. |
tablesAdded |
List<Table> |
\[\] |
Tables present in b but not in a (by index position, excess right-side tables). |
tablesRemoved |
List<Table> |
\[\] |
Tables present in a but not in b (by index position, excess left-side tables). |
tablesChanged |
List<TableDiff> |
\[\] |
Cell-level changes for table pairs that share the same index and dimensions. |
metadataChanged |
Any |
— | Metadata difference, encoded as a JSON object with three top-level keys: added (keys present in b but not a), removed (keys present in a but not b), and changed (keys whose values differ — each entry is { "from": <value-in-a>, "to": <value-in-b> }). This is NOT RFC 6902 JSON Patch — we deliberately chose a flatter shape to avoid pulling in a json-patch crate. If you need RFC 6902 semantics (with JSON Pointer paths) feed a.metadata and b.metadata to your preferred json-patch impl directly. |
embeddedChanges |
EmbeddedChanges |
— | Changes to embedded archive children. |
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 |
— | Plain-text representation of the extracted document content. |
mimeType |
String |
— | MIME type of the source document (e.g. "application/pdf"). |
metadata |
Metadata |
— | Document-level metadata (author, title, dates, format-specific fields). |
extractionMethod |
ExtractionMethod? |
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 |
List<Table> |
\[\] |
Tables extracted from the document, each with structured cell data. |
detectedLanguages |
List<String>? |
\[\] |
ISO 639-1 language codes detected in the document content. |
chunks |
List<Chunk>? |
\[\] |
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 |
List<ExtractedImage>? |
\[\] |
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 |
List<PageContent>? |
\[\] |
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 |
List<Element>? |
\[\] |
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 |
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 |
List<OcrElement>? |
\[\] |
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 |
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 |
List<Keyword>? |
\[\] |
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 |
Double? |
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 |
List<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 |
List<PdfAnnotation>? |
\[\] |
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 |
List<ArchiveEntry>? |
\[\] |
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 |
List<ExtractedUri>? |
\[\] |
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. |
revisions |
List<DocumentRevision>? |
\[\] |
Tracked changes embedded in the source document. Populated by per-format extractors that understand change-tracking metadata (DOCX w:ins/w:del/w:rPrChange, ODT text:change-*, …). Every extractor defaults to null until its format-specific implementation is added. Extractors that do populate this field follow the "accepted-changes" convention: inserted text is present in content, deleted text is absent — the revision list is the separate audit trail. |
structuredOutput |
Any? |
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 |
Any? |
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 |
List<LlmUsage>? |
\[\] |
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. |
entities |
List<Entity>? |
\[\] |
Named entities detected in content by the NER post-processor. null when no NER backend is configured. Populated by the gline-rs ONNX backend or the LLM-driven backend (see crates/kreuzberg/src/text/ner/). |
summary |
DocumentSummary? |
null |
Summary of content produced by the summarisation post-processor. null when summarisation is not configured. Populated by the TextRank extractive backend (deterministic, no external service) or by the liter-llm-driven abstractive backend. |
extractionConfidence |
ExtractionConfidence? |
null |
Confidence score computed by the heuristics pipeline. Populated when the heuristics feature is enabled and confidence scoring has been performed. Combines text-coverage, OCR aggregate confidence, and schema-compliance into a single \[0, 1\] value. null when confidence scoring is not configured or the feature is absent. |
translation |
Translation? |
null |
Translation of content produced by the translation post-processor. null when translation is not configured. |
pageClassifications |
List<PageClassification>? |
\[\] |
Per-page classifications produced by the page-classification post-processor. null when classification is not configured. |
redactionReport |
RedactionReport? |
null |
Audit report of redactions applied by the redaction post-processor. The redaction processor rewrites content, formatted_content, every chunk's text, and the textual fields of entities / summary / translation / page_classifications in place. This report describes what was found and how it was replaced. null when redaction is not configured. |
formulas |
List<Formula> |
\[\] |
Mathematical formulas recognized in the document. Populated by the layout-guided formula pipeline when the layout-detection feature is enabled and the document contains regions classified as formulas. Empty otherwise. |
formFields |
List<PdfFormField> |
\[\] |
Form fields extracted from a PDF's AcroForm or XFA structure. Populated by the PDF extractor when PdfConfig.extract_form_fields is enabled (default) and the document is a fillable form. Empty otherwise. |
formattedContent |
String? |
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. |
Methods¶
fromOcr()¶
Convert from an OCR result.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
ocr |
OcrExtractionResult |
Yes | The ocr extraction result |
Returns: ExtractionResult
FictionBookMetadata¶
FictionBook (FB2) metadata.
| Field | Type | Default | Description |
|---|---|---|---|
genres |
List<String> |
\[\] |
Genre tags as declared in the FB2 <genre> elements. |
sequences |
List<String> |
\[\] |
Book series (sequence) names, if any. |
annotation |
String? |
null |
Short annotation / summary from the FB2 <annotation> element. |
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 |
Override quality post-processing for this file. |
ocr |
OcrConfig? |
null |
Override OCR configuration for this file (None in the Option = use batch default). |
forceOcr |
Boolean? |
null |
Override force OCR for this file. |
forceOcrPages |
List<Int>? |
\[\] |
Override force OCR pages for this file (1-indexed page numbers). |
disableOcr |
Boolean? |
null |
Override disable OCR for this file. |
chunking |
ChunkingConfig? |
null |
Override chunking configuration for this file. |
contentFilter |
ContentFilterConfig? |
null |
Override content filtering configuration for this file. |
images |
ImageExtractionConfig? |
null |
Override image extraction configuration for this file. |
pdfOptions |
PdfConfig? |
null |
Override PDF options for this file. |
tokenReduction |
TokenReductionOptions? |
null |
Override token reduction for this file. |
languageDetection |
LanguageDetectionConfig? |
null |
Override language detection for this file. |
pages |
PageConfig? |
null |
Override page extraction for this file. |
keywords |
KeywordConfig? |
null |
Override keyword extraction for this file. |
postprocessor |
PostProcessorConfig? |
null |
Override post-processor for this file. |
resultFormat |
ResultFormat? |
null |
Override result format for this file. |
outputFormat |
OutputFormat? |
null |
Override output content format for this file. |
includeDocumentStructure |
Boolean? |
null |
Override document structure output for this file. |
layout |
LayoutDetectionConfig? |
null |
Override layout detection for this file. |
transcription |
TranscriptionConfig? |
null |
Transcription configuration (see ExtractionConfig for docs). |
timeoutSecs |
Long? |
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 |
Override tree-sitter configuration for this file. |
structuredExtraction |
StructuredExtractionConfig? |
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 |
List<FormattedBlock> |
— | Footnote content blocks |
FootnoteAnchor¶
A footnote anchor reference in markdown text.
Represents a [^label] use-site (not a definition).
| Field | Type | Default | Description |
|---|---|---|---|
label |
String |
— | The label of the footnote reference (e.g., "1" in \[^1\]). |
offset |
Long |
— | Byte offset of the anchor in the markdown text. |
FootnoteConfig¶
Configuration for markdown footnote and citation parsing.
| Field | Type | Default | Description |
|---|---|---|---|
parseCitations |
Boolean |
true |
Whether to parse the structured citation block (default: true). When enabled, the parser will look for and extract citations from the block after --- + <!-- citations ... -->. |
Methods¶
default()¶
Signature:
Example:
Returns: FootnoteConfig
withParseCitations()¶
Set whether to parse the citation block.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
enabled |
Boolean |
Yes | The enabled |
Returns: FootnoteConfig
FootnoteDefinition¶
A footnote definition from markdown text.
Represents [^label]: content declarations (including multi-line continuations).
| Field | Type | Default | Description |
|---|---|---|---|
label |
String |
— | The label of the footnote (e.g., "1" in \[^1\]: ...). |
content |
String |
— | The full content of the footnote definition. |
offset |
Long |
— | Byte offset of the definition line in the markdown text. |
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 |
Long? |
null |
Heading level (1-6) for headings, or nesting level for lists |
inlineContent |
List<InlineElement> |
— | Inline content within the block |
language |
String? |
null |
Language identifier for code blocks |
code |
String? |
null |
Raw code content for code blocks |
children |
List<FormattedBlock> |
/* serde(default) */ |
Nested blocks for containers (blockquotes, list items, divs) |
Formula¶
A mathematical formula detected and recognized in a document.
Populated by the layout-guided formula pipeline: regions classified as
LayoutClass.Formula are routed to the formula OCR task, which returns the
LaTeX source for the region. The field is always present on
ExtractionResult but only populated
when the layout-detection feature is active and the document contains
formula regions.
| Field | Type | Default | Description |
|---|---|---|---|
latex |
String |
— | LaTeX source of the recognized formula, without surrounding $$ delimiters. This field contains the raw LaTeX code as produced by the OCR backend. To render the formula in Markdown or other formats, wrap with $$..$$ delimiters as needed. |
bbox |
BoundingBox |
— | Bounding box of the formula region on its page, in rendered-image pixel coordinates. The coordinates are in the space of the OCR-rendered page image at the OCR DPI (typically 300 DPI). These coordinates are NOT comparable to bounding boxes from native PDF text extraction, which use PDF point coordinates. |
page |
Int |
— | 1-indexed page number the formula appears on in the document. This is set by the extraction pipeline based on which page the formula was found on. |
GridCell¶
Individual grid cell with position and span metadata.
| Field | Type | Default | Description |
|---|---|---|---|
content |
String |
— | Cell text content. |
row |
Int |
— | Zero-indexed row position. |
col |
Int |
— | Zero-indexed column position. |
rowSpan |
Int |
serde(default = "default_span") |
Number of rows this cell spans. |
colSpan |
Int |
serde(default = "default_span") |
Number of columns this cell spans. |
isHeader |
Boolean |
/* serde(default) */ |
Whether this is a header cell. |
bbox |
BoundingBox? |
null |
Bounding box for this cell (if available). |
HeaderMetadata¶
Header/heading element metadata.
| Field | Type | Default | Description |
|---|---|---|---|
level |
Byte |
— | Header level: 1 (h1) through 6 (h6) |
text |
String |
— | Normalized text content of the header |
id |
String? |
null |
HTML id attribute if present |
depth |
Int |
— | Document tree depth at the header element |
htmlOffset |
Int |
— | 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 |
List<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 |
Byte |
— | Heading depth (1 = h1, 2 = h2, etc.) |
text |
String |
— | The text content of the heading. |
HeuristicsConfig¶
Configuration for document chunking and analysis heuristics.
Every threshold is a public field so callers can override any subset via
struct-update syntax: HeuristicsConfig { text_layer_threshold: 0.5, ..the default constructor }.
| Field | Type | Default | Description |
|---|---|---|---|
enablePdfTextHeuristics |
Boolean |
true |
Enable PDF text-layer detection heuristics. When true, PDFs with a substantial text layer will skip chunking. Default: true. |
textLayerThreshold |
Float |
0.7 |
Minimum fraction of pages that must have text to skip chunking. Range 0.0..=1.0. Default: 0.7 (70 % of pages). |
fileSizeThresholdBytes |
Long |
10485760 |
File size threshold in bytes for considering chunking. Files smaller than this are processed without chunking. Default: 10 MiB (10 × 1 024 × 1 024). |
pageCountThreshold |
Int |
50 |
Page count threshold for considering chunking. Documents with fewer pages are processed without chunking. Default: 50. |
targetPagesPerChunk |
Int |
10 |
Target number of pages per chunk for optimal parallel processing. Default: 10. |
maxPagesPerChunk |
Int |
25 |
Hard cap on pages per chunk. No chunk will exceed this limit. Must be ≥ target_pages_per_chunk. Default: 25. |
diskProcessingThresholdBytes |
Long |
52428800 |
File size threshold for disk-based processing. Files larger than this are buffered to disk to prevent OOM. Default: 50 MiB (50 × 1 024 × 1 024). |
minCharsPerPage |
Int |
50 |
Minimum characters per page to consider a page as having text. Default: 50. |
maxXlsxSheetCount |
Int |
200 |
Maximum sheet count allowed in an XLSX workbook. Workbooks beyond this are rejected pre-extraction to avoid OOM / abusive billing inflation. Default: 200. |
maxXlsxWorkbookCells |
Long |
5000000 |
Maximum cell count (sheets × rows × columns approximation) in an XLSX workbook. Default: 5 000 000 (≈ 200 sheets × 25 k cells). |
maxPptxEmbeddedCount |
Int |
50 |
Maximum number of OLE-embedded objects extractable from a single PPTX or DOCX. Protects against zip-bomb-style nested-document abuse. Default: 50. |
Methods¶
default()¶
Signature:
Example:
Returns: HeuristicsConfig
validate()¶
Validate the configuration.
Errors:
Returns HeuristicsError.ConfigError when:
target_pages_per_chunkis 0max_pages_per_chunk<target_pages_per_chunkfile_size_threshold_bytesis 0
Signature:
Example:
Returns: No return value.
Errors: Throws Error.
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 |
Float |
— | 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) |
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 |
Long |
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 |
Float? |
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:
Example:
Returns: HierarchyConfig
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 |
Document title from <title> tag |
description |
String? |
null |
Document description from <meta name="description"> tag |
keywords |
List<String> |
\[\] |
Document keywords from <meta name="keywords"> tag, split on commas |
author |
String? |
null |
Document author from <meta name="author"> tag |
canonicalUrl |
String? |
null |
Canonical URL from <link rel="canonical"> tag |
baseHref |
String? |
null |
Base URL from <base href=""> tag for resolving relative URLs |
language |
String? |
null |
Document language from lang attribute |
textDirection |
TextDirection? |
null |
Document text direction from dir attribute |
openGraph |
Map<String, String> |
{} |
Open Graph metadata (og:* properties) for social media Keys like "title", "description", "image", "url", etc. |
twitterCard |
Map<String, String> |
{} |
Twitter Card metadata (twitter:* properties) Keys like "card", "site", "creator", "title", "description", "image", etc. |
metaTags |
Map<String, String> |
{} |
Additional meta tags not covered by specific fields Keys are meta name/property attributes, values are content |
headers |
List<HeaderMetadata> |
\[\] |
Extracted header elements with hierarchy |
links |
List<LinkMetadata> |
\[\] |
Extracted hyperlinks with type classification |
images |
List<ImageMetadataType> |
\[\] |
Extracted images with source and dimensions |
structuredData |
List<StructuredData> |
\[\] |
Extracted structured data blocks |
HtmlOutputConfig¶
Configuration for styled HTML output.
When set on 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 |
Inline CSS string injected into the output after the theme stylesheet. Concatenated after css_file content when both are set. |
cssFile |
Path? |
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:
Example:
Returns: HtmlOutputConfig
ImageExtractionConfig¶
Image extraction configuration.
| Field | Type | Default | Description |
|---|---|---|---|
extractImages |
Boolean |
true |
Extract images from documents |
targetDpi |
Int |
300 |
Target DPI for image normalization |
maxImageDimension |
Int |
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 !\[Image 1\](embedded:p1_i0) 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 |
Int |
72 |
Minimum DPI threshold |
maxDpi |
Int |
600 |
Maximum DPI threshold |
maxImagesPerPage |
Int? |
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 |
false |
When true, extracted images are classified by kind and grouped into clusters where they appear to belong to one figure. Defaults to false — opt in explicitly to avoid unexpected ML overhead. |
includePageRasters |
Boolean |
false |
When true, full-page renders produced during OCR preprocessing are captured and returned as ImageKind.PageRaster entries in ExtractionResult.images. PDF + OCR only. No rasters are captured for non-PDF inputs or when the document-level OCR bypass is active (whole-document backend). When OCR is enabled and this flag is set but the active backend skips per-page rendering, a ProcessingWarning is emitted in ExtractionResult.processing_warnings. Defaults to false. Enable when downstream consumers need page thumbnails (e.g. citation previews, visual grounding). |
runOcrOnImages |
Boolean |
true |
Run OCR on extracted images and include the recognized text in the document content. When true (default) and ExtractionConfig.ocr is configured, extracted images are processed with the configured OCR backend. Set to false to extract images without OCR processing, even when OCR is enabled. |
ocrTextOnly |
Boolean |
false |
When true, image OCR results are rendered as plain text without the !\[...\](...) markdown placeholder. Only takes effect when run_ocr_on_images is also true. |
appendOcrText |
Boolean |
false |
When true and ocr_text_only is false, append the OCR text after the image placeholder in the rendered output. |
outputFormat |
ImageOutputFormat |
ImageOutputFormat.Native |
Target format for re-encoding extracted images. When set to anything other than Native, each extracted image is re-encoded to the requested format before being returned. This lets callers receive uniform output without duplicating encode logic downstream. Defaults to Native — no re-encode pass is performed and ExtractedImage.format reflects the source extractor's output. |
svg |
SvgOptions |
— | SVG-specific knobs for the image-encode pipeline. Controls sanitization and rasterization DPI when the source or output format is SVG. Only available when the svg feature is active. |
includeDataBase64 |
Boolean |
false |
When true, populate ExtractedImage.data_base64 with a Base64-encoded copy of the raw image bytes. Useful for JSON-only clients that cannot efficiently parse the default integer-array serialization of data. Defaults to false; enabling it doubles the in-memory image representation for the duration of the response. |
Methods¶
default()¶
Signature:
Example:
Returns: ImageExtractionConfig
ImageMetadata¶
Image metadata extracted from image files.
Includes dimensions, format, and EXIF data.
| Field | Type | Default | Description |
|---|---|---|---|
width |
Int |
— | Image width in pixels |
height |
Int |
— | Image height in pixels |
format |
String |
— | Image format (e.g., "PNG", "JPEG", "TIFF") |
exif |
Map<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 |
Alternative text from alt attribute |
title |
String? |
null |
Title attribute |
imageType |
ImageType |
— | Image type classification |
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 |
Int |
300 |
Target DPI for the image (300 is standard, 600 for small text). |
autoRotate |
Boolean |
false |
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:
Example:
Returns: ImagePreprocessingConfig
ImagePreprocessingMetadata¶
Image preprocessing metadata.
Tracks the transformations applied to an image during OCR preprocessing, including DPI normalization, resizing, and resampling.
| Field | Type | Default | Description |
|---|---|---|---|
targetDpi |
Int |
— | Target DPI from configuration |
scaleFactor |
Double |
— | Scaling factor applied to the image |
autoAdjusted |
Boolean |
— | Whether DPI was auto-adjusted based on content |
finalDpi |
Int |
— | Final DPI after processing |
resampleMethod |
String |
— | Resampling algorithm used ("LANCZOS3", "CATMULLROM", etc.) |
dimensionClamped |
Boolean |
— | Whether dimensions were clamped to max_image_dimension |
calculatedDpi |
Int? |
null |
Calculated optimal DPI (if auto_adjust_dpi enabled) |
skippedResize |
Boolean |
— | Whether resize was skipped (dimensions already optimal) |
resizeError |
String? |
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 |
metadata |
Map<String, String>? |
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 |
Copyright statement from the article's <permissions> element. |
license |
String? |
null |
Open-access license URI from the article's <license> element. |
historyDates |
Map<String, String> |
{} |
Publication history dates keyed by event type (e.g. "received", "accepted"). |
contributorRoles |
List<ContributorRole> |
\[\] |
Authors and contributors with their stated roles. |
Keyword¶
Extracted keyword with metadata.
| Field | Type | Default | Description |
|---|---|---|---|
text |
String |
— | The keyword text. |
score |
Float |
— | Relevance score (higher is better, algorithm-specific range). |
algorithm |
KeywordAlgorithm |
— | Algorithm that extracted this keyword. |
positions |
List<Long>? |
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 |
Long |
10 |
Maximum number of keywords to extract (default: 10). |
minScore |
Float |
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. |
language |
String? |
null |
Language code for stopword filtering (e.g., "en", "de", "fr"). If None, no stopword filtering is applied. |
yakeParams |
YakeParams? |
null |
YAKE-specific tuning parameters. |
rakeParams |
RakeParams? |
null |
RAKE-specific tuning parameters. |
Methods¶
default()¶
Signature:
Example:
Returns: KeywordConfig
LanguageDetectionConfig¶
Language detection configuration.
| Field | Type | Default | Description |
|---|---|---|---|
enabled |
Boolean |
true |
Enable language detection |
minConfidence |
Double |
0.8 |
Minimum confidence threshold (0.0-1.0) |
detectMultiple |
Boolean |
false |
Detect multiple languages in the document |
Methods¶
default()¶
Signature:
Example:
Returns: LanguageDetectionConfig
LayoutDetection¶
A single layout detection result.
| Field | Type | Default | Description |
|---|---|---|---|
className |
LayoutClass |
— | Detected layout class (e.g. Table, Text, Title). |
confidence |
Float |
— | Detection confidence score in \[0.0, 1.0\]. |
bbox |
BBox |
— | Bounding box in image pixel coordinates. |
LayoutDetectionConfig¶
Layout detection configuration.
Controls layout detection behavior in the extraction pipeline.
When set on ExtractionConfig, layout detection
is enabled for PDF extraction.
| Field | Type | Default | Description |
|---|---|---|---|
confidenceThreshold |
Float? |
null |
Confidence threshold override (None = use model default). |
applyHeuristics |
Boolean |
true |
Whether to apply postprocessing heuristics (default: true). |
tableModel |
TableModel |
TableModel.Tatr |
Table structure recognition model. Controls which model is used for table cell detection within layout-detected table regions. Defaults to TableModel.Tatr. |
acceleration |
AccelerationConfig? |
null |
Hardware acceleration for ONNX models (layout detection + table structure). When set, controls which execution provider (CPU, CUDA, CoreML, TensorRT) is used for inference. Defaults to null (auto-select per platform). |
enableChartUnderstanding |
Boolean |
false |
Route regions classified as charts to the chart-understanding OCR task. When true, layout regions detected as charts are sent to the VLM chart task (data-series/axis recovery) instead of being treated as generic image regions. Defaults to false — chart understanding is opt-in and has no effect on standard text/table extraction scores. |
Methods¶
default()¶
Signature:
Example:
Returns: LayoutDetectionConfig
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 |
Double |
— | Confidence score from the layout detection model (0.0 to 1.0). |
boundingBox |
BoundingBox |
— | Bounding box in document coordinate space. |
areaFraction |
Double |
— | 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 |
Optional title attribute |
linkType |
LinkType |
— | Link type classification |
rel |
List<String> |
— | Rel attribute values |
LlmBackend¶
liter-llm-backed NER backend.
Methods¶
new()¶
Create a new LLM-backed NER backend with the given LLM configuration.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
config |
LlmConfig |
Yes | The configuration options |
Returns: LlmBackend
detect()¶
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text |
categories |
List<EntityCategory> |
Yes | The categories |
Returns: List<Entity>
Errors: Throws Error.
detectWithCustom()¶
Signature:
@Throws(Error::class)
fun detectWithCustom(text: String, categories: List<EntityCategory>, customLabels: List<String>): List<Entity>
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
text |
String |
Yes | The text |
categories |
List<EntityCategory> |
Yes | The categories |
customLabels |
List<String> |
Yes | The custom labels |
Returns: List<Entity>
Errors: Throws Error.
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 |
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 |
Custom base URL override for the provider endpoint. |
timeoutSecs |
Long? |
null |
Request timeout in seconds (default: 60). |
maxRetries |
Int? |
null |
Maximum retry attempts (default: 3). |
temperature |
Double? |
null |
Sampling temperature for generation tasks. |
maxTokens |
Long? |
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 |
Long? |
null |
Number of input/prompt tokens consumed. |
outputTokens |
Long? |
null |
Number of output/completion tokens generated. |
totalTokens |
Long? |
null |
Total tokens (input + output). |
estimatedCost |
Double? |
null |
Estimated cost in USD based on the provider's published pricing. |
finishReason |
String? |
null |
Why the model stopped generating (e.g. "stop", "length", "content_filter"). |
MetaSchema¶
Compiled meta-schema validator over preset.schema.json.
Methods¶
compile()¶
Compile the given JSON text as a Draft 2020-12 meta-schema.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
metaSchemaJson |
String |
Yes | The meta schema json |
Returns: MetaSchema
Errors: Throws LoadError.
parsePreset()¶
Validate raw against the meta-schema and deserialize into a Preset,
stamping the fingerprint over the canonical file bytes.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
String |
Yes | Path to the file |
raw |
ByteArray |
Yes | The raw |
Returns: Preset
Errors: Throws LoadError.
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 |
Document title |
subject |
String? |
null |
Document subject or description |
authors |
List<String>? |
\[\] |
Primary author(s) - always Vec for consistency |
keywords |
List<String>? |
\[\] |
Keywords/tags - always Vec for consistency |
language |
String? |
null |
Primary language (ISO 639 code) |
createdAt |
String? |
null |
Creation timestamp (ISO 8601 format) |
modifiedAt |
String? |
null |
Last modification timestamp (ISO 8601 format) |
createdBy |
String? |
null |
User who created the document |
modifiedBy |
String? |
null |
User who last modified the document |
pages |
PageStructure? |
null |
Page/slide/sheet structure with boundaries |
format |
FormatMetadata? |
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 |
Image preprocessing metadata (when OCR preprocessing was applied) |
jsonSchema |
Any? |
null |
JSON schema (for structured data extraction) |
error |
ErrorMetadata? |
null |
Error metadata (for batch operations) |
extractionDurationMs |
Long? |
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 |
Document category (from frontmatter or classification). |
tags |
List<String>? |
\[\] |
Document tags (from frontmatter). |
documentVersion |
String? |
null |
Document version string (from frontmatter). |
abstractText |
String? |
null |
Abstract or summary text (from frontmatter). |
outputFormat |
String? |
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 |
Map<String, Any> |
{} |
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:
Example:
Returns: Boolean
ModelPaths¶
Combined paths to all models needed for OCR (backward compatibility).
| Field | Type | Default | Description |
|---|---|---|---|
detModel |
Path |
— | Path to the detection model directory. |
clsModel |
Path |
— | Path to the classification model directory. |
recModel |
Path |
— | Path to the recognition model directory. |
dictFile |
Path |
— | Path to the character dictionary file. |
MultidocInput¶
Input signals for multi-document boundary detection.
| Field | Type | Default | Description |
|---|---|---|---|
pageCount |
Int |
— | Total number of pages in the PDF. |
pages |
List<PageSignals> |
— | Per-page signals extracted from the PDF. |
MultidocThresholds¶
Thresholds for multi-document boundary detection.
All fields are public; callers override any subset via struct-update syntax.
| Field | Type | Default | Description |
|---|---|---|---|
densityShiftThreshold |
Float |
0.3 |
Text density difference threshold for DensityShift detection. Default: 0.3. |
bigramOverlapMin |
Float |
0.1 |
Minimum bigram-overlap ratio below which a density shift is promoted to a DensityShift boundary. Default: 0.1 (10 % overlap). |
Methods¶
default()¶
Signature:
Example:
Returns: MultidocThresholds
NerConfig¶
Since: v5.0
Configuration for the NER post-processor.
| Field | Type | Default | Description |
|---|---|---|---|
backend |
NerBackendKind |
NerBackendKind.Onnx |
Backend that runs the entity detection. |
categories |
List<EntityCategory> |
\[\] |
Entity categories to detect. Defaults to a sensible PERSON/ORG/LOCATION/EMAIL set when empty. |
model |
String? |
null |
Override the default model — only used by NerBackendKind.Onnx. null lets the backend pick its pinned default (urchade/gliner_multi-v2.1 for gline-rs). |
llm |
LlmConfig? |
null |
Optional LLM configuration — only used by NerBackendKind.Llm. Token usage for LLM backends is recorded in ExtractionResult.llm_usage. |
customLabels |
List<String> |
\[\] |
Arbitrary user-supplied entity labels for zero-shot detection. gline-rs natively supports zero-shot inference over caller-supplied labels — this is the primary value of GLiNER. The LLM backend also honours these labels by including them in the structured-output schema. Custom labels surface as EntityCategory.Custom in the resulting Entity stream. Use this when you need domain-specific entity types (e.g. "Treatment", "Product", "Vessel") without forking GLiNER's taxonomy. |
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
imageBytes |
ByteArray |
Yes | Raw image data (JPEG, PNG, TIFF, etc.) |
config |
OcrConfig |
Yes | OCR configuration (language, PSM mode, etc.) |
Returns: ExtractionResult
Errors: Throws Error.
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:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | Path to the image file |
config |
OcrConfig |
Yes | OCR configuration |
Returns: ExtractionResult
Errors: Throws Error.
supportsLanguage()¶
Check if this backend supports a given language code.
Returns:
true if the language is supported, false otherwise.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
lang |
String |
Yes | ISO 639-⅔ language code (e.g., "eng", "deu", "fra") |
Returns: Boolean
backendType()¶
Get the backend type identifier.
Returns:
The backend type enum value.
Signature:
Example:
Returns: OcrBackendType
supportedLanguages()¶
Optional: Get a list of all supported languages.
Defaults to empty list. Override to provide comprehensive language support info.
Signature:
Example:
Returns: List<String>
supportsTableDetection()¶
Optional: Check if the backend supports table detection.
Defaults to false. Override if your backend can detect and extract tables.
Signature:
Example:
Returns: Boolean
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:
Example:
Returns: Boolean
emitsStructuredMarkdown()¶
Declare that this backend emits structured markdown directly (tables, headings, lists) and downstream layout reconstruction should be skipped.
Defaults to false — classical OCR backends (Tesseract, PaddleOCR classical) return
plain text per detected region. End-to-end VLM backends (PaddleOCR-VL, GOT-OCR 2.0)
emit markdown in one forward pass and should override this to true.
Signature:
Example:
Returns: Boolean
processDocument()¶
Process a document file directly via OCR.
Only called if supports_document_processing returns true.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | The path |
config |
OcrConfig |
Yes | The ocr config |
Returns: ExtractionResult
Errors: Throws Error.
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 |
Double? |
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 |
Double |
— | 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 |
List<String> |
\[\] |
Language code(s) for OCR recognition. Accepts either a single language code ("eng") or a list (["eng", "deu"]). Defaults to ["eng"]. For Tesseract, languages are joined with "+". |
tesseractConfig |
TesseractConfig? |
null |
Tesseract-specific configuration (optional) |
outputFormat |
OutputFormat? |
null |
Output format for OCR results (optional, for format conversion) |
paddleOcrConfig |
Any? |
null |
PaddleOCR-specific configuration (optional, JSON passthrough) |
backendOptions |
Any? |
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 |
OCR element extraction configuration |
qualityThresholds |
OcrQualityThresholds? |
null |
Quality thresholds for the native-text-to-OCR fallback decision. When None, uses compiled defaults (matching previous hardcoded behavior). |
pipeline |
OcrPipelineConfig? |
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. |
vlmFallback |
VlmFallbackPolicy |
VlmFallbackPolicy.Disabled |
Ergonomic VLM fallback policy. When set to anything other than VlmFallbackPolicy.Disabled and OcrConfig.pipeline is null, a multi-stage pipeline is synthesised automatically: - VlmFallbackPolicy.OnLowQuality → \[classical_stage, vlm_stage\] with the quality_threshold mapped onto OcrQualityThresholds.pipeline_min_quality. - VlmFallbackPolicy.Always → \[vlm_stage\] only. Requires OcrConfig.vlm_config to be Some when not Disabled. When OcrConfig.pipeline is explicitly set, this field is ignored. |
vlmConfig |
LlmConfig? |
null |
VLM (Vision Language Model) OCR configuration. Required when backend is "vlm" or when vlm_fallback is not VlmFallbackPolicy.Disabled. Uses liter-llm to send page images to a vision model for text extraction. |
vlmPrompt |
String? |
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 |
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 |
Map<String, ByteArray>? |
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. |
tessdataPath |
Path? |
null |
Runtime override for tessdata directory path. When set, uses this path as the highest-priority tessdata location, bypassing environment variables and cache directories. Useful for embedding pre-installed tessdata in applications. When null, uses the standard resolution chain: TESSDATA_PREFIX env, cache dir, system paths. |
Methods¶
default()¶
Signature:
Example:
Returns: OcrConfig
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 |
Rotation information (if detected). |
pageNumber |
Int |
— | Page number (1-indexed). |
parentId |
String? |
null |
Parent element ID for hierarchical relationships. Only used for Tesseract output which has word -> line -> block hierarchy. |
backendMetadata |
Map<String, Any> |
{} |
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 |
Double |
— | 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 |
Map<String, Any> |
— | OCR processing metadata (confidence scores, language, etc.) |
tables |
List<OcrTable> |
— | Tables detected and extracted via OCR |
ocrElements |
List<OcrElement>? |
/* serde(default) */ |
Structured OCR elements with bounding boxes and confidence scores. Available when TSV output is requested or table detection is enabled. |
OcrMetadata¶
OCR processing metadata.
Captures information about OCR processing configuration and results.
| Field | Type | Default | Description |
|---|---|---|---|
language |
String |
— | OCR language code(s) used |
psm |
Int |
— | Tesseract Page Segmentation Mode (PSM) |
outputFormat |
String |
— | Output format (e.g., "text", "hocr") |
tableCount |
Int |
— | Number of tables detected |
tableRows |
Int? |
null |
Number of rows in the detected table (if a single table was found). |
tableCols |
Int? |
null |
Number of columns in the detected table (if a single table was found). |
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 |
List<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 |
Int |
serde(default = "default_priority") |
Priority weight (higher = tried first). Stages are sorted by priority descending. |
language |
List<String>? |
/* serde(default) */ |
Language override for this stage (None = use parent OcrConfig.language). Accepts either a single language code ("eng") or a list (["eng", "deu"]). |
tesseractConfig |
TesseractConfig? |
/* serde(default) */ |
Tesseract-specific config override for this stage. |
paddleOcrConfig |
Any? |
/* serde(default) */ |
PaddleOCR-specific config for this stage. |
vlmConfig |
LlmConfig? |
/* serde(default) */ |
VLM config override for this pipeline stage. |
backendOptions |
Any? |
/* 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 |
Long |
64 |
Minimum total non-whitespace characters to consider text substantive. |
minNonWhitespacePerPage |
Double |
32 |
Minimum non-whitespace characters per page on average. |
minMeaningfulWordLen |
Long |
4 |
Minimum character count for a word to be "meaningful". |
minMeaningfulWords |
Long |
3 |
Minimum count of meaningful words before text is accepted. |
minAlnumRatio |
Double |
0.3 |
Minimum alphanumeric ratio (non-whitespace chars that are alphanumeric). |
minGarbageChars |
Long |
5 |
Minimum Unicode replacement characters (U+FFFD) to trigger OCR fallback. |
maxFragmentedWordRatio |
Double |
0.6 |
Maximum fraction of short (1-2 char) words before text is considered fragmented. |
criticalFragmentedWordRatio |
Double |
0.8 |
Critical fragmentation threshold — triggers OCR regardless of meaningful words. Normal English text has ~20-30% short words. 80%+ is definitive garbage. |
minAvgWordLength |
Double |
2 |
Minimum average word length. Below this with enough words indicates garbled extraction. |
minWordsForAvgLengthCheck |
Long |
50 |
Minimum word count before average word length check applies. |
minConsecutiveRepeatRatio |
Double |
0.08 |
Minimum consecutive word repetition ratio to detect column scrambling. |
minWordsForRepeatCheck |
Long |
50 |
Minimum word count before consecutive repetition check is applied. |
substantiveMinChars |
Long |
100 |
Minimum character count for "substantive markdown" OCR skip gate. |
nonTextMinChars |
Long |
20 |
Minimum character count for "non-text content" OCR skip gate. |
alnumWsRatioThreshold |
Double |
0.4 |
Alphanumeric+whitespace ratio threshold for skip decisions. |
pipelineMinQuality |
Double |
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:
Example:
Returns: OcrQualityThresholds
OcrRotation¶
Rotation information for an OCR element.
| Field | Type | Default | Description |
|---|---|---|---|
angleDegrees |
Double |
— | Rotation angle in degrees (0, 90, 180, 270 for PaddleOCR). |
confidence |
Double? |
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 |
List<List<String>> |
— | Table cells as a 2D vector (rows × columns) |
markdown |
String |
— | Markdown representation of the table |
pageNumber |
Int |
— | Page number where the table was found (1-indexed) |
boundingBox |
OcrTableBoundingBox? |
/* 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 |
Int |
— | Left x-coordinate (pixels) |
top |
Int |
— | Top y-coordinate (pixels) |
right |
Int |
— | Right x-coordinate (pixels) |
bottom |
Int |
— | Bottom y-coordinate (pixels) |
OrientationResult¶
Document orientation detection result.
| Field | Type | Default | Description |
|---|---|---|---|
degrees |
Int |
— | Detected orientation in degrees (0, 90, 180, or 270). |
confidence |
Float |
— | Confidence score (0.0-1.0). |
PaddleOcrConfig¶
Configuration for PaddleOCR backend.
Configures PaddleOCR text detection and recognition with multi-language support. Uses a builder pattern for convenient configuration.
| Field | Type | Default | Description |
|---|---|---|---|
language |
String |
— | Language code (e.g., "en", "ch", "jpn", "kor", "deu", "fra") |
cacheDir |
Path? |
null |
Optional custom cache directory for model files |
useAngleCls |
Boolean |
— | Enable angle classification for rotated text (default: false). Can misfire on short text regions, rotating crops incorrectly before recognition. |
enableTableDetection |
Boolean |
— | Enable table structure detection (default: false) |
detDbThresh |
Float |
— | Database threshold for text detection (default: 0.3) Range: 0.0-1.0, higher values require more confident detections |
detDbBoxThresh |
Float |
— | Box threshold for text bounding box refinement (default: 0.5) Range: 0.0-1.0 |
detDbUnclipRatio |
Float |
— | Unclip ratio for expanding text bounding boxes (default: 1.6) Controls the expansion of detected text regions |
detLimitSideLen |
Int |
— | Maximum side length for detection image (default: 960) Larger images may be resized to this limit for faster inference |
recBatchNum |
Int |
— | Batch size for recognition inference (default: 6) Number of text regions to process simultaneously |
padding |
Int |
— | Padding in pixels added around the image before detection (default: 10). Large values can include surrounding content like table gridlines. |
dropScore |
Float |
— | Minimum recognition confidence score for text lines (default: 0.5). Text regions with recognition confidence below this threshold are discarded. Matches PaddleOCR Python's drop_score parameter. Range: 0.0-1.0 |
modelTier |
String |
— | Model tier controlling detection/recognition model size and accuracy trade-off. - "mobile" (default): Lightweight models (~4.5MB detection, ~16.5MB recognition), fast download and inference - "server": Large, high-accuracy models (~88MB detection, ~84MB recognition), best for GPU or complex documents |
Methods¶
withCacheDir()¶
Sets a custom cache directory for model files.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
path |
Path |
Yes | Path to cache directory |
Returns: PaddleOcrConfig
withTableDetection()¶
Enables or disables table structure detection.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
enable |
Boolean |
Yes | Whether to enable table detection |
Returns: PaddleOcrConfig
withAngleCls()¶
Enables or disables angle classification for rotated text.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
enable |
Boolean |
Yes | Whether to enable angle classification |
Returns: PaddleOcrConfig
withDetDbThresh()¶
Sets the database threshold for text detection.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
threshold |
Float |
Yes | Detection threshold (0.0-1.0) |
Returns: PaddleOcrConfig
withDetDbBoxThresh()¶
Sets the box threshold for text bounding box refinement.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
threshold |
Float |
Yes | Box threshold (0.0-1.0) |
Returns: PaddleOcrConfig
withDetDbUnclipRatio()¶
Sets the unclip ratio for expanding text bounding boxes.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
ratio |
Float |
Yes | Unclip ratio (typically 1.5-2.0) |
Returns: PaddleOcrConfig
withDetLimitSideLen()¶
Sets the maximum side length for detection images.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
length |
Int |
Yes | Maximum side length in pixels |
Returns: PaddleOcrConfig
withRecBatchNum()¶
Sets the batch size for recognition inference.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
batchSize |
Int |
Yes | Number of text regions to process simultaneously |
Returns: PaddleOcrConfig
withDropScore()¶
Sets the minimum recognition confidence threshold.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
score |
Float |
Yes | Minimum confidence (0.0-1.0), text below this is dropped |
Returns: PaddleOcrConfig
withPadding()¶
Sets padding in pixels added around images before detection.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
padding |
Int |
Yes | Padding in pixels (0-100) |
Returns: PaddleOcrConfig
withModelTier()¶
Sets the model tier controlling detection/recognition model size.
Signature:
Example:
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
tier |
String |
Yes | "mobile" (default, lightweight, faster) or "server" (high accuracy, GPU/complex documents) |
Returns: PaddleOcrConfig
default()¶
Creates a default configuration with English language support.
Signature:
Example:
Returns: PaddleOcrConfig
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 |
Long |
— | Byte offset where this page starts in the content string (UTF-8 valid boundary, inclusive) |
byteEnd |
Long |
— | Byte offset where this page ends in the content string (UTF-8 valid boundary, exclusive) |
pageNumber |
Int |
— | Page number (1-indexed) |
PageClassification¶
Classification result for a single page.
| Field | Type | Default | Description |
|---|---|---|---|
pageNumber |
Int |
— | 1-indexed page number this classification belongs to. |
labels |
List<ClassificationLabel> |
— | Labels assigned to the page. Single-label classification yields exactly one entry; multi-label classification yields any subset of the configured label set. |
PageClassificationConfig¶
Since: v5.0
Configuration for the page-classification post-processor.
| Field | Type | Default | Description |
|---|---|---|---|
promptTemplate |
String? |
null |
Minijinja prompt template. Receives {{ labels }} (joined list), {{ page_text }} and {{ multi_label }} variables. null lets the backend pick a sensible default. |
labels |
List<String> |
— | The set of labels the classifier may emit. Must contain at least one entry. |
multiLabel |
Boolean |
/* serde(default) */ |
Allow multiple labels per page. Single-label mode returns at most one label. |
llm |
LlmConfig |
— | LLM configuration used for classification. |
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 {page_num} -->" |
Page marker format (use {page_num} placeholder) Default: "\n\n\n\n" |
Methods¶
default()¶
Signature:
Example:
Returns: PageConfig
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 shared tables and images for memory efficiency:
List<Table>enables zero-copy sharing of table dataList<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 |
Int |
— | Page number (1-indexed) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content |
String |
— | Text content for this page | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
tables |
List<Table> |
/* serde(default) */ |
Tables found on this page (uses Arc for memory efficiency) Serializes as List
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).
PageRange¶Page range for a chunk (0-indexed, inclusive).
Methods¶pageCount()¶Get the number of pages in this range. Signature: Example: Returns: PageSignals¶Per-page signals extracted from PDF content.
Methods¶fromPageText()¶Derive signals from raw page text. Callers that already have structured per-page data (e.g. from a PDF extractor)
can set individual fields directly. This constructor is for callers that only
have the plain-text content of a page (e.g. from when unknown (disables density-shift detection for this page). Heuristics¶All signal derivations are conservative starting points. Each is documented
inline. They err on the side of fewer false positives; tune thresholds via
Signature: Example: Parameters:
Returns: 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.
PatternMatch¶One detected PII span in the input text.
PdfAnnotation¶A PDF annotation extracted from a document page.
PdfConfig¶PDF-specific configuration.
Methods¶default()¶Signature: Example: Returns: PdfFormField¶A form field extracted from a PDF's AcroForm or XFA structure. Populated by the PDF extractor when
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: Example: Returns: version()¶Returns the semantic version of this plugin. Should follow semver format: Defaults to the kreuzberg crate version. Signature: Example: Returns: 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: Example: Returns: No return value. Errors: Throws 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: Example: Returns: No return value. Errors: Throws description()¶Optional plugin description for debugging and logging. Defaults to empty string if not overridden. Signature: Example: Returns: author()¶Optional plugin author information. Defaults to empty string if not overridden. Signature: Example: Returns: 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: Example: Parameters:
Returns: No return value. Errors: Throws processingStage()¶Get the processing stage for this post-processor. Determines when this processor runs in the pipeline. Returns: The Signature: Example: Returns: 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: Example: Parameters:
Returns: estimatedDurationMs()¶Optional: Estimate processing time in milliseconds. Used for logging and debugging. Defaults to 0 (unknown). Returns: Estimated processing time in milliseconds. Signature: Example: Parameters:
Returns: priority()¶Execution priority within the processing stage. Higher values run first within the same Signature: Example: Returns: PostProcessorConfig¶Post-processor configuration.
Methods¶default()¶Signature: Example: Returns: 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.
Preset¶A curated structured-extraction preset loaded from the embedded library. Each preset is a JSON file under The curated catalog is downstream (kreuzberg-cloud) and injects presets via
PresetSample¶Pointer to a sample input + its reference output bundled with the preset.
PresetSummary¶Lightweight projection of
ProcessingWarning¶A non-fatal warning from a processing pipeline stage. Captures errors from optional features that don't prevent extraction but may indicate degraded results.
PstMetadata¶Outlook PST archive metadata.
QrBoundingBox¶Pixel-space bounding box of a QR code inside its source image.
QrCode¶One QR code decoded from an extracted image.
RakeParams¶RAKE-specific parameters.
Methods¶default()¶Signature: Example: Returns: RecognizedTable¶Pre-computed table markdown for a table detection region. Produced by the TATR-based table structure recognizer and surfaced as part of
layout-aware OCR results. The struct lives here (under
RedactionConfig¶Since: Configuration for the redaction post-processor.
Methods¶default()¶Signature: Example: Returns: validate()¶Validate user-supplied terms and patterns at config-construction time. Compiles every Signature: Example: Returns: No return value. Errors: Throws RedactionFinding¶One redaction event: which span was rewritten, why, and with what.
RedactionPattern¶One user-supplied regex pattern to redact. The pattern is compiled with the Rust
Methods¶labeled()¶Build a pattern with the given label (case-insensitive by default). Signature: Example: Parameters:
Returns: RedactionReport¶Audit report describing what the redaction processor found and how it replaced it. The redactor returns this alongside the rewritten content so compliance, replay, and
audit-log consumers can see exactly what fired. Offsets are relative to the original
pre-redaction
RedactionTerm¶One user-supplied literal term to redact. Matched as a regex-escaped substring (so callers do not need to escape
metacharacters themselves). Case-insensitive by default — set
Methods¶literal()¶Build a term whose label is the literal value itself (case-insensitive). Signature: Example: Parameters:
Returns: labeled()¶Build a term with a custom label. Signature: Example: Parameters:
Returns: Registry¶Sorted map of preset id → Methods¶loadEmbedded()¶Build the registry from preset files embedded at compile time under
Signature: Example: Returns: Errors: Throws global()¶Return the global registry, loading it on first access. Panics: Panics if any embedded preset is malformed. The build-time validation test ensures this cannot happen for the embedded presets; a panic here indicates a build artifact problem, not a runtime error. Signature: Example: Returns: get()¶Look up a preset by its identifier. Signature: Example: Parameters:
Returns: summaries()¶Materialize a Signature: Example: Returns: len()¶Number of presets currently loaded. Signature: Example: Returns: isEmpty()¶Whether the registry contains zero presets. Signature: Example: Returns: sampleBytes()¶Read raw sample bytes for Signature: Example: Parameters:
Returns: extendFromDir()¶Load additional preset files from a runtime directory and insert them into this registry. Reads every Returns the number of presets successfully loaded from Use case¶This is the injection point for downstream catalogs: kreuzberg-cloud calls this once at startup to add its 20+ curated presets on top of the single embedded OSS preset. Signature: Example: Parameters:
Returns: Errors: Throws 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: Example: Parameters:
Returns: Errors: Throws RerankedDocument¶A single document returned by the reranker, with its position in the input and score.
Since v5.0.
RerankerBackend¶Trait for in-process reranker backend plugins. Cross-encoders score Async to match the convention used by Thread safety¶Backends must be Contract¶
Runtime¶The synchronous Since v5.0. Methods¶rerank()¶Score a list of documents against a query. Returns one raw logit per document in the same order as the input.
The dispatcher applies sigmoid to convert to Errors: Implementations should return Signature: Example: Parameters:
Returns: Errors: Throws RerankerConfig¶Configuration for the reranking pipeline. Controls which model to use, how many results to return, and download/cache behavior for local ONNX models. Since v5.0.
Methods¶default()¶Signature: Example: Returns: RerankerPreset¶Metadata for a bundled reranker preset. All string fields are owned Since v5.0.
ResolvedPreset¶A preset merged with caller-supplied overrides (custom schema, prompt suffix, context map). Output is what the pipeline orchestrator consumes.
RevisionDelta¶The content changes that make up a single revision. For insertions and deletions the
SecurityLimits¶Configuration for security limits across extractors. All limits are intentionally conservative to prevent DoS attacks while still supporting legitimate documents.
Methods¶default()¶Signature: Example: Returns: 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: Example: Returns: listenAddr()¶Get the server listen address (host:port). Signature: Example: Returns: corsAllowsAll()¶Check if CORS allows all origins. Returns Signature: Example: Returns: isOriginAllowed()¶Check if a given origin is allowed by CORS configuration. Returns
Signature: Example: Parameters:
Returns: maxRequestBodyMb()¶Get maximum request body size in megabytes (rounded up). Signature: Example: Returns: maxMultipartFieldMb()¶Get maximum multipart field size in megabytes (rounded up). Signature: Example: Returns: StructuredData¶Structured data (Schema.org, microdata, RDFa) block.
StructuredDataResult¶Result of parsing a structured data file (JSON, JSONL, YAML, or TOML).
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.
StructuredInput¶Signals consumed by the call-mode heuristic. All fields derive from a prior kreuzberg extraction — no double-work. This is a plain DTO; it intentionally has no dependency on internal kreuzberg extraction types so it can be constructed from any source.
StructuredThresholds¶Thresholds for the structured-extraction call-mode heuristic. All defaults are conservative starting points. Deployments should measure their own document corpus and override via their own config; these values are chosen to be safe-by-default, not to be optimal for any particular workload. Construct custom thresholds with struct-update syntax:
Methods¶default()¶Signature: Example: Returns: SummarizationConfig¶Since: Configuration for the summarisation post-processor.
SupportedFormat¶A supported document format entry. Represents a file extension and its corresponding MIME type that Kreuzberg can process.
SvgOptions¶SVG-specific configuration for the image-encode pipeline. Applies when the source image is SVG or when the output format is set to
Used via
Methods¶default()¶Signature: Example: Returns: 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.
TableDiff¶Cell-level changes for a pair of tables that share the same index.
TableGrid¶Structured table grid with cell-level metadata. Stores row/column dimensions and a flat list of cells with position info.
TesseractConfig¶Tesseract OCR configuration. Provides fine-grained control over Tesseract OCR engine parameters. Most users can use the defaults, but these settings allow optimization for specific document types (invoices, handwriting, etc.).
Methods¶default()¶Signature: Example: Returns: 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.
TokenCounter¶Per-category running counter for Methods¶new()¶Create a fresh counter with no previous state. Signature: Example: Returns: TokenReductionConfig¶Configuration for the token-reduction pipeline.
Methods¶default()¶Signature: Example: Returns: TokenReductionOptions¶Token reduction configuration.
Methods¶default()¶Signature: Example: Returns: TranscriptionConfig¶Configuration for audio/video transcription (speech-to-text). When present and The heavy dependencies (ORT, hf-hub, symphonia) are only pulled when the
All fields have sensible defaults. The recommended starting point is:
Methods¶default()¶Signature: Example: Returns: Translation¶Translation of the extracted content. Holds the translated rendition of
TranslationConfig¶Since: Configuration for the translation post-processor.
TreeSitterConfig¶Configuration for tree-sitter language pack integration. Controls grammar download behavior and code analysis options. Example (TOML)¶
Methods¶default()¶Signature: Example: Returns: TreeSitterProcessConfig¶Processing options for tree-sitter code analysis. Controls which analysis features are enabled when extracting code files.
Methods¶default()¶Signature: Example: Returns: UserChunkConfig¶User-provided chunk configuration.
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: Example: Parameters:
Returns: No return value. Errors: Throws 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: Example: Parameters:
Returns: 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: Example: Returns: 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: Example: Returns: YearRange¶Year range for bibliographic metadata.
Enums¶ExecutionProviderType¶ONNX Runtime execution provider type. Determines which hardware backend is used for model inference.
ImageOutputFormat¶Target format for re-encoding extracted images. Controls whether and how extracted images are normalised to a uniform
container format before being returned in Callers that need uniform output — e.g. cloud pipelines that always store
WebP thumbnails — set this once on Serde shape¶Uses a tagged enum:
OutputFormat¶Output format for extraction results. Controls the format of the
HtmlTheme¶Built-in HTML theme selection.
TableModel¶Which table structure recognition model to use. Controls the model used for table cell detection within layout-detected table regions. Wire format is snake_case in all serializers (JSON, TOML, YAML).
CallMode¶How a structured-extraction preset is dispatched to the model. This is the preset-facing call mode (the
MergeMode¶How partial results from multiple model calls (e.g. per page batch) are combined. Canonical home for the merge strategy referenced by presets and by the structured pipeline's post-processing. There is intentionally only one merge type across the crate — do not introduce a second.
NerBackendKind¶NER backend selector.
VlmFallbackPolicy¶Policy controlling when VLM (Vision Language Model) OCR is used as a fallback. This knob is syntactic sugar over the explicit
When Errors: Both
TableChunkingMode¶Controls how markdown tables are handled when they exceed the chunk size limit. Only applies when Variants¶
ChunkerType¶Type of text chunker to use. Variants¶
ChunkSizing¶How chunk size is measured. Defaults to Token-based sizing uses HuggingFace tokenizers loaded at runtime. Any tokenizer
available on HuggingFace Hub can be used, including OpenAI-compatible tokenizers
(e.g.,
EmbeddingModelType¶Embedding model types supported by Kreuzberg.
RerankerModelType¶Reranker model types supported by Kreuzberg. Since v5.0.
WhisperModel¶Supported Whisper model sizes. These map to published ONNX exports on Hugging Face (onnx-community or similar orgs). The actual filenames and repos are resolved inside the transcription engine.
CodeContentMode¶Content rendering mode for code extraction. Controls how extracted code content is represented in the
ListType¶Type of list detection.
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¶Intensity level for the token-reduction pipeline.
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.
EntityCategory¶Standard entity categories produced by built-in NER backends. The
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.
FormFieldType¶Kind of a PDF form field. Mirrors
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).
RedactionStrategy¶Strategy applied when a PII match is rewritten.
PiiCategory¶PII categories the pattern engine recognises.
DiffLine¶A single line in a unified-diff hunk. Defined here (rather than only in
RevisionKind¶Semantic classification of a tracked change.
RevisionAnchor¶Best-effort document location for a revision.
SummaryStrategy¶Summarisation strategy.
UriKind¶Semantic classification of an extracted URI.
RegionKind¶Classification of a detected layout region that warrants VLM extraction. Each variant maps to a specific prompt optimised for that content type. The mapping is intentionally narrow — only region kinds for which VLM extraction provides a clear quality benefit over classical suppression.
KeywordAlgorithm¶Keyword algorithm selection.
EnrichStatus¶Async lifecycle status for an enrichment job. Intended for use with any polling or event-driven pipeline that needs to track whether enrichment has completed, succeeded, or failed. Serialisation¶Uses an internally-tagged
SchemaCompliance¶Schema-validation outcome surfaced as one of three buckets. Fold into the combined confidence score without leaking internal validation error types.
ChunkingDecision¶The chunking decision made by the analyzer.
NoChunkingReason¶Reason for not chunking a document.
ChunkingReason¶Reason for chunking a document.
BoundaryReason¶Reason for boundary detection.
StructuredCallMode¶Outcome of the structured-extraction call-mode heuristic. Distinct from
PresetCategory¶High-level category used to group presets in the registry UI.
PsmMode¶Page Segmentation Mode for Tesseract OCR.
PaddleLanguage¶Supported languages in PaddleOCR. Maps user-friendly language codes to paddle-ocr-rs language identifiers.
LayoutClass¶The 18 canonical document layout classes. All model backends (RT-DETR, YOLO, etc.) map their native class IDs to this shared set. Models with fewer classes (DocLayNet: 11, PubLayNet: 5) map to the closest equivalent. Wire format is snake_case in all serializers (JSON, TOML, YAML).
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¶
HeuristicsError¶Errors that can occur during heuristics analysis.
LoadError¶Errors produced while loading or validating a preset file.
ResolveError¶Errors produced while resolving a preset against caller overrides.
|