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
deapi_sdk/_cards.py ADDED
@@ -0,0 +1,313 @@
1
+ """Fill unset model parameters from the model card (``info.defaults``).
2
+
3
+ The API still requires several card-driven parameters (width, height, seed, steps, ...),
4
+ so when the caller leaves one unset it is taken from the model's card. The whole
5
+ catalogue is fetched lazily (on the first call that needs it) and cached per HTTP client
6
+ for ``_CARD_TTL`` seconds; a lookup of a slug missing from the cache refreshes it (at most
7
+ once per ``_MISS_COOLDOWN`` seconds). Defaulting never raises: if the catalogue cannot be
8
+ fetched, or the model is not in it, no card value is filled and the API answers with its
9
+ normal validation error. A failed fetch (any error, auth errors included, as they are
10
+ per-request and may be fixed later) is logged and retried after ``_RETRY_COOLDOWN`` seconds.
11
+
12
+ When the card has no default for a key but its ``limits`` pin it (``min_X == max_X``), that
13
+ value is used; nothing is derived when min and max differ.
14
+
15
+ Rules (same as the deAPI MCP server): a value the caller set always wins; a key the card
16
+ does not default is left out; free-text fields (prompt, negative_prompt, ...) are never
17
+ filled; ``seed`` falls back to ``-1`` (random) where the API requires it, even without a card.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ import threading
24
+ import time
25
+ from collections.abc import Iterable
26
+ from typing import Any
27
+
28
+ logger = logging.getLogger("deapi")
29
+
30
+ _PAGE_SIZE = 50 # the API caps ``limit`` at 50
31
+ _MAX_PAGES = 50 # safety bound on pagination
32
+ _RANDOM_SEED = -1
33
+ _RETRY_COOLDOWN = 60.0 # seconds before a failed catalogue fetch is retried
34
+ _CARD_TTL = 300.0 # seconds before the cached catalogue is refreshed
35
+ _MISS_COOLDOWN = 30.0 # min seconds between catalogue refreshes triggered by an unknown slug
36
+ _CREATE_LOCK = threading.Lock() # guards creation of a client's cache object
37
+
38
+ # Fillable keys per endpoint family (spec-required card-driven params; names match the card).
39
+ IMAGE_KEYS = ("width", "height", "steps")
40
+ VIDEO_KEYS = ("width", "height", "frames", "fps", "steps")
41
+ TTS_KEYS = ("lang", "speed", "format", "sample_rate")
42
+ MUSIC_KEYS = ("format", "inference_steps", "guidance_scale")
43
+ MUSIC_PRICE_KEYS = ("inference_steps",)
44
+
45
+ # Request field -> card limit name (``min_X``/``max_X``) where they differ.
46
+ _LIMIT_NAMES = {"inference_steps": "steps", "guidance_scale": "guidance"}
47
+
48
+ _FALSE_VALUES = ("0", "false", "no", "off")
49
+
50
+
51
+ def parse_flag(raw: str | None, default: bool = True) -> bool:
52
+ """Parse a boolean env value: "0"/"false"/"no"/"off" disable, anything else enables."""
53
+ if raw is None or not raw.strip():
54
+ return default
55
+ return raw.strip().lower() not in _FALSE_VALUES
56
+
57
+
58
+ def fill_from_card(
59
+ payload: dict[str, Any], defaults: dict[str, Any], keys: Iterable[str]
60
+ ) -> dict[str, Any]:
61
+ """Return ``payload`` with each unset key in ``keys`` taken from ``defaults``.
62
+
63
+ A key is unset when it is missing or ``None``; card values that are ``None`` are skipped.
64
+ """
65
+ for key in keys:
66
+ if payload.get(key) is None and defaults.get(key) is not None:
67
+ payload[key] = defaults[key]
68
+ return payload
69
+
70
+
71
+ class _CardCache:
72
+ """slug -> ``info`` dict for one HTTP client, with a TTL and refresh on a slug miss."""
73
+
74
+ def __init__(self) -> None:
75
+ self.cards: dict[str, dict[str, Any]] | None = None
76
+ self.fetched_at = 0.0 # monotonic time of the last successful fetch
77
+ self.retry_at = 0.0 # monotonic time before which a failed fetch is not retried
78
+ self.tlock = threading.Lock() # serialises the sync fetch
79
+ self.lock: Any = None # asyncio.Lock, created lazily inside a running loop
80
+ self.lock_loop: Any = None # the loop ``lock`` belongs to
81
+
82
+ def needs_fetch(self, model: Any = None) -> bool:
83
+ """True when the catalogue is absent, older than the TTL, or ``model`` is not in it."""
84
+ now = time.monotonic()
85
+ if now < self.retry_at:
86
+ return False
87
+ if self.cards is None or now - self.fetched_at >= _CARD_TTL:
88
+ return True
89
+ return model is not None and model not in self.cards and now - self.fetched_at >= _MISS_COOLDOWN
90
+
91
+ def record_success(self, cards: dict[str, dict[str, Any]]) -> None:
92
+ self.cards = cards
93
+ self.fetched_at = time.monotonic()
94
+
95
+ def record_failure(self, exc: Exception) -> None:
96
+ """Log a failed fetch and hold off retrying for a cooldown; any stale cards are kept."""
97
+ self.retry_at = time.monotonic() + _RETRY_COOLDOWN
98
+ logger.warning(
99
+ "Could not load the model catalogue (%s: %s); model card defaults %s "
100
+ "(will retry in %d s).",
101
+ type(exc).__name__, exc,
102
+ "may be stale" if self.cards is not None else
103
+ "were not applied, so unset parameters (width, height, steps, ...) will be sent empty",
104
+ int(_RETRY_COOLDOWN),
105
+ )
106
+
107
+ def values(self, model: Any, keys: Iterable[str]) -> dict[str, Any] | None:
108
+ """Card values for ``keys``: ``info.defaults``, else a value pinned by ``info.limits``.
109
+
110
+ A limit pins a value when ``min_X == max_X`` (e.g. fixed steps or guidance). Returns
111
+ ``None`` when the model/catalogue is unknown.
112
+ """
113
+ if self.cards is None or model not in self.cards:
114
+ return None
115
+ info = self.cards[model]
116
+ defaults = info.get("defaults")
117
+ limits = info.get("limits")
118
+ values = dict(defaults) if isinstance(defaults, dict) else {}
119
+ if isinstance(limits, dict):
120
+ for key in keys:
121
+ if values.get(key) is None:
122
+ name = _LIMIT_NAMES.get(key, key)
123
+ lo, hi = limits.get(f"min_{name}"), limits.get(f"max_{name}")
124
+ if lo is not None and lo == hi:
125
+ values[key] = lo
126
+ return values
127
+
128
+
129
+ def _cache(client: Any) -> _CardCache:
130
+ cache = getattr(client, "_card_cache", None)
131
+ if cache is None:
132
+ with _CREATE_LOCK:
133
+ cache = getattr(client, "_card_cache", None)
134
+ if cache is None:
135
+ cache = _CardCache()
136
+ client._card_cache = cache
137
+ return cache
138
+
139
+
140
+ def _ingest(models: Any, store: dict[str, dict[str, Any]]) -> None:
141
+ for model in models:
142
+ slug = model.get("slug")
143
+ if isinstance(slug, str):
144
+ info = model.get("info")
145
+ store[slug] = info if isinstance(info, dict) else {}
146
+
147
+
148
+ def _fill_tts_mode(cache: _CardCache, payload: dict[str, Any]) -> None:
149
+ """Fill ``mode`` / ``voice`` of a TTS request from the model card.
150
+
151
+ The API treats a missing ``mode`` as ``custom_voice`` (which then needs ``voice``), so a
152
+ voice-design or voice-clone only model fails unless the mode is named, and a custom-voice
153
+ model fails without a ``voice``. Explicit values always win.
154
+ """
155
+ if cache.cards is None or payload.get("model") not in cache.cards:
156
+ return
157
+ info = cache.cards[payload["model"]]
158
+ _features = info.get("features")
159
+ features = _features if isinstance(_features, dict) else {}
160
+ _defaults = info.get("defaults")
161
+ defaults = _defaults if isinstance(_defaults, dict) else {}
162
+ if payload.get("mode") is None and features.get("supports_custom_voice") is False:
163
+ if features.get("supports_voice_design") and not features.get("supports_voice_clone"):
164
+ payload["mode"] = "voice_design"
165
+ elif features.get("supports_voice_clone") and not features.get("supports_voice_design"):
166
+ payload["mode"] = "voice_clone"
167
+ if (
168
+ (payload.get("mode") or "custom_voice") == "custom_voice"
169
+ and payload.get("voice") is None
170
+ and defaults.get("voice") is not None
171
+ ):
172
+ payload["voice"] = defaults["voice"]
173
+
174
+
175
+ def _apply(
176
+ cache: _CardCache, payload: dict[str, Any], keys: Iterable[str], seed: bool, form: bool,
177
+ tts: bool = False,
178
+ ) -> dict[str, Any]:
179
+ keys = tuple(keys)
180
+ unset = {k for k in (*keys, "seed") if payload.get(k) is None}
181
+ values = cache.values(payload.get("model"), keys)
182
+ if values is not None:
183
+ fill_from_card(payload, values, keys)
184
+ if tts:
185
+ _fill_tts_mode(cache, payload)
186
+ if seed and payload.get("seed") is None: # not card-derived: needs no catalogue
187
+ payload["seed"] = _RANDOM_SEED
188
+ if form: # multipart fields are strings
189
+ for key in unset:
190
+ if payload.get(key) is not None:
191
+ payload[key] = str(payload[key])
192
+ return payload
193
+
194
+
195
+ def _wanted(client: Any, payload: dict[str, Any]) -> bool:
196
+ return bool(getattr(client._config, "fill_model_defaults", True)) and bool(payload.get("model"))
197
+
198
+
199
+ def _needs_card(payload: dict[str, Any], keys: Iterable[str], tts: bool) -> bool:
200
+ """True when some card-driven field is still unset, so the catalogue is worth fetching."""
201
+ if any(payload.get(k) is None for k in keys):
202
+ return True
203
+ return tts and (payload.get("mode") is None or payload.get("voice") is None)
204
+
205
+
206
+ def _has_next(resp: Any, page: int) -> bool:
207
+ """Whether another page follows ``page``.
208
+
209
+ ``meta.last_page`` is authoritative when present. Without it the only safe signal is a full
210
+ page (``_PAGE_SIZE`` items): a shorter one is the last. Never stop on a short page when
211
+ ``last_page`` says more exist, or the catalogue comes back incomplete.
212
+ """
213
+ if not resp["data"] or page >= _MAX_PAGES:
214
+ return False
215
+ meta = resp.get("meta")
216
+ if isinstance(meta, dict) and isinstance(meta.get("last_page"), int) and meta["last_page"] > 0:
217
+ return bool(page < meta["last_page"])
218
+ return len(resp["data"]) >= _PAGE_SIZE
219
+
220
+
221
+ def _fetch_sync(client: Any) -> dict[str, dict[str, Any]]:
222
+ store: dict[str, dict[str, Any]] = {}
223
+ page = 1
224
+ while True:
225
+ resp = client.get(client._resolve_endpoint("models"), params={"limit": _PAGE_SIZE, "page": page})
226
+ _ingest(resp["data"], store)
227
+ if not _has_next(resp, page):
228
+ return store
229
+ page += 1
230
+
231
+
232
+ async def _fetch_async(client: Any) -> dict[str, dict[str, Any]]:
233
+ store: dict[str, dict[str, Any]] = {}
234
+ page = 1
235
+ while True:
236
+ resp = await client.get(client._resolve_endpoint("models"), params={"limit": _PAGE_SIZE, "page": page})
237
+ _ingest(resp["data"], store)
238
+ if not _has_next(resp, page):
239
+ return store
240
+ page += 1
241
+
242
+
243
+ def _ensure_sync(client: Any, model: Any) -> _CardCache:
244
+ cache = _cache(client)
245
+ if cache.needs_fetch(model):
246
+ with cache.tlock:
247
+ if cache.needs_fetch(model):
248
+ try:
249
+ cache.record_success(_fetch_sync(client))
250
+ except Exception as exc:
251
+ cache.record_failure(exc)
252
+ return cache
253
+
254
+
255
+ async def _ensure_async(client: Any, model: Any) -> _CardCache:
256
+ cache = _cache(client)
257
+ if cache.needs_fetch(model):
258
+ import asyncio
259
+
260
+ loop = asyncio.get_running_loop()
261
+ if cache.lock is None or cache.lock_loop is not loop: # an asyncio.Lock is bound to one loop
262
+ cache.lock, cache.lock_loop = asyncio.Lock(), loop
263
+ async with cache.lock:
264
+ if cache.needs_fetch(model):
265
+ try:
266
+ cache.record_success(await _fetch_async(client))
267
+ except Exception as exc:
268
+ cache.record_failure(exc)
269
+ return cache
270
+
271
+
272
+ def get_card(client: Any, slug: str) -> dict[str, Any] | None:
273
+ """The model's card (``info`` dict) from the cached catalogue, or ``None`` if unknown.
274
+
275
+ Loads the catalogue on first use, refreshes it after the TTL and when ``slug`` is missing.
276
+ ``client`` is the sync HTTP client (``DeapiClient._http_client``).
277
+ """
278
+ cache = _ensure_sync(client, slug)
279
+ return cache.cards.get(slug) if cache.cards is not None else None
280
+
281
+
282
+ async def aget_card(client: Any, slug: str) -> dict[str, Any] | None:
283
+ """Async twin of :func:`get_card`."""
284
+ cache = await _ensure_async(client, slug)
285
+ return cache.cards.get(slug) if cache.cards is not None else None
286
+
287
+
288
+ def fill_payload(
289
+ client: Any, payload: dict[str, Any], keys: Iterable[str], *, seed: bool = False, form: bool = False,
290
+ tts: bool = False,
291
+ ) -> dict[str, Any]:
292
+ """Fill unset ``keys`` of a request payload from the model card (sync client).
293
+
294
+ ``seed=True`` also defaults an unset ``seed`` to -1 (random). ``form=True`` stringifies
295
+ the filled values for multipart bodies. Mutates and returns ``payload``.
296
+ """
297
+ if not _wanted(client, payload):
298
+ return payload
299
+ keys = tuple(keys)
300
+ cache = _ensure_sync(client, payload.get("model")) if _needs_card(payload, keys, tts) else _cache(client)
301
+ return _apply(cache, payload, keys, seed, form, tts)
302
+
303
+
304
+ async def afill_payload(
305
+ client: Any, payload: dict[str, Any], keys: Iterable[str], *, seed: bool = False, form: bool = False,
306
+ tts: bool = False,
307
+ ) -> dict[str, Any]:
308
+ """Async twin of :func:`fill_payload` (uses the async HTTP client)."""
309
+ if not _wanted(client, payload):
310
+ return payload
311
+ keys = tuple(keys)
312
+ cache = await _ensure_async(client, payload.get("model")) if _needs_card(payload, keys, tts) else _cache(client)
313
+ return _apply(cache, payload, keys, seed, form, tts)