dtelecom-server-sdk 0.1.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.
- dtelecom_server/__init__.py +43 -0
- dtelecom_server/_typing/livekit_egress_pb2.pyi +473 -0
- dtelecom_server/_typing/livekit_ingress_pb2.pyi +213 -0
- dtelecom_server/_typing/livekit_models_pb2.pyi +524 -0
- dtelecom_server/_typing/livekit_room_pb2.pyi +154 -0
- dtelecom_server/_typing/livekit_webhook_pb2.pyi +28 -0
- dtelecom_server/client.py +159 -0
- dtelecom_server/http.py +112 -0
- dtelecom_server/models.py +250 -0
- dtelecom_server/moderation.py +84 -0
- dtelecom_server/protocol/LICENSE +202 -0
- dtelecom_server/protocol/NOTICE +1 -0
- dtelecom_server/protocol/__init__.py +25 -0
- dtelecom_server/protocol/wire.pb +0 -0
- dtelecom_server/py.typed +0 -0
- dtelecom_server/room.py +298 -0
- dtelecom_server/services.py +273 -0
- dtelecom_server/speech.py +642 -0
- dtelecom_server/webhooks.py +148 -0
- dtelecom_server/wire.py +32 -0
- dtelecom_server_sdk-0.1.0.dist-info/METADATA +78 -0
- dtelecom_server_sdk-0.1.0.dist-info/RECORD +25 -0
- dtelecom_server_sdk-0.1.0.dist-info/WHEEL +4 -0
- dtelecom_server_sdk-0.1.0.dist-info/licenses/LICENSE +201 -0
- dtelecom_server_sdk-0.1.0.dist-info/licenses/NOTICE +9 -0
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
"""Asynchronous clients for authenticated dTelecom streaming speech sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from collections import deque
|
|
9
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
10
|
+
from contextlib import suppress
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
from websockets.asyncio.client import ClientConnection, connect
|
|
17
|
+
from websockets.exceptions import ConnectionClosed
|
|
18
|
+
|
|
19
|
+
from .http import CloudApiError
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from . import CloudClient
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SpeechError(Exception):
|
|
26
|
+
"""A speech service rejected the request or its response was invalid."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _stream_url(origin: str) -> str:
|
|
30
|
+
url = urlsplit(origin)
|
|
31
|
+
scheme = {"http": "ws", "https": "wss", "ws": "ws", "wss": "wss"}.get(url.scheme)
|
|
32
|
+
if (
|
|
33
|
+
not scheme
|
|
34
|
+
or not url.hostname
|
|
35
|
+
or url.username
|
|
36
|
+
or url.password
|
|
37
|
+
or url.path.rstrip("/") not in ("", "/v1/stream")
|
|
38
|
+
):
|
|
39
|
+
raise ValueError("Expected a speech server origin or /v1/stream URL")
|
|
40
|
+
return urlunsplit((scheme, url.netloc, "/v1/stream", url.query, ""))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class SpeechCredentials:
|
|
44
|
+
"""Cloud session issuer or a single-use speech key and optional refresh callback."""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
*,
|
|
49
|
+
cloud: CloudClient | None = None,
|
|
50
|
+
webrtc_session_id: str | None = None,
|
|
51
|
+
server_url: str | None = None,
|
|
52
|
+
session_key: str | None = None,
|
|
53
|
+
get_session_key: Callable[[], Awaitable[tuple[str, str]]] | None = None,
|
|
54
|
+
):
|
|
55
|
+
if cloud is None and not (server_url and session_key):
|
|
56
|
+
raise ValueError(
|
|
57
|
+
"Provide a Cloud client or both server_url and session_key"
|
|
58
|
+
)
|
|
59
|
+
if cloud is not None and (server_url or session_key or get_session_key):
|
|
60
|
+
raise ValueError("Choose one credential source")
|
|
61
|
+
self.cloud = cloud
|
|
62
|
+
self.webrtc_session_id = webrtc_session_id
|
|
63
|
+
self._url = server_url
|
|
64
|
+
self._key = session_key
|
|
65
|
+
self._refresh = get_session_key
|
|
66
|
+
self._lock = asyncio.Lock()
|
|
67
|
+
|
|
68
|
+
async def _external_grant(self) -> tuple[str, str]:
|
|
69
|
+
async with self._lock:
|
|
70
|
+
if self._key and self._url:
|
|
71
|
+
key, self._key = self._key, None
|
|
72
|
+
return self._url, key
|
|
73
|
+
if self._refresh:
|
|
74
|
+
return await self._refresh()
|
|
75
|
+
raise SpeechError("A new connection needs a fresh session key")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _expiration(value: datetime | str) -> float:
|
|
79
|
+
if isinstance(value, str):
|
|
80
|
+
value = datetime.fromisoformat(value)
|
|
81
|
+
return value.timestamp()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
_RENEW_RETRY_SECONDS = 15.0
|
|
85
|
+
_CONNECT_RETRY_SECONDS = 1.0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _safe_retry(exc: Exception) -> bool:
|
|
89
|
+
# Speech grant writes have no idempotency key. Retry only when the request
|
|
90
|
+
# didn't leave the client or the Cloud explicitly declined it.
|
|
91
|
+
return isinstance(
|
|
92
|
+
exc, (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
|
|
93
|
+
) or (
|
|
94
|
+
isinstance(exc, CloudApiError)
|
|
95
|
+
and (
|
|
96
|
+
exc.status == 429
|
|
97
|
+
or (exc.status == 503 and exc.code == "no_servers_available")
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _retry_delay(exc: Exception, minimum: float) -> float:
|
|
103
|
+
return max(minimum, (exc.retry_after or 0) if isinstance(exc, CloudApiError) else 0)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class _Lease:
|
|
107
|
+
def __init__(
|
|
108
|
+
self, credentials: SpeechCredentials, kind: str, amount: int, margin: int
|
|
109
|
+
):
|
|
110
|
+
if amount <= 0 or margin <= 0 or (kind == "stt" and margin >= amount):
|
|
111
|
+
raise ValueError("Invalid speech session reservation or renewal threshold")
|
|
112
|
+
self.credentials = credentials
|
|
113
|
+
self.kind, self.amount, self.margin = kind, amount, margin
|
|
114
|
+
self.session_id: str | None = None
|
|
115
|
+
self.expires = 0.0
|
|
116
|
+
self._limit = amount
|
|
117
|
+
self._used = 0
|
|
118
|
+
self._timer: asyncio.TimerHandle | None = None
|
|
119
|
+
self._extension: asyncio.Task | None = None
|
|
120
|
+
self._expiry_close: asyncio.Task | None = None
|
|
121
|
+
self._last_issue: Exception | None = None
|
|
122
|
+
self._retry_at = 0.0
|
|
123
|
+
self.error: Exception | None = None
|
|
124
|
+
self.socket: ClientConnection | None = None
|
|
125
|
+
|
|
126
|
+
async def open(self, language: str, voice: str | None = None) -> tuple[str, str]:
|
|
127
|
+
cloud = self.credentials.cloud
|
|
128
|
+
if cloud is None:
|
|
129
|
+
return await self.credentials._external_grant()
|
|
130
|
+
common = {"language": language}
|
|
131
|
+
if self.credentials.webrtc_session_id:
|
|
132
|
+
common["webrtc_session_id"] = self.credentials.webrtc_session_id
|
|
133
|
+
if self.kind == "stt":
|
|
134
|
+
session = await cloud.stt.create_session(
|
|
135
|
+
duration=self.amount * 60, **common
|
|
136
|
+
)
|
|
137
|
+
else:
|
|
138
|
+
session = await cloud.tts.create_session(
|
|
139
|
+
max_characters=self.amount, voice=voice, **common
|
|
140
|
+
)
|
|
141
|
+
self.session_id = session.session_id
|
|
142
|
+
self.expires = _expiration(session.expires_at)
|
|
143
|
+
return session.stream_url or session.server_url, session.token
|
|
144
|
+
|
|
145
|
+
def attach(self, socket: ClientConnection) -> None:
|
|
146
|
+
self.socket = socket
|
|
147
|
+
self._schedule()
|
|
148
|
+
|
|
149
|
+
def _schedule(self) -> None:
|
|
150
|
+
if self._timer:
|
|
151
|
+
self._timer.cancel()
|
|
152
|
+
if (
|
|
153
|
+
not self.session_id
|
|
154
|
+
or not self.socket
|
|
155
|
+
or self.socket.close_code is not None
|
|
156
|
+
or self.error
|
|
157
|
+
):
|
|
158
|
+
return
|
|
159
|
+
margin_seconds = self.margin * 60 if self.kind == "stt" else 120
|
|
160
|
+
due = min(self.expires, max(self.expires - margin_seconds, self._retry_at))
|
|
161
|
+
if self._extension or (self._last_issue and not _safe_retry(self._last_issue)):
|
|
162
|
+
due = self.expires
|
|
163
|
+
self._timer = asyncio.get_running_loop().call_later(
|
|
164
|
+
max(0, due - time.time()), self._on_timer
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def _on_timer(self) -> None:
|
|
168
|
+
self._timer = None
|
|
169
|
+
if not self.socket or self.socket.close_code is not None:
|
|
170
|
+
return
|
|
171
|
+
if time.time() >= self.expires:
|
|
172
|
+
self.error = self._last_issue or SpeechError("Speech session expired")
|
|
173
|
+
self._expiry_close = asyncio.create_task(self.socket.close())
|
|
174
|
+
else:
|
|
175
|
+
self._begin_extension(self.amount)
|
|
176
|
+
|
|
177
|
+
def _begin_extension(self, amount: int) -> asyncio.Task:
|
|
178
|
+
if not self._extension:
|
|
179
|
+
self._extension = asyncio.create_task(self._run_extension(amount))
|
|
180
|
+
self._schedule()
|
|
181
|
+
return self._extension
|
|
182
|
+
|
|
183
|
+
async def _run_extension(self, amount: int) -> None:
|
|
184
|
+
socket, cloud = self.socket, self.credentials.cloud
|
|
185
|
+
assert socket and cloud and self.session_id
|
|
186
|
+
try:
|
|
187
|
+
try:
|
|
188
|
+
if self.kind == "stt":
|
|
189
|
+
result = await cloud.stt.extend(self.session_id, amount * 60)
|
|
190
|
+
else:
|
|
191
|
+
tts_result = await cloud.tts.extend(self.session_id, amount)
|
|
192
|
+
if tts_result.max_characters <= self._limit:
|
|
193
|
+
raise SpeechError("Cloud did not increase the TTS allowance")
|
|
194
|
+
self._limit = tts_result.max_characters
|
|
195
|
+
result = tts_result
|
|
196
|
+
self.expires = _expiration(result.expires_at)
|
|
197
|
+
except Exception as exc: # noqa: BLE001 - surfaced to the consumer at the hold boundary
|
|
198
|
+
self._last_issue = exc
|
|
199
|
+
self._retry_at = time.time() + _retry_delay(exc, _RENEW_RETRY_SECONDS)
|
|
200
|
+
return
|
|
201
|
+
if self.socket is not socket or self.error:
|
|
202
|
+
return
|
|
203
|
+
try:
|
|
204
|
+
await _send(socket, type="extend", session_key=result.token)
|
|
205
|
+
except (ConnectionClosed, OSError) as exc:
|
|
206
|
+
# The hold was already extended. Retrying the Cloud write could
|
|
207
|
+
# charge twice even though the socket failed to receive its key.
|
|
208
|
+
self.error = self._last_issue = exc
|
|
209
|
+
await socket.close()
|
|
210
|
+
return
|
|
211
|
+
self._last_issue = None
|
|
212
|
+
self._retry_at = time.time() + _RENEW_RETRY_SECONDS
|
|
213
|
+
finally:
|
|
214
|
+
self._extension = None
|
|
215
|
+
self._schedule()
|
|
216
|
+
|
|
217
|
+
async def reserve(self, characters: int) -> None:
|
|
218
|
+
if not self.session_id:
|
|
219
|
+
return
|
|
220
|
+
while self._used + characters > self._limit:
|
|
221
|
+
if (
|
|
222
|
+
self.error
|
|
223
|
+
or not self.socket
|
|
224
|
+
or self.socket.close_code is not None
|
|
225
|
+
or time.time() >= self.expires
|
|
226
|
+
):
|
|
227
|
+
raise (
|
|
228
|
+
self.error
|
|
229
|
+
or self._last_issue
|
|
230
|
+
or SpeechError("Speech session ended")
|
|
231
|
+
)
|
|
232
|
+
if self._last_issue and (
|
|
233
|
+
not _safe_retry(self._last_issue)
|
|
234
|
+
or (
|
|
235
|
+
isinstance(self._last_issue, CloudApiError)
|
|
236
|
+
and self._last_issue.retry_after
|
|
237
|
+
and time.time() < self._retry_at
|
|
238
|
+
)
|
|
239
|
+
):
|
|
240
|
+
raise self._last_issue
|
|
241
|
+
needed = self._used + characters + self.margin - self._limit
|
|
242
|
+
await asyncio.shield(self._begin_extension(max(self.amount, needed)))
|
|
243
|
+
if self._last_issue:
|
|
244
|
+
raise self._last_issue
|
|
245
|
+
if (
|
|
246
|
+
self.error
|
|
247
|
+
or not self.socket
|
|
248
|
+
or self.socket.close_code is not None
|
|
249
|
+
or time.time() >= self.expires
|
|
250
|
+
):
|
|
251
|
+
raise self.error or self._last_issue or SpeechError("Speech session ended")
|
|
252
|
+
self._used += characters
|
|
253
|
+
if self._limit - self._used < self.margin and (
|
|
254
|
+
not self._last_issue
|
|
255
|
+
or (_safe_retry(self._last_issue) and time.time() >= self._retry_at)
|
|
256
|
+
):
|
|
257
|
+
self._begin_extension(self.amount)
|
|
258
|
+
|
|
259
|
+
async def close(self) -> None:
|
|
260
|
+
self.socket = None
|
|
261
|
+
if self._timer:
|
|
262
|
+
self._timer.cancel()
|
|
263
|
+
if self._extension:
|
|
264
|
+
self._extension.cancel()
|
|
265
|
+
await asyncio.gather(self._extension, return_exceptions=True)
|
|
266
|
+
if self._expiry_close:
|
|
267
|
+
await asyncio.gather(self._expiry_close, return_exceptions=True)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
async def _send(socket: ClientConnection, **fields: Any) -> None:
|
|
271
|
+
await socket.send(json.dumps(fields))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _control(raw: str) -> dict[str, Any]:
|
|
275
|
+
msg = json.loads(raw)
|
|
276
|
+
if not isinstance(msg, dict):
|
|
277
|
+
raise SpeechError("Unexpected control message")
|
|
278
|
+
if msg.get("type") == "error" or msg.get("error"):
|
|
279
|
+
raise SpeechError(
|
|
280
|
+
str(msg.get("message") or msg.get("error") or "Speech service error")
|
|
281
|
+
)
|
|
282
|
+
return msg
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class STTStream:
|
|
286
|
+
"""One speaker's 16 kHz mono PCM16 input and ordered speech service events."""
|
|
287
|
+
|
|
288
|
+
def __init__(
|
|
289
|
+
self,
|
|
290
|
+
credentials: SpeechCredentials,
|
|
291
|
+
*,
|
|
292
|
+
language: str = "auto",
|
|
293
|
+
force_whisper: bool = False,
|
|
294
|
+
partials: bool = False,
|
|
295
|
+
smart_turn: bool = False,
|
|
296
|
+
minutes: int = 10,
|
|
297
|
+
extend_when_minutes_left: int = 2,
|
|
298
|
+
):
|
|
299
|
+
self.credentials, self.language = credentials, language
|
|
300
|
+
self.force_whisper, self.partials, self.smart_turn = (
|
|
301
|
+
force_whisper,
|
|
302
|
+
partials,
|
|
303
|
+
smart_turn,
|
|
304
|
+
)
|
|
305
|
+
self.minutes, self.margin = minutes, extend_when_minutes_left
|
|
306
|
+
self._events: asyncio.Queue = asyncio.Queue(256)
|
|
307
|
+
self._task: asyncio.Task | None = None
|
|
308
|
+
self._ws: ClientConnection | None = None
|
|
309
|
+
self._send_lock = asyncio.Lock()
|
|
310
|
+
self._ready = self._can_finalize = self._closed = False
|
|
311
|
+
self._pending: deque[bytes] = deque()
|
|
312
|
+
self._pending_size = 0
|
|
313
|
+
self._failure: Exception | None = None
|
|
314
|
+
|
|
315
|
+
def _config(self) -> dict[str, Any]:
|
|
316
|
+
result = {
|
|
317
|
+
"language": self.language,
|
|
318
|
+
"partials": self.partials,
|
|
319
|
+
"smart_turn": self.smart_turn,
|
|
320
|
+
}
|
|
321
|
+
if self.force_whisper:
|
|
322
|
+
result["model"] = "whisper"
|
|
323
|
+
return result
|
|
324
|
+
|
|
325
|
+
async def start(self) -> None:
|
|
326
|
+
if self._closed:
|
|
327
|
+
raise SpeechError("Recognition stream is closed")
|
|
328
|
+
if self._task is None:
|
|
329
|
+
self._task = asyncio.create_task(self._run())
|
|
330
|
+
|
|
331
|
+
async def send_audio(self, pcm: bytes) -> None:
|
|
332
|
+
if self._failure:
|
|
333
|
+
raise self._failure
|
|
334
|
+
if self._closed:
|
|
335
|
+
raise SpeechError("Recognition stream is closed")
|
|
336
|
+
if len(pcm) % 2:
|
|
337
|
+
raise ValueError("PCM16 frames must contain complete samples")
|
|
338
|
+
if not pcm:
|
|
339
|
+
return
|
|
340
|
+
async with self._send_lock:
|
|
341
|
+
if self._ready and self._ws:
|
|
342
|
+
try:
|
|
343
|
+
await self._ws.send(pcm)
|
|
344
|
+
return
|
|
345
|
+
except ConnectionClosed:
|
|
346
|
+
# The peer may already have received this frame.
|
|
347
|
+
self._ready = False
|
|
348
|
+
return
|
|
349
|
+
chunk = bytes(pcm[-160000:])
|
|
350
|
+
self._pending.append(chunk)
|
|
351
|
+
self._pending_size += len(chunk)
|
|
352
|
+
while self._pending_size > 160000:
|
|
353
|
+
self._pending_size -= len(self._pending.popleft())
|
|
354
|
+
|
|
355
|
+
async def _run(self) -> None:
|
|
356
|
+
delay = _CONNECT_RETRY_SECONDS
|
|
357
|
+
try:
|
|
358
|
+
while not self._closed:
|
|
359
|
+
lease = _Lease(self.credentials, "stt", self.minutes, self.margin)
|
|
360
|
+
try:
|
|
361
|
+
try:
|
|
362
|
+
url, key = await lease.open(self.language)
|
|
363
|
+
except Exception as exc: # noqa: BLE001 - credential callbacks may raise application errors
|
|
364
|
+
if not _safe_retry(exc):
|
|
365
|
+
self._failure = exc
|
|
366
|
+
await self._events.put(exc)
|
|
367
|
+
return
|
|
368
|
+
await asyncio.sleep(_retry_delay(exc, delay))
|
|
369
|
+
delay = min(delay * 2, 30)
|
|
370
|
+
continue
|
|
371
|
+
async with connect(_stream_url(url), open_timeout=10) as ws:
|
|
372
|
+
self._ws = ws
|
|
373
|
+
await _send(
|
|
374
|
+
ws, type="config", session_key=key, **self._config()
|
|
375
|
+
)
|
|
376
|
+
lease.attach(ws)
|
|
377
|
+
while True:
|
|
378
|
+
try:
|
|
379
|
+
raw = await asyncio.wait_for(
|
|
380
|
+
ws.recv(), 5 if self._ready else 15
|
|
381
|
+
)
|
|
382
|
+
except TimeoutError:
|
|
383
|
+
if not self._ready:
|
|
384
|
+
raise SpeechError(
|
|
385
|
+
"Speech server did not acknowledge configuration"
|
|
386
|
+
)
|
|
387
|
+
await _send(ws, type="ping")
|
|
388
|
+
continue
|
|
389
|
+
if isinstance(raw, bytes):
|
|
390
|
+
raise SpeechError("Unexpected binary response from STT")
|
|
391
|
+
msg = _control(raw)
|
|
392
|
+
if msg.get("type") == "ready":
|
|
393
|
+
delay = _CONNECT_RETRY_SECONDS
|
|
394
|
+
async with self._send_lock:
|
|
395
|
+
self._can_finalize = msg.get("finalize") is True
|
|
396
|
+
while self._pending:
|
|
397
|
+
chunk = self._pending.popleft()
|
|
398
|
+
self._pending_size -= len(chunk)
|
|
399
|
+
await ws.send(chunk)
|
|
400
|
+
self._ready = True
|
|
401
|
+
if msg.get("type") != "pong":
|
|
402
|
+
await self._events.put(msg)
|
|
403
|
+
except (ConnectionClosed, OSError):
|
|
404
|
+
if lease.error:
|
|
405
|
+
raise lease.error
|
|
406
|
+
finally:
|
|
407
|
+
self._ready = self._can_finalize = False
|
|
408
|
+
self._ws = None
|
|
409
|
+
await lease.close()
|
|
410
|
+
if not self._closed:
|
|
411
|
+
await asyncio.sleep(delay)
|
|
412
|
+
delay = min(delay * 2, 30)
|
|
413
|
+
except Exception as exc: # noqa: BLE001 - deliver the task failure to the event iterator
|
|
414
|
+
self._failure = exc
|
|
415
|
+
await self._events.put(exc)
|
|
416
|
+
|
|
417
|
+
async def set_language(self, language: str, force_whisper: bool = False) -> None:
|
|
418
|
+
self.language, self.force_whisper = language, force_whisper
|
|
419
|
+
if self._ws and self._ready:
|
|
420
|
+
await _send(self._ws, type="config", **self._config())
|
|
421
|
+
|
|
422
|
+
async def finalize(self) -> bool:
|
|
423
|
+
if not self._ws or not self._ready or not self._can_finalize:
|
|
424
|
+
return False
|
|
425
|
+
await _send(self._ws, type="finalize")
|
|
426
|
+
return True
|
|
427
|
+
|
|
428
|
+
async def __aiter__(self) -> AsyncIterator[dict[str, Any]]:
|
|
429
|
+
while not self._closed:
|
|
430
|
+
event = await self._events.get()
|
|
431
|
+
if event is None:
|
|
432
|
+
return
|
|
433
|
+
if isinstance(event, Exception):
|
|
434
|
+
raise event
|
|
435
|
+
yield event
|
|
436
|
+
|
|
437
|
+
async def close(self) -> None:
|
|
438
|
+
self._closed = True
|
|
439
|
+
if self._task:
|
|
440
|
+
self._task.cancel()
|
|
441
|
+
await asyncio.gather(self._task, return_exceptions=True)
|
|
442
|
+
self._pending.clear()
|
|
443
|
+
self._pending_size = 0
|
|
444
|
+
while not self._events.empty():
|
|
445
|
+
self._events.get_nowait()
|
|
446
|
+
self._events.put_nowait(None)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
class TTSStream:
|
|
450
|
+
"""Reusable, sequential synthesis socket returning 48 kHz mono PCM16."""
|
|
451
|
+
|
|
452
|
+
def __init__(
|
|
453
|
+
self,
|
|
454
|
+
credentials: SpeechCredentials,
|
|
455
|
+
*,
|
|
456
|
+
voice: str = "M5",
|
|
457
|
+
language: str = "en",
|
|
458
|
+
speed: float = 1.0,
|
|
459
|
+
watermark: bool = False,
|
|
460
|
+
characters: int = 2000,
|
|
461
|
+
extend_when_characters_left: int = 500,
|
|
462
|
+
):
|
|
463
|
+
self.credentials = credentials
|
|
464
|
+
self.voice, self.language, self.speed, self.watermark = (
|
|
465
|
+
voice,
|
|
466
|
+
language,
|
|
467
|
+
speed,
|
|
468
|
+
watermark,
|
|
469
|
+
)
|
|
470
|
+
self.characters, self.margin = characters, extend_when_characters_left
|
|
471
|
+
self._ws: ClientConnection | None = None
|
|
472
|
+
self._lease: _Lease | None = None
|
|
473
|
+
self._capabilities: dict[str, Any] | None = None
|
|
474
|
+
self._lock = asyncio.Lock()
|
|
475
|
+
self._generation = 0
|
|
476
|
+
self._opening: asyncio.Task | None = None
|
|
477
|
+
self._watcher: asyncio.Task | None = None
|
|
478
|
+
|
|
479
|
+
async def _connect(self, generation: int) -> ClientConnection:
|
|
480
|
+
if generation != self._generation:
|
|
481
|
+
raise SpeechError("Synthesis operation was closed")
|
|
482
|
+
if self._ws and self._ws.close_code is None:
|
|
483
|
+
return self._ws
|
|
484
|
+
opening = self._opening = asyncio.create_task(self._open())
|
|
485
|
+
try:
|
|
486
|
+
return await opening
|
|
487
|
+
finally:
|
|
488
|
+
if self._opening is opening:
|
|
489
|
+
self._opening = None
|
|
490
|
+
|
|
491
|
+
async def _open(self) -> ClientConnection:
|
|
492
|
+
if self._ws:
|
|
493
|
+
await self._discard(self._ws)
|
|
494
|
+
lease = _Lease(self.credentials, "tts", self.characters, self.margin)
|
|
495
|
+
url, key = await lease.open(self.language, self.voice)
|
|
496
|
+
ws = await connect(_stream_url(url), open_timeout=10)
|
|
497
|
+
try:
|
|
498
|
+
await _send(
|
|
499
|
+
ws,
|
|
500
|
+
session_key=key,
|
|
501
|
+
config={
|
|
502
|
+
"voice": self.voice,
|
|
503
|
+
"lang_code": self.language,
|
|
504
|
+
"speed": self.speed,
|
|
505
|
+
},
|
|
506
|
+
)
|
|
507
|
+
lease.attach(ws)
|
|
508
|
+
self._lease, self._ws = lease, ws
|
|
509
|
+
self._watcher = asyncio.create_task(self._watch(ws))
|
|
510
|
+
return ws
|
|
511
|
+
except BaseException:
|
|
512
|
+
await lease.close()
|
|
513
|
+
await ws.close()
|
|
514
|
+
raise
|
|
515
|
+
|
|
516
|
+
async def _watch(self, ws: ClientConnection) -> None:
|
|
517
|
+
await ws.wait_closed()
|
|
518
|
+
await self._discard(ws)
|
|
519
|
+
|
|
520
|
+
async def _discard(self, ws: ClientConnection) -> None:
|
|
521
|
+
if self._ws is not ws:
|
|
522
|
+
return
|
|
523
|
+
lease, watcher = self._lease, self._watcher
|
|
524
|
+
self._ws = self._lease = self._watcher = self._capabilities = None
|
|
525
|
+
if watcher and watcher is not asyncio.current_task():
|
|
526
|
+
watcher.cancel()
|
|
527
|
+
await asyncio.gather(watcher, return_exceptions=True)
|
|
528
|
+
if lease:
|
|
529
|
+
await lease.close()
|
|
530
|
+
with suppress(ConnectionClosed):
|
|
531
|
+
await ws.close()
|
|
532
|
+
|
|
533
|
+
async def _capable(self, ws: ClientConnection, ssml: bool) -> None:
|
|
534
|
+
if not (ssml or self.watermark):
|
|
535
|
+
return
|
|
536
|
+
if self._capabilities is None:
|
|
537
|
+
await _send(ws, type="capabilities")
|
|
538
|
+
async with asyncio.timeout(5):
|
|
539
|
+
while True:
|
|
540
|
+
raw = await ws.recv()
|
|
541
|
+
if isinstance(raw, bytes):
|
|
542
|
+
raise SpeechError("Unexpected audio during negotiation")
|
|
543
|
+
msg = _control(raw)
|
|
544
|
+
if msg.get("type") == "capabilities":
|
|
545
|
+
self._capabilities = msg
|
|
546
|
+
break
|
|
547
|
+
if ssml and "dtelecom-ssml-v1" not in self._capabilities.get(
|
|
548
|
+
"ssml_profiles", []
|
|
549
|
+
):
|
|
550
|
+
raise SpeechError("Server does not support dtelecom-ssml-v1")
|
|
551
|
+
if self.watermark and self._capabilities.get("watermark") is not True:
|
|
552
|
+
raise SpeechError("Server does not support watermarking")
|
|
553
|
+
|
|
554
|
+
async def warmup(self) -> None:
|
|
555
|
+
generation = self._generation
|
|
556
|
+
async with self._lock:
|
|
557
|
+
await self._capable(await self._connect(generation), False)
|
|
558
|
+
|
|
559
|
+
async def synthesize(
|
|
560
|
+
self,
|
|
561
|
+
text: str,
|
|
562
|
+
*,
|
|
563
|
+
voice: str | None = None,
|
|
564
|
+
language: str | None = None,
|
|
565
|
+
speed: float | None = None,
|
|
566
|
+
input_format: str = "text",
|
|
567
|
+
) -> AsyncIterator[bytes]:
|
|
568
|
+
if input_format not in ("text", "ssml"):
|
|
569
|
+
raise ValueError("Unsupported synthesis input format")
|
|
570
|
+
generation = self._generation
|
|
571
|
+
async with self._lock:
|
|
572
|
+
ws = await self._connect(generation)
|
|
573
|
+
ssml = input_format == "ssml"
|
|
574
|
+
await self._capable(ws, ssml)
|
|
575
|
+
if self._ws is not ws or self._lease is None:
|
|
576
|
+
raise SpeechError("Synthesis connection closed")
|
|
577
|
+
await self._lease.reserve(len(text if ssml else text.strip()))
|
|
578
|
+
msg = {
|
|
579
|
+
"text": text,
|
|
580
|
+
"voice": voice or self.voice,
|
|
581
|
+
"lang_code": language or self.language,
|
|
582
|
+
"speed": self.speed if speed is None else speed,
|
|
583
|
+
}
|
|
584
|
+
if ssml:
|
|
585
|
+
msg["input_format"] = "ssml"
|
|
586
|
+
if self.watermark:
|
|
587
|
+
msg["watermark"] = True
|
|
588
|
+
done = False
|
|
589
|
+
confirmed = False
|
|
590
|
+
try:
|
|
591
|
+
await ws.send(json.dumps(msg))
|
|
592
|
+
except BaseException:
|
|
593
|
+
await self._discard(ws)
|
|
594
|
+
raise
|
|
595
|
+
try:
|
|
596
|
+
while True:
|
|
597
|
+
raw = await asyncio.wait_for(ws.recv(), timeout=60)
|
|
598
|
+
if isinstance(raw, bytes):
|
|
599
|
+
if self.watermark and not confirmed:
|
|
600
|
+
raise SpeechError(
|
|
601
|
+
"Watermark was not acknowledged before audio"
|
|
602
|
+
)
|
|
603
|
+
yield raw
|
|
604
|
+
continue
|
|
605
|
+
control = _control(raw)
|
|
606
|
+
if control.get("type") == "generating":
|
|
607
|
+
confirmed = control.get("watermark") == "active"
|
|
608
|
+
if self.watermark and not confirmed:
|
|
609
|
+
raise SpeechError(
|
|
610
|
+
"Server did not activate requested watermark"
|
|
611
|
+
)
|
|
612
|
+
if control.get("type") == "done":
|
|
613
|
+
done = True
|
|
614
|
+
return
|
|
615
|
+
finally:
|
|
616
|
+
if not done:
|
|
617
|
+
await self._clear(ws)
|
|
618
|
+
|
|
619
|
+
async def _clear(self, ws: ClientConnection) -> None:
|
|
620
|
+
try:
|
|
621
|
+
async with asyncio.timeout(2):
|
|
622
|
+
await _send(ws, type="clear")
|
|
623
|
+
while True:
|
|
624
|
+
raw = await ws.recv()
|
|
625
|
+
if isinstance(raw, str) and _control(raw).get("type") == "cleared":
|
|
626
|
+
return
|
|
627
|
+
except (OSError, ConnectionClosed, TimeoutError, SpeechError):
|
|
628
|
+
await self._discard(ws)
|
|
629
|
+
|
|
630
|
+
async def close(self) -> None:
|
|
631
|
+
"""Stop outstanding operations. A subsequent call opens a fresh session."""
|
|
632
|
+
self._generation += 1
|
|
633
|
+
# A caller may be paused on a yielded frame. New operations use a
|
|
634
|
+
# fresh lock while already queued operations observe the old generation.
|
|
635
|
+
self._lock = asyncio.Lock()
|
|
636
|
+
opening, ws = self._opening, self._ws
|
|
637
|
+
if opening:
|
|
638
|
+
opening.cancel()
|
|
639
|
+
if ws:
|
|
640
|
+
await self._discard(ws)
|
|
641
|
+
if opening:
|
|
642
|
+
await asyncio.gather(opening, return_exceptions=True)
|