talksign 0.2.0__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.
- talksign/__init__.py +57 -0
- talksign/_base.py +244 -0
- talksign/_client.py +240 -0
- talksign/_echo.py +391 -0
- talksign/_errors.py +171 -0
- talksign/_requests.py +309 -0
- talksign/_resources.py +775 -0
- talksign/_splitter.py +124 -0
- talksign/_version.py +1 -0
- talksign/py.typed +0 -0
- talksign/types.py +379 -0
- talksign/video.py +625 -0
- talksign-0.2.0.dist-info/METADATA +188 -0
- talksign-0.2.0.dist-info/RECORD +16 -0
- talksign-0.2.0.dist-info/WHEEL +4 -0
- talksign-0.2.0.dist-info/licenses/LICENSE +191 -0
talksign/_echo.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""Live Echo 2.0 signing from streamed text (client side, built on ``/v1/speech-to-sign/realtime``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections import deque
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Literal, Union
|
|
10
|
+
|
|
11
|
+
from ._splitter import SentenceSplitter
|
|
12
|
+
from .types import Clip, IdleClip, RealtimeResponse, Usage
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from ._resources import AsyncAvatars, AsyncSpeechToSign
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"ClipEvent",
|
|
19
|
+
"DoneEvent",
|
|
20
|
+
"EchoEvent",
|
|
21
|
+
"EchoStream",
|
|
22
|
+
"ErrorEvent",
|
|
23
|
+
"IdleEvent",
|
|
24
|
+
"InterruptedEvent",
|
|
25
|
+
"SentenceEvent",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, kw_only=True)
|
|
30
|
+
class SentenceEvent:
|
|
31
|
+
"""A sentence was translated; its ``clip`` events follow, in order."""
|
|
32
|
+
|
|
33
|
+
index: int
|
|
34
|
+
text: str
|
|
35
|
+
response: RealtimeResponse
|
|
36
|
+
type: Literal["sentence"] = field(default="sentence", init=False)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def glosses(self) -> list[str]:
|
|
40
|
+
return list(self.response.get("data", {}).get("glosses", []))
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def usage(self) -> Usage | None:
|
|
44
|
+
return self.response.get("usage")
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def idle(self) -> IdleClip | None:
|
|
48
|
+
return self.response.get("data", {}).get("idle")
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def has_missing(self) -> bool:
|
|
52
|
+
"""True when some words had no clip (those clips are skipped)."""
|
|
53
|
+
return bool(self.response.get("data", {}).get("has_missing"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, kw_only=True)
|
|
57
|
+
class ClipEvent:
|
|
58
|
+
"""One word to play. Play order: ``in_url`` -> ``url`` [active range] -> ``out_url``."""
|
|
59
|
+
|
|
60
|
+
sentence_index: int
|
|
61
|
+
index: int
|
|
62
|
+
clip: Clip
|
|
63
|
+
last: bool
|
|
64
|
+
type: Literal["clip"] = field(default="clip", init=False)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, kw_only=True)
|
|
68
|
+
class IdleEvent:
|
|
69
|
+
"""The avatar should show its idle loop.
|
|
70
|
+
|
|
71
|
+
``reason``: ``"ready"`` (the idle loop was fetched at start, before any sentence),
|
|
72
|
+
``"drained"`` (nothing left to sign) or ``"interrupt"``. ``idle`` is the latest rest-pose loop
|
|
73
|
+
(``None`` when the avatar has none).
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
idle: IdleClip | None
|
|
77
|
+
reason: Literal["ready", "drained", "interrupt"]
|
|
78
|
+
type: Literal["idle"] = field(default="idle", init=False)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, kw_only=True)
|
|
82
|
+
class InterruptedEvent:
|
|
83
|
+
""":meth:`EchoStream.interrupt` was called: queued text and clips were dropped. An ``idle`` event follows."""
|
|
84
|
+
|
|
85
|
+
type: Literal["interrupted"] = field(default="interrupted", init=False)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, kw_only=True)
|
|
89
|
+
class ErrorEvent:
|
|
90
|
+
"""A sentence failed (it is skipped; the stream keeps going)."""
|
|
91
|
+
|
|
92
|
+
error: BaseException
|
|
93
|
+
sentence_index: int
|
|
94
|
+
text: str
|
|
95
|
+
type: Literal["error"] = field(default="error", init=False)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True, kw_only=True)
|
|
99
|
+
class DoneEvent:
|
|
100
|
+
"""The stream was closed and every queued sentence was delivered. Iteration ends after it."""
|
|
101
|
+
|
|
102
|
+
type: Literal["done"] = field(default="done", init=False)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
EchoEvent = Union[SentenceEvent, ClipEvent, IdleEvent, InterruptedEvent, ErrorEvent, DoneEvent] # noqa: UP007
|
|
106
|
+
|
|
107
|
+
_END = object()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class _Item:
|
|
112
|
+
index: int
|
|
113
|
+
text: str
|
|
114
|
+
task: asyncio.Task[RealtimeResponse] | None = None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class EchoStream:
|
|
118
|
+
"""Turns streamed text into an ordered stream of sign clips.
|
|
119
|
+
|
|
120
|
+
Text pushed with :meth:`push_text` is cut into sentences (``. ! ? …`` / newline, ``max_chars``, or
|
|
121
|
+
``idle_flush`` seconds without new text). Each sentence is one ``/v1/speech-to-sign/realtime`` call;
|
|
122
|
+
the next ``prefetch`` sentences are requested while the current one is in flight. Events come out in
|
|
123
|
+
sentence order. :meth:`interrupt` aborts in-flight calls, drops everything queued and goes idle.
|
|
124
|
+
|
|
125
|
+
Use it as an async iterator (``async for event in stream``) and/or an async context manager.
|
|
126
|
+
Create it with ``client.echo.stream(...)``.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__(
|
|
130
|
+
self,
|
|
131
|
+
speech_to_sign: AsyncSpeechToSign,
|
|
132
|
+
*,
|
|
133
|
+
avatar: str = "arthur",
|
|
134
|
+
language: str = "asl",
|
|
135
|
+
model: str | None = None,
|
|
136
|
+
config: Mapping[str, Any] | None = None,
|
|
137
|
+
max_chars: int = 120,
|
|
138
|
+
idle_flush: float = 1.2,
|
|
139
|
+
prefetch: int = 1,
|
|
140
|
+
on_close: Callable[[], Awaitable[None]] | None = None,
|
|
141
|
+
avatars: AsyncAvatars | None = None,
|
|
142
|
+
chunking: Literal["sentence", "full"] = "sentence",
|
|
143
|
+
first_chunk_chars: int = 40,
|
|
144
|
+
) -> None:
|
|
145
|
+
if chunking not in ("sentence", "full"):
|
|
146
|
+
raise ValueError('chunking must be "sentence" or "full"')
|
|
147
|
+
self.avatar = avatar
|
|
148
|
+
self.language = language
|
|
149
|
+
self.model = model
|
|
150
|
+
self.config = dict(config) if config else None
|
|
151
|
+
self.idle_flush = idle_flush
|
|
152
|
+
self.prefetch = max(0, int(prefetch))
|
|
153
|
+
self._api = speech_to_sign
|
|
154
|
+
self._on_close = on_close
|
|
155
|
+
self.chunking = chunking
|
|
156
|
+
self._avatars = avatars
|
|
157
|
+
self._idle_task: asyncio.Task[None] | None = None
|
|
158
|
+
self._full: list[str] = []
|
|
159
|
+
self._splitter = SentenceSplitter(max_chars, max(0, int(first_chunk_chars or 0)))
|
|
160
|
+
self._pending: deque[_Item] = deque()
|
|
161
|
+
self._events: asyncio.Queue[object] = asyncio.Queue()
|
|
162
|
+
self._wake = asyncio.Event()
|
|
163
|
+
self._worker: asyncio.Task[None] | None = None
|
|
164
|
+
self._timer: asyncio.TimerHandle | None = None
|
|
165
|
+
self._next_index = 0
|
|
166
|
+
self._closing = False
|
|
167
|
+
self._closed = False
|
|
168
|
+
self._finished = False
|
|
169
|
+
self._idle: IdleClip | None = None
|
|
170
|
+
|
|
171
|
+
# -- public API -------------------------------------------------------
|
|
172
|
+
@property
|
|
173
|
+
def idle(self) -> IdleClip | None:
|
|
174
|
+
"""Latest idle (rest-pose) loop of the avatar, once any sentence has been answered."""
|
|
175
|
+
return self._idle
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def closed(self) -> bool:
|
|
179
|
+
return self._closing
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def busy(self) -> bool:
|
|
183
|
+
"""True while signing work is pending: sentences in flight, undelivered events, or buffered text
|
|
184
|
+
that the pause timer will send. (Unflushed text in ``chunking="full"`` mode does not count.)"""
|
|
185
|
+
if self._finished and self._events.empty():
|
|
186
|
+
return False
|
|
187
|
+
buffered = self._timer is not None and bool(self._splitter.pending.strip())
|
|
188
|
+
return bool(self._pending) or not self._events.empty() or buffered
|
|
189
|
+
|
|
190
|
+
async def wait_idle_fetched(self) -> IdleClip | None:
|
|
191
|
+
"""Waits for the start-up idle-loop fetch (if any) and returns :attr:`idle`."""
|
|
192
|
+
self._ensure_worker()
|
|
193
|
+
if self._idle_task is not None and not self._idle_task.done():
|
|
194
|
+
await asyncio.wait({self._idle_task})
|
|
195
|
+
return self._idle
|
|
196
|
+
|
|
197
|
+
def push_text(self, chunk: str) -> None:
|
|
198
|
+
"""Adds streamed text (any size: a token, a word, a paragraph). Must be called inside a running loop."""
|
|
199
|
+
if self._closing:
|
|
200
|
+
raise RuntimeError("EchoStream is closed")
|
|
201
|
+
loop = asyncio.get_running_loop()
|
|
202
|
+
self._ensure_worker()
|
|
203
|
+
if self.chunking == "full":
|
|
204
|
+
if chunk:
|
|
205
|
+
self._full.append(chunk)
|
|
206
|
+
return
|
|
207
|
+
for sentence in self._splitter.push(chunk):
|
|
208
|
+
self._enqueue(sentence)
|
|
209
|
+
self._cancel_timer()
|
|
210
|
+
if self._splitter.pending.strip():
|
|
211
|
+
self._timer = loop.call_later(self.idle_flush, self._on_pause)
|
|
212
|
+
|
|
213
|
+
def flush(self) -> None:
|
|
214
|
+
"""Sends any buffered partial sentence now (e.g. when the agent's turn ends).
|
|
215
|
+
|
|
216
|
+
In ``chunking="full"`` mode this sends everything pushed since the last flush as one call.
|
|
217
|
+
"""
|
|
218
|
+
self._cancel_timer()
|
|
219
|
+
if self.chunking == "full":
|
|
220
|
+
text, self._full = " ".join("".join(self._full).split()), []
|
|
221
|
+
if any(c.isalnum() for c in text):
|
|
222
|
+
self._ensure_worker()
|
|
223
|
+
self._enqueue(text)
|
|
224
|
+
return
|
|
225
|
+
sentence = self._splitter.flush()
|
|
226
|
+
if sentence:
|
|
227
|
+
self._ensure_worker()
|
|
228
|
+
self._enqueue(sentence)
|
|
229
|
+
|
|
230
|
+
def interrupt(self) -> None:
|
|
231
|
+
"""Stops signing now: aborts in-flight requests, drops queued text and clips, emits ``idle``."""
|
|
232
|
+
self._cancel_timer()
|
|
233
|
+
self._splitter.clear()
|
|
234
|
+
self._full = []
|
|
235
|
+
for item in self._pending:
|
|
236
|
+
if item.task is not None and not item.task.done():
|
|
237
|
+
item.task.cancel()
|
|
238
|
+
self._pending.clear()
|
|
239
|
+
kept: list[object] = []
|
|
240
|
+
while not self._events.empty():
|
|
241
|
+
ev = self._events.get_nowait()
|
|
242
|
+
if ev is _END or isinstance(ev, DoneEvent):
|
|
243
|
+
kept.append(ev)
|
|
244
|
+
for ev in kept:
|
|
245
|
+
self._events.put_nowait(ev)
|
|
246
|
+
if not self._finished:
|
|
247
|
+
self._events.put_nowait(InterruptedEvent())
|
|
248
|
+
self._events.put_nowait(IdleEvent(idle=self._idle, reason="interrupt"))
|
|
249
|
+
self._wake.set()
|
|
250
|
+
|
|
251
|
+
async def aclose(self) -> None:
|
|
252
|
+
"""Flushes buffered text, waits for queued sentences to be delivered, then emits ``done``.
|
|
253
|
+
|
|
254
|
+
Call :meth:`interrupt` first for an immediate stop.
|
|
255
|
+
"""
|
|
256
|
+
if self._closing:
|
|
257
|
+
if self._worker is not None:
|
|
258
|
+
await asyncio.wait({self._worker})
|
|
259
|
+
return
|
|
260
|
+
self.flush()
|
|
261
|
+
self._closing = True
|
|
262
|
+
self._wake.set()
|
|
263
|
+
if self._worker is None:
|
|
264
|
+
self._finish()
|
|
265
|
+
else:
|
|
266
|
+
await asyncio.wait({self._worker})
|
|
267
|
+
if self._on_close is not None:
|
|
268
|
+
cb, self._on_close = self._on_close, None
|
|
269
|
+
await cb()
|
|
270
|
+
|
|
271
|
+
async def __aenter__(self) -> EchoStream:
|
|
272
|
+
return self
|
|
273
|
+
|
|
274
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
275
|
+
if exc[0] is not None:
|
|
276
|
+
self.interrupt()
|
|
277
|
+
await self.aclose()
|
|
278
|
+
|
|
279
|
+
def __aiter__(self) -> EchoStream:
|
|
280
|
+
return self
|
|
281
|
+
|
|
282
|
+
async def __anext__(self) -> EchoEvent:
|
|
283
|
+
if self._closed:
|
|
284
|
+
raise StopAsyncIteration
|
|
285
|
+
self._ensure_worker()
|
|
286
|
+
ev = await self._events.get()
|
|
287
|
+
if ev is _END:
|
|
288
|
+
self._closed = True
|
|
289
|
+
raise StopAsyncIteration
|
|
290
|
+
return ev # type: ignore[return-value]
|
|
291
|
+
|
|
292
|
+
# -- internals ----------------------------------------------------------
|
|
293
|
+
def _ensure_worker(self) -> None:
|
|
294
|
+
if self._worker is None and not self._closing:
|
|
295
|
+
loop = asyncio.get_running_loop()
|
|
296
|
+
if self._avatars is not None and self._idle_task is None:
|
|
297
|
+
self._idle_task = loop.create_task(self._fetch_idle(), name="talksign-echo-idle")
|
|
298
|
+
self._worker = loop.create_task(self._run(), name="talksign-echo-stream")
|
|
299
|
+
|
|
300
|
+
async def _fetch_idle(self) -> None:
|
|
301
|
+
"""One free GET /v1/avatars/{id}: the idle loop, so players show the avatar before the first sentence."""
|
|
302
|
+
try:
|
|
303
|
+
assert self._avatars is not None
|
|
304
|
+
res = await self._avatars.get(self.avatar, language=self.language)
|
|
305
|
+
except asyncio.CancelledError:
|
|
306
|
+
raise
|
|
307
|
+
except Exception: # noqa: BLE001 - best effort; the first realtime answer also carries idle
|
|
308
|
+
return
|
|
309
|
+
idle = (res.get("data") or {}).get("idle") if isinstance(res, Mapping) else None
|
|
310
|
+
if idle and idle.get("url") and self._idle is None and not self._finished:
|
|
311
|
+
self._idle = idle
|
|
312
|
+
self._events.put_nowait(IdleEvent(idle=idle, reason="ready"))
|
|
313
|
+
|
|
314
|
+
def _cancel_timer(self) -> None:
|
|
315
|
+
if self._timer is not None:
|
|
316
|
+
self._timer.cancel()
|
|
317
|
+
self._timer = None
|
|
318
|
+
|
|
319
|
+
def _on_pause(self) -> None:
|
|
320
|
+
self._timer = None
|
|
321
|
+
sentence = self._splitter.flush()
|
|
322
|
+
if sentence:
|
|
323
|
+
self._enqueue(sentence)
|
|
324
|
+
|
|
325
|
+
def _enqueue(self, text: str) -> None:
|
|
326
|
+
self._pending.append(_Item(self._next_index, text))
|
|
327
|
+
self._next_index += 1
|
|
328
|
+
self._fill_prefetch()
|
|
329
|
+
self._wake.set()
|
|
330
|
+
|
|
331
|
+
def _fill_prefetch(self) -> None:
|
|
332
|
+
for i, item in enumerate(self._pending):
|
|
333
|
+
if i > self.prefetch:
|
|
334
|
+
break
|
|
335
|
+
if item.task is None:
|
|
336
|
+
item.task = asyncio.get_running_loop().create_task(self._fetch(item.text))
|
|
337
|
+
|
|
338
|
+
async def _fetch(self, text: str) -> RealtimeResponse:
|
|
339
|
+
return await self._api.realtime(
|
|
340
|
+
text, avatar=self.avatar, language=self.language, model=self.model, config=self.config
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
def _finish(self) -> None:
|
|
344
|
+
if not self._finished:
|
|
345
|
+
self._finished = True
|
|
346
|
+
self._events.put_nowait(DoneEvent())
|
|
347
|
+
self._events.put_nowait(_END)
|
|
348
|
+
|
|
349
|
+
async def _run(self) -> None:
|
|
350
|
+
try:
|
|
351
|
+
while True:
|
|
352
|
+
if not self._pending:
|
|
353
|
+
if self._closing:
|
|
354
|
+
return
|
|
355
|
+
self._wake.clear()
|
|
356
|
+
await self._wake.wait()
|
|
357
|
+
continue
|
|
358
|
+
self._fill_prefetch()
|
|
359
|
+
item = self._pending[0]
|
|
360
|
+
assert item.task is not None
|
|
361
|
+
await asyncio.wait({item.task})
|
|
362
|
+
if not self._pending or self._pending[0] is not item:
|
|
363
|
+
continue # interrupted while waiting
|
|
364
|
+
self._pending.popleft()
|
|
365
|
+
self._fill_prefetch()
|
|
366
|
+
if item.task.cancelled():
|
|
367
|
+
continue
|
|
368
|
+
exc = item.task.exception()
|
|
369
|
+
if exc is not None:
|
|
370
|
+
self._events.put_nowait(ErrorEvent(error=exc, sentence_index=item.index, text=item.text))
|
|
371
|
+
else:
|
|
372
|
+
self._deliver(item, item.task.result())
|
|
373
|
+
if not self._pending and not self._splitter.pending.strip():
|
|
374
|
+
self._events.put_nowait(IdleEvent(idle=self._idle, reason="drained"))
|
|
375
|
+
finally:
|
|
376
|
+
for item in self._pending:
|
|
377
|
+
if item.task is not None:
|
|
378
|
+
item.task.cancel()
|
|
379
|
+
if self._idle_task is not None and not self._idle_task.done():
|
|
380
|
+
self._idle_task.cancel()
|
|
381
|
+
self._finish()
|
|
382
|
+
|
|
383
|
+
def _deliver(self, item: _Item, response: RealtimeResponse) -> None:
|
|
384
|
+
data = response.get("data") or {}
|
|
385
|
+
idle = data.get("idle")
|
|
386
|
+
if idle and idle.get("url"):
|
|
387
|
+
self._idle = idle
|
|
388
|
+
self._events.put_nowait(SentenceEvent(index=item.index, text=item.text, response=response))
|
|
389
|
+
clips = [c for c in data.get("playlist") or [] if c.get("url")]
|
|
390
|
+
for i, clip in enumerate(clips):
|
|
391
|
+
self._events.put_nowait(ClipEvent(sentence_index=item.index, index=i, clip=clip, last=i == len(clips) - 1))
|
talksign/_errors.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"APIConnectionError",
|
|
9
|
+
"APIError",
|
|
10
|
+
"APITimeoutError",
|
|
11
|
+
"AuthenticationError",
|
|
12
|
+
"BadRequestError",
|
|
13
|
+
"InsufficientBalanceError",
|
|
14
|
+
"NotFoundError",
|
|
15
|
+
"PermissionDeniedError",
|
|
16
|
+
"RateLimitError",
|
|
17
|
+
"TalksignError",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TalksignError(Exception):
|
|
22
|
+
"""Base class of every error raised by this SDK.
|
|
23
|
+
|
|
24
|
+
HTTP errors carry the API's error envelope ``{ error: { code, message, type, param }, request_id }``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
status_code: int | None
|
|
28
|
+
code: str | None
|
|
29
|
+
type: str | None
|
|
30
|
+
param: str | None
|
|
31
|
+
request_id: str | None
|
|
32
|
+
body: Any
|
|
33
|
+
headers: httpx.Headers | None
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
message: str,
|
|
38
|
+
*,
|
|
39
|
+
status_code: int | None = None,
|
|
40
|
+
code: str | None = None,
|
|
41
|
+
type: str | None = None, # noqa: A002
|
|
42
|
+
param: str | None = None,
|
|
43
|
+
request_id: str | None = None,
|
|
44
|
+
body: Any = None,
|
|
45
|
+
headers: httpx.Headers | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
super().__init__(message)
|
|
48
|
+
self.message = message
|
|
49
|
+
self.status_code = status_code
|
|
50
|
+
self.code = code
|
|
51
|
+
self.type = type
|
|
52
|
+
self.param = param
|
|
53
|
+
self.request_id = request_id
|
|
54
|
+
self.body = body
|
|
55
|
+
self.headers = headers
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def status(self) -> int | None:
|
|
59
|
+
"""Alias of ``status_code`` (same name as the JavaScript SDK)."""
|
|
60
|
+
return self.status_code
|
|
61
|
+
|
|
62
|
+
def __str__(self) -> str:
|
|
63
|
+
parts = [self.message]
|
|
64
|
+
if self.status_code is not None:
|
|
65
|
+
parts.insert(0, f"[{self.status_code}{' ' + self.code if self.code else ''}]")
|
|
66
|
+
if self.request_id:
|
|
67
|
+
parts.append(f"(request_id={self.request_id})")
|
|
68
|
+
return " ".join(parts)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class APIError(TalksignError):
|
|
72
|
+
"""An HTTP error answered by the API (base of the status-specific errors; also 5xx and 501)."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class APIConnectionError(TalksignError):
|
|
76
|
+
"""The request never got an HTTP answer (DNS, TLS, connection reset...)."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class APITimeoutError(APIConnectionError):
|
|
80
|
+
"""The request timed out."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class BadRequestError(APIError):
|
|
84
|
+
"""400 / 409 / 413 / 422: the request was refused (``code`` says why, ``param`` names the field)."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class AuthenticationError(APIError):
|
|
88
|
+
"""401: missing, malformed, revoked or retired API key."""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class InsufficientBalanceError(APIError):
|
|
92
|
+
"""402: not enough wallet funds (``insufficient_credits``) or another billing block
|
|
93
|
+
(``payment_method_required``, ``avatar_slot_inactive``). Nothing was charged."""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class PermissionDeniedError(APIError):
|
|
97
|
+
"""403: key scope, IP allow-list or account limit (``insufficient_scope``, ``ip_not_allowed`` ...)."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class NotFoundError(APIError):
|
|
101
|
+
"""404: unknown endpoint, avatar, job, meeting or video."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class RateLimitError(APIError):
|
|
105
|
+
"""429: too many requests. ``retry_after`` holds the server's ``Retry-After`` in seconds."""
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def retry_after(self) -> float | None:
|
|
109
|
+
return _parse_retry_after(self.headers)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _parse_retry_after(headers: httpx.Headers | None) -> float | None:
|
|
113
|
+
if not headers:
|
|
114
|
+
return None
|
|
115
|
+
raw = headers.get("retry-after")
|
|
116
|
+
if raw is None:
|
|
117
|
+
return None
|
|
118
|
+
try:
|
|
119
|
+
return max(0.0, float(raw))
|
|
120
|
+
except ValueError:
|
|
121
|
+
pass
|
|
122
|
+
try:
|
|
123
|
+
import datetime as _dt
|
|
124
|
+
from email.utils import parsedate_to_datetime
|
|
125
|
+
|
|
126
|
+
when = parsedate_to_datetime(raw)
|
|
127
|
+
return max(0.0, (when - _dt.datetime.now(when.tzinfo)).total_seconds())
|
|
128
|
+
except (TypeError, ValueError, IndexError):
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def error_from_response(response: httpx.Response) -> TalksignError:
|
|
133
|
+
status = response.status_code
|
|
134
|
+
body: Any
|
|
135
|
+
try:
|
|
136
|
+
body = response.json()
|
|
137
|
+
except ValueError:
|
|
138
|
+
body = response.text
|
|
139
|
+
err = body.get("error") if isinstance(body, dict) else None
|
|
140
|
+
if not isinstance(err, dict):
|
|
141
|
+
err = {}
|
|
142
|
+
message = err.get("message") or (body.get("message") if isinstance(body, dict) else None)
|
|
143
|
+
if not message:
|
|
144
|
+
message = (body if isinstance(body, str) and body else None) or f"HTTP {status}"
|
|
145
|
+
code = err.get("code") or (body.get("code") if isinstance(body, dict) else None)
|
|
146
|
+
request_id = (body.get("request_id") if isinstance(body, dict) else None) or response.headers.get("x-request-id")
|
|
147
|
+
cls: type[TalksignError]
|
|
148
|
+
if status == 401:
|
|
149
|
+
cls = AuthenticationError
|
|
150
|
+
elif status == 402:
|
|
151
|
+
cls = InsufficientBalanceError
|
|
152
|
+
elif status == 403:
|
|
153
|
+
cls = PermissionDeniedError
|
|
154
|
+
elif status == 404:
|
|
155
|
+
cls = NotFoundError
|
|
156
|
+
elif status == 429:
|
|
157
|
+
cls = RateLimitError
|
|
158
|
+
elif status in (400, 405, 409, 413, 422):
|
|
159
|
+
cls = BadRequestError
|
|
160
|
+
else:
|
|
161
|
+
cls = APIError
|
|
162
|
+
return cls(
|
|
163
|
+
str(message),
|
|
164
|
+
status_code=status,
|
|
165
|
+
code=code if isinstance(code, str) else None,
|
|
166
|
+
type=err.get("type"),
|
|
167
|
+
param=err.get("param"),
|
|
168
|
+
request_id=request_id,
|
|
169
|
+
body=body,
|
|
170
|
+
headers=response.headers,
|
|
171
|
+
)
|