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.
- pdfconversionapi/__init__.py +80 -0
- pdfconversionapi/_async_client.py +290 -0
- pdfconversionapi/_base.py +134 -0
- pdfconversionapi/_client.py +315 -0
- pdfconversionapi/_core.py +593 -0
- pdfconversionapi/_exceptions.py +170 -0
- pdfconversionapi/_files.py +36 -0
- pdfconversionapi/_inputs.py +266 -0
- pdfconversionapi/_models.py +281 -0
- pdfconversionapi/_multipart.py +80 -0
- pdfconversionapi/_version.py +1 -0
- pdfconversionapi/py.typed +0 -0
- pdfconversionapi-0.1.0.dist-info/METADATA +410 -0
- pdfconversionapi-0.1.0.dist-info/RECORD +16 -0
- pdfconversionapi-0.1.0.dist-info/WHEEL +4 -0
- pdfconversionapi-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Results: converted files, usage and the list of conversions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Awaitable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Generic, Protocol, TypeVar
|
|
11
|
+
|
|
12
|
+
from ._exceptions import StoredFileError
|
|
13
|
+
from ._files import safe_file_name, save_target
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from ._core import FileEntry
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"AsyncConversionResult",
|
|
20
|
+
"AsyncOutputFile",
|
|
21
|
+
"Conversion",
|
|
22
|
+
"ConversionResult",
|
|
23
|
+
"OutputFile",
|
|
24
|
+
"Usage",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Usage:
|
|
30
|
+
"""Your plan, its limits and this month's count (``GET /v2/usage``)."""
|
|
31
|
+
|
|
32
|
+
plan: str
|
|
33
|
+
"""The plan's name, for example ``Free``."""
|
|
34
|
+
included: int
|
|
35
|
+
"""Successful conversions included each calendar month."""
|
|
36
|
+
used: int
|
|
37
|
+
"""Successful conversions so far this month."""
|
|
38
|
+
remaining: int | None
|
|
39
|
+
"""What is left of ``included`` this month."""
|
|
40
|
+
overage: bool
|
|
41
|
+
"""Whether the plan keeps converting past ``included``."""
|
|
42
|
+
running: int
|
|
43
|
+
"""Conversions running for the account right now."""
|
|
44
|
+
concurrent_limit: int
|
|
45
|
+
"""How many conversions the plan runs at the same time."""
|
|
46
|
+
max_upload_mb: int
|
|
47
|
+
"""The largest request the plan accepts, all files together, in MB."""
|
|
48
|
+
period_start: datetime
|
|
49
|
+
"""The start of this month's count (UTC)."""
|
|
50
|
+
period_end: datetime
|
|
51
|
+
"""The end of this month's count (UTC); the count starts again then."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Conversion:
|
|
56
|
+
"""One conversion the API offers (an entry of ``GET /v2/info``)."""
|
|
57
|
+
|
|
58
|
+
from_format: str
|
|
59
|
+
"""The format in the path's ``{from}``, such as ``docx``."""
|
|
60
|
+
to_format: str
|
|
61
|
+
"""The format or tool in the path's ``{to}``, such as ``pdf`` or ``merge``."""
|
|
62
|
+
title: str
|
|
63
|
+
category: str
|
|
64
|
+
inputs: str
|
|
65
|
+
"""How many files it takes: ``one``, ``many`` or ``optional``."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _SyncFetcher(Protocol):
|
|
69
|
+
def download(self, url: str, *, timeout: float | None = None) -> bytes: ...
|
|
70
|
+
|
|
71
|
+
def download_to(
|
|
72
|
+
self, url: str, path: str | os.PathLike[str], *, timeout: float | None = None
|
|
73
|
+
) -> Path: ...
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _AsyncFetcher(Protocol):
|
|
77
|
+
def download(self, url: str, *, timeout: float | None = None) -> Awaitable[bytes]: ...
|
|
78
|
+
|
|
79
|
+
def download_to(
|
|
80
|
+
self, url: str, path: str | os.PathLike[str], *, timeout: float | None = None
|
|
81
|
+
) -> Awaitable[Path]: ...
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _OutputFileBase:
|
|
85
|
+
__slots__ = ("_entry",)
|
|
86
|
+
|
|
87
|
+
def __init__(self, entry: FileEntry) -> None:
|
|
88
|
+
self._entry = entry
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def name(self) -> str:
|
|
92
|
+
"""The file's name, extension included, as the API returned it."""
|
|
93
|
+
return self._entry.name
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def ext(self) -> str:
|
|
97
|
+
"""The extension in lower case, without the dot: ``pdf``, ``jpg``."""
|
|
98
|
+
return self._entry.ext
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def size(self) -> int:
|
|
102
|
+
"""The size in bytes."""
|
|
103
|
+
return self._entry.size
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def stored(self) -> bool:
|
|
107
|
+
"""True when the file was stored (``store_file=True``): it has a ``url`` instead of data."""
|
|
108
|
+
return self._entry.data is None
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def url(self) -> str | None:
|
|
112
|
+
"""The download link of a stored file (works for 3 hours, needs no key), else None."""
|
|
113
|
+
return self._entry.url
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def file_id(self) -> str | None:
|
|
117
|
+
"""The id of a stored file, for ``delete_stored_file()``, else None."""
|
|
118
|
+
return self._entry.file_id
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def data(self) -> bytes:
|
|
122
|
+
"""The file's bytes. For a stored file this raises StoredFileError: use ``download()``."""
|
|
123
|
+
data = self._entry.data
|
|
124
|
+
if data is None:
|
|
125
|
+
raise StoredFileError(
|
|
126
|
+
f"{self.name} is stored on the server (store_file=True), so the response has "
|
|
127
|
+
"no data: call download() or save() to fetch it"
|
|
128
|
+
)
|
|
129
|
+
return data
|
|
130
|
+
|
|
131
|
+
def __repr__(self) -> str:
|
|
132
|
+
where = f", url={self.url!r}" if self.stored else ""
|
|
133
|
+
return (
|
|
134
|
+
f"{type(self).__name__}(name={self.name!r}, ext={self.ext!r}, size={self.size}, "
|
|
135
|
+
f"stored={self.stored}{where})"
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class OutputFile(_OutputFileBase):
|
|
140
|
+
"""One converted file."""
|
|
141
|
+
|
|
142
|
+
__slots__ = ("_client",)
|
|
143
|
+
|
|
144
|
+
def __init__(self, entry: FileEntry, client: _SyncFetcher) -> None:
|
|
145
|
+
super().__init__(entry)
|
|
146
|
+
self._client = client
|
|
147
|
+
|
|
148
|
+
def download(self) -> bytes:
|
|
149
|
+
"""The file's bytes: fetched from ``url`` for a stored file (no key sent), else ``data``."""
|
|
150
|
+
if self._entry.url is not None and self._entry.data is None:
|
|
151
|
+
return self._client.download(self._entry.url)
|
|
152
|
+
return self.data
|
|
153
|
+
|
|
154
|
+
def save(self, path: str | os.PathLike[str]) -> Path:
|
|
155
|
+
"""Writes the file and returns the path written.
|
|
156
|
+
|
|
157
|
+
If ``path`` is an existing folder, the file is written inside it under its own name.
|
|
158
|
+
An existing file is overwritten. A stored file is downloaded, streamed to disk.
|
|
159
|
+
"""
|
|
160
|
+
target = save_target(path, self.name)
|
|
161
|
+
if self._entry.url is not None and self._entry.data is None:
|
|
162
|
+
return self._client.download_to(self._entry.url, target)
|
|
163
|
+
target.write_bytes(self.data)
|
|
164
|
+
return target
|
|
165
|
+
|
|
166
|
+
def download_to(self, path: str | os.PathLike[str]) -> Path:
|
|
167
|
+
"""The same as :meth:`save`."""
|
|
168
|
+
return self.save(path)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class AsyncOutputFile(_OutputFileBase):
|
|
172
|
+
"""One converted file, from :class:`AsyncPdfConversionApi`."""
|
|
173
|
+
|
|
174
|
+
__slots__ = ("_client",)
|
|
175
|
+
|
|
176
|
+
def __init__(self, entry: FileEntry, client: _AsyncFetcher) -> None:
|
|
177
|
+
super().__init__(entry)
|
|
178
|
+
self._client = client
|
|
179
|
+
|
|
180
|
+
async def download(self) -> bytes:
|
|
181
|
+
"""The file's bytes: fetched from ``url`` for a stored file (no key sent), else ``data``."""
|
|
182
|
+
if self._entry.url is not None and self._entry.data is None:
|
|
183
|
+
return await self._client.download(self._entry.url)
|
|
184
|
+
return self.data
|
|
185
|
+
|
|
186
|
+
async def save(self, path: str | os.PathLike[str]) -> Path:
|
|
187
|
+
"""Writes the file and returns the path written.
|
|
188
|
+
|
|
189
|
+
If ``path`` is an existing folder, the file is written inside it under its own name.
|
|
190
|
+
An existing file is overwritten. A stored file is downloaded, streamed to disk.
|
|
191
|
+
"""
|
|
192
|
+
target = save_target(path, self.name)
|
|
193
|
+
if self._entry.url is not None and self._entry.data is None:
|
|
194
|
+
return await self._client.download_to(self._entry.url, target)
|
|
195
|
+
target.write_bytes(self.data)
|
|
196
|
+
return target
|
|
197
|
+
|
|
198
|
+
async def download_to(self, path: str | os.PathLike[str]) -> Path:
|
|
199
|
+
"""The same as :meth:`save`."""
|
|
200
|
+
return await self.save(path)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
F = TypeVar("F", bound=_OutputFileBase)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class _ConversionResultBase(Generic[F]):
|
|
207
|
+
__slots__ = ("_conversion_cost", "_conversion_time", "_files", "_request_id")
|
|
208
|
+
|
|
209
|
+
def __init__(
|
|
210
|
+
self,
|
|
211
|
+
files: list[F],
|
|
212
|
+
conversion_cost: int,
|
|
213
|
+
conversion_time: float,
|
|
214
|
+
request_id: str | None,
|
|
215
|
+
) -> None:
|
|
216
|
+
self._files = files
|
|
217
|
+
self._conversion_cost = conversion_cost
|
|
218
|
+
self._conversion_time = conversion_time
|
|
219
|
+
self._request_id = request_id
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def files(self) -> list[F]:
|
|
223
|
+
"""Every output file, in the API's order."""
|
|
224
|
+
return list(self._files)
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def file(self) -> F:
|
|
228
|
+
"""The first output file: the only one for most conversions."""
|
|
229
|
+
return self._files[0]
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def conversion_cost(self) -> int:
|
|
233
|
+
"""Conversions this request used (always 1)."""
|
|
234
|
+
return self._conversion_cost
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def conversion_time(self) -> float:
|
|
238
|
+
"""Seconds the conversion took on the server, excluding upload, queueing and download."""
|
|
239
|
+
return self._conversion_time
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def request_id(self) -> str | None:
|
|
243
|
+
"""The ``x-request-id`` of the response: quote it when you ask support about a call."""
|
|
244
|
+
return self._request_id
|
|
245
|
+
|
|
246
|
+
def __repr__(self) -> str:
|
|
247
|
+
names = ", ".join(repr(f.name) for f in self._files)
|
|
248
|
+
return (
|
|
249
|
+
f"{type(self).__name__}(files=[{names}], conversion_cost={self.conversion_cost}, "
|
|
250
|
+
f"conversion_time={self.conversion_time}, request_id={self.request_id!r})"
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class ConversionResult(_ConversionResultBase[OutputFile]):
|
|
255
|
+
"""What a conversion returned."""
|
|
256
|
+
|
|
257
|
+
__slots__ = ()
|
|
258
|
+
|
|
259
|
+
def save_all(self, directory: str | os.PathLike[str]) -> list[Path]:
|
|
260
|
+
"""Writes every file into ``directory`` under its own name and returns the paths.
|
|
261
|
+
|
|
262
|
+
Creates the folder if needed, overwrites existing files, and downloads stored files.
|
|
263
|
+
"""
|
|
264
|
+
folder = Path(directory)
|
|
265
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
266
|
+
return [f.save(folder / safe_file_name(f.name)) for f in self._files]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class AsyncConversionResult(_ConversionResultBase[AsyncOutputFile]):
|
|
270
|
+
"""What a conversion returned, from :class:`AsyncPdfConversionApi`."""
|
|
271
|
+
|
|
272
|
+
__slots__ = ()
|
|
273
|
+
|
|
274
|
+
async def save_all(self, directory: str | os.PathLike[str]) -> list[Path]:
|
|
275
|
+
"""Writes every file into ``directory`` under its own name and returns the paths.
|
|
276
|
+
|
|
277
|
+
Creates the folder if needed, overwrites existing files, and downloads stored files.
|
|
278
|
+
"""
|
|
279
|
+
folder = Path(directory)
|
|
280
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
281
|
+
return [await f.save(folder / safe_file_name(f.name)) for f in self._files]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The multipart/form-data body, written by hand.
|
|
2
|
+
|
|
3
|
+
Stock encoders differ on file names: some write only ``filename*=``, percent-encode, or
|
|
4
|
+
MIME-encode non-ASCII names, and httpx doubles backslashes. The API reads only a plain
|
|
5
|
+
``filename="..."`` in raw UTF-8, so this module writes the parts itself: file names in raw
|
|
6
|
+
UTF-8 as UploadFile.name gives them (``"``, CR and LF already replaced by ``_``), and field
|
|
7
|
+
names with ``"``, CR and LF escaped as ``%22``, ``%0D`` and ``%0A`` so the header stays intact
|
|
8
|
+
(the API refuses such names with a 400).
|
|
9
|
+
|
|
10
|
+
The body is streamed with a known length, so a large file is never copied into memory, and a
|
|
11
|
+
file on disk is read again for each attempt.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import secrets
|
|
17
|
+
from collections.abc import AsyncIterator, Callable, Iterator, Sequence
|
|
18
|
+
from typing import Union
|
|
19
|
+
|
|
20
|
+
from ._inputs import UploadFile
|
|
21
|
+
|
|
22
|
+
__all__ = ["MultipartBody"]
|
|
23
|
+
|
|
24
|
+
FieldValue = Union[str, UploadFile]
|
|
25
|
+
|
|
26
|
+
_ESCAPES = str.maketrans({'"': "%22", "\r": "%0D", "\n": "%0A"})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _quote(value: str) -> str:
|
|
30
|
+
return value.translate(_ESCAPES)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class MultipartBody:
|
|
34
|
+
"""One attempt's request body. Build a new one for each attempt."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, fields: Sequence[tuple[str, FieldValue]]) -> None:
|
|
37
|
+
self.boundary = secrets.token_hex(16)
|
|
38
|
+
self.content_type = f"multipart/form-data; boundary={self.boundary}"
|
|
39
|
+
delimiter = f"--{self.boundary}\r\n".encode()
|
|
40
|
+
self._pieces: list[bytes | tuple[UploadFile, int]] = []
|
|
41
|
+
length = 0
|
|
42
|
+
for name, value in fields:
|
|
43
|
+
if isinstance(value, UploadFile):
|
|
44
|
+
head = (
|
|
45
|
+
f'Content-Disposition: form-data; name="{_quote(name)}"; '
|
|
46
|
+
f'filename="{value.name}"\r\n'
|
|
47
|
+
"Content-Type: application/octet-stream\r\n\r\n"
|
|
48
|
+
).encode()
|
|
49
|
+
size = value._content_size()
|
|
50
|
+
self._pieces += [delimiter + head, (value, size), b"\r\n"]
|
|
51
|
+
length += len(delimiter) + len(head) + size + 2
|
|
52
|
+
else:
|
|
53
|
+
part = (
|
|
54
|
+
delimiter
|
|
55
|
+
+ f'Content-Disposition: form-data; name="{_quote(name)}"\r\n\r\n'.encode()
|
|
56
|
+
+ value.encode()
|
|
57
|
+
+ b"\r\n"
|
|
58
|
+
)
|
|
59
|
+
self._pieces.append(part)
|
|
60
|
+
length += len(part)
|
|
61
|
+
closing = f"--{self.boundary}--\r\n".encode()
|
|
62
|
+
self._pieces.append(closing)
|
|
63
|
+
self.content_length = length + len(closing)
|
|
64
|
+
|
|
65
|
+
def chunks(self, check: Callable[[], None]) -> Iterator[bytes]:
|
|
66
|
+
"""The body's bytes. ``check`` runs before each chunk (it raises when time is up)."""
|
|
67
|
+
for piece in self._pieces:
|
|
68
|
+
check()
|
|
69
|
+
if isinstance(piece, bytes):
|
|
70
|
+
yield piece
|
|
71
|
+
else:
|
|
72
|
+
upload, size = piece
|
|
73
|
+
for chunk in upload._chunks(size):
|
|
74
|
+
check()
|
|
75
|
+
yield chunk
|
|
76
|
+
|
|
77
|
+
async def achunks(self, check: Callable[[], None]) -> AsyncIterator[bytes]:
|
|
78
|
+
"""The same bytes for an async client."""
|
|
79
|
+
for chunk in self.chunks(check):
|
|
80
|
+
yield chunk
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
File without changes
|