paddleocr-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/paddleocr/__init__.py +6 -0
- haystack_integrations/components/converters/paddleocr/paddleocr_vl_document_converter.py +494 -0
- haystack_integrations/components/converters/py.typed +0 -0
- paddleocr_haystack-0.1.0.dist-info/METADATA +40 -0
- paddleocr_haystack-0.1.0.dist-info/RECORD +7 -0
- paddleocr_haystack-0.1.0.dist-info/WHEEL +4 -0
- paddleocr_haystack-0.1.0.dist-info/licenses/LICENSE.txt +73 -0
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import base64
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Literal, Optional, Union
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
10
|
+
from haystack.components.converters.utils import (
|
|
11
|
+
get_bytestream_from_source,
|
|
12
|
+
normalize_metadata,
|
|
13
|
+
)
|
|
14
|
+
from haystack.dataclasses import ByteStream
|
|
15
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
16
|
+
from paddlex.inference.serving.schemas.paddleocr_vl import ( # type: ignore[import-untyped]
|
|
17
|
+
InferRequest as PaddleOCRVLInferRequest,
|
|
18
|
+
)
|
|
19
|
+
from paddlex.inference.serving.schemas.paddleocr_vl import ( # type: ignore[import-untyped]
|
|
20
|
+
InferResult as PaddleOCRVLInferResult,
|
|
21
|
+
)
|
|
22
|
+
from paddlex.inference.serving.schemas.shared.ocr import FileType # type: ignore[import-untyped]
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
FileTypeInput = Union[Literal["pdf", "image"], None]
|
|
28
|
+
|
|
29
|
+
# Supported image file extensions
|
|
30
|
+
_IMAGE_EXTENSIONS = {
|
|
31
|
+
".jpg",
|
|
32
|
+
".jpeg",
|
|
33
|
+
".png",
|
|
34
|
+
".bmp",
|
|
35
|
+
".tiff",
|
|
36
|
+
".tif",
|
|
37
|
+
".webp",
|
|
38
|
+
}
|
|
39
|
+
# Supported PDF file extensions
|
|
40
|
+
_PDF_EXTENSIONS = {".pdf"}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _infer_file_type_from_source(
|
|
44
|
+
source: Union[str, Path, ByteStream],
|
|
45
|
+
mime_type: Optional[str] = None,
|
|
46
|
+
) -> Optional[FileType]:
|
|
47
|
+
"""
|
|
48
|
+
Infer file type from file extension or MIME type.
|
|
49
|
+
|
|
50
|
+
:param source:
|
|
51
|
+
Original source (file path, Path object, or ByteStream).
|
|
52
|
+
:param mime_type:
|
|
53
|
+
MIME type of the source.
|
|
54
|
+
:returns:
|
|
55
|
+
Inferred file type: 0 for PDF, 1 for image, or None if cannot be
|
|
56
|
+
determined.
|
|
57
|
+
"""
|
|
58
|
+
# Try to get extension from file path
|
|
59
|
+
file_path: Optional[str] = None
|
|
60
|
+
|
|
61
|
+
# Check if source is a file path
|
|
62
|
+
if isinstance(source, (str, Path)):
|
|
63
|
+
file_path = str(source)
|
|
64
|
+
# Check if source is `ByteStream` and has `file_path` in metadata
|
|
65
|
+
elif isinstance(source, ByteStream) and source.meta:
|
|
66
|
+
file_path = source.meta.get("file_path")
|
|
67
|
+
|
|
68
|
+
# Try to infer from file extension
|
|
69
|
+
if file_path:
|
|
70
|
+
path_obj = Path(file_path)
|
|
71
|
+
extension = path_obj.suffix.lower()
|
|
72
|
+
|
|
73
|
+
if extension in _PDF_EXTENSIONS:
|
|
74
|
+
return 0
|
|
75
|
+
if extension in _IMAGE_EXTENSIONS:
|
|
76
|
+
return 1
|
|
77
|
+
|
|
78
|
+
# Try to infer from MIME type if available
|
|
79
|
+
if mime_type:
|
|
80
|
+
mime_type_lower = mime_type.lower()
|
|
81
|
+
if mime_type_lower == "application/pdf":
|
|
82
|
+
return 0
|
|
83
|
+
if mime_type_lower.startswith("image/"):
|
|
84
|
+
return 1
|
|
85
|
+
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _normalize_file_type(file_type: Optional[FileTypeInput]) -> Optional[FileType]:
|
|
90
|
+
"""
|
|
91
|
+
Normalize file type input to the numeric format expected by the API.
|
|
92
|
+
|
|
93
|
+
:param file_type:
|
|
94
|
+
File type input. Can be "pdf" for PDF, "image" for image,
|
|
95
|
+
or `None` for auto-detection.
|
|
96
|
+
:returns:
|
|
97
|
+
Normalized file type: 0 for PDF, 1 for image, or `None` for
|
|
98
|
+
auto-detection.
|
|
99
|
+
"""
|
|
100
|
+
if file_type is None:
|
|
101
|
+
return None
|
|
102
|
+
if isinstance(file_type, str):
|
|
103
|
+
if file_type.lower() == "pdf":
|
|
104
|
+
return 0
|
|
105
|
+
if file_type.lower() == "image":
|
|
106
|
+
return 1
|
|
107
|
+
msg = f"Invalid `file_type` string: {file_type}. Must be 'pdf' or 'image'."
|
|
108
|
+
raise ValueError(msg)
|
|
109
|
+
msg = f"Invalid `file_type` value: {file_type}. Must be 'pdf', 'image', or `None`."
|
|
110
|
+
raise ValueError(msg)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@component
|
|
114
|
+
class PaddleOCRVLDocumentConverter:
|
|
115
|
+
"""
|
|
116
|
+
This component extracts text from documents using PaddleOCR's large model
|
|
117
|
+
document parsing API.
|
|
118
|
+
|
|
119
|
+
PaddleOCR-VL is used behind the scenes. For more information, please
|
|
120
|
+
refer to:
|
|
121
|
+
https://www.paddleocr.ai/latest/en/version3.x/algorithm/PaddleOCR-VL/PaddleOCR-VL.html
|
|
122
|
+
|
|
123
|
+
**Usage Example:**
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from haystack.utils import Secret
|
|
127
|
+
from haystack_integrations.components.converters.paddleocr import (
|
|
128
|
+
PaddleOCRVLDocumentConverter,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
converter = PaddleOCRVLDocumentConverter(
|
|
132
|
+
api_url="http://xxxxx.aistudio-app.com/layout-parsing",
|
|
133
|
+
access_token=Secret.from_env_var("AISTUDIO_ACCESS_TOKEN"),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
result = converter.run(sources=["sample.pdf"])
|
|
137
|
+
|
|
138
|
+
documents = result["documents"]
|
|
139
|
+
raw_responses = result["raw_paddleocr_responses"]
|
|
140
|
+
```
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(
|
|
144
|
+
self,
|
|
145
|
+
*,
|
|
146
|
+
api_url: str,
|
|
147
|
+
access_token: Secret = Secret.from_env_var("AISTUDIO_ACCESS_TOKEN"),
|
|
148
|
+
file_type: Optional[FileTypeInput] = None,
|
|
149
|
+
use_doc_orientation_classify: Optional[bool] = None,
|
|
150
|
+
use_doc_unwarping: Optional[bool] = None,
|
|
151
|
+
use_layout_detection: Optional[bool] = None,
|
|
152
|
+
use_chart_recognition: Optional[bool] = None,
|
|
153
|
+
layout_threshold: Optional[Union[float, dict]] = None,
|
|
154
|
+
layout_nms: Optional[bool] = None,
|
|
155
|
+
layout_unclip_ratio: Optional[Union[float, tuple[float, float], dict]] = None,
|
|
156
|
+
layout_merge_bboxes_mode: Optional[Union[str, dict]] = None,
|
|
157
|
+
prompt_label: Optional[str] = None,
|
|
158
|
+
format_block_content: Optional[bool] = None,
|
|
159
|
+
repetition_penalty: Optional[float] = None,
|
|
160
|
+
temperature: Optional[float] = None,
|
|
161
|
+
top_p: Optional[float] = None,
|
|
162
|
+
min_pixels: Optional[int] = None,
|
|
163
|
+
max_pixels: Optional[int] = None,
|
|
164
|
+
prettify_markdown: Optional[bool] = None,
|
|
165
|
+
show_formula_number: Optional[bool] = None,
|
|
166
|
+
visualize: Optional[bool] = None,
|
|
167
|
+
additional_params: Optional[dict[str, Any]] = None,
|
|
168
|
+
):
|
|
169
|
+
"""
|
|
170
|
+
Create a `PaddleOCRVLDocumentConverter` component.
|
|
171
|
+
|
|
172
|
+
:param api_url:
|
|
173
|
+
API URL. To obtain the API URL, visit the [PaddleOCR official
|
|
174
|
+
website](https://aistudio.baidu.com/paddleocr/task), click the
|
|
175
|
+
**API** button in the upper-left corner, choose the example code
|
|
176
|
+
for **Large Model document parsing(PaddleOCR-VL)**, and copy the
|
|
177
|
+
`API_URL`.
|
|
178
|
+
:param access_token:
|
|
179
|
+
AI Studio access token. You can obtain it from [this
|
|
180
|
+
page](https://aistudio.baidu.com/account/accessToken).
|
|
181
|
+
:param file_type:
|
|
182
|
+
File type. Can be "pdf" for PDF files, "image" for
|
|
183
|
+
image files, or `None` for auto-detection. If not specified, the
|
|
184
|
+
file type will be inferred from the file extension.
|
|
185
|
+
:param use_doc_orientation_classify:
|
|
186
|
+
Whether to enable the document orientation classification
|
|
187
|
+
function. Enabling this feature allows the input image to be
|
|
188
|
+
automatically rotated to the correct orientation.
|
|
189
|
+
:param use_doc_unwarping:
|
|
190
|
+
Whether to enable the text image unwarping function. Enabling
|
|
191
|
+
this feature allows automatic correction of distorted text images.
|
|
192
|
+
:param use_layout_detection:
|
|
193
|
+
Whether to enable the layout detection function.
|
|
194
|
+
:param use_chart_recognition:
|
|
195
|
+
Whether to enable the chart recognition function.
|
|
196
|
+
:param layout_threshold:
|
|
197
|
+
Layout detection threshold. Can be a float or a dict with
|
|
198
|
+
page-specific thresholds.
|
|
199
|
+
:param layout_nms:
|
|
200
|
+
Whether to perform NMS (Non-Maximum Suppression) on layout
|
|
201
|
+
detection results.
|
|
202
|
+
:param layout_unclip_ratio:
|
|
203
|
+
Layout unclip ratio. Can be a float, a tuple of (min, max), or a
|
|
204
|
+
dict with page-specific values.
|
|
205
|
+
:param layout_merge_bboxes_mode:
|
|
206
|
+
Layout merge bounding boxes mode. Can be a string or a dict.
|
|
207
|
+
:param prompt_label:
|
|
208
|
+
Prompt type for the VLM. Possible values are "ocr", "formula",
|
|
209
|
+
"table", and "chart".
|
|
210
|
+
:param format_block_content:
|
|
211
|
+
Whether to format block content.
|
|
212
|
+
:param repetition_penalty:
|
|
213
|
+
Repetition penalty parameter used in VLM sampling.
|
|
214
|
+
:param temperature:
|
|
215
|
+
Temperature parameter used in VLM sampling.
|
|
216
|
+
:param top_p:
|
|
217
|
+
Top-p parameter used in VLM sampling.
|
|
218
|
+
:param min_pixels:
|
|
219
|
+
Minimum number of pixels allowed during VLM preprocessing.
|
|
220
|
+
:param max_pixels:
|
|
221
|
+
Maximum number of pixels allowed during VLM preprocessing.
|
|
222
|
+
:param prettify_markdown:
|
|
223
|
+
Whether to prettify the output Markdown text.
|
|
224
|
+
:param show_formula_number:
|
|
225
|
+
Whether to include formula numbers in the output markdown text.
|
|
226
|
+
:param visualize:
|
|
227
|
+
Whether to return visualization results.
|
|
228
|
+
:param additional_params:
|
|
229
|
+
Additional parameters for calling the PaddleOCR API.
|
|
230
|
+
"""
|
|
231
|
+
self.api_url = api_url
|
|
232
|
+
self.access_token = access_token
|
|
233
|
+
self.file_type = _normalize_file_type(file_type)
|
|
234
|
+
self.use_doc_orientation_classify = use_doc_orientation_classify
|
|
235
|
+
self.use_doc_unwarping = use_doc_unwarping
|
|
236
|
+
self.use_layout_detection = use_layout_detection
|
|
237
|
+
self.use_chart_recognition = use_chart_recognition
|
|
238
|
+
self.layout_threshold = layout_threshold
|
|
239
|
+
self.layout_nms = layout_nms
|
|
240
|
+
self.layout_unclip_ratio = layout_unclip_ratio
|
|
241
|
+
self.layout_merge_bboxes_mode = layout_merge_bboxes_mode
|
|
242
|
+
self.prompt_label = prompt_label
|
|
243
|
+
self.format_block_content = format_block_content
|
|
244
|
+
self.repetition_penalty = repetition_penalty
|
|
245
|
+
self.temperature = temperature
|
|
246
|
+
self.top_p = top_p
|
|
247
|
+
self.min_pixels = min_pixels
|
|
248
|
+
self.max_pixels = max_pixels
|
|
249
|
+
self.prettify_markdown = prettify_markdown
|
|
250
|
+
self.show_formula_number = show_formula_number
|
|
251
|
+
self.visualize = visualize
|
|
252
|
+
self.additional_params = additional_params
|
|
253
|
+
|
|
254
|
+
def to_dict(self) -> dict[str, Any]:
|
|
255
|
+
"""
|
|
256
|
+
Serialize the component to a dictionary.
|
|
257
|
+
|
|
258
|
+
:returns:
|
|
259
|
+
Dictionary with serialized data.
|
|
260
|
+
"""
|
|
261
|
+
return default_to_dict(
|
|
262
|
+
self,
|
|
263
|
+
api_url=self.api_url,
|
|
264
|
+
access_token=self.access_token.to_dict(),
|
|
265
|
+
file_type=self.file_type,
|
|
266
|
+
use_doc_orientation_classify=self.use_doc_orientation_classify,
|
|
267
|
+
use_doc_unwarping=self.use_doc_unwarping,
|
|
268
|
+
use_layout_detection=self.use_layout_detection,
|
|
269
|
+
use_chart_recognition=self.use_chart_recognition,
|
|
270
|
+
layout_threshold=self.layout_threshold,
|
|
271
|
+
layout_nms=self.layout_nms,
|
|
272
|
+
layout_unclip_ratio=self.layout_unclip_ratio,
|
|
273
|
+
layout_merge_bboxes_mode=self.layout_merge_bboxes_mode,
|
|
274
|
+
prompt_label=self.prompt_label,
|
|
275
|
+
format_block_content=self.format_block_content,
|
|
276
|
+
repetition_penalty=self.repetition_penalty,
|
|
277
|
+
temperature=self.temperature,
|
|
278
|
+
top_p=self.top_p,
|
|
279
|
+
min_pixels=self.min_pixels,
|
|
280
|
+
max_pixels=self.max_pixels,
|
|
281
|
+
prettify_markdown=self.prettify_markdown,
|
|
282
|
+
show_formula_number=self.show_formula_number,
|
|
283
|
+
visualize=self.visualize,
|
|
284
|
+
additional_params=self.additional_params,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
@classmethod
|
|
288
|
+
def from_dict(cls, data: dict[str, Any]) -> "PaddleOCRVLDocumentConverter":
|
|
289
|
+
"""
|
|
290
|
+
Deserialize the component from a dictionary.
|
|
291
|
+
|
|
292
|
+
:param data:
|
|
293
|
+
Dictionary to deserialize from.
|
|
294
|
+
:returns:
|
|
295
|
+
Deserialized component.
|
|
296
|
+
"""
|
|
297
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["access_token"])
|
|
298
|
+
return default_from_dict(cls, data)
|
|
299
|
+
|
|
300
|
+
def _parse(self, data: bytes, file_type: FileType) -> tuple[str, dict[str, Any]]:
|
|
301
|
+
"""
|
|
302
|
+
Parse document using PaddleOCR API.
|
|
303
|
+
|
|
304
|
+
:param data:
|
|
305
|
+
Raw file data as bytes.
|
|
306
|
+
:param file_type:
|
|
307
|
+
File type (0 for PDF, 1 for image).
|
|
308
|
+
:returns:
|
|
309
|
+
A tuple containing the extracted text (separated by form feed
|
|
310
|
+
characters for multiple pages) and the raw response dictionary.
|
|
311
|
+
:raises requests.RequestException:
|
|
312
|
+
If the API request fails.
|
|
313
|
+
:raises ValueError:
|
|
314
|
+
If the API response is invalid or missing required fields.
|
|
315
|
+
"""
|
|
316
|
+
# Encode file data to base64
|
|
317
|
+
encoded_data = base64.b64encode(data).decode("ascii")
|
|
318
|
+
|
|
319
|
+
# Build request payload
|
|
320
|
+
request_data = {
|
|
321
|
+
"file": encoded_data,
|
|
322
|
+
"fileType": file_type,
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
# Add optional parameters if they are set
|
|
326
|
+
if self.use_doc_orientation_classify is not None:
|
|
327
|
+
request_data["useDocOrientationClassify"] = self.use_doc_orientation_classify
|
|
328
|
+
if self.use_doc_unwarping is not None:
|
|
329
|
+
request_data["useDocUnwarping"] = self.use_doc_unwarping
|
|
330
|
+
if self.use_layout_detection is not None:
|
|
331
|
+
request_data["useLayoutDetection"] = self.use_layout_detection
|
|
332
|
+
if self.use_chart_recognition is not None:
|
|
333
|
+
request_data["useChartRecognition"] = self.use_chart_recognition
|
|
334
|
+
if self.layout_threshold is not None:
|
|
335
|
+
request_data["layoutThreshold"] = self.layout_threshold
|
|
336
|
+
if self.layout_nms is not None:
|
|
337
|
+
request_data["layoutNms"] = self.layout_nms
|
|
338
|
+
if self.layout_unclip_ratio is not None:
|
|
339
|
+
request_data["layoutUnclipRatio"] = self.layout_unclip_ratio
|
|
340
|
+
if self.layout_merge_bboxes_mode is not None:
|
|
341
|
+
request_data["layoutMergeBboxesMode"] = self.layout_merge_bboxes_mode
|
|
342
|
+
if self.prompt_label is not None:
|
|
343
|
+
request_data["promptLabel"] = self.prompt_label
|
|
344
|
+
if self.format_block_content is not None:
|
|
345
|
+
request_data["formatBlockContent"] = self.format_block_content
|
|
346
|
+
if self.repetition_penalty is not None:
|
|
347
|
+
request_data["repetitionPenalty"] = self.repetition_penalty
|
|
348
|
+
if self.temperature is not None:
|
|
349
|
+
request_data["temperature"] = self.temperature
|
|
350
|
+
if self.top_p is not None:
|
|
351
|
+
request_data["topP"] = self.top_p
|
|
352
|
+
if self.min_pixels is not None:
|
|
353
|
+
request_data["minPixels"] = self.min_pixels
|
|
354
|
+
if self.max_pixels is not None:
|
|
355
|
+
request_data["maxPixels"] = self.max_pixels
|
|
356
|
+
if self.prettify_markdown is not None:
|
|
357
|
+
request_data["prettifyMarkdown"] = self.prettify_markdown
|
|
358
|
+
if self.show_formula_number is not None:
|
|
359
|
+
request_data["showFormulaNumber"] = self.show_formula_number
|
|
360
|
+
if self.visualize is not None:
|
|
361
|
+
request_data["visualize"] = self.visualize
|
|
362
|
+
if self.additional_params is not None:
|
|
363
|
+
request_data.update(self.additional_params)
|
|
364
|
+
|
|
365
|
+
# Validate input parameters
|
|
366
|
+
try:
|
|
367
|
+
request = PaddleOCRVLInferRequest(**request_data)
|
|
368
|
+
request_dict = request.model_dump(exclude_none=True)
|
|
369
|
+
except Exception as e:
|
|
370
|
+
msg = f"Invalid request parameters: {e}"
|
|
371
|
+
raise ValueError(msg) from e
|
|
372
|
+
|
|
373
|
+
# Prepare headers with authentication
|
|
374
|
+
access_token_value = self.access_token.resolve_value() if self.access_token else None
|
|
375
|
+
headers = {"Content-Type": "application/json"}
|
|
376
|
+
if access_token_value:
|
|
377
|
+
headers["Authorization"] = f"token {access_token_value}"
|
|
378
|
+
|
|
379
|
+
# Make API request
|
|
380
|
+
try:
|
|
381
|
+
response = requests.post(
|
|
382
|
+
self.api_url,
|
|
383
|
+
json=request_dict,
|
|
384
|
+
headers=headers,
|
|
385
|
+
timeout=300,
|
|
386
|
+
)
|
|
387
|
+
response.raise_for_status()
|
|
388
|
+
except requests.RequestException as e:
|
|
389
|
+
logger.error(f"Failed to call PaddleOCR API: {e}")
|
|
390
|
+
raise
|
|
391
|
+
|
|
392
|
+
# Parse and validate response
|
|
393
|
+
try:
|
|
394
|
+
response_data = response.json()
|
|
395
|
+
except ValueError as e:
|
|
396
|
+
msg = f"Invalid JSON response from API: {e}"
|
|
397
|
+
raise ValueError(msg) from e
|
|
398
|
+
|
|
399
|
+
if "result" not in response_data:
|
|
400
|
+
msg = "Response missing 'result' field"
|
|
401
|
+
raise ValueError(msg)
|
|
402
|
+
|
|
403
|
+
try:
|
|
404
|
+
result = PaddleOCRVLInferResult(**response_data["result"])
|
|
405
|
+
except Exception as e:
|
|
406
|
+
msg = f"Invalid response format: {e}"
|
|
407
|
+
raise ValueError(msg) from e
|
|
408
|
+
|
|
409
|
+
# Extract text from markdown in layout parsing results
|
|
410
|
+
# Pages are separated by form feed character (\f) for compatibility
|
|
411
|
+
# with Haystack's `DocumentSplitter`
|
|
412
|
+
text_parts = []
|
|
413
|
+
for layout_result in result.layoutParsingResults:
|
|
414
|
+
if layout_result.markdown and layout_result.markdown.text:
|
|
415
|
+
text_parts.append(layout_result.markdown.text)
|
|
416
|
+
|
|
417
|
+
text = "\f".join(text_parts) if text_parts else ""
|
|
418
|
+
|
|
419
|
+
return text, response_data
|
|
420
|
+
|
|
421
|
+
@component.output_types(documents=list[Document], raw_paddleocr_responses=list[dict[str, Any]])
|
|
422
|
+
def run(
|
|
423
|
+
self,
|
|
424
|
+
sources: list[Union[str, Path, ByteStream]],
|
|
425
|
+
meta: Optional[Union[dict[str, Any], list[dict[str, Any]]]] = None,
|
|
426
|
+
) -> dict[str, Any]:
|
|
427
|
+
"""
|
|
428
|
+
Convert image or PDF files to Documents.
|
|
429
|
+
|
|
430
|
+
:param sources:
|
|
431
|
+
List of image or PDF file paths or ByteStream objects.
|
|
432
|
+
:param meta:
|
|
433
|
+
Optional metadata to attach to the Documents.
|
|
434
|
+
This value can be either a list of dictionaries or a single
|
|
435
|
+
dictionary. If it's a single dictionary, its content is added to
|
|
436
|
+
the metadata of all produced Documents. If it's a list, the length
|
|
437
|
+
of the list must match the number of sources, because the two
|
|
438
|
+
lists will be zipped. If `sources` contains ByteStream objects,
|
|
439
|
+
their `meta` will be added to the output Documents.
|
|
440
|
+
|
|
441
|
+
:returns:
|
|
442
|
+
A dictionary with the following keys:
|
|
443
|
+
- `documents`: A list of created Documents.
|
|
444
|
+
- `raw_paddleocr_responses`: A list of raw PaddleOCR API responses.
|
|
445
|
+
"""
|
|
446
|
+
documents = []
|
|
447
|
+
raw_responses = []
|
|
448
|
+
|
|
449
|
+
meta_list = normalize_metadata(meta, sources_count=len(sources))
|
|
450
|
+
|
|
451
|
+
for source, metadata in zip(sources, meta_list):
|
|
452
|
+
try:
|
|
453
|
+
bytestream = get_bytestream_from_source(source)
|
|
454
|
+
except Exception as e:
|
|
455
|
+
logger.warning(
|
|
456
|
+
f"Could not read {source}. Skipping it. Error: {e}",
|
|
457
|
+
)
|
|
458
|
+
continue
|
|
459
|
+
|
|
460
|
+
# Determine file type (either from config or inferred from extension)
|
|
461
|
+
if self.file_type is not None:
|
|
462
|
+
file_type = self.file_type
|
|
463
|
+
else:
|
|
464
|
+
mime_type = bytestream.mime_type if hasattr(bytestream, "mime_type") and bytestream.mime_type else None
|
|
465
|
+
file_type = _infer_file_type_from_source(source, mime_type)
|
|
466
|
+
if file_type is None:
|
|
467
|
+
logger.warning(
|
|
468
|
+
f"Could not determine file type for {source}. Skipping it.",
|
|
469
|
+
)
|
|
470
|
+
continue
|
|
471
|
+
|
|
472
|
+
try:
|
|
473
|
+
text, raw_resp = self._parse(bytestream.data, file_type)
|
|
474
|
+
except Exception as e:
|
|
475
|
+
logger.warning(
|
|
476
|
+
f"Could not read {source} and convert it to Document, skipping. Error: {e}",
|
|
477
|
+
)
|
|
478
|
+
continue
|
|
479
|
+
|
|
480
|
+
if not text:
|
|
481
|
+
msg = (
|
|
482
|
+
f"{self.__class__.__name__} could not extract text"
|
|
483
|
+
" from the file {source}. Returning an empty document."
|
|
484
|
+
)
|
|
485
|
+
logger.warning(msg)
|
|
486
|
+
|
|
487
|
+
merged_metadata = {**bytestream.meta, **metadata}
|
|
488
|
+
|
|
489
|
+
document = Document(content=text, meta=merged_metadata)
|
|
490
|
+
documents.append(document)
|
|
491
|
+
|
|
492
|
+
raw_responses.append(raw_resp)
|
|
493
|
+
|
|
494
|
+
return {"documents": documents, "raw_paddleocr_responses": raw_responses}
|
|
File without changes
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: paddleocr-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An integration of PaddleOCR with Haystack
|
|
5
|
+
Project-URL: Documentation, https://github.com/haystack-core-integrations/tree/main/integrations/paddleocr#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/haystack-core-integrations/tree/main/integrations/paddleocr
|
|
8
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Requires-Dist: haystack-ai>=2.19.0
|
|
21
|
+
Requires-Dist: paddleocr>=3.3.2
|
|
22
|
+
Requires-Dist: paddlex[serving]>=3.3.10
|
|
23
|
+
Requires-Dist: requests>=2.25.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# paddleocr-haystack
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/paddleocr-haystack)
|
|
29
|
+
[](https://pypi.org/project/paddleocr-haystack)
|
|
30
|
+
|
|
31
|
+
- [Integration page](https://haystack.deepset.ai/integrations/paddleocr)
|
|
32
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/paddleocr/CHANGELOG.md)
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Contributing
|
|
37
|
+
|
|
38
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
39
|
+
|
|
40
|
+
To run integration tests locally, you need to export the `PADDLEOCR_VL_API_URL` and `AISTUDIO_ACCESS_TOKEN` environment variables.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
haystack_integrations/components/converters/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
haystack_integrations/components/converters/paddleocr/__init__.py,sha256=EyXp3NMyaLxz5YJtY-ikuW_WvJshGMUAh3rsFhj3_zg,228
|
|
3
|
+
haystack_integrations/components/converters/paddleocr/paddleocr_vl_document_converter.py,sha256=IodwgCzCzqYj2_gIcaZP3ApIc4jSTLUJlqbHWUZ3LqY,19493
|
|
4
|
+
paddleocr_haystack-0.1.0.dist-info/METADATA,sha256=6DfHATvknBcDiL9yVvvosHyZdop0L_MJKy758p-8IHo,1891
|
|
5
|
+
paddleocr_haystack-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
6
|
+
paddleocr_haystack-0.1.0.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
|
|
7
|
+
paddleocr_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.
|