pdfconversionapi 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.
@@ -0,0 +1,315 @@
1
+ """The synchronous client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from pathlib import Path
9
+ from types import TracebackType
10
+ from typing import TypeVar
11
+
12
+ import httpx
13
+
14
+ from ._base import ClientBase
15
+ from ._core import (
16
+ DEFAULT_CONNECT_TIMEOUT,
17
+ DEFAULT_MAX_RETRIES,
18
+ DEFAULT_MAX_RETRY_WAIT,
19
+ DEFAULT_TIMEOUT,
20
+ Call,
21
+ Deadline,
22
+ ParamValue,
23
+ ParsedConversion,
24
+ RetryState,
25
+ api_error,
26
+ body_error,
27
+ httpx_timeout,
28
+ log_retry,
29
+ parse_conversion,
30
+ parse_conversions,
31
+ parse_usage,
32
+ request_headers,
33
+ request_id,
34
+ wait_after_send_error,
35
+ )
36
+ from ._files import discard_partial, safe_file_name, url_file_name
37
+ from ._inputs import FileInput
38
+ from ._models import Conversion, ConversionResult, OutputFile, Usage
39
+ from ._multipart import MultipartBody
40
+
41
+ __all__ = ["PdfConversionApi"]
42
+
43
+ T = TypeVar("T")
44
+
45
+
46
+ class PdfConversionApi(ClientBase):
47
+ """The PDF Conversion API client.
48
+
49
+ >>> client = PdfConversionApi() # reads PDFCONVERSIONAPI_KEY
50
+ >>> result = client.convert_file("report.docx", "pdf")
51
+ >>> result.save_all("out") # writes out/report.pdf
52
+
53
+ Args:
54
+ api_key: the API key. Defaults to the ``PDFCONVERSIONAPI_KEY`` environment variable.
55
+ It may be missing: ``conversions()`` and downloads need none, and other calls raise
56
+ MissingApiKeyError before sending anything.
57
+ base_url: defaults to ``PDFCONVERSIONAPI_BASE_URL``, else
58
+ ``https://api.pdfconversionapi.com``.
59
+ timeout: seconds each attempt may take, for the whole response (default 240).
60
+ connect_timeout: seconds to wait for a connection to open (default 10).
61
+ max_retries: retries after the first attempt (default 4); 0 turns retries off.
62
+ max_retry_wait: the longest ``Retry-After`` to wait for (default 60 seconds). A longer
63
+ one, such as a used-up month, is raised at once.
64
+ http_client: your own ``httpx.Client`` (proxies, custom TLS). It is not closed by
65
+ :meth:`close`. The timeout is set on each request.
66
+ sleep: replaces ``time.sleep`` between retries. For tests.
67
+
68
+ The client is safe to share between threads. Close it with :meth:`close`, or use it as a
69
+ context manager.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ api_key: str | None = None,
76
+ base_url: str | None = None,
77
+ timeout: float = DEFAULT_TIMEOUT,
78
+ connect_timeout: float = DEFAULT_CONNECT_TIMEOUT,
79
+ max_retries: int = DEFAULT_MAX_RETRIES,
80
+ max_retry_wait: float = DEFAULT_MAX_RETRY_WAIT,
81
+ http_client: httpx.Client | None = None,
82
+ sleep: Callable[[float], None] | None = None,
83
+ ) -> None:
84
+ super().__init__(
85
+ api_key=api_key,
86
+ base_url=base_url,
87
+ timeout=timeout,
88
+ connect_timeout=connect_timeout,
89
+ max_retries=max_retries,
90
+ max_retry_wait=max_retry_wait,
91
+ )
92
+ if http_client is not None and not isinstance(http_client, httpx.Client):
93
+ raise TypeError(
94
+ f"http_client must be an httpx.Client, not {type(http_client).__name__}"
95
+ + (
96
+ " (use AsyncPdfConversionApi)"
97
+ if isinstance(http_client, httpx.AsyncClient)
98
+ else ""
99
+ )
100
+ )
101
+ self._owns_http = http_client is None
102
+ self._http = http_client if http_client is not None else httpx.Client()
103
+ self._sleep = sleep if sleep is not None else time.sleep
104
+
105
+ def close(self) -> None:
106
+ """Closes the connections, unless the httpx.Client was passed in."""
107
+ if self._owns_http:
108
+ self._http.close()
109
+
110
+ def __enter__(self) -> PdfConversionApi:
111
+ return self
112
+
113
+ def __exit__(
114
+ self,
115
+ exc_type: type[BaseException] | None,
116
+ exc: BaseException | None,
117
+ tb: TracebackType | None,
118
+ ) -> None:
119
+ self.close()
120
+
121
+ # The API
122
+
123
+ def convert(
124
+ self,
125
+ from_format: str,
126
+ to_format: str,
127
+ files: FileInput | Sequence[FileInput] | None = None,
128
+ params: Mapping[str, ParamValue] | None = None,
129
+ *,
130
+ file_name: str | None = None,
131
+ store_file: bool = False,
132
+ timeout: float | None = None,
133
+ ) -> ConversionResult:
134
+ """Converts files: ``POST /v2/convert/{from_format}/to/{to_format}``.
135
+
136
+ Args:
137
+ from_format: the input format, such as ``docx``, or ``pdf`` for the PDF tools.
138
+ to_format: the output format, such as ``pdf``, or a tool such as ``merge``.
139
+ files: one input or a list of inputs. An input is a path (a ``str`` is always a
140
+ path), bytes, a binary stream or an :class:`UploadFile`. One file is sent as
141
+ ``File``, several as repeated ``Files``. Leave it out for conversions that take
142
+ no file, such as ``data/to/qrcode``.
143
+ params: the conversion's parameters, such as ``{"PageRange": "1-3"}``. Numbers and
144
+ booleans are sent as text, ``None`` is left out, and a file value (a
145
+ ``pathlib.Path``, bytes, a stream or an UploadFile) is sent as a named file field
146
+ such as ``ImageFile``.
147
+ file_name: the output's name, without the extension (sent as ``FileName``).
148
+ store_file: return download links instead of data (sent as ``StoreFile=true``).
149
+ timeout: seconds for this call's attempts, instead of the client's.
150
+ """
151
+ call = self._convert_call(
152
+ from_format, to_format, files, params, file_name, store_file, timeout
153
+ )
154
+ return self._result(self._json(call, parse_conversion))
155
+
156
+ def convert_file(
157
+ self,
158
+ path: str | os.PathLike[str],
159
+ to_format: str,
160
+ params: Mapping[str, ParamValue] | None = None,
161
+ *,
162
+ file_name: str | None = None,
163
+ store_file: bool = False,
164
+ timeout: float | None = None,
165
+ ) -> ConversionResult:
166
+ """Converts one file on disk; its extension is the input format.
167
+
168
+ ``convert_file("report.docx", "pdf")`` is ``convert("docx", "pdf", "report.docx")``.
169
+ Raises ValueError when the path has no extension.
170
+ """
171
+ from_format, upload = self._file_input(path)
172
+ return self.convert(
173
+ from_format,
174
+ to_format,
175
+ upload,
176
+ params,
177
+ file_name=file_name,
178
+ store_file=store_file,
179
+ timeout=timeout,
180
+ )
181
+
182
+ def usage(self, *, timeout: float | None = None) -> Usage:
183
+ """Your plan, its limits and this month's count: ``GET /v2/usage``."""
184
+ return self._json(self._usage_call(timeout), parse_usage)
185
+
186
+ def conversions(self, *, timeout: float | None = None) -> list[Conversion]:
187
+ """Every conversion the API offers: ``GET /v2/info``. Needs no key."""
188
+ return self._json(self._conversions_call(timeout), parse_conversions)
189
+
190
+ def download(self, url: str, *, timeout: float | None = None) -> bytes:
191
+ """Downloads a stored file's ``url`` into memory. The key is not sent."""
192
+ call = self._download_call(url, timeout)
193
+
194
+ def handle(response: httpx.Response, deadline: Deadline) -> bytes:
195
+ body = self._read(response, call, deadline)
196
+ if response.status_code != 200:
197
+ raise api_error(response.status_code, response.headers, body)
198
+ return bytes(body)
199
+
200
+ return self._execute(call, handle)
201
+
202
+ def download_to(
203
+ self, url: str, path: str | os.PathLike[str], *, timeout: float | None = None
204
+ ) -> Path:
205
+ """Downloads a stored file's ``url`` to ``path``, streamed to disk, and returns the path.
206
+
207
+ If ``path`` is an existing folder, the file is written inside it under the name at the
208
+ end of the URL. An existing file is overwritten. The key is not sent.
209
+ """
210
+ call = self._download_call(url, timeout)
211
+ target = Path(path)
212
+ if target.is_dir():
213
+ target = target / safe_file_name(url_file_name(call.url))
214
+
215
+ def handle(response: httpx.Response, deadline: Deadline) -> Path:
216
+ if response.status_code != 200:
217
+ body = self._read(response, call, deadline)
218
+ raise api_error(response.status_code, response.headers, body)
219
+ try:
220
+ with open(target, "wb") as out:
221
+ for chunk in response.iter_bytes():
222
+ out.write(chunk)
223
+ deadline.check()
224
+ except httpx.HTTPError as exc:
225
+ discard_partial(target)
226
+ raise body_error(exc, call, self._settings) from exc
227
+ except BaseException:
228
+ discard_partial(target)
229
+ raise
230
+ return target
231
+
232
+ return self._execute(call, handle)
233
+
234
+ def delete_stored_file(self, file_id: str, *, timeout: float | None = None) -> bool:
235
+ """Deletes a stored file now: ``DELETE /v2/d/{file_id}``.
236
+
237
+ Returns True when it was deleted, False when there was nothing to delete (unknown id,
238
+ already deleted or expired, or another account's file).
239
+ """
240
+ call = self._delete_call(file_id, timeout)
241
+
242
+ def handle(response: httpx.Response, deadline: Deadline) -> bool:
243
+ if 200 <= response.status_code < 300:
244
+ return True
245
+ body = self._read(response, call, deadline)
246
+ if response.status_code == 404:
247
+ return False
248
+ raise api_error(response.status_code, response.headers, body)
249
+
250
+ return self._execute(call, handle)
251
+
252
+ # Plumbing
253
+
254
+ def _result(self, parsed: ParsedConversion) -> ConversionResult:
255
+ files = [OutputFile(entry, self) for entry in parsed.files]
256
+ return ConversionResult(
257
+ files, parsed.conversion_cost, parsed.conversion_time, parsed.request_id
258
+ )
259
+
260
+ def _json(self, call: Call, parse: Callable[[bytearray, str | None], T]) -> T:
261
+ def handle(response: httpx.Response, deadline: Deadline) -> T:
262
+ body = self._read(response, call, deadline)
263
+ if response.status_code != 200:
264
+ raise api_error(response.status_code, response.headers, body)
265
+ return parse(body, request_id(response.headers))
266
+
267
+ return self._execute(call, handle)
268
+
269
+ def _read(self, response: httpx.Response, call: Call, deadline: Deadline) -> bytearray:
270
+ body = bytearray()
271
+ try:
272
+ for chunk in response.iter_bytes():
273
+ body += chunk
274
+ deadline.check()
275
+ except httpx.HTTPError as exc:
276
+ raise body_error(exc, call, self._settings) from exc
277
+ return body
278
+
279
+ def _build(self, call: Call, deadline: Deadline) -> httpx.Request:
280
+ body = MultipartBody(call.fields) if call.fields is not None else None
281
+ request = self._http.build_request(
282
+ call.method,
283
+ call.url,
284
+ headers=request_headers(call, self._settings, body),
285
+ content=body.chunks(deadline.check) if body is not None else None,
286
+ timeout=httpx_timeout(call, self._settings),
287
+ )
288
+ if not call.authorized:
289
+ request.headers.pop("Authorization", None)
290
+ return request
291
+
292
+ def _execute(self, call: Call, handle: Callable[[httpx.Response, Deadline], T]) -> T:
293
+ """Sends ``call`` with the retry rules, then hands the final response to ``handle``."""
294
+ state = RetryState(self._settings.max_retries, self._settings.max_retry_wait)
295
+ while True:
296
+ state.next_attempt()
297
+ deadline = Deadline(call)
298
+ request = self._build(call, deadline)
299
+ try:
300
+ response = self._http.send(request, stream=True, follow_redirects=False)
301
+ except httpx.TransportError as exc:
302
+ wait = wait_after_send_error(exc, state, call, self._settings)
303
+ why = f"no response ({type(exc).__name__})"
304
+ else:
305
+ try:
306
+ retry = state.after_status(
307
+ response.status_code, response.headers.get("retry-after")
308
+ )
309
+ if retry is None:
310
+ return handle(response, deadline)
311
+ wait, why = retry, f"HTTP {response.status_code}"
312
+ finally:
313
+ response.close()
314
+ log_retry(call, state, wait, why)
315
+ self._sleep(wait)