deapi-sdk 0.6.1__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.
Files changed (47) hide show
  1. deapi_sdk/__init__.py +409 -0
  2. deapi_sdk/_cards.py +313 -0
  3. deapi_sdk/_client.py +411 -0
  4. deapi_sdk/_config.py +77 -0
  5. deapi_sdk/_constants.py +61 -0
  6. deapi_sdk/_download.py +37 -0
  7. deapi_sdk/_exceptions.py +184 -0
  8. deapi_sdk/_files.py +59 -0
  9. deapi_sdk/_payload.py +50 -0
  10. deapi_sdk/_polling.py +157 -0
  11. deapi_sdk/_realtime/__init__.py +7 -0
  12. deapi_sdk/_realtime/_discovery.py +43 -0
  13. deapi_sdk/_realtime/_engine.py +419 -0
  14. deapi_sdk/_realtime/_protocol.py +152 -0
  15. deapi_sdk/_realtime/_session.py +529 -0
  16. deapi_sdk/_types.py +31 -0
  17. deapi_sdk/_version.py +3 -0
  18. deapi_sdk/py.typed +0 -0
  19. deapi_sdk/resources/__init__.py +35 -0
  20. deapi_sdk/resources/account.py +149 -0
  21. deapi_sdk/resources/audio.py +386 -0
  22. deapi_sdk/resources/embeddings.py +116 -0
  23. deapi_sdk/resources/images.py +616 -0
  24. deapi_sdk/resources/keys.py +277 -0
  25. deapi_sdk/resources/models.py +161 -0
  26. deapi_sdk/resources/ocr.py +152 -0
  27. deapi_sdk/resources/prompts.py +137 -0
  28. deapi_sdk/resources/transcription.py +308 -0
  29. deapi_sdk/resources/video.py +985 -0
  30. deapi_sdk/transcript.py +142 -0
  31. deapi_sdk/types/__init__.py +68 -0
  32. deapi_sdk/types/account.py +115 -0
  33. deapi_sdk/types/audio.py +35 -0
  34. deapi_sdk/types/common.py +174 -0
  35. deapi_sdk/types/embeddings.py +11 -0
  36. deapi_sdk/types/images.py +40 -0
  37. deapi_sdk/types/keys.py +53 -0
  38. deapi_sdk/types/ocr.py +14 -0
  39. deapi_sdk/types/prompts.py +26 -0
  40. deapi_sdk/types/transcription.py +14 -0
  41. deapi_sdk/types/video.py +84 -0
  42. deapi_sdk/types/websocket.py +36 -0
  43. deapi_sdk/webhook.py +159 -0
  44. deapi_sdk-0.6.1.dist-info/METADATA +644 -0
  45. deapi_sdk-0.6.1.dist-info/RECORD +47 -0
  46. deapi_sdk-0.6.1.dist-info/WHEEL +4 -0
  47. deapi_sdk-0.6.1.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,644 @@
1
+ Metadata-Version: 2.5
2
+ Name: deapi-sdk
3
+ Version: 0.6.1
4
+ Summary: Official Python SDK for deAPI — distributed AI inference platform
5
+ Project-URL: Homepage, https://deapi.ai
6
+ Project-URL: Documentation, https://docs.deapi.ai/other/sdks-and-integrations
7
+ Project-URL: Repository, https://github.com/deapi-ai/deapi-python-sdk
8
+ Project-URL: Changelog, https://github.com/deapi-ai/deapi-python-sdk/blob/main/CHANGELOG.md
9
+ Author: deAPI Team
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ai,deapi,inference,sdk,stable-diffusion,tts,whisper
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: httpx<1.0.0,>=0.25.0
24
+ Requires-Dist: pydantic<3.0.0,>=2.6.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.5; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
28
+ Requires-Dist: pytest>=7.0; extra == 'dev'
29
+ Requires-Dist: respx>=0.21; extra == 'dev'
30
+ Requires-Dist: ruff>=0.1; extra == 'dev'
31
+ Requires-Dist: websockets<18,>=17.0; extra == 'dev'
32
+ Provides-Extra: ws
33
+ Requires-Dist: websockets<18,>=17.0; extra == 'ws'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # deAPI Python SDK
37
+
38
+ [![CI](https://github.com/deapi-ai/deapi-python-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/deapi-ai/deapi-python-sdk/actions/workflows/ci.yml)
39
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
40
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
41
+
42
+ Official Python SDK for the [deAPI](https://deapi.ai) distributed AI inference platform. API details live in the [deAPI docs](https://docs.deapi.ai).
43
+
44
+ Generate images, videos, audio, transcriptions, embeddings, and more — all through a clean, type-safe Python interface with sync and async support.
45
+
46
+ ## Features
47
+
48
+ - **Image generation** — text-to-image, image edits (one or many sources), upscale, background removal
49
+ - **Video generation** — text-to-video, image-to-video (keyframes or reference images/videos/audio), audio-to-video, upscale
50
+ - **Video description** — timestamped events and scenes of a video
51
+ - **Audio** — text-to-speech (with voice cloning), text-to-music (with a style reference)
52
+ - **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts
53
+ - **Embeddings, OCR, prompt enhancement**
54
+ - **Account and keys** — balance, usage, payments, API-key management (ADMIN keys)
55
+ - **Sync + Async** — both `DeapiClient` and `AsyncDeapiClient`
56
+ - **Job polling** — automatic exponential backoff with `.wait()`, resumable after a timeout
57
+ - **Real-time status** — live job progress over WebSocket (optional `[ws]` extra)
58
+ - **Precise errors** — every exception carries the API's machine-readable `code`
59
+ - **Safe auto-retry** — GETs retry on 429/5xx/network errors; job-creating POSTs never retry after a timeout or 5xx (no double charges)
60
+ - **Model-card defaults** — `width`, `height`, `steps`, `fps`, `seed`, ... are optional; the SDK fills them from the model card
61
+ - **Type-safe** — full type hints, Pydantic v2 models, `py.typed` marker
62
+ - **Webhook verification** — HMAC-SHA256 signature validation utility
63
+ - **File flexibility** — accepts `Path` objects, bytes, or binary file objects (never a bare `str` path)
64
+
65
+ ## Installation
66
+
67
+ ```bash
68
+ pip install deapi-sdk
69
+ ```
70
+
71
+ Real-time job updates over WebSocket need the optional `ws` extra (installs `websockets`):
72
+
73
+ ```bash
74
+ pip install "deapi-sdk[ws]"
75
+ ```
76
+
77
+ The latest unreleased code can be installed straight from GitHub:
78
+ `pip install git+https://github.com/deapi-ai/deapi-python-sdk.git@main`.
79
+
80
+ > `pip install deapi` installs an **unrelated** package. Do not use it.
81
+
82
+ For development (`pytest` runs from the repo root):
83
+
84
+ ```bash
85
+ git clone https://github.com/deapi-ai/deapi-python-sdk.git
86
+ cd deapi-python-sdk
87
+ pip install -e ".[dev]"
88
+ pytest # unit tests only; `pytest -m integration` runs paid tests against production
89
+ ```
90
+
91
+ ## API keys
92
+
93
+ Create a key in your [deAPI dashboard](https://deapi.ai). Current keys look like
94
+ `sk-dp-<id>-<secret>` (older `<id>|<secret>` keys keep working). Keep them out of source control:
95
+ use an environment variable or a `.env` file (see [`.env.example`](.env.example)).
96
+
97
+ Keys have a role. **ADMIN** keys can do everything. **API** keys run jobs but get a 403
98
+ `insufficient_permissions` on balance, account and key-management endpoints
99
+ (`client.balance()`, `client.account`, and `client.keys` except `current()` / `current_usage()`).
100
+
101
+ ## Quick Start
102
+
103
+ ```python
104
+ from deapi_sdk import DeapiClient
105
+
106
+ client = DeapiClient(api_key="sk-dp-<id>-<secret>")
107
+
108
+ job = client.images.generate(
109
+ prompt="a cat floating in a nebula, photorealistic",
110
+ model="Flux1schnell",
111
+ width=1024,
112
+ height=1024,
113
+ seed=42,
114
+ )
115
+
116
+ result = job.wait() # polls with exponential backoff
117
+ print(result.result_url)
118
+ ```
119
+
120
+ ## Configuration
121
+
122
+ ```python
123
+ client = DeapiClient(
124
+ api_key="sk-dp-<id>-<secret>", # or DEAPI_API_KEY
125
+ base_url="https://api.deapi.ai", # or DEAPI_BASE_URL
126
+ timeout=60.0, # request timeout in seconds (default: 30)
127
+ max_retries=5, # retry attempts (default: 3)
128
+ api_version="v2", # only "v2" is accepted (default)
129
+ fill_model_defaults=True, # default; see "Model-card defaults"
130
+ )
131
+ ```
132
+
133
+ | Option | Environment variable | Default |
134
+ |--------|----------------------|---------|
135
+ | `api_key` | `DEAPI_API_KEY` | required |
136
+ | `base_url` | `DEAPI_BASE_URL` | `https://api.deapi.ai` |
137
+ | `api_version` | `DEAPI_API_VERSION` | `v2` |
138
+ | `fill_model_defaults` | `DEAPI_FILL_MODEL_DEFAULTS` (`0` disables) | on |
139
+ | `client_id` (`client.realtime()`) | `DEAPI_CLIENT_ID` | discovered from the API |
140
+ | `ws_url` (`client.realtime()`) | `DEAPI_WS_URL` | discovered from the API |
141
+ | `app_key` (`client.realtime()`) | `DEAPI_WS_APP_KEY` | discovered from the API |
142
+ | `timeout` | — | `30.0` |
143
+ | `max_retries` | — | `3` |
144
+ | `max_retry_after` | — | `60.0` (cap on a 429 `Retry-After` sleep, in seconds) |
145
+
146
+ ```python
147
+ client = DeapiClient() # reads the environment
148
+
149
+ with DeapiClient() as client: # closes the HTTP connection on exit
150
+ ...
151
+ ```
152
+
153
+ The SDK targets deAPI API v2. `api_version` accepts only `"v2"`; see [Upgrading to 0.4.0](#upgrading-to-040).
154
+
155
+ ### Model-card defaults
156
+
157
+ Parameters that depend on the model (`width`, `height`, `steps`, `frames`, `fps`, `seed`, `lang`,
158
+ `speed`, `format`, `sample_rate`, `inference_steps`, `guidance_scale`, ...) are optional. When you
159
+ leave one unset, the SDK fills it from the model's `info.defaults` in `GET /models` (one catalogue
160
+ request per client, then cached), and `seed` defaults to `-1` (random). Explicit values always win.
161
+ Disable with `DeapiClient(fill_model_defaults=False)` or `DEAPI_FILL_MODEL_DEFAULTS=0`.
162
+
163
+ ## Usage
164
+
165
+ ### Image Generation
166
+
167
+ ```python
168
+ from pathlib import Path
169
+
170
+ # Text-to-image
171
+ job = client.images.generate(
172
+ prompt="mountain landscape at sunset",
173
+ negative_prompt="blurry, low quality",
174
+ model="Flux1schnell",
175
+ width=1024,
176
+ height=1024,
177
+ seed=42,
178
+ loras=[{"name": "detail-enhancer", "weight": 0.8}],
179
+ quality="high", # model tier, where the model supports it
180
+ enhance_prompt=True, # boost the prompt inside the job (fee billed on the job, not in *_price)
181
+ )
182
+ result = job.wait()
183
+ print(result.result_url)
184
+ print(result.results_alt_formats) # {"jpg": "...", "webp": "..."}
185
+
186
+ # Image edits: image= for one source, images=[...] for several (not both)
187
+ job = client.images.transform(
188
+ prompt="make it look like a watercolor painting",
189
+ image=Path("photo.jpg"), # Path, bytes or a binary file object (not a plain str)
190
+ model="QwenImageEdit_Plus_NF4",
191
+ )
192
+
193
+ job = client.images.upscale(image=Path("low_res.png"), model="RealESRGAN_x4")
194
+ job = client.images.remove_background(image=Path("photo.png"), model="Ben2")
195
+ ```
196
+
197
+ ### Video Generation
198
+
199
+ ```python
200
+ from pathlib import Path
201
+
202
+ # Text-to-video
203
+ job = client.video.generate(
204
+ prompt="a rocket launching into space",
205
+ model="Ltx2_5_22B_Dist_INT8",
206
+ width=768, height=512, frames=120, fps=24,
207
+ )
208
+
209
+ # Image-to-video with keyframes
210
+ job = client.video.animate(
211
+ prompt="gentle camera pan across the scene",
212
+ first_frame_image=Path("landscape.jpg"),
213
+ model="Ltx2_5_22B_Dist_INT8",
214
+ )
215
+
216
+ # Reference mode: list order binds files to <Picture N> / <Video N> / <Audio N> in the prompt.
217
+ # Mutually exclusive with first/last frame images.
218
+ job = client.video.animate(
219
+ prompt="<Picture 1> walks through the scene from <Video 1>, speaking <Audio 1>",
220
+ model="MiniMaxH3_33B_Turbo_INT8", # a model whose card has supports_*_refs
221
+ ref_images=[Path("character.png")],
222
+ ref_videos=[Path("scene.mp4")],
223
+ ref_audios=[Path("voice.mp3")],
224
+ )
225
+
226
+ # Audio-to-video
227
+ job = client.video.generate_from_audio(
228
+ prompt="visualize the music with abstract shapes",
229
+ audio=Path("track.mp3"),
230
+ model="Ltx2_5_22B_Dist_INT8",
231
+ )
232
+
233
+ # Describe a video: events, scenes and metadata
234
+ job = client.video.describe(
235
+ model="Marlin_2B",
236
+ video_url="https://youtube.com/watch?v=dQw4w9WgXcQ",
237
+ preset="balanced", # fast | balanced | detail (models with presets)
238
+ )
239
+ description = client.video.get_description(job.wait()) # VideoDescription: events, scenes, meta
240
+ ```
241
+
242
+ Reference limits (`max_ref_images`, `max_ref_videos`, `max_ref_audios`) come from the model card;
243
+ the API never accepts more than 9 images, 1 video or 3 audios.
244
+
245
+ ### Audio
246
+
247
+ ```python
248
+ from pathlib import Path
249
+
250
+ # Text-to-speech
251
+ job = client.audio.synthesize(
252
+ text="Hello, welcome to deAPI!",
253
+ model="Kokoro",
254
+ voice="af_sky",
255
+ lang="en-us",
256
+ format="mp3",
257
+ )
258
+
259
+ # Text-to-music, optionally with a style reference clip
260
+ job = client.audio.compose(
261
+ caption="upbeat electronic track with synth leads",
262
+ model="AceStep_1_5_XL_Turbo_INT8",
263
+ duration=30,
264
+ reference_audio=Path("style.mp3"),
265
+ )
266
+ ```
267
+
268
+ ### Transcription
269
+
270
+ ```python
271
+ from pathlib import Path
272
+
273
+ job = client.transcription.create(
274
+ source_url="https://youtube.com/watch?v=dQw4w9WgXcQ", # or source_file=Path("interview.mp3")
275
+ model="WhisperLargeV3Ct2",
276
+ ts_level="segment", # segment | word | char (implies include_ts)
277
+ diarize=True, # label speakers (implies timestamps)
278
+ lang="en", # unset or "auto" = detect
279
+ include_metadata=True,
280
+ )
281
+ transcript = client.transcription.get_transcript(job.wait())
282
+ print(transcript.format, transcript.text)
283
+ for seg in transcript.segments:
284
+ print(seg.start, seg.end, seg.speaker, seg.text)
285
+ ```
286
+
287
+ **Two transcript formats.** Models whose card has `info.limits.output_format: "json"` (for example
288
+ `WhisperLargeV3Ct2`) always return a JSON document (`text`, `language`, `segments` with
289
+ `start`/`end`/`speaker`/`words`). Models with `output_format: null` (for example `WhisperLargeV3`)
290
+ return plain text with timestamps inline. `client.transcription.get_transcript(result)` (or
291
+ `deapi_sdk.parse_transcript(raw)`) handles both and returns a `Transcript` whose `format` is `"json"` or
292
+ `"text"` (`segments` is empty for text). Result URLs are downloaded without your API key.
293
+
294
+ ### Embeddings and OCR
295
+
296
+ ```python
297
+ from pathlib import Path
298
+
299
+ job = client.embeddings.create(
300
+ input=["first sentence", "second sentence"], # or a single string
301
+ model="Bge_M3_FP16",
302
+ return_result_in_response=True,
303
+ )
304
+
305
+ job = client.ocr.extract(image=Path("scan.png"), model="Nanonets_Ocr_S_F16", return_result_in_response=True)
306
+ ```
307
+
308
+ ### Prompt Enhancement
309
+
310
+ Prompt methods return results immediately (no job polling):
311
+
312
+ ```python
313
+ enhanced = client.prompts.enhance(
314
+ prompt="cat in space",
315
+ type="images.generations", # images.edits, videos.generations, videos.animations, audio.speech, ...
316
+ model_slug="Flux1schnell",
317
+ negative_prompt="blurry",
318
+ )
319
+ print(enhanced.prompt)
320
+ ```
321
+
322
+ `images.edits` and `videos.animations` also need `image=`. The per-type methods
323
+ `enhance_image()`, `enhance_video()` etc. were removed in 0.4.0 (see [Upgrading to 0.4.0](#upgrading-to-040)).
324
+
325
+ ### Price Calculation
326
+
327
+ Every job method has a `_price` counterpart. The `enhance_prompt` fee is billed on the job and is
328
+ not part of the quote.
329
+
330
+ ```python
331
+ price = client.images.generate_price(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024)
332
+ print(f"Cost: ${price.price}")
333
+ ```
334
+
335
+ ### Account, Keys and Balance
336
+
337
+ ```python
338
+ client.balance().balance # ADMIN key only
339
+ client.websocket_config() # realtime connection settings (any role)
340
+
341
+ client.account.get() # balance, currency, auto top-up (ADMIN)
342
+ client.account.usage(group_by="day") # from_=, to=; group_by day|hour|key|type|model
343
+ client.account.payments(limit=20)
344
+
345
+ client.keys.current() # the calling key (any role)
346
+ client.keys.current_usage(group_by="model") # usage of the calling key (any role)
347
+
348
+ # ADMIN only
349
+ client.keys.list(limit=50)
350
+ created = client.keys.create(name="ci", limit=25.0, reset_interval="monthly")
351
+ print(created.secret) # shown ONCE, store it now
352
+ client.keys.update(created.id, active=False) # disable; active=True re-enables
353
+ client.keys.delete(created.id)
354
+ ```
355
+
356
+ ### Models
357
+
358
+ ```python
359
+ page = client.models.list(limit=50, page=1, inference_types=["txt2img"], tags=["new"], sort="-created_at")
360
+ everything = client.models.list_all()
361
+ model = client.models.get("Flux1schnell") # ModelInfo or None
362
+ ```
363
+
364
+ `per_page` is a deprecated alias for `limit`.
365
+
366
+ ## Async Usage
367
+
368
+ Every method has an async equivalent via `AsyncDeapiClient`:
369
+
370
+ ```python
371
+ import asyncio
372
+ from deapi_sdk import AsyncDeapiClient
373
+
374
+ async def main():
375
+ async with AsyncDeapiClient(api_key="sk-dp-<id>-<secret>") as client:
376
+ jobs = await asyncio.gather(*[
377
+ client.images.generate(prompt=p, model="Flux1schnell", width=1024, height=1024)
378
+ for p in ("mountain landscape", "ocean sunset", "forest path")
379
+ ])
380
+ results = await asyncio.gather(*[job.wait() for job in jobs])
381
+ for result in results:
382
+ print(result.result_url)
383
+
384
+ asyncio.run(main())
385
+ ```
386
+
387
+ ## Job Polling
388
+
389
+ All job methods return a `Job` (or `AsyncJob`):
390
+
391
+ ```python
392
+ job = client.images.generate(...)
393
+
394
+ result = job.wait(
395
+ poll_interval=1.0, # initial interval between polls (default: 1s)
396
+ max_wait=300.0, # timeout in seconds (default: 5 min)
397
+ backoff_factor=1.5,
398
+ max_interval=10.0,
399
+ )
400
+
401
+ result = job.status() # or poll once yourself: result.status, result.progress
402
+ ```
403
+
404
+ If `wait()` times out it raises `JobTimeoutError`, but **the job keeps running**. Resume it any time:
405
+
406
+ ```python
407
+ from deapi_sdk import JobTimeoutError
408
+
409
+ try:
410
+ result = job.wait(max_wait=60)
411
+ except JobTimeoutError as e:
412
+ result = client.jobs.get(e.request_id).wait() # or client.jobs.status(e.request_id)
413
+ ```
414
+
415
+ ## Real-time Updates (WebSocket)
416
+
417
+ Instead of polling, follow your jobs live over one WebSocket connection. Install the `ws` extra
418
+ (see [Installation](#installation)) and open a connection **before** submitting jobs:
419
+
420
+ ```python
421
+ from deapi_sdk import DeapiClient
422
+
423
+ with DeapiClient(api_key="sk-dp-<id>-<secret>") as client:
424
+ with client.realtime() as rt: # no other settings needed: the SDK asks the API where to connect
425
+ job = client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024)
426
+
427
+ result = rt.wait(job, on_progress=lambda e: print(e.status, e.progress)) # same JobResult as job.wait()
428
+ print(result.status, result.result_url)
429
+
430
+ for event in rt.events(): # every status event on your channel (all your jobs); blocks
431
+ print(event.request_id, event.status, event.progress)
432
+ ```
433
+
434
+ Async works the same way:
435
+
436
+ ```python
437
+ async with AsyncDeapiClient() as client:
438
+ async with client.realtime() as rt:
439
+ job = await client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024)
440
+ result = await rt.wait(job, on_progress=callback) # plain function or async function
441
+ async for event in rt.events():
442
+ ...
443
+ ```
444
+
445
+ - **All settings are optional.** `client_id`, `ws_url` and `app_key` are each taken from the argument,
446
+ else from `DEAPI_CLIENT_ID` / `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`, else from the account's
447
+ `GET /websocket` response (`client.websocket_config()`). The SDK calls that endpoint once, on
448
+ `connect()` / `with` (never in the constructor), and only when something is still missing; with all three
449
+ set there is no extra request. `rt.client_id` is `None` until then if you did not pass one.
450
+ `client_id` is the "Client ID" shown in your deAPI dashboard; servers handling many users should pass it
451
+ explicitly per user. A `client_id` that does not belong to the API key raises `RealtimeError`.
452
+ - **`rt.wait(job_or_request_id)`** accepts a `Job` or a request id. WebSocket events drive progress and
453
+ completion; on `done` the SDK fetches the final `JobResult` over HTTP (fresh signed `result_url`, all
454
+ fields).
455
+ - **Failed jobs are usually not announced over WebSocket.** `wait()` therefore also checks the job over
456
+ HTTP every `poll_interval` seconds (default 10), right after every reconnect and as soon as the socket
457
+ reports `done` or `error`. A failed job is returned
458
+ with `status == "error"`, exactly like `job.wait()`. After `max_wait` (default 300 s) it raises
459
+ `JobTimeoutError`.
460
+ - **Reconnects** happen automatically with exponential backoff and the channel is re-subscribed. Events
461
+ sent while disconnected are lost; `wait()` compensates by checking the job over HTTP after
462
+ reconnecting. `rt.connected` tells you whether the socket is up.
463
+ - `JobStatusEvent` has `request_id`, `status` (`processing`, repeated while `progress` grows, then `done`), `progress` (0-100),
464
+ `preview` (base64 data URI, image jobs) and `result_url` (only on `done`).
465
+ - Without the extra, connecting raises an `ImportError` telling you to install `deapi-sdk[ws]`. A failed
466
+ discovery call raises the usual API exception (for example `AuthenticationError`); an unusable response
467
+ raises `RealtimeError`.
468
+
469
+ See [`examples/realtime_status.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/realtime_status.py).
470
+
471
+ ## Error Handling
472
+
473
+ Every exception derives from `DeapiError` and carries `.code` (the API's machine-readable code, or
474
+ `None`), `.status_code`, `.message` and `.body`.
475
+
476
+ ```
477
+ DeapiError
478
+ ├── AuthenticationError 401 missing_key | invalid_key | key_expired | key_revoked
479
+ ├── PaymentRequiredError 402
480
+ │ └── KeyLimitExceededError 402 key_limit_exceeded: this KEY's spend limit
481
+ │ (limit, used, remaining, resets_at)
482
+ ├── PermissionDeniedError 403 any other code
483
+ │ ├── IpNotAllowedError 403 ip_not_allowed
484
+ │ ├── InsufficientPermissionsError 403 insufficient_permissions (API key on an ADMIN endpoint)
485
+ │ └── AccountSuspendedError 403 no code
486
+ ├── NotFoundError 404
487
+ ├── PayloadTooLargeError 413
488
+ ├── ValidationError 422 .errors = {"field": ["message", ...]}
489
+ │ ├── InsufficientBalanceError 422 insufficient_balance: the ACCOUNT is out of credit
490
+ │ └── ActiveKeyLimitReachedError 422 active_key_limit_reached
491
+ ├── RateLimitError 429 retry_after, limit_type
492
+ ├── ServerError 5xx
493
+ ├── NetworkError connection failure / timeout
494
+ ├── RealtimeError fatal WebSocket failure (.close_code)
495
+ └── JobTimeoutError polling exceeded max_wait (request_id; the job keeps running)
496
+ ```
497
+
498
+ ```python
499
+ from deapi_sdk import (
500
+ DeapiError, InsufficientBalanceError, KeyLimitExceededError, IpNotAllowedError,
501
+ InsufficientPermissionsError, ValidationError, RateLimitError, JobTimeoutError,
502
+ )
503
+
504
+ try:
505
+ result = client.images.generate(prompt="a cat", model="Flux1schnell").wait()
506
+ except InsufficientBalanceError:
507
+ print("Account out of credit, top up at https://deapi.ai")
508
+ except KeyLimitExceededError as e:
509
+ print(f"This key's limit is used up: {e.used}/{e.limit}, resets {e.resets_at}")
510
+ except IpNotAllowedError:
511
+ print("Your IP is not on the key's allowlist")
512
+ except InsufficientPermissionsError:
513
+ print("Use an ADMIN key for this endpoint")
514
+ except ValidationError as e:
515
+ print(e.message, e.errors)
516
+ except RateLimitError as e:
517
+ print(f"Rate limited, retry in {e.retry_after}s ({e.limit_type})")
518
+ except JobTimeoutError as e:
519
+ result = client.jobs.get(e.request_id).wait()
520
+ except DeapiError as e:
521
+ print(f"{e.status_code} {e.code}: {e.message}")
522
+ ```
523
+
524
+ Existing `except AccountSuspendedError` and `except ValidationError` handlers keep working.
525
+
526
+ **Retries** (up to `max_retries`):
527
+
528
+ - `GET` requests are retried on 429, 5xx and network errors.
529
+ - Job-creating `POST`s (and `PATCH` / `DELETE`) are retried **only** on 429 or when the connection
530
+ was never established. They are never retried after a timeout or a 5xx, so one job is never paid
531
+ for twice. After such an error, check whether the job exists before resubmitting.
532
+
533
+ ## Webhooks
534
+
535
+ Every job method accepts `webhook_url` (must be `https`) and `webhook_secret` (32-255 characters,
536
+ requires `webhook_url`), a per-job HMAC secret used to sign that job's deliveries:
537
+
538
+ ```python
539
+ import secrets
540
+
541
+ WEBHOOK_SECRET = secrets.token_urlsafe(48)
542
+
543
+ job = client.images.generate(
544
+ prompt="a cat", model="Flux1schnell",
545
+ webhook_url="https://example.com/webhooks/deapi",
546
+ webhook_secret=WEBHOOK_SECRET,
547
+ )
548
+ ```
549
+
550
+ Verify incoming requests with the same secret:
551
+
552
+ ```python
553
+ from deapi_sdk.webhook import construct_event, InvalidSignatureError
554
+
555
+ @app.post("/webhooks/deapi")
556
+ async def handle_webhook(request: Request):
557
+ payload = await request.body()
558
+
559
+ try:
560
+ event = construct_event(
561
+ payload=payload,
562
+ signature=request.headers["X-DeAPI-Signature"],
563
+ timestamp=request.headers["X-DeAPI-Timestamp"],
564
+ secret=WEBHOOK_SECRET,
565
+ tolerance=300, # reject events older than 5 minutes
566
+ )
567
+ except InvalidSignatureError:
568
+ return {"error": "Invalid signature"}, 403
569
+
570
+ if already_processed(event.delivery_id): # your own store, e.g. a set or a cache with a TTL
571
+ return {"ok": True}
572
+
573
+ if event.type == "job.completed":
574
+ print(f"Job {event.data.job_request_id} completed: {event.data.result_url}")
575
+ elif event.type == "job.failed":
576
+ data = event.data
577
+ print(f"Job {data.job_request_id} failed: {data.error_code} / {data.error_reason}, retryable={data.retryable}")
578
+
579
+ return {"ok": True}
580
+ ```
581
+
582
+ - Pass the **raw** request body to `construct_event()`; re-serialised JSON will not match the signature.
583
+ - A delivery replayed within `tolerance` still verifies, so deduplicate on `event.delivery_id`.
584
+ - `job.failed` carries `error_code`, `error_reason` (an open list: treat unknown values as
585
+ `PROCESSING_FAILED`), `retryable` and `refunded`. Failed jobs are reliably announced only by webhook
586
+ (and the job status endpoint), not over the real-time WebSocket.
587
+ - `job.completed` and `job.failed` carry `price` (`JobPrice`: `amount`, `is_estimated`). On completion it
588
+ may still be an estimate; for a failed job's final amount and refund state read
589
+ `client.jobs.status(request_id)`.
590
+
591
+ ## Upgrading to 0.5.0
592
+
593
+ 0.5.0 removes the video operations that deAPI API v2 no longer serves:
594
+
595
+ | Removed | Use instead |
596
+ |---------|-------------|
597
+ | `video.replace()` / `replace_price()`, type `VideoReplaceParams` | `video.animate()` with the character as `ref_images` and the source motion as `ref_videos` |
598
+ | `video.remove_background()` / `remove_background_price()`, `InferenceType.VIDEO_REMOVE_BG` | no replacement (`images.remove_background()` is unchanged) |
599
+
600
+ ## Upgrading to 0.4.0
601
+
602
+ 0.4.0 supports only deAPI API v2 and removes everything that existed for API v1. `api_version` /
603
+ `DEAPI_API_VERSION` still exist but accept only `"v2"` (the default); any other value raises `ValueError`.
604
+
605
+ | Removed | Use instead |
606
+ |---------|-------------|
607
+ | `transcription.from_video_url()`, `from_audio_url()`, `from_audio_file()`, `from_video_file()` (and `*_price`) | `transcription.create(source_url=... \| source_file=..., ...)` / `create_price(...)` |
608
+ | `prompts.enhance_image()`, `enhance_video()`, `enhance_speech()`, `enhance_image2image()` (and `*_price`) | `prompts.enhance(prompt=..., type=..., model_slug=...)` / `enhance_price(...)` |
609
+ | `prompts.samples()` / `samples_price()` | no replacement (already raised `NotImplementedError`) |
610
+ | Types `VideoToTextParams`, `AudioToTextParams`, `AudioFileToTextParams`, `VideoFileToTextParams`, `EnhanceSpeechPromptResult`, `SamplePromptResult` | no replacement |
611
+ | Modules `deapi_sdk.resources.v1` / `.v2`, `deapi_sdk.types.v1` / `.v2` | `deapi_sdk.resources`, `deapi_sdk.types` (top-level `from deapi_sdk import ...` names are unchanged) |
612
+
613
+ `client.account` and `client.keys` are always available.
614
+
615
+ ## API Reference
616
+
617
+ See [docs/api-reference.md](https://github.com/deapi-ai/deapi-python-sdk/blob/main/docs/api-reference.md) for method signatures, parameters and return
618
+ types, and [docs.deapi.ai](https://docs.deapi.ai) for the HTTP API.
619
+
620
+ ## Examples
621
+
622
+ The [`examples/`](https://github.com/deapi-ai/deapi-python-sdk/tree/main/examples) directory contains runnable scripts:
623
+
624
+ | File | Description |
625
+ |------|-------------|
626
+ | [`basic_image.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/basic_image.py) | Image generation, transformation, upscale |
627
+ | [`async_batch.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/async_batch.py) | Concurrent async job submission |
628
+ | [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription with JSON and plain-text transcripts |
629
+ | [`tts_and_audio.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/tts_and_audio.py) | Text-to-speech and music generation |
630
+ | [`video_generation.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/video_generation.py) | Text-to-video and image-to-video |
631
+ | [`realtime_status.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/realtime_status.py) | Live job progress over WebSocket |
632
+ | [`webhook_server.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/webhook_server.py) | Flask webhook receiver with signature verification |
633
+ | [`error_handling.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/error_handling.py) | Error handling patterns and best practices |
634
+
635
+ ## Requirements
636
+
637
+ - Python 3.11+
638
+ - [`httpx`](https://www.python-httpx.org/) >= 0.25.0
639
+ - [`pydantic`](https://docs.pydantic.dev/) >= 2.6.0
640
+ - [`websockets`](https://websockets.readthedocs.io/) 17.x (optional, `ws` extra)
641
+
642
+ ## License
643
+
644
+ MIT — see [LICENSE](https://github.com/deapi-ai/deapi-python-sdk/blob/main/LICENSE) for details.