converter-studio-haystack 1.0.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.
@@ -0,0 +1,392 @@
1
+ """What both components share: the API client's life cycle and the client name, reading a
2
+ source, the API's list of formats, and which errors stop a run instead of skipping a source."""
3
+
4
+ import mimetypes
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ from pathlib import Path, PurePosixPath
8
+ from typing import Any, Self, TypeAlias
9
+ from urllib.parse import urlsplit
10
+
11
+ import httpx
12
+ from haystack import default_from_dict, logging
13
+ from haystack.dataclasses import ByteStream
14
+ from haystack.utils import Secret, deserialize_secrets_inplace
15
+
16
+ from converter_studio import (
17
+ APIConnectionError,
18
+ AsyncConverterStudio,
19
+ AuthenticationError,
20
+ ConverterStudio,
21
+ Format,
22
+ InsufficientCreditsError,
23
+ MissingApiKeyError,
24
+ PermissionDeniedError,
25
+ RateLimitError,
26
+ )
27
+
28
+ from ._version import __version__
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ API_KEY_ENV = "CONVERTER_STUDIO_API_KEY"
33
+ #: Sent on every request in X-Converter-Studio-Client and in front of the User-Agent (the Python
34
+ #: client's ``client_name``), for usage statistics only.
35
+ CLIENT_NAME = f"haystack/{__version__}"
36
+ #: Seconds for each network step of a request (connecting, sending or reading a chunk).
37
+ NETWORK_TIMEOUT = 60.0
38
+ #: Seconds to wait for one conversion.
39
+ DEFAULT_TIMEOUT = 600.0
40
+ #: Conversions running at the same time in ``run_async``.
41
+ DEFAULT_CONCURRENCY = 4
42
+
43
+ SourceType: TypeAlias = str | Path | ByteStream
44
+
45
+ #: Errors every following source would meet too (no key, a wrong key, no credits, a plan that
46
+ #: does not allow it, too many requests, the API out of reach): they stop the run.
47
+ STOPPING_ERRORS: tuple[type[Exception], ...] = (
48
+ MissingApiKeyError,
49
+ AuthenticationError,
50
+ PermissionDeniedError,
51
+ InsufficientCreditsError,
52
+ RateLimitError,
53
+ APIConnectionError,
54
+ )
55
+
56
+ # MIME types Python's own table may not know, by the format they are.
57
+ _MIME_EXTENSIONS = {
58
+ "image/heic": "heic",
59
+ "image/heif": "heic",
60
+ "image/avif": "avif",
61
+ "image/webp": "webp",
62
+ "image/x-adobe-dng": "dng",
63
+ "image/x-canon-cr2": "cr2",
64
+ "image/x-nikon-nef": "nef",
65
+ "image/x-sony-arw": "arw",
66
+ "image/svg+xml": "svg",
67
+ "application/postscript": "eps",
68
+ "text/markdown": "md",
69
+ "application/yaml": "yaml",
70
+ "application/x-yaml": "yaml",
71
+ "text/yaml": "yaml",
72
+ "application/epub+zip": "epub",
73
+ "application/x-mobipocket-ebook": "mobi",
74
+ "application/vnd.amazon.ebook": "azw3",
75
+ "application/x-fictionbook+xml": "fb2",
76
+ "application/x-7z-compressed": "7z",
77
+ "application/vnd.rar": "rar",
78
+ "application/x-rar-compressed": "rar",
79
+ "text/vtt": "vtt",
80
+ "application/x-subrip": "srt",
81
+ "font/ttf": "ttf",
82
+ "font/otf": "otf",
83
+ "font/woff": "woff",
84
+ "font/woff2": "woff2",
85
+ }
86
+ _EXTENSION_MIMES = {
87
+ **{extension: mime for mime, extension in reversed(_MIME_EXTENSIONS.items())},
88
+ "tar.gz": "application/gzip",
89
+ "tgz": "application/gzip",
90
+ }
91
+
92
+
93
+ def is_url(source: object) -> bool:
94
+ return isinstance(source, str) and source.lower().startswith(("http://", "https://"))
95
+
96
+
97
+ def extension_of(name: str | None) -> str | None:
98
+ """A file name's extension, lower case and without the dot (``tar.gz`` counts as one)."""
99
+ if not name:
100
+ return None
101
+ lower = name.lower()
102
+ if lower.endswith(".tar.gz"):
103
+ return "tar.gz"
104
+ suffix = PurePosixPath(lower).suffix
105
+ return suffix[1:] or None
106
+
107
+
108
+ def extension_for_mime(mime_type: str | None) -> str | None:
109
+ """The extension a MIME type stands for, when it names a specific format."""
110
+ if not mime_type:
111
+ return None
112
+ bare = mime_type.split(";", 1)[0].strip().lower()
113
+ if bare in _MIME_EXTENSIONS:
114
+ return _MIME_EXTENSIONS[bare]
115
+ guessed = mimetypes.guess_extension(bare, strict=False)
116
+ return guessed[1:] if guessed and guessed != ".bin" else None
117
+
118
+
119
+ def mime_type_for(name: str | None) -> str | None:
120
+ """The MIME type of a file by its name."""
121
+ extension = extension_of(name)
122
+ if extension in _EXTENSION_MIMES:
123
+ return _EXTENSION_MIMES[extension]
124
+ guessed, _ = (
125
+ mimetypes.guess_type(f"file.{extension}", strict=False) if extension else (None, None)
126
+ )
127
+ return guessed
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class Input:
132
+ """A source made ready for the client."""
133
+
134
+ #: A link (``str``), a local path, or the bytes of a ``ByteStream``.
135
+ file: str | Path | bytes
136
+ #: The name a ``ByteStream`` has in its metadata (``file_path``, ``file_name`` or ``name``).
137
+ name: str | None
138
+ #: The extension its name gives, and the one its MIME type gives (``ByteStream`` only).
139
+ name_extension: str | None
140
+ type_extension: str | None
141
+ #: The metadata it brings: a ``ByteStream``'s own, ``file_path`` of a path, ``url`` of a link.
142
+ meta: dict[str, Any]
143
+ #: A ``ByteStream``'s ``encoding`` (Haystack's convention), for reading text here.
144
+ encoding: str | None = None
145
+
146
+ @property
147
+ def is_url(self) -> bool:
148
+ return isinstance(self.file, str)
149
+
150
+
151
+ def read_source(source: SourceType) -> Input:
152
+ """What to send for a source: a ``ByteStream``'s bytes, a path, or a link (a ``str`` starting
153
+ with ``http://`` or ``https://``; Converter Studio downloads the file itself)."""
154
+ if isinstance(source, ByteStream):
155
+ meta = dict(source.meta or {})
156
+ raw = meta.get("file_path") or meta.get("file_name") or meta.get("name")
157
+ name = PurePosixPath(str(raw).replace("\\", "/")).name if raw else None
158
+ encoding = meta.get("encoding")
159
+ return Input(
160
+ file=source.data,
161
+ name=name or None,
162
+ name_extension=extension_of(name),
163
+ type_extension=extension_for_mime(source.mime_type),
164
+ meta=meta,
165
+ encoding=encoding if isinstance(encoding, str) else None,
166
+ )
167
+ if isinstance(source, str) and is_url(source):
168
+ last = PurePosixPath(urlsplit(source).path).name
169
+ return Input(
170
+ file=source,
171
+ name=None,
172
+ name_extension=extension_of(last),
173
+ type_extension=None,
174
+ meta={"url": source},
175
+ )
176
+ if isinstance(source, str | Path):
177
+ path = Path(source)
178
+ if not path.is_file():
179
+ raise FileNotFoundError(f"No such file: {path}")
180
+ return Input(
181
+ file=path,
182
+ name=path.name,
183
+ name_extension=extension_of(path.name),
184
+ type_extension=None,
185
+ meta={"file_path": str(source)},
186
+ )
187
+ raise ValueError(f"Unsupported source type {type(source).__name__}")
188
+
189
+
190
+ def describe(source: SourceType) -> str:
191
+ """A source in a log line: its path or link, or a ``ByteStream``'s name (never its bytes)."""
192
+ if isinstance(source, ByteStream):
193
+ meta = source.meta or {}
194
+ raw = meta.get("file_path") or meta.get("file_name") or meta.get("name")
195
+ return f"ByteStream {raw}" if raw else f"a ByteStream of {len(source.data)} bytes"
196
+ return str(source)
197
+
198
+
199
+ class Catalog:
200
+ """The formats the API reads (``GET /v1/formats``, no key needed), by id and extension."""
201
+
202
+ def __init__(self, formats: list[Format]) -> None:
203
+ self.by_id: dict[str, Format] = {item.id: item for item in formats}
204
+ self.by_extension: dict[str, Format] = {}
205
+ for item in formats:
206
+ for extension in (item.id, *item.extensions):
207
+ self.by_extension.setdefault(extension.lower(), item)
208
+
209
+ def get(self, format_id: str | None) -> Format | None:
210
+ return self.by_id.get(format_id) if format_id else None
211
+
212
+ def identify(self, item: Input) -> Format | None:
213
+ """What a source is: by a ``ByteStream``'s MIME type first, then by its name."""
214
+ return self.by_extension.get(item.type_extension or "") or self.by_extension.get(
215
+ item.name_extension or ""
216
+ )
217
+
218
+ def upload(self, item: Input, known: Format | None) -> tuple[str | Path | bytes, str | None]:
219
+ """What to hand to the client and, for bytes, the file name to send with them.
220
+
221
+ A ``ByteStream`` whose name says something else than its MIME type (``slides.pptx``
222
+ holding the PDF made from it) is sent under the name its MIME type gives (``slides.pdf``);
223
+ one without a name is sent as ``document`` (the API also reads the format from the bytes).
224
+ """
225
+ if not isinstance(item.file, bytes):
226
+ return item.file, None
227
+ name = item.name or "document"
228
+ by_name = self.by_extension.get(item.name_extension or "")
229
+ if known is None or by_name is known:
230
+ return item.file, name
231
+ if by_name is not None and item.name_extension:
232
+ name = name[: -(len(item.name_extension) + 1)]
233
+ extension = known.extensions[0] if known.extensions else known.id
234
+ return item.file, f"{name}.{extension}"
235
+
236
+
237
+ class ConverterStudioComponent:
238
+ """The settings, the client's life cycle and the error rule both components share.
239
+
240
+ Not a component itself. The API client is made in :meth:`warm_up` (the API key is read
241
+ there, not in ``__init__``) and released in :meth:`close`; ``run`` warms up on its own when
242
+ it has not been.
243
+ """
244
+
245
+ def __init__(
246
+ self,
247
+ *,
248
+ api_key: Secret,
249
+ base_url: str | None,
250
+ options: Mapping[str, Any] | None,
251
+ max_credits: int | None,
252
+ timeout: float,
253
+ raise_on_failure: bool,
254
+ concurrency_limit: int,
255
+ ) -> None:
256
+ if options is not None and not isinstance(options, Mapping):
257
+ raise ValueError("options must be a dictionary of the API's conversion settings")
258
+ if max_credits is not None and (
259
+ isinstance(max_credits, bool) or not isinstance(max_credits, int) or max_credits < 0
260
+ ):
261
+ raise ValueError("max_credits must be a whole number, 0 or more, or None")
262
+ if timeout <= 0:
263
+ raise ValueError("timeout must be more than 0 seconds")
264
+ if isinstance(concurrency_limit, bool) or concurrency_limit < 1:
265
+ raise ValueError("concurrency_limit must be 1 or more")
266
+ self.api_key = api_key
267
+ self.base_url = base_url
268
+ self.options = dict(options) if options else None
269
+ self.max_credits = max_credits
270
+ self.timeout = timeout
271
+ self.raise_on_failure = raise_on_failure
272
+ self.concurrency_limit = concurrency_limit
273
+ self._client: ConverterStudio | None = None
274
+ self._http: httpx.Client | None = None
275
+ self._async_client: AsyncConverterStudio | None = None
276
+ self._async_http: httpx.AsyncClient | None = None
277
+ self._catalog: Catalog | None = None
278
+ # Tests replace the network here.
279
+ self._transport: httpx.BaseTransport | None = None
280
+ self._async_transport: httpx.AsyncBaseTransport | None = None
281
+
282
+ # Life cycle
283
+
284
+ def warm_up(self) -> None:
285
+ """Makes the API client and reads the API key (raises when ``api_key`` cannot be read).
286
+
287
+ Calling it again does nothing until :meth:`close`.
288
+ """
289
+ if self._client is not None:
290
+ return
291
+ api_key = self._resolve_api_key()
292
+ http = httpx.Client(
293
+ timeout=NETWORK_TIMEOUT, follow_redirects=False, transport=self._transport
294
+ )
295
+ try:
296
+ self._client = ConverterStudio(
297
+ api_key=api_key, base_url=self.base_url, http_client=http, client_name=CLIENT_NAME
298
+ )
299
+ except BaseException:
300
+ http.close()
301
+ raise
302
+ self._http = http
303
+
304
+ async def warm_up_async(self) -> None:
305
+ """Makes the asynchronous API client on the running event loop; see :meth:`warm_up`."""
306
+ if self._async_client is not None:
307
+ return
308
+ api_key = self._resolve_api_key()
309
+ http = httpx.AsyncClient(
310
+ timeout=NETWORK_TIMEOUT, follow_redirects=False, transport=self._async_transport
311
+ )
312
+ try:
313
+ self._async_client = AsyncConverterStudio(
314
+ api_key=api_key, base_url=self.base_url, http_client=http, client_name=CLIENT_NAME
315
+ )
316
+ except BaseException:
317
+ await http.aclose()
318
+ raise
319
+ self._async_http = http
320
+
321
+ def close(self) -> None:
322
+ """Closes the synchronous client's connections."""
323
+ if self._http is not None:
324
+ self._http.close()
325
+ self._client = None
326
+ self._http = None
327
+
328
+ async def close_async(self) -> None:
329
+ """Closes the asynchronous client's connections."""
330
+ if self._async_http is not None:
331
+ await self._async_http.aclose()
332
+ self._async_client = None
333
+ self._async_http = None
334
+
335
+ def _resolve_api_key(self) -> str | None:
336
+ value = self.api_key.resolve_value()
337
+ return value if isinstance(value, str) else None
338
+
339
+ def _ready_client(self) -> ConverterStudio:
340
+ self.warm_up()
341
+ if self._client is None: # pragma: no cover (warm_up made it)
342
+ raise RuntimeError("The Converter Studio client could not be made")
343
+ return self._client
344
+
345
+ async def _ready_async_client(self) -> AsyncConverterStudio:
346
+ await self.warm_up_async()
347
+ if self._async_client is None: # pragma: no cover (warm_up_async made it)
348
+ raise RuntimeError("The Converter Studio client could not be made")
349
+ return self._async_client
350
+
351
+ def _catalog_from(self, client: ConverterStudio) -> Catalog:
352
+ if self._catalog is None:
353
+ self._catalog = Catalog(client.formats())
354
+ return self._catalog
355
+
356
+ async def _catalog_from_async(self, client: AsyncConverterStudio) -> Catalog:
357
+ if self._catalog is None:
358
+ self._catalog = Catalog(await client.formats())
359
+ return self._catalog
360
+
361
+ # Failures
362
+
363
+ def _failed(self, message: str, source: SourceType, error: Exception) -> None:
364
+ """A source that could not be converted: skipped with a warning (the API's own message),
365
+ or raised again with ``raise_on_failure``."""
366
+ if self.raise_on_failure:
367
+ raise error
368
+ logger.warning(message, source=describe(source), error=str(error))
369
+
370
+ # Serialization
371
+
372
+ def _shared_init_parameters(self) -> dict[str, Any]:
373
+ return {
374
+ "api_key": self.api_key.to_dict(),
375
+ "base_url": self.base_url,
376
+ "options": self.options,
377
+ "max_credits": self.max_credits,
378
+ "timeout": self.timeout,
379
+ "raise_on_failure": self.raise_on_failure,
380
+ "concurrency_limit": self.concurrency_limit,
381
+ }
382
+
383
+ @classmethod
384
+ def from_dict(cls, data: dict[str, Any]) -> Self:
385
+ """Deserializes the component from a dictionary.
386
+
387
+ :param data: The dictionary to deserialize from (it is not changed).
388
+ :returns: The deserialized component.
389
+ """
390
+ init_parameters = dict(data.get("init_parameters", {}))
391
+ deserialize_secrets_inplace(init_parameters, keys=["api_key"])
392
+ return default_from_dict(cls, {**data, "init_parameters": init_parameters})
@@ -0,0 +1,3 @@
1
+ """The package version, also sent in the X-Converter-Studio-Client header."""
2
+
3
+ __version__ = "1.0.0"