gotenberg-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.
- gotenberg_haystack-0.1.0.dist-info/METADATA +48 -0
- gotenberg_haystack-0.1.0.dist-info/RECORD +7 -0
- gotenberg_haystack-0.1.0.dist-info/WHEEL +4 -0
- gotenberg_haystack-0.1.0.dist-info/licenses/LICENSE.txt +201 -0
- haystack_integrations/components/converters/gotenberg/__init__.py +7 -0
- haystack_integrations/components/converters/gotenberg/converter.py +581 -0
- haystack_integrations/components/converters/py.typed +0 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: gotenberg-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Gotenberg document to PDF converter integration for Haystack
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/gotenberg#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/gotenberg
|
|
8
|
+
Author: Max Swain
|
|
9
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE.txt
|
|
12
|
+
Keywords: document-conversion,gotenberg,haystack,libreoffice,pdf
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
22
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: haystack-ai
|
|
25
|
+
Requires-Dist: httpx2>=2.12.0
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# gotenberg-haystack
|
|
29
|
+
|
|
30
|
+
[](https://pypi.org/project/gotenberg-haystack)
|
|
31
|
+
[](https://pypi.org/project/gotenberg-haystack)
|
|
32
|
+
|
|
33
|
+
- [Integration page](https://haystack.deepset.ai/integrations/gotenberg)
|
|
34
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/gotenberg/CHANGELOG.md)
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Contributing
|
|
39
|
+
|
|
40
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
41
|
+
|
|
42
|
+
The integration tests require a local Gotenberg service. Start the provided Gotenberg v8 container from this directory:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
docker compose up -d --wait
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Then run the integration tests with `hatch run test:integration`. Stop the service afterward with `docker compose down`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
haystack_integrations/components/converters/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
haystack_integrations/components/converters/gotenberg/__init__.py,sha256=OYlaE8SFJdynvQMi8mBnAz_3gOpCkyx9UxJ5jnWLElM,248
|
|
3
|
+
haystack_integrations/components/converters/gotenberg/converter.py,sha256=lJv3qKfAbPhM7uDbGmBlL12ClpyHdk2ZpUCmDOjJ73M,24519
|
|
4
|
+
gotenberg_haystack-0.1.0.dist-info/METADATA,sha256=tPiv4yjgWwnei-u3Rpn72Qc8DHH-gBQIg0CS-S1XNMw,2212
|
|
5
|
+
gotenberg_haystack-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
6
|
+
gotenberg_haystack-0.1.0.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
|
|
7
|
+
gotenberg_haystack-0.1.0.dist-info/RECORD,,
|
|
@@ -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,581 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import mimetypes
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
import httpx2
|
|
12
|
+
from haystack import component, default_from_dict, default_to_dict
|
|
13
|
+
from haystack.components.converters.utils import normalize_metadata
|
|
14
|
+
from haystack.dataclasses import ByteStream
|
|
15
|
+
from httpx2._types import FileTypes, RequestFiles
|
|
16
|
+
from typing_extensions import Self
|
|
17
|
+
|
|
18
|
+
_Route = Literal["libreoffice", "html", "markdown", "url"]
|
|
19
|
+
# Supported Gotenberg LibreOffice conversion input formats:
|
|
20
|
+
# https://gotenberg.dev/docs/convert-with-libreoffice/convert-to-pdf
|
|
21
|
+
_LIBREOFFICE_EXTENSIONS = frozenset(
|
|
22
|
+
{
|
|
23
|
+
".123",
|
|
24
|
+
".602",
|
|
25
|
+
".abw",
|
|
26
|
+
".bib",
|
|
27
|
+
".bmp",
|
|
28
|
+
".cdr",
|
|
29
|
+
".cgm",
|
|
30
|
+
".cmx",
|
|
31
|
+
".csv",
|
|
32
|
+
".cwk",
|
|
33
|
+
".dbf",
|
|
34
|
+
".dif",
|
|
35
|
+
".doc",
|
|
36
|
+
".docm",
|
|
37
|
+
".docx",
|
|
38
|
+
".dot",
|
|
39
|
+
".dotm",
|
|
40
|
+
".dotx",
|
|
41
|
+
".dxf",
|
|
42
|
+
".emf",
|
|
43
|
+
".eps",
|
|
44
|
+
".epub",
|
|
45
|
+
".fodg",
|
|
46
|
+
".fodp",
|
|
47
|
+
".fods",
|
|
48
|
+
".fodt",
|
|
49
|
+
".fopd",
|
|
50
|
+
".gif",
|
|
51
|
+
".htm",
|
|
52
|
+
".html",
|
|
53
|
+
".hwp",
|
|
54
|
+
".jpeg",
|
|
55
|
+
".jpg",
|
|
56
|
+
".key",
|
|
57
|
+
".ltx",
|
|
58
|
+
".lwp",
|
|
59
|
+
".mcw",
|
|
60
|
+
".met",
|
|
61
|
+
".mml",
|
|
62
|
+
".mw",
|
|
63
|
+
".numbers",
|
|
64
|
+
".odd",
|
|
65
|
+
".odg",
|
|
66
|
+
".odm",
|
|
67
|
+
".odp",
|
|
68
|
+
".ods",
|
|
69
|
+
".odt",
|
|
70
|
+
".otg",
|
|
71
|
+
".oth",
|
|
72
|
+
".otp",
|
|
73
|
+
".ots",
|
|
74
|
+
".ott",
|
|
75
|
+
".pages",
|
|
76
|
+
".pbm",
|
|
77
|
+
".pcd",
|
|
78
|
+
".pct",
|
|
79
|
+
".pcx",
|
|
80
|
+
".pdb",
|
|
81
|
+
".pdf",
|
|
82
|
+
".pgm",
|
|
83
|
+
".png",
|
|
84
|
+
".pot",
|
|
85
|
+
".potm",
|
|
86
|
+
".potx",
|
|
87
|
+
".ppm",
|
|
88
|
+
".pps",
|
|
89
|
+
".ppsm",
|
|
90
|
+
".ppsx",
|
|
91
|
+
".ppt",
|
|
92
|
+
".pptm",
|
|
93
|
+
".pptx",
|
|
94
|
+
".psd",
|
|
95
|
+
".psw",
|
|
96
|
+
".pub",
|
|
97
|
+
".pwp",
|
|
98
|
+
".pxl",
|
|
99
|
+
".ras",
|
|
100
|
+
".rtf",
|
|
101
|
+
".sda",
|
|
102
|
+
".sdc",
|
|
103
|
+
".sdd",
|
|
104
|
+
".sdp",
|
|
105
|
+
".sdw",
|
|
106
|
+
".sgl",
|
|
107
|
+
".slk",
|
|
108
|
+
".smf",
|
|
109
|
+
".stc",
|
|
110
|
+
".std",
|
|
111
|
+
".sti",
|
|
112
|
+
".stw",
|
|
113
|
+
".svg",
|
|
114
|
+
".svm",
|
|
115
|
+
".swf",
|
|
116
|
+
".sxc",
|
|
117
|
+
".sxd",
|
|
118
|
+
".sxg",
|
|
119
|
+
".sxi",
|
|
120
|
+
".sxm",
|
|
121
|
+
".sxw",
|
|
122
|
+
".tga",
|
|
123
|
+
".tif",
|
|
124
|
+
".tiff",
|
|
125
|
+
".txt",
|
|
126
|
+
".uof",
|
|
127
|
+
".uop",
|
|
128
|
+
".uos",
|
|
129
|
+
".uot",
|
|
130
|
+
".vdx",
|
|
131
|
+
".vor",
|
|
132
|
+
".vsd",
|
|
133
|
+
".vsdm",
|
|
134
|
+
".vsdx",
|
|
135
|
+
".wb2",
|
|
136
|
+
".wk1",
|
|
137
|
+
".wks",
|
|
138
|
+
".wmf",
|
|
139
|
+
".wpd",
|
|
140
|
+
".wpg",
|
|
141
|
+
".wps",
|
|
142
|
+
".xbm",
|
|
143
|
+
".xhtml",
|
|
144
|
+
".xls",
|
|
145
|
+
".xlsb",
|
|
146
|
+
".xlsm",
|
|
147
|
+
".xlsx",
|
|
148
|
+
".xlt",
|
|
149
|
+
".xltm",
|
|
150
|
+
".xltx",
|
|
151
|
+
".xlw",
|
|
152
|
+
".xml",
|
|
153
|
+
".xpm",
|
|
154
|
+
".zabw",
|
|
155
|
+
}
|
|
156
|
+
)
|
|
157
|
+
_MIME_TYPE_EXTENSIONS = {
|
|
158
|
+
"application/epub+zip": ".epub",
|
|
159
|
+
"application/msword": ".doc",
|
|
160
|
+
"application/pdf": ".pdf",
|
|
161
|
+
"application/postscript": ".eps",
|
|
162
|
+
"application/rtf": ".rtf",
|
|
163
|
+
"application/vnd.apple.keynote": ".key",
|
|
164
|
+
"application/vnd.apple.numbers": ".numbers",
|
|
165
|
+
"application/vnd.apple.pages": ".pages",
|
|
166
|
+
"application/vnd.ms-excel": ".xls",
|
|
167
|
+
"application/vnd.ms-excel.sheet.binary.macroenabled.12": ".xlsb",
|
|
168
|
+
"application/vnd.ms-excel.sheet.macroenabled.12": ".xlsm",
|
|
169
|
+
"application/vnd.ms-excel.template.macroenabled.12": ".xltm",
|
|
170
|
+
"application/vnd.ms-powerpoint": ".ppt",
|
|
171
|
+
"application/vnd.ms-powerpoint.presentation.macroenabled.12": ".pptm",
|
|
172
|
+
"application/vnd.ms-powerpoint.slideshow.macroenabled.12": ".ppsm",
|
|
173
|
+
"application/vnd.ms-powerpoint.template.macroenabled.12": ".potm",
|
|
174
|
+
"application/vnd.ms-word.document.macroenabled.12": ".docm",
|
|
175
|
+
"application/vnd.ms-word.template.macroenabled.12": ".dotm",
|
|
176
|
+
"application/vnd.oasis.opendocument.graphics": ".odg",
|
|
177
|
+
"application/vnd.oasis.opendocument.graphics-template": ".otg",
|
|
178
|
+
"application/vnd.oasis.opendocument.presentation": ".odp",
|
|
179
|
+
"application/vnd.oasis.opendocument.presentation-template": ".otp",
|
|
180
|
+
"application/vnd.oasis.opendocument.spreadsheet": ".ods",
|
|
181
|
+
"application/vnd.oasis.opendocument.spreadsheet-template": ".ots",
|
|
182
|
+
"application/vnd.oasis.opendocument.text": ".odt",
|
|
183
|
+
"application/vnd.oasis.opendocument.text-master": ".odm",
|
|
184
|
+
"application/vnd.oasis.opendocument.text-template": ".ott",
|
|
185
|
+
"application/vnd.oasis.opendocument.text-web": ".oth",
|
|
186
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
|
|
187
|
+
"application/vnd.openxmlformats-officedocument.presentationml.slideshow": ".ppsx",
|
|
188
|
+
"application/vnd.openxmlformats-officedocument.presentationml.template": ".potx",
|
|
189
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
|
|
190
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.template": ".xltx",
|
|
191
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
|
|
192
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.template": ".dotx",
|
|
193
|
+
"application/vnd.stardivision.calc": ".sdc",
|
|
194
|
+
"application/vnd.stardivision.draw": ".sda",
|
|
195
|
+
"application/vnd.stardivision.impress": ".sdd",
|
|
196
|
+
"application/vnd.stardivision.math": ".smf",
|
|
197
|
+
"application/vnd.stardivision.writer": ".sdw",
|
|
198
|
+
"application/vnd.sun.xml.calc": ".sxc",
|
|
199
|
+
"application/vnd.sun.xml.draw": ".sxd",
|
|
200
|
+
"application/vnd.sun.xml.impress": ".sxi",
|
|
201
|
+
"application/vnd.sun.xml.math": ".sxm",
|
|
202
|
+
"application/vnd.sun.xml.writer": ".sxw",
|
|
203
|
+
"application/vnd.sun.xml.writer.global": ".sxg",
|
|
204
|
+
"application/vnd.uof.presentation": ".uop",
|
|
205
|
+
"application/vnd.uof.spreadsheet": ".uos",
|
|
206
|
+
"application/vnd.uof.text": ".uot",
|
|
207
|
+
"application/vnd.wordperfect": ".wpd",
|
|
208
|
+
"application/xml": ".xml",
|
|
209
|
+
"image/pict": ".pct",
|
|
210
|
+
"image/svg+xml": ".svg",
|
|
211
|
+
"text/csv": ".csv",
|
|
212
|
+
"text/plain": ".txt",
|
|
213
|
+
"text/rtf": ".rtf",
|
|
214
|
+
"text/xml": ".xml",
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _resources(resources: list[Path] | None) -> list[Path]:
|
|
219
|
+
"""Validate resource paths once and return the normalized list."""
|
|
220
|
+
paths = resources or []
|
|
221
|
+
names: set[str] = set()
|
|
222
|
+
for resource in paths:
|
|
223
|
+
if not isinstance(resource, Path):
|
|
224
|
+
msg = f"Unsupported resource type: {type(resource).__name__}; expected Path"
|
|
225
|
+
raise TypeError(msg)
|
|
226
|
+
if not resource.is_file():
|
|
227
|
+
msg = f"Resource does not exist or is not a file: {resource}"
|
|
228
|
+
raise FileNotFoundError(msg)
|
|
229
|
+
if resource.name in names:
|
|
230
|
+
msg = f"Resource filenames must be unique: {resource.name!r}"
|
|
231
|
+
raise ValueError(msg)
|
|
232
|
+
if resource.name == "index.html":
|
|
233
|
+
msg = "A resource cannot be named 'index.html'; that name is reserved by Gotenberg"
|
|
234
|
+
raise ValueError(msg)
|
|
235
|
+
names.add(resource.name)
|
|
236
|
+
return paths
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _source_metadata(source: str | Path | ByteStream) -> dict[str, Any]:
|
|
240
|
+
"""Return metadata inherited from the source."""
|
|
241
|
+
if isinstance(source, ByteStream):
|
|
242
|
+
return source.meta
|
|
243
|
+
if isinstance(source, Path) or "://" not in source:
|
|
244
|
+
return {"file_path": str(source)}
|
|
245
|
+
return {}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _is_url_source(source: str) -> bool:
|
|
249
|
+
"""Return whether a string is an HTTP(S) URL, rejecting malformed or unsupported URLs."""
|
|
250
|
+
if "://" not in source:
|
|
251
|
+
return False
|
|
252
|
+
try:
|
|
253
|
+
parsed = httpx2.URL(url=source)
|
|
254
|
+
except httpx2.InvalidURL as error:
|
|
255
|
+
msg = f"Malformed HTTP(S) URL source: {source!r}"
|
|
256
|
+
raise ValueError(msg) from error
|
|
257
|
+
if parsed.scheme not in {"http", "https"}:
|
|
258
|
+
msg = f"Unsupported URL scheme {parsed.scheme!r}; only HTTP(S) URLs are supported"
|
|
259
|
+
raise ValueError(msg)
|
|
260
|
+
|
|
261
|
+
if not parsed.host:
|
|
262
|
+
msg = f"Malformed HTTP(S) URL source: {source!r}; expected a valid host"
|
|
263
|
+
raise ValueError(msg)
|
|
264
|
+
return True
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@component
|
|
268
|
+
class GotenbergFileConverter:
|
|
269
|
+
"""
|
|
270
|
+
Automatically route local files, typed byte streams, and web URLs to Gotenberg and return ordered PDFs.
|
|
271
|
+
|
|
272
|
+
Local Markdown files use Gotenberg's Markdown route, local HTML files use its Chromium HTML route, and every
|
|
273
|
+
other supported local file uses its LibreOffice route. HTTP(S) strings use the Chromium URL route. `ByteStream`
|
|
274
|
+
sources are routed by their MIME type. Resources are validated for every batch but uploaded only with HTML and
|
|
275
|
+
Markdown sources. Output metadata preserves local source paths under `file_path` and metadata from `ByteStream`
|
|
276
|
+
sources; explicit metadata takes precedence.
|
|
277
|
+
|
|
278
|
+
### Usage example
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
from pathlib import Path
|
|
282
|
+
|
|
283
|
+
from haystack_integrations.components.converters.gotenberg import GotenbergFileConverter
|
|
284
|
+
|
|
285
|
+
converter = GotenbergFileConverter()
|
|
286
|
+
result = converter.run(sources=[Path("report.docx"), "https://haystack.deepset.ai"])
|
|
287
|
+
pdfs = result["output"]
|
|
288
|
+
```
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
def __init__(
|
|
292
|
+
self,
|
|
293
|
+
url: str = "http://localhost:3000",
|
|
294
|
+
timeout: float = 30.0,
|
|
295
|
+
concurrency_limit: int = 5,
|
|
296
|
+
) -> None:
|
|
297
|
+
"""
|
|
298
|
+
Create a Gotenberg file converter.
|
|
299
|
+
|
|
300
|
+
:param url: The URL of the Gotenberg service.
|
|
301
|
+
:param timeout: The request timeout in seconds.
|
|
302
|
+
:param concurrency_limit: Maximum number of Gotenberg requests in flight during `run_async`. Has no
|
|
303
|
+
effect on synchronous `run`, which converts one source at a time.
|
|
304
|
+
"""
|
|
305
|
+
try:
|
|
306
|
+
parsed_url = httpx2.URL(url=url)
|
|
307
|
+
except httpx2.InvalidURL as error:
|
|
308
|
+
msg = "url must be a valid HTTP(S) Gotenberg service URL"
|
|
309
|
+
raise ValueError(msg) from error
|
|
310
|
+
if parsed_url.scheme not in {"http", "https"} or not parsed_url.host:
|
|
311
|
+
msg = "url must be a valid HTTP(S) Gotenberg service URL"
|
|
312
|
+
raise ValueError(msg)
|
|
313
|
+
if timeout <= 0:
|
|
314
|
+
msg = "timeout must be greater than zero"
|
|
315
|
+
raise ValueError(msg)
|
|
316
|
+
self.url = url.rstrip("/")
|
|
317
|
+
self.timeout = timeout
|
|
318
|
+
self.concurrency_limit = concurrency_limit
|
|
319
|
+
|
|
320
|
+
def to_dict(self) -> dict[str, Any]:
|
|
321
|
+
"""Serialize this component to a dictionary."""
|
|
322
|
+
return default_to_dict(
|
|
323
|
+
obj=self,
|
|
324
|
+
url=self.url,
|
|
325
|
+
timeout=self.timeout,
|
|
326
|
+
concurrency_limit=self.concurrency_limit,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
@classmethod
|
|
330
|
+
def from_dict(cls, data: dict[str, Any]) -> Self:
|
|
331
|
+
"""Deserialize this component from a dictionary."""
|
|
332
|
+
return default_from_dict(cls=cls, data=data)
|
|
333
|
+
|
|
334
|
+
@staticmethod
|
|
335
|
+
def _pdf(response: httpx2.Response, meta: dict[str, Any]) -> ByteStream:
|
|
336
|
+
"""Validate a Gotenberg response and convert it to a PDF byte stream."""
|
|
337
|
+
response.raise_for_status()
|
|
338
|
+
content_type = response.headers.get("content-type", "").split(";", maxsplit=1)[0].strip().lower()
|
|
339
|
+
if content_type in {"application/zip", "application/x-zip-compressed"}:
|
|
340
|
+
msg = "Gotenberg unexpectedly returned a ZIP archive instead of one PDF"
|
|
341
|
+
raise RuntimeError(msg)
|
|
342
|
+
return ByteStream(data=bytes(response.content), meta=meta, mime_type="application/pdf")
|
|
343
|
+
|
|
344
|
+
@staticmethod
|
|
345
|
+
def _local_route(source: Path) -> _Route:
|
|
346
|
+
"""Validate a local source and return its route from the file suffix."""
|
|
347
|
+
if not source.is_file():
|
|
348
|
+
msg = f"Local source file does not exist or is not a file: {source}"
|
|
349
|
+
raise FileNotFoundError(msg)
|
|
350
|
+
suffix = source.suffix.lower()
|
|
351
|
+
if not suffix:
|
|
352
|
+
msg = f"Local source filename is missing a file extension: {source.name!r}"
|
|
353
|
+
raise ValueError(msg)
|
|
354
|
+
if suffix in {".md", ".markdown"}:
|
|
355
|
+
return "markdown"
|
|
356
|
+
if suffix in {".html", ".htm", ".xhtml"}:
|
|
357
|
+
return "html"
|
|
358
|
+
if suffix in _LIBREOFFICE_EXTENSIONS:
|
|
359
|
+
return "libreoffice"
|
|
360
|
+
msg = f"Unsupported local source suffix: {suffix!r}"
|
|
361
|
+
raise ValueError(msg)
|
|
362
|
+
|
|
363
|
+
@staticmethod
|
|
364
|
+
def _byte_stream_route(source: ByteStream) -> tuple[_Route, str]:
|
|
365
|
+
"""Classify a byte stream by its normalized MIME type and return its authoritative suffix."""
|
|
366
|
+
mime_type = (source.mime_type or "").split(";", maxsplit=1)[0].strip().lower()
|
|
367
|
+
if not mime_type:
|
|
368
|
+
msg = "ByteStream sources require a non-empty mime_type"
|
|
369
|
+
raise ValueError(msg)
|
|
370
|
+
if mime_type in {"text/html", "application/xhtml+xml"}:
|
|
371
|
+
return "html", ".html"
|
|
372
|
+
if mime_type in {"text/markdown", "text/x-markdown"}:
|
|
373
|
+
return "markdown", ".md"
|
|
374
|
+
|
|
375
|
+
suffix = _MIME_TYPE_EXTENSIONS.get(mime_type) or mimetypes.guess_extension(type=mime_type, strict=False)
|
|
376
|
+
if suffix is None or suffix.lower() not in _LIBREOFFICE_EXTENSIONS:
|
|
377
|
+
msg = f"Unsupported ByteStream MIME type: {mime_type!r}"
|
|
378
|
+
raise ValueError(msg)
|
|
379
|
+
return "libreoffice", suffix.lower()
|
|
380
|
+
|
|
381
|
+
@staticmethod
|
|
382
|
+
def _safe_stem(filename: str | None) -> str:
|
|
383
|
+
"""Return a filesystem-safe source filename stem."""
|
|
384
|
+
stem = re.sub(pattern=r"[^A-Za-z0-9_.-]", repl="_", string=Path(filename or "document").stem)
|
|
385
|
+
return "document" if stem in {"", ".", ".."} else stem
|
|
386
|
+
|
|
387
|
+
def _prepare(
|
|
388
|
+
self,
|
|
389
|
+
sources: list[str | Path | ByteStream],
|
|
390
|
+
resources: list[Path] | None,
|
|
391
|
+
) -> list[tuple[str, RequestFiles]]:
|
|
392
|
+
"""Validate inputs and build direct multipart requests in input order."""
|
|
393
|
+
if not sources:
|
|
394
|
+
msg = "sources must contain at least one source"
|
|
395
|
+
raise ValueError(msg)
|
|
396
|
+
resource_paths = _resources(resources=resources)
|
|
397
|
+
resource_names = {resource.name for resource in resource_paths}
|
|
398
|
+
resource_files: list[tuple[str, FileTypes]] = [
|
|
399
|
+
(
|
|
400
|
+
"files",
|
|
401
|
+
(
|
|
402
|
+
resource.name,
|
|
403
|
+
resource.read_bytes(),
|
|
404
|
+
mimetypes.guess_type(resource.name.lower(), strict=False)[0] or "application/octet-stream",
|
|
405
|
+
),
|
|
406
|
+
)
|
|
407
|
+
for resource in resource_paths
|
|
408
|
+
]
|
|
409
|
+
requests: list[tuple[str, RequestFiles]] = []
|
|
410
|
+
for index, source in enumerate(sources):
|
|
411
|
+
if isinstance(source, str) and _is_url_source(source=source):
|
|
412
|
+
requests.append(("/forms/chromium/convert/url", [("url", (None, source))]))
|
|
413
|
+
continue
|
|
414
|
+
|
|
415
|
+
filename: str | None
|
|
416
|
+
suffix: str | None = None
|
|
417
|
+
if isinstance(source, (Path, str)):
|
|
418
|
+
source_path = Path(source)
|
|
419
|
+
kind = self._local_route(source=source_path)
|
|
420
|
+
data, filename = source_path.read_bytes(), source_path.name
|
|
421
|
+
elif isinstance(source, ByteStream):
|
|
422
|
+
kind, suffix = self._byte_stream_route(source=source)
|
|
423
|
+
file_path = source.meta.get("file_path")
|
|
424
|
+
filename = Path(file_path).name if file_path else None
|
|
425
|
+
data = source.data
|
|
426
|
+
else:
|
|
427
|
+
msg = f"Unsupported source type: {type(source).__name__}; expected str, Path, or ByteStream"
|
|
428
|
+
raise TypeError(msg)
|
|
429
|
+
|
|
430
|
+
if kind == "libreoffice":
|
|
431
|
+
upload_filename = filename or f"{index}-document{suffix or ''}"
|
|
432
|
+
if suffix is not None:
|
|
433
|
+
upload_filename = f"{index}-{self._safe_stem(filename)}{suffix}"
|
|
434
|
+
content_type = (
|
|
435
|
+
mimetypes.guess_type(upload_filename.lower(), strict=False)[0] or "application/octet-stream"
|
|
436
|
+
)
|
|
437
|
+
requests.append(("/forms/libreoffice/convert", [("files", (upload_filename, data, content_type))]))
|
|
438
|
+
continue
|
|
439
|
+
try:
|
|
440
|
+
text = data.decode("utf-8")
|
|
441
|
+
except UnicodeDecodeError as error:
|
|
442
|
+
msg = f"{kind.upper() if kind == 'html' else kind.title()} sources must contain UTF-8 text"
|
|
443
|
+
raise ValueError(msg) from error
|
|
444
|
+
if kind == "html":
|
|
445
|
+
requests.append(
|
|
446
|
+
("/forms/chromium/convert/html", [("files", ("index.html", text, "text/html")), *resource_files])
|
|
447
|
+
)
|
|
448
|
+
continue
|
|
449
|
+
|
|
450
|
+
markdown_filename = f"{self._safe_stem(filename=filename)}.md"
|
|
451
|
+
if markdown_filename in resource_names:
|
|
452
|
+
msg = f"A resource conflicts with the Markdown source filename: {markdown_filename!r}"
|
|
453
|
+
raise ValueError(msg)
|
|
454
|
+
head = '<!doctype html><html><head><meta charset="utf-8"></head>'
|
|
455
|
+
template = f'{head}<body>{{{{ toHTML "{markdown_filename}" }}}}</body></html>'
|
|
456
|
+
requests.append(
|
|
457
|
+
(
|
|
458
|
+
"/forms/chromium/convert/markdown",
|
|
459
|
+
[
|
|
460
|
+
("files", ("index.html", template, "text/html")),
|
|
461
|
+
("files", (markdown_filename, text, "text/markdown")),
|
|
462
|
+
*resource_files,
|
|
463
|
+
],
|
|
464
|
+
)
|
|
465
|
+
)
|
|
466
|
+
return requests
|
|
467
|
+
|
|
468
|
+
@component.output_types(output=list[ByteStream])
|
|
469
|
+
def run(
|
|
470
|
+
self,
|
|
471
|
+
sources: list[str | Path | ByteStream],
|
|
472
|
+
meta: dict[str, Any] | list[dict[str, Any]] | None = None,
|
|
473
|
+
*,
|
|
474
|
+
resources: list[Path] | None = None,
|
|
475
|
+
) -> dict[str, list[ByteStream]]:
|
|
476
|
+
"""
|
|
477
|
+
Convert automatically routed sources to PDF.
|
|
478
|
+
|
|
479
|
+
Each source is classified independently and converted using the corresponding Gotenberg route:
|
|
480
|
+
|
|
481
|
+
- A string containing `://` is treated as a URL. It must be an HTTP(S) URL, and Gotenberg's Chromium URL
|
|
482
|
+
route navigates to that URL and prints the resulting page to PDF.
|
|
483
|
+
- A string without `://`, or a `Path`, is treated as a local file. Markdown files (`.md` and `.markdown`) use
|
|
484
|
+
the Chromium Markdown route, HTML files (`.html`, `.htm`, and `.xhtml`) use the Chromium HTML route, and
|
|
485
|
+
other supported file extensions use the LibreOffice route.
|
|
486
|
+
- A `ByteStream` is classified by its MIME type. HTML MIME types use the Chromium HTML route, Markdown MIME
|
|
487
|
+
types use the Chromium Markdown route, and other supported MIME types use the LibreOffice route. For
|
|
488
|
+
LibreOffice conversion, the MIME type determines the staged file extension. MIME parameters such as
|
|
489
|
+
`charset=utf-8` are ignored when classifying the stream.
|
|
490
|
+
|
|
491
|
+
HTML and Markdown inputs are uploaded to Gotenberg together with `resources`, while URL inputs are fetched by
|
|
492
|
+
Gotenberg and LibreOffice inputs are uploaded as files. A mixed batch can contain any combination of these
|
|
493
|
+
source types. Routes are executed in input order, and one PDF is produced for each source. HTML and Markdown
|
|
494
|
+
`ByteStream` content must be UTF-8 text.
|
|
495
|
+
|
|
496
|
+
:param sources: Sources to convert. Strings, `Path` objects, and `ByteStream` objects are supported as
|
|
497
|
+
described above.
|
|
498
|
+
:param meta: Optional metadata to attach to the output PDFs. A single dictionary is applied to every output. A
|
|
499
|
+
list of dictionaries must have the same length as `sources` and is applied to corresponding outputs.
|
|
500
|
+
Metadata on a source `ByteStream` is preserved, with values from this parameter taking precedence.
|
|
501
|
+
:param resources: Optional local resources for HTML and Markdown conversion. Resources are validated once and
|
|
502
|
+
uploaded only with those routes. Filenames must be unique and cannot be `index.html`; a resource also
|
|
503
|
+
cannot have the same filename as a staged Markdown source.
|
|
504
|
+
:returns: A dictionary containing an `"output"` list with one PDF `ByteStream` per source, in input order.
|
|
505
|
+
:raises TypeError: If a source or resource has an unsupported type.
|
|
506
|
+
:raises FileNotFoundError: If a local source or resource does not exist or is not a file.
|
|
507
|
+
:raises ValueError: If sources, metadata, URLs, suffixes, MIME types, resources, or text contents are invalid.
|
|
508
|
+
:raises RuntimeError: If Gotenberg returns a ZIP archive instead of a PDF.
|
|
509
|
+
"""
|
|
510
|
+
meta_list = normalize_metadata(meta=meta, sources_count=len(sources))
|
|
511
|
+
requests = self._prepare(sources=sources, resources=resources)
|
|
512
|
+
with httpx2.Client(base_url=self.url, timeout=self.timeout) as client:
|
|
513
|
+
output = [
|
|
514
|
+
self._pdf(
|
|
515
|
+
response=client.post(path, files=files),
|
|
516
|
+
meta={**_source_metadata(source=source), **source_meta},
|
|
517
|
+
)
|
|
518
|
+
for source, (path, files), source_meta in zip(sources, requests, meta_list, strict=True)
|
|
519
|
+
]
|
|
520
|
+
return {"output": output}
|
|
521
|
+
|
|
522
|
+
@component.output_types(output=list[ByteStream])
|
|
523
|
+
async def run_async(
|
|
524
|
+
self,
|
|
525
|
+
sources: list[str | Path | ByteStream],
|
|
526
|
+
meta: dict[str, Any] | list[dict[str, Any]] | None = None,
|
|
527
|
+
*,
|
|
528
|
+
resources: list[Path] | None = None,
|
|
529
|
+
) -> dict[str, list[ByteStream]]:
|
|
530
|
+
"""
|
|
531
|
+
Asynchronously convert automatically routed sources to PDF.
|
|
532
|
+
|
|
533
|
+
This is the asynchronous equivalent of `run()` and uses the same source classification and routing rules. Each
|
|
534
|
+
source is classified independently and converted using the corresponding Gotenberg route:
|
|
535
|
+
|
|
536
|
+
- A string containing `://` is treated as a valid HTTP(S) URL and converted by Gotenberg's Chromium URL route.
|
|
537
|
+
- A string without `://`, or a `Path`, is treated as a local file. Markdown files (`.md` and `.markdown`) use
|
|
538
|
+
the Chromium Markdown route, HTML files (`.html`, `.htm`, and `.xhtml`) use the Chromium HTML route, and
|
|
539
|
+
other supported file extensions use the LibreOffice route.
|
|
540
|
+
- A `ByteStream` is classified by its MIME type: HTML MIME types use the Chromium HTML route, Markdown MIME
|
|
541
|
+
types use the Chromium Markdown route, and other supported MIME types use the LibreOffice route. The MIME
|
|
542
|
+
type determines the staged file extension for LibreOffice conversion, without its parameters (for example,
|
|
543
|
+
`charset=utf-8`).
|
|
544
|
+
|
|
545
|
+
HTML and Markdown inputs are uploaded with `resources`, URL inputs are fetched by Gotenberg, and LibreOffice
|
|
546
|
+
inputs are uploaded as files. A mixed batch can contain any combination of these source types. Routes are
|
|
547
|
+
executed in input order, and one PDF is produced for each source. HTML and Markdown `ByteStream` content must
|
|
548
|
+
be UTF-8 text.
|
|
549
|
+
|
|
550
|
+
:param sources: Sources to convert. Strings, `Path` objects, and `ByteStream` objects are supported as
|
|
551
|
+
described above.
|
|
552
|
+
:param meta: Optional metadata to attach to the output PDFs. A single dictionary is applied to every output. A
|
|
553
|
+
list of dictionaries must have the same length as `sources` and is applied to corresponding outputs.
|
|
554
|
+
Metadata on a source `ByteStream` is preserved, with values from this parameter taking precedence.
|
|
555
|
+
:param resources: Optional local resources for HTML and Markdown conversion. Resources are validated once and
|
|
556
|
+
uploaded only with those routes. Filenames must be unique and cannot be `index.html`; a resource also
|
|
557
|
+
cannot have the same filename as a staged Markdown source.
|
|
558
|
+
:returns: A dictionary containing an `"output"` list with one PDF `ByteStream` per source, in input order.
|
|
559
|
+
:raises TypeError: If a source or resource has an unsupported type.
|
|
560
|
+
:raises FileNotFoundError: If a local source or resource does not exist or is not a file.
|
|
561
|
+
:raises ValueError: If sources, metadata, URLs, suffixes, MIME types, resources, or text contents are invalid.
|
|
562
|
+
:raises RuntimeError: If Gotenberg returns a ZIP archive instead of a PDF.
|
|
563
|
+
"""
|
|
564
|
+
meta_list = normalize_metadata(meta=meta, sources_count=len(sources))
|
|
565
|
+
requests = self._prepare(sources=sources, resources=resources)
|
|
566
|
+
semaphore = asyncio.Semaphore(max(1, self.concurrency_limit))
|
|
567
|
+
|
|
568
|
+
async def _runner(path: str, files: RequestFiles) -> httpx2.Response:
|
|
569
|
+
async with semaphore:
|
|
570
|
+
return await client.post(path, files=files)
|
|
571
|
+
|
|
572
|
+
async with httpx2.AsyncClient(base_url=self.url, timeout=self.timeout) as client:
|
|
573
|
+
responses = await asyncio.gather(*(_runner(path, files) for path, files in requests))
|
|
574
|
+
output = [
|
|
575
|
+
self._pdf(
|
|
576
|
+
response=response,
|
|
577
|
+
meta={**_source_metadata(source=source), **source_meta},
|
|
578
|
+
)
|
|
579
|
+
for source, response, source_meta in zip(sources, responses, meta_list, strict=True)
|
|
580
|
+
]
|
|
581
|
+
return {"output": output}
|
|
File without changes
|