assist-live-client 0.1.0a1__tar.gz
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.
- assist_live_client-0.1.0a1/.gitignore +11 -0
- assist_live_client-0.1.0a1/PKG-INFO +6 -0
- assist_live_client-0.1.0a1/assist_live_client/__init__.py +25 -0
- assist_live_client-0.1.0a1/assist_live_client/client.py +607 -0
- assist_live_client-0.1.0a1/assist_live_client/models.py +286 -0
- assist_live_client-0.1.0a1/assist_live_client/protocol.py +212 -0
- assist_live_client-0.1.0a1/pyproject.toml +10 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Assist Live Python client package."""
|
|
2
|
+
|
|
3
|
+
from .client import AssistLiveClient
|
|
4
|
+
from .models import (
|
|
5
|
+
HealthCapabilities,
|
|
6
|
+
TimingEvent,
|
|
7
|
+
TTSAudio,
|
|
8
|
+
TTSFormat,
|
|
9
|
+
TTSItem,
|
|
10
|
+
TTSSentenceEnd,
|
|
11
|
+
TTSVoice,
|
|
12
|
+
TurnOpen,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"AssistLiveClient",
|
|
17
|
+
"HealthCapabilities",
|
|
18
|
+
"TTSAudio",
|
|
19
|
+
"TTSFormat",
|
|
20
|
+
"TTSItem",
|
|
21
|
+
"TTSSentenceEnd",
|
|
22
|
+
"TTSVoice",
|
|
23
|
+
"TimingEvent",
|
|
24
|
+
"TurnOpen",
|
|
25
|
+
]
|
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import contextlib
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import socket
|
|
6
|
+
from collections.abc import AsyncGenerator, AsyncIterator, Callable
|
|
7
|
+
from dataclasses import asdict
|
|
8
|
+
from ipaddress import ip_address
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import aiohttp
|
|
12
|
+
|
|
13
|
+
from .models import (
|
|
14
|
+
MAX_TURN_RESPONSE,
|
|
15
|
+
STAGES,
|
|
16
|
+
HealthCapabilities,
|
|
17
|
+
TimingEvent,
|
|
18
|
+
TTSAudio,
|
|
19
|
+
TTSFormat,
|
|
20
|
+
TTSItem,
|
|
21
|
+
TTSSentenceEnd,
|
|
22
|
+
TTSVoice,
|
|
23
|
+
TurnOpen,
|
|
24
|
+
TurnRecord,
|
|
25
|
+
identifier,
|
|
26
|
+
unsigned,
|
|
27
|
+
)
|
|
28
|
+
from .protocol import (
|
|
29
|
+
MAX_AUDIO,
|
|
30
|
+
MAX_CONTROL,
|
|
31
|
+
MAX_HINT_BYTES,
|
|
32
|
+
MESSAGE_DEADLINE,
|
|
33
|
+
ProtocolError,
|
|
34
|
+
decode_audio,
|
|
35
|
+
decode_control,
|
|
36
|
+
encode_audio,
|
|
37
|
+
encode_control,
|
|
38
|
+
encode_text,
|
|
39
|
+
parse_json,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AssistLiveClient:
|
|
44
|
+
def __init__(
|
|
45
|
+
self, url: str, token: str, *, session: aiohttp.ClientSession | None = None
|
|
46
|
+
) -> None:
|
|
47
|
+
parsed = aiohttp.client_reqrep.URL(url)
|
|
48
|
+
if (
|
|
49
|
+
parsed.scheme not in {"http", "https"}
|
|
50
|
+
or parsed.user
|
|
51
|
+
or parsed.query
|
|
52
|
+
or parsed.fragment
|
|
53
|
+
):
|
|
54
|
+
raise ValueError("invalid server URL")
|
|
55
|
+
self.url = url.rstrip("/")
|
|
56
|
+
self._token = token
|
|
57
|
+
self._session = session
|
|
58
|
+
self._owns_session = session is None
|
|
59
|
+
|
|
60
|
+
async def __aenter__(self) -> AssistLiveClient:
|
|
61
|
+
self._connection()
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
async def __aexit__(self, *args: object) -> None:
|
|
65
|
+
await self.close()
|
|
66
|
+
|
|
67
|
+
def _connection(self) -> aiohttp.ClientSession:
|
|
68
|
+
if self._session is None:
|
|
69
|
+
self._session = aiohttp.ClientSession(
|
|
70
|
+
timeout=aiohttp.ClientTimeout(total=20, sock_read=MESSAGE_DEADLINE),
|
|
71
|
+
read_bufsize=MAX_CONTROL,
|
|
72
|
+
auto_decompress=False,
|
|
73
|
+
)
|
|
74
|
+
return self._session
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def _headers(self) -> dict[str, str]:
|
|
78
|
+
return {"Authorization": "Bearer " + self._token}
|
|
79
|
+
|
|
80
|
+
async def close(self) -> None:
|
|
81
|
+
if self._owns_session and self._session is not None:
|
|
82
|
+
await self._session.close()
|
|
83
|
+
|
|
84
|
+
@contextlib.asynccontextmanager
|
|
85
|
+
async def _connect[Response](
|
|
86
|
+
self,
|
|
87
|
+
connect: Callable[..., contextlib.AbstractAsyncContextManager[Response]],
|
|
88
|
+
path: str,
|
|
89
|
+
*,
|
|
90
|
+
timeout: aiohttp.ClientTimeout | None = None,
|
|
91
|
+
**kwargs: Any,
|
|
92
|
+
) -> AsyncIterator[Response]:
|
|
93
|
+
session = self._connection()
|
|
94
|
+
url = aiohttp.client_reqrep.URL(self.url + path)
|
|
95
|
+
headers = self._headers
|
|
96
|
+
total = (timeout or session.timeout).total
|
|
97
|
+
if timeout is not None:
|
|
98
|
+
kwargs["timeout"] = timeout
|
|
99
|
+
async with contextlib.AsyncExitStack() as stack:
|
|
100
|
+
async with asyncio.timeout(
|
|
101
|
+
total if total and total > 0 else None
|
|
102
|
+
) as deadline:
|
|
103
|
+
try:
|
|
104
|
+
response = await stack.enter_async_context(
|
|
105
|
+
connect(url=url, headers=headers, **kwargs)
|
|
106
|
+
)
|
|
107
|
+
except aiohttp.ClientConnectorDNSError as error:
|
|
108
|
+
host = url.raw_host
|
|
109
|
+
connector = session.connector
|
|
110
|
+
if host is None or not isinstance(connector, aiohttp.TCPConnector):
|
|
111
|
+
raise
|
|
112
|
+
try:
|
|
113
|
+
ip_address(host)
|
|
114
|
+
except ValueError:
|
|
115
|
+
pass
|
|
116
|
+
else:
|
|
117
|
+
raise error
|
|
118
|
+
# The supplied resolver can keep an old NXDOMAIN answer.
|
|
119
|
+
try:
|
|
120
|
+
addresses = await asyncio.get_running_loop().getaddrinfo(
|
|
121
|
+
host,
|
|
122
|
+
url.port or 0,
|
|
123
|
+
family=connector.family,
|
|
124
|
+
type=socket.SOCK_STREAM,
|
|
125
|
+
)
|
|
126
|
+
except OSError:
|
|
127
|
+
raise error from None
|
|
128
|
+
if not addresses:
|
|
129
|
+
raise error
|
|
130
|
+
headers["Host"] = url.host_port_subcomponent or host
|
|
131
|
+
when = deadline.when()
|
|
132
|
+
if timeout is not None and when is not None:
|
|
133
|
+
remaining = when - asyncio.get_running_loop().time()
|
|
134
|
+
if remaining <= 0:
|
|
135
|
+
raise TimeoutError from None
|
|
136
|
+
kwargs["timeout"] = aiohttp.ClientTimeout(
|
|
137
|
+
total=remaining,
|
|
138
|
+
connect=timeout.connect,
|
|
139
|
+
sock_read=timeout.sock_read,
|
|
140
|
+
sock_connect=timeout.sock_connect,
|
|
141
|
+
ceil_threshold=float("inf"),
|
|
142
|
+
)
|
|
143
|
+
response = await stack.enter_async_context(
|
|
144
|
+
connect(
|
|
145
|
+
url=url.with_host(str(addresses[0][4][0])),
|
|
146
|
+
headers=headers,
|
|
147
|
+
server_hostname=host,
|
|
148
|
+
**kwargs,
|
|
149
|
+
)
|
|
150
|
+
)
|
|
151
|
+
# HTTP keeps its body deadline. WebSockets keep their stream deadlines.
|
|
152
|
+
yield response
|
|
153
|
+
|
|
154
|
+
async def _request(
|
|
155
|
+
self,
|
|
156
|
+
method: str,
|
|
157
|
+
path: str,
|
|
158
|
+
*,
|
|
159
|
+
data: object = None,
|
|
160
|
+
timeout: float = 20,
|
|
161
|
+
response_max: int = MAX_CONTROL,
|
|
162
|
+
request_max: int = MAX_CONTROL,
|
|
163
|
+
) -> Any:
|
|
164
|
+
raw = json.dumps(data, allow_nan=False).encode() if data is not None else None
|
|
165
|
+
if raw is not None and len(raw) > request_max:
|
|
166
|
+
raise ProtocolError("request too large", kind="malformed")
|
|
167
|
+
try:
|
|
168
|
+
async with self._connect(
|
|
169
|
+
self._connection().request,
|
|
170
|
+
path,
|
|
171
|
+
method=method,
|
|
172
|
+
data=raw,
|
|
173
|
+
timeout=aiohttp.ClientTimeout(total=timeout),
|
|
174
|
+
allow_redirects=False,
|
|
175
|
+
) as response:
|
|
176
|
+
if response.status != 200:
|
|
177
|
+
raise ProtocolError("request refused", kind="refused")
|
|
178
|
+
value = bytearray()
|
|
179
|
+
async for chunk in response.content.iter_chunked(1024):
|
|
180
|
+
if len(value) + len(chunk) > response_max:
|
|
181
|
+
raise ProtocolError("response too large", kind="malformed")
|
|
182
|
+
value.extend(chunk)
|
|
183
|
+
if path.startswith("/v1/bindings"):
|
|
184
|
+
bindings = json.loads(value)
|
|
185
|
+
if not isinstance(bindings, list) or any(
|
|
186
|
+
not isinstance(row, dict) or row.keys() != {"satellite"}
|
|
187
|
+
for row in bindings
|
|
188
|
+
):
|
|
189
|
+
raise ProtocolError("invalid bindings", kind="malformed")
|
|
190
|
+
for row in bindings:
|
|
191
|
+
identifier(row["satellite"])
|
|
192
|
+
return bindings
|
|
193
|
+
return parse_json(bytes(value), response_max)
|
|
194
|
+
except TimeoutError:
|
|
195
|
+
raise ProtocolError("request failed", kind="timeout") from None
|
|
196
|
+
except aiohttp.ClientError:
|
|
197
|
+
raise ProtocolError("request failed", kind="closed") from None
|
|
198
|
+
except ValueError:
|
|
199
|
+
raise ProtocolError("request failed", kind="malformed") from None
|
|
200
|
+
|
|
201
|
+
async def health(self, timeout: float = 0.2) -> bool:
|
|
202
|
+
try:
|
|
203
|
+
value = await self._request("GET", "/health", timeout=timeout)
|
|
204
|
+
return value.get("version") == 1 and value.get("healthy") is True
|
|
205
|
+
except ProtocolError:
|
|
206
|
+
return False
|
|
207
|
+
|
|
208
|
+
async def health_capabilities(self, timeout: float = 0.2) -> HealthCapabilities:
|
|
209
|
+
value = await self._request("GET", "/health", timeout=timeout)
|
|
210
|
+
if value.get("version") != 1 or type(value.get("healthy")) is not bool:
|
|
211
|
+
raise ProtocolError("invalid health response", kind="malformed")
|
|
212
|
+
capabilities = value.get("capabilities", {})
|
|
213
|
+
if not isinstance(capabilities, dict):
|
|
214
|
+
raise ProtocolError("invalid health capabilities", kind="malformed")
|
|
215
|
+
fields = {}
|
|
216
|
+
for key in ("stt", "tts", "text_positions", "stt_hints"):
|
|
217
|
+
item = capabilities.get(key, False)
|
|
218
|
+
if type(item) is not bool:
|
|
219
|
+
raise ProtocolError("invalid health capability", kind="malformed")
|
|
220
|
+
fields[key] = item
|
|
221
|
+
local_only = value.get("local_only")
|
|
222
|
+
if local_only is not None and type(local_only) is not bool:
|
|
223
|
+
raise ProtocolError("invalid health local only", kind="malformed")
|
|
224
|
+
destinations = value.get("destinations")
|
|
225
|
+
if isinstance(destinations, dict):
|
|
226
|
+
destinations = {
|
|
227
|
+
key: item
|
|
228
|
+
for key, item in destinations.items()
|
|
229
|
+
if key in {"stt", "tts", "speaker"}
|
|
230
|
+
}
|
|
231
|
+
if destinations is not None and (
|
|
232
|
+
not isinstance(destinations, dict)
|
|
233
|
+
or any(
|
|
234
|
+
not isinstance(item, str) or item not in {"local", "cloud", "unknown"}
|
|
235
|
+
for item in destinations.values()
|
|
236
|
+
)
|
|
237
|
+
):
|
|
238
|
+
raise ProtocolError("invalid health destinations", kind="malformed")
|
|
239
|
+
voices = []
|
|
240
|
+
default_voice = capabilities.get("tts_default_voice")
|
|
241
|
+
try:
|
|
242
|
+
entries = capabilities.get("tts_voices", [])
|
|
243
|
+
if not isinstance(entries, list):
|
|
244
|
+
raise ValueError("invalid voice list")
|
|
245
|
+
for entry in entries:
|
|
246
|
+
if not isinstance(entry, dict):
|
|
247
|
+
raise ValueError("invalid voice entry")
|
|
248
|
+
voices.append(TTSVoice(entry["id"], entry["name"], entry["language"]))
|
|
249
|
+
ids = [voice.id for voice in voices]
|
|
250
|
+
if len(set(ids)) != len(ids) or (
|
|
251
|
+
default_voice is not None
|
|
252
|
+
and (not isinstance(default_voice, str) or default_voice not in ids)
|
|
253
|
+
):
|
|
254
|
+
raise ValueError("invalid default voice")
|
|
255
|
+
except ValueError, TypeError, KeyError:
|
|
256
|
+
raise ProtocolError("invalid health TTS voices", kind="malformed") from None
|
|
257
|
+
hints = value.get("stt_hints_by_satellite")
|
|
258
|
+
try:
|
|
259
|
+
if hints is not None:
|
|
260
|
+
if not isinstance(hints, dict):
|
|
261
|
+
raise ValueError("invalid hints map")
|
|
262
|
+
for satellite, summary in hints.items():
|
|
263
|
+
identifier(satellite)
|
|
264
|
+
if (
|
|
265
|
+
not isinstance(summary, dict)
|
|
266
|
+
or type(summary.get("count")) is not int
|
|
267
|
+
or not 0 <= summary["count"] <= 500
|
|
268
|
+
or not isinstance(summary.get("digest"), str)
|
|
269
|
+
or not re.fullmatch("[a-f0-9]{64}", summary["digest"])
|
|
270
|
+
):
|
|
271
|
+
raise ValueError("invalid hint summary")
|
|
272
|
+
except ValueError, TypeError:
|
|
273
|
+
raise ProtocolError("invalid health STT hints", kind="malformed") from None
|
|
274
|
+
return HealthCapabilities(
|
|
275
|
+
value["healthy"],
|
|
276
|
+
**fields,
|
|
277
|
+
local_only=local_only,
|
|
278
|
+
destinations=destinations,
|
|
279
|
+
tts_voices=tuple(voices),
|
|
280
|
+
tts_default_voice=default_voice,
|
|
281
|
+
stt_hints_by_satellite=hints,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
async def set_hints(self, satellite: str, names: list[str]) -> None:
|
|
285
|
+
identifier(satellite)
|
|
286
|
+
await self._request(
|
|
287
|
+
"PUT",
|
|
288
|
+
f"/v1/satellites/{satellite}/hints",
|
|
289
|
+
data=names,
|
|
290
|
+
request_max=MAX_HINT_BYTES,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
async def open_turn(self, turn: TurnOpen) -> None:
|
|
294
|
+
await self._request("POST", "/v1/turns", data=asdict(turn))
|
|
295
|
+
|
|
296
|
+
async def event(self, event: TimingEvent) -> None:
|
|
297
|
+
await self._request("POST", "/v1/event", data=asdict(event))
|
|
298
|
+
|
|
299
|
+
async def turn(self, turn_id: str) -> TurnRecord:
|
|
300
|
+
from .models import turn_uuid
|
|
301
|
+
|
|
302
|
+
turn_uuid(turn_id)
|
|
303
|
+
return await self._request(
|
|
304
|
+
"GET", "/v1/turns/" + turn_id, response_max=MAX_TURN_RESPONSE
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
async def bindings(self) -> list[dict[str, str]]:
|
|
308
|
+
return await self._request("GET", "/v1/bindings")
|
|
309
|
+
|
|
310
|
+
def _envelope(
|
|
311
|
+
self, value: dict[str, Any], satellite: str, cursor: int
|
|
312
|
+
) -> dict[str, Any]:
|
|
313
|
+
if value.keys() != {"version", "event_id", "event"} or value["version"] != 1:
|
|
314
|
+
raise ProtocolError("invalid event envelope", kind="malformed")
|
|
315
|
+
unsigned(value["event_id"])
|
|
316
|
+
event = TimingEvent(**value["event"])
|
|
317
|
+
if event.satellite != satellite or value["event_id"] <= cursor:
|
|
318
|
+
raise ProtocolError("event isolation or cursor mismatch", kind="malformed")
|
|
319
|
+
return value
|
|
320
|
+
|
|
321
|
+
async def events(
|
|
322
|
+
self, satellite: str, after_event_id: int = 0
|
|
323
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
324
|
+
identifier(satellite)
|
|
325
|
+
unsigned(after_event_id)
|
|
326
|
+
try:
|
|
327
|
+
async with self._connect(
|
|
328
|
+
self._connection().ws_connect,
|
|
329
|
+
"/v1/events",
|
|
330
|
+
max_msg_size=MAX_CONTROL,
|
|
331
|
+
compress=0,
|
|
332
|
+
) as ws:
|
|
333
|
+
await ws.send_json(
|
|
334
|
+
{
|
|
335
|
+
"type": "subscribe",
|
|
336
|
+
"version": 1,
|
|
337
|
+
"satellite": satellite,
|
|
338
|
+
"after_event_id": after_event_id,
|
|
339
|
+
"stages": sorted(STAGES),
|
|
340
|
+
}
|
|
341
|
+
)
|
|
342
|
+
async for message in ws:
|
|
343
|
+
if message.type != aiohttp.WSMsgType.TEXT:
|
|
344
|
+
raise ProtocolError("event stream stopped", kind="closed")
|
|
345
|
+
value = self._envelope(
|
|
346
|
+
parse_json(message.data, MAX_CONTROL), satellite, after_event_id
|
|
347
|
+
)
|
|
348
|
+
after_event_id = value["event_id"]
|
|
349
|
+
yield value
|
|
350
|
+
except TimeoutError:
|
|
351
|
+
raise ProtocolError("event stream failed", kind="timeout") from None
|
|
352
|
+
except aiohttp.ClientError:
|
|
353
|
+
raise ProtocolError("event stream failed", kind="closed") from None
|
|
354
|
+
except ValueError, TypeError, KeyError:
|
|
355
|
+
raise ProtocolError("event stream failed", kind="malformed") from None
|
|
356
|
+
|
|
357
|
+
async def export(
|
|
358
|
+
self, satellite: str, since_utc_ns: int
|
|
359
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
360
|
+
identifier(satellite)
|
|
361
|
+
unsigned(since_utc_ns)
|
|
362
|
+
try:
|
|
363
|
+
async with self._connect(
|
|
364
|
+
self._connection().get,
|
|
365
|
+
"/v1/export",
|
|
366
|
+
params={"satellite": satellite, "since_utc_ns": str(since_utc_ns)},
|
|
367
|
+
timeout=self._connection().timeout,
|
|
368
|
+
allow_redirects=False,
|
|
369
|
+
) as response:
|
|
370
|
+
if response.status != 200:
|
|
371
|
+
raise ProtocolError("export refused", kind="refused")
|
|
372
|
+
line = bytearray()
|
|
373
|
+
cursor = 0
|
|
374
|
+
async for chunk in response.content.iter_chunked(1024):
|
|
375
|
+
for byte in chunk:
|
|
376
|
+
if byte == 10:
|
|
377
|
+
value = self._envelope(
|
|
378
|
+
parse_json(bytes(line), MAX_CONTROL), satellite, cursor
|
|
379
|
+
)
|
|
380
|
+
if value["event"]["t_utc_ns"] < since_utc_ns:
|
|
381
|
+
raise ProtocolError(
|
|
382
|
+
"export time mismatch", kind="malformed"
|
|
383
|
+
)
|
|
384
|
+
cursor = value["event_id"]
|
|
385
|
+
yield value
|
|
386
|
+
line.clear()
|
|
387
|
+
else:
|
|
388
|
+
if len(line) >= MAX_CONTROL:
|
|
389
|
+
raise ProtocolError(
|
|
390
|
+
"export line too large", kind="malformed"
|
|
391
|
+
)
|
|
392
|
+
line.append(byte)
|
|
393
|
+
if line:
|
|
394
|
+
raise ProtocolError("incomplete export line", kind="malformed")
|
|
395
|
+
except TimeoutError:
|
|
396
|
+
raise ProtocolError("export failed", kind="timeout") from None
|
|
397
|
+
except aiohttp.ClientError:
|
|
398
|
+
raise ProtocolError("export failed", kind="closed") from None
|
|
399
|
+
except ValueError, TypeError, KeyError:
|
|
400
|
+
raise ProtocolError("export failed", kind="malformed") from None
|
|
401
|
+
|
|
402
|
+
async def _audio(
|
|
403
|
+
self,
|
|
404
|
+
turn_id: str,
|
|
405
|
+
source: AsyncIterator[bytes] | AsyncIterator[str],
|
|
406
|
+
mode: str,
|
|
407
|
+
voice: str | None = None,
|
|
408
|
+
text_positions: bool = False,
|
|
409
|
+
) -> AsyncGenerator[dict[str, Any] | bytes]:
|
|
410
|
+
sender: asyncio.Task[None] | None = None
|
|
411
|
+
received_terminal = False
|
|
412
|
+
sent_characters = 0
|
|
413
|
+
previous_text_end = 0
|
|
414
|
+
try:
|
|
415
|
+
async with self._connect(
|
|
416
|
+
self._connection().ws_connect,
|
|
417
|
+
"/v1/audio",
|
|
418
|
+
# aiohttp refuses equality. The protocol maximum is inclusive.
|
|
419
|
+
max_msg_size=MAX_AUDIO + 1,
|
|
420
|
+
compress=0,
|
|
421
|
+
) as ws:
|
|
422
|
+
fields: dict[str, object] = {
|
|
423
|
+
"mode": mode,
|
|
424
|
+
"capabilities": [mode, "speaker_result"],
|
|
425
|
+
}
|
|
426
|
+
if mode == "tts":
|
|
427
|
+
if voice is not None:
|
|
428
|
+
fields["voice"] = voice
|
|
429
|
+
if text_positions:
|
|
430
|
+
fields["text_positions"] = True
|
|
431
|
+
await ws.send_json(encode_control("negotiate", turn_id, **fields))
|
|
432
|
+
reply = await ws.receive(timeout=MESSAGE_DEADLINE)
|
|
433
|
+
if reply.type != aiohttp.WSMsgType.TEXT:
|
|
434
|
+
raise ProtocolError("negotiation refused", kind="closed")
|
|
435
|
+
negotiated = decode_control(reply.data, turn_id)
|
|
436
|
+
if (
|
|
437
|
+
negotiated["type"] != "negotiated"
|
|
438
|
+
or mode not in negotiated["capabilities"]
|
|
439
|
+
):
|
|
440
|
+
raise ProtocolError("negotiation refused", kind="refused")
|
|
441
|
+
|
|
442
|
+
async def send() -> None:
|
|
443
|
+
nonlocal sent_characters
|
|
444
|
+
seq = 0
|
|
445
|
+
async for chunk in source:
|
|
446
|
+
if mode == "stt" and isinstance(chunk, bytes):
|
|
447
|
+
await ws.send_bytes(encode_audio(turn_id, seq, chunk))
|
|
448
|
+
seq += 1
|
|
449
|
+
elif mode == "tts" and isinstance(chunk, str):
|
|
450
|
+
for message in encode_text(turn_id, chunk):
|
|
451
|
+
sent_characters += len(decode_control(message)["text"])
|
|
452
|
+
await ws.send_str(message)
|
|
453
|
+
else:
|
|
454
|
+
raise ProtocolError("invalid audio input", kind="malformed")
|
|
455
|
+
await ws.send_json(encode_control("end", turn_id))
|
|
456
|
+
|
|
457
|
+
sender = asyncio.create_task(send(), name="assist-live-client-send")
|
|
458
|
+
expected_seq = 0
|
|
459
|
+
got_format = False
|
|
460
|
+
while True:
|
|
461
|
+
if sender.done() and not received_terminal:
|
|
462
|
+
sender.result()
|
|
463
|
+
reply = await ws.receive(timeout=MESSAGE_DEADLINE)
|
|
464
|
+
if (
|
|
465
|
+
reply.type == aiohttp.WSMsgType.BINARY
|
|
466
|
+
and mode == "tts"
|
|
467
|
+
and got_format
|
|
468
|
+
):
|
|
469
|
+
seq, pcm = decode_audio(reply.data, turn_id)
|
|
470
|
+
if seq != expected_seq:
|
|
471
|
+
raise ProtocolError(
|
|
472
|
+
"audio sequence mismatch", kind="malformed"
|
|
473
|
+
)
|
|
474
|
+
expected_seq += 1
|
|
475
|
+
yield pcm
|
|
476
|
+
elif reply.type == aiohttp.WSMsgType.TEXT:
|
|
477
|
+
value = decode_control(
|
|
478
|
+
reply.data,
|
|
479
|
+
turn_id,
|
|
480
|
+
text_positions=mode != "tts" or text_positions,
|
|
481
|
+
)
|
|
482
|
+
if (
|
|
483
|
+
mode == "tts"
|
|
484
|
+
and value["type"] == "sentence_end"
|
|
485
|
+
and "text_end" in value
|
|
486
|
+
):
|
|
487
|
+
text_end = value["text_end"]
|
|
488
|
+
if not previous_text_end <= text_end <= sent_characters:
|
|
489
|
+
raise ProtocolError(
|
|
490
|
+
"TTS text position out of range", kind="malformed"
|
|
491
|
+
)
|
|
492
|
+
previous_text_end = text_end
|
|
493
|
+
if value["type"] in {"end", "error"} or (
|
|
494
|
+
mode == "stt" and value["type"] == "final"
|
|
495
|
+
):
|
|
496
|
+
received_terminal = True
|
|
497
|
+
sender.cancel()
|
|
498
|
+
if value["type"] == "end":
|
|
499
|
+
return
|
|
500
|
+
if value["type"] == "error":
|
|
501
|
+
if value["code"] == "unknown_tts_voice":
|
|
502
|
+
raise ProtocolError("unknown_tts_voice", kind="refused")
|
|
503
|
+
raise ProtocolError("audio refused", kind="refused")
|
|
504
|
+
if value["type"] == "format":
|
|
505
|
+
got_format = True
|
|
506
|
+
yield value
|
|
507
|
+
else:
|
|
508
|
+
raise ProtocolError("audio stream stopped", kind="closed")
|
|
509
|
+
except TimeoutError:
|
|
510
|
+
raise ProtocolError("message deadline exceeded", kind="timeout") from None
|
|
511
|
+
except aiohttp.ClientError:
|
|
512
|
+
raise ProtocolError("audio stream failed", kind="closed") from None
|
|
513
|
+
except ValueError, TypeError, KeyError:
|
|
514
|
+
raise ProtocolError("audio stream failed", kind="malformed") from None
|
|
515
|
+
finally:
|
|
516
|
+
if sender is not None:
|
|
517
|
+
sender.cancel()
|
|
518
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
519
|
+
try:
|
|
520
|
+
await sender
|
|
521
|
+
except aiohttp.ClientConnectionResetError:
|
|
522
|
+
if not received_terminal:
|
|
523
|
+
raise
|
|
524
|
+
|
|
525
|
+
async def stt(
|
|
526
|
+
self, turn_id: str, audio: AsyncIterator[bytes]
|
|
527
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
528
|
+
stream = self._audio(turn_id, audio, "stt")
|
|
529
|
+
try:
|
|
530
|
+
async for value in stream:
|
|
531
|
+
if not isinstance(value, dict):
|
|
532
|
+
raise ProtocolError("unexpected PCM", kind="malformed")
|
|
533
|
+
yield value
|
|
534
|
+
finally:
|
|
535
|
+
await stream.aclose()
|
|
536
|
+
|
|
537
|
+
async def tts(
|
|
538
|
+
self,
|
|
539
|
+
turn_id: str,
|
|
540
|
+
text: AsyncIterator[str],
|
|
541
|
+
voice: str | None = None,
|
|
542
|
+
*,
|
|
543
|
+
text_positions: bool = False,
|
|
544
|
+
) -> AsyncIterator[bytes]:
|
|
545
|
+
stream = self._audio(turn_id, text, "tts", voice, text_positions)
|
|
546
|
+
try:
|
|
547
|
+
async for value in stream:
|
|
548
|
+
if (
|
|
549
|
+
isinstance(value, dict)
|
|
550
|
+
and value["type"] == "format"
|
|
551
|
+
and (
|
|
552
|
+
value["codec"],
|
|
553
|
+
value["rate"],
|
|
554
|
+
value["channels"],
|
|
555
|
+
value["width"],
|
|
556
|
+
)
|
|
557
|
+
!= ("pcm_s16le", 16000, 1, 2)
|
|
558
|
+
):
|
|
559
|
+
raise ProtocolError(
|
|
560
|
+
"audio format needs the typed TTS stream", kind="malformed"
|
|
561
|
+
)
|
|
562
|
+
if isinstance(value, bytes):
|
|
563
|
+
yield value
|
|
564
|
+
finally:
|
|
565
|
+
await stream.aclose()
|
|
566
|
+
|
|
567
|
+
async def tts_stream(
|
|
568
|
+
self,
|
|
569
|
+
turn_id: str,
|
|
570
|
+
text: AsyncIterator[str],
|
|
571
|
+
voice: str | None = None,
|
|
572
|
+
*,
|
|
573
|
+
text_positions: bool = False,
|
|
574
|
+
) -> AsyncIterator[TTSItem]:
|
|
575
|
+
"""Yield the declared format, audio, and sentence-completion items."""
|
|
576
|
+
stream = self._audio(turn_id, text, "tts", voice, text_positions)
|
|
577
|
+
got_format = False
|
|
578
|
+
pending_audio = False
|
|
579
|
+
sentence = 0
|
|
580
|
+
try:
|
|
581
|
+
async for value in stream:
|
|
582
|
+
if isinstance(value, bytes):
|
|
583
|
+
if not got_format:
|
|
584
|
+
raise ProtocolError(
|
|
585
|
+
"TTS format required before audio", kind="malformed"
|
|
586
|
+
)
|
|
587
|
+
pending_audio = True
|
|
588
|
+
yield TTSAudio(value)
|
|
589
|
+
elif value["type"] == "format":
|
|
590
|
+
if got_format:
|
|
591
|
+
raise ProtocolError("duplicate TTS format", kind="malformed")
|
|
592
|
+
got_format = True
|
|
593
|
+
yield TTSFormat(
|
|
594
|
+
value["codec"], value["rate"], value["channels"], value["width"]
|
|
595
|
+
)
|
|
596
|
+
elif value["type"] == "sentence_end":
|
|
597
|
+
if not got_format or value["sentence"] != sentence:
|
|
598
|
+
raise ProtocolError(
|
|
599
|
+
"TTS sentence sequence mismatch", kind="malformed"
|
|
600
|
+
)
|
|
601
|
+
sentence += 1
|
|
602
|
+
pending_audio = False
|
|
603
|
+
yield TTSSentenceEnd(value["sentence"], value.get("text_end"))
|
|
604
|
+
if not got_format or pending_audio:
|
|
605
|
+
raise ProtocolError("incomplete TTS sentence stream", kind="malformed")
|
|
606
|
+
finally:
|
|
607
|
+
await stream.aclose()
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from collections.abc import Mapping
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Literal, NotRequired, TypedDict
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
MAX_TURN_EVENTS = 1024
|
|
8
|
+
MAX_TURN_EVENT_BYTES = 1_048_576
|
|
9
|
+
# JSON adds 19 spaces for 10 event fields and 21 for 11 data fields.
|
|
10
|
+
# The bound is 1 MiB + 1024 * (40 + 2) + 4096 bytes for turn metadata.
|
|
11
|
+
MAX_TURN_RESPONSE = MAX_TURN_EVENT_BYTES + MAX_TURN_EVENTS * 42 + 4096
|
|
12
|
+
|
|
13
|
+
LEGACY_STAGES = frozenset(
|
|
14
|
+
"""wake_detected mic_open speech_start end_candidate end_decision
|
|
15
|
+
stt_partial stt_final speaker_result tts_first_text tts_first_byte playback_start
|
|
16
|
+
playback_end satellite_state fallback_used stt_failed tts_failed turn_superseded
|
|
17
|
+
unmatched barge_in late_result_queued late_result_delivering late_result_spoken
|
|
18
|
+
late_result_cancelled late_result_uncertain late_result_notify_sent
|
|
19
|
+
late_result_notify_failed late_result_expired""".split()
|
|
20
|
+
)
|
|
21
|
+
STAGES = LEGACY_STAGES | {
|
|
22
|
+
"tts_sentence",
|
|
23
|
+
"tts_last_byte",
|
|
24
|
+
"stt_final_received",
|
|
25
|
+
"tts_audio_received",
|
|
26
|
+
"tts_text_received",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
# See assist-live `docs/design.md`, "Measurement rules".
|
|
30
|
+
STAGE_OWNERS: dict[str, dict[str, str | None]] = {
|
|
31
|
+
stage: {"server": owner, "fallback": fallback}
|
|
32
|
+
for stages, owner, fallback in (
|
|
33
|
+
(
|
|
34
|
+
"wake_detected mic_open playback_start playback_end barge_in",
|
|
35
|
+
"device",
|
|
36
|
+
"device",
|
|
37
|
+
),
|
|
38
|
+
(
|
|
39
|
+
"speech_start end_candidate end_decision stt_partial stt_final "
|
|
40
|
+
"stt_failed tts_failed",
|
|
41
|
+
"server",
|
|
42
|
+
"integration",
|
|
43
|
+
),
|
|
44
|
+
(
|
|
45
|
+
"tts_first_text fallback_used turn_superseded "
|
|
46
|
+
"stt_final_received tts_audio_received",
|
|
47
|
+
"integration",
|
|
48
|
+
"integration",
|
|
49
|
+
),
|
|
50
|
+
("satellite_state", "ha_state", "ha_state"),
|
|
51
|
+
("tts_first_byte", "server", "integration"),
|
|
52
|
+
("tts_sentence tts_last_byte", "server", None),
|
|
53
|
+
("speaker_result tts_text_received unmatched", "server", "server"),
|
|
54
|
+
(
|
|
55
|
+
"late_result_queued late_result_delivering late_result_spoken "
|
|
56
|
+
"late_result_cancelled late_result_uncertain late_result_notify_sent "
|
|
57
|
+
"late_result_notify_failed late_result_expired",
|
|
58
|
+
"integration",
|
|
59
|
+
"integration",
|
|
60
|
+
),
|
|
61
|
+
)
|
|
62
|
+
for stage in stages.split()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
FALLBACK_REASONS = frozenset(
|
|
66
|
+
"""health_timeout health_error server_unhealthy
|
|
67
|
+
stt_unsupported tts_unsupported not_local_only destination_not_local open_refused
|
|
68
|
+
open_error stream_refused stream_closed stream_error message_timeout
|
|
69
|
+
fallback_unavailable""".split()
|
|
70
|
+
)
|
|
71
|
+
END_REASONS = frozenset({"early", "hard", "max_silence", "input_end"})
|
|
72
|
+
SATELLITE_STATES = frozenset({"idle", "listening", "processing", "responding"})
|
|
73
|
+
EVENT_CODES = {
|
|
74
|
+
"fallback_used": {"reason": FALLBACK_REASONS, "part": frozenset({"stt", "tts"})},
|
|
75
|
+
"end_decision": {
|
|
76
|
+
"reason": END_REASONS,
|
|
77
|
+
"decision_source": frozenset({"server", "ha_audio_end"}),
|
|
78
|
+
},
|
|
79
|
+
"satellite_state": {"state": SATELLITE_STATES},
|
|
80
|
+
}
|
|
81
|
+
EVENT_NUMBERS = {
|
|
82
|
+
"speech_start": frozenset({"onset_ms"}),
|
|
83
|
+
"tts_sentence": frozenset(
|
|
84
|
+
{"index", "text_end", "text_ms", "first_byte_ms", "audio_ms"}
|
|
85
|
+
),
|
|
86
|
+
"tts_last_byte": frozenset({"sentences", "audio_ms"}),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def identifier(value: object) -> str:
|
|
91
|
+
if not isinstance(value, str) or not 1 <= len(value.encode()) <= 128:
|
|
92
|
+
raise ValueError("invalid identifier")
|
|
93
|
+
if not all(c.isascii() and (c.isalnum() or c in "-_") for c in value):
|
|
94
|
+
raise ValueError("invalid identifier")
|
|
95
|
+
return value
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def turn_uuid(value: object) -> str:
|
|
99
|
+
if (
|
|
100
|
+
not isinstance(value, str)
|
|
101
|
+
or UUID(value).version != 7
|
|
102
|
+
or str(UUID(value)) != value
|
|
103
|
+
):
|
|
104
|
+
raise ValueError("invalid turn identifier")
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def unsigned(value: object, bits: int = 64) -> int:
|
|
109
|
+
if type(value) is not int or not 0 <= value < 2**bits:
|
|
110
|
+
raise ValueError("invalid unsigned integer")
|
|
111
|
+
return value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def event_data(stage: str, data: object) -> None:
|
|
115
|
+
if not isinstance(data, dict):
|
|
116
|
+
raise ValueError("invalid event data")
|
|
117
|
+
for key, values in EVENT_CODES.get(stage, {}).items():
|
|
118
|
+
if key in data and (not isinstance(data[key], str) or data[key] not in values):
|
|
119
|
+
raise ValueError("invalid event data")
|
|
120
|
+
numbers = EVENT_NUMBERS.get(stage, frozenset())
|
|
121
|
+
if stage.startswith("tts_"):
|
|
122
|
+
numbers = numbers | {"request"}
|
|
123
|
+
for key in numbers:
|
|
124
|
+
if key not in data or (key == "text_end" and data[key] is None):
|
|
125
|
+
continue
|
|
126
|
+
if type(data[key]) is not int or not 0 <= data[key] < 2**64:
|
|
127
|
+
raise ValueError("invalid event data")
|
|
128
|
+
if "pre_roll_ms" in data and (
|
|
129
|
+
stage != "mic_open"
|
|
130
|
+
or type(data["pre_roll_ms"]) is not int
|
|
131
|
+
or not 0 <= data["pre_roll_ms"] <= 1000
|
|
132
|
+
):
|
|
133
|
+
raise ValueError("invalid event data")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class TTSFormat:
|
|
138
|
+
"""The format of all audio in one TTS stream."""
|
|
139
|
+
|
|
140
|
+
codec: str
|
|
141
|
+
rate: int
|
|
142
|
+
channels: int
|
|
143
|
+
width: int
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True)
|
|
147
|
+
class TTSAudio:
|
|
148
|
+
data: bytes
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True)
|
|
152
|
+
class TTSSentenceEnd:
|
|
153
|
+
"""All audio for this zero-based sentence index has arrived."""
|
|
154
|
+
|
|
155
|
+
sentence: int
|
|
156
|
+
text_end: int | None = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
type TTSItem = TTSFormat | TTSAudio | TTSSentenceEnd
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class TTSVoice:
|
|
164
|
+
id: str
|
|
165
|
+
name: str
|
|
166
|
+
language: str
|
|
167
|
+
|
|
168
|
+
def __post_init__(self) -> None:
|
|
169
|
+
if any(
|
|
170
|
+
not isinstance(value, str) or not value.strip()
|
|
171
|
+
for value in (self.id, self.name, self.language)
|
|
172
|
+
):
|
|
173
|
+
raise ValueError("invalid TTS voice")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(frozen=True)
|
|
177
|
+
class HealthCapabilities:
|
|
178
|
+
healthy: bool
|
|
179
|
+
stt: bool = False
|
|
180
|
+
tts: bool = False
|
|
181
|
+
text_positions: bool = False
|
|
182
|
+
local_only: bool | None = None
|
|
183
|
+
destinations: Mapping[str, str] | None = None
|
|
184
|
+
tts_voices: tuple[TTSVoice, ...] = ()
|
|
185
|
+
tts_default_voice: str | None = None
|
|
186
|
+
stt_hints: bool = False
|
|
187
|
+
stt_hints_by_satellite: Mapping[str, Mapping[str, str | int]] | None = None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class ConversationIdError(ValueError):
|
|
191
|
+
pass
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass(frozen=True)
|
|
195
|
+
class TurnOpen:
|
|
196
|
+
turn_id: str
|
|
197
|
+
satellite: str
|
|
198
|
+
turn_type: Literal["voice", "tts_only"]
|
|
199
|
+
parent_turn_id: str | None
|
|
200
|
+
conversation_id: str | None
|
|
201
|
+
record_transcripts: bool = False
|
|
202
|
+
opened_utc_ns: int | None = None
|
|
203
|
+
|
|
204
|
+
def __post_init__(self) -> None:
|
|
205
|
+
turn_uuid(self.turn_id)
|
|
206
|
+
identifier(self.satellite)
|
|
207
|
+
if self.opened_utc_ns is not None:
|
|
208
|
+
unsigned(self.opened_utc_ns)
|
|
209
|
+
if self.parent_turn_id is not None:
|
|
210
|
+
turn_uuid(self.parent_turn_id)
|
|
211
|
+
if self.turn_type not in {"voice", "tts_only"}:
|
|
212
|
+
raise ValueError("invalid turn type")
|
|
213
|
+
if type(self.record_transcripts) is not bool:
|
|
214
|
+
raise ValueError("invalid transcript option")
|
|
215
|
+
if self.conversation_id is not None:
|
|
216
|
+
try:
|
|
217
|
+
if len(identifier(self.conversation_id)) > 64:
|
|
218
|
+
raise ValueError("conversation identifier too long")
|
|
219
|
+
except ValueError:
|
|
220
|
+
raise ConversationIdError("invalid_conversation_id") from None
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class TurnRecord(TypedDict):
|
|
224
|
+
turn_id: str
|
|
225
|
+
satellite: str
|
|
226
|
+
turn_type: Literal["voice", "tts_only"]
|
|
227
|
+
parent_turn_id: str | None
|
|
228
|
+
conversation_id: str | None
|
|
229
|
+
record_transcripts: bool
|
|
230
|
+
opened_utc_ns: NotRequired[int | None]
|
|
231
|
+
late_open: NotRequired[bool]
|
|
232
|
+
status: NotRequired[Literal["open", "complete", "incomplete"]]
|
|
233
|
+
events: NotRequired[list[TimingRecord]]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class TimingRecord(TypedDict):
|
|
237
|
+
turn_id: str | None
|
|
238
|
+
satellite: str
|
|
239
|
+
source: Literal["device", "ha_state", "integration", "server"]
|
|
240
|
+
stage: str
|
|
241
|
+
t_utc_ns: int
|
|
242
|
+
quality: Literal["measured", "proxy", "estimate"]
|
|
243
|
+
uncertainty_ms: float | None
|
|
244
|
+
t_device_ms: int | None
|
|
245
|
+
seq: int | None
|
|
246
|
+
data: dict[str, object]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@dataclass(frozen=True)
|
|
250
|
+
class TimingEvent:
|
|
251
|
+
turn_id: str | None
|
|
252
|
+
satellite: str
|
|
253
|
+
source: Literal["device", "ha_state", "integration", "server"]
|
|
254
|
+
stage: str
|
|
255
|
+
t_utc_ns: int
|
|
256
|
+
quality: Literal["measured", "proxy", "estimate"]
|
|
257
|
+
uncertainty_ms: float | None
|
|
258
|
+
t_device_ms: int | None = None
|
|
259
|
+
seq: int | None = None
|
|
260
|
+
data: dict[str, object] = field(default_factory=dict)
|
|
261
|
+
|
|
262
|
+
def __post_init__(self) -> None:
|
|
263
|
+
if self.turn_id is not None:
|
|
264
|
+
turn_uuid(self.turn_id)
|
|
265
|
+
identifier(self.satellite)
|
|
266
|
+
unsigned(self.t_utc_ns)
|
|
267
|
+
if self.source not in {"device", "ha_state", "integration", "server"}:
|
|
268
|
+
raise ValueError("invalid event source")
|
|
269
|
+
if self.stage not in STAGES or self.quality not in {
|
|
270
|
+
"measured",
|
|
271
|
+
"proxy",
|
|
272
|
+
"estimate",
|
|
273
|
+
}:
|
|
274
|
+
raise ValueError("invalid timing event")
|
|
275
|
+
if self.uncertainty_ms is not None and (
|
|
276
|
+
type(self.uncertainty_ms) not in {float, int}
|
|
277
|
+
or not math.isfinite(self.uncertainty_ms)
|
|
278
|
+
or self.uncertainty_ms < 0
|
|
279
|
+
):
|
|
280
|
+
raise ValueError("invalid uncertainty")
|
|
281
|
+
if self.quality == "estimate" and self.uncertainty_ms is None:
|
|
282
|
+
raise ValueError("missing uncertainty")
|
|
283
|
+
for value in (self.t_device_ms, self.seq):
|
|
284
|
+
if value is not None:
|
|
285
|
+
unsigned(value)
|
|
286
|
+
event_data(self.stage, self.data)
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import math
|
|
3
|
+
import struct
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from .models import turn_uuid, unsigned
|
|
9
|
+
|
|
10
|
+
VERSION = 1
|
|
11
|
+
MAX_CONTROL = 16384
|
|
12
|
+
# Each of 500 names has at most 64 characters. A JSON surrogate pair uses 12 bytes.
|
|
13
|
+
# Four bytes are for each name's JSON syntax. Two are for the list brackets.
|
|
14
|
+
MAX_HINT_BYTES = 500 * (64 * 12 + 4) + 2
|
|
15
|
+
# This JSON-escaped text budget lets each transcript envelope fit.
|
|
16
|
+
MAX_TRANSCRIPT_BYTES = 16000
|
|
17
|
+
MAX_PCM = 32000
|
|
18
|
+
MAX_AUDIO = 21 + MAX_PCM
|
|
19
|
+
MESSAGE_DEADLINE = 0.6
|
|
20
|
+
HEARTBEAT_INTERVAL = 0.1
|
|
21
|
+
CAPABILITIES = frozenset({"stt", "tts", "speaker_result", "events"})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ProtocolError(Exception):
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
*args: object,
|
|
28
|
+
kind: Literal["refused", "closed", "timeout", "malformed"] | None = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
super().__init__(*args)
|
|
31
|
+
self.kind = kind
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
35
|
+
result = {}
|
|
36
|
+
for key, value in pairs:
|
|
37
|
+
if key in result:
|
|
38
|
+
raise ValueError("duplicate JSON key")
|
|
39
|
+
result[key] = value
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _constant(value: str) -> None:
|
|
44
|
+
raise ValueError("non-finite JSON number")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_json(raw: str | bytes, maximum: int) -> dict[str, Any]:
|
|
48
|
+
if len(raw) > maximum:
|
|
49
|
+
raise ValueError("message too large")
|
|
50
|
+
if isinstance(raw, str) and len(raw.encode()) > maximum:
|
|
51
|
+
raise ValueError("message too large")
|
|
52
|
+
try:
|
|
53
|
+
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
|
|
54
|
+
depth = 0
|
|
55
|
+
quoted = escaped = False
|
|
56
|
+
for character in text:
|
|
57
|
+
if quoted:
|
|
58
|
+
if escaped:
|
|
59
|
+
escaped = False
|
|
60
|
+
elif character == "\\":
|
|
61
|
+
escaped = True
|
|
62
|
+
elif character == '"':
|
|
63
|
+
quoted = False
|
|
64
|
+
elif character == '"':
|
|
65
|
+
quoted = True
|
|
66
|
+
elif character in "{[":
|
|
67
|
+
depth += 1
|
|
68
|
+
if depth > 32:
|
|
69
|
+
raise ValueError("JSON depth limit")
|
|
70
|
+
elif character in "}]":
|
|
71
|
+
depth -= 1
|
|
72
|
+
value = json.loads(raw, object_pairs_hook=_pairs, parse_constant=_constant)
|
|
73
|
+
if not isinstance(value, dict):
|
|
74
|
+
raise ValueError("JSON object required")
|
|
75
|
+
json.dumps(value, allow_nan=False)
|
|
76
|
+
return value
|
|
77
|
+
except (RecursionError, UnicodeError, OverflowError) as error:
|
|
78
|
+
raise ValueError("invalid JSON") from error
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
CONTROL_FIELDS: dict[str, tuple[set[str], set[str]]] = {
|
|
82
|
+
"negotiate": ({"mode", "capabilities"}, {"voice", "text_positions"}),
|
|
83
|
+
"negotiated": ({"capabilities"}, set()),
|
|
84
|
+
"partial": ({"text"}, set()),
|
|
85
|
+
"final": ({"text"}, set()),
|
|
86
|
+
"end_decision": (set(), set()),
|
|
87
|
+
"heartbeat": (set(), set()),
|
|
88
|
+
"error": ({"code"}, set()),
|
|
89
|
+
"end": (set(), set()),
|
|
90
|
+
"text": ({"text"}, set()),
|
|
91
|
+
"speaker_result": ({"name", "distance", "destination"}, set()),
|
|
92
|
+
"format": ({"codec", "rate", "channels", "width"}, set()),
|
|
93
|
+
"sentence_end": ({"sentence"}, {"text_end"}),
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def decode_control(
|
|
98
|
+
raw: str | bytes, turn_id: str | None = None, *, text_positions: bool = True
|
|
99
|
+
) -> dict[str, Any]:
|
|
100
|
+
value = parse_json(raw, MAX_CONTROL)
|
|
101
|
+
kind = value.get("type")
|
|
102
|
+
if not isinstance(kind, str) or kind not in CONTROL_FIELDS:
|
|
103
|
+
raise ValueError("unknown control type")
|
|
104
|
+
required, optional = CONTROL_FIELDS[kind]
|
|
105
|
+
required = required | {"type", "version", "turn_id"}
|
|
106
|
+
if not required <= value.keys() or value.keys() - required - optional:
|
|
107
|
+
raise ValueError("invalid control fields")
|
|
108
|
+
if kind == "sentence_end" and not text_positions:
|
|
109
|
+
value.pop("text_end", None)
|
|
110
|
+
if type(value["version"]) is not int or value["version"] != VERSION:
|
|
111
|
+
raise ValueError("unsupported protocol version")
|
|
112
|
+
turn_uuid(value["turn_id"])
|
|
113
|
+
if turn_id is not None and value["turn_id"] != turn_id:
|
|
114
|
+
raise ValueError("turn identifier mismatch")
|
|
115
|
+
if "capabilities" in value and (
|
|
116
|
+
not isinstance(value["capabilities"], list)
|
|
117
|
+
or not all(
|
|
118
|
+
isinstance(c, str) and c in CAPABILITIES for c in value["capabilities"]
|
|
119
|
+
)
|
|
120
|
+
or len(set(value["capabilities"])) != len(value["capabilities"])
|
|
121
|
+
):
|
|
122
|
+
raise ValueError("unsupported capability")
|
|
123
|
+
if kind == "negotiate" and (
|
|
124
|
+
value["mode"] not in {"stt", "tts"}
|
|
125
|
+
or value["mode"] not in value["capabilities"]
|
|
126
|
+
):
|
|
127
|
+
raise ValueError("unsupported mode")
|
|
128
|
+
if "text_positions" in value and (
|
|
129
|
+
type(value["text_positions"]) is not bool or value["mode"] != "tts"
|
|
130
|
+
):
|
|
131
|
+
raise ValueError("invalid text position option")
|
|
132
|
+
if "text_end" in value and (
|
|
133
|
+
type(value["text_end"]) is not int or value["text_end"] < 0
|
|
134
|
+
):
|
|
135
|
+
raise ValueError("invalid sentence text position")
|
|
136
|
+
for key in ("text", "name", "destination", "voice", "codec", "code"):
|
|
137
|
+
if key in value and not isinstance(value[key], str):
|
|
138
|
+
raise ValueError("invalid text field")
|
|
139
|
+
if kind == "speaker_result" and (
|
|
140
|
+
value["destination"] not in {"local", "cloud"}
|
|
141
|
+
or type(value["distance"]) not in {int, float}
|
|
142
|
+
or not math.isfinite(value["distance"])
|
|
143
|
+
or value["distance"] < 0
|
|
144
|
+
):
|
|
145
|
+
raise ValueError("invalid speaker result")
|
|
146
|
+
for key in ("rate", "channels", "width", "sentence"):
|
|
147
|
+
if key in value:
|
|
148
|
+
unsigned(value[key], 32)
|
|
149
|
+
if kind == "format" and (
|
|
150
|
+
value["codec"] != "pcm_s16le"
|
|
151
|
+
or value["rate"] not in {16000, 22050}
|
|
152
|
+
or value["channels"] != 1
|
|
153
|
+
or value["width"] != 2
|
|
154
|
+
):
|
|
155
|
+
raise ValueError("unsupported audio format")
|
|
156
|
+
return value
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def encode_control(kind: str, turn_id: str, **fields: object) -> dict[str, Any]:
|
|
160
|
+
value = {"type": kind, "version": VERSION, "turn_id": turn_id, **fields}
|
|
161
|
+
return decode_control(
|
|
162
|
+
json.dumps(value, ensure_ascii=False, allow_nan=False), turn_id
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def encode_text(turn_id: str, text: str) -> Iterator[str]:
|
|
167
|
+
"""Divide text at code-point boundaries into complete wire messages."""
|
|
168
|
+
envelope = encode_control("text", turn_id, text="")
|
|
169
|
+
if not text:
|
|
170
|
+
yield json.dumps(envelope, ensure_ascii=False)
|
|
171
|
+
return
|
|
172
|
+
start = 0
|
|
173
|
+
while start < len(text):
|
|
174
|
+
low, high = 0, min(len(text) - start, MAX_CONTROL)
|
|
175
|
+
raw = ""
|
|
176
|
+
while low < high:
|
|
177
|
+
size = (low + high + 1) // 2
|
|
178
|
+
candidate = json.dumps(
|
|
179
|
+
{**envelope, "text": text[start : start + size]}, ensure_ascii=False
|
|
180
|
+
)
|
|
181
|
+
if len(candidate.encode("utf-8")) <= MAX_CONTROL:
|
|
182
|
+
low = size
|
|
183
|
+
raw = candidate
|
|
184
|
+
else:
|
|
185
|
+
high = size - 1
|
|
186
|
+
if not low:
|
|
187
|
+
raise ValueError("text character exceeds control limit")
|
|
188
|
+
yield raw
|
|
189
|
+
start += low
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def encode_transcript(kind: str, turn_id: str, text: str) -> dict[str, Any]:
|
|
193
|
+
"""Keep transcript text in the server's JSON wire budget."""
|
|
194
|
+
if len(json.dumps(text).encode("utf-8")) - 2 > MAX_TRANSCRIPT_BYTES:
|
|
195
|
+
raise ValueError("transcript limit exceeded")
|
|
196
|
+
return encode_control(kind, turn_id, text=text)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def encode_audio(turn_id: str, sequence: int, pcm: bytes) -> bytes:
|
|
200
|
+
unsigned(sequence, 32)
|
|
201
|
+
if not 0 < len(pcm) <= MAX_PCM or len(pcm) % 2:
|
|
202
|
+
raise ValueError("invalid PCM length")
|
|
203
|
+
return struct.pack("!B16sI", VERSION, UUID(turn_id).bytes, sequence) + pcm
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def decode_audio(frame: bytes, turn_id: str) -> tuple[int, bytes]:
|
|
207
|
+
if not 21 < len(frame) <= MAX_AUDIO or (len(frame) - 21) % 2:
|
|
208
|
+
raise ValueError("invalid audio length")
|
|
209
|
+
version, identifier, sequence = struct.unpack_from("!B16sI", frame)
|
|
210
|
+
if version != VERSION or identifier != UUID(turn_id).bytes:
|
|
211
|
+
raise ValueError("audio version or turn mismatch")
|
|
212
|
+
return sequence, frame[21:]
|