ewest 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.
- ewest/__init__.py +31 -0
- ewest/_client.py +373 -0
- ewest/_errors.py +171 -0
- ewest/_schema.py +46 -0
- ewest/_sse.py +61 -0
- ewest/_types.py +105 -0
- ewest/_webhooks.py +84 -0
- ewest/py.typed +0 -0
- ewest-0.1.0.dist-info/METADATA +129 -0
- ewest-0.1.0.dist-info/RECORD +13 -0
- ewest-0.1.0.dist-info/WHEEL +5 -0
- ewest-0.1.0.dist-info/licenses/LICENSE +21 -0
- ewest-0.1.0.dist-info/top_level.txt +1 -0
ewest/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""eWest helpers for async jobs (video, music, sound): submit, wait, stream, verify webhooks.
|
|
2
|
+
|
|
3
|
+
For chat, embeddings and images use the OpenAI or Anthropic SDK with base URL https://api.ewest.ai/v1.
|
|
4
|
+
"""
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
from ._client import Audio, Ewest, Jobs, ThreeD, Videos
|
|
8
|
+
from ._errors import (
|
|
9
|
+
APIConnectionError,
|
|
10
|
+
APIError,
|
|
11
|
+
AuthError,
|
|
12
|
+
BadRequestError,
|
|
13
|
+
EwestError,
|
|
14
|
+
InsufficientBudgetError,
|
|
15
|
+
JobFailedError,
|
|
16
|
+
JobTimeoutError,
|
|
17
|
+
NotFoundError,
|
|
18
|
+
PermissionDeniedError,
|
|
19
|
+
RateLimitError,
|
|
20
|
+
ServerError,
|
|
21
|
+
WebhookVerificationError,
|
|
22
|
+
)
|
|
23
|
+
from ._types import Job, JobError, JobOutput
|
|
24
|
+
from ._webhooks import verify_webhook
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"APIConnectionError", "APIError", "AuthError", "Audio", "BadRequestError", "Ewest", "EwestError", "ThreeD",
|
|
28
|
+
"InsufficientBudgetError", "Job", "JobError", "JobFailedError", "JobOutput", "JobTimeoutError",
|
|
29
|
+
"Jobs", "NotFoundError", "PermissionDeniedError", "RateLimitError", "ServerError", "Videos",
|
|
30
|
+
"WebhookVerificationError", "verify_webhook", "__version__",
|
|
31
|
+
]
|
ewest/_client.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""The client: HTTP with retries, and the video, audio and jobs resources. Standard library only."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import codecs
|
|
5
|
+
import http.client
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import random
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Tuple, Union
|
|
11
|
+
from urllib.parse import quote, urlencode, urlsplit
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from ._errors import (
|
|
15
|
+
parse_retry_after,
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
APIError,
|
|
18
|
+
AuthError,
|
|
19
|
+
EwestError,
|
|
20
|
+
JobFailedError,
|
|
21
|
+
JobTimeoutError,
|
|
22
|
+
RateLimitError,
|
|
23
|
+
error_from_response,
|
|
24
|
+
)
|
|
25
|
+
from ._schema import DEFAULT_BASE_URL, PATHS
|
|
26
|
+
from ._sse import SSEParser
|
|
27
|
+
from ._types import Job
|
|
28
|
+
|
|
29
|
+
JobRef = Union[str, Job]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _job_id(job: JobRef) -> str:
|
|
33
|
+
return job if isinstance(job, str) else job.id
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _clean(params: Mapping[str, Any]) -> Dict[str, Any]:
|
|
37
|
+
return {k: v for k, v in params.items() if v is not None}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Ewest:
|
|
41
|
+
"""eWest client.
|
|
42
|
+
|
|
43
|
+
``api_key`` defaults to the ``EWEST_KEY`` environment variable and ``base_url`` to
|
|
44
|
+
https://api.ewest.ai. 429 answers are retried with backoff (honouring ``Retry-After``) for
|
|
45
|
+
every call; 5xx answers and connection errors only for reads (GET), because a failed POST
|
|
46
|
+
may already have started a paid job. 402 and other 4xx are never retried.
|
|
47
|
+
|
|
48
|
+
``timeout`` (default 60 s) applies to each socket operation (connect, send, one read), not to a
|
|
49
|
+
whole call. ``jobs.wait`` has its own total ``timeout``; ``jobs.stream`` ends when the job does
|
|
50
|
+
(stop earlier by closing the generator), and treats 45 s without any data as a dead connection.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
api_key: Optional[str] = None,
|
|
56
|
+
*,
|
|
57
|
+
base_url: Optional[str] = None,
|
|
58
|
+
max_retries: int = 2,
|
|
59
|
+
timeout: float = 60.0,
|
|
60
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
61
|
+
) -> None:
|
|
62
|
+
key = api_key or os.environ.get("EWEST_KEY")
|
|
63
|
+
if not key:
|
|
64
|
+
raise AuthError("No API key: pass api_key=... or set the EWEST_KEY environment variable.", status=401)
|
|
65
|
+
self._api_key = key
|
|
66
|
+
url = (base_url or os.environ.get("EWEST_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
67
|
+
if url.endswith("/v1"): # OpenAI-style base URLs work too
|
|
68
|
+
url = url[:-3]
|
|
69
|
+
self.base_url = url
|
|
70
|
+
self.max_retries = max_retries
|
|
71
|
+
self.timeout = timeout
|
|
72
|
+
self._sleep = sleep
|
|
73
|
+
self.videos = Videos(self)
|
|
74
|
+
self.audio = Audio(self)
|
|
75
|
+
self.three_d = ThreeD(self)
|
|
76
|
+
self.jobs = Jobs(self)
|
|
77
|
+
|
|
78
|
+
def __repr__(self) -> str:
|
|
79
|
+
return f"Ewest(base_url={self.base_url!r}, api_key='***')"
|
|
80
|
+
|
|
81
|
+
# ---- HTTP ----
|
|
82
|
+
|
|
83
|
+
def _connect(self, timeout: float) -> Tuple[http.client.HTTPConnection, str]:
|
|
84
|
+
parts = urlsplit(self.base_url)
|
|
85
|
+
cls = http.client.HTTPSConnection if parts.scheme == "https" else http.client.HTTPConnection
|
|
86
|
+
return cls(parts.hostname or "", parts.port, timeout=timeout), parts.path.rstrip("/")
|
|
87
|
+
|
|
88
|
+
def _headers(self, extra: Optional[Mapping[str, str]] = None) -> Dict[str, str]:
|
|
89
|
+
h = {
|
|
90
|
+
"authorization": f"Bearer {self._api_key}",
|
|
91
|
+
"user-agent": f"ewest-python/{__version__}",
|
|
92
|
+
"accept": "application/json",
|
|
93
|
+
}
|
|
94
|
+
h.update(extra or {})
|
|
95
|
+
return h
|
|
96
|
+
|
|
97
|
+
def _delay(self, attempt: int, err: Optional[APIError]) -> float:
|
|
98
|
+
if isinstance(err, RateLimitError) and err.retry_after is not None:
|
|
99
|
+
return min(err.retry_after, 60.0)
|
|
100
|
+
if err is not None and err.code == "idempotency_key_in_use":
|
|
101
|
+
wait = parse_retry_after(err.headers.get("retry-after"))
|
|
102
|
+
if wait is not None:
|
|
103
|
+
return min(wait, 60.0)
|
|
104
|
+
return min(0.5 * (2 ** attempt), 8.0) * (0.75 + random.random() / 2)
|
|
105
|
+
|
|
106
|
+
def request(
|
|
107
|
+
self,
|
|
108
|
+
method: str,
|
|
109
|
+
path: str,
|
|
110
|
+
json_body: Any = None,
|
|
111
|
+
*,
|
|
112
|
+
params: Optional[Mapping[str, Any]] = None,
|
|
113
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
114
|
+
safe_to_retry: bool = False,
|
|
115
|
+
) -> Any:
|
|
116
|
+
"""Send one request and return the parsed JSON. Low-level escape hatch for endpoints without a helper.
|
|
117
|
+
|
|
118
|
+
Raises a typed ``APIError`` subclass on an error status.
|
|
119
|
+
"""
|
|
120
|
+
target = path if path.startswith("/") else f"/{path}"
|
|
121
|
+
if params:
|
|
122
|
+
target += "?" + urlencode(_clean(params))
|
|
123
|
+
body = None if json_body is None else json.dumps(json_body).encode("utf-8")
|
|
124
|
+
send_headers = self._headers({**({"content-type": "application/json"} if body is not None else {}), **(headers or {})})
|
|
125
|
+
# A POST is retried like a read only when repeating it is safe (it carries an Idempotency-Key).
|
|
126
|
+
read_only = method.upper() == "GET" or safe_to_retry
|
|
127
|
+
attempt = 0
|
|
128
|
+
while True:
|
|
129
|
+
err: Optional[APIError] = None
|
|
130
|
+
try:
|
|
131
|
+
conn, prefix = self._connect(self.timeout)
|
|
132
|
+
try:
|
|
133
|
+
conn.request(method, prefix + target, body=body, headers=send_headers)
|
|
134
|
+
resp = conn.getresponse()
|
|
135
|
+
status, rheaders, raw = resp.status, dict(resp.getheaders()), resp.read()
|
|
136
|
+
finally:
|
|
137
|
+
conn.close()
|
|
138
|
+
except (OSError, http.client.HTTPException) as e:
|
|
139
|
+
if read_only and attempt < self.max_retries:
|
|
140
|
+
self._sleep(self._delay(attempt, None))
|
|
141
|
+
attempt += 1
|
|
142
|
+
continue
|
|
143
|
+
raise APIConnectionError(f"Could not reach {self.base_url}: {e}") from e
|
|
144
|
+
if status < 400:
|
|
145
|
+
if not raw:
|
|
146
|
+
return None
|
|
147
|
+
try:
|
|
148
|
+
return json.loads(raw.decode("utf-8"))
|
|
149
|
+
except ValueError as e:
|
|
150
|
+
raise EwestError(f"The API answered {status} with a body that is not JSON.") from e
|
|
151
|
+
err = error_from_response(status, rheaders, raw)
|
|
152
|
+
# 409 idempotency_key_in_use: the first request with this key is still running; retry like a 429 (the key makes that safe).
|
|
153
|
+
key_in_use = safe_to_retry and status == 409 and err.code == "idempotency_key_in_use"
|
|
154
|
+
retryable = status == 429 or key_in_use or (status >= 500 and read_only)
|
|
155
|
+
if retryable and attempt < self.max_retries:
|
|
156
|
+
self._sleep(self._delay(attempt, err))
|
|
157
|
+
attempt += 1
|
|
158
|
+
continue
|
|
159
|
+
raise err
|
|
160
|
+
|
|
161
|
+
def _events(self, path: str, timeout: float) -> Iterator[Tuple[str, str]]:
|
|
162
|
+
"""Yield ``(event, data)`` pairs of a Server-Sent Events stream until the server closes it."""
|
|
163
|
+
try:
|
|
164
|
+
conn, prefix = self._connect(timeout)
|
|
165
|
+
conn.request("GET", prefix + path, headers=self._headers({"accept": "text/event-stream"}))
|
|
166
|
+
resp = conn.getresponse()
|
|
167
|
+
except (OSError, http.client.HTTPException) as e:
|
|
168
|
+
raise APIConnectionError(f"Could not reach {self.base_url}: {e}") from e
|
|
169
|
+
try:
|
|
170
|
+
if resp.status != 200:
|
|
171
|
+
raise error_from_response(resp.status, dict(resp.getheaders()), resp.read())
|
|
172
|
+
parser = SSEParser()
|
|
173
|
+
decoder = codecs.getincrementaldecoder("utf-8")("replace")
|
|
174
|
+
while True:
|
|
175
|
+
try:
|
|
176
|
+
chunk = resp.read1(8192)
|
|
177
|
+
except (OSError, http.client.HTTPException) as e:
|
|
178
|
+
raise APIConnectionError(f"The event stream broke: {e}") from e
|
|
179
|
+
if not chunk:
|
|
180
|
+
return
|
|
181
|
+
for ev in parser.feed(decoder.decode(chunk)):
|
|
182
|
+
yield ev.event, ev.data
|
|
183
|
+
finally:
|
|
184
|
+
conn.close()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class _Generator:
|
|
188
|
+
_path = ""
|
|
189
|
+
|
|
190
|
+
def __init__(self, client: Ewest) -> None:
|
|
191
|
+
self._client = client
|
|
192
|
+
|
|
193
|
+
def _create(self, body: Dict[str, Any], idempotency_key: Optional[str] = None) -> Job:
|
|
194
|
+
# With an Idempotency-Key a repeated POST returns the same job, so lost responses and 5xx answers can be retried.
|
|
195
|
+
headers = {"idempotency-key": idempotency_key} if idempotency_key else None
|
|
196
|
+
return Job.from_dict(self._client.request("POST", self._path, _clean(body), headers=headers, safe_to_retry=bool(idempotency_key)))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class Videos(_Generator):
|
|
200
|
+
_path = PATHS["create_video"]
|
|
201
|
+
|
|
202
|
+
def generate(
|
|
203
|
+
self,
|
|
204
|
+
model: str,
|
|
205
|
+
prompt: str,
|
|
206
|
+
*,
|
|
207
|
+
duration: Optional[int] = None,
|
|
208
|
+
resolution: Optional[str] = None,
|
|
209
|
+
aspect_ratio: Optional[str] = None,
|
|
210
|
+
audio: Optional[bool] = None,
|
|
211
|
+
image_url: Optional[str] = None,
|
|
212
|
+
end_image_url: Optional[str] = None,
|
|
213
|
+
webhook_url: Optional[str] = None,
|
|
214
|
+
idempotency_key: Optional[str] = None,
|
|
215
|
+
start_timeout: Optional[int] = None,
|
|
216
|
+
**extra: Any,
|
|
217
|
+
) -> Job:
|
|
218
|
+
"""Start a video job (``POST /v1/videos/generations``). Returns the queued job at once."""
|
|
219
|
+
return self._create(
|
|
220
|
+
dict(model=model, prompt=prompt, duration=duration, resolution=resolution, aspect_ratio=aspect_ratio,
|
|
221
|
+
audio=audio, image_url=image_url, end_image_url=end_image_url, webhook_url=webhook_url,
|
|
222
|
+
start_timeout=start_timeout, **extra),
|
|
223
|
+
idempotency_key,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
def generate_and_wait(self, model: str, prompt: str, *, timeout: float = 1200.0, poll_interval: float = 3.0, **kwargs: Any) -> Job:
|
|
227
|
+
"""``generate`` then ``jobs.wait``. Raises ``JobFailedError`` if the job fails."""
|
|
228
|
+
return self._client.jobs.wait(self.generate(model, prompt, **kwargs), timeout=timeout, poll_interval=poll_interval)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class Audio(_Generator):
|
|
232
|
+
_path = PATHS["create_audio"]
|
|
233
|
+
|
|
234
|
+
def generate(
|
|
235
|
+
self,
|
|
236
|
+
model: str,
|
|
237
|
+
prompt: str,
|
|
238
|
+
*,
|
|
239
|
+
duration: Optional[int] = None,
|
|
240
|
+
instrumental: Optional[bool] = None,
|
|
241
|
+
loop: Optional[bool] = None,
|
|
242
|
+
lyrics: Optional[str] = None,
|
|
243
|
+
webhook_url: Optional[str] = None,
|
|
244
|
+
idempotency_key: Optional[str] = None,
|
|
245
|
+
start_timeout: Optional[int] = None,
|
|
246
|
+
**extra: Any,
|
|
247
|
+
) -> Job:
|
|
248
|
+
"""Start a music or sound-effect job (``POST /v1/audio/generations``)."""
|
|
249
|
+
return self._create(
|
|
250
|
+
dict(model=model, prompt=prompt, duration=duration, instrumental=instrumental, loop=loop,
|
|
251
|
+
lyrics=lyrics, webhook_url=webhook_url, start_timeout=start_timeout, **extra),
|
|
252
|
+
idempotency_key,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
def generate_and_wait(self, model: str, prompt: str, *, timeout: float = 600.0, poll_interval: float = 3.0, **kwargs: Any) -> Job:
|
|
256
|
+
return self._client.jobs.wait(self.generate(model, prompt, **kwargs), timeout=timeout, poll_interval=poll_interval)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class ThreeD(_Generator):
|
|
260
|
+
_path = PATHS["create_3d"]
|
|
261
|
+
|
|
262
|
+
def generate(
|
|
263
|
+
self,
|
|
264
|
+
model: str,
|
|
265
|
+
*,
|
|
266
|
+
prompt: Optional[str] = None,
|
|
267
|
+
image_url: Optional[str] = None,
|
|
268
|
+
view_images: Optional[Dict[str, str]] = None,
|
|
269
|
+
generate_type: Optional[str] = None,
|
|
270
|
+
enable_pbr: Optional[bool] = None,
|
|
271
|
+
face_count: Optional[int] = None,
|
|
272
|
+
texture_quality: Optional[str] = None,
|
|
273
|
+
geometry_quality: Optional[str] = None,
|
|
274
|
+
quad: Optional[bool] = None,
|
|
275
|
+
negative_prompt: Optional[str] = None,
|
|
276
|
+
seed: Optional[int] = None,
|
|
277
|
+
auto_size: Optional[bool] = None,
|
|
278
|
+
orientation: Optional[str] = None,
|
|
279
|
+
texture_alignment: Optional[str] = None,
|
|
280
|
+
webhook_url: Optional[str] = None,
|
|
281
|
+
idempotency_key: Optional[str] = None,
|
|
282
|
+
start_timeout: Optional[int] = None,
|
|
283
|
+
**extra: Any,
|
|
284
|
+
) -> Job:
|
|
285
|
+
"""Start a 3D job (``POST /v1/3d/generations``): ``prompt`` or ``image_url``. Returns the queued job at once."""
|
|
286
|
+
return self._create(
|
|
287
|
+
dict(model=model, prompt=prompt, image_url=image_url, view_images=view_images, generate_type=generate_type,
|
|
288
|
+
enable_pbr=enable_pbr, face_count=face_count, texture_quality=texture_quality,
|
|
289
|
+
geometry_quality=geometry_quality, quad=quad, negative_prompt=negative_prompt, seed=seed,
|
|
290
|
+
auto_size=auto_size, orientation=orientation, texture_alignment=texture_alignment,
|
|
291
|
+
webhook_url=webhook_url, start_timeout=start_timeout, **extra),
|
|
292
|
+
idempotency_key,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def generate_and_wait(self, model: str, *, timeout: float = 900.0, poll_interval: float = 5.0, **kwargs: Any) -> Job:
|
|
296
|
+
return self._client.jobs.wait(self.generate(model, **kwargs), timeout=timeout, poll_interval=poll_interval)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class Jobs:
|
|
300
|
+
def __init__(self, client: Ewest) -> None:
|
|
301
|
+
self._client = client
|
|
302
|
+
|
|
303
|
+
def get(self, job: JobRef) -> Job:
|
|
304
|
+
"""``GET /v1/jobs/{id}``. Raises ``NotFoundError`` for an unknown job or another key's job."""
|
|
305
|
+
return Job.from_dict(self._client.request("GET", PATHS["get_job"].format(id=quote(_job_id(job), safe=""))))
|
|
306
|
+
|
|
307
|
+
def cancel(self, job: JobRef) -> Job:
|
|
308
|
+
"""``POST /v1/jobs/{id}/cancel``: stop a job that has not started; returns the job, now failed with code ``cancelled`` (not charged).
|
|
309
|
+
|
|
310
|
+
Raises ``APIError`` (status 409, code ``job_running``, ``job_finished`` or ``job_busy``) when the job cannot be cancelled.
|
|
311
|
+
"""
|
|
312
|
+
return Job.from_dict(self._client.request("POST", PATHS["cancel_job"].format(id=quote(_job_id(job), safe=""))))
|
|
313
|
+
|
|
314
|
+
def list(self, limit: int = 20) -> List[Job]:
|
|
315
|
+
"""``GET /v1/jobs``: this key's jobs, newest first."""
|
|
316
|
+
data = self._client.request("GET", PATHS["list_jobs"], params={"limit": limit})
|
|
317
|
+
return [Job.from_dict(d) for d in data.get("data", [])]
|
|
318
|
+
|
|
319
|
+
def wait(
|
|
320
|
+
self,
|
|
321
|
+
job: JobRef,
|
|
322
|
+
*,
|
|
323
|
+
timeout: float = 1200.0,
|
|
324
|
+
poll_interval: float = 3.0,
|
|
325
|
+
on_update: Optional[Callable[[Job], None]] = None,
|
|
326
|
+
) -> Job:
|
|
327
|
+
"""Poll until the job succeeds and return it.
|
|
328
|
+
|
|
329
|
+
Raises ``JobFailedError`` if it fails and ``JobTimeoutError`` after ``timeout`` seconds
|
|
330
|
+
(the job keeps running). ``on_update`` is called with every poll result.
|
|
331
|
+
"""
|
|
332
|
+
job_id = _job_id(job)
|
|
333
|
+
deadline = time.monotonic() + timeout
|
|
334
|
+
while True:
|
|
335
|
+
current = self.get(job_id)
|
|
336
|
+
if on_update:
|
|
337
|
+
on_update(current)
|
|
338
|
+
if current.status == "succeeded":
|
|
339
|
+
return current
|
|
340
|
+
if current.status == "failed":
|
|
341
|
+
raise JobFailedError(current)
|
|
342
|
+
remaining = deadline - time.monotonic()
|
|
343
|
+
if remaining <= 0:
|
|
344
|
+
raise JobTimeoutError(current, timeout)
|
|
345
|
+
self._client._sleep(min(poll_interval, remaining))
|
|
346
|
+
|
|
347
|
+
def stream(self, job: JobRef, *, max_reconnects: int = 5) -> Iterator[Job]:
|
|
348
|
+
"""Follow a job over Server-Sent Events (``GET /v1/jobs/{id}/events``).
|
|
349
|
+
|
|
350
|
+
Yields a ``Job`` whenever it changes and stops after ``succeeded`` or ``failed``
|
|
351
|
+
(it does not raise for a failed job; check ``job.status``). If the connection drops
|
|
352
|
+
or the server closes the stream early, it reconnects up to ``max_reconnects`` times.
|
|
353
|
+
"""
|
|
354
|
+
path = PATHS["job_events"].format(id=quote(_job_id(job), safe=""))
|
|
355
|
+
reconnects = 0
|
|
356
|
+
while True:
|
|
357
|
+
try:
|
|
358
|
+
# The server sends a heartbeat every 10 s, so 45 s of silence means a dead connection.
|
|
359
|
+
for event, data in self._client._events(path, timeout=45.0):
|
|
360
|
+
if event != "job":
|
|
361
|
+
continue
|
|
362
|
+
current = Job.from_dict(json.loads(data))
|
|
363
|
+
yield current
|
|
364
|
+
if current.done:
|
|
365
|
+
return
|
|
366
|
+
except APIConnectionError:
|
|
367
|
+
if reconnects >= max_reconnects:
|
|
368
|
+
raise
|
|
369
|
+
else:
|
|
370
|
+
if reconnects >= max_reconnects:
|
|
371
|
+
raise APIConnectionError("The event stream ended before the job finished.")
|
|
372
|
+
reconnects += 1
|
|
373
|
+
self._client._sleep(min(0.5 * reconnects, 5.0))
|
ewest/_errors.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Typed errors. Every HTTP error carries the API's error object and the request id."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
from email.utils import parsedate_to_datetime
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Mapping, Optional
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
10
|
+
from ._types import Job
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EwestError(Exception):
|
|
14
|
+
"""Base class of everything this package raises on purpose."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class APIConnectionError(EwestError):
|
|
18
|
+
"""The request never got an answer (network error or timeout)."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class APIError(EwestError):
|
|
22
|
+
"""The API answered with an error status. Fields come from ``{"error": {...}}``."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
message: str,
|
|
27
|
+
*,
|
|
28
|
+
status: int,
|
|
29
|
+
type: Optional[str] = None,
|
|
30
|
+
code: Optional[str] = None,
|
|
31
|
+
param: Optional[str] = None,
|
|
32
|
+
request_id: Optional[str] = None,
|
|
33
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
34
|
+
body: Any = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
self.message = message
|
|
38
|
+
self.status = status
|
|
39
|
+
self.type = type
|
|
40
|
+
self.code = code
|
|
41
|
+
self.param = param
|
|
42
|
+
self.request_id = request_id
|
|
43
|
+
self.headers = dict(headers or {})
|
|
44
|
+
self.body = body
|
|
45
|
+
|
|
46
|
+
def __str__(self) -> str:
|
|
47
|
+
bits = [f"HTTP {self.status}"]
|
|
48
|
+
if self.code and self.code != str(self.status):
|
|
49
|
+
bits.append(self.code)
|
|
50
|
+
if self.request_id:
|
|
51
|
+
bits.append(f"request id {self.request_id}")
|
|
52
|
+
return f"{self.message} ({', '.join(bits)})"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BadRequestError(APIError):
|
|
56
|
+
"""400: invalid fields. ``code`` says which: ``model_not_supported``, ``unsupported_value``, ..."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AuthError(APIError):
|
|
60
|
+
"""401: missing, invalid, expired or blocked API key."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class InsufficientBudgetError(APIError):
|
|
64
|
+
"""402: the key's budget (``insufficient_budget``) or the prepaid balance (``insufficient_balance``) is used up. Never retried."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class PermissionDeniedError(APIError):
|
|
68
|
+
"""403: the key may not use this model."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class NotFoundError(APIError):
|
|
72
|
+
"""404: unknown model, endpoint or job (a job is visible only to the key that made it)."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class RateLimitError(APIError):
|
|
76
|
+
"""429: too many requests. ``retry_after`` is the pause in seconds, when the API sent one."""
|
|
77
|
+
|
|
78
|
+
retry_after: Optional[float] = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ServerError(APIError):
|
|
82
|
+
"""5xx: the API or the model failed. Reads are retried with backoff."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class JobFailedError(EwestError):
|
|
86
|
+
"""A job ended with ``status: failed``. ``code`` and ``message`` come from ``job.error``."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, job: "Job") -> None:
|
|
89
|
+
err = job.error
|
|
90
|
+
self.job = job
|
|
91
|
+
self.code = err.code if err else None
|
|
92
|
+
self.message = (err.message if err else None) or "The job failed."
|
|
93
|
+
self.request_id = job.id # for jobs, the request id is the job id
|
|
94
|
+
super().__init__(f"{job.id} failed: {self.message}" + (f" ({self.code})" if self.code else ""))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class JobTimeoutError(EwestError):
|
|
98
|
+
"""``jobs.wait`` ran out of time. The job keeps running; ``job`` is the last state seen."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, job: "Job", timeout: float) -> None:
|
|
101
|
+
self.job = job
|
|
102
|
+
super().__init__(f"{job.id} is still {job.status} after {timeout:g} s")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class WebhookVerificationError(EwestError):
|
|
106
|
+
"""The webhook signature, timestamp or headers are not valid."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def parse_retry_after(value: Optional[str]) -> Optional[float]:
|
|
110
|
+
"""``Retry-After`` as seconds: a number, or an HTTP date."""
|
|
111
|
+
if not value:
|
|
112
|
+
return None
|
|
113
|
+
try:
|
|
114
|
+
return max(0.0, float(value))
|
|
115
|
+
except ValueError:
|
|
116
|
+
pass
|
|
117
|
+
try:
|
|
118
|
+
return max(0.0, parsedate_to_datetime(value).timestamp() - time.time())
|
|
119
|
+
except (TypeError, ValueError):
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def error_from_response(status: int, headers: Mapping[str, str], raw: bytes) -> APIError:
|
|
124
|
+
"""Build the right ``APIError`` subclass from an error response."""
|
|
125
|
+
body: Any = None
|
|
126
|
+
try:
|
|
127
|
+
body = json.loads(raw.decode("utf-8")) if raw else None
|
|
128
|
+
except (ValueError, UnicodeDecodeError):
|
|
129
|
+
body = None
|
|
130
|
+
err = body.get("error") if isinstance(body, dict) else None
|
|
131
|
+
if not isinstance(err, dict):
|
|
132
|
+
err = {}
|
|
133
|
+
fallback = "" if err else raw[:200].decode("utf-8", "replace").strip()
|
|
134
|
+
msg = err.get("message")
|
|
135
|
+
message = msg if isinstance(msg, str) and msg else (fallback or f"HTTP {status}")
|
|
136
|
+
lower = {k.lower(): v for k, v in headers.items()}
|
|
137
|
+
cls: type
|
|
138
|
+
if status in (400, 422):
|
|
139
|
+
cls = BadRequestError
|
|
140
|
+
elif status == 401:
|
|
141
|
+
cls = AuthError
|
|
142
|
+
elif status == 402:
|
|
143
|
+
cls = InsufficientBudgetError
|
|
144
|
+
elif status == 403:
|
|
145
|
+
cls = PermissionDeniedError
|
|
146
|
+
elif status == 404:
|
|
147
|
+
cls = NotFoundError
|
|
148
|
+
elif status == 429:
|
|
149
|
+
cls = RateLimitError
|
|
150
|
+
elif status >= 500:
|
|
151
|
+
cls = ServerError
|
|
152
|
+
else:
|
|
153
|
+
cls = APIError
|
|
154
|
+
|
|
155
|
+
def field(name: str) -> Optional[str]:
|
|
156
|
+
v = err.get(name)
|
|
157
|
+
return None if v is None else str(v)
|
|
158
|
+
|
|
159
|
+
out = cls(
|
|
160
|
+
message,
|
|
161
|
+
status=status,
|
|
162
|
+
type=field("type"),
|
|
163
|
+
code=field("code"),
|
|
164
|
+
param=field("param"),
|
|
165
|
+
request_id=lower.get("x-request-id"),
|
|
166
|
+
headers=lower,
|
|
167
|
+
body=body,
|
|
168
|
+
)
|
|
169
|
+
if isinstance(out, RateLimitError):
|
|
170
|
+
out.retry_after = parse_retry_after(lower.get("retry-after"))
|
|
171
|
+
return out
|
ewest/_schema.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Field names and values of the public API, kept in step with apps/web/openapi/spec.ts.
|
|
2
|
+
|
|
3
|
+
apps/web/openapi/sdk.test.ts reads this module and fails CI when the OpenAPI spec and these
|
|
4
|
+
lists differ, so a changed job or error field cannot go unnoticed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
DEFAULT_BASE_URL = "https://api.ewest.ai"
|
|
8
|
+
|
|
9
|
+
JOB_FIELDS = (
|
|
10
|
+
"id", "object", "type", "model", "status", "progress", "eta_seconds", "created_at",
|
|
11
|
+
"started_at", "completed_at", "start_deadline", "tags", "input", "output", "error", "usage",
|
|
12
|
+
)
|
|
13
|
+
JOB_TYPES = ("video", "audio", "3d")
|
|
14
|
+
JOB_STATUSES = ("queued", "running", "succeeded", "failed")
|
|
15
|
+
JOB_OUTPUT_FIELDS = ("url", "content_type", "duration", "resolution", "files", "thumbnail_url")
|
|
16
|
+
JOB_ERROR_FIELDS = ("code", "message")
|
|
17
|
+
# The union over all job types; audio jobs never get "image_download_failed" (the spec's AudioJob lists four).
|
|
18
|
+
JOB_ERROR_CODES = ("generation_failed", "content_policy", "image_download_failed", "timeout", "storage_error", "cancelled", "start_timeout")
|
|
19
|
+
|
|
20
|
+
ERROR_FIELDS = ("message", "type", "code", "param")
|
|
21
|
+
ERROR_TYPES = (
|
|
22
|
+
"invalid_request_error", "invalid_api_key", "insufficient_budget", "insufficient_balance",
|
|
23
|
+
"permission_error", "not_found_error", "content_policy", "model_unavailable",
|
|
24
|
+
"timeout_error", "api_error",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
VIDEO_REQUEST_FIELDS = (
|
|
28
|
+
"model", "prompt", "duration", "resolution", "aspect_ratio", "audio", "image_url",
|
|
29
|
+
"end_image_url", "webhook_url", "start_timeout",
|
|
30
|
+
)
|
|
31
|
+
AUDIO_REQUEST_FIELDS = ("model", "prompt", "duration", "instrumental", "loop", "lyrics", "webhook_url", "start_timeout")
|
|
32
|
+
THREED_REQUEST_FIELDS = (
|
|
33
|
+
"model", "prompt", "image_url", "view_images", "generate_type", "enable_pbr", "face_count", "texture_quality",
|
|
34
|
+
"geometry_quality", "quad", "negative_prompt", "seed", "auto_size", "orientation", "texture_alignment", "webhook_url",
|
|
35
|
+
"start_timeout",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
PATHS = {
|
|
39
|
+
"create_video": "/v1/videos/generations",
|
|
40
|
+
"create_audio": "/v1/audio/generations",
|
|
41
|
+
"create_3d": "/v1/3d/generations",
|
|
42
|
+
"list_jobs": "/v1/jobs",
|
|
43
|
+
"get_job": "/v1/jobs/{id}",
|
|
44
|
+
"job_events": "/v1/jobs/{id}/events",
|
|
45
|
+
"cancel_job": "/v1/jobs/{id}/cancel",
|
|
46
|
+
}
|
ewest/_sse.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""A small Server-Sent Events parser that accepts input in chunks of any size."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import List, Optional
|
|
7
|
+
|
|
8
|
+
_LINE_END = re.compile(r"\r\n|\n|\r")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class SSEEvent:
|
|
13
|
+
event: str # "message" when the stream gave no name
|
|
14
|
+
data: str
|
|
15
|
+
id: Optional[str] = None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SSEParser:
|
|
19
|
+
"""Feed text as it arrives; ``feed`` returns the events completed by that text."""
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
self._buf = ""
|
|
23
|
+
self._event: Optional[str] = None
|
|
24
|
+
self._data: List[str] = []
|
|
25
|
+
self._id: Optional[str] = None
|
|
26
|
+
|
|
27
|
+
def feed(self, text: str) -> List[SSEEvent]:
|
|
28
|
+
self._buf += text
|
|
29
|
+
events: List[SSEEvent] = []
|
|
30
|
+
while True:
|
|
31
|
+
m = _LINE_END.search(self._buf)
|
|
32
|
+
if m is None:
|
|
33
|
+
break
|
|
34
|
+
if m.group() == "\r" and m.end() == len(self._buf):
|
|
35
|
+
break # a "\n" may follow in the next chunk
|
|
36
|
+
line, self._buf = self._buf[: m.start()], self._buf[m.end():]
|
|
37
|
+
ev = self._line(line)
|
|
38
|
+
if ev is not None:
|
|
39
|
+
events.append(ev)
|
|
40
|
+
return events
|
|
41
|
+
|
|
42
|
+
def _line(self, line: str) -> Optional[SSEEvent]:
|
|
43
|
+
if line == "":
|
|
44
|
+
if not self._data:
|
|
45
|
+
self._event = None
|
|
46
|
+
return None
|
|
47
|
+
ev = SSEEvent(self._event or "message", "\n".join(self._data), self._id)
|
|
48
|
+
self._event, self._data = None, []
|
|
49
|
+
return ev
|
|
50
|
+
if line.startswith(":"):
|
|
51
|
+
return None # comment, e.g. ": heartbeat"
|
|
52
|
+
name, sep, value = line.partition(":")
|
|
53
|
+
if sep and value.startswith(" "):
|
|
54
|
+
value = value[1:]
|
|
55
|
+
if name == "event":
|
|
56
|
+
self._event = value
|
|
57
|
+
elif name == "data":
|
|
58
|
+
self._data.append(value)
|
|
59
|
+
elif name == "id":
|
|
60
|
+
self._id = value
|
|
61
|
+
return None
|
ewest/_types.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Job objects. Hand-written and small; field names are checked against the OpenAPI spec in CI."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
TERMINAL_STATUSES = ("succeeded", "failed")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _opt_int(v: Any) -> Optional[int]:
|
|
11
|
+
return int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class JobOutput:
|
|
16
|
+
"""The finished file. ``url`` is on cdn.ewest.ai and is kept for 7 days."""
|
|
17
|
+
|
|
18
|
+
url: str
|
|
19
|
+
content_type: str
|
|
20
|
+
duration: Optional[float] = None
|
|
21
|
+
resolution: Optional[str] = None
|
|
22
|
+
# 3D jobs: every file by format (glb, obj, ...), each {url, content_type, size}; ``url`` is the GLB.
|
|
23
|
+
files: Optional[Dict[str, Any]] = None
|
|
24
|
+
thumbnail_url: Optional[str] = None
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def from_dict(cls, d: Dict[str, Any]) -> "JobOutput":
|
|
28
|
+
return cls(
|
|
29
|
+
url=str(d.get("url", "")),
|
|
30
|
+
content_type=str(d.get("content_type", "")),
|
|
31
|
+
duration=d.get("duration"),
|
|
32
|
+
resolution=d.get("resolution"),
|
|
33
|
+
files=d.get("files"),
|
|
34
|
+
thumbnail_url=d.get("thumbnail_url"),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class JobError:
|
|
40
|
+
"""Why a job failed: ``generation_failed``, ``content_policy``, ``image_download_failed``, ``timeout``, ``storage_error``, ``cancelled`` or ``start_timeout``."""
|
|
41
|
+
|
|
42
|
+
code: Optional[str]
|
|
43
|
+
message: str
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_dict(cls, d: Dict[str, Any]) -> "JobError":
|
|
47
|
+
return cls(code=d.get("code"), message=str(d.get("message", "")))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class Job:
|
|
52
|
+
id: str
|
|
53
|
+
object: str
|
|
54
|
+
type: str # "video" | "audio"
|
|
55
|
+
model: str
|
|
56
|
+
status: str # "queued" | "running" | "succeeded" | "failed"
|
|
57
|
+
progress: int
|
|
58
|
+
eta_seconds: Optional[int]
|
|
59
|
+
created_at: int
|
|
60
|
+
started_at: Optional[int] = None
|
|
61
|
+
completed_at: Optional[int] = None
|
|
62
|
+
start_deadline: Optional[int] = None
|
|
63
|
+
tags: List[str] = field(default_factory=list)
|
|
64
|
+
input: Dict[str, Any] = field(default_factory=dict)
|
|
65
|
+
output: Optional[JobOutput] = None
|
|
66
|
+
error: Optional[JobError] = None
|
|
67
|
+
usage: Optional[Dict[str, Any]] = None
|
|
68
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_dict(cls, d: Dict[str, Any]) -> "Job":
|
|
72
|
+
out, err = d.get("output"), d.get("error")
|
|
73
|
+
return cls(
|
|
74
|
+
id=str(d["id"]),
|
|
75
|
+
object=str(d.get("object", "job")),
|
|
76
|
+
type=str(d.get("type", "")),
|
|
77
|
+
model=str(d.get("model", "")),
|
|
78
|
+
status=str(d.get("status", "")),
|
|
79
|
+
progress=int(d.get("progress") or 0),
|
|
80
|
+
eta_seconds=_opt_int(d.get("eta_seconds")),
|
|
81
|
+
created_at=int(d.get("created_at") or 0),
|
|
82
|
+
started_at=_opt_int(d.get("started_at")),
|
|
83
|
+
completed_at=_opt_int(d.get("completed_at")),
|
|
84
|
+
start_deadline=_opt_int(d.get("start_deadline")),
|
|
85
|
+
tags=[t for t in d.get("tags") or [] if isinstance(t, str)],
|
|
86
|
+
input=d.get("input") or {},
|
|
87
|
+
output=JobOutput.from_dict(out) if isinstance(out, dict) else None,
|
|
88
|
+
error=JobError.from_dict(err) if isinstance(err, dict) else None,
|
|
89
|
+
usage=d.get("usage") if isinstance(d.get("usage"), dict) else None,
|
|
90
|
+
raw=d,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def done(self) -> bool:
|
|
95
|
+
"""True once the job succeeded or failed."""
|
|
96
|
+
return self.status in TERMINAL_STATUSES
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def succeeded(self) -> bool:
|
|
100
|
+
return self.status == "succeeded"
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def url(self) -> Optional[str]:
|
|
104
|
+
"""The result file on cdn.ewest.ai, once the job succeeded."""
|
|
105
|
+
return self.output.url if self.output else None
|
ewest/_webhooks.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Webhook verification (Standard Webhooks, https://www.standardwebhooks.com).
|
|
2
|
+
|
|
3
|
+
Beta: the secret is GET /v1/webhooks/secret; deliveries are retried, so dedupe on the job id (a redelivery gets a new webhook-id).
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import binascii
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Mapping, Optional, Union
|
|
14
|
+
|
|
15
|
+
from ._errors import WebhookVerificationError
|
|
16
|
+
|
|
17
|
+
DEFAULT_TOLERANCE = 300 # seconds, both directions
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _header(headers: Mapping[str, Any], name: str) -> Optional[str]:
|
|
21
|
+
for key, value in headers.items():
|
|
22
|
+
if str(key).lower() == name:
|
|
23
|
+
if isinstance(value, (list, tuple)): # e.g. a multi-dict
|
|
24
|
+
value = value[0] if value else None
|
|
25
|
+
return None if value is None else str(value)
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _key(secret: str) -> bytes:
|
|
30
|
+
raw = secret[len("whsec_"):] if secret.startswith("whsec_") else secret
|
|
31
|
+
try:
|
|
32
|
+
return base64.b64decode(raw, validate=True)
|
|
33
|
+
except (binascii.Error, ValueError) as e:
|
|
34
|
+
raise WebhookVerificationError("The webhook secret is not base64 (expected whsec_...).") from e
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def sign(payload: Union[bytes, str], msg_id: str, timestamp: int, secret: str) -> str:
|
|
38
|
+
"""The ``v1,<signature>`` value for a payload. Used by tests and for local simulations."""
|
|
39
|
+
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
|
|
40
|
+
signed = f"{msg_id}.{timestamp}.".encode("utf-8") + body
|
|
41
|
+
digest = hmac.new(_key(secret), signed, hashlib.sha256).digest()
|
|
42
|
+
return "v1," + base64.b64encode(digest).decode("ascii")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def verify_webhook(
|
|
46
|
+
payload: Union[bytes, str],
|
|
47
|
+
headers: Mapping[str, Any],
|
|
48
|
+
secret: str,
|
|
49
|
+
tolerance: Optional[int] = DEFAULT_TOLERANCE,
|
|
50
|
+
*,
|
|
51
|
+
now: Optional[float] = None,
|
|
52
|
+
) -> Any:
|
|
53
|
+
"""Check a webhook and return its parsed JSON body (a finished job).
|
|
54
|
+
|
|
55
|
+
``payload`` must be the raw request body, byte for byte: do not parse and re-serialize it.
|
|
56
|
+
``headers`` needs ``webhook-id``, ``webhook-timestamp`` and ``webhook-signature`` (any case).
|
|
57
|
+
``tolerance`` is the allowed clock difference in seconds (default 300); ``None`` skips the
|
|
58
|
+
timestamp check. Raises ``WebhookVerificationError`` on any problem.
|
|
59
|
+
"""
|
|
60
|
+
msg_id = _header(headers, "webhook-id")
|
|
61
|
+
ts_text = _header(headers, "webhook-timestamp")
|
|
62
|
+
sigs = _header(headers, "webhook-signature")
|
|
63
|
+
if not msg_id or not ts_text or not sigs:
|
|
64
|
+
raise WebhookVerificationError("Missing webhook-id, webhook-timestamp or webhook-signature header.")
|
|
65
|
+
if not (ts_text.isascii() and ts_text.isdigit()): # digits only, like the JS helper
|
|
66
|
+
raise WebhookVerificationError("Invalid webhook-timestamp header.")
|
|
67
|
+
timestamp = int(ts_text)
|
|
68
|
+
if tolerance is not None:
|
|
69
|
+
current = time.time() if now is None else now
|
|
70
|
+
if abs(current - timestamp) > tolerance:
|
|
71
|
+
raise WebhookVerificationError("The webhook timestamp is outside the allowed tolerance.")
|
|
72
|
+
|
|
73
|
+
expected = sign(payload, msg_id, timestamp, secret).split(",", 1)[1].encode("ascii")
|
|
74
|
+
ok = False
|
|
75
|
+
for part in sigs.split(): # the loop never stops early, so timing does not depend on the match
|
|
76
|
+
version, _, sig = part.partition(",")
|
|
77
|
+
if version == "v1" and hmac.compare_digest(sig.encode("ascii", "ignore"), expected):
|
|
78
|
+
ok = True
|
|
79
|
+
if not ok:
|
|
80
|
+
raise WebhookVerificationError("No matching signature found.")
|
|
81
|
+
try:
|
|
82
|
+
return json.loads(payload)
|
|
83
|
+
except ValueError as e:
|
|
84
|
+
raise WebhookVerificationError("The webhook body is not valid JSON.") from e
|
ewest/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ewest
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Small, typed helpers for eWest's async jobs (video, music, sound): submit, wait, stream, verify webhooks.
|
|
5
|
+
Author-email: eWest <support@ewest.ai>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://ewest.ai/docs
|
|
8
|
+
Project-URL: Documentation, https://ewest.ai/docs
|
|
9
|
+
Project-URL: Changelog, https://ewest.ai/changelog
|
|
10
|
+
Project-URL: Source, https://gitlab.com/ewest-ai/sdk
|
|
11
|
+
Keywords: ewest,ai,video,audio,jobs,webhooks
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# ewest (Python)
|
|
28
|
+
|
|
29
|
+
Small, typed helpers for eWest's async jobs: video, music and sound. Standard library only, Python 3.9
|
|
30
|
+
or newer. **Beta.** For chat, embeddings and images use the OpenAI or Anthropic SDK with base URL
|
|
31
|
+
`https://api.ewest.ai/v1`; see the [cookbook](../COOKBOOK.md).
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install ewest
|
|
35
|
+
export EWEST_KEY="paste your key here"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Make a video
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from ewest import Ewest
|
|
42
|
+
|
|
43
|
+
client = Ewest() # api_key defaults to $EWEST_KEY, base_url to https://api.ewest.ai
|
|
44
|
+
job = client.videos.generate_and_wait("ewest/veo-3.1-fast", "A red fox walks through fresh snow", duration=6)
|
|
45
|
+
print(job.url) # a file on cdn.ewest.ai, kept for 7 days
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Jobs
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from ewest import Ewest
|
|
52
|
+
|
|
53
|
+
client = Ewest()
|
|
54
|
+
job = client.videos.generate("ewest/veo-3.1-fast", "Waves at dusk", duration=4, resolution="720p") # 202, queued
|
|
55
|
+
job = client.jobs.get(job.id)
|
|
56
|
+
for j in client.jobs.list(limit=5):
|
|
57
|
+
print(j.id, j.status)
|
|
58
|
+
|
|
59
|
+
done = client.jobs.wait(job, timeout=600, poll_interval=3) # polls; raises JobFailedError / JobTimeoutError
|
|
60
|
+
for update in client.jobs.stream(job): # Server-Sent Events, reconnects on its own
|
|
61
|
+
print(update.status, update.progress)
|
|
62
|
+
|
|
63
|
+
song = client.audio.generate_and_wait("ewest/eleven-music-v2.5", "Calm piano", duration=30, instrumental=True)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`Job` has `id`, `status` (`queued`, `running`, `succeeded`, `failed`), `progress`, `eta_seconds`, `input`,
|
|
67
|
+
`output` (`url`, `content_type`, `duration`, `resolution`), `error` (`code`, `message`), `usage` and
|
|
68
|
+
`raw` (the JSON as received), plus `done`, `succeeded` and `url`.
|
|
69
|
+
|
|
70
|
+
## Cancel a job and retry safely
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
job = client.videos.generate(
|
|
74
|
+
"ewest/veo-3.1-fast", "Gulls over a harbor",
|
|
75
|
+
idempotency_key="harbor-001", # the same key returns the same job, so a retry never starts (or charges) a second one
|
|
76
|
+
)
|
|
77
|
+
client.jobs.cancel(job) # only before it starts; a running job raises APIError with status 409, code job_running
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
With an `idempotency_key`, a failed `generate` (network error, 5xx) is retried on its own, because
|
|
81
|
+
repeating it is safe. Keys are kept 24 hours; reusing one with a different body answers 409
|
|
82
|
+
`idempotency_key_reused`. `generate_and_wait` takes the same option. See
|
|
83
|
+
[Jobs and webhooks](https://ewest.ai/docs/jobs).
|
|
84
|
+
|
|
85
|
+
## Errors and retries
|
|
86
|
+
|
|
87
|
+
All errors derive from `EwestError`. HTTP errors are `APIError` subclasses with `status`, `type`, `code`,
|
|
88
|
+
`param`, `request_id` and `headers`:
|
|
89
|
+
|
|
90
|
+
| Status | Class |
|
|
91
|
+
|---|---|
|
|
92
|
+
| 400 | `BadRequestError` (`code`: `model_not_supported`, `unsupported_value`, ...) |
|
|
93
|
+
| 401 | `AuthError` |
|
|
94
|
+
| 402 | `InsufficientBudgetError` (never retried) |
|
|
95
|
+
| 403 | `PermissionDeniedError` |
|
|
96
|
+
| 404 | `NotFoundError` |
|
|
97
|
+
| 429 | `RateLimitError` (`retry_after`) |
|
|
98
|
+
| 5xx | `ServerError` |
|
|
99
|
+
|
|
100
|
+
`JobFailedError` (a job ended `failed`), `JobTimeoutError`, `APIConnectionError` and
|
|
101
|
+
`WebhookVerificationError` are not HTTP errors. A 429 is retried with backoff for every call (honouring
|
|
102
|
+
`Retry-After`, `max_retries=2`). 5xx answers and network errors are retried for reads only, because a
|
|
103
|
+
failed POST may already have started a paid job (unless you send an idempotency key; see above).
|
|
104
|
+
|
|
105
|
+
## Verify a webhook (beta)
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from ewest import WebhookVerificationError, verify_webhook
|
|
109
|
+
|
|
110
|
+
def handle(raw_body: bytes, headers, secret: str):
|
|
111
|
+
try:
|
|
112
|
+
job = verify_webhook(raw_body, headers, secret) # Standard Webhooks; tolerance 300 s
|
|
113
|
+
except WebhookVerificationError:
|
|
114
|
+
return 400
|
|
115
|
+
print(job["id"], job["status"])
|
|
116
|
+
return 204
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The secret (`whsec_...`) is `GET /v1/webhooks/secret` for your organization. Deliveries are retried over
|
|
120
|
+
about 27.6 hours and can arrive twice, so dedupe on the job `id` (a redelivery gets a new `webhook-id`); see the cookbook for Flask and FastAPI.
|
|
121
|
+
|
|
122
|
+
## Other endpoints
|
|
123
|
+
|
|
124
|
+
`client.request("GET", "/v1/models")` sends any request with the same auth, retries and typed errors
|
|
125
|
+
and returns the parsed JSON.
|
|
126
|
+
|
|
127
|
+
## Versions
|
|
128
|
+
|
|
129
|
+
Semantic versioning; `0.x` is beta, so a minor version may change an API.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
ewest/__init__.py,sha256=f9QjL4folgz50ny1xCd3oJ-utWkUV912jzIZNKfnj4I,1051
|
|
2
|
+
ewest/_client.py,sha256=XFvALfmsEqX7mGSAY98R0JK6Mv1IGV7L7XjSXYfrctQ,15915
|
|
3
|
+
ewest/_errors.py,sha256=fYmyf9uHuxNUZJd7PQxA-Kxf1nSSjxtzOQH-ZcVlFYE,5378
|
|
4
|
+
ewest/_schema.py,sha256=LSMRQp7dPfP2oaAJyDWA9pxCj8BMunHtCR9rYXBvm5w,2129
|
|
5
|
+
ewest/_sse.py,sha256=Y8njPcbKDhXUTVCTMv5ZaXpD_tweun0OyGPTk8S77TQ,1921
|
|
6
|
+
ewest/_types.py,sha256=T1IhpJvFopPDo8OFjGL-oXvH5wdNIMeFfO05iy68tFA,3690
|
|
7
|
+
ewest/_webhooks.py,sha256=KvFiRqYt395G1spC-J-5Npyvll_lpBkNlCuVlpm4Bgw,3580
|
|
8
|
+
ewest/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
ewest-0.1.0.dist-info/licenses/LICENSE,sha256=-ALbnRdTZCWKnRzKXQMsW2J6HFR-aiIFdaSHzkkW1Xg,1062
|
|
10
|
+
ewest-0.1.0.dist-info/METADATA,sha256=Qj9udvDZO1sWkdJPvwb3MxR_Dxbn5XACXgWYbuxsIe8,5000
|
|
11
|
+
ewest-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
12
|
+
ewest-0.1.0.dist-info/top_level.txt,sha256=zHs6pCCmaK1dukwRaRrzL7jhKIe6ZyR_AW92hbTpUAw,6
|
|
13
|
+
ewest-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 eWest
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ewest
|