docling-serve-haystack 1.0.0__tar.gz

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.
@@ -0,0 +1,146 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ volumes/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+
114
+ # Spyder project settings
115
+ .spyderproject
116
+ .spyproject
117
+
118
+ # Rope project settings
119
+ .ropeproject
120
+
121
+ # mkdocs documentation
122
+ /site
123
+
124
+ # mypy
125
+ .mypy_cache/
126
+ .dmypy.json
127
+ dmypy.json
128
+
129
+ # Pyre type checker
130
+ .pyre/
131
+
132
+ # IDEs
133
+ .vscode
134
+
135
+ # Docs generation artifacts
136
+ _readme_*.md
137
+ .idea
138
+
139
+ # macOS
140
+ .DS_Store
141
+
142
+ # http cache (requests-cache)
143
+ **/http_cache.sqlite
144
+
145
+ # ruff
146
+ .ruff_cache
@@ -0,0 +1,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: docling-serve-haystack
3
+ Version: 1.0.0
4
+ Summary: Haystack converter component for DoclingServe — document conversion via HTTP
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/docling_serve#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/docling_serve
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: Docling,DoclingServe,Haystack,OCR,PDF,document conversion
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
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: haystack-ai>=2.9.0
24
+ Requires-Dist: httpx>=0.27.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # docling-serve-haystack
28
+
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/docling-serve-haystack.svg)](https://pypi.org/project/docling-serve-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/docling-serve-haystack.svg)](https://pypi.org/project/docling-serve-haystack)
31
+
32
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/docling_serve/CHANGELOG.md)
33
+
34
+ ---
35
+
36
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,10 @@
1
+ # docling-serve-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/docling-serve-haystack.svg)](https://pypi.org/project/docling-serve-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/docling-serve-haystack.svg)](https://pypi.org/project/docling-serve-haystack)
5
+
6
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/docling_serve/CHANGELOG.md)
7
+
8
+ ---
9
+
10
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,13 @@
1
+ loaders:
2
+ - modules:
3
+ - haystack_integrations.components.converters.docling_serve.converter
4
+ search_path: [../src]
5
+ processors:
6
+ - type: filter
7
+ documented_only: true
8
+ skip_empty_modules: true
9
+ renderer:
10
+ description: Docling Serve integration for Haystack
11
+ id: integrations-docling_serve
12
+ filename: docling_serve.md
13
+ title: Docling Serve
@@ -0,0 +1,163 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "docling-serve-haystack"
7
+ dynamic = ["version"]
8
+ description = "Haystack converter component for DoclingServe — document conversion via HTTP"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = ["Haystack", "Docling", "DoclingServe", "document conversion", "PDF", "OCR"]
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: Implementation :: CPython",
24
+ "Programming Language :: Python :: Implementation :: PyPy",
25
+ ]
26
+ dependencies = [
27
+ "haystack-ai>=2.9.0",
28
+ "httpx>=0.27.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/docling_serve#readme"
33
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
34
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/docling_serve"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/haystack_integrations"]
38
+
39
+ [tool.hatch.version]
40
+ source = "vcs"
41
+ tag-pattern = 'integrations\/docling_serve-v(?P<version>.*)'
42
+
43
+ [tool.hatch.version.raw-options]
44
+ root = "../.."
45
+ git_describe_command = 'git describe --tags --match="integrations/docling_serve-v[0-9]*"'
46
+
47
+ [tool.hatch.envs.default]
48
+ installer = "uv"
49
+ dependencies = ["haystack-pydoc-tools", "ruff"]
50
+
51
+ [tool.hatch.envs.default.scripts]
52
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
53
+ fmt = "ruff check --fix {args}; ruff format {args}"
54
+ fmt-check = "ruff check {args} && ruff format --check {args}"
55
+
56
+ [tool.hatch.envs.test]
57
+ dependencies = [
58
+ "pytest",
59
+ "pytest-asyncio",
60
+ "pytest-cov",
61
+ "pytest-rerunfailures",
62
+ "mypy",
63
+ "pip",
64
+ ]
65
+
66
+ [tool.hatch.envs.test.scripts]
67
+ unit = 'pytest -m "not integration" {args:tests}'
68
+ integration = 'pytest -m "integration" {args:tests}'
69
+ all = 'pytest {args:tests}'
70
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
71
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
72
+ types = "mypy -p haystack_integrations.components.converters.docling_serve {args}"
73
+
74
+ [tool.mypy]
75
+ install_types = true
76
+ non_interactive = true
77
+ check_untyped_defs = true
78
+ disallow_incomplete_defs = true
79
+
80
+ [[tool.mypy.overrides]]
81
+ module = ["httpx"]
82
+ ignore_missing_imports = true
83
+
84
+ [tool.ruff]
85
+ line-length = 120
86
+
87
+ [tool.ruff.lint]
88
+ select = [
89
+ "A",
90
+ "ANN",
91
+ "ARG",
92
+ "B",
93
+ "C",
94
+ "D102",
95
+ "D103",
96
+ "D205",
97
+ "D209",
98
+ "D213",
99
+ "D417",
100
+ "D419",
101
+ "DTZ",
102
+ "E",
103
+ "EM",
104
+ "F",
105
+ "I",
106
+ "ICN",
107
+ "ISC",
108
+ "N",
109
+ "PLC",
110
+ "PLE",
111
+ "PLR",
112
+ "PLW",
113
+ "Q",
114
+ "RUF",
115
+ "S",
116
+ "T",
117
+ "TID",
118
+ "UP",
119
+ "W",
120
+ "YTT",
121
+ ]
122
+ ignore = [
123
+ "B027",
124
+ "B008",
125
+ "S105",
126
+ "S106",
127
+ "S107",
128
+ "C901",
129
+ "PLR0911",
130
+ "PLR0912",
131
+ "PLR0913",
132
+ "PLR0915",
133
+ "ANN401",
134
+ ]
135
+
136
+ [tool.ruff.lint.isort]
137
+ known-first-party = ["haystack_integrations"]
138
+
139
+ [tool.ruff.lint.flake8-tidy-imports]
140
+ ban-relative-imports = "parents"
141
+
142
+ [tool.ruff.lint.per-file-ignores]
143
+ "tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"]
144
+
145
+ [tool.coverage.run]
146
+ source = ["haystack_integrations"]
147
+ branch = true
148
+ relative_files = true
149
+ parallel = false
150
+
151
+ [tool.coverage.report]
152
+ omit = ["*/tests/*", "*/__init__.py"]
153
+ show_missing = true
154
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
155
+
156
+ [tool.pytest.ini_options]
157
+ addopts = "--strict-markers"
158
+ markers = [
159
+ "integration: integration tests",
160
+ ]
161
+ log_cli = true
162
+ asyncio_mode = "auto"
163
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from haystack_integrations.components.converters.docling_serve.converter import DoclingServeConverter, ExportType
6
+
7
+ __all__ = ["DoclingServeConverter", "ExportType"]
@@ -0,0 +1,335 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import json
6
+ import mimetypes
7
+ from enum import Enum
8
+ from pathlib import Path
9
+ from typing import Any
10
+ from urllib.parse import urlparse
11
+
12
+ import httpx
13
+ from haystack import Document, component, default_from_dict, default_to_dict, logging
14
+ from haystack.components.converters.utils import normalize_metadata
15
+ from haystack.dataclasses import ByteStream
16
+ from haystack.utils import Secret, deserialize_secrets_inplace
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ _FILE_CONVERT_PATH = "/v1/convert/file"
21
+ _SOURCE_CONVERT_PATH = "/v1/convert/source"
22
+
23
+
24
+ class ExportType(str, Enum):
25
+ """
26
+ Enumeration of export formats supported by DoclingServe.
27
+
28
+ - `MARKDOWN`: Converts documents to Markdown format.
29
+ - `TEXT`: Extracts plain text.
30
+ - `JSON`: Returns the full Docling document as a JSON string.
31
+ """
32
+
33
+ MARKDOWN = "markdown"
34
+ TEXT = "text"
35
+ JSON = "json"
36
+
37
+
38
+ def _is_url(source: str) -> bool:
39
+ parsed = urlparse(source)
40
+ return parsed.scheme in ("http", "https")
41
+
42
+
43
+ def _resolve_filename(source: str | Path | ByteStream) -> str:
44
+ """Extract a filename for a source, used as a hint to docling-serve for format detection."""
45
+ if isinstance(source, ByteStream):
46
+ meta = source.meta or {}
47
+ raw = meta.get("file_path") or meta.get("file_name") or meta.get("name")
48
+ return Path(raw).name if raw else "document"
49
+ return Path(source).name
50
+
51
+
52
+ def _guess_mime_type(filename: str) -> str:
53
+ return mimetypes.guess_type(filename)[0] or "application/octet-stream"
54
+
55
+
56
+ @component
57
+ class DoclingServeConverter:
58
+ """
59
+ Converts documents to Haystack Documents using a DoclingServe server.
60
+
61
+ See [DoclingServe](https://github.com/docling-project/docling-serve).
62
+
63
+ DoclingServe hosts Docling in a scalable HTTP server, supporting PDFs, Office documents, HTML, and many other
64
+ formats. Unlike the local `DoclingConverter`, this component has no heavy ML dependencies — all processing
65
+ happens on the remote server.
66
+
67
+ Local files and ByteStreams are uploaded via the ``/v1/convert/file`` endpoint. URL strings are sent to
68
+ ``/v1/convert/source``.
69
+
70
+ Supports both synchronous (`run`) and asynchronous (`run_async`) execution.
71
+
72
+ ### Usage example
73
+
74
+ ```python
75
+ from haystack_integrations.components.converters.docling_serve import DoclingServeConverter
76
+
77
+ converter = DoclingServeConverter(base_url="http://localhost:5001")
78
+ result = converter.run(sources=["https://arxiv.org/pdf/2206.01062"])
79
+ print(result["documents"][0].content[:200])
80
+ ```
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ *,
86
+ base_url: str = "http://localhost:5001",
87
+ export_type: ExportType = ExportType.MARKDOWN,
88
+ convert_options: dict[str, Any] | None = None,
89
+ timeout: float = 120.0,
90
+ api_key: Secret | None = Secret.from_env_var("DOCLING_SERVE_API_KEY", strict=False),
91
+ ) -> None:
92
+ """
93
+ Initializes the DoclingServeConverter.
94
+
95
+ :param base_url:
96
+ Base URL of the DoclingServe instance. Defaults to `"http://localhost:5001"`.
97
+ :param export_type:
98
+ The output format for converted documents. One of `ExportType.MARKDOWN` (default),
99
+ `ExportType.TEXT`, or `ExportType.JSON`.
100
+ :param convert_options:
101
+ Optional dictionary of conversion options passed directly to the DoclingServe API
102
+ (e.g. `{"do_ocr": True, "ocr_engine": "tesseract"}`).
103
+ See [DoclingServe options](https://github.com/docling-project/docling-serve/blob/main/docs/usage.md).
104
+ Note: `to_formats` is set automatically based on `export_type` and should not be included here.
105
+ :param timeout:
106
+ HTTP request timeout in seconds. Defaults to `120.0`.
107
+ :param api_key:
108
+ API key for authenticating with a secured DoclingServe instance. Reads from the
109
+ `DOCLING_SERVE_API_KEY` environment variable by default. Set to `None` to disable
110
+ authentication.
111
+ """
112
+ self.base_url = base_url.rstrip("/")
113
+ self.export_type = ExportType(export_type)
114
+ self.convert_options = dict(convert_options) if convert_options else {}
115
+ self.timeout = timeout
116
+ self.api_key = api_key
117
+
118
+ def to_dict(self) -> dict[str, Any]:
119
+ """
120
+ Serializes the component to a dictionary.
121
+
122
+ :returns:
123
+ A dictionary representation of the component.
124
+ """
125
+ return default_to_dict(
126
+ self,
127
+ base_url=self.base_url,
128
+ export_type=self.export_type.value,
129
+ convert_options=self.convert_options,
130
+ timeout=self.timeout,
131
+ api_key=self.api_key.to_dict() if self.api_key else None,
132
+ )
133
+
134
+ @classmethod
135
+ def from_dict(cls, data: dict[str, Any]) -> "DoclingServeConverter":
136
+ """
137
+ Deserializes the component from a dictionary.
138
+
139
+ :param data:
140
+ Dictionary representation of the component.
141
+ :returns:
142
+ A new `DoclingServeConverter` instance.
143
+ """
144
+ deserialize_secrets_inplace(data.get("init_parameters", {}), keys=["api_key"])
145
+ return default_from_dict(cls, data)
146
+
147
+ def _headers(self) -> dict[str, str]:
148
+ headers: dict[str, str] = {}
149
+ if self.api_key:
150
+ resolved = self.api_key.resolve_value()
151
+ if resolved:
152
+ headers["X-Api-Key"] = resolved
153
+ return headers
154
+
155
+ def _to_format(self) -> str:
156
+ return {"markdown": "md", "text": "text", "json": "json"}[self.export_type.value]
157
+
158
+ def _extract_content(self, data: dict[str, Any]) -> str | None:
159
+ doc = data.get("document", {})
160
+ if self.export_type == ExportType.MARKDOWN:
161
+ return doc.get("md_content")
162
+ if self.export_type == ExportType.TEXT:
163
+ return doc.get("text_content")
164
+ if self.export_type == ExportType.JSON:
165
+ content = doc.get("json_content")
166
+ return json.dumps(content) if content is not None else None
167
+ return None
168
+
169
+ def _post_file(self, client: httpx.Client, source: str | Path | ByteStream) -> dict[str, Any]:
170
+ filename = _resolve_filename(source)
171
+ file_bytes = source.data if isinstance(source, ByteStream) else Path(source).read_bytes()
172
+ mime_type = (
173
+ (source.mime_type or _guess_mime_type(filename))
174
+ if isinstance(source, ByteStream)
175
+ else _guess_mime_type(filename)
176
+ )
177
+ options = {**self.convert_options, "to_formats": self._to_format()}
178
+ response = client.post(
179
+ f"{self.base_url}{_FILE_CONVERT_PATH}",
180
+ files={"files": (filename, file_bytes, mime_type)},
181
+ data=options,
182
+ headers=self._headers(),
183
+ )
184
+ response.raise_for_status()
185
+ return response.json()
186
+
187
+ def _post_url(self, client: httpx.Client, url: str) -> dict[str, Any]:
188
+ payload: dict[str, Any] = {
189
+ "options": {**self.convert_options, "to_formats": [self._to_format()]},
190
+ "sources": [{"kind": "http", "url": url}],
191
+ }
192
+ response = client.post(
193
+ f"{self.base_url}{_SOURCE_CONVERT_PATH}",
194
+ json=payload,
195
+ headers=self._headers(),
196
+ )
197
+ response.raise_for_status()
198
+ return response.json()
199
+
200
+ async def _post_file_async(self, client: httpx.AsyncClient, source: str | Path | ByteStream) -> dict[str, Any]:
201
+ filename = _resolve_filename(source)
202
+ file_bytes = source.data if isinstance(source, ByteStream) else Path(source).read_bytes()
203
+ mime_type = (
204
+ (source.mime_type or _guess_mime_type(filename))
205
+ if isinstance(source, ByteStream)
206
+ else _guess_mime_type(filename)
207
+ )
208
+ options = {**self.convert_options, "to_formats": self._to_format()}
209
+ response = await client.post(
210
+ f"{self.base_url}{_FILE_CONVERT_PATH}",
211
+ files={"files": (filename, file_bytes, mime_type)},
212
+ data=options,
213
+ headers=self._headers(),
214
+ )
215
+ response.raise_for_status()
216
+ return response.json()
217
+
218
+ async def _post_url_async(self, client: httpx.AsyncClient, url: str) -> dict[str, Any]:
219
+ payload: dict[str, Any] = {
220
+ "options": {**self.convert_options, "to_formats": [self._to_format()]},
221
+ "sources": [{"kind": "http", "url": url}],
222
+ }
223
+ response = await client.post(
224
+ f"{self.base_url}{_SOURCE_CONVERT_PATH}",
225
+ json=payload,
226
+ headers=self._headers(),
227
+ )
228
+ response.raise_for_status()
229
+ return response.json()
230
+
231
+ @component.output_types(documents=list[Document])
232
+ def run(
233
+ self,
234
+ sources: list[str | Path | ByteStream],
235
+ meta: dict[str, Any] | list[dict[str, Any]] | None = None,
236
+ ) -> dict[str, list[Document]]:
237
+ """
238
+ Converts documents by sending them to DoclingServe and returns Haystack Documents.
239
+
240
+ :param sources:
241
+ List of sources to convert. Each item can be a URL string, a local file path, or a
242
+ `ByteStream`. URL strings are sent to `/v1/convert/source`; all other sources are
243
+ uploaded to `/v1/convert/file`.
244
+ :param meta:
245
+ Optional metadata to attach to the output Documents. Can be a single dict applied to
246
+ all documents, or a list of dicts with one entry per source.
247
+ :returns:
248
+ A dictionary with key `"documents"` containing the converted Haystack Documents.
249
+ """
250
+ meta_list = normalize_metadata(meta=meta, sources_count=len(sources))
251
+ documents: list[Document] = []
252
+
253
+ with httpx.Client(timeout=self.timeout) as client:
254
+ for source, source_meta in zip(sources, meta_list, strict=True):
255
+ bytestream_meta = source.meta or {} if isinstance(source, ByteStream) else {}
256
+ merged_meta = {**bytestream_meta, **source_meta}
257
+ try:
258
+ if isinstance(source, str) and _is_url(source):
259
+ result = self._post_url(client, source)
260
+ else:
261
+ result = self._post_file(client, source)
262
+ content = self._extract_content(result)
263
+ if content is not None:
264
+ documents.append(Document(content=content, meta=merged_meta))
265
+ else:
266
+ logger.warning("No content returned for source {source}.", source=source)
267
+ except httpx.HTTPStatusError as e:
268
+ logger.warning(
269
+ "DoclingServe returned HTTP {status} for {source}: {body}",
270
+ status=e.response.status_code,
271
+ source=source,
272
+ body=e.response.text,
273
+ )
274
+ except httpx.HTTPError as e:
275
+ logger.warning(
276
+ "Could not connect to DoclingServe for {source}. Skipping it. Error: {error}",
277
+ source=source,
278
+ error=e,
279
+ )
280
+
281
+ return {"documents": documents}
282
+
283
+ @component.output_types(documents=list[Document])
284
+ async def run_async(
285
+ self,
286
+ sources: list[str | Path | ByteStream],
287
+ meta: dict[str, Any] | list[dict[str, Any]] | None = None,
288
+ ) -> dict[str, list[Document]]:
289
+ """
290
+ Asynchronously converts documents by sending them to DoclingServe.
291
+
292
+ This is the async equivalent of `run()`, useful when DoclingServe requests should not
293
+ block the event loop.
294
+
295
+ :param sources:
296
+ List of sources to convert. Each item can be a URL string, a local file path, or a
297
+ `ByteStream`. URL strings are sent to `/v1/convert/source`; all other sources are
298
+ uploaded to `/v1/convert/file`.
299
+ :param meta:
300
+ Optional metadata to attach to the output Documents.
301
+ :returns:
302
+ A dictionary with key `"documents"` containing the converted Haystack Documents.
303
+ """
304
+ meta_list = normalize_metadata(meta=meta, sources_count=len(sources))
305
+ documents: list[Document] = []
306
+
307
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
308
+ for source, source_meta in zip(sources, meta_list, strict=True):
309
+ bytestream_meta = source.meta or {} if isinstance(source, ByteStream) else {}
310
+ merged_meta = {**bytestream_meta, **source_meta}
311
+ try:
312
+ if isinstance(source, str) and _is_url(source):
313
+ result = await self._post_url_async(client, source)
314
+ else:
315
+ result = await self._post_file_async(client, source)
316
+ content = self._extract_content(result)
317
+ if content is not None:
318
+ documents.append(Document(content=content, meta=merged_meta))
319
+ else:
320
+ logger.warning("No content returned for source {source}.", source=source)
321
+ except httpx.HTTPStatusError as e:
322
+ logger.warning(
323
+ "DoclingServe returned HTTP {status} for {source}: {body}",
324
+ status=e.response.status_code,
325
+ source=source,
326
+ body=e.response.text,
327
+ )
328
+ except httpx.HTTPError as e:
329
+ logger.warning(
330
+ "Could not connect to DoclingServe for {source}. Skipping it. Error: {error}",
331
+ source=source,
332
+ error=e,
333
+ )
334
+
335
+ return {"documents": documents}
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,424 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import json
6
+ import logging
7
+ from unittest.mock import AsyncMock, patch
8
+
9
+ import httpx
10
+ import pytest
11
+ from haystack.dataclasses import ByteStream
12
+ from haystack.utils import Secret
13
+
14
+ from haystack_integrations.components.converters.docling_serve import DoclingServeConverter, ExportType
15
+
16
+
17
+ def _mock_httpx_response(content: str, export_type: ExportType = ExportType.MARKDOWN) -> httpx.Response:
18
+ content_key = {"markdown": "md_content", "text": "text_content", "json": "json_content"}[export_type.value]
19
+ json_data: dict = {"document": {content_key: content}, "status": "success"}
20
+ return httpx.Response(200, json=json_data, request=httpx.Request("POST", "http://test"))
21
+
22
+
23
+ class TestDoclingServeConverterInit:
24
+ def test_defaults(self, monkeypatch):
25
+ monkeypatch.delenv("DOCLING_SERVE_API_KEY", raising=False)
26
+ converter = DoclingServeConverter()
27
+ assert converter.base_url == "http://localhost:5001"
28
+ assert converter.export_type == ExportType.MARKDOWN
29
+ assert converter.convert_options == {}
30
+ assert converter.timeout == 120.0
31
+ # Default is Secret(DOCLING_SERVE_API_KEY, strict=False) — resolves to None when env var is unset
32
+ assert converter.api_key is not None
33
+ assert converter.api_key.resolve_value() is None
34
+
35
+ def test_custom_params(self):
36
+ converter = DoclingServeConverter(
37
+ base_url="http://myserver:8080/",
38
+ export_type=ExportType.TEXT,
39
+ convert_options={"do_ocr": True},
40
+ timeout=60.0,
41
+ api_key=None,
42
+ )
43
+ assert converter.base_url == "http://myserver:8080" # trailing slash stripped
44
+ assert converter.export_type == ExportType.TEXT
45
+ assert converter.convert_options == {"do_ocr": True}
46
+ assert converter.timeout == 60.0
47
+
48
+ def test_trailing_slash_stripped(self):
49
+ converter = DoclingServeConverter(base_url="http://localhost:5001/")
50
+ assert converter.base_url == "http://localhost:5001"
51
+
52
+ def test_api_key_from_env(self, monkeypatch):
53
+ monkeypatch.setenv("DOCLING_SERVE_API_KEY", "test-key")
54
+ converter = DoclingServeConverter()
55
+ assert converter.api_key is not None
56
+ assert converter.api_key.resolve_value() == "test-key"
57
+
58
+ def test_api_key_none_overrides_env(self, monkeypatch):
59
+ monkeypatch.setenv("DOCLING_SERVE_API_KEY", "test-key")
60
+ converter = DoclingServeConverter(api_key=None)
61
+ assert converter.api_key is None
62
+
63
+
64
+ class TestDoclingServeConverterSerialization:
65
+ def test_to_dict(self):
66
+ converter = DoclingServeConverter(
67
+ base_url="http://localhost:5001",
68
+ export_type=ExportType.TEXT,
69
+ convert_options={"do_ocr": False},
70
+ timeout=30.0,
71
+ api_key=None,
72
+ )
73
+ data = converter.to_dict()
74
+ assert data["type"].endswith("DoclingServeConverter")
75
+ params = data["init_parameters"]
76
+ assert params["base_url"] == "http://localhost:5001"
77
+ assert params["export_type"] == "text"
78
+ assert params["convert_options"] == {"do_ocr": False}
79
+ assert params["timeout"] == 30.0
80
+ assert params["api_key"] is None
81
+
82
+ def test_from_dict(self):
83
+ data = {
84
+ "type": "haystack_integrations.components.converters.docling_serve.converter.DoclingServeConverter",
85
+ "init_parameters": {
86
+ "base_url": "http://myserver:9000",
87
+ "export_type": "json",
88
+ "convert_options": {},
89
+ "timeout": 60.0,
90
+ "api_key": None,
91
+ },
92
+ }
93
+ converter = DoclingServeConverter.from_dict(data)
94
+ assert converter.base_url == "http://myserver:9000"
95
+ assert converter.export_type == ExportType.JSON
96
+ assert converter.timeout == 60.0
97
+
98
+ def test_to_dict_with_api_key(self, monkeypatch):
99
+ monkeypatch.setenv("DOCLING_API_KEY", "test-key")
100
+ converter = DoclingServeConverter(api_key=Secret.from_env_var("DOCLING_API_KEY"))
101
+ data = converter.to_dict()
102
+ assert data["init_parameters"]["api_key"] is not None
103
+ assert data["init_parameters"]["api_key"]["type"] == "env_var"
104
+
105
+ def test_roundtrip(self, monkeypatch):
106
+ monkeypatch.setenv("MY_KEY", "val")
107
+ converter = DoclingServeConverter(
108
+ base_url="http://remote:5001",
109
+ export_type=ExportType.MARKDOWN,
110
+ convert_options={"table_mode": "fast"},
111
+ timeout=45.0,
112
+ api_key=Secret.from_env_var("MY_KEY"),
113
+ )
114
+ data = converter.to_dict()
115
+ restored = DoclingServeConverter.from_dict(data)
116
+ assert restored.base_url == converter.base_url
117
+ assert restored.export_type == converter.export_type
118
+ assert restored.convert_options == converter.convert_options
119
+ assert restored.timeout == converter.timeout
120
+ assert restored.api_key is not None
121
+
122
+
123
+ class TestDoclingServeConverterHeaders:
124
+ def test_no_api_key(self):
125
+ converter = DoclingServeConverter(api_key=None)
126
+ assert converter._headers() == {}
127
+
128
+ def test_with_api_key(self):
129
+ converter = DoclingServeConverter(api_key=Secret.from_token("my-secret-token"))
130
+ headers = converter._headers()
131
+ assert headers["X-Api-Key"] == "my-secret-token"
132
+
133
+
134
+ class TestDoclingServeConverterRun:
135
+ def test_run_url_source(self):
136
+ converter = DoclingServeConverter(api_key=None)
137
+ mock_resp = _mock_httpx_response("# Hello World")
138
+
139
+ with patch("httpx.Client.post", return_value=mock_resp):
140
+ result = converter.run(sources=["https://example.com/doc.pdf"])
141
+
142
+ assert len(result["documents"]) == 1
143
+ assert result["documents"][0].content == "# Hello World"
144
+
145
+ def test_run_url_uses_source_endpoint(self):
146
+ converter = DoclingServeConverter(api_key=None)
147
+ mock_resp = _mock_httpx_response("content")
148
+
149
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
150
+ converter.run(sources=["https://example.com/doc.pdf"])
151
+
152
+ url = mock_post.call_args[0][0]
153
+ assert "/v1/convert/source" in url
154
+
155
+ def test_run_file_uses_file_endpoint(self, tmp_path):
156
+ pdf = tmp_path / "test.pdf"
157
+ pdf.write_bytes(b"%PDF-test")
158
+ converter = DoclingServeConverter(api_key=None)
159
+ mock_resp = _mock_httpx_response("# PDF content")
160
+
161
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
162
+ result = converter.run(sources=[pdf])
163
+
164
+ url = mock_post.call_args[0][0]
165
+ assert "/v1/convert/file" in url
166
+ assert result["documents"][0].content == "# PDF content"
167
+
168
+ def test_run_bytestream_uses_file_endpoint(self):
169
+ converter = DoclingServeConverter(api_key=None)
170
+ mock_resp = _mock_httpx_response("content")
171
+ bs = ByteStream(data=b"bytes", meta={"file_name": "report.pdf"})
172
+
173
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
174
+ converter.run(sources=[bs])
175
+
176
+ url = mock_post.call_args[0][0]
177
+ assert "/v1/convert/file" in url
178
+
179
+ def test_run_multiple_sources(self):
180
+ converter = DoclingServeConverter(api_key=None)
181
+ mock_resp = _mock_httpx_response("content")
182
+
183
+ with patch("httpx.Client.post", return_value=mock_resp):
184
+ result = converter.run(sources=["https://a.com/1.pdf", "https://b.com/2.pdf"])
185
+
186
+ assert len(result["documents"]) == 2
187
+
188
+ def test_run_with_meta(self):
189
+ converter = DoclingServeConverter(api_key=None)
190
+ mock_resp = _mock_httpx_response("text")
191
+
192
+ with patch("httpx.Client.post", return_value=mock_resp):
193
+ result = converter.run(sources=["https://example.com/doc.pdf"], meta={"author": "Alice"})
194
+
195
+ assert result["documents"][0].meta["author"] == "Alice"
196
+
197
+ def test_run_bytestream_meta_merged(self):
198
+ converter = DoclingServeConverter(api_key=None)
199
+ mock_resp = _mock_httpx_response("text")
200
+ bs = ByteStream(data=b"bytes", meta={"file_path": "doc.pdf"})
201
+
202
+ with patch("httpx.Client.post", return_value=mock_resp):
203
+ result = converter.run(sources=[bs], meta={"page": 1})
204
+
205
+ doc = result["documents"][0]
206
+ assert doc.meta["file_path"] == "doc.pdf"
207
+ assert doc.meta["page"] == 1
208
+
209
+ def test_run_skips_on_http_status_error(self, caplog):
210
+ converter = DoclingServeConverter(api_key=None)
211
+ error_response = httpx.Response(500, text="Server error", request=httpx.Request("POST", "http://test"))
212
+
213
+ with patch(
214
+ "httpx.Client.post",
215
+ side_effect=httpx.HTTPStatusError("err", request=error_response.request, response=error_response),
216
+ ):
217
+ with caplog.at_level(logging.WARNING):
218
+ result = converter.run(sources=["https://example.com/doc.pdf"])
219
+
220
+ assert result["documents"] == []
221
+ assert "HTTP 500" in caplog.text
222
+
223
+ def test_run_skips_on_connection_error(self, caplog):
224
+ converter = DoclingServeConverter(api_key=None)
225
+
226
+ with patch("httpx.Client.post", side_effect=httpx.ConnectError("Connection refused")):
227
+ with caplog.at_level(logging.WARNING):
228
+ result = converter.run(sources=["https://example.com/doc.pdf"])
229
+
230
+ assert result["documents"] == []
231
+ assert "Could not connect" in caplog.text
232
+
233
+ def test_run_skips_when_no_content(self, caplog):
234
+ converter = DoclingServeConverter(api_key=None)
235
+ mock_resp = httpx.Response(
236
+ 200,
237
+ json={"document": {"md_content": None}, "status": "success"},
238
+ request=httpx.Request("POST", "http://test"),
239
+ )
240
+
241
+ with patch("httpx.Client.post", return_value=mock_resp):
242
+ with caplog.at_level(logging.WARNING):
243
+ result = converter.run(sources=["https://example.com/doc.pdf"])
244
+
245
+ assert result["documents"] == []
246
+ assert "No content returned" in caplog.text
247
+
248
+ def test_run_text_export(self):
249
+ converter = DoclingServeConverter(export_type=ExportType.TEXT, api_key=None)
250
+ mock_resp = _mock_httpx_response("plain text content", ExportType.TEXT)
251
+
252
+ with patch("httpx.Client.post", return_value=mock_resp):
253
+ result = converter.run(sources=["https://example.com/doc.pdf"])
254
+
255
+ assert result["documents"][0].content == "plain text content"
256
+
257
+ def test_run_json_export(self):
258
+ converter = DoclingServeConverter(export_type=ExportType.JSON, api_key=None)
259
+ json_doc = {"schema_name": "DoclingDocument", "pages": []}
260
+ mock_resp = _mock_httpx_response(json_doc, ExportType.JSON) # type: ignore[arg-type]
261
+
262
+ with patch("httpx.Client.post", return_value=mock_resp):
263
+ result = converter.run(sources=["https://example.com/doc.pdf"])
264
+
265
+ content = json.loads(result["documents"][0].content)
266
+ assert content["schema_name"] == "DoclingDocument"
267
+
268
+ def test_run_sends_api_key_header(self):
269
+ converter = DoclingServeConverter(api_key=Secret.from_token("my-secret-token"))
270
+ mock_resp = _mock_httpx_response("content")
271
+
272
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
273
+ converter.run(sources=["https://example.com/doc.pdf"])
274
+
275
+ headers = mock_post.call_args[1]["headers"]
276
+ assert headers["X-Api-Key"] == "my-secret-token"
277
+
278
+ def test_run_url_payload_includes_to_formats(self):
279
+ converter = DoclingServeConverter(export_type=ExportType.MARKDOWN, api_key=None)
280
+ mock_resp = _mock_httpx_response("content")
281
+
282
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
283
+ converter.run(sources=["https://example.com/doc.pdf"])
284
+
285
+ payload = mock_post.call_args[1]["json"]
286
+ assert payload["options"]["to_formats"] == ["md"]
287
+
288
+ def test_run_convert_options_merged_into_payload(self):
289
+ converter = DoclingServeConverter(convert_options={"do_ocr": True, "table_mode": "accurate"}, api_key=None)
290
+ mock_resp = _mock_httpx_response("content")
291
+
292
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
293
+ converter.run(sources=["https://example.com/doc.pdf"])
294
+
295
+ payload = mock_post.call_args[1]["json"]
296
+ assert payload["options"]["do_ocr"] is True
297
+ assert payload["options"]["table_mode"] == "accurate"
298
+
299
+
300
+ class TestDoclingServeConverterFilename:
301
+ def test_bytestream_filename_from_file_name(self):
302
+ converter = DoclingServeConverter(api_key=None)
303
+ bs = ByteStream(data=b"bytes", meta={"file_name": "report.pdf"})
304
+ mock_resp = _mock_httpx_response("content")
305
+
306
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
307
+ converter.run(sources=[bs])
308
+
309
+ files = mock_post.call_args[1]["files"]
310
+ assert files["files"][0] == "report.pdf"
311
+
312
+ def test_bytestream_filename_from_file_path(self):
313
+ converter = DoclingServeConverter(api_key=None)
314
+ bs = ByteStream(data=b"bytes", meta={"file_path": "/data/reports/annual.pdf"})
315
+ mock_resp = _mock_httpx_response("content")
316
+
317
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
318
+ converter.run(sources=[bs])
319
+
320
+ files = mock_post.call_args[1]["files"]
321
+ assert files["files"][0] == "annual.pdf"
322
+
323
+ def test_bytestream_filename_from_name(self):
324
+ converter = DoclingServeConverter(api_key=None)
325
+ bs = ByteStream(data=b"bytes", meta={"name": "summary.docx"})
326
+ mock_resp = _mock_httpx_response("content")
327
+
328
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
329
+ converter.run(sources=[bs])
330
+
331
+ files = mock_post.call_args[1]["files"]
332
+ assert files["files"][0] == "summary.docx"
333
+
334
+ def test_bytestream_filename_fallback(self):
335
+ converter = DoclingServeConverter(api_key=None)
336
+ bs = ByteStream(data=b"bytes")
337
+ mock_resp = _mock_httpx_response("content")
338
+
339
+ with patch("httpx.Client.post", return_value=mock_resp) as mock_post:
340
+ converter.run(sources=[bs])
341
+
342
+ files = mock_post.call_args[1]["files"]
343
+ assert files["files"][0] == "document"
344
+
345
+
346
+ class TestDoclingServeConverterRunAsync:
347
+ @pytest.mark.asyncio
348
+ async def test_run_async_url_source(self):
349
+ converter = DoclingServeConverter(api_key=None)
350
+ mock_resp = httpx.Response(
351
+ 200,
352
+ json={"document": {"md_content": "# Async content"}, "status": "success"},
353
+ request=httpx.Request("POST", "http://test"),
354
+ )
355
+
356
+ with patch("httpx.AsyncClient.post", new_callable=AsyncMock, return_value=mock_resp):
357
+ result = await converter.run_async(sources=["https://example.com/doc.pdf"])
358
+
359
+ assert len(result["documents"]) == 1
360
+ assert result["documents"][0].content == "# Async content"
361
+
362
+ @pytest.mark.asyncio
363
+ async def test_run_async_skips_on_status_error(self, caplog):
364
+ converter = DoclingServeConverter(api_key=None)
365
+ error_response = httpx.Response(500, text="error", request=httpx.Request("POST", "http://test"))
366
+
367
+ with patch(
368
+ "httpx.AsyncClient.post",
369
+ new_callable=AsyncMock,
370
+ side_effect=httpx.HTTPStatusError("err", request=error_response.request, response=error_response),
371
+ ):
372
+ with caplog.at_level(logging.WARNING):
373
+ result = await converter.run_async(sources=["https://example.com/doc.pdf"])
374
+
375
+ assert result["documents"] == []
376
+ assert "HTTP 500" in caplog.text
377
+
378
+ @pytest.mark.asyncio
379
+ async def test_run_async_skips_on_connection_error(self, caplog):
380
+ converter = DoclingServeConverter(api_key=None)
381
+
382
+ with patch(
383
+ "httpx.AsyncClient.post",
384
+ new_callable=AsyncMock,
385
+ side_effect=httpx.ConnectError("timeout"),
386
+ ):
387
+ with caplog.at_level(logging.WARNING):
388
+ result = await converter.run_async(sources=["https://example.com/doc.pdf"])
389
+
390
+ assert result["documents"] == []
391
+ assert "Could not connect" in caplog.text
392
+
393
+ @pytest.mark.asyncio
394
+ async def test_run_async_multiple_sources(self):
395
+ converter = DoclingServeConverter(api_key=None)
396
+ mock_resp = httpx.Response(
397
+ 200,
398
+ json={"document": {"md_content": "content"}, "status": "success"},
399
+ request=httpx.Request("POST", "http://test"),
400
+ )
401
+
402
+ with patch("httpx.AsyncClient.post", new_callable=AsyncMock, return_value=mock_resp):
403
+ result = await converter.run_async(sources=["https://a.com/1.pdf", "https://b.com/2.pdf"])
404
+
405
+ assert len(result["documents"]) == 2
406
+
407
+
408
+ class TestDoclingServeConverterIntegration:
409
+ @pytest.mark.integration
410
+ def test_run_integration(self):
411
+ """Requires a running DoclingServe instance at http://localhost:5001."""
412
+ converter = DoclingServeConverter(api_key=None)
413
+ result = converter.run(sources=["https://arxiv.org/pdf/2206.01062"])
414
+ assert len(result["documents"]) > 0
415
+ assert result["documents"][0].content
416
+
417
+ @pytest.mark.integration
418
+ @pytest.mark.asyncio
419
+ async def test_run_async_integration(self):
420
+ """Requires a running DoclingServe instance at http://localhost:5001."""
421
+ converter = DoclingServeConverter(api_key=None)
422
+ result = await converter.run_async(sources=["https://arxiv.org/pdf/2206.01062"])
423
+ assert len(result["documents"]) > 0
424
+ assert result["documents"][0].content