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,84 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from pydantic import BaseModel, ConfigDict
7
+
8
+
9
+ class Text2VideoParams(BaseModel):
10
+ prompt: str
11
+ model: str
12
+ width: int | None = None
13
+ height: int | None = None
14
+ steps: int | None = None
15
+ seed: int | None = None
16
+ frames: int | None = None
17
+ fps: int | None = None
18
+ negative_prompt: str | None = None
19
+ guidance: float | None = None
20
+ enhance_prompt: bool | None = None
21
+ webhook_url: str | None = None
22
+ webhook_secret: str | None = None
23
+
24
+
25
+ class Img2VideoParams(BaseModel):
26
+ prompt: str
27
+ model: str
28
+ seed: int | None = None
29
+ width: int | None = None
30
+ height: int | None = None
31
+ frames: int | None = None
32
+ fps: int | None = None
33
+ negative_prompt: str | None = None
34
+ guidance: float | None = None
35
+ steps: int | None = None
36
+ enhance_prompt: bool | None = None
37
+ webhook_url: str | None = None
38
+ webhook_secret: str | None = None
39
+
40
+
41
+ class Aud2VideoParams(BaseModel):
42
+ prompt: str
43
+ model: str
44
+ width: int | None = None
45
+ height: int | None = None
46
+ seed: int | None = None
47
+ frames: int | None = None
48
+ fps: int | None = None
49
+ negative_prompt: str | None = None
50
+ guidance: float | None = None
51
+ steps: int | None = None
52
+ webhook_url: str | None = None
53
+ webhook_secret: str | None = None
54
+
55
+
56
+ class VideoEvent(BaseModel):
57
+ """One timestamped on-screen event (``start`` / ``end`` in seconds)."""
58
+
59
+ model_config = ConfigDict(extra="allow")
60
+
61
+ start: float
62
+ end: float
63
+ description: str
64
+ merged: bool | None = None
65
+ edge_distance: float | None = None
66
+
67
+
68
+ class VideoDescription(BaseModel):
69
+ """Result of a video description job: ``events``, ``scenes`` and source ``meta``."""
70
+
71
+ model_config = ConfigDict(extra="allow")
72
+
73
+ events: list[VideoEvent] = []
74
+ scenes: list[Any] = []
75
+ meta: dict[str, Any] = {}
76
+
77
+
78
+ def parse_video_description(raw: str | bytes | dict[str, Any]) -> VideoDescription:
79
+ """Parse a video description result (JSON string from ``JobResult.result``, bytes, or dict)."""
80
+ if isinstance(raw, (str, bytes)):
81
+ raw = json.loads(raw)
82
+ if not isinstance(raw, dict):
83
+ raise ValueError("Video description must be a JSON object")
84
+ return VideoDescription.model_validate(raw)
@@ -0,0 +1,36 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class WebSocketConnection(BaseModel):
7
+ """Where to open the realtime WebSocket (the ``connection`` block of ``GET /websocket``)."""
8
+
9
+ protocol: str # "pusher"
10
+ key: str # public application key of the WebSocket server (not a secret)
11
+ host: str
12
+ port: int
13
+ tls: bool
14
+
15
+ model_config = {"extra": "allow"}
16
+
17
+ @property
18
+ def url(self) -> str:
19
+ """``wss://host`` / ``ws://host``; the port is included only when it is not the scheme default."""
20
+ scheme = "wss" if self.tls else "ws"
21
+ default_port = 443 if self.tls else 80
22
+ host = f"[{self.host}]" if ":" in self.host and not self.host.startswith("[") else self.host
23
+ suffix = "" if self.port == default_port else f":{self.port}"
24
+ return f"{scheme}://{host}{suffix}"
25
+
26
+
27
+ class WebSocketConfig(BaseModel):
28
+ """Realtime WebSocket parameters of the calling account (``GET /websocket``). No secrets."""
29
+
30
+ client_id: str
31
+ channel: str
32
+ event: str
33
+ auth_endpoint: str | None = None
34
+ connection: WebSocketConnection
35
+
36
+ model_config = {"extra": "allow"}
deapi_sdk/webhook.py ADDED
@@ -0,0 +1,159 @@
1
+ """Webhook signature verification for deAPI webhook events."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import hmac
6
+ import json
7
+ import time
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel
11
+
12
+ from deapi_sdk._exceptions import DeapiError
13
+
14
+
15
+ class JobPrice(BaseModel):
16
+ """Cost of a job: ``amount`` and whether it is still an estimate."""
17
+
18
+ amount: float
19
+ is_estimated: bool
20
+
21
+ model_config = {"extra": "allow"}
22
+
23
+
24
+ class WebhookEventData(BaseModel):
25
+ """Data payload from a webhook event.
26
+
27
+ ``job.processing`` sets ``started_at``; ``job.completed`` sets ``completed_at``,
28
+ ``result_url``, ``processing_time_ms`` and ``price``; ``job.failed`` sets ``failed_at``,
29
+ ``price`` and the failure fields. On ``job.completed`` the price may still be an
30
+ estimate (``is_estimated``); for the final amount and refund state of a failed job,
31
+ read the job status endpoint (``client.jobs.status(request_id)``).
32
+
33
+ ``error_reason`` is an open list: treat a value you do not recognise as
34
+ ``PROCESSING_FAILED``, and branch on ``retryable`` to decide whether to resubmit.
35
+ """
36
+
37
+ job_request_id: str
38
+ status: str
39
+ previous_status: str | None = None
40
+ job_type: str | None = None
41
+ started_at: str | None = None
42
+ completed_at: str | None = None
43
+ result_url: str | None = None
44
+ processing_time_ms: int | None = None
45
+ price: JobPrice | None = None # job.completed and job.failed
46
+ # Failure details (job.failed only)
47
+ failed_at: str | None = None
48
+ error_code: str | None = None # WORKER_TIMEOUT | WORKER_ERROR | PROCESSING_ERROR
49
+ error_reason: str | None = None # e.g. SOURCE_PRIVATE, TIMEOUT, CAPACITY_UNAVAILABLE (open list)
50
+ retryable: bool | None = None
51
+ refunded: bool | None = None
52
+
53
+ model_config = {"extra": "allow"}
54
+
55
+
56
+ class WebhookEvent(BaseModel):
57
+ """Parsed and verified webhook event."""
58
+ event: str
59
+ delivery_id: str
60
+ timestamp: str
61
+ data: WebhookEventData
62
+
63
+ @property
64
+ def type(self) -> str:
65
+ """Alias for event type (e.g. 'job.completed')."""
66
+ return self.event
67
+
68
+
69
+ class InvalidSignatureError(DeapiError):
70
+ """Raised when webhook signature verification fails."""
71
+
72
+ def __init__(self, message: str = "Invalid webhook signature") -> None:
73
+ super().__init__(message)
74
+
75
+
76
+ def verify_signature(
77
+ *,
78
+ payload: bytes | str,
79
+ signature: str,
80
+ timestamp: str,
81
+ secret: str,
82
+ tolerance: int = 300,
83
+ ) -> None:
84
+ """Verify a webhook signature.
85
+
86
+ Args:
87
+ payload: Raw request body (bytes or string).
88
+ signature: Value of X-DeAPI-Signature header (e.g. "sha256=abcdef...").
89
+ timestamp: Value of X-DeAPI-Timestamp header (unix timestamp string).
90
+ secret: Your webhook signing secret.
91
+ tolerance: Maximum age in seconds before rejecting (default 300 = 5 min).
92
+
93
+ Raises:
94
+ InvalidSignatureError: If signature is invalid or timestamp is too old.
95
+ """
96
+ if tolerance > 0:
97
+ try:
98
+ ts = int(timestamp)
99
+ except (ValueError, TypeError) as exc:
100
+ raise InvalidSignatureError("Invalid timestamp format") from exc
101
+
102
+ age = abs(time.time() - ts)
103
+ if age > tolerance:
104
+ raise InvalidSignatureError(
105
+ f"Timestamp too old: {int(age)}s exceeds tolerance of {tolerance}s"
106
+ )
107
+
108
+ if isinstance(payload, str):
109
+ payload = payload.encode("utf-8")
110
+
111
+ signed_content = f"{timestamp}.".encode() + payload
112
+ expected = hmac.new(
113
+ secret.encode("utf-8"),
114
+ signed_content,
115
+ hashlib.sha256,
116
+ ).hexdigest()
117
+
118
+ expected_sig = f"sha256={expected}"
119
+
120
+ if not hmac.compare_digest(expected_sig, signature):
121
+ raise InvalidSignatureError()
122
+
123
+
124
+ def construct_event(
125
+ *,
126
+ payload: bytes | str,
127
+ signature: str,
128
+ timestamp: str,
129
+ secret: str,
130
+ tolerance: int = 300,
131
+ ) -> WebhookEvent:
132
+ """Verify signature and parse the webhook payload into a WebhookEvent.
133
+
134
+ Args:
135
+ payload: Raw request body.
136
+ signature: Value of X-DeAPI-Signature header.
137
+ timestamp: Value of X-DeAPI-Timestamp header.
138
+ secret: Your webhook signing secret.
139
+ tolerance: Maximum age in seconds (default 300).
140
+
141
+ Returns:
142
+ Parsed WebhookEvent with verified signature.
143
+
144
+ Raises:
145
+ InvalidSignatureError: If signature is invalid or timestamp is stale.
146
+ """
147
+ verify_signature(
148
+ payload=payload,
149
+ signature=signature,
150
+ timestamp=timestamp,
151
+ secret=secret,
152
+ tolerance=tolerance,
153
+ )
154
+
155
+ if isinstance(payload, bytes):
156
+ payload = payload.decode("utf-8")
157
+
158
+ body: dict[str, Any] = json.loads(payload)
159
+ return WebhookEvent.model_validate(body)