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,170 @@
1
+ """The errors this library raises.
2
+
3
+ Every error is a :class:`PdfConversionApiError`. Bad arguments raise the built-in
4
+ :class:`ValueError` or :class:`TypeError` instead, before anything is sent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ __all__ = [
10
+ "APIConnectionError",
11
+ "APITimeoutError",
12
+ "ApiError",
13
+ "AuthenticationError",
14
+ "BadRequestError",
15
+ "GatewayTimeoutError",
16
+ "InternalServerError",
17
+ "InvalidResponseError",
18
+ "MissingApiKeyError",
19
+ "NotFoundError",
20
+ "PayloadTooLargeError",
21
+ "PdfConversionApiError",
22
+ "PermissionDeniedError",
23
+ "RateLimitError",
24
+ "ServiceUnavailableError",
25
+ "StoredFileError",
26
+ "UnprocessableEntityError",
27
+ ]
28
+
29
+
30
+ def _with_request_id(text: str, request_id: str | None) -> str:
31
+ return f"{text} (request id: {request_id})" if request_id else text
32
+
33
+
34
+ class PdfConversionApiError(Exception):
35
+ """The base class of every error raised by this library."""
36
+
37
+ message: str
38
+
39
+ def __init__(self, message: str) -> None:
40
+ super().__init__(message)
41
+ self.message = message
42
+
43
+
44
+ class MissingApiKeyError(PdfConversionApiError):
45
+ """A call that needs an API key was made without one. Nothing was sent.
46
+
47
+ Pass ``api_key=`` to the client or set the ``PDFCONVERSIONAPI_KEY`` environment variable.
48
+ """
49
+
50
+
51
+ class StoredFileError(PdfConversionApiError):
52
+ """The data of a stored file (``store_file=True``) was read. Call ``download()`` instead."""
53
+
54
+
55
+ class APIConnectionError(PdfConversionApiError):
56
+ """No response came back: the connection failed or was closed, after every retry."""
57
+
58
+
59
+ class APITimeoutError(PdfConversionApiError):
60
+ """The client's own timeout ran out. Never retried.
61
+
62
+ A conversion may still be running on the server and counts toward the month if it
63
+ succeeds, so raise ``timeout`` rather than retrying at once.
64
+ """
65
+
66
+
67
+ class InvalidResponseError(PdfConversionApiError):
68
+ """A successful response whose body can't be used: bad JSON, no ``Files``, a size mismatch."""
69
+
70
+ request_id: str | None
71
+
72
+ def __init__(self, message: str, *, request_id: str | None = None) -> None:
73
+ super().__init__(message)
74
+ self.request_id = request_id
75
+
76
+ def __str__(self) -> str:
77
+ return _with_request_id(self.message, self.request_id)
78
+
79
+
80
+ class ApiError(PdfConversionApiError):
81
+ """The API answered with an error status.
82
+
83
+ Attributes:
84
+ status: the HTTP status code.
85
+ message: the API's message, or a description of a body that had none.
86
+ request_id: the ``x-request-id`` header, or ``None`` when the response had none
87
+ (such responses come from the network in front of the API).
88
+ retry_after: the ``Retry-After`` header in seconds (sent on 429 and 503), else ``None``.
89
+ body: the raw response body, for debugging.
90
+ """
91
+
92
+ status: int
93
+ request_id: str | None
94
+ retry_after: int | None
95
+ body: str
96
+
97
+ def __init__(
98
+ self,
99
+ status: int,
100
+ message: str,
101
+ *,
102
+ request_id: str | None = None,
103
+ retry_after: int | None = None,
104
+ body: str = "",
105
+ ) -> None:
106
+ # args holds (status, message) so that pickling rebuilds the error; the keyword
107
+ # attributes travel in __dict__.
108
+ Exception.__init__(self, status, message)
109
+ self.status = status
110
+ self.message = message
111
+ self.request_id = request_id
112
+ self.retry_after = retry_after
113
+ self.body = body
114
+
115
+ def __str__(self) -> str:
116
+ return _with_request_id(f"HTTP {self.status}: {self.message}", self.request_id)
117
+
118
+
119
+ class BadRequestError(ApiError):
120
+ """400: the request is malformed, or a parameter has a value the conversion can't use."""
121
+
122
+
123
+ class AuthenticationError(ApiError):
124
+ """401: the API key is missing, unknown or no longer valid."""
125
+
126
+
127
+ class PermissionDeniedError(ApiError):
128
+ """403: the key's plan isn't set up."""
129
+
130
+
131
+ class NotFoundError(ApiError):
132
+ """404: an unsupported conversion, or a stored file that expired or was deleted."""
133
+
134
+
135
+ class PayloadTooLargeError(ApiError):
136
+ """413: the request, an image or a page is over a limit."""
137
+
138
+
139
+ class UnprocessableEntityError(ApiError):
140
+ """422: the file can't be read or converted as asked."""
141
+
142
+
143
+ class RateLimitError(ApiError):
144
+ """429: too many requests, too many conversions at once, or the month's conversions used up."""
145
+
146
+
147
+ class InternalServerError(ApiError):
148
+ """500: an unexpected failure on the server. Retried once."""
149
+
150
+
151
+ class ServiceUnavailableError(ApiError):
152
+ """503: the servers are busy, or conversions on the plan are paused."""
153
+
154
+
155
+ class GatewayTimeoutError(ApiError):
156
+ """504: the conversion ran out of time on the server. Not retried."""
157
+
158
+
159
+ ERRORS_BY_STATUS: dict[int, type[ApiError]] = {
160
+ 400: BadRequestError,
161
+ 401: AuthenticationError,
162
+ 403: PermissionDeniedError,
163
+ 404: NotFoundError,
164
+ 413: PayloadTooLargeError,
165
+ 422: UnprocessableEntityError,
166
+ 429: RateLimitError,
167
+ 500: InternalServerError,
168
+ 503: ServiceUnavailableError,
169
+ 504: GatewayTimeoutError,
170
+ }
@@ -0,0 +1,36 @@
1
+ """Writing results to disk safely."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import os
7
+ from pathlib import Path
8
+ from urllib.parse import unquote
9
+
10
+ import httpx
11
+
12
+ from ._exceptions import InvalidResponseError
13
+ from ._inputs import own_name
14
+
15
+
16
+ def safe_file_name(name: str) -> str:
17
+ """The file's own name, refusing names that would leave the folder or be empty."""
18
+ own = own_name(name)
19
+ if own in ("", ".", "..") or "\x00" in own:
20
+ raise InvalidResponseError(f"refusing to write a file named {name!r}")
21
+ return own
22
+
23
+
24
+ def save_target(path: str | os.PathLike[str], name: str) -> Path:
25
+ """``path`` itself, or ``name`` inside it when ``path`` is an existing folder."""
26
+ target = Path(path)
27
+ return target / safe_file_name(name) if target.is_dir() else target
28
+
29
+
30
+ def url_file_name(url: str) -> str:
31
+ return unquote(httpx.URL(url).path.rsplit("/", 1)[-1])
32
+
33
+
34
+ def discard_partial(path: Path) -> None:
35
+ with contextlib.suppress(OSError):
36
+ path.unlink()
@@ -0,0 +1,266 @@
1
+ """Input files: what can be uploaded, and how its bytes are read for each attempt."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import os
7
+ import re
8
+ from collections.abc import Iterator, Sequence
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Protocol, Union
11
+
12
+ if TYPE_CHECKING:
13
+ from typing_extensions import TypeAlias
14
+
15
+ __all__ = ["FileInput", "SupportsRead", "UploadFile"]
16
+
17
+ _CHUNK = 64 * 1024
18
+ _FOLDERS = re.compile(r"^.*[/\\]")
19
+
20
+
21
+ class SupportsRead(Protocol):
22
+ """A binary stream: anything with ``read(size) -> bytes``."""
23
+
24
+ def read(self, size: int = ..., /) -> bytes: ...
25
+
26
+
27
+ def own_name(name: str) -> str:
28
+ """The file's own name: everything after the last ``/`` or ``\\``."""
29
+ return _FOLDERS.sub("", name)
30
+
31
+
32
+ _UNSENDABLE = str.maketrans({'"': "_", "\r": "_", "\n": "_"})
33
+
34
+
35
+ def sendable_name(name: str) -> str:
36
+ """The name as sent in ``filename="..."``: the file's own name, with ``"``, CR and LF
37
+ replaced by ``_`` (the API reads ``%22`` literally, and turns a quote into ``_`` itself)."""
38
+ return own_name(name).translate(_UNSENDABLE) or "file"
39
+
40
+
41
+ class UploadFile:
42
+ """One file to upload: where its bytes come from, and the name sent with them.
43
+
44
+ Most calls accept a path, bytes or a binary stream directly; use these factories to set
45
+ the name sent with bytes or a stream (the API names its output after it):
46
+
47
+ >>> UploadFile.from_path("reports/q3.docx") # sent as "q3.docx"
48
+ >>> UploadFile.from_bytes(data, "q3.docx")
49
+ >>> UploadFile.from_stream(response_body, "q3.docx")
50
+
51
+ Only the file's own name is sent, never its folders, with ``"``, CR and LF replaced by
52
+ ``_``. Bytes and streams without a name are sent as ``file``; an open file object is sent
53
+ under its own file name.
54
+ """
55
+
56
+ __slots__ = ("_data", "_name", "_path", "_size", "_start", "_stream")
57
+
58
+ _name: str
59
+ _path: str | None
60
+ _data: bytes | None
61
+ _stream: SupportsRead | None
62
+ _start: int
63
+ _size: int
64
+
65
+ def __init__(self) -> None:
66
+ raise TypeError(
67
+ "use UploadFile.from_path(), UploadFile.from_bytes() or UploadFile.from_stream()"
68
+ )
69
+
70
+ @classmethod
71
+ def _make(cls, name: str) -> UploadFile:
72
+ self = object.__new__(cls)
73
+ self._name = sendable_name(name)
74
+ self._path = None
75
+ self._data = None
76
+ self._stream = None
77
+ self._start = 0
78
+ self._size = 0
79
+ return self
80
+
81
+ @classmethod
82
+ def from_path(cls, path: str | os.PathLike[str], name: str | None = None) -> UploadFile:
83
+ """A file on disk, read again for each attempt. The name sent is the path's last part.
84
+
85
+ A string is always a path, never the file's content.
86
+ """
87
+ if not isinstance(path, (str, os.PathLike)):
88
+ raise TypeError(f"path must be a str or os.PathLike, not {type(path).__name__}")
89
+ text = os.fsdecode(path)
90
+ if not text:
91
+ raise ValueError("path must not be empty")
92
+ self = cls._make(_check_name(name) if name is not None else os.path.basename(text))
93
+ self._path = text
94
+ return self
95
+
96
+ @classmethod
97
+ def from_bytes(
98
+ cls, data: bytes | bytearray | memoryview, name: str | None = None
99
+ ) -> UploadFile:
100
+ """Bytes in memory. Without a name they are sent as ``file``."""
101
+ if not isinstance(data, (bytes, bytearray, memoryview)):
102
+ raise TypeError(
103
+ f"data must be bytes, bytearray or memoryview, not {type(data).__name__}"
104
+ )
105
+ self = cls._make(_check_name(name) if name is not None else "file")
106
+ self._data = bytes(data)
107
+ self._size = len(self._data)
108
+ return self
109
+
110
+ @classmethod
111
+ def from_stream(cls, stream: SupportsRead, name: str | None = None) -> UploadFile:
112
+ """A binary stream. A seekable stream is rewound for each attempt; any other stream is
113
+ read into memory once, now, so that retries send the same bytes.
114
+
115
+ Without a name, an open file is sent under its own file name and any other stream as
116
+ ``file``.
117
+ """
118
+ read = getattr(stream, "read", None)
119
+ if not callable(read):
120
+ raise TypeError(f"stream must have a read() method, not {type(stream).__name__}")
121
+ if name is None:
122
+ stream_name = getattr(stream, "name", None)
123
+ if isinstance(stream_name, str) and stream_name and not stream_name.startswith("<"):
124
+ name = os.path.basename(stream_name)
125
+ else:
126
+ name = "file"
127
+ self = cls._make(_check_name(name))
128
+ if _seekable(stream):
129
+ probe = stream.read(0)
130
+ _check_binary(probe)
131
+ seeker: io.IOBase = stream # type: ignore[assignment]
132
+ self._start = seeker.tell()
133
+ self._size = seeker.seek(0, io.SEEK_END) - self._start
134
+ seeker.seek(self._start)
135
+ self._stream = stream
136
+ else:
137
+ chunks = []
138
+ while True:
139
+ chunk = stream.read(_CHUNK)
140
+ _check_binary(chunk)
141
+ if not chunk:
142
+ break
143
+ chunks.append(chunk)
144
+ self._data = b"".join(chunks)
145
+ self._size = len(self._data)
146
+ return self
147
+
148
+ @property
149
+ def name(self) -> str:
150
+ """The name sent in the upload's ``filename``."""
151
+ return self._name
152
+
153
+ def __repr__(self) -> str:
154
+ if self._path is not None:
155
+ return f"UploadFile.from_path({self._path!r}, name={self._name!r})"
156
+ kind = "from_stream" if self._stream is not None else "from_bytes"
157
+ return f"UploadFile.{kind}(<{self._size} bytes>, name={self._name!r})"
158
+
159
+ # Used by the multipart encoder, once per attempt.
160
+
161
+ def _content_size(self) -> int:
162
+ if self._path is not None:
163
+ return os.stat(self._path).st_size
164
+ return self._size
165
+
166
+ def _chunks(self, size: int) -> Iterator[bytes]:
167
+ """Yields exactly ``size`` bytes of content, read from the start."""
168
+ if self._data is not None:
169
+ view = memoryview(self._data)
170
+ for offset in range(0, len(view), _CHUNK):
171
+ yield bytes(view[offset : offset + _CHUNK])
172
+ return
173
+ if self._path is not None:
174
+ with open(self._path, "rb") as f:
175
+ yield from _read_exactly(f, size, self._path)
176
+ return
177
+ stream = self._stream
178
+ assert stream is not None
179
+ seeker: io.IOBase = stream # type: ignore[assignment]
180
+ seeker.seek(self._start)
181
+ yield from _read_exactly(stream, size, self._name)
182
+
183
+
184
+ FileInput: TypeAlias = Union[
185
+ str, "os.PathLike[str]", bytes, bytearray, memoryview, SupportsRead, UploadFile
186
+ ]
187
+ """One input file: a path (``str`` or ``os.PathLike``), bytes, a binary stream, or an
188
+ :class:`UploadFile`. A ``str`` is always a path."""
189
+
190
+
191
+ def _check_name(name: object) -> str:
192
+ if not isinstance(name, str):
193
+ raise TypeError(f"name must be a str, not {type(name).__name__}")
194
+ return name
195
+
196
+
197
+ def _check_binary(chunk: object) -> None:
198
+ if not isinstance(chunk, (bytes, bytearray)):
199
+ raise TypeError("streams must be opened in binary mode ('rb') and return bytes from read()")
200
+
201
+
202
+ def _seekable(stream: object) -> bool:
203
+ seekable = getattr(stream, "seekable", None)
204
+ try:
205
+ return bool(callable(seekable) and seekable())
206
+ except (OSError, ValueError):
207
+ return False
208
+
209
+
210
+ def _read_exactly(stream: SupportsRead, size: int, label: str) -> Iterator[bytes]:
211
+ remaining = size
212
+ while remaining > 0:
213
+ chunk = stream.read(min(_CHUNK, remaining))
214
+ if not chunk:
215
+ raise OSError(f"{label} became shorter while it was being uploaded")
216
+ remaining -= len(chunk)
217
+ yield bytes(chunk)
218
+
219
+
220
+ def to_upload(value: object, what: str) -> UploadFile:
221
+ """Turns one accepted input form into an UploadFile. A str is a path."""
222
+ if isinstance(value, UploadFile):
223
+ return value
224
+ if isinstance(value, (str, os.PathLike)):
225
+ return UploadFile.from_path(value)
226
+ if isinstance(value, (bytes, bytearray, memoryview)):
227
+ return UploadFile.from_bytes(value)
228
+ if callable(getattr(value, "read", None)):
229
+ return UploadFile.from_stream(value) # type: ignore[arg-type]
230
+ raise TypeError(
231
+ f"{what} must be a path (str or os.PathLike), bytes, a binary stream or an UploadFile, "
232
+ f"not {type(value).__name__}"
233
+ )
234
+
235
+
236
+ def is_single_input(value: object) -> bool:
237
+ return isinstance(value, (UploadFile, str, os.PathLike, bytes, bytearray, memoryview)) or (
238
+ callable(getattr(value, "read", None))
239
+ )
240
+
241
+
242
+ def to_uploads(files: object) -> list[UploadFile]:
243
+ """One input, a list of inputs, or None (no file), as a list."""
244
+ if files is None:
245
+ return []
246
+ if is_single_input(files):
247
+ return [to_upload(files, "files")]
248
+ if isinstance(files, Sequence):
249
+ return [to_upload(item, "each item of files") for item in files]
250
+ raise TypeError(
251
+ "files must be a path, bytes, a binary stream, an UploadFile, or a list of these, "
252
+ f"not {type(files).__name__}"
253
+ )
254
+
255
+
256
+ def path_extension(path: str | os.PathLike[str]) -> str:
257
+ """The lower-case extension of a path, without the dot. ValueError when there is none."""
258
+ if not isinstance(path, (str, os.PathLike)):
259
+ raise TypeError(f"path must be a str or os.PathLike, not {type(path).__name__}")
260
+ suffix = Path(os.fsdecode(path)).suffix
261
+ if len(suffix) < 2:
262
+ raise ValueError(
263
+ f"can't tell the format of {os.fsdecode(path)!r}: it has no extension; "
264
+ "use convert() and name the format"
265
+ )
266
+ return suffix[1:].lower()