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/_splitter.py ADDED
@@ -0,0 +1,124 @@
1
+ """Sentence splitter for streamed text (LLM tokens, TTS text chunks)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ["SentenceSplitter"]
6
+
7
+ _TERMINATORS = ".!?…\n"
8
+ _CLOSERS = "\"'”’)]»"
9
+ _CLAUSE = ",;:—–"
10
+ _ABBREVIATIONS = frozenset({"mr", "mrs", "ms", "dr", "prof", "st", "vs", "etc", "e.g", "i.e", "jr", "sr", "no"})
11
+
12
+
13
+ class SentenceSplitter:
14
+ """Cuts streamed text into sentences.
15
+
16
+ A sentence ends at ``. ! ? …`` or a newline. A ``.`` between digits (``3.5``) is not a cut, and a
17
+ terminator at the very end of the buffered text right after a digit waits for the next chunk.
18
+ Text longer than ``max_chars`` is cut at the last space before the limit. :meth:`flush` returns
19
+ whatever is left (the caller also flushes after a pause with no new text).
20
+
21
+ ``first_chunk_chars`` (0 = off): until the first piece of a turn is out, a clause boundary
22
+ (``, ; : —`` followed by a space) after at least this many characters is also a cut, so a live
23
+ avatar can start signing before the first full sentence has arrived. A turn ends at
24
+ :meth:`flush` / :meth:`clear`.
25
+ """
26
+
27
+ def __init__(self, max_chars: int = 120, first_chunk_chars: int = 0) -> None:
28
+ if max_chars < 8:
29
+ raise ValueError("max_chars must be at least 8")
30
+ if first_chunk_chars < 0:
31
+ raise ValueError("first_chunk_chars must be >= 0")
32
+ self.max_chars = max_chars
33
+ self.first_chunk_chars = first_chunk_chars
34
+ self._buf = ""
35
+ self._first = True
36
+
37
+ @property
38
+ def pending(self) -> str:
39
+ """Text received but not yet returned as a sentence."""
40
+ return self._buf
41
+
42
+ def push(self, text: str) -> list[str]:
43
+ """Adds a chunk; returns the sentences it completed (possibly none)."""
44
+ if text:
45
+ self._buf += text
46
+ out: list[str] = []
47
+ while True:
48
+ cut = self._find_cut()
49
+ if cut is None and self._first and self.first_chunk_chars:
50
+ cut = self._clause_cut()
51
+ if cut is None:
52
+ break
53
+ piece, self._buf = self._buf[:cut], self._buf[cut:]
54
+ _add(out, piece)
55
+ if out:
56
+ self._first = False
57
+ return out
58
+
59
+ def flush(self) -> str | None:
60
+ """Returns the remaining text as a sentence (or ``None`` if there is nothing to sign)."""
61
+ piece, self._buf = self._buf, ""
62
+ self._first = True
63
+ out: list[str] = []
64
+ _add(out, piece)
65
+ return out[0] if out else None
66
+
67
+ def clear(self) -> None:
68
+ self._buf = ""
69
+ self._first = True
70
+
71
+ def _clause_cut(self) -> int | None:
72
+ buf = self._buf
73
+ for i in range(self.first_chunk_chars, len(buf) - 1):
74
+ if buf[i] in _CLAUSE and buf[i + 1].isspace():
75
+ return i + 1
76
+ return None
77
+
78
+ def _find_cut(self) -> int | None:
79
+ buf = self._buf
80
+ n = len(buf)
81
+ i = 0
82
+ while i < n:
83
+ ch = buf[i]
84
+ if ch in _TERMINATORS:
85
+ if ch == "." and 0 < i and buf[i - 1].isdigit():
86
+ if i + 1 < n and buf[i + 1].isdigit():
87
+ i += 1
88
+ continue
89
+ if i + 1 == n:
90
+ return self._length_cut() # "3." may still become "3.5"
91
+ if ch == "." and _word_before(buf, i).lower() in _ABBREVIATIONS:
92
+ i += 1
93
+ continue
94
+ end = i + 1
95
+ while end < n and (buf[end] in _TERMINATORS or buf[end] in _CLOSERS) and buf[end] != "\n":
96
+ end += 1
97
+ if ch != "\n" and end < n and not buf[end].isspace():
98
+ # "e.g" / "U.S" style: only cut when followed by whitespace or the end.
99
+ i = end
100
+ continue
101
+ return end
102
+ if i >= self.max_chars:
103
+ return self._length_cut()
104
+ i += 1
105
+ return self._length_cut()
106
+
107
+ def _length_cut(self) -> int | None:
108
+ if len(self._buf) <= self.max_chars:
109
+ return None
110
+ space = self._buf.rfind(" ", 0, self.max_chars + 1)
111
+ return space + 1 if space > 0 else self.max_chars
112
+
113
+
114
+ def _word_before(buf: str, i: int) -> str:
115
+ j = i
116
+ while j > 0 and not buf[j - 1].isspace():
117
+ j -= 1
118
+ return buf[j:i]
119
+
120
+
121
+ def _add(out: list[str], piece: str) -> None:
122
+ s = " ".join(piece.split())
123
+ if any(c.isalnum() for c in s):
124
+ out.append(s)
talksign/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
talksign/py.typed ADDED
File without changes
talksign/types.py ADDED
@@ -0,0 +1,379 @@
1
+ """Typed shapes of Talksign API responses.
2
+
3
+ They are ``TypedDict``\\ s: responses are plain ``dict`` objects (exactly the JSON the API sent),
4
+ so new fields added by the API never break your code, and type checkers still know the keys.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Literal, TypedDict
10
+
11
+ __all__ = [
12
+ "Avatar",
13
+ "AvatarQualityCheck",
14
+ "AvatarQualityResult",
15
+ "AvatarResponse",
16
+ "AvatarsData",
17
+ "AvatarsResponse",
18
+ "Balance",
19
+ "BalanceLot",
20
+ "BrowserToken",
21
+ "Clip",
22
+ "ClipTransition",
23
+ "DeleteResponse",
24
+ "GlossData",
25
+ "GlossResponse",
26
+ "IdleClip",
27
+ "Job",
28
+ "JobError",
29
+ "JobList",
30
+ "JobResult",
31
+ "JobStatus",
32
+ "JobType",
33
+ "JobUsage",
34
+ "Meeting",
35
+ "ModelOption",
36
+ "ModelsResponse",
37
+ "RealtimeData",
38
+ "RealtimeResponse",
39
+ "SpeechToSpeechData",
40
+ "SpeechToSpeechResponse",
41
+ "StudioData",
42
+ "StudioResponse",
43
+ "Upload",
44
+ "Usage",
45
+ "UsageList",
46
+ "UsageRecord",
47
+ "Voice",
48
+ "VoiceJsonData",
49
+ "VoiceJsonResponse",
50
+ "VoiceList",
51
+ "Warmup",
52
+ "Warning",
53
+ ]
54
+
55
+ JobType = Literal["sign_video", "captions", "sign_morph"]
56
+ JobStatus = Literal["queued", "processing", "succeeded", "failed", "canceled"]
57
+
58
+
59
+ class Usage(TypedDict, total=False):
60
+ """Charge for one call (every paid response carries it)."""
61
+
62
+ type: str
63
+ durationSeconds: float
64
+ costUsd: float
65
+ walletRemainingUsd: float | None
66
+
67
+
68
+ class ClipTransition(TypedDict, total=False):
69
+ effect: str
70
+ duration_ms: int
71
+
72
+
73
+ class Clip(TypedDict, total=False):
74
+ """One word of a realtime playlist.
75
+
76
+ Play order: ``in_url`` (at ``in_out_speed``) -> ``url`` from ``active_start_s`` to ``active_end_s``
77
+ -> ``out_url`` (at ``in_out_speed``). When ``in_url``/``out_url`` are ``None``, play ``url`` in full.
78
+ """
79
+
80
+ gloss: str
81
+ group: int | str | None
82
+ letter: str | None
83
+ url: str | None
84
+ alphaUrl: str | None
85
+ tier: str
86
+ transition: ClipTransition
87
+ in_url: str | None
88
+ out_url: str | None
89
+ in_alpha_url: str | None
90
+ out_alpha_url: str | None
91
+ active_start_s: float | None
92
+ active_end_s: float | None
93
+ in_out_speed: float | None
94
+
95
+
96
+ class IdleClip(TypedDict, total=False):
97
+ url: str
98
+ expires_at: str
99
+
100
+
101
+ class RealtimeData(TypedDict, total=False):
102
+ language: str
103
+ avatar: str
104
+ text: str
105
+ glosses: list[str]
106
+ playlist: list[Clip]
107
+ idle: IdleClip | None
108
+ expires_at: str
109
+ transition: ClipTransition
110
+ has_missing: bool
111
+ notice: str
112
+ requested_avatar: str
113
+ model_notice: str
114
+ input: str
115
+ transcript: str
116
+
117
+
118
+ class RealtimeResponse(TypedDict, total=False):
119
+ success: bool
120
+ data: RealtimeData
121
+ usage: Usage
122
+
123
+
124
+ class StudioData(TypedDict, total=False):
125
+ videoUrl: str
126
+ video_url: str
127
+ download_url: str | None
128
+ expires_at: str | None
129
+ requestId: str | None
130
+ durationSeconds: float
131
+ avatar: str
132
+ language: str
133
+
134
+
135
+ class StudioResponse(TypedDict, total=False):
136
+ success: bool
137
+ data: StudioData
138
+ usage: Usage
139
+
140
+
141
+ class GlossData(TypedDict, total=False):
142
+ text: str
143
+ language: str
144
+ gloss: str
145
+ glosses: list[str]
146
+ proper_nouns: list[str]
147
+
148
+
149
+ class GlossResponse(TypedDict, total=False):
150
+ success: bool
151
+ data: GlossData
152
+ usage: Usage
153
+
154
+
155
+ class Warning(TypedDict, total=False): # noqa: A001 - mirrors the API field name
156
+ code: str
157
+ message: str
158
+
159
+
160
+ class Avatar(TypedDict, total=False):
161
+ id: str
162
+ name: str
163
+ is_preset: bool
164
+ languages: list[str]
165
+ status: Literal["pending", "processing", "ready", "failed", "rejected_quality"]
166
+ quality_reasons: list[Warning]
167
+ moderationStatus: Literal["pending", "approved", "rejected"]
168
+ progress: int
169
+ progress_label: str | None
170
+ estimated_ready_at: str | None
171
+ preview_url: str | None
172
+ paused: bool
173
+ preparing_languages: list[str]
174
+ idle: IdleClip | None
175
+ """The avatar's idle loop (signed URL, short-lived) or ``None``. Show it before the first sentence."""
176
+ coming_soon: bool
177
+
178
+
179
+ class AvatarsData(TypedDict, total=False):
180
+ system_avatars: list[Avatar]
181
+ custom_avatars: list[Avatar]
182
+ total: int
183
+
184
+
185
+ class AvatarsResponse(TypedDict, total=False):
186
+ success: bool
187
+ data: AvatarsData
188
+
189
+
190
+ class AvatarResponse(TypedDict, total=False):
191
+ success: bool
192
+ data: Avatar
193
+ warnings: list[Warning]
194
+
195
+
196
+ class BrowserToken(TypedDict, total=False):
197
+ object: Literal["token"]
198
+ token: str
199
+ expires_at: str
200
+ expires_in: int
201
+ scopes: list[str]
202
+ allowed_origins: list[str] | None
203
+
204
+
205
+ class AvatarQualityCheck(TypedDict, total=False):
206
+ code: str
207
+ # "pass" is a Python keyword; read it as check["pass"].
208
+ severity: Literal["hard", "soft"]
209
+ message: str
210
+
211
+
212
+ class AvatarQualityResult(TypedDict, total=False):
213
+ ok: bool
214
+ checks: list[AvatarQualityCheck]
215
+ warnings: list[Warning]
216
+
217
+
218
+ class DeleteResponse(TypedDict, total=False):
219
+ success: bool
220
+ message: str
221
+
222
+
223
+ class SpeechToSpeechData(TypedDict, total=False):
224
+ translatedText: str
225
+ fromLang: str | None
226
+ toLang: str
227
+
228
+
229
+ class SpeechToSpeechResponse(TypedDict, total=False):
230
+ success: bool
231
+ data: SpeechToSpeechData
232
+ usage: Usage
233
+
234
+
235
+ class ModelOption(TypedDict, total=False):
236
+ id: str
237
+ label: str
238
+ description: str
239
+
240
+
241
+ class ModelsResponse(TypedDict, total=False):
242
+ success: bool
243
+ data: dict[str, Any]
244
+
245
+
246
+ class Warmup(TypedDict, total=False):
247
+ warm: bool
248
+ ms: int
249
+
250
+
251
+ class JobResult(TypedDict, total=False):
252
+ download_url: str | None
253
+ expires_at: str | None
254
+ video_url: str | None
255
+ requestId: str | None
256
+ durationSeconds: float
257
+ avatar: str
258
+ language: str
259
+ srt_url: str | None
260
+ vtt_url: str | None
261
+ lines: int
262
+ transcript: str
263
+ input: str
264
+ quality: str
265
+ billedSeconds: float
266
+
267
+
268
+ class JobError(TypedDict, total=False):
269
+ code: str
270
+ message: str
271
+
272
+
273
+ class JobUsage(TypedDict, total=False):
274
+ type: str
275
+ durationSeconds: float | None
276
+ costUsd: float
277
+
278
+
279
+ class Job(TypedDict, total=False):
280
+ id: str
281
+ object: Literal["job"]
282
+ type: JobType
283
+ status: JobStatus
284
+ created_at: str
285
+ started_at: str | None
286
+ finished_at: str | None
287
+ result: JobResult | None
288
+ error: JobError | None
289
+ usage: JobUsage | None
290
+
291
+
292
+ class JobList(TypedDict, total=False):
293
+ object: Literal["list"]
294
+ data: list[Job]
295
+ has_more: bool
296
+
297
+
298
+ class Upload(TypedDict, total=False):
299
+ id: str
300
+ object: Literal["upload"]
301
+ upload_url: str
302
+ method: Literal["PUT"]
303
+ headers: dict[str, str]
304
+ expires_at: str
305
+
306
+
307
+ class Meeting(TypedDict, total=False):
308
+ id: str
309
+ object: Literal["meeting"]
310
+ status: Literal["requested", "joining", "waiting_room", "live", "ended", "failed"]
311
+ platform: Literal["meet", "zoom", "teams"]
312
+ meeting_url: str
313
+ avatar: str
314
+ background: str | None
315
+ created_at: str
316
+ joined_at: str | None
317
+ ended_at: str | None
318
+ end_reason: str | None
319
+ paused: bool
320
+ billed_seconds: float
321
+ cost_usd: float | None
322
+ reserved_usd: float
323
+
324
+
325
+ class Voice(TypedDict, total=False):
326
+ id: str
327
+ name: str
328
+ default: bool
329
+
330
+
331
+ class VoiceList(TypedDict, total=False):
332
+ object: Literal["list"]
333
+ data: list[Voice]
334
+
335
+
336
+ class VoiceJsonData(TypedDict, total=False):
337
+ audio_base64: str
338
+ content_type: str
339
+ characters: int
340
+
341
+
342
+ class VoiceJsonResponse(TypedDict, total=False):
343
+ data: VoiceJsonData
344
+ usage: Usage
345
+
346
+
347
+ class UsageRecord(TypedDict, total=False):
348
+ id: str
349
+ object: Literal["usage_record"]
350
+ created_at: str
351
+ endpoint: str
352
+ status: int
353
+ product: str | None
354
+ quantity: float | None
355
+ unit: str | None
356
+ cost_usd: float
357
+ api_key_id: str | None
358
+
359
+
360
+ class UsageList(TypedDict, total=False):
361
+ object: Literal["list"]
362
+ data: list[UsageRecord]
363
+ has_more: bool
364
+
365
+
366
+ class BalanceLot(TypedDict, total=False):
367
+ remaining_usd: float
368
+ expires_at: str
369
+ label: str
370
+ """``"Welcome credit"`` for the one-time welcome credit."""
371
+
372
+
373
+ class Balance(TypedDict, total=False):
374
+ object: Literal["balance"]
375
+ currency: Literal["usd"]
376
+ available_usd: float
377
+ reserved_usd: float
378
+ credit_lots_usd: float
379
+ lots: list[BalanceLot]