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 ADDED
@@ -0,0 +1,57 @@
1
+ """Official Python SDK for the Talksign API."""
2
+
3
+ from ._base import DEFAULT_BASE_URL, FileInput
4
+ from ._client import AsyncTalksign, Talksign
5
+ from ._echo import (
6
+ ClipEvent,
7
+ DoneEvent,
8
+ EchoEvent,
9
+ EchoStream,
10
+ ErrorEvent,
11
+ IdleEvent,
12
+ InterruptedEvent,
13
+ SentenceEvent,
14
+ )
15
+ from ._errors import (
16
+ APIConnectionError,
17
+ APIError,
18
+ APITimeoutError,
19
+ AuthenticationError,
20
+ BadRequestError,
21
+ InsufficientBalanceError,
22
+ NotFoundError,
23
+ PermissionDeniedError,
24
+ RateLimitError,
25
+ TalksignError,
26
+ )
27
+ from ._resources import JobWaitTimeout
28
+ from ._splitter import SentenceSplitter
29
+ from ._version import __version__
30
+
31
+ __all__ = [
32
+ "DEFAULT_BASE_URL",
33
+ "APIConnectionError",
34
+ "APIError",
35
+ "APITimeoutError",
36
+ "AsyncTalksign",
37
+ "AuthenticationError",
38
+ "BadRequestError",
39
+ "ClipEvent",
40
+ "DoneEvent",
41
+ "EchoEvent",
42
+ "EchoStream",
43
+ "ErrorEvent",
44
+ "FileInput",
45
+ "IdleEvent",
46
+ "InterruptedEvent",
47
+ "InsufficientBalanceError",
48
+ "JobWaitTimeout",
49
+ "NotFoundError",
50
+ "PermissionDeniedError",
51
+ "RateLimitError",
52
+ "SentenceEvent",
53
+ "SentenceSplitter",
54
+ "Talksign",
55
+ "TalksignError",
56
+ "__version__",
57
+ ]
talksign/_base.py ADDED
@@ -0,0 +1,244 @@
1
+ """HTTP core shared by the sync and async clients: request building, retries, error mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import random
8
+ import time
9
+ import uuid
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import IO, Any, Union
14
+
15
+ import httpx
16
+
17
+ from ._errors import (
18
+ APIConnectionError,
19
+ APITimeoutError,
20
+ TalksignError,
21
+ _parse_retry_after,
22
+ error_from_response,
23
+ )
24
+ from ._version import __version__
25
+
26
+ DEFAULT_BASE_URL = "https://api.talksign.co"
27
+ DEFAULT_TIMEOUT = 60.0
28
+ DEFAULT_MAX_RETRIES = 2
29
+ MAX_RETRY_DELAY = 60.0
30
+ USER_AGENT = f"talksign-python/{__version__}"
31
+
32
+ FileContent = Union[bytes, IO[bytes]] # noqa: UP007
33
+ FileInput = Union[str, "os.PathLike[str]", bytes, IO[bytes], tuple[str, FileContent], tuple[str, FileContent, str]]
34
+ """A file argument: a path, raw bytes, an open binary file, or ``(filename, content[, content_type])``."""
35
+
36
+ _RETRY_STATUS = {408, 429, 500, 502, 503, 504}
37
+
38
+
39
+ @dataclass
40
+ class Req:
41
+ method: str
42
+ path: str
43
+ params: Mapping[str, Any] | None = None
44
+ json: Any = None
45
+ data: Mapping[str, Any] | None = None
46
+ files: Mapping[str, FileInput] | None = None
47
+ binary: bool = False
48
+ idempotency_key: str | None = None
49
+ timeout: float | None = None
50
+ headers: dict[str, str] = field(default_factory=dict)
51
+
52
+
53
+ def _file_tuple(name: str, value: FileInput) -> tuple[str, bytes, str] | tuple[str, bytes]:
54
+ """Reads a file argument into memory once, so retries can resend it."""
55
+ if isinstance(value, tuple):
56
+ filename, content = value[0], value[1]
57
+ raw = content if isinstance(content, bytes) else content.read()
58
+ return (filename, raw, value[2]) if len(value) > 2 else (filename, raw)
59
+ if isinstance(value, (str, os.PathLike)):
60
+ p = Path(value)
61
+ return (p.name, p.read_bytes())
62
+ if isinstance(value, bytes):
63
+ return (name, value)
64
+ raw = value.read()
65
+ filename = os.path.basename(str(getattr(value, "name", "") or name))
66
+ return (filename, raw)
67
+
68
+
69
+ def _form_value(v: Any) -> str:
70
+ if isinstance(v, bool):
71
+ return "true" if v else "false"
72
+ return str(v)
73
+
74
+
75
+ def clean(d: Mapping[str, Any]) -> dict[str, Any]:
76
+ """Drops ``None`` values (optional arguments the caller left out)."""
77
+ return {k: v for k, v in d.items() if v is not None}
78
+
79
+
80
+ class BaseClient:
81
+ def __init__(
82
+ self,
83
+ *,
84
+ api_key: str | None,
85
+ base_url: str | None,
86
+ timeout: float | httpx.Timeout | None,
87
+ max_retries: int,
88
+ default_headers: Mapping[str, str] | None,
89
+ ) -> None:
90
+ key = api_key if api_key is not None else os.environ.get("TALKSIGN_API_KEY")
91
+ if not key:
92
+ raise TalksignError("No API key. Pass api_key=... or set the TALKSIGN_API_KEY environment variable.")
93
+ self.api_key = key
94
+ self.base_url = (base_url or os.environ.get("TALKSIGN_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
95
+ self.timeout = timeout if timeout is not None else DEFAULT_TIMEOUT
96
+ self.max_retries = max(0, int(max_retries))
97
+ self._default_headers = dict(default_headers or {})
98
+
99
+ # -- request building -------------------------------------------------
100
+ def _url(self, path: str) -> str:
101
+ return f"{self.base_url}/v1{path}"
102
+
103
+ def _headers(self, req: Req) -> dict[str, str]:
104
+ h = {
105
+ "Authorization": f"Bearer {self.api_key}",
106
+ "User-Agent": USER_AGENT,
107
+ "Accept": "application/json",
108
+ **self._default_headers,
109
+ **req.headers,
110
+ }
111
+ if req.method == "POST" and req.idempotency_key:
112
+ h["Idempotency-Key"] = req.idempotency_key
113
+ return h
114
+
115
+ @staticmethod
116
+ def _prepare(req: Req) -> None:
117
+ # One key per logical call, reused by every retry, so a retried POST is never charged twice.
118
+ if req.method == "POST" and not req.idempotency_key:
119
+ req.idempotency_key = f"talksign-python-{uuid.uuid4()}"
120
+
121
+ def _build(self, client: httpx.Client | httpx.AsyncClient, req: Req) -> httpx.Request:
122
+ kwargs: dict[str, Any] = {"headers": self._headers(req)}
123
+ if req.params:
124
+ kwargs["params"] = {k: _form_value(v) for k, v in clean(req.params).items()}
125
+ if req.files:
126
+ kwargs["files"] = {k: _file_tuple(k, v) for k, v in req.files.items()}
127
+ if req.data:
128
+ kwargs["data"] = {k: _form_value(v) for k, v in clean(req.data).items()}
129
+ elif req.json is not None:
130
+ kwargs["json"] = req.json
131
+ timeout = req.timeout if req.timeout is not None else self.timeout
132
+ kwargs["timeout"] = timeout
133
+ return client.build_request(req.method, self._url(req.path), **kwargs)
134
+
135
+ # -- retry policy -----------------------------------------------------
136
+ @staticmethod
137
+ def _should_retry(response: httpx.Response) -> bool:
138
+ if response.headers.get("x-should-retry") == "false":
139
+ return False
140
+ if response.status_code in _RETRY_STATUS:
141
+ return True
142
+ if response.status_code == 409:
143
+ # An Idempotency-Key request still running: retrying replays the stored result.
144
+ try:
145
+ body = response.json()
146
+ except ValueError:
147
+ return False
148
+ err = body.get("error") if isinstance(body, dict) else None
149
+ return isinstance(err, dict) and err.get("code") == "idempotency_in_progress"
150
+ return False
151
+
152
+ @staticmethod
153
+ def _retry_delay(attempt: int, response: httpx.Response | None) -> float:
154
+ if response is not None:
155
+ after = _parse_retry_after(response.headers)
156
+ if after is not None:
157
+ return min(after, MAX_RETRY_DELAY)
158
+ base: float = min(0.5 * (2**attempt), 8.0)
159
+ return base * (0.75 + random.random() * 0.5)
160
+
161
+ @staticmethod
162
+ def _parse(response: httpx.Response, req: Req) -> Any:
163
+ if response.status_code >= 400:
164
+ raise error_from_response(response)
165
+ if req.binary and not response.headers.get("content-type", "").startswith("application/json"):
166
+ return response.content
167
+ if not response.content:
168
+ return {}
169
+ try:
170
+ return response.json()
171
+ except ValueError:
172
+ return response.content
173
+
174
+
175
+ class SyncHTTP(BaseClient):
176
+ def __init__(self, *, http_client: httpx.Client | None = None, **kw: Any) -> None:
177
+ super().__init__(**kw)
178
+ self._owns_http = http_client is None
179
+ self._http = http_client or httpx.Client()
180
+
181
+ def request(self, req: Req) -> Any:
182
+ self._prepare(req)
183
+ attempt = 0
184
+ while True:
185
+ try:
186
+ response = self._http.send(self._build(self._http, req))
187
+ except httpx.TimeoutException as e:
188
+ if attempt < self.max_retries:
189
+ time.sleep(self._retry_delay(attempt, None))
190
+ attempt += 1
191
+ continue
192
+ raise APITimeoutError(f"Request timed out: {e}") from e
193
+ except httpx.TransportError as e:
194
+ if attempt < self.max_retries:
195
+ time.sleep(self._retry_delay(attempt, None))
196
+ attempt += 1
197
+ continue
198
+ raise APIConnectionError(f"Connection error: {e}") from e
199
+ if attempt < self.max_retries and self._should_retry(response):
200
+ response.close()
201
+ time.sleep(self._retry_delay(attempt, response))
202
+ attempt += 1
203
+ continue
204
+ return self._parse(response, req)
205
+
206
+ def close(self) -> None:
207
+ if self._owns_http:
208
+ self._http.close()
209
+
210
+
211
+ class AsyncHTTP(BaseClient):
212
+ def __init__(self, *, http_client: httpx.AsyncClient | None = None, **kw: Any) -> None:
213
+ super().__init__(**kw)
214
+ self._owns_http = http_client is None
215
+ self._http = http_client or httpx.AsyncClient()
216
+
217
+ async def request(self, req: Req) -> Any:
218
+ self._prepare(req)
219
+ attempt = 0
220
+ while True:
221
+ try:
222
+ response = await self._http.send(self._build(self._http, req))
223
+ except httpx.TimeoutException as e:
224
+ if attempt < self.max_retries:
225
+ await asyncio.sleep(self._retry_delay(attempt, None))
226
+ attempt += 1
227
+ continue
228
+ raise APITimeoutError(f"Request timed out: {e}") from e
229
+ except httpx.TransportError as e:
230
+ if attempt < self.max_retries:
231
+ await asyncio.sleep(self._retry_delay(attempt, None))
232
+ attempt += 1
233
+ continue
234
+ raise APIConnectionError(f"Connection error: {e}") from e
235
+ if attempt < self.max_retries and self._should_retry(response):
236
+ await response.aclose()
237
+ await asyncio.sleep(self._retry_delay(attempt, response))
238
+ attempt += 1
239
+ continue
240
+ return self._parse(response, req)
241
+
242
+ async def aclose(self) -> None:
243
+ if self._owns_http:
244
+ await self._http.aclose()
talksign/_client.py ADDED
@@ -0,0 +1,240 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any, Literal, cast
5
+
6
+ import httpx
7
+
8
+ from . import _requests as r
9
+ from ._base import DEFAULT_MAX_RETRIES, AsyncHTTP, SyncHTTP
10
+ from ._echo import EchoStream
11
+ from ._resources import (
12
+ AsyncAvatars,
13
+ AsyncBalanceResource,
14
+ AsyncJobs,
15
+ AsyncMeetings,
16
+ AsyncModels,
17
+ AsyncSignToSpeech,
18
+ AsyncSpeechToSign,
19
+ AsyncSpeechToSpeech,
20
+ AsyncTokens,
21
+ AsyncUploads,
22
+ AsyncUsageResource,
23
+ AsyncVoiceResource,
24
+ Avatars,
25
+ BalanceResource,
26
+ Jobs,
27
+ Meetings,
28
+ Models,
29
+ SignToSpeech,
30
+ SpeechToSign,
31
+ SpeechToSpeech,
32
+ Tokens,
33
+ Uploads,
34
+ UsageResource,
35
+ VoiceResource,
36
+ )
37
+ from .types import Warmup
38
+
39
+ __all__ = ["AsyncTalksign", "Talksign"]
40
+
41
+
42
+ class Talksign(SyncHTTP):
43
+ """Synchronous Talksign client.
44
+
45
+ ``api_key`` defaults to the ``TALKSIGN_API_KEY`` environment variable and ``base_url`` to
46
+ ``TALKSIGN_BASE_URL`` or ``https://api.talksign.co``. Retries 429/5xx/network errors ``max_retries`` times.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ *,
52
+ api_key: str | None = None,
53
+ base_url: str | None = None,
54
+ timeout: float | httpx.Timeout | None = None,
55
+ max_retries: int = DEFAULT_MAX_RETRIES,
56
+ default_headers: Mapping[str, str] | None = None,
57
+ http_client: httpx.Client | None = None,
58
+ ) -> None:
59
+ super().__init__(
60
+ api_key=api_key,
61
+ base_url=base_url,
62
+ timeout=timeout,
63
+ max_retries=max_retries,
64
+ default_headers=default_headers,
65
+ http_client=http_client,
66
+ )
67
+ self.speech_to_sign = SpeechToSign(self)
68
+ self.avatars = Avatars(self)
69
+ self.sign_to_speech = SignToSpeech(self)
70
+ self.speech_to_speech = SpeechToSpeech(self)
71
+ self.voice = VoiceResource(self)
72
+ self.jobs = Jobs(self)
73
+ self.uploads = Uploads(self)
74
+ self.meetings = Meetings(self)
75
+ self.models = Models(self)
76
+ self.usage = UsageResource(self)
77
+ self.balance = BalanceResource(self)
78
+ self.tokens = Tokens(self)
79
+ self.echo = Echo(self)
80
+
81
+ def warmup(self) -> Warmup:
82
+ """Same as ``models.warmup()``."""
83
+ return self.models.warmup()
84
+
85
+ def openapi(self) -> dict[str, Any]:
86
+ """The API's OpenAPI 3.1 document."""
87
+ return cast(dict[str, Any], self.request(r.openapi()))
88
+
89
+ def __enter__(self) -> Talksign:
90
+ return self
91
+
92
+ def __exit__(self, *exc: object) -> None:
93
+ self.close()
94
+
95
+
96
+ class AsyncTalksign(AsyncHTTP):
97
+ """Asynchronous Talksign client (same resources as :class:`Talksign`, methods are ``async``)."""
98
+
99
+ def __init__(
100
+ self,
101
+ *,
102
+ api_key: str | None = None,
103
+ base_url: str | None = None,
104
+ timeout: float | httpx.Timeout | None = None,
105
+ max_retries: int = DEFAULT_MAX_RETRIES,
106
+ default_headers: Mapping[str, str] | None = None,
107
+ http_client: httpx.AsyncClient | None = None,
108
+ ) -> None:
109
+ super().__init__(
110
+ api_key=api_key,
111
+ base_url=base_url,
112
+ timeout=timeout,
113
+ max_retries=max_retries,
114
+ default_headers=default_headers,
115
+ http_client=http_client,
116
+ )
117
+ self.speech_to_sign = AsyncSpeechToSign(self)
118
+ self.avatars = AsyncAvatars(self)
119
+ self.sign_to_speech = AsyncSignToSpeech(self)
120
+ self.speech_to_speech = AsyncSpeechToSpeech(self)
121
+ self.voice = AsyncVoiceResource(self)
122
+ self.jobs = AsyncJobs(self)
123
+ self.uploads = AsyncUploads(self)
124
+ self.meetings = AsyncMeetings(self)
125
+ self.models = AsyncModels(self)
126
+ self.usage = AsyncUsageResource(self)
127
+ self.balance = AsyncBalanceResource(self)
128
+ self.tokens = AsyncTokens(self)
129
+ self.echo = AsyncEcho(self)
130
+
131
+ async def warmup(self) -> Warmup:
132
+ """Same as ``models.warmup()``."""
133
+ return await self.models.warmup()
134
+
135
+ async def openapi(self) -> dict[str, Any]:
136
+ return cast(dict[str, Any], await self.request(r.openapi()))
137
+
138
+ async def __aenter__(self) -> AsyncTalksign:
139
+ return self
140
+
141
+ async def __aexit__(self, *exc: object) -> None:
142
+ await self.aclose()
143
+
144
+
145
+ _STREAM_DOC = """Opens a live :class:`EchoStream`.
146
+
147
+ Args:
148
+ avatar: preset (``arthur``, ``amara``) or one of your custom avatar ids.
149
+ language: sign language (``asl``; ``bsl`` when enabled for your account).
150
+ max_chars: force a sentence cut after this many characters.
151
+ idle_flush: force a cut after this many seconds without new text.
152
+ prefetch: how many sentences to request ahead of the one being delivered.
153
+ chunking: ``"sentence"`` (default: one call per sentence, lowest latency) or ``"full"`` (buffer
154
+ everything until :meth:`EchoStream.flush` / close and sign it in one call).
155
+ first_chunk_chars: in ``"sentence"`` mode, let the first piece of each reply be cut at a comma /
156
+ clause boundary once it has this many characters, so the avatar starts sooner. ``0`` = off.
157
+ fetch_idle: fetch the avatar's idle loop at start (one free ``GET /v1/avatars/{id}``), so a player
158
+ can show the avatar before the first sentence. An ``idle`` event with ``reason="ready"`` follows.
159
+ """
160
+
161
+
162
+ class AsyncEcho:
163
+ def __init__(self, client: AsyncTalksign) -> None:
164
+ self._client = client
165
+
166
+ def stream(
167
+ self,
168
+ *,
169
+ avatar: str = "arthur",
170
+ language: str = "asl",
171
+ model: str | None = None,
172
+ config: Mapping[str, Any] | None = None,
173
+ max_chars: int = 120,
174
+ idle_flush: float = 1.2,
175
+ prefetch: int = 1,
176
+ chunking: Literal["sentence", "full"] = "sentence",
177
+ first_chunk_chars: int = 40,
178
+ fetch_idle: bool = True,
179
+ ) -> EchoStream:
180
+ return EchoStream(
181
+ self._client.speech_to_sign,
182
+ avatars=self._client.avatars if fetch_idle else None,
183
+ chunking=chunking,
184
+ first_chunk_chars=first_chunk_chars,
185
+ avatar=avatar,
186
+ language=language,
187
+ model=model,
188
+ config=config,
189
+ max_chars=max_chars,
190
+ idle_flush=idle_flush,
191
+ prefetch=prefetch,
192
+ )
193
+
194
+ stream.__doc__ = _STREAM_DOC
195
+
196
+
197
+ class Echo:
198
+ """Live signing for the sync client. The stream itself is async (it runs inside your event loop)."""
199
+
200
+ def __init__(self, client: Talksign) -> None:
201
+ self._client = client
202
+
203
+ def stream(
204
+ self,
205
+ *,
206
+ avatar: str = "arthur",
207
+ language: str = "asl",
208
+ model: str | None = None,
209
+ config: Mapping[str, Any] | None = None,
210
+ max_chars: int = 120,
211
+ idle_flush: float = 1.2,
212
+ prefetch: int = 1,
213
+ chunking: Literal["sentence", "full"] = "sentence",
214
+ first_chunk_chars: int = 40,
215
+ fetch_idle: bool = True,
216
+ ) -> EchoStream:
217
+ c = self._client
218
+ aclient = AsyncTalksign(
219
+ api_key=c.api_key,
220
+ base_url=c.base_url,
221
+ timeout=c.timeout,
222
+ max_retries=c.max_retries,
223
+ default_headers=c._default_headers,
224
+ )
225
+ return EchoStream(
226
+ aclient.speech_to_sign,
227
+ avatars=aclient.avatars if fetch_idle else None,
228
+ chunking=chunking,
229
+ first_chunk_chars=first_chunk_chars,
230
+ avatar=avatar,
231
+ language=language,
232
+ model=model,
233
+ config=config,
234
+ max_chars=max_chars,
235
+ idle_flush=idle_flush,
236
+ prefetch=prefetch,
237
+ on_close=aclient.aclose,
238
+ )
239
+
240
+ stream.__doc__ = _STREAM_DOC