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,184 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class DeapiError(Exception):
7
+ """Base exception for all SDK errors.
8
+
9
+ ``code`` is the machine-readable error code the API sends next to ``message``
10
+ (e.g. ``invalid_key``, ``ip_not_allowed``), or ``None`` when absent.
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ message: str,
16
+ *,
17
+ status_code: int | None = None,
18
+ body: dict | None = None, # type: ignore[type-arg]
19
+ code: str | None = None,
20
+ ) -> None:
21
+ super().__init__(message)
22
+ self.message = message
23
+ self.status_code = status_code
24
+ self.body = body
25
+ if code is None and isinstance(body, dict) and isinstance(body.get("code"), str):
26
+ code = body["code"]
27
+ self.code = code
28
+
29
+
30
+ class AuthenticationError(DeapiError):
31
+ """401 — Missing, invalid, expired or revoked API key (see ``code``)."""
32
+
33
+
34
+ class PaymentRequiredError(DeapiError):
35
+ """402 — Payment required (the API key's spend limit)."""
36
+
37
+
38
+ class KeyLimitExceededError(PaymentRequiredError):
39
+ """402 ``key_limit_exceeded`` — the API key's spend limit is used up.
40
+
41
+ This is the per-key spend limit, not the account balance (see ``InsufficientBalanceError``).
42
+ ``resets_at`` is the raw value from the API (ISO datetime string or ``None``).
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ message: str,
48
+ *,
49
+ status_code: int | None = 402,
50
+ body: dict | None = None, # type: ignore[type-arg]
51
+ code: str | None = None,
52
+ limit: float | None = None,
53
+ used: float | None = None,
54
+ remaining: float | None = None,
55
+ resets_at: str | None = None,
56
+ ) -> None:
57
+ super().__init__(message, status_code=status_code, body=body, code=code)
58
+ self.limit = limit
59
+ self.used = used
60
+ self.remaining = remaining
61
+ self.resets_at = resets_at
62
+
63
+
64
+ class PermissionDeniedError(DeapiError):
65
+ """403 — The request is forbidden. Inspect ``code`` for the reason."""
66
+
67
+
68
+ class AccountSuspendedError(PermissionDeniedError):
69
+ """403 without a code — Account suspended."""
70
+
71
+
72
+ class IpNotAllowedError(PermissionDeniedError):
73
+ """403 ``ip_not_allowed`` — caller IP is outside the API key's IP allowlist."""
74
+
75
+
76
+ class InsufficientPermissionsError(PermissionDeniedError):
77
+ """403 ``insufficient_permissions`` — the key's role cannot call this (admin-only) endpoint."""
78
+
79
+
80
+ class NotFoundError(DeapiError):
81
+ """404 — Resource not found."""
82
+
83
+
84
+ class PayloadTooLargeError(DeapiError):
85
+ """413 — Uploaded payload exceeds the size limit."""
86
+
87
+
88
+ def _normalize_errors(errors: Any) -> dict[str, list[str]]:
89
+ if isinstance(errors, dict):
90
+ return {
91
+ str(k): [str(m) for m in v] if isinstance(v, (list, tuple)) else [str(v)]
92
+ for k, v in errors.items()
93
+ }
94
+ if isinstance(errors, (list, tuple)) and errors:
95
+ return {"_": [str(m) for m in errors]}
96
+ return {}
97
+
98
+
99
+ class ValidationError(DeapiError):
100
+ """422 — Request validation failed."""
101
+
102
+ def __init__(
103
+ self,
104
+ message: str,
105
+ *,
106
+ status_code: int | None = 422,
107
+ body: dict | None = None, # type: ignore[type-arg]
108
+ errors: Any = None,
109
+ code: str | None = None,
110
+ ) -> None:
111
+ super().__init__(message, status_code=status_code, body=body, code=code)
112
+ self.errors: dict[str, list[str]] = _normalize_errors(errors)
113
+
114
+
115
+ class InsufficientBalanceError(ValidationError):
116
+ """422 ``insufficient_balance`` — not enough credits on the account."""
117
+
118
+
119
+ class ActiveKeyLimitReachedError(ValidationError):
120
+ """422 ``active_key_limit_reached`` — would exceed the maximum number of active API keys."""
121
+
122
+
123
+ class RateLimitError(DeapiError):
124
+ """429 — Rate limited."""
125
+
126
+ def __init__(
127
+ self,
128
+ message: str,
129
+ *,
130
+ status_code: int | None = 429,
131
+ body: dict | None = None, # type: ignore[type-arg]
132
+ retry_after: float = 0.0,
133
+ limit_type: str = "",
134
+ code: str | None = None,
135
+ ) -> None:
136
+ super().__init__(message, status_code=status_code, body=body, code=code)
137
+ self.retry_after = retry_after
138
+ self.limit_type = limit_type
139
+
140
+
141
+ class ServerError(DeapiError):
142
+ """5xx — Server-side error."""
143
+
144
+
145
+ class JobTimeoutError(DeapiError):
146
+ """Polling timeout — job didn't complete within max_wait."""
147
+
148
+ def __init__(
149
+ self,
150
+ message: str,
151
+ *,
152
+ status_code: int | None = None,
153
+ body: dict | None = None, # type: ignore[type-arg]
154
+ code: str | None = None,
155
+ request_id: str | None = None,
156
+ ) -> None:
157
+ super().__init__(message, status_code=status_code, body=body, code=code)
158
+ self.request_id = request_id
159
+
160
+
161
+ class NetworkError(DeapiError):
162
+ """Network connectivity error."""
163
+
164
+
165
+ class RealtimeError(DeapiError):
166
+ """Fatal real-time (WebSocket) failure: the connection or channel subscription was refused.
167
+
168
+ Raised for errors that reconnecting cannot fix, e.g. the server rejecting the
169
+ channel authorization (a ``client_id`` that does not belong to the API key)
170
+ or closing the connection with a "do not reconnect" code. ``close_code`` is
171
+ the WebSocket close code when the failure came from one, else ``None``.
172
+ """
173
+
174
+ def __init__(
175
+ self,
176
+ message: str,
177
+ *,
178
+ close_code: int | None = None,
179
+ status_code: int | None = None,
180
+ body: dict | None = None, # type: ignore[type-arg]
181
+ code: str | None = None,
182
+ ) -> None:
183
+ super().__init__(message, status_code=status_code, body=body, code=code)
184
+ self.close_code = close_code
deapi_sdk/_files.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ import mimetypes
4
+ from pathlib import Path
5
+ from typing import BinaryIO, TypeAlias
6
+
7
+ # Types accepted for file parameters. A plain ``str`` is intentionally NOT
8
+ # accepted: it must never be read as a filesystem path by default, so untrusted
9
+ # input handed to a server cannot make it read and exfiltrate an arbitrary local
10
+ # file. Pass a local file explicitly as ``Path(...)``, or pass ``bytes`` / an open
11
+ # binary file object.
12
+ FileInput: TypeAlias = Path | bytes | BinaryIO
13
+
14
+
15
+ def normalize_file(file: FileInput, param_name: str = "file") -> tuple[str, bytes, str]:
16
+ """Convert accepted file input types to httpx's expected tuple format.
17
+
18
+ Accepts ``Path`` (read from disk), ``bytes``, or a binary file object. A plain
19
+ ``str`` is rejected: wrap a local path in ``Path(...)`` so reading from disk is
20
+ always an explicit choice, never an implicit side effect of a bare string.
21
+
22
+ Returns:
23
+ (filename, file_bytes, content_type)
24
+ """
25
+ if isinstance(file, str):
26
+ raise TypeError(
27
+ f"{param_name}: a plain str is not accepted as a file. Wrap a local path "
28
+ "in Path(...), or pass bytes / an open binary file object. (A bare str is "
29
+ "refused so untrusted input can't make a server read an arbitrary local file.)"
30
+ )
31
+
32
+ if isinstance(file, Path):
33
+ content_type = mimetypes.guess_type(str(file))[0] or "application/octet-stream"
34
+ return (file.name, file.read_bytes(), content_type)
35
+
36
+ if isinstance(file, bytes):
37
+ return (f"{param_name}.bin", file, "application/octet-stream")
38
+
39
+ # BinaryIO / file-like object
40
+ name = getattr(file, "name", None)
41
+ if isinstance(name, str):
42
+ filename = Path(name).name
43
+ content_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
44
+ else:
45
+ filename = f"{param_name}.bin"
46
+ content_type = "application/octet-stream"
47
+
48
+ data = file.read()
49
+ return (filename, data, content_type)
50
+
51
+
52
+ def normalize_files(
53
+ files: list[FileInput] | FileInput,
54
+ param_name: str = "file",
55
+ ) -> list[tuple[str, bytes, str]]:
56
+ """Normalize a single file or list of files."""
57
+ if not isinstance(files, list):
58
+ return [normalize_file(files, param_name)]
59
+ return [normalize_file(f, param_name) for f in files]
deapi_sdk/_payload.py ADDED
@@ -0,0 +1,50 @@
1
+ """Helpers shared by resource payload builders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ # Mirrors the API's webhook rules:
8
+ # webhook_url nullable|url:https|max:2048|required_with:webhook_secret
9
+ # webhook_secret nullable|string|min:32|max:255
10
+ WEBHOOK_URL_MAX_LENGTH = 2048
11
+ WEBHOOK_SECRET_MIN_LENGTH = 32
12
+ WEBHOOK_SECRET_MAX_LENGTH = 255
13
+
14
+
15
+ def webhook_fields(webhook_url: str | None, webhook_secret: str | None) -> dict[str, str]:
16
+ """Return the webhook fields to add to a job payload, validated locally.
17
+
18
+ The API checks the same rules, but failing here gives a clear message
19
+ before any file is uploaded. Returns an empty dict when neither is set.
20
+
21
+ Raises:
22
+ ValueError: secret without URL, non-https URL, or bad lengths.
23
+ """
24
+ if not webhook_url and not webhook_secret:
25
+ return {}
26
+ if not webhook_url:
27
+ raise ValueError("webhook_secret requires webhook_url")
28
+ if not webhook_url.lower().startswith("https://"):
29
+ raise ValueError("webhook_url must use https")
30
+ if len(webhook_url) > WEBHOOK_URL_MAX_LENGTH:
31
+ raise ValueError(f"webhook_url must be at most {WEBHOOK_URL_MAX_LENGTH} characters")
32
+
33
+ fields = {"webhook_url": webhook_url}
34
+ if webhook_secret:
35
+ if not WEBHOOK_SECRET_MIN_LENGTH <= len(webhook_secret) <= WEBHOOK_SECRET_MAX_LENGTH:
36
+ raise ValueError(
37
+ f"webhook_secret must be {WEBHOOK_SECRET_MIN_LENGTH}-{WEBHOOK_SECRET_MAX_LENGTH} characters"
38
+ )
39
+ fields["webhook_secret"] = webhook_secret
40
+ return fields
41
+
42
+
43
+ def drop_none(payload: dict[str, Any]) -> dict[str, Any]:
44
+ """Return a copy of payload without None values (unset optional fields)."""
45
+ return {k: v for k, v in payload.items() if v is not None}
46
+
47
+
48
+ def form_bool(value: bool) -> str:
49
+ """Encode a bool for a multipart form field the way Laravel accepts it."""
50
+ return "1" if value else "0"
deapi_sdk/_polling.py ADDED
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import time
5
+ from typing import TYPE_CHECKING
6
+
7
+ from deapi_sdk._exceptions import JobTimeoutError
8
+ from deapi_sdk._types import JobStatus
9
+ from deapi_sdk.types.common import JobResult
10
+
11
+ if TYPE_CHECKING:
12
+ from deapi_sdk._client import AsyncHTTPClient, SyncHTTPClient
13
+
14
+
15
+ def _timeout_error(request_id: str, max_wait: float) -> JobTimeoutError:
16
+ exc = JobTimeoutError(
17
+ f"Job {request_id} did not complete within {max_wait}s. The job is still running on the server; "
18
+ f"resume waiting with client.jobs.get({request_id!r}).wait() or check it once with "
19
+ f"client.jobs.status({request_id!r})."
20
+ )
21
+ exc.request_id = request_id
22
+ return exc
23
+
24
+
25
+ class Job:
26
+ """A submitted job that can be polled for status."""
27
+
28
+ def __init__(self, request_id: str, client: SyncHTTPClient, status_url: str) -> None:
29
+ self.request_id = request_id
30
+ self._client = client
31
+ self._status_url = status_url
32
+
33
+ def status(self) -> JobResult:
34
+ """Poll once and return current status."""
35
+ url = f"{self._status_url}/{self.request_id}"
36
+ resp = self._client.get(url)
37
+ return JobResult.model_validate(resp.get("data", resp))
38
+
39
+ def wait(
40
+ self,
41
+ *,
42
+ poll_interval: float = 1.0,
43
+ max_wait: float = 300.0,
44
+ backoff_factor: float = 1.5,
45
+ max_interval: float = 10.0,
46
+ ) -> JobResult:
47
+ """Poll until done/error with exponential backoff.
48
+
49
+ Raises JobTimeoutError if max_wait is exceeded.
50
+ """
51
+ deadline = time.monotonic() + max_wait
52
+ interval = poll_interval
53
+
54
+ while time.monotonic() < deadline:
55
+ result = self.status()
56
+ if result.status == JobStatus.DONE or result.status == JobStatus.ERROR:
57
+ return result
58
+
59
+ remaining = deadline - time.monotonic()
60
+ if remaining <= 0:
61
+ break
62
+ time.sleep(min(interval, remaining))
63
+ interval = min(interval * backoff_factor, max_interval)
64
+
65
+ raise _timeout_error(self.request_id, max_wait)
66
+
67
+ def is_done(self) -> bool:
68
+ """Check if the job is done. Note: this makes an HTTP request each time."""
69
+ return self.status().status == JobStatus.DONE
70
+
71
+ def is_error(self) -> bool:
72
+ """Check if the job errored. Note: this makes an HTTP request each time."""
73
+ return self.status().status == JobStatus.ERROR
74
+
75
+ def __repr__(self) -> str:
76
+ return f"Job(request_id={self.request_id!r})"
77
+
78
+
79
+ class AsyncJob:
80
+ """Async variant of Job."""
81
+
82
+ def __init__(self, request_id: str, client: AsyncHTTPClient, status_url: str) -> None:
83
+ self.request_id = request_id
84
+ self._client = client
85
+ self._status_url = status_url
86
+
87
+ async def status(self) -> JobResult:
88
+ """Poll once and return current status."""
89
+ url = f"{self._status_url}/{self.request_id}"
90
+ resp = await self._client.get(url)
91
+ return JobResult.model_validate(resp.get("data", resp))
92
+
93
+ async def wait(
94
+ self,
95
+ *,
96
+ poll_interval: float = 1.0,
97
+ max_wait: float = 300.0,
98
+ backoff_factor: float = 1.5,
99
+ max_interval: float = 10.0,
100
+ ) -> JobResult:
101
+ """Poll until done/error with exponential backoff."""
102
+ deadline = time.monotonic() + max_wait
103
+ interval = poll_interval
104
+
105
+ while time.monotonic() < deadline:
106
+ result = await self.status()
107
+ if result.status == JobStatus.DONE or result.status == JobStatus.ERROR:
108
+ return result
109
+
110
+ remaining = deadline - time.monotonic()
111
+ if remaining <= 0:
112
+ break
113
+ await asyncio.sleep(min(interval, remaining))
114
+ interval = min(interval * backoff_factor, max_interval)
115
+
116
+ raise _timeout_error(self.request_id, max_wait)
117
+
118
+ async def is_done(self) -> bool:
119
+ """Check if the job is done. Note: this makes an HTTP request each time."""
120
+ return (await self.status()).status == JobStatus.DONE
121
+
122
+ async def is_error(self) -> bool:
123
+ """Check if the job errored. Note: this makes an HTTP request each time."""
124
+ return (await self.status()).status == JobStatus.ERROR
125
+
126
+ def __repr__(self) -> str:
127
+ return f"AsyncJob(request_id={self.request_id!r})"
128
+
129
+
130
+ class Jobs:
131
+ """Resume or inspect jobs by ``request_id`` (e.g. after a :class:`JobTimeoutError`)."""
132
+
133
+ def __init__(self, client: SyncHTTPClient) -> None:
134
+ self._client = client
135
+
136
+ def get(self, request_id: str) -> Job:
137
+ """Return a :class:`Job` handle for an already submitted job (no HTTP request)."""
138
+ return Job(request_id, self._client, self._client._resolve_endpoint("request_status"))
139
+
140
+ def status(self, request_id: str) -> JobResult:
141
+ """Poll a job once and return its current status."""
142
+ return self.get(request_id).status()
143
+
144
+
145
+ class AsyncJobs:
146
+ """Async variant of :class:`Jobs`."""
147
+
148
+ def __init__(self, client: AsyncHTTPClient) -> None:
149
+ self._client = client
150
+
151
+ def get(self, request_id: str) -> AsyncJob:
152
+ """Return an :class:`AsyncJob` handle for an already submitted job (no HTTP request)."""
153
+ return AsyncJob(request_id, self._client, self._client._resolve_endpoint("request_status"))
154
+
155
+ async def status(self, request_id: str) -> JobResult:
156
+ """Poll a job once and return its current status."""
157
+ return await self.get(request_id).status()
@@ -0,0 +1,7 @@
1
+ """Real-time job status over WebSocket (optional ``ws`` extra)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from deapi_sdk._realtime._session import AsyncRealtime, JobRef, ProgressCallback, Realtime
6
+
7
+ __all__ = ["AsyncRealtime", "JobRef", "ProgressCallback", "Realtime"]
@@ -0,0 +1,43 @@
1
+ """Parsing of ``GET /websocket`` (realtime connection parameters). Pure functions, no I/O."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from urllib.parse import urlsplit
7
+
8
+ from pydantic import ValidationError as PydanticValidationError
9
+
10
+ from deapi_sdk._exceptions import RealtimeError
11
+ from deapi_sdk._realtime import _protocol as protocol
12
+ from deapi_sdk.types.websocket import WebSocketConfig
13
+
14
+ _HINT = "set client_id, ws_url and app_key (or DEAPI_CLIENT_ID, DEAPI_WS_URL, DEAPI_WS_APP_KEY) to skip discovery"
15
+
16
+
17
+ def parse_websocket_config(resp: Any) -> WebSocketConfig:
18
+ """Validate a ``GET /websocket`` body; raise :class:`RealtimeError` when it is unusable."""
19
+ data = resp.get("data", resp) if isinstance(resp, dict) else resp
20
+ try:
21
+ config = WebSocketConfig.model_validate(data)
22
+ except PydanticValidationError as exc:
23
+ fields = ", ".join(sorted({".".join(str(p) for p in e["loc"]) for e in exc.errors()}))
24
+ raise RealtimeError(f"Unexpected response from the WebSocket discovery endpoint (invalid: {fields}).") from exc
25
+ if config.connection.protocol != "pusher":
26
+ raise RealtimeError(
27
+ f"Unsupported WebSocket protocol {config.connection.protocol!r}; this SDK speaks 'pusher'. "
28
+ f"Upgrade the SDK or {_HINT}."
29
+ )
30
+ if not (config.client_id.strip() and config.channel and config.connection.key and config.connection.host):
31
+ raise RealtimeError("The WebSocket discovery response is missing client_id, channel, key or host.")
32
+ if config.event != protocol.STATUS_EVENT:
33
+ raise RealtimeError(
34
+ f"The server announces status updates as event {config.event!r}, but this SDK handles "
35
+ f"{protocol.STATUS_EVENT!r}. Upgrade the SDK."
36
+ )
37
+ if config.auth_endpoint is not None:
38
+ parts = urlsplit(config.auth_endpoint)
39
+ if parts.scheme not in ("http", "https") or not parts.netloc:
40
+ raise RealtimeError(
41
+ f"The WebSocket discovery response has an invalid auth_endpoint: {config.auth_endpoint!r}"
42
+ )
43
+ return config