kreuzberg-haystack 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- haystack_integrations/components/converters/kreuzberg/__init__.py +6 -0
- haystack_integrations/components/converters/kreuzberg/converter.py +547 -0
- haystack_integrations/components/converters/kreuzberg/utils.py +91 -0
- haystack_integrations/components/converters/py.typed +0 -0
- kreuzberg_haystack-0.1.0.dist-info/METADATA +39 -0
- kreuzberg_haystack-0.1.0.dist-info/RECORD +8 -0
- kreuzberg_haystack-0.1.0.dist-info/WHEEL +4 -0
- kreuzberg_haystack-0.1.0.dist-info/licenses/LICENSE.txt +73 -0
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import copy
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
9
|
+
from haystack.components.converters.utils import (
|
|
10
|
+
get_bytestream_from_source,
|
|
11
|
+
normalize_metadata,
|
|
12
|
+
)
|
|
13
|
+
from haystack.dataclasses import ByteStream
|
|
14
|
+
|
|
15
|
+
from kreuzberg import (
|
|
16
|
+
ExtractedTable,
|
|
17
|
+
ExtractionConfig,
|
|
18
|
+
ExtractionResult,
|
|
19
|
+
LanguageDetectionConfig,
|
|
20
|
+
batch_extract_bytes_sync,
|
|
21
|
+
batch_extract_files_sync,
|
|
22
|
+
classify_error,
|
|
23
|
+
config_to_json,
|
|
24
|
+
detect_mime_type,
|
|
25
|
+
error_code_name,
|
|
26
|
+
extract_bytes_sync,
|
|
27
|
+
extract_file_sync,
|
|
28
|
+
get_error_details,
|
|
29
|
+
get_extensions_for_mime,
|
|
30
|
+
get_last_error_code,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from .utils import (
|
|
34
|
+
_config_from_json_str,
|
|
35
|
+
_copy_config,
|
|
36
|
+
_get_table_markdown,
|
|
37
|
+
_is_batch_error,
|
|
38
|
+
_serialize_annotations,
|
|
39
|
+
_serialize_images,
|
|
40
|
+
_serialize_warnings,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
logger = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@component
|
|
47
|
+
class KreuzbergConverter:
|
|
48
|
+
"""
|
|
49
|
+
Converts files to Documents using [Kreuzberg](https://docs.kreuzberg.dev/).
|
|
50
|
+
|
|
51
|
+
Kreuzberg is a document intelligence framework that extracts text from
|
|
52
|
+
PDFs, Office documents, images, and 75+ other formats. All processing
|
|
53
|
+
is performed locally with no external API calls.
|
|
54
|
+
|
|
55
|
+
**Usage Example:**
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from haystack_integrations.components.converters.kreuzberg import (
|
|
59
|
+
KreuzbergConverter,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
converter = KreuzbergConverter()
|
|
63
|
+
result = converter.run(sources=["document.pdf", "report.docx"])
|
|
64
|
+
documents = result["documents"]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
You can also pass kreuzberg's `ExtractionConfig` to customize extraction:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from kreuzberg import ExtractionConfig, OcrConfig
|
|
71
|
+
|
|
72
|
+
converter = KreuzbergConverter(
|
|
73
|
+
config=ExtractionConfig(
|
|
74
|
+
output_format="markdown",
|
|
75
|
+
ocr=OcrConfig(backend="tesseract", language="eng"),
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**Token reduction** can be configured via
|
|
81
|
+
`ExtractionConfig(token_reduction=TokenReductionConfig(mode="moderate"))`
|
|
82
|
+
to reduce output size for LLM consumption. Five levels are available:
|
|
83
|
+
`"off"`, `"light"`, `"moderate"`, `"aggressive"`, `"maximum"`.
|
|
84
|
+
The reduced text appears directly in `Document.content`.
|
|
85
|
+
|
|
86
|
+
**Image preprocessing for OCR** can be tuned via
|
|
87
|
+
`OcrConfig(tesseract_config=TesseractConfig(preprocessing=ImagePreprocessingConfig(...)))`
|
|
88
|
+
with options for target DPI, auto-rotate, deskew, denoise,
|
|
89
|
+
contrast enhancement, and binarization method.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
*,
|
|
95
|
+
config: ExtractionConfig | None = None,
|
|
96
|
+
config_path: str | Path | None = None,
|
|
97
|
+
store_full_path: bool = False,
|
|
98
|
+
batch: bool = True,
|
|
99
|
+
easyocr_kwargs: dict[str, Any] | None = None,
|
|
100
|
+
) -> None:
|
|
101
|
+
"""
|
|
102
|
+
Create a `KreuzbergConverter` component.
|
|
103
|
+
|
|
104
|
+
:param config:
|
|
105
|
+
An optional `kreuzberg.ExtractionConfig` object to customize
|
|
106
|
+
extraction behavior. Use this to set output format, OCR backend
|
|
107
|
+
and language, force-OCR mode, per-page extraction, chunking,
|
|
108
|
+
keyword extraction, and other kreuzberg options. If not provided,
|
|
109
|
+
kreuzberg's defaults are used.
|
|
110
|
+
See the [kreuzberg API reference](https://docs.kreuzberg.dev/reference/api-python/)
|
|
111
|
+
for the full list of configuration options.
|
|
112
|
+
:param config_path:
|
|
113
|
+
Path to a kreuzberg configuration file (`.toml`, `.yaml`, or
|
|
114
|
+
`.json`). Cannot be used together with `config`.
|
|
115
|
+
:param store_full_path:
|
|
116
|
+
If `True`, the full file path is stored in the Document metadata.
|
|
117
|
+
If `False`, only the file name is stored.
|
|
118
|
+
:param batch:
|
|
119
|
+
If `True`, use kreuzberg's batch extraction APIs, which leverage
|
|
120
|
+
Rust's rayon thread pool for parallel processing. If `False`,
|
|
121
|
+
sources are extracted one at a time.
|
|
122
|
+
:param easyocr_kwargs:
|
|
123
|
+
Optional keyword arguments to pass to EasyOCR when using the
|
|
124
|
+
`"easyocr"` backend. Supports GPU, beam width, model storage,
|
|
125
|
+
and other EasyOCR-specific options.
|
|
126
|
+
See the [EasyOCR documentation](https://www.jaided.ai/easyocr/documentation/)
|
|
127
|
+
for the full list of supported arguments.
|
|
128
|
+
"""
|
|
129
|
+
if config is not None and config_path is not None:
|
|
130
|
+
msg = "Cannot specify both 'config' and 'config_path'. Use one or the other."
|
|
131
|
+
raise ValueError(msg)
|
|
132
|
+
|
|
133
|
+
self.config = config
|
|
134
|
+
self.config_path = Path(config_path).as_posix() if config_path is not None else None
|
|
135
|
+
self.store_full_path = store_full_path
|
|
136
|
+
self.batch = batch
|
|
137
|
+
self.easyocr_kwargs = easyocr_kwargs
|
|
138
|
+
|
|
139
|
+
def to_dict(self) -> dict[str, Any]:
|
|
140
|
+
"""
|
|
141
|
+
Serialize this component to a dictionary.
|
|
142
|
+
|
|
143
|
+
:returns:
|
|
144
|
+
Dictionary with serialized data.
|
|
145
|
+
"""
|
|
146
|
+
config_json = config_to_json(self.config) if self.config else None
|
|
147
|
+
return default_to_dict(
|
|
148
|
+
self,
|
|
149
|
+
config=config_json,
|
|
150
|
+
config_path=self.config_path,
|
|
151
|
+
store_full_path=self.store_full_path,
|
|
152
|
+
batch=self.batch,
|
|
153
|
+
easyocr_kwargs=self.easyocr_kwargs,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def from_dict(cls, data: dict[str, Any]) -> "KreuzbergConverter":
|
|
158
|
+
"""
|
|
159
|
+
Deserialize this component from a dictionary.
|
|
160
|
+
|
|
161
|
+
:param data:
|
|
162
|
+
Dictionary to deserialize from.
|
|
163
|
+
:returns:
|
|
164
|
+
Deserialized component.
|
|
165
|
+
"""
|
|
166
|
+
config_data = data["init_parameters"].get("config")
|
|
167
|
+
if isinstance(config_data, str):
|
|
168
|
+
data["init_parameters"]["config"] = _config_from_json_str(config_data)
|
|
169
|
+
return default_from_dict(cls, data)
|
|
170
|
+
|
|
171
|
+
def _build_config(self) -> ExtractionConfig:
|
|
172
|
+
"""
|
|
173
|
+
Build the effective `ExtractionConfig`.
|
|
174
|
+
|
|
175
|
+
Always returns a *fresh* config object — never mutates `self.config`.
|
|
176
|
+
"""
|
|
177
|
+
if self.config is not None:
|
|
178
|
+
config = _copy_config(self.config)
|
|
179
|
+
elif self.config_path is not None:
|
|
180
|
+
config = ExtractionConfig.from_file(self.config_path)
|
|
181
|
+
else:
|
|
182
|
+
config = ExtractionConfig()
|
|
183
|
+
|
|
184
|
+
# Auto-enable language detection if not explicitly configured
|
|
185
|
+
if config.language_detection is None:
|
|
186
|
+
config.language_detection = LanguageDetectionConfig(enabled=True)
|
|
187
|
+
|
|
188
|
+
return config
|
|
189
|
+
|
|
190
|
+
def _extract_batch(
|
|
191
|
+
self,
|
|
192
|
+
sources: list[str | Path | ByteStream],
|
|
193
|
+
config: ExtractionConfig,
|
|
194
|
+
) -> list[ExtractionResult | None]:
|
|
195
|
+
"""
|
|
196
|
+
Extract content from multiple sources using kreuzberg's batch APIs.
|
|
197
|
+
|
|
198
|
+
The result list is indexed to match `sources`. Slots for
|
|
199
|
+
file-based sources are filled by `batch_extract_files_sync`;
|
|
200
|
+
slots for bytes-based sources by `batch_extract_bytes_sync`.
|
|
201
|
+
A slot remains `None` only if neither batch API populated it
|
|
202
|
+
(i.e. the source was not dispatched to either batch call).
|
|
203
|
+
"""
|
|
204
|
+
file_indices: list[int] = []
|
|
205
|
+
file_paths: list[str | Path] = []
|
|
206
|
+
bytes_indices: list[int] = []
|
|
207
|
+
bytes_data: list[bytes | bytearray] = []
|
|
208
|
+
bytes_mimes: list[str] = []
|
|
209
|
+
|
|
210
|
+
for i, source in enumerate(sources):
|
|
211
|
+
if isinstance(source, ByteStream):
|
|
212
|
+
bytes_indices.append(i)
|
|
213
|
+
bytes_data.append(source.data)
|
|
214
|
+
bytes_mimes.append(source.mime_type or detect_mime_type(source.data))
|
|
215
|
+
else:
|
|
216
|
+
file_indices.append(i)
|
|
217
|
+
file_paths.append(source)
|
|
218
|
+
|
|
219
|
+
results: list[ExtractionResult | None] = [None] * len(sources)
|
|
220
|
+
|
|
221
|
+
# Batch-extract file paths
|
|
222
|
+
if file_paths:
|
|
223
|
+
self._collect_batch_results(
|
|
224
|
+
file_indices,
|
|
225
|
+
batch_extract_files_sync(file_paths, config=config, easyocr_kwargs=self.easyocr_kwargs),
|
|
226
|
+
sources,
|
|
227
|
+
results,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
# Batch-extract byte streams
|
|
231
|
+
if bytes_data:
|
|
232
|
+
self._collect_batch_results(
|
|
233
|
+
bytes_indices,
|
|
234
|
+
batch_extract_bytes_sync(bytes_data, bytes_mimes, config=config, easyocr_kwargs=self.easyocr_kwargs),
|
|
235
|
+
sources,
|
|
236
|
+
results,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
return results
|
|
240
|
+
|
|
241
|
+
@staticmethod
|
|
242
|
+
def _collect_batch_results(
|
|
243
|
+
indices: list[int],
|
|
244
|
+
batch_results: list[ExtractionResult],
|
|
245
|
+
sources: list[str | Path | ByteStream],
|
|
246
|
+
results: list[ExtractionResult | None],
|
|
247
|
+
) -> None:
|
|
248
|
+
"""Filter batch results, logging and skipping error entries."""
|
|
249
|
+
for idx, result in zip(indices, batch_results, strict=True):
|
|
250
|
+
if _is_batch_error(result):
|
|
251
|
+
err_code = classify_error(result.content)
|
|
252
|
+
logger.warning(
|
|
253
|
+
"Could not convert {source} to Document. Error code: {code} ({code_name}). "
|
|
254
|
+
"Details: {details}. Skipping it.",
|
|
255
|
+
source=sources[idx],
|
|
256
|
+
code=err_code,
|
|
257
|
+
code_name=error_code_name(err_code),
|
|
258
|
+
details=result.content,
|
|
259
|
+
)
|
|
260
|
+
continue
|
|
261
|
+
results[idx] = result
|
|
262
|
+
|
|
263
|
+
@staticmethod
|
|
264
|
+
def _build_extraction_metadata(result: ExtractionResult) -> dict[str, Any]:
|
|
265
|
+
"""
|
|
266
|
+
Build metadata dict from an `ExtractionResult`, flattening kreuzberg's
|
|
267
|
+
metadata fields and enriching with top-level result attributes.
|
|
268
|
+
|
|
269
|
+
Fields already present in `result.metadata` (`quality_score`,
|
|
270
|
+
`output_format`, `keywords`) are passed through as-is - they
|
|
271
|
+
don't need separate serialization. None values are filtered out.
|
|
272
|
+
"""
|
|
273
|
+
meta: dict[str, Any] = {k: v for k, v in result.metadata.items() if v is not None}
|
|
274
|
+
|
|
275
|
+
if result.processing_warnings:
|
|
276
|
+
meta["processing_warnings"] = _serialize_warnings(result.processing_warnings)
|
|
277
|
+
if result.detected_languages:
|
|
278
|
+
meta["detected_languages"] = list(result.detected_languages)
|
|
279
|
+
meta["result_format"] = str(result.result_format)
|
|
280
|
+
meta["mime_type"] = result.mime_type
|
|
281
|
+
try:
|
|
282
|
+
extensions = get_extensions_for_mime(result.mime_type)
|
|
283
|
+
if extensions:
|
|
284
|
+
meta["file_extensions"] = extensions
|
|
285
|
+
except RuntimeError:
|
|
286
|
+
pass
|
|
287
|
+
|
|
288
|
+
if result.images:
|
|
289
|
+
meta["image_count"] = len(result.images)
|
|
290
|
+
meta["images"] = _serialize_images(result.images)
|
|
291
|
+
|
|
292
|
+
if result.annotations:
|
|
293
|
+
meta["annotations"] = _serialize_annotations(result.annotations)
|
|
294
|
+
|
|
295
|
+
return meta
|
|
296
|
+
|
|
297
|
+
@staticmethod
|
|
298
|
+
def _assemble_content(
|
|
299
|
+
text: str, tables: list[ExtractedTable | dict[str, Any]] | None, output_format: str | None
|
|
300
|
+
) -> str:
|
|
301
|
+
"""
|
|
302
|
+
Assemble document content, appending table markdown for plain-text output.
|
|
303
|
+
|
|
304
|
+
When `output_format` is `"markdown"` or `"html"`, kreuzberg already
|
|
305
|
+
inlines tables into the content, so appending is skipped to avoid duplicates.
|
|
306
|
+
|
|
307
|
+
Tables may be `ExtractedTable` objects or plain dicts (page context).
|
|
308
|
+
"""
|
|
309
|
+
if not tables or output_format in ("markdown", "html"):
|
|
310
|
+
return text
|
|
311
|
+
|
|
312
|
+
table_blocks = [md for t in tables if (md := _get_table_markdown(t))]
|
|
313
|
+
if not table_blocks:
|
|
314
|
+
return text
|
|
315
|
+
|
|
316
|
+
return text + "\n\n" + "\n\n".join(table_blocks)
|
|
317
|
+
|
|
318
|
+
def _create_documents(
|
|
319
|
+
self,
|
|
320
|
+
result: ExtractionResult,
|
|
321
|
+
bytestream: ByteStream,
|
|
322
|
+
user_meta: dict[str, Any],
|
|
323
|
+
) -> list[Document]:
|
|
324
|
+
"""
|
|
325
|
+
Create one or more `Document` objects from an `ExtractionResult`.
|
|
326
|
+
|
|
327
|
+
Output mode depends on what kreuzberg returns:
|
|
328
|
+
- **Default:** one Document per source (unified content).
|
|
329
|
+
- **Pages present:** one Document per page (when
|
|
330
|
+
`PageConfig(extract_pages=True)` is in the config).
|
|
331
|
+
- **Chunks present:** one Document per chunk (when
|
|
332
|
+
`ChunkingConfig` is in the config).
|
|
333
|
+
"""
|
|
334
|
+
base_meta = self._build_extraction_metadata(result)
|
|
335
|
+
|
|
336
|
+
# Source metadata from bytestream
|
|
337
|
+
source_meta = dict(bytestream.meta)
|
|
338
|
+
if not self.store_full_path and "file_path" in source_meta:
|
|
339
|
+
source_meta["file_path"] = Path(source_meta["file_path"]).name
|
|
340
|
+
|
|
341
|
+
# Chunking mode — one Document per chunk
|
|
342
|
+
if result.chunks:
|
|
343
|
+
return self._create_chunked_documents(result, base_meta, source_meta, user_meta)
|
|
344
|
+
|
|
345
|
+
# Per-page mode — one Document per page
|
|
346
|
+
if result.pages:
|
|
347
|
+
return self._create_per_page_documents(result, base_meta, source_meta, user_meta)
|
|
348
|
+
|
|
349
|
+
# Default: unified mode — one Document per source
|
|
350
|
+
content = self._assemble_content(result.content, result.tables, result.output_format)
|
|
351
|
+
merged = {**base_meta, **source_meta, **copy.deepcopy(user_meta)}
|
|
352
|
+
return [Document(content=content, meta=merged)]
|
|
353
|
+
|
|
354
|
+
@staticmethod
|
|
355
|
+
def _create_per_page_documents(
|
|
356
|
+
result: ExtractionResult,
|
|
357
|
+
base_meta: dict[str, Any],
|
|
358
|
+
source_meta: dict[str, Any],
|
|
359
|
+
user_meta: dict[str, Any],
|
|
360
|
+
) -> list[Document]:
|
|
361
|
+
"""Create one Document per page."""
|
|
362
|
+
documents: list[Document] = []
|
|
363
|
+
for page in result.pages:
|
|
364
|
+
page_content = page.get("content", "")
|
|
365
|
+
page_tables = page.get("tables", [])
|
|
366
|
+
page_images = page.get("images", [])
|
|
367
|
+
|
|
368
|
+
page_content = KreuzbergConverter._assemble_content(page_content, page_tables, result.output_format)
|
|
369
|
+
|
|
370
|
+
page_meta: dict[str, Any] = {
|
|
371
|
+
**copy.deepcopy(base_meta),
|
|
372
|
+
**source_meta,
|
|
373
|
+
"page_number": page.get("page_number"),
|
|
374
|
+
"is_blank": page.get("is_blank", False),
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if page_images:
|
|
378
|
+
page_meta["image_count"] = len(page_images)
|
|
379
|
+
page_meta["images"] = _serialize_images(page_images)
|
|
380
|
+
|
|
381
|
+
page_meta.update(copy.deepcopy(user_meta))
|
|
382
|
+
documents.append(Document(content=page_content, meta=page_meta))
|
|
383
|
+
|
|
384
|
+
return documents
|
|
385
|
+
|
|
386
|
+
@staticmethod
|
|
387
|
+
def _create_chunked_documents(
|
|
388
|
+
result: ExtractionResult,
|
|
389
|
+
base_meta: dict[str, Any],
|
|
390
|
+
source_meta: dict[str, Any],
|
|
391
|
+
user_meta: dict[str, Any],
|
|
392
|
+
) -> list[Document]:
|
|
393
|
+
"""Create one Document per chunk, with optional embeddings."""
|
|
394
|
+
documents: list[Document] = []
|
|
395
|
+
total_chunks = len(result.chunks)
|
|
396
|
+
|
|
397
|
+
for i, chunk in enumerate(result.chunks):
|
|
398
|
+
chunk_meta = {
|
|
399
|
+
**copy.deepcopy(base_meta),
|
|
400
|
+
**source_meta,
|
|
401
|
+
"chunk_index": i,
|
|
402
|
+
"total_chunks": total_chunks,
|
|
403
|
+
**copy.deepcopy(user_meta),
|
|
404
|
+
}
|
|
405
|
+
documents.append(
|
|
406
|
+
Document(
|
|
407
|
+
content=chunk.content,
|
|
408
|
+
embedding=chunk.embedding,
|
|
409
|
+
meta=chunk_meta,
|
|
410
|
+
)
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
return documents
|
|
414
|
+
|
|
415
|
+
@component.output_types(documents=list[Document])
|
|
416
|
+
def run(
|
|
417
|
+
self,
|
|
418
|
+
sources: list[str | Path | ByteStream],
|
|
419
|
+
meta: dict[str, Any] | list[dict[str, Any]] | None = None,
|
|
420
|
+
) -> dict[str, list[Document]]:
|
|
421
|
+
"""
|
|
422
|
+
Convert files to Documents using Kreuzberg.
|
|
423
|
+
|
|
424
|
+
:param sources:
|
|
425
|
+
List of file paths, directory paths, or ByteStream objects to
|
|
426
|
+
convert. Directory paths are expanded to their direct file children
|
|
427
|
+
(non-recursive, sorted alphabetically).
|
|
428
|
+
:param meta:
|
|
429
|
+
Optional metadata to attach to the Documents.
|
|
430
|
+
This value can be either a list of dictionaries or a single
|
|
431
|
+
dictionary. If it's a single dictionary, its content is added to
|
|
432
|
+
the metadata of all produced Documents. If it's a list, the length
|
|
433
|
+
of the list must match the number of sources, because the two
|
|
434
|
+
lists will be zipped. If `sources` contains ByteStream objects,
|
|
435
|
+
their `meta` will be added to the output Documents.
|
|
436
|
+
|
|
437
|
+
**Note:** When directories are present in `sources`, `meta` must
|
|
438
|
+
be a single dictionary (not a list), since the number of files in
|
|
439
|
+
a directory is not known in advance.
|
|
440
|
+
|
|
441
|
+
:returns:
|
|
442
|
+
A dictionary with the following key:
|
|
443
|
+
|
|
444
|
+
- `documents`: A list of created Documents.
|
|
445
|
+
"""
|
|
446
|
+
# Expand directories
|
|
447
|
+
has_dirs = any(isinstance(s, (str, Path)) and Path(s).is_dir() for s in sources)
|
|
448
|
+
if has_dirs and isinstance(meta, list):
|
|
449
|
+
msg = (
|
|
450
|
+
"When directories are present in 'sources', 'meta' must be a "
|
|
451
|
+
"single dictionary, not a list, since the number of files in "
|
|
452
|
+
"a directory is not known in advance."
|
|
453
|
+
)
|
|
454
|
+
raise TypeError(msg)
|
|
455
|
+
|
|
456
|
+
# Expand directory paths to their direct file children
|
|
457
|
+
expanded: list[str | Path | ByteStream] = []
|
|
458
|
+
for source in sources:
|
|
459
|
+
if isinstance(source, ByteStream):
|
|
460
|
+
expanded.append(source)
|
|
461
|
+
else:
|
|
462
|
+
path = Path(source)
|
|
463
|
+
if path.is_dir():
|
|
464
|
+
expanded.extend(sorted(path.glob("*.*")))
|
|
465
|
+
else:
|
|
466
|
+
expanded.append(source)
|
|
467
|
+
|
|
468
|
+
meta_list = normalize_metadata(meta, sources_count=len(expanded))
|
|
469
|
+
|
|
470
|
+
config = self._build_config()
|
|
471
|
+
|
|
472
|
+
# Resolve each source to a ByteStream
|
|
473
|
+
bytestreams: list[ByteStream | None] = []
|
|
474
|
+
for source in expanded:
|
|
475
|
+
try:
|
|
476
|
+
bytestreams.append(get_bytestream_from_source(source))
|
|
477
|
+
except Exception as e:
|
|
478
|
+
logger.warning(
|
|
479
|
+
"Could not read {source}. Skipping it. Error: {error}",
|
|
480
|
+
source=source,
|
|
481
|
+
error=e,
|
|
482
|
+
)
|
|
483
|
+
bytestreams.append(None)
|
|
484
|
+
|
|
485
|
+
if self.batch and len(expanded) > 1:
|
|
486
|
+
results = self._extract_batch(expanded, config)
|
|
487
|
+
else:
|
|
488
|
+
results = self._extract_sequential(expanded, bytestreams, config)
|
|
489
|
+
|
|
490
|
+
documents: list[Document] = []
|
|
491
|
+
for result, bytestream, user_meta in zip(results, bytestreams, meta_list, strict=True):
|
|
492
|
+
if result is None or bytestream is None:
|
|
493
|
+
continue
|
|
494
|
+
documents.extend(self._create_documents(result, bytestream, user_meta))
|
|
495
|
+
|
|
496
|
+
return {"documents": documents}
|
|
497
|
+
|
|
498
|
+
def _extract_sequential(
|
|
499
|
+
self,
|
|
500
|
+
sources: list[str | Path | ByteStream],
|
|
501
|
+
bytestreams: list[ByteStream | None],
|
|
502
|
+
config: ExtractionConfig,
|
|
503
|
+
) -> list[ExtractionResult | None]:
|
|
504
|
+
"""Extract sources one at a time, returning results aligned with sources."""
|
|
505
|
+
results: list[ExtractionResult | None] = []
|
|
506
|
+
for source, bytestream in zip(sources, bytestreams, strict=True):
|
|
507
|
+
if bytestream is None:
|
|
508
|
+
results.append(None)
|
|
509
|
+
continue
|
|
510
|
+
try:
|
|
511
|
+
if isinstance(source, ByteStream):
|
|
512
|
+
effective_mime = source.mime_type or detect_mime_type(source.data)
|
|
513
|
+
result = extract_bytes_sync(
|
|
514
|
+
source.data,
|
|
515
|
+
mime_type=effective_mime,
|
|
516
|
+
config=config,
|
|
517
|
+
easyocr_kwargs=self.easyocr_kwargs,
|
|
518
|
+
)
|
|
519
|
+
else:
|
|
520
|
+
result = extract_file_sync(
|
|
521
|
+
source,
|
|
522
|
+
config=config,
|
|
523
|
+
easyocr_kwargs=self.easyocr_kwargs,
|
|
524
|
+
)
|
|
525
|
+
results.append(result)
|
|
526
|
+
except Exception as e:
|
|
527
|
+
try:
|
|
528
|
+
err_code = get_last_error_code()
|
|
529
|
+
details = get_error_details()
|
|
530
|
+
code_name = error_code_name(err_code) if err_code is not None else "UNKNOWN"
|
|
531
|
+
logger.warning(
|
|
532
|
+
"Could not convert {source} to Document. Error code: {code} ({code_name}). "
|
|
533
|
+
"Details: {details}. Skipping it.",
|
|
534
|
+
source=source,
|
|
535
|
+
code=err_code,
|
|
536
|
+
code_name=code_name,
|
|
537
|
+
details=details.get("message", str(e)),
|
|
538
|
+
)
|
|
539
|
+
except Exception as diag_err:
|
|
540
|
+
logger.debug("Failed to get error diagnostics: {err}", err=diag_err)
|
|
541
|
+
logger.warning(
|
|
542
|
+
"Could not convert {source} to Document. Skipping it. Error: {error}",
|
|
543
|
+
source=source,
|
|
544
|
+
error=e,
|
|
545
|
+
)
|
|
546
|
+
results.append(None)
|
|
547
|
+
return results
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import tempfile
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from kreuzberg import (
|
|
9
|
+
ExtractedImage,
|
|
10
|
+
ExtractedTable,
|
|
11
|
+
ExtractionConfig,
|
|
12
|
+
ExtractionResult,
|
|
13
|
+
config_to_json,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _is_batch_error(result: ExtractionResult) -> bool:
|
|
18
|
+
"""Detect error results returned by kreuzberg's batch APIs.
|
|
19
|
+
|
|
20
|
+
Batch APIs return ``ExtractionResult(content="Error: ...", metadata={},
|
|
21
|
+
quality_score=None)`` instead of raising exceptions. Valid results always
|
|
22
|
+
have populated metadata (at minimum ``output_format``).
|
|
23
|
+
"""
|
|
24
|
+
return result.metadata == {} and result.quality_score is None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _get_table_markdown(table: ExtractedTable | dict[str, Any]) -> str | None:
|
|
28
|
+
"""Get markdown string from a table (`ExtractedTable` object or dict)."""
|
|
29
|
+
if isinstance(table, dict):
|
|
30
|
+
return table.get("markdown") or None
|
|
31
|
+
md = getattr(table, "markdown", None)
|
|
32
|
+
return md or None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _serialize_images(images: list[ExtractedImage]) -> list[dict[str, Any]]:
|
|
36
|
+
"""Serialize image metadata dicts, excluding binary data."""
|
|
37
|
+
return [{k: v for k, v in img.items() if k != "data"} for img in images]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _serialize_warnings(warnings: list[Any]) -> list[dict[str, str]]:
|
|
41
|
+
"""Serialize processing warnings to plain dicts."""
|
|
42
|
+
serialized = []
|
|
43
|
+
for w in warnings:
|
|
44
|
+
if isinstance(w, dict):
|
|
45
|
+
serialized.append({"source": w.get("source", ""), "message": w.get("message", "")})
|
|
46
|
+
else:
|
|
47
|
+
serialized.append({"source": getattr(w, "source", ""), "message": getattr(w, "message", "")})
|
|
48
|
+
return serialized
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _serialize_annotations(annotations: list[Any]) -> list[dict[str, Any]]:
|
|
52
|
+
"""Serialize PDF annotations to plain dicts."""
|
|
53
|
+
serialized = []
|
|
54
|
+
for ann in annotations:
|
|
55
|
+
if isinstance(ann, dict):
|
|
56
|
+
serialized.append(dict(ann))
|
|
57
|
+
else:
|
|
58
|
+
serialized.append(
|
|
59
|
+
{
|
|
60
|
+
"type": getattr(ann, "annotation_type", None),
|
|
61
|
+
"content": getattr(ann, "content", None),
|
|
62
|
+
"page_number": getattr(ann, "page_number", None),
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
return serialized
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _config_from_json_str(json_str: str) -> ExtractionConfig:
|
|
69
|
+
"""
|
|
70
|
+
Load an `ExtractionConfig` from a JSON string via a temporary file.
|
|
71
|
+
|
|
72
|
+
This is necessary because kreuzberg's PyO3 config objects don't expose a
|
|
73
|
+
`from_json()` classmethod — only `from_file()`.
|
|
74
|
+
"""
|
|
75
|
+
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
|
|
76
|
+
tmp_path = f.name
|
|
77
|
+
f.write(json_str)
|
|
78
|
+
try:
|
|
79
|
+
return ExtractionConfig.from_file(tmp_path)
|
|
80
|
+
finally:
|
|
81
|
+
Path(tmp_path).unlink(missing_ok=True)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _copy_config(config: ExtractionConfig) -> ExtractionConfig:
|
|
85
|
+
"""
|
|
86
|
+
Deep copy an `ExtractionConfig` by round-tripping through JSON.
|
|
87
|
+
|
|
88
|
+
This is necessary because kreuzberg's PyO3 config objects don't support
|
|
89
|
+
Python's `copy.deepcopy()` protocol.
|
|
90
|
+
"""
|
|
91
|
+
return _config_from_json_str(config_to_json(config))
|
|
File without changes
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kreuzberg-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Kreuzberg document converter for Haystack
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/kreuzberg#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/kreuzberg
|
|
8
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Keywords: document-conversion,haystack,kreuzberg,ocr,pdf
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: haystack-ai>=2.22.0
|
|
23
|
+
Requires-Dist: kreuzberg>=4.4.6
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# kreuzberg-haystack
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/kreuzberg-haystack)
|
|
29
|
+
[](https://pypi.org/project/kreuzberg-haystack)
|
|
30
|
+
|
|
31
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/kreuzberg/CHANGELOG.md)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Contributing
|
|
36
|
+
|
|
37
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
38
|
+
|
|
39
|
+
For OCR tests, ensure Tesseract is installed on your system.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
haystack_integrations/components/converters/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
haystack_integrations/components/converters/kreuzberg/__init__.py,sha256=2OVIgRwVDAt0HsJw6wUzkRnbKDs7w_YZVNuRPikaWTk,186
|
|
3
|
+
haystack_integrations/components/converters/kreuzberg/converter.py,sha256=KHQaFBQSgDKfu8NVAYN0HyVeQG6_xQEUNK3XPz4J0Zc,20775
|
|
4
|
+
haystack_integrations/components/converters/kreuzberg/utils.py,sha256=utdmI06auqCSGAoaVTeno8K4gG03N9_oEXtDLtnjWyU,3111
|
|
5
|
+
kreuzberg_haystack-0.1.0.dist-info/METADATA,sha256=VhV9gHC5aqzE7bkWIkaUsuQx1lCV--xVP-UP0pg-5tM,1813
|
|
6
|
+
kreuzberg_haystack-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
7
|
+
kreuzberg_haystack-0.1.0.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
|
|
8
|
+
kreuzberg_haystack-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|