zebracat 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.
- zebracat/__init__.py +46 -0
- zebracat/_client.py +443 -0
- zebracat/_errors.py +152 -0
- zebracat/_generated/__init__.py +5 -0
- zebracat/_generated/meta.py +110 -0
- zebracat/_generated/operations.py +3481 -0
- zebracat/_generated/types.py +1179 -0
- zebracat/_types.py +57 -0
- zebracat/_version.py +1 -0
- zebracat/py.typed +0 -0
- zebracat-0.1.0.dist-info/METADATA +202 -0
- zebracat-0.1.0.dist-info/RECORD +14 -0
- zebracat-0.1.0.dist-info/WHEEL +4 -0
- zebracat-0.1.0.dist-info/licenses/LICENSE +21 -0
zebracat/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Zebracat: make videos with AI from Python. See https://api.zebracat.ai/docs."""
|
|
2
|
+
|
|
3
|
+
from ._client import DEFAULT_BASE_URL, Zebracat
|
|
4
|
+
from ._errors import (
|
|
5
|
+
APIConnectionError,
|
|
6
|
+
APIError,
|
|
7
|
+
APITimeoutError,
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
BadRequestError,
|
|
10
|
+
ConflictError,
|
|
11
|
+
InsufficientFundsError,
|
|
12
|
+
InternalServerError,
|
|
13
|
+
NotFoundError,
|
|
14
|
+
PermissionDeniedError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
VideoFailedError,
|
|
17
|
+
WaitTimeoutError,
|
|
18
|
+
ZebracatError,
|
|
19
|
+
)
|
|
20
|
+
from ._generated import types
|
|
21
|
+
from ._types import NOT_GIVEN, NotGiven, RequestOptions
|
|
22
|
+
from ._version import __version__
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"DEFAULT_BASE_URL",
|
|
26
|
+
"NOT_GIVEN",
|
|
27
|
+
"APIConnectionError",
|
|
28
|
+
"APIError",
|
|
29
|
+
"APITimeoutError",
|
|
30
|
+
"AuthenticationError",
|
|
31
|
+
"BadRequestError",
|
|
32
|
+
"ConflictError",
|
|
33
|
+
"InsufficientFundsError",
|
|
34
|
+
"InternalServerError",
|
|
35
|
+
"NotFoundError",
|
|
36
|
+
"NotGiven",
|
|
37
|
+
"PermissionDeniedError",
|
|
38
|
+
"RateLimitError",
|
|
39
|
+
"RequestOptions",
|
|
40
|
+
"VideoFailedError",
|
|
41
|
+
"WaitTimeoutError",
|
|
42
|
+
"Zebracat",
|
|
43
|
+
"ZebracatError",
|
|
44
|
+
"__version__",
|
|
45
|
+
"types",
|
|
46
|
+
]
|
zebracat/_client.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
"""The hand-written layer over the generated operations: auth, retries, idempotency keys, typed errors and
|
|
2
|
+
``wait_for_video``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import email.utils
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import random
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional, Tuple, Union, cast
|
|
14
|
+
from urllib.parse import quote, unquote, urlsplit
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from ._errors import (
|
|
19
|
+
APIConnectionError,
|
|
20
|
+
APITimeoutError,
|
|
21
|
+
AuthenticationError,
|
|
22
|
+
RateLimitError,
|
|
23
|
+
VideoFailedError,
|
|
24
|
+
WaitTimeoutError,
|
|
25
|
+
ZebracatError,
|
|
26
|
+
error_class,
|
|
27
|
+
message_of,
|
|
28
|
+
)
|
|
29
|
+
from ._generated.operations import GeneratedOperations
|
|
30
|
+
from ._types import NotGiven, Operation, RequestOptions
|
|
31
|
+
from ._version import __version__
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from ._generated.types import FileContent, TaskView, UploadLinkStored
|
|
35
|
+
|
|
36
|
+
DEFAULT_BASE_URL = "https://api.zebracat.ai"
|
|
37
|
+
TOKEN_PATH = "/api/oauth/token"
|
|
38
|
+
|
|
39
|
+
#: Statuses worth another attempt. A 429 is always retried (the API refused before doing any work); a 5xx only
|
|
40
|
+
#: when resending cannot do the work twice (see ``Zebracat._safe_to_resend``).
|
|
41
|
+
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
42
|
+
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
|
|
43
|
+
|
|
44
|
+
#: ``wait_for_video`` on an API that does not send ``poll_after_s`` yet: seconds per phase.
|
|
45
|
+
_FALLBACK_POLL_S = {"planning": 10.0, "generating": 30.0, "rendering": 15.0}
|
|
46
|
+
#: Phases where nothing changes until the caller acts (or ever): ``wait_for_video`` returns.
|
|
47
|
+
_STOP_PHASES = frozenset({"completed", "plan_ready", "needs_input"})
|
|
48
|
+
_FAILED_PHASES = frozenset({"failed", "cancelled"})
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Zebracat(GeneratedOperations):
|
|
52
|
+
"""Client for the Zebracat public API.
|
|
53
|
+
|
|
54
|
+
Authenticate with an API key (``X-API-KEY``, billed from the API balance) or an OAuth access token
|
|
55
|
+
(``Authorization: Bearer zoa_…``, billed from the account's plan credits)::
|
|
56
|
+
|
|
57
|
+
client = Zebracat() # reads ZEBRACAT_API_KEY
|
|
58
|
+
client = Zebracat(api_key="sk-…")
|
|
59
|
+
client = Zebracat(access_token="zoa_…", refresh_token="zor_…", client_id="…",
|
|
60
|
+
on_token_refresh=save_tokens) # refreshes once on a 401
|
|
61
|
+
|
|
62
|
+
Every API operation is a method named after its ``operationId`` (``create_video``, ``get_video``, …).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
api_key: Optional[str] = None,
|
|
68
|
+
*,
|
|
69
|
+
access_token: Optional[str] = None,
|
|
70
|
+
refresh_token: Optional[str] = None,
|
|
71
|
+
client_id: Optional[str] = None,
|
|
72
|
+
client_secret: Optional[str] = None,
|
|
73
|
+
on_token_refresh: Optional[Callable[[Dict[str, Any]], None]] = None,
|
|
74
|
+
base_url: Optional[str] = None,
|
|
75
|
+
timeout: float = 60.0,
|
|
76
|
+
max_retries: int = 3,
|
|
77
|
+
max_retry_wait: float = 60.0,
|
|
78
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
79
|
+
http_client: Optional[httpx.Client] = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
if api_key is None and access_token is None:
|
|
82
|
+
api_key = os.environ.get("ZEBRACAT_API_KEY") or None
|
|
83
|
+
if api_key and access_token:
|
|
84
|
+
raise ZebracatError("Pass either api_key or access_token, not both.")
|
|
85
|
+
if not api_key and not access_token:
|
|
86
|
+
raise ZebracatError(
|
|
87
|
+
"No credentials: pass api_key=… (or set ZEBRACAT_API_KEY), or access_token=… for OAuth."
|
|
88
|
+
)
|
|
89
|
+
if refresh_token and not client_id:
|
|
90
|
+
raise ZebracatError("refresh_token needs the OAuth client_id it was issued to.")
|
|
91
|
+
self.api_key = api_key
|
|
92
|
+
self.access_token = access_token
|
|
93
|
+
self.refresh_token = refresh_token
|
|
94
|
+
self.client_id = client_id
|
|
95
|
+
self.client_secret = client_secret
|
|
96
|
+
self.on_token_refresh = on_token_refresh
|
|
97
|
+
self.base_url = (base_url or os.environ.get("ZEBRACAT_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
98
|
+
self.timeout = timeout
|
|
99
|
+
self.max_retries = max_retries
|
|
100
|
+
#: A 429 or 5xx asking to wait longer than this (seconds) is raised instead of slept through.
|
|
101
|
+
self.max_retry_wait = max_retry_wait
|
|
102
|
+
self._default_headers = dict(default_headers or {})
|
|
103
|
+
self._http = http_client or httpx.Client(follow_redirects=False)
|
|
104
|
+
self._owns_http = http_client is None
|
|
105
|
+
self._refresh_lock = threading.Lock()
|
|
106
|
+
# Test seams: replaced by the test suite to skip real waiting.
|
|
107
|
+
self._sleep: Callable[[float], None] = time.sleep
|
|
108
|
+
self._clock: Callable[[], float] = time.monotonic
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------------ lifecycle
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
if self._owns_http:
|
|
114
|
+
self._http.close()
|
|
115
|
+
|
|
116
|
+
def __enter__(self) -> "Zebracat":
|
|
117
|
+
return self
|
|
118
|
+
|
|
119
|
+
def __exit__(self, *exc: Any) -> None:
|
|
120
|
+
self.close()
|
|
121
|
+
|
|
122
|
+
# ------------------------------------------------------------------ requests
|
|
123
|
+
|
|
124
|
+
def _auth_headers(self) -> Dict[str, str]:
|
|
125
|
+
if self.api_key:
|
|
126
|
+
return {"X-API-KEY": self.api_key}
|
|
127
|
+
return {"Authorization": f"Bearer {self.access_token}"}
|
|
128
|
+
|
|
129
|
+
@staticmethod
|
|
130
|
+
def _safe_to_resend(op: Operation) -> bool:
|
|
131
|
+
"""True when sending the request again cannot do its work twice."""
|
|
132
|
+
return op.method in _SAFE_METHODS or op.replays_idempotency_key
|
|
133
|
+
|
|
134
|
+
def _request(
|
|
135
|
+
self,
|
|
136
|
+
op: Operation,
|
|
137
|
+
*,
|
|
138
|
+
path: Dict[str, Any],
|
|
139
|
+
query: Dict[str, Any],
|
|
140
|
+
body: Any,
|
|
141
|
+
idempotency_key: Optional[str],
|
|
142
|
+
request_options: Optional[RequestOptions],
|
|
143
|
+
) -> Any:
|
|
144
|
+
opts: RequestOptions = request_options or {}
|
|
145
|
+
url = self.base_url + _fill_path(op.path, path)
|
|
146
|
+
params = {k: _query_value(v) for k, v in query.items() if not isinstance(v, NotGiven) and v is not None}
|
|
147
|
+
request_id = uuid.uuid4().hex
|
|
148
|
+
headers = {
|
|
149
|
+
"User-Agent": f"zebracat-python/{__version__}",
|
|
150
|
+
"Accept": "application/json",
|
|
151
|
+
"X-Request-ID": request_id,
|
|
152
|
+
**self._default_headers,
|
|
153
|
+
}
|
|
154
|
+
if op.paid:
|
|
155
|
+
headers["Idempotency-Key"] = idempotency_key or opts.get("idempotency_key") or f"zc-{uuid.uuid4().hex}"
|
|
156
|
+
headers.update(opts.get("headers") or {})
|
|
157
|
+
content = _encode_body(op, body)
|
|
158
|
+
headers.update(content.pop("headers", {}))
|
|
159
|
+
max_retries = opts.get("max_retries", self.max_retries)
|
|
160
|
+
timeout = opts.get("timeout", self.timeout)
|
|
161
|
+
|
|
162
|
+
attempt = 0
|
|
163
|
+
refreshed = False
|
|
164
|
+
while True:
|
|
165
|
+
sent_token = self.access_token
|
|
166
|
+
try:
|
|
167
|
+
response = self._http.request(
|
|
168
|
+
op.method,
|
|
169
|
+
url,
|
|
170
|
+
params=params,
|
|
171
|
+
headers={**headers, **(self._auth_headers() if op.auth else {})},
|
|
172
|
+
timeout=timeout,
|
|
173
|
+
**content,
|
|
174
|
+
)
|
|
175
|
+
except httpx.TimeoutException as exc:
|
|
176
|
+
if attempt < max_retries and self._safe_to_resend(op):
|
|
177
|
+
attempt += 1
|
|
178
|
+
self._sleep(_backoff(attempt))
|
|
179
|
+
continue
|
|
180
|
+
raise APITimeoutError(f"{op.method} {op.path} timed out: {exc}", request_id=request_id) from exc
|
|
181
|
+
except httpx.TransportError as exc:
|
|
182
|
+
never_sent = isinstance(exc, httpx.ConnectError)
|
|
183
|
+
if attempt < max_retries and (never_sent or self._safe_to_resend(op)):
|
|
184
|
+
attempt += 1
|
|
185
|
+
self._sleep(_backoff(attempt))
|
|
186
|
+
continue
|
|
187
|
+
raise APIConnectionError(f"{op.method} {op.path} failed: {exc}", request_id=request_id) from exc
|
|
188
|
+
|
|
189
|
+
if response.status_code == 401 and op.auth and self.refresh_token and not refreshed:
|
|
190
|
+
refreshed = True
|
|
191
|
+
self._refresh(sent_token)
|
|
192
|
+
continue
|
|
193
|
+
if response.status_code in RETRY_STATUSES and attempt < max_retries:
|
|
194
|
+
if response.status_code == 429 or self._safe_to_resend(op):
|
|
195
|
+
wait = self._retry_wait(response, attempt + 1)
|
|
196
|
+
if wait is not None:
|
|
197
|
+
attempt += 1
|
|
198
|
+
self._sleep(wait)
|
|
199
|
+
continue
|
|
200
|
+
return _parse(response, request_id)
|
|
201
|
+
|
|
202
|
+
def _retry_wait(self, response: httpx.Response, attempt: int) -> Optional[float]:
|
|
203
|
+
"""Seconds to wait before the next attempt, or None when the API asks for longer than ``max_retry_wait``."""
|
|
204
|
+
after = retry_after_seconds(response.headers.get("Retry-After"))
|
|
205
|
+
if after is None:
|
|
206
|
+
return _backoff(attempt)
|
|
207
|
+
return after if after <= self.max_retry_wait else None
|
|
208
|
+
|
|
209
|
+
def _refresh(self, sent_token: Optional[str]) -> None:
|
|
210
|
+
"""Swap the refresh token for a new pair (the API rotates both). Another thread may have done it already."""
|
|
211
|
+
with self._refresh_lock:
|
|
212
|
+
if self.access_token != sent_token:
|
|
213
|
+
return
|
|
214
|
+
form = {"grant_type": "refresh_token", "refresh_token": self.refresh_token, "client_id": self.client_id}
|
|
215
|
+
if self.client_secret:
|
|
216
|
+
form["client_secret"] = self.client_secret
|
|
217
|
+
try:
|
|
218
|
+
response = self._http.post(
|
|
219
|
+
self.base_url + TOKEN_PATH,
|
|
220
|
+
data=form,
|
|
221
|
+
headers={"User-Agent": f"zebracat-python/{__version__}", "Accept": "application/json"},
|
|
222
|
+
timeout=self.timeout,
|
|
223
|
+
)
|
|
224
|
+
except httpx.TransportError as exc:
|
|
225
|
+
raise APIConnectionError(f"OAuth token refresh failed: {exc}") from exc
|
|
226
|
+
body = _body_of(response)
|
|
227
|
+
if response.status_code != 200 or not isinstance(body, dict) or not body.get("access_token"):
|
|
228
|
+
raise AuthenticationError(
|
|
229
|
+
"The access token expired and the refresh token was refused: sign in again.",
|
|
230
|
+
status_code=response.status_code,
|
|
231
|
+
body=body,
|
|
232
|
+
headers=response.headers,
|
|
233
|
+
request_id=response.headers.get("X-Request-ID"),
|
|
234
|
+
)
|
|
235
|
+
self.access_token = body["access_token"]
|
|
236
|
+
self.refresh_token = body.get("refresh_token") or self.refresh_token
|
|
237
|
+
if self.on_token_refresh:
|
|
238
|
+
self.on_token_refresh(body)
|
|
239
|
+
|
|
240
|
+
# ------------------------------------------------------------------ helpers
|
|
241
|
+
|
|
242
|
+
def upload_with_link(
|
|
243
|
+
self,
|
|
244
|
+
file: Union[str, "os.PathLike[str]", "FileContent"],
|
|
245
|
+
*,
|
|
246
|
+
use: str = "picture",
|
|
247
|
+
filename: Optional[str] = None,
|
|
248
|
+
content_type: Optional[str] = None,
|
|
249
|
+
kind: Optional[str] = None,
|
|
250
|
+
name: Optional[str] = None,
|
|
251
|
+
) -> "UploadLinkStored":
|
|
252
|
+
"""Upload one file through a one-time upload link and return where it is stored.
|
|
253
|
+
|
|
254
|
+
``file`` is a local path, bytes, an open binary file or ``(filename, content[, content_type])``. ``use``
|
|
255
|
+
picks the accepted types and caps (``picture``, ``translate``, ``clone``, ``swap``, ``voice_clone``); send
|
|
256
|
+
the answer's ``url`` to the call ``use`` names (a ``translate`` video goes in ``translate_video(video_url=…)``,
|
|
257
|
+
a picture's ``upload`` in ``create_video(uploads=[…])``). Two calls: ``create_upload_link``, then the file
|
|
258
|
+
goes to the link's ``upload_url`` without credentials (``upload_to_link``).
|
|
259
|
+
"""
|
|
260
|
+
if isinstance(file, (str, os.PathLike)):
|
|
261
|
+
path = os.fspath(file)
|
|
262
|
+
with open(path, "rb") as handle:
|
|
263
|
+
data = handle.read()
|
|
264
|
+
part: Optional[Tuple[str, bytes, str]] = (
|
|
265
|
+
os.path.basename(path), data, content_type or "application/octet-stream"
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
part = _file_part(file)
|
|
269
|
+
if part is None:
|
|
270
|
+
raise ZebracatError("file must be a path, bytes, an open binary file or (filename, content).")
|
|
271
|
+
filename = filename or (part[0] if part[0] != "upload" else None)
|
|
272
|
+
fields: Dict[str, Any] = {"use": use, "filename": filename, "content_type": content_type, "kind": kind, "name": name}
|
|
273
|
+
link = self.create_upload_link(**{k: v for k, v in fields.items() if v is not None})
|
|
274
|
+
upload_url = cast(Dict[str, Any], link)["upload_url"]
|
|
275
|
+
marker = "/uploads/link/"
|
|
276
|
+
link_path = urlsplit(upload_url).path
|
|
277
|
+
if marker not in link_path:
|
|
278
|
+
raise ZebracatError(f"Unexpected upload_url: {upload_url}")
|
|
279
|
+
token = unquote(link_path.split(marker, 1)[1])
|
|
280
|
+
return self.upload_to_link(token, body=part)
|
|
281
|
+
|
|
282
|
+
def wait_for_video(
|
|
283
|
+
self,
|
|
284
|
+
task_id: str,
|
|
285
|
+
*,
|
|
286
|
+
timeout: float = 1800.0,
|
|
287
|
+
poll_interval: Optional[float] = None,
|
|
288
|
+
on_update: Optional[Callable[["TaskView"], None]] = None,
|
|
289
|
+
) -> "TaskView":
|
|
290
|
+
"""Read ``get_video`` until the video stops changing on its own, waiting ``poll_after_s`` between reads.
|
|
291
|
+
|
|
292
|
+
Returns the video when its phase is ``completed`` (``video_url`` is the file), ``plan_ready`` (a plan made
|
|
293
|
+
with ``auto_generate=False``: show the ``quote``, call ``generate_video``, then wait again) or
|
|
294
|
+
``needs_input`` (answer ``question`` with ``answer_video_question``). Raises :class:`VideoFailedError` when
|
|
295
|
+
it ends ``failed`` or ``cancelled``, and :class:`WaitTimeoutError` after ``timeout`` seconds (the video
|
|
296
|
+
keeps going; wait again later). ``poll_interval`` overrides the API's ``poll_after_s``.
|
|
297
|
+
"""
|
|
298
|
+
deadline = self._clock() + timeout
|
|
299
|
+
while True:
|
|
300
|
+
answer = self.get_video(task_id)
|
|
301
|
+
if on_update:
|
|
302
|
+
on_update(answer)
|
|
303
|
+
video: Dict[str, Any] = cast(Dict[str, Any], answer)
|
|
304
|
+
phase = video.get("phase")
|
|
305
|
+
if phase in _FAILED_PHASES:
|
|
306
|
+
reason = video.get("error")
|
|
307
|
+
if isinstance(reason, dict):
|
|
308
|
+
reason = reason.get("message") or reason.get("code")
|
|
309
|
+
raise VideoFailedError(f"Video {task_id} {phase}" + (f": {reason}" if reason else ""), video=video)
|
|
310
|
+
if "poll_after_s" in video:
|
|
311
|
+
wait = video["poll_after_s"]
|
|
312
|
+
if wait is None:
|
|
313
|
+
return answer
|
|
314
|
+
elif phase in _STOP_PHASES:
|
|
315
|
+
return answer
|
|
316
|
+
else:
|
|
317
|
+
wait = _FALLBACK_POLL_S.get(str(phase), 15.0)
|
|
318
|
+
if poll_interval is not None:
|
|
319
|
+
wait = poll_interval
|
|
320
|
+
remaining = deadline - self._clock()
|
|
321
|
+
if remaining <= 0:
|
|
322
|
+
raise WaitTimeoutError(f"Video {task_id} is still {phase} after {timeout:g} s.", video=video)
|
|
323
|
+
self._sleep(max(1.0, min(float(wait), remaining)))
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ---------------------------------------------------------------------- module helpers
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _fill_path(template: str, values: Dict[str, Any]) -> str:
|
|
330
|
+
for name, value in values.items():
|
|
331
|
+
text = str(value)
|
|
332
|
+
# "", "." and ".." would resolve to another endpoint once the URL is normalized: refuse them.
|
|
333
|
+
if text in ("", ".", ".."):
|
|
334
|
+
raise ZebracatError(f"Invalid {name}: {text!r}")
|
|
335
|
+
template = template.replace("{" + name + "}", quote(text, safe=""))
|
|
336
|
+
return template
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _query_value(value: Any) -> Any:
|
|
340
|
+
if isinstance(value, bool):
|
|
341
|
+
return "true" if value else "false"
|
|
342
|
+
return value
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _strip_not_given(body: Any) -> Any:
|
|
346
|
+
if isinstance(body, dict):
|
|
347
|
+
return {k: v for k, v in body.items() if not isinstance(v, NotGiven)}
|
|
348
|
+
return body
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _file_part(value: Any) -> Optional[Tuple[str, bytes, str]]:
|
|
352
|
+
"""``(filename, bytes, content_type)`` for a file value, read once so retries can resend it; None otherwise."""
|
|
353
|
+
if isinstance(value, (bytes, bytearray)):
|
|
354
|
+
return ("upload", bytes(value), "application/octet-stream")
|
|
355
|
+
if isinstance(value, tuple) and len(value) in (2, 3):
|
|
356
|
+
name, data = value[0], value[1]
|
|
357
|
+
reader = getattr(data, "read", None)
|
|
358
|
+
if reader is not None:
|
|
359
|
+
data = reader()
|
|
360
|
+
kind = value[2] if len(value) == 3 else "application/octet-stream"
|
|
361
|
+
return (str(name), bytes(data), kind)
|
|
362
|
+
if hasattr(value, "read"):
|
|
363
|
+
name = os.path.basename(getattr(value, "name", "") or "upload")
|
|
364
|
+
return (name, value.read(), "application/octet-stream")
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _encode_body(op: Operation, body: Any) -> Dict[str, Any]:
|
|
369
|
+
body = _strip_not_given(body)
|
|
370
|
+
if body is None or isinstance(body, NotGiven):
|
|
371
|
+
return {}
|
|
372
|
+
if op.body == "binary":
|
|
373
|
+
part = _file_part(body)
|
|
374
|
+
if part is None:
|
|
375
|
+
raise ZebracatError("body must be bytes, an open binary file or (filename, content[, content_type]).")
|
|
376
|
+
return {"content": part[1], "headers": {"Content-Type": part[2]}}
|
|
377
|
+
if op.body != "multipart":
|
|
378
|
+
return {"json": body}
|
|
379
|
+
files: Dict[str, Tuple[str, bytes, str]] = {}
|
|
380
|
+
data: Dict[str, Any] = {}
|
|
381
|
+
for key, value in body.items():
|
|
382
|
+
if value is None:
|
|
383
|
+
continue
|
|
384
|
+
part = _file_part(value)
|
|
385
|
+
if part is not None:
|
|
386
|
+
files[key] = part
|
|
387
|
+
elif isinstance(value, (dict, list)):
|
|
388
|
+
data[key] = json.dumps(value)
|
|
389
|
+
elif isinstance(value, bool):
|
|
390
|
+
data[key] = "true" if value else "false"
|
|
391
|
+
else:
|
|
392
|
+
data[key] = str(value)
|
|
393
|
+
return {"data": data, "files": files or None}
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _body_of(response: httpx.Response) -> Any:
|
|
397
|
+
if not response.content:
|
|
398
|
+
return None
|
|
399
|
+
try:
|
|
400
|
+
return response.json()
|
|
401
|
+
except ValueError:
|
|
402
|
+
return response.text
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _parse(response: httpx.Response, request_id: str) -> Any:
|
|
406
|
+
status = response.status_code
|
|
407
|
+
if status >= 400:
|
|
408
|
+
body = _body_of(response)
|
|
409
|
+
rid = (body.get("request_id") if isinstance(body, dict) else None) or response.headers.get("X-Request-ID")
|
|
410
|
+
cls = error_class(status)
|
|
411
|
+
kwargs: Dict[str, Any] = dict(
|
|
412
|
+
status_code=status, body=body, headers=response.headers, request_id=rid or request_id
|
|
413
|
+
)
|
|
414
|
+
if cls is RateLimitError:
|
|
415
|
+
kwargs["retry_after"] = retry_after_seconds(response.headers.get("Retry-After"))
|
|
416
|
+
raise cls(message_of(body, status), **kwargs)
|
|
417
|
+
if 300 <= status < 400:
|
|
418
|
+
return response.headers.get("Location")
|
|
419
|
+
return _body_of(response)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def retry_after_seconds(value: Optional[str]) -> Optional[float]:
|
|
423
|
+
"""``Retry-After`` as seconds: a number, or an HTTP date."""
|
|
424
|
+
if not value:
|
|
425
|
+
return None
|
|
426
|
+
value = value.strip()
|
|
427
|
+
try:
|
|
428
|
+
return max(0.0, float(value))
|
|
429
|
+
except ValueError:
|
|
430
|
+
pass
|
|
431
|
+
try:
|
|
432
|
+
when = email.utils.parsedate_to_datetime(value)
|
|
433
|
+
except (TypeError, ValueError):
|
|
434
|
+
return None
|
|
435
|
+
if when is None:
|
|
436
|
+
return None
|
|
437
|
+
return max(0.0, when.timestamp() - time.time())
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _backoff(attempt: int) -> float:
|
|
441
|
+
"""0.5 s, 1 s, 2 s, … capped at 8 s, minus up to 25 % jitter."""
|
|
442
|
+
base = min(8.0, 0.5 * (2 ** (attempt - 1)))
|
|
443
|
+
return base * (1 - 0.25 * random.random())
|
zebracat/_errors.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Typed errors. Every error that came from the API carries the ``request_id`` to quote to support."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ZebracatError(Exception):
|
|
9
|
+
"""Base class of every error this package raises."""
|
|
10
|
+
|
|
11
|
+
request_id: Optional[str] = None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class APIConnectionError(ZebracatError):
|
|
15
|
+
"""The request never got an HTTP answer (DNS, refused connection, reset, timeout)."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, message: str, *, request_id: Optional[str] = None) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.request_id = request_id
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class APITimeoutError(APIConnectionError):
|
|
23
|
+
"""The HTTP attempt timed out."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class APIError(ZebracatError):
|
|
27
|
+
"""The API answered with an error status. The fields mirror the public error envelope."""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
message: str,
|
|
32
|
+
*,
|
|
33
|
+
status_code: int,
|
|
34
|
+
body: Any = None,
|
|
35
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
36
|
+
request_id: Optional[str] = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
self.status_code = status_code
|
|
40
|
+
self.body = body
|
|
41
|
+
self.headers: Dict[str, str] = dict(headers or {})
|
|
42
|
+
self.request_id = request_id
|
|
43
|
+
data = body if isinstance(body, dict) else {}
|
|
44
|
+
#: Machine-readable slug, e.g. ``insufficient_balance`` or ``invalid_choice``.
|
|
45
|
+
self.code: Optional[str] = data.get("code")
|
|
46
|
+
#: Error class: ``invalid_request``, ``authentication``, ``insufficient_funds``, ``rate_limited``, …
|
|
47
|
+
self.type: Optional[str] = data.get("type")
|
|
48
|
+
self.field: Optional[str] = data.get("field")
|
|
49
|
+
self.hint: Optional[str] = data.get("hint")
|
|
50
|
+
self.docs_url: Optional[str] = data.get("docs_url")
|
|
51
|
+
self.retryable: Optional[bool] = data.get("retryable")
|
|
52
|
+
self.allowed_values: Optional[List[Any]] = data.get("allowed_values")
|
|
53
|
+
self.errors: List[Dict[str, Any]] = list(data.get("errors") or [])
|
|
54
|
+
#: Where to add credit (402) or upgrade the plan (403), when the API names one.
|
|
55
|
+
self.topup_url: Optional[str] = data.get("topup_url")
|
|
56
|
+
self.upgrade_url: Optional[str] = data.get("upgrade_url")
|
|
57
|
+
|
|
58
|
+
def __str__(self) -> str:
|
|
59
|
+
text = f"{self.status_code} {super().__str__()}"
|
|
60
|
+
if self.hint:
|
|
61
|
+
text += f" (hint: {self.hint})"
|
|
62
|
+
if self.request_id:
|
|
63
|
+
text += f" [request_id={self.request_id}]"
|
|
64
|
+
return text
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class BadRequestError(APIError):
|
|
68
|
+
"""400 or 422: the request is invalid. ``field``, ``allowed_values`` and ``errors`` say what to fix."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AuthenticationError(APIError):
|
|
72
|
+
"""401: the API key or access token is missing, wrong, revoked or expired."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class InsufficientFundsError(APIError):
|
|
76
|
+
"""402: not enough balance or credits. ``topup_url`` is where to add more."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class PermissionDeniedError(APIError):
|
|
80
|
+
"""403: the plan, the token scope or the account does not allow this. ``upgrade_url`` when a plan would."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class NotFoundError(APIError):
|
|
84
|
+
"""404 or 410: no such object of yours."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ConflictError(APIError):
|
|
88
|
+
"""409: the object is not in a state that allows this yet (e.g. downloading a video still being made)."""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class RateLimitError(APIError):
|
|
92
|
+
"""429: too many requests, or a daily cap. ``retry_after`` is the wait in seconds the API asked for."""
|
|
93
|
+
|
|
94
|
+
def __init__(self, *args: Any, retry_after: Optional[float] = None, **kwargs: Any) -> None:
|
|
95
|
+
super().__init__(*args, **kwargs)
|
|
96
|
+
self.retry_after = retry_after
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class InternalServerError(APIError):
|
|
100
|
+
"""5xx: the API failed or is unavailable. Safe calls were already retried."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class VideoFailedError(ZebracatError):
|
|
104
|
+
"""``wait_for_video``: the video ended ``failed`` or ``cancelled``. ``video`` is the last answer."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, message: str, *, video: Mapping[str, Any]) -> None:
|
|
107
|
+
super().__init__(message)
|
|
108
|
+
self.video = video
|
|
109
|
+
self.phase = video.get("phase")
|
|
110
|
+
self.error = video.get("error")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class WaitTimeoutError(ZebracatError):
|
|
114
|
+
"""``wait_for_video``: the timeout passed first. ``video`` is the last answer; the job keeps running."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, message: str, *, video: Optional[Mapping[str, Any]]) -> None:
|
|
117
|
+
super().__init__(message)
|
|
118
|
+
self.video = video
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
_BY_STATUS = {
|
|
122
|
+
400: BadRequestError,
|
|
123
|
+
401: AuthenticationError,
|
|
124
|
+
402: InsufficientFundsError,
|
|
125
|
+
403: PermissionDeniedError,
|
|
126
|
+
404: NotFoundError,
|
|
127
|
+
409: ConflictError,
|
|
128
|
+
410: NotFoundError,
|
|
129
|
+
422: BadRequestError,
|
|
130
|
+
429: RateLimitError,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def error_class(status_code: int) -> type:
|
|
135
|
+
if status_code in _BY_STATUS:
|
|
136
|
+
return _BY_STATUS[status_code]
|
|
137
|
+
if status_code >= 500:
|
|
138
|
+
return InternalServerError
|
|
139
|
+
return BadRequestError if status_code >= 400 else APIError
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def message_of(body: Any, status_code: int) -> str:
|
|
143
|
+
if isinstance(body, dict):
|
|
144
|
+
for key in ("error", "detail", "message", "error_description"):
|
|
145
|
+
value = body.get(key)
|
|
146
|
+
if isinstance(value, str) and value:
|
|
147
|
+
return value
|
|
148
|
+
if isinstance(value, dict) and isinstance(value.get("error"), str):
|
|
149
|
+
return value["error"]
|
|
150
|
+
if isinstance(body, str) and body.strip():
|
|
151
|
+
return body.strip()[:500]
|
|
152
|
+
return f"HTTP {status_code}"
|