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/_client.py ADDED
@@ -0,0 +1,411 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import math
5
+ import time
6
+ from collections.abc import Mapping, Sequence
7
+ from datetime import UTC, datetime
8
+ from email.utils import parsedate_to_datetime
9
+ from typing import IO, Any, TypeAlias
10
+
11
+ import httpx
12
+
13
+ from deapi_sdk._config import ClientConfig
14
+ from deapi_sdk._constants import ENDPOINTS
15
+ from deapi_sdk._exceptions import (
16
+ AccountSuspendedError,
17
+ ActiveKeyLimitReachedError,
18
+ AuthenticationError,
19
+ DeapiError,
20
+ InsufficientBalanceError,
21
+ InsufficientPermissionsError,
22
+ IpNotAllowedError,
23
+ KeyLimitExceededError,
24
+ NetworkError,
25
+ NotFoundError,
26
+ PayloadTooLargeError,
27
+ PaymentRequiredError,
28
+ PermissionDeniedError,
29
+ RateLimitError,
30
+ ServerError,
31
+ ValidationError,
32
+ )
33
+
34
+ # Multipart file parts accepted by the low-level ``request()`` / ``post()``, mirroring what httpx
35
+ # accepts (a mapping or a sequence of (field, part) pairs; content as bytes or a binary file object,
36
+ # optionally with a filename, content type and headers). Resource methods build these from
37
+ # ``FileInput`` via ``normalize_file``; a plain ``str`` is deliberately not allowed as content.
38
+ FileContent: TypeAlias = IO[bytes] | bytes
39
+ FilePart: TypeAlias = (
40
+ FileContent
41
+ | tuple[str | None, FileContent]
42
+ | tuple[str | None, FileContent, str | None]
43
+ | tuple[str | None, FileContent, str | None, Mapping[str, str]]
44
+ )
45
+ RequestFiles: TypeAlias = Mapping[str, FilePart] | Sequence[tuple[str, FilePart]]
46
+
47
+
48
+ class BaseClient:
49
+ """Shared logic for sync and async HTTP clients."""
50
+
51
+ def __init__(self, config: ClientConfig) -> None:
52
+ self._config = config
53
+
54
+ def _resolve_endpoint(self, operation: str) -> str:
55
+ """Resolve an operation name to a full URL."""
56
+ path = ENDPOINTS.get(operation)
57
+ if path is None:
58
+ raise DeapiError(f"Unknown API operation '{operation}'")
59
+ return f"{self._config.base_url}{self._config.api_prefix}/{path}"
60
+
61
+ def _default_headers(self) -> dict[str, str]:
62
+ return {
63
+ "Authorization": f"Bearer {self._config.api_key}",
64
+ "Accept": "application/json",
65
+ "User-Agent": self._config._user_agent,
66
+ }
67
+
68
+ @staticmethod
69
+ def _parse_retry_after(value: str | None) -> float:
70
+ """Parse a Retry-After header (seconds or HTTP-date) into seconds; garbage -> 0.0."""
71
+ if not value:
72
+ return 0.0
73
+ value = value.strip()
74
+ try:
75
+ seconds = float(value)
76
+ except ValueError:
77
+ try:
78
+ when = parsedate_to_datetime(value)
79
+ except (TypeError, ValueError, IndexError):
80
+ return 0.0
81
+ if when.tzinfo is None:
82
+ when = when.replace(tzinfo=UTC)
83
+ return max((when - datetime.now(UTC)).total_seconds(), 0.0)
84
+ if math.isnan(seconds) or math.isinf(seconds):
85
+ return 0.0
86
+ return max(seconds, 0.0)
87
+
88
+ @staticmethod
89
+ def _to_float(value: Any) -> float | None:
90
+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):
91
+ return None
92
+ try:
93
+ return float(value)
94
+ except ValueError:
95
+ return None
96
+
97
+ def _raise_for_status(self, response: httpx.Response) -> None:
98
+ """Map HTTP error responses to typed exceptions."""
99
+ if response.is_success:
100
+ return
101
+
102
+ status = response.status_code
103
+ try:
104
+ parsed = response.json()
105
+ except Exception:
106
+ parsed = None
107
+ body: dict[str, Any] = parsed if isinstance(parsed, dict) else {}
108
+
109
+ message: Any = body.get("message")
110
+ if not isinstance(message, str) or not message:
111
+ message = body.get("error")
112
+ if not isinstance(message, str) or not message:
113
+ message = response.text or f"HTTP {status}"
114
+
115
+ raw_code = body.get("code")
116
+ code = raw_code if isinstance(raw_code, str) and raw_code else None
117
+ kwargs: dict[str, Any] = {"status_code": status, "body": body, "code": code}
118
+
119
+ if status == 401:
120
+ raise AuthenticationError(message, **kwargs)
121
+
122
+ if status == 402:
123
+ if code == "key_limit_exceeded":
124
+ resets_at = body.get("resets_at")
125
+ raise KeyLimitExceededError(
126
+ message,
127
+ **kwargs,
128
+ limit=self._to_float(body.get("limit")),
129
+ used=self._to_float(body.get("used")),
130
+ remaining=self._to_float(body.get("remaining")),
131
+ resets_at=resets_at if isinstance(resets_at, str) else None,
132
+ )
133
+ raise PaymentRequiredError(message, **kwargs)
134
+
135
+ if status == 403:
136
+ if code == "ip_not_allowed":
137
+ raise IpNotAllowedError(message, **kwargs)
138
+ if code == "insufficient_permissions":
139
+ raise InsufficientPermissionsError(message, **kwargs)
140
+ if code is None:
141
+ # Only a code-less 403 means the account is suspended.
142
+ raise AccountSuspendedError(message, **kwargs)
143
+ raise PermissionDeniedError(message, **kwargs)
144
+
145
+ if status == 404:
146
+ raise NotFoundError(message, **kwargs)
147
+
148
+ if status == 413:
149
+ raise PayloadTooLargeError(message, **kwargs)
150
+
151
+ if status == 422:
152
+ errors = body.get("errors")
153
+ if code == "insufficient_balance" or (isinstance(errors, dict) and "balance" in errors):
154
+ raise InsufficientBalanceError(message, **kwargs, errors=errors)
155
+ if code == "active_key_limit_reached":
156
+ raise ActiveKeyLimitReachedError(message, **kwargs, errors=errors)
157
+ raise ValidationError(message, **kwargs, errors=errors)
158
+
159
+ if status == 429:
160
+ raise RateLimitError(
161
+ message,
162
+ **kwargs,
163
+ retry_after=self._parse_retry_after(response.headers.get("Retry-After")),
164
+ limit_type=response.headers.get("X-RateLimit-Type", ""),
165
+ )
166
+
167
+ if status >= 500:
168
+ raise ServerError(message, **kwargs)
169
+
170
+ raise DeapiError(message, **kwargs)
171
+
172
+ @staticmethod
173
+ def _parse_success(response: httpx.Response) -> Any:
174
+ """Parse a 2xx body: JSON, or ``{}`` when empty (e.g. 204)."""
175
+ if not response.content:
176
+ return {}
177
+ try:
178
+ return response.json()
179
+ except ValueError as exc:
180
+ raise DeapiError(
181
+ f"Invalid JSON in response (HTTP {response.status_code})",
182
+ status_code=response.status_code,
183
+ ) from exc
184
+
185
+ @staticmethod
186
+ def _wrap_transport_error(exc: httpx.TransportError) -> NetworkError:
187
+ err = NetworkError(str(exc))
188
+ # Connection never established -> request provably never reached the server.
189
+ err._never_sent = isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)) # type: ignore[attr-defined]
190
+ return err
191
+
192
+ def _should_retry(self, exc: Exception, attempt: int, method: str = "GET") -> float | None:
193
+ """Determine if a request should be retried and return wait time in seconds.
194
+
195
+ GET/HEAD/OPTIONS are retried on 429, 5xx and network errors. Other methods
196
+ (POST/PATCH/DELETE) are retried only if the request provably did not reach
197
+ processing: 429, or a connection that was never established. Retrying anything
198
+ else could resubmit (and double-charge) a job the server already accepted.
199
+
200
+ Returns None if no retry should happen.
201
+ """
202
+ if attempt >= self._config.max_retries:
203
+ return None
204
+
205
+ if isinstance(exc, RateLimitError):
206
+ # Honour Retry-After, but never sleep longer than the configured cap:
207
+ # a long or day-bucket value (seconds or a far-future HTTP-date) must
208
+ # not park the request. The raw value stays on exc.retry_after.
209
+ return min(max(exc.retry_after, 1.0), self._config.max_retry_after)
210
+
211
+ safe = method.upper() in ("GET", "HEAD", "OPTIONS")
212
+
213
+ if isinstance(exc, ServerError):
214
+ return min(2.0 ** attempt, 8.0) if safe else None
215
+
216
+ if isinstance(exc, NetworkError) and (safe or getattr(exc, "_never_sent", False)):
217
+ return min(2.0 ** attempt, 8.0)
218
+
219
+ return None
220
+
221
+
222
+ class SyncHTTPClient(BaseClient):
223
+ """Synchronous HTTP client with retry logic.
224
+
225
+ An ``httpx.Client`` may be injected so many per-user clients share one
226
+ connection pool. Auth is sent per request (not baked into the transport),
227
+ so a shared client serves every user with the right token. A caller-injected
228
+ client is not closed by :meth:`close` unless ``owns_http_client=True``.
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ config: ClientConfig,
234
+ http_client: httpx.Client | None = None,
235
+ *,
236
+ owns_http_client: bool | None = None,
237
+ ) -> None:
238
+ super().__init__(config)
239
+ self._headers = self._default_headers()
240
+ if http_client is not None:
241
+ self._http = http_client
242
+ self._owns_http = bool(owns_http_client)
243
+ else:
244
+ self._http = httpx.Client(timeout=config.timeout)
245
+ self._owns_http = True if owns_http_client is None else owns_http_client
246
+
247
+ @property
248
+ def owns_http_client(self) -> bool:
249
+ return self._owns_http
250
+
251
+ def close(self) -> None:
252
+ # Only close a transport we created; never close one the caller injected.
253
+ if self._owns_http:
254
+ self._http.close()
255
+
256
+ def request(
257
+ self,
258
+ method: str,
259
+ url: str,
260
+ *,
261
+ json: dict[str, Any] | None = None,
262
+ data: dict[str, Any] | None = None,
263
+ files: RequestFiles | None = None,
264
+ params: dict[str, Any] | None = None,
265
+ ) -> Any:
266
+ last_exc: Exception | None = None
267
+
268
+ for attempt in range(self._config.max_retries + 1):
269
+ try:
270
+ response = self._http.request(
271
+ method,
272
+ url,
273
+ json=json,
274
+ data=data,
275
+ files=files,
276
+ params=params,
277
+ headers=self._headers,
278
+ )
279
+ self._raise_for_status(response)
280
+ return self._parse_success(response)
281
+ except (RateLimitError, ServerError, NetworkError) as exc:
282
+ last_exc = exc
283
+ wait = self._should_retry(exc, attempt, method)
284
+ if wait is not None:
285
+ time.sleep(wait)
286
+ continue
287
+ raise
288
+ except httpx.TransportError as exc:
289
+ last_exc = self._wrap_transport_error(exc)
290
+ wait = self._should_retry(last_exc, attempt, method)
291
+ if wait is not None:
292
+ time.sleep(wait)
293
+ continue
294
+ raise last_exc from exc
295
+
296
+ raise last_exc # type: ignore[misc]
297
+
298
+ def get(self, url: str, *, params: dict[str, Any] | None = None) -> Any:
299
+ return self.request("GET", url, params=params)
300
+
301
+ def post(
302
+ self,
303
+ url: str,
304
+ *,
305
+ json: dict[str, Any] | None = None,
306
+ data: dict[str, Any] | None = None,
307
+ files: RequestFiles | None = None,
308
+ ) -> Any:
309
+ return self.request("POST", url, json=json, data=data, files=files)
310
+
311
+ def patch(self, url: str, *, json: dict[str, Any] | None = None) -> Any:
312
+ return self.request("PATCH", url, json=json)
313
+
314
+ def delete(self, url: str) -> Any:
315
+ return self.request("DELETE", url)
316
+
317
+
318
+ class AsyncHTTPClient(BaseClient):
319
+ """Asynchronous HTTP client with retry logic.
320
+
321
+ An ``httpx.AsyncClient`` may be injected so many per-user clients share one
322
+ connection pool. Auth is sent per request (not baked into the transport),
323
+ so a shared client serves every user with the right token. A caller-injected
324
+ client is not closed by :meth:`close` unless ``owns_http_client=True``.
325
+ """
326
+
327
+ def __init__(
328
+ self,
329
+ config: ClientConfig,
330
+ http_client: httpx.AsyncClient | None = None,
331
+ *,
332
+ owns_http_client: bool | None = None,
333
+ ) -> None:
334
+ super().__init__(config)
335
+ self._headers = self._default_headers()
336
+ if http_client is not None:
337
+ self._http = http_client
338
+ self._owns_http = bool(owns_http_client)
339
+ else:
340
+ self._http = httpx.AsyncClient(timeout=config.timeout)
341
+ self._owns_http = True if owns_http_client is None else owns_http_client
342
+
343
+ @property
344
+ def owns_http_client(self) -> bool:
345
+ return self._owns_http
346
+
347
+ async def close(self) -> None:
348
+ # Only close a transport we created; never close one the caller injected.
349
+ if self._owns_http:
350
+ await self._http.aclose()
351
+
352
+ async def request(
353
+ self,
354
+ method: str,
355
+ url: str,
356
+ *,
357
+ json: dict[str, Any] | None = None,
358
+ data: dict[str, Any] | None = None,
359
+ files: RequestFiles | None = None,
360
+ params: dict[str, Any] | None = None,
361
+ ) -> Any:
362
+ last_exc: Exception | None = None
363
+
364
+ for attempt in range(self._config.max_retries + 1):
365
+ try:
366
+ response = await self._http.request(
367
+ method,
368
+ url,
369
+ json=json,
370
+ data=data,
371
+ files=files,
372
+ params=params,
373
+ headers=self._headers,
374
+ )
375
+ self._raise_for_status(response)
376
+ return self._parse_success(response)
377
+ except (RateLimitError, ServerError, NetworkError) as exc:
378
+ last_exc = exc
379
+ wait = self._should_retry(exc, attempt, method)
380
+ if wait is not None:
381
+ await asyncio.sleep(wait)
382
+ continue
383
+ raise
384
+ except httpx.TransportError as exc:
385
+ last_exc = self._wrap_transport_error(exc)
386
+ wait = self._should_retry(last_exc, attempt, method)
387
+ if wait is not None:
388
+ await asyncio.sleep(wait)
389
+ continue
390
+ raise last_exc from exc
391
+
392
+ raise last_exc # type: ignore[misc]
393
+
394
+ async def get(self, url: str, *, params: dict[str, Any] | None = None) -> Any:
395
+ return await self.request("GET", url, params=params)
396
+
397
+ async def post(
398
+ self,
399
+ url: str,
400
+ *,
401
+ json: dict[str, Any] | None = None,
402
+ data: dict[str, Any] | None = None,
403
+ files: RequestFiles | None = None,
404
+ ) -> Any:
405
+ return await self.request("POST", url, json=json, data=data, files=files)
406
+
407
+ async def patch(self, url: str, *, json: dict[str, Any] | None = None) -> Any:
408
+ return await self.request("PATCH", url, json=json)
409
+
410
+ async def delete(self, url: str) -> Any:
411
+ return await self.request("DELETE", url)
deapi_sdk/_config.py ADDED
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass, field
5
+
6
+ from deapi_sdk._cards import parse_flag
7
+ from deapi_sdk._constants import API_PREFIX, API_VERSION
8
+ from deapi_sdk._version import __version__
9
+
10
+ _DEFAULT_BASE_URL = "https://api.deapi.ai"
11
+ _DEFAULT_TIMEOUT = 30.0
12
+ _DEFAULT_MAX_RETRIES = 3
13
+ # Upper bound on how long we actually sleep for a 429 `Retry-After`, regardless of
14
+ # the value (or absolute HTTP-date) the server sends. Keeps a long/day-bucket
15
+ # Retry-After from parking a request for minutes/hours; the true server value is
16
+ # still carried on the raised RateLimitError for the caller to inspect.
17
+ _DEFAULT_MAX_RETRY_AFTER = 60.0
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ClientConfig:
22
+ api_key: str = field(repr=False)
23
+ base_url: str = _DEFAULT_BASE_URL
24
+ timeout: float = _DEFAULT_TIMEOUT
25
+ max_retries: int = _DEFAULT_MAX_RETRIES
26
+ api_version: str = API_VERSION
27
+ fill_model_defaults: bool = True
28
+ max_retry_after: float = _DEFAULT_MAX_RETRY_AFTER
29
+ _user_agent: str = field(init=False, default=f"deapi-sdk/{__version__}")
30
+
31
+ @classmethod
32
+ def from_env(
33
+ cls,
34
+ *,
35
+ api_key: str | None = None,
36
+ base_url: str | None = None,
37
+ timeout: float | None = None,
38
+ max_retries: int | None = None,
39
+ api_version: str | None = None,
40
+ fill_model_defaults: bool | None = None,
41
+ max_retry_after: float | None = None,
42
+ ) -> ClientConfig:
43
+ resolved_key = (api_key or os.environ.get("DEAPI_API_KEY", "")).strip()
44
+ if not resolved_key:
45
+ raise ValueError(
46
+ "API key is required. Pass api_key= or set the DEAPI_API_KEY environment variable."
47
+ )
48
+ return cls(
49
+ api_key=resolved_key,
50
+ base_url=base_url or os.environ.get("DEAPI_BASE_URL", _DEFAULT_BASE_URL),
51
+ timeout=timeout if timeout is not None else _DEFAULT_TIMEOUT,
52
+ max_retries=max_retries if max_retries is not None else _DEFAULT_MAX_RETRIES,
53
+ api_version=_check_api_version(api_version or os.environ.get("DEAPI_API_VERSION")),
54
+ fill_model_defaults=(
55
+ fill_model_defaults
56
+ if fill_model_defaults is not None
57
+ else parse_flag(os.environ.get("DEAPI_FILL_MODEL_DEFAULTS"))
58
+ ),
59
+ max_retry_after=(
60
+ max_retry_after if max_retry_after is not None else _DEFAULT_MAX_RETRY_AFTER
61
+ ),
62
+ )
63
+
64
+ @property
65
+ def api_prefix(self) -> str:
66
+ return API_PREFIX
67
+
68
+
69
+ def _check_api_version(value: str | None) -> str:
70
+ """Only deAPI API v2 is supported; anything else is a configuration error."""
71
+ version = (value or API_VERSION).strip().lower()
72
+ if version != API_VERSION:
73
+ raise ValueError(
74
+ f"Unsupported API version {value!r}: this SDK supports deAPI API {API_VERSION} only "
75
+ "(API v1 support was removed in 0.4.0). Omit api_version / DEAPI_API_VERSION or set it to 'v2'."
76
+ )
77
+ return version
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ # The SDK targets deAPI API v2. Every endpoint lives under this prefix.
4
+ API_VERSION = "v2"
5
+ API_PREFIX = "/api/v2"
6
+
7
+ # Endpoint paths relative to API_PREFIX, keyed by a stable operation name.
8
+ ENDPOINTS: dict[str, str] = {
9
+ # Images
10
+ "txt2img": "images/generations",
11
+ "txt2img_price": "images/generations/price",
12
+ "img2img": "images/edits",
13
+ "img2img_price": "images/edits/price",
14
+ "img_upscale": "images/upscales",
15
+ "img_upscale_price": "images/upscales/price",
16
+ "img_rmbg": "images/background-removals",
17
+ "img_rmbg_price": "images/background-removals/price",
18
+ # Audio
19
+ "txt2audio": "audio/speech",
20
+ "txt2audio_price": "audio/speech/price",
21
+ "txt2music": "audio/music",
22
+ "txt2music_price": "audio/music/price",
23
+ # Video
24
+ "txt2video": "videos/generations",
25
+ "txt2video_price": "videos/generations/price",
26
+ "img2video": "videos/animations",
27
+ "img2video_price": "videos/animations/price",
28
+ "vid_upscale": "videos/upscales",
29
+ "vid_upscale_price": "videos/upscales/price",
30
+ "aud2video": "videos/audio-syncs",
31
+ "aud2video_price": "videos/audio-syncs/price",
32
+ "vid_description": "videos/descriptions",
33
+ "vid_description_price": "videos/descriptions/price",
34
+ # Transcription (one endpoint for audio and video, URL or file)
35
+ "transcribe": "audio/transcriptions",
36
+ "transcribe_price": "audio/transcriptions/price",
37
+ # Embeddings
38
+ "txt2embedding": "embeddings",
39
+ "txt2embedding_price": "embeddings/price",
40
+ # Image-to-text (OCR)
41
+ "img2txt": "images/ocr",
42
+ "img2txt_price": "images/ocr/price",
43
+ # Prompts (one prompt booster endpoint, selected by `type`)
44
+ "prompts_enhance": "prompts/enhancements",
45
+ "prompts_enhance_price": "prompts/enhancements/price",
46
+ # Account (ADMIN key only — an API-role key gets 403 insufficient_permissions)
47
+ "balance": "account/balance",
48
+ "account": "account",
49
+ "account_usage": "account/usage",
50
+ "account_payments": "account/payments",
51
+ # Keys — the calling key (any role)
52
+ "key": "key",
53
+ "key_usage": "key/usage",
54
+ # Keys — account key management (ADMIN key only); per-key paths are keys/{id}
55
+ "keys": "keys",
56
+ # Catalogue and jobs
57
+ "models": "models",
58
+ "request_status": "jobs",
59
+ # Realtime WebSocket parameters of the calling key's account (any role)
60
+ "websocket": "websocket",
61
+ }
deapi_sdk/_download.py ADDED
@@ -0,0 +1,37 @@
1
+ """Download a finished job's result from its storage URL.
2
+
3
+ A plain GET: no Authorization header (the API key must never reach a storage host), redirects
4
+ followed, the client's timeout. HTTP errors become one clear ``DeapiError`` (never the
5
+ API-key-specific auth errors, which would mislead), transport errors become ``NetworkError``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ from deapi_sdk._exceptions import DeapiError, NetworkError
15
+
16
+
17
+ def _check(resp: httpx.Response) -> str:
18
+ if resp.status_code >= 400:
19
+ raise DeapiError(f"Could not download result (HTTP {resp.status_code})", status_code=resp.status_code)
20
+ return resp.text
21
+
22
+
23
+ def download_text(url: str, timeout: Any) -> str:
24
+ try:
25
+ resp = httpx.get(url, timeout=timeout, follow_redirects=True)
26
+ except httpx.TransportError as exc:
27
+ raise NetworkError(str(exc)) from exc
28
+ return _check(resp)
29
+
30
+
31
+ async def adownload_text(url: str, timeout: Any) -> str:
32
+ try:
33
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as http:
34
+ resp = await http.get(url)
35
+ except httpx.TransportError as exc:
36
+ raise NetworkError(str(exc)) from exc
37
+ return _check(resp)