livekit-plugins-facemode 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.
- livekit_plugins_facemode/__init__.py +17 -0
- livekit_plugins_facemode/avatar.py +972 -0
- livekit_plugins_facemode/exceptions.py +17 -0
- livekit_plugins_facemode/models.py +240 -0
- livekit_plugins_facemode/version.py +1 -0
- livekit_plugins_facemode-0.1.0.dist-info/METADATA +13 -0
- livekit_plugins_facemode-0.1.0.dist-info/RECORD +10 -0
- livekit_plugins_facemode-0.1.0.dist-info/WHEEL +5 -0
- livekit_plugins_facemode-0.1.0.dist-info/licenses/LICENSE +13 -0
- livekit_plugins_facemode-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .avatar import AvatarSession
|
|
2
|
+
from .exceptions import FaceModeAPIError, FaceModeError, FaceModeNotReadyError, FaceModeProtocolError
|
|
3
|
+
from .models import IngestionDetails, LiveKitRoom, SessionDetails, SessionRequest
|
|
4
|
+
from .version import __version__
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AvatarSession",
|
|
8
|
+
"FaceModeAPIError",
|
|
9
|
+
"FaceModeError",
|
|
10
|
+
"FaceModeNotReadyError",
|
|
11
|
+
"FaceModeProtocolError",
|
|
12
|
+
"IngestionDetails",
|
|
13
|
+
"LiveKitRoom",
|
|
14
|
+
"SessionDetails",
|
|
15
|
+
"SessionRequest",
|
|
16
|
+
"__version__",
|
|
17
|
+
]
|
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
"""FaceMode AvatarSession for LiveKit Agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import contextlib
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import aiohttp
|
|
15
|
+
import websockets
|
|
16
|
+
from livekit import rtc
|
|
17
|
+
|
|
18
|
+
from .exceptions import (
|
|
19
|
+
FaceModeAPIError,
|
|
20
|
+
FaceModeError,
|
|
21
|
+
FaceModeNotReadyError,
|
|
22
|
+
FaceModeProtocolError,
|
|
23
|
+
)
|
|
24
|
+
from .models import (
|
|
25
|
+
SUPPORTED_INPUT_PROVIDERS,
|
|
26
|
+
IngestionDetails,
|
|
27
|
+
LiveKitRoom,
|
|
28
|
+
SessionDetails,
|
|
29
|
+
SessionRequest,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
from livekit.agents.voice.avatar import AvatarSession as BaseAvatarSession
|
|
34
|
+
except ImportError:
|
|
35
|
+
from livekit.agents.voice import AvatarSession as BaseAvatarSession
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
from livekit.agents.voice.io import AudioOutput, AudioOutputCapabilities
|
|
39
|
+
except ImportError:
|
|
40
|
+
AudioOutput = None
|
|
41
|
+
AudioOutputCapabilities = None
|
|
42
|
+
|
|
43
|
+
logger = logging.getLogger("livekit_plugins_facemode")
|
|
44
|
+
|
|
45
|
+
_MIN_INPUT_SAMPLE_RATE = 8_000
|
|
46
|
+
_MAX_INPUT_SAMPLE_RATE = 48_000
|
|
47
|
+
_INGESTION_READY_TIMEOUT_SECONDS = 240.0
|
|
48
|
+
_INGESTION_INITIAL_RETRY_SECONDS = 0.25
|
|
49
|
+
_INGESTION_MAX_RETRY_SECONDS = 2.0
|
|
50
|
+
_WS_OPEN_TIMEOUT_SECONDS = 240.0
|
|
51
|
+
_PROTOCOL_RESPONSE_TIMEOUT_SECONDS = 15.0
|
|
52
|
+
_RECONNECT_MAX_ATTEMPTS = 2
|
|
53
|
+
_RECONNECT_BACKOFF_SECONDS = 0.5
|
|
54
|
+
_PREFERRED_SAMPLE_RATES = frozenset(
|
|
55
|
+
{8_000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000}
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _FaceModeAudioOutput(AudioOutput):
|
|
60
|
+
def __init__(self, owner: "AvatarSession"):
|
|
61
|
+
super().__init__(
|
|
62
|
+
label="FaceModeAudioOutput",
|
|
63
|
+
next_in_chain=None,
|
|
64
|
+
sample_rate=None,
|
|
65
|
+
capabilities=AudioOutputCapabilities(pause=False),
|
|
66
|
+
)
|
|
67
|
+
self.owner = owner
|
|
68
|
+
self._utterance_started = False
|
|
69
|
+
|
|
70
|
+
async def capture_frame(self, frame: rtc.AudioFrame) -> None:
|
|
71
|
+
await self.owner._drain_control_tasks()
|
|
72
|
+
await super().capture_frame(frame)
|
|
73
|
+
if not self._utterance_started:
|
|
74
|
+
await self.owner._ensure_protocol_started(frame.sample_rate, frame.num_channels)
|
|
75
|
+
await self.owner._send_start_utterance()
|
|
76
|
+
self._utterance_started = True
|
|
77
|
+
await self.owner._send_tts_audio(frame)
|
|
78
|
+
|
|
79
|
+
def flush(self) -> None:
|
|
80
|
+
super().flush()
|
|
81
|
+
if self._utterance_started:
|
|
82
|
+
self.owner._schedule_control(self._finish_utterance(), "facemode-end-utterance")
|
|
83
|
+
self._utterance_started = False
|
|
84
|
+
|
|
85
|
+
def clear_buffer(self) -> None:
|
|
86
|
+
if self._utterance_started:
|
|
87
|
+
self.owner._schedule_control(
|
|
88
|
+
self.owner._send_cancel_utterance(), "facemode-cancel-utterance"
|
|
89
|
+
)
|
|
90
|
+
self._utterance_started = False
|
|
91
|
+
|
|
92
|
+
async def _finish_utterance(self) -> None:
|
|
93
|
+
await self.owner._send_end_utterance()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class AvatarSession(BaseAvatarSession):
|
|
97
|
+
def __init__(
|
|
98
|
+
self,
|
|
99
|
+
*,
|
|
100
|
+
api_key: str,
|
|
101
|
+
avatar_id: str = "",
|
|
102
|
+
api_url: str = "https://api.facemode.io/api",
|
|
103
|
+
avatar_participant_identity: str = "facemode-avatar",
|
|
104
|
+
avatar_participant_name: str = "FaceMode Avatar",
|
|
105
|
+
input_provider: str | None = None,
|
|
106
|
+
):
|
|
107
|
+
super().__init__()
|
|
108
|
+
if not api_key:
|
|
109
|
+
raise ValueError("api_key is required")
|
|
110
|
+
if (
|
|
111
|
+
input_provider is not None
|
|
112
|
+
and input_provider not in SUPPORTED_INPUT_PROVIDERS
|
|
113
|
+
):
|
|
114
|
+
raise ValueError(
|
|
115
|
+
"input_provider must be one of: "
|
|
116
|
+
+ ", ".join(sorted(SUPPORTED_INPUT_PROVIDERS))
|
|
117
|
+
)
|
|
118
|
+
self.api_key = api_key
|
|
119
|
+
self.avatar_id = avatar_id
|
|
120
|
+
self.api_url = api_url.rstrip("/")
|
|
121
|
+
self.input_provider = input_provider
|
|
122
|
+
self.avatar_participant_identity = avatar_participant_identity
|
|
123
|
+
self.avatar_participant_name = avatar_participant_name
|
|
124
|
+
self.session: SessionDetails | None = None
|
|
125
|
+
self._room: rtc.Room | None = None
|
|
126
|
+
self._agent_session = None
|
|
127
|
+
self._websocket = None
|
|
128
|
+
self._receiver_task: asyncio.Task | None = None
|
|
129
|
+
self._keepalive_task: asyncio.Task | None = None
|
|
130
|
+
self._join_task: asyncio.Task | None = None
|
|
131
|
+
self._control_tasks: set[asyncio.Task] = set()
|
|
132
|
+
self._protocol_started = asyncio.Event()
|
|
133
|
+
self._protocol_response = asyncio.Event()
|
|
134
|
+
self._avatar_ready = asyncio.Event()
|
|
135
|
+
self._session_ended = asyncio.Event()
|
|
136
|
+
self._protocol_error: FaceModeError | None = None
|
|
137
|
+
self._reconnect_task: asyncio.Task | None = None
|
|
138
|
+
self._protocol_lock = asyncio.Lock()
|
|
139
|
+
self._send_lock = asyncio.Lock()
|
|
140
|
+
self._audio_sample_rate: int | None = None
|
|
141
|
+
self._audio_channels: int | None = None
|
|
142
|
+
self._session_log_marker: str | None = None
|
|
143
|
+
self._sequence = 0
|
|
144
|
+
self._started_once = False
|
|
145
|
+
self._stopped = False
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def avatar_identity(self) -> str:
|
|
149
|
+
return self.avatar_participant_identity
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def provider(self) -> str:
|
|
153
|
+
return "facemode"
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def session_id(self) -> str | None:
|
|
157
|
+
return self.session.session_id if self.session else None
|
|
158
|
+
|
|
159
|
+
async def start(
|
|
160
|
+
self,
|
|
161
|
+
agent_session,
|
|
162
|
+
livekit_room: rtc.Room | None = None,
|
|
163
|
+
*,
|
|
164
|
+
room: LiveKitRoom | Mapping[str, Any] | rtc.Room | None = None,
|
|
165
|
+
room_config: LiveKitRoom | Mapping[str, Any] | None = None,
|
|
166
|
+
) -> None:
|
|
167
|
+
"""Start the avatar with a typed customer LiveKit room configuration.
|
|
168
|
+
|
|
169
|
+
``livekit_room`` is the already-connected AgentSession room used for
|
|
170
|
+
media. ``room`` carries the server-side room credentials sent to
|
|
171
|
+
FaceMode. ``room_config`` is an explicit alias for callers that prefer
|
|
172
|
+
to avoid the two meanings of the word room.
|
|
173
|
+
"""
|
|
174
|
+
if self._started_once:
|
|
175
|
+
raise RuntimeError("AvatarSession.start() may only be called once per instance")
|
|
176
|
+
if isinstance(room, rtc.Room):
|
|
177
|
+
if livekit_room is not None:
|
|
178
|
+
raise ValueError("livekit_room was provided more than once")
|
|
179
|
+
livekit_room = room
|
|
180
|
+
room = None
|
|
181
|
+
if room is not None and room_config is not None:
|
|
182
|
+
raise ValueError("pass either room or room_config, not both")
|
|
183
|
+
room_value = room_config if room_config is not None else room
|
|
184
|
+
if livekit_room is None:
|
|
185
|
+
raise ValueError("livekit_room is required")
|
|
186
|
+
if room_value is None:
|
|
187
|
+
raise ValueError("room is required")
|
|
188
|
+
try:
|
|
189
|
+
livekit_config = LiveKitRoom.from_value(room_value)
|
|
190
|
+
except ValueError as error:
|
|
191
|
+
raise ValueError(str(error)) from error
|
|
192
|
+
room_name = (
|
|
193
|
+
livekit_config.name
|
|
194
|
+
or str(getattr(livekit_room, "name", "") or "")
|
|
195
|
+
or _token_room_hint(livekit_config.token)
|
|
196
|
+
)
|
|
197
|
+
if not room_name:
|
|
198
|
+
raise ValueError("the exact LiveKit room name is required")
|
|
199
|
+
|
|
200
|
+
if self.avatar_participant_identity == "facemode-avatar":
|
|
201
|
+
token_identity = _token_identity_hint(livekit_config.token)
|
|
202
|
+
if token_identity:
|
|
203
|
+
self.avatar_participant_identity = token_identity
|
|
204
|
+
self._started_once = True
|
|
205
|
+
self._stopped = False
|
|
206
|
+
await super().start(agent_session, livekit_room)
|
|
207
|
+
self._room = livekit_room
|
|
208
|
+
self._agent_session = agent_session
|
|
209
|
+
try:
|
|
210
|
+
self.session = await self._create_session(livekit_config, room_name)
|
|
211
|
+
self.session = await self._wait_for_ingestion(self.session)
|
|
212
|
+
self._session_log_marker = _sanitize_session_marker(self.session.session_id)
|
|
213
|
+
if (
|
|
214
|
+
self.avatar_participant_identity == "facemode-avatar"
|
|
215
|
+
and self.session.avatar_participant_identity
|
|
216
|
+
):
|
|
217
|
+
self.avatar_participant_identity = self.session.avatar_participant_identity
|
|
218
|
+
self._websocket = await self._connect_websocket()
|
|
219
|
+
self._receiver_task = asyncio.create_task(
|
|
220
|
+
self._receive_events(), name="facemode-ws-events"
|
|
221
|
+
)
|
|
222
|
+
self._keepalive_task = asyncio.create_task(
|
|
223
|
+
self._keepalive_loop(), name="facemode-ws-keepalive"
|
|
224
|
+
)
|
|
225
|
+
tts = getattr(agent_session, "tts", None)
|
|
226
|
+
if tts is not None:
|
|
227
|
+
await self._ensure_protocol_started(
|
|
228
|
+
int(tts.sample_rate), int(tts.num_channels)
|
|
229
|
+
)
|
|
230
|
+
if getattr(agent_session, "output", None) is None:
|
|
231
|
+
raise FaceModeAPIError("LiveKit AgentSession output is not initialized")
|
|
232
|
+
agent_session.output.replace_audio_tail(_FaceModeAudioOutput(self))
|
|
233
|
+
self._join_task = asyncio.create_task(
|
|
234
|
+
self._wait_for_video_track(), name="facemode-avatar-join"
|
|
235
|
+
)
|
|
236
|
+
logger.info("FaceMode avatar session started session=%s", self._session_log_marker)
|
|
237
|
+
except asyncio.CancelledError:
|
|
238
|
+
with contextlib.suppress(Exception):
|
|
239
|
+
await self.stop()
|
|
240
|
+
raise
|
|
241
|
+
except Exception as error:
|
|
242
|
+
with contextlib.suppress(Exception):
|
|
243
|
+
await self.stop()
|
|
244
|
+
if isinstance(error, (FaceModeAPIError, FaceModeProtocolError)):
|
|
245
|
+
raise
|
|
246
|
+
raise FaceModeAPIError(
|
|
247
|
+
f"Unable to start FaceMode avatar session: {error.__class__.__name__}"
|
|
248
|
+
) from error
|
|
249
|
+
|
|
250
|
+
async def wait_for_join(self, *, timeout: float | None = 30.0) -> None:
|
|
251
|
+
if self._join_task is None:
|
|
252
|
+
return
|
|
253
|
+
try:
|
|
254
|
+
if timeout is None:
|
|
255
|
+
await self._join_task
|
|
256
|
+
else:
|
|
257
|
+
await asyncio.wait_for(asyncio.shield(self._join_task), timeout=timeout)
|
|
258
|
+
except asyncio.TimeoutError as error:
|
|
259
|
+
raise FaceModeNotReadyError("Timed out waiting for FaceMode avatar video track") from error
|
|
260
|
+
|
|
261
|
+
async def stop(self) -> None:
|
|
262
|
+
if self._stopped:
|
|
263
|
+
return
|
|
264
|
+
self._stopped = True
|
|
265
|
+
await self._cancel_task(self._keepalive_task)
|
|
266
|
+
self._keepalive_task = None
|
|
267
|
+
await self._cancel_task(self._reconnect_task)
|
|
268
|
+
self._reconnect_task = None
|
|
269
|
+
self._protocol_response.set()
|
|
270
|
+
with contextlib.suppress(Exception):
|
|
271
|
+
await self._drain_control_tasks()
|
|
272
|
+
|
|
273
|
+
websocket = self._websocket
|
|
274
|
+
if websocket is not None:
|
|
275
|
+
if self._protocol_started.is_set():
|
|
276
|
+
with contextlib.suppress(Exception):
|
|
277
|
+
await self._send_control("end_session", self._next_sequence())
|
|
278
|
+
await asyncio.wait_for(self._session_ended.wait(), timeout=3.0)
|
|
279
|
+
with contextlib.suppress(Exception):
|
|
280
|
+
await websocket.close()
|
|
281
|
+
|
|
282
|
+
await self._cancel_task(self._receiver_task)
|
|
283
|
+
self._receiver_task = None
|
|
284
|
+
await self._cancel_task(self._join_task)
|
|
285
|
+
self._join_task = None
|
|
286
|
+
for task in tuple(self._control_tasks):
|
|
287
|
+
task.cancel()
|
|
288
|
+
if self._control_tasks:
|
|
289
|
+
await asyncio.gather(*tuple(self._control_tasks), return_exceptions=True)
|
|
290
|
+
self._control_tasks.clear()
|
|
291
|
+
self._websocket = None
|
|
292
|
+
with contextlib.suppress(Exception):
|
|
293
|
+
await super().aclose()
|
|
294
|
+
|
|
295
|
+
async def aclose(self) -> None:
|
|
296
|
+
await self.stop()
|
|
297
|
+
|
|
298
|
+
async def _create_session(self, room: LiveKitRoom, room_name: str) -> SessionDetails:
|
|
299
|
+
payload = SessionRequest(
|
|
300
|
+
avatar_id=self.avatar_id,
|
|
301
|
+
room=room,
|
|
302
|
+
room_name=room_name,
|
|
303
|
+
input_provider=self.input_provider,
|
|
304
|
+
).to_payload()
|
|
305
|
+
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
|
306
|
+
try:
|
|
307
|
+
timeout = aiohttp.ClientTimeout(total=30)
|
|
308
|
+
async with aiohttp.ClientSession(timeout=timeout) as client:
|
|
309
|
+
async with client.post(f"{self.api_url}/sessions", json=payload, headers=headers) as response:
|
|
310
|
+
body = await response.text()
|
|
311
|
+
if response.status >= 400:
|
|
312
|
+
raise FaceModeAPIError(
|
|
313
|
+
f"FaceMode session creation failed ({response.status})"
|
|
314
|
+
)
|
|
315
|
+
try:
|
|
316
|
+
data = json.loads(body)
|
|
317
|
+
except json.JSONDecodeError as error:
|
|
318
|
+
raise FaceModeAPIError("FaceMode session response was not JSON") from error
|
|
319
|
+
if not isinstance(data, Mapping):
|
|
320
|
+
raise FaceModeAPIError("FaceMode session response was not an object")
|
|
321
|
+
try:
|
|
322
|
+
return SessionDetails.from_api(data)
|
|
323
|
+
except ValueError as error:
|
|
324
|
+
raise FaceModeAPIError("FaceMode session response was incomplete") from error
|
|
325
|
+
except FaceModeAPIError:
|
|
326
|
+
raise
|
|
327
|
+
except Exception as error:
|
|
328
|
+
raise FaceModeAPIError(
|
|
329
|
+
f"FaceMode session request failed: {error.__class__.__name__}"
|
|
330
|
+
) from error
|
|
331
|
+
|
|
332
|
+
async def _wait_for_ingestion(self, initial_session: SessionDetails) -> SessionDetails:
|
|
333
|
+
"""Poll the public session resource until its ingestion connection is usable.
|
|
334
|
+
|
|
335
|
+
The create-session response usually arrives already ready, in which case
|
|
336
|
+
no HTTP session is opened at all. Terminal worker states short-circuit
|
|
337
|
+
before any polling or retry delay.
|
|
338
|
+
"""
|
|
339
|
+
session = initial_session
|
|
340
|
+
self._raise_terminal_worker_state(session)
|
|
341
|
+
if not session.ingestion.ready:
|
|
342
|
+
deadline = asyncio.get_running_loop().time() + _INGESTION_READY_TIMEOUT_SECONDS
|
|
343
|
+
delay = _INGESTION_INITIAL_RETRY_SECONDS
|
|
344
|
+
timeout = aiohttp.ClientTimeout(total=30)
|
|
345
|
+
headers = {"Authorization": f"Bearer {self.api_key}"}
|
|
346
|
+
|
|
347
|
+
async with aiohttp.ClientSession(timeout=timeout) as client:
|
|
348
|
+
while not session.ingestion.ready:
|
|
349
|
+
if asyncio.get_running_loop().time() >= deadline:
|
|
350
|
+
raise FaceModeAPIError("Timed out waiting for FaceMode ingestion assignment")
|
|
351
|
+
await asyncio.sleep(delay)
|
|
352
|
+
delay = min(delay * 1.5, _INGESTION_MAX_RETRY_SECONDS)
|
|
353
|
+
try:
|
|
354
|
+
async with client.get(
|
|
355
|
+
f"{self.api_url}/sessions/{session.session_id}", headers=headers
|
|
356
|
+
) as response:
|
|
357
|
+
body = await response.text()
|
|
358
|
+
if response.status >= 400:
|
|
359
|
+
raise FaceModeAPIError(
|
|
360
|
+
f"FaceMode ingestion status failed ({response.status})"
|
|
361
|
+
)
|
|
362
|
+
data = json.loads(body)
|
|
363
|
+
except FaceModeAPIError:
|
|
364
|
+
raise
|
|
365
|
+
except json.JSONDecodeError as error:
|
|
366
|
+
raise FaceModeAPIError(
|
|
367
|
+
"FaceMode ingestion status response was not JSON"
|
|
368
|
+
) from error
|
|
369
|
+
except Exception as error:
|
|
370
|
+
raise FaceModeAPIError(
|
|
371
|
+
f"FaceMode ingestion status request failed: {error.__class__.__name__}"
|
|
372
|
+
) from error
|
|
373
|
+
|
|
374
|
+
if not isinstance(data, Mapping):
|
|
375
|
+
raise FaceModeAPIError("FaceMode ingestion status response was not an object")
|
|
376
|
+
try:
|
|
377
|
+
session = SessionDetails.from_api(data, fallback=session)
|
|
378
|
+
except ValueError as error:
|
|
379
|
+
raise FaceModeAPIError(
|
|
380
|
+
"FaceMode ingestion status response was incomplete"
|
|
381
|
+
) from error
|
|
382
|
+
self._raise_terminal_worker_state(session)
|
|
383
|
+
|
|
384
|
+
if not session.ingestion.url or not session.ingestion.ws_token:
|
|
385
|
+
raise FaceModeAPIError(
|
|
386
|
+
"FaceMode ingestion assignment is missing WebSocket credentials"
|
|
387
|
+
)
|
|
388
|
+
return session
|
|
389
|
+
|
|
390
|
+
@staticmethod
|
|
391
|
+
def _raise_terminal_worker_state(session: SessionDetails) -> None:
|
|
392
|
+
if session.worker_status in {"FAILED", "ENDED"}:
|
|
393
|
+
raise FaceModeAPIError(
|
|
394
|
+
f"FaceMode ingestion worker entered {session.worker_status.lower()} state"
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
async def _connect_websocket(self):
|
|
398
|
+
"""Open the canonical ingestion socket with backend-issued headers intact."""
|
|
399
|
+
if self.session is None:
|
|
400
|
+
raise FaceModeProtocolError("FaceMode session is not initialized")
|
|
401
|
+
ingestion = self.session.ingestion
|
|
402
|
+
if not ingestion.ready or not ingestion.url or not ingestion.ws_token:
|
|
403
|
+
raise FaceModeProtocolError("FaceMode ingestion assignment is not ready")
|
|
404
|
+
return await websockets.connect(
|
|
405
|
+
ingestion.url,
|
|
406
|
+
subprotocols=[f"facemode.{ingestion.ws_token}"],
|
|
407
|
+
additional_headers=dict(ingestion.headers),
|
|
408
|
+
max_size=2**20,
|
|
409
|
+
ping_interval=None,
|
|
410
|
+
compression=None,
|
|
411
|
+
open_timeout=_WS_OPEN_TIMEOUT_SECONDS,
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
async def _request_reconnect_session(self) -> SessionDetails:
|
|
415
|
+
"""POST the session reconnect endpoint for a fresh one-time wsToken.
|
|
416
|
+
|
|
417
|
+
The body intentionally carries only the LiveKit room object; no prior
|
|
418
|
+
WebSocket credential or extra secret is replayed.
|
|
419
|
+
"""
|
|
420
|
+
if self.session is None:
|
|
421
|
+
raise FaceModeAPIError("FaceMode session is not initialized")
|
|
422
|
+
url = f"{self.api_url}/sessions/{self.session.session_id}/reconnect"
|
|
423
|
+
payload = {"room": self.session.room.to_payload()}
|
|
424
|
+
headers = {
|
|
425
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
426
|
+
"Content-Type": "application/json",
|
|
427
|
+
}
|
|
428
|
+
try:
|
|
429
|
+
timeout = aiohttp.ClientTimeout(total=30)
|
|
430
|
+
async with aiohttp.ClientSession(timeout=timeout) as client:
|
|
431
|
+
async with client.post(url, json=payload, headers=headers) as response:
|
|
432
|
+
body = await response.text()
|
|
433
|
+
if response.status >= 400:
|
|
434
|
+
raise FaceModeAPIError(
|
|
435
|
+
f"FaceMode session reconnect failed ({response.status})"
|
|
436
|
+
)
|
|
437
|
+
try:
|
|
438
|
+
data = json.loads(body)
|
|
439
|
+
except json.JSONDecodeError as error:
|
|
440
|
+
raise FaceModeAPIError(
|
|
441
|
+
"FaceMode reconnect response was not JSON"
|
|
442
|
+
) from error
|
|
443
|
+
if not isinstance(data, Mapping):
|
|
444
|
+
raise FaceModeAPIError("FaceMode reconnect response was not an object")
|
|
445
|
+
merged = dict(data)
|
|
446
|
+
merged.setdefault("sessionId", self.session.session_id)
|
|
447
|
+
try:
|
|
448
|
+
refreshed = SessionDetails.from_api(merged, fallback=self.session)
|
|
449
|
+
except ValueError as error:
|
|
450
|
+
raise FaceModeAPIError(
|
|
451
|
+
"FaceMode reconnect response was incomplete"
|
|
452
|
+
) from error
|
|
453
|
+
except FaceModeAPIError:
|
|
454
|
+
raise
|
|
455
|
+
except Exception as error:
|
|
456
|
+
raise FaceModeAPIError(
|
|
457
|
+
f"FaceMode reconnect request failed: {error.__class__.__name__}"
|
|
458
|
+
) from error
|
|
459
|
+
if (
|
|
460
|
+
not refreshed.ingestion.ready
|
|
461
|
+
or not refreshed.ingestion.url
|
|
462
|
+
or not refreshed.ingestion.ws_token
|
|
463
|
+
):
|
|
464
|
+
raise FaceModeAPIError(
|
|
465
|
+
"FaceMode reconnect response is missing WebSocket credentials"
|
|
466
|
+
)
|
|
467
|
+
return refreshed
|
|
468
|
+
|
|
469
|
+
def _reconnecting(self) -> bool:
|
|
470
|
+
task = self._reconnect_task
|
|
471
|
+
return task is not None and not task.done()
|
|
472
|
+
|
|
473
|
+
def _start_reconnect(self) -> asyncio.Task | None:
|
|
474
|
+
"""Single-flight starter shared by every transport-loss signal.
|
|
475
|
+
|
|
476
|
+
Returns the in-flight task when one is already running, a fresh task
|
|
477
|
+
when reconnect is allowed, or ``None`` when the session is stopped,
|
|
478
|
+
ended, already in a fatal error state, or never negotiated the
|
|
479
|
+
protocol in the first place.
|
|
480
|
+
"""
|
|
481
|
+
task = self._reconnect_task
|
|
482
|
+
if task is not None and not task.done():
|
|
483
|
+
return task
|
|
484
|
+
if (
|
|
485
|
+
self._stopped
|
|
486
|
+
or self._session_ended.is_set()
|
|
487
|
+
or self._protocol_error is not None
|
|
488
|
+
or not self._protocol_started.is_set()
|
|
489
|
+
):
|
|
490
|
+
return None
|
|
491
|
+
self._protocol_started.clear()
|
|
492
|
+
self._protocol_response.clear()
|
|
493
|
+
self._avatar_ready.clear()
|
|
494
|
+
task = asyncio.create_task(self._reconnect(), name="facemode-ws-reconnect")
|
|
495
|
+
self._reconnect_task = task
|
|
496
|
+
return task
|
|
497
|
+
|
|
498
|
+
async def _reconnect(self) -> None:
|
|
499
|
+
"""Open a fresh ingestion socket and renegotiate the canonical start.
|
|
500
|
+
|
|
501
|
+
Bounded to ``_RECONNECT_MAX_ATTEMPTS`` attempts with linear backoff.
|
|
502
|
+
Every attempt requests a new one-time wsToken; a consumed token is
|
|
503
|
+
never replayed. Exhaustion is recorded as a typed FaceMode error on
|
|
504
|
+
``_protocol_error`` rather than raised through the receiver task.
|
|
505
|
+
"""
|
|
506
|
+
last_error: FaceModeError | None = None
|
|
507
|
+
self._protocol_started.clear()
|
|
508
|
+
self._protocol_response.clear()
|
|
509
|
+
for attempt in range(1, _RECONNECT_MAX_ATTEMPTS + 1):
|
|
510
|
+
if self._stopped or self._session_ended.is_set():
|
|
511
|
+
return
|
|
512
|
+
pending = None
|
|
513
|
+
adopted = False
|
|
514
|
+
try:
|
|
515
|
+
self._protocol_error = None
|
|
516
|
+
refreshed = await self._request_reconnect_session()
|
|
517
|
+
self.session = refreshed
|
|
518
|
+
pending = await self._connect_websocket()
|
|
519
|
+
self._websocket = pending
|
|
520
|
+
async with self._send_lock:
|
|
521
|
+
await pending.send(self._start_message())
|
|
522
|
+
await self._await_reconnect_started(pending)
|
|
523
|
+
adopted = True
|
|
524
|
+
logger.info(
|
|
525
|
+
"FaceMode WebSocket reconnected session=%s attempt=%s",
|
|
526
|
+
self._session_log_marker,
|
|
527
|
+
attempt,
|
|
528
|
+
)
|
|
529
|
+
return
|
|
530
|
+
except asyncio.CancelledError:
|
|
531
|
+
raise
|
|
532
|
+
except FaceModeError as error:
|
|
533
|
+
last_error = error
|
|
534
|
+
except Exception as error:
|
|
535
|
+
last_error = FaceModeNotReadyError(
|
|
536
|
+
f"FaceMode reconnect failed: {error.__class__.__name__}"
|
|
537
|
+
)
|
|
538
|
+
finally:
|
|
539
|
+
if pending is not None and not adopted:
|
|
540
|
+
try:
|
|
541
|
+
await pending.close()
|
|
542
|
+
finally:
|
|
543
|
+
if self._websocket is pending:
|
|
544
|
+
self._websocket = None
|
|
545
|
+
if attempt < _RECONNECT_MAX_ATTEMPTS:
|
|
546
|
+
await asyncio.sleep(_RECONNECT_BACKOFF_SECONDS * attempt)
|
|
547
|
+
self._protocol_error = last_error or FaceModeNotReadyError(
|
|
548
|
+
"FaceMode reconnect attempts exhausted"
|
|
549
|
+
)
|
|
550
|
+
self._protocol_response.set()
|
|
551
|
+
logger.warning("FaceMode reconnect exhausted: %s", self._protocol_error)
|
|
552
|
+
|
|
553
|
+
async def _await_reconnect_started(self, websocket) -> None:
|
|
554
|
+
"""Read the fresh socket until the canonical ``started`` message lands."""
|
|
555
|
+
iterator = websocket.__aiter__()
|
|
556
|
+
while not self._protocol_started.is_set():
|
|
557
|
+
self._raise_protocol_error()
|
|
558
|
+
if self._stopped or self._session_ended.is_set():
|
|
559
|
+
raise FaceModeNotReadyError(
|
|
560
|
+
"FaceMode session ended while reconnecting"
|
|
561
|
+
)
|
|
562
|
+
try:
|
|
563
|
+
raw = await asyncio.wait_for(
|
|
564
|
+
iterator.__anext__(),
|
|
565
|
+
timeout=_PROTOCOL_RESPONSE_TIMEOUT_SECONDS,
|
|
566
|
+
)
|
|
567
|
+
except StopAsyncIteration as error:
|
|
568
|
+
raise FaceModeNotReadyError(
|
|
569
|
+
"FaceMode WebSocket closed during reconnect"
|
|
570
|
+
) from error
|
|
571
|
+
except asyncio.TimeoutError as error:
|
|
572
|
+
raise FaceModeNotReadyError(
|
|
573
|
+
"FaceMode did not acknowledge reconnect negotiation"
|
|
574
|
+
) from error
|
|
575
|
+
self._dispatch_message(raw)
|
|
576
|
+
|
|
577
|
+
async def _wait_for_send_ready(self) -> None:
|
|
578
|
+
"""Block outbound sends until renegotiation finishes or fails."""
|
|
579
|
+
while not self._protocol_started.is_set():
|
|
580
|
+
self._raise_protocol_error()
|
|
581
|
+
if self._stopped:
|
|
582
|
+
raise FaceModeProtocolError("FaceMode session is stopped")
|
|
583
|
+
if self._session_ended.is_set():
|
|
584
|
+
raise FaceModeProtocolError("FaceMode session has ended")
|
|
585
|
+
await self._protocol_response.wait()
|
|
586
|
+
|
|
587
|
+
async def _send_start_utterance(self) -> None:
|
|
588
|
+
await self._send_control("start_utterance", self._next_sequence())
|
|
589
|
+
|
|
590
|
+
async def _send_end_utterance(self) -> None:
|
|
591
|
+
if self._protocol_started.is_set():
|
|
592
|
+
await self._send_control("end_utterance", self._next_sequence())
|
|
593
|
+
|
|
594
|
+
async def _send_cancel_utterance(self) -> None:
|
|
595
|
+
if self._protocol_started.is_set():
|
|
596
|
+
await self._send_control("cancel_utterance", self._next_sequence())
|
|
597
|
+
|
|
598
|
+
async def _send_tts_audio(self, frame: rtc.AudioFrame) -> None:
|
|
599
|
+
await self._ensure_protocol_started(frame.sample_rate, frame.num_channels)
|
|
600
|
+
self._raise_protocol_error()
|
|
601
|
+
if self._websocket is None:
|
|
602
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
603
|
+
audio = frame.data.tobytes()
|
|
604
|
+
alignment = 2 * frame.num_channels
|
|
605
|
+
if len(audio) % alignment:
|
|
606
|
+
raise FaceModeProtocolError("LiveKit TTS PCM payload is not channel aligned")
|
|
607
|
+
async with self._send_lock:
|
|
608
|
+
if not self._protocol_started.is_set():
|
|
609
|
+
raise FaceModeProtocolError("FaceMode protocol is not ready")
|
|
610
|
+
await self._websocket.send(audio)
|
|
611
|
+
|
|
612
|
+
def _start_message(self) -> str:
|
|
613
|
+
"""Canonical ``start`` payload shared by negotiation and reconnect."""
|
|
614
|
+
if (
|
|
615
|
+
self.session is None
|
|
616
|
+
or self._audio_sample_rate is None
|
|
617
|
+
or self._audio_channels is None
|
|
618
|
+
):
|
|
619
|
+
raise FaceModeProtocolError(
|
|
620
|
+
"FaceMode session audio format is not initialized"
|
|
621
|
+
)
|
|
622
|
+
return json.dumps({
|
|
623
|
+
"type": "start",
|
|
624
|
+
"session_id": self.session.session_id,
|
|
625
|
+
"audio_encoding": "pcm_s16le",
|
|
626
|
+
"sample_rate": int(self._audio_sample_rate),
|
|
627
|
+
"channels": int(self._audio_channels),
|
|
628
|
+
"avatar_id": self.avatar_id,
|
|
629
|
+
"metadata": {"source": "livekit-agents"},
|
|
630
|
+
}, separators=(",", ":"))
|
|
631
|
+
|
|
632
|
+
async def _ensure_protocol_started(self, sample_rate: int, channels: int) -> None:
|
|
633
|
+
async with self._protocol_lock:
|
|
634
|
+
self._raise_protocol_error()
|
|
635
|
+
if not self._protocol_started.is_set() and self._reconnecting():
|
|
636
|
+
await self._wait_for_send_ready()
|
|
637
|
+
if self._protocol_started.is_set():
|
|
638
|
+
if (
|
|
639
|
+
self._audio_sample_rate != sample_rate
|
|
640
|
+
or self._audio_channels != channels
|
|
641
|
+
):
|
|
642
|
+
raise FaceModeProtocolError(
|
|
643
|
+
"LiveKit TTS audio format changed during the FaceMode session"
|
|
644
|
+
)
|
|
645
|
+
return
|
|
646
|
+
if isinstance(sample_rate, bool) or not isinstance(sample_rate, int):
|
|
647
|
+
raise FaceModeProtocolError("LiveKit TTS sample rate must be an integer")
|
|
648
|
+
if not _MIN_INPUT_SAMPLE_RATE <= sample_rate <= _MAX_INPUT_SAMPLE_RATE:
|
|
649
|
+
raise FaceModeProtocolError(
|
|
650
|
+
f"LiveKit TTS sample rate must be between {_MIN_INPUT_SAMPLE_RATE} "
|
|
651
|
+
f"and {_MAX_INPUT_SAMPLE_RATE}: {sample_rate}"
|
|
652
|
+
)
|
|
653
|
+
if sample_rate not in _PREFERRED_SAMPLE_RATES:
|
|
654
|
+
logger.info("Using uncommon LiveKit TTS sample rate: %s", sample_rate)
|
|
655
|
+
if channels not in (1, 2):
|
|
656
|
+
raise FaceModeProtocolError(f"Unsupported LiveKit TTS channel count: {channels}")
|
|
657
|
+
if self._websocket is None or self.session is None:
|
|
658
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
659
|
+
self._audio_sample_rate = sample_rate
|
|
660
|
+
self._audio_channels = channels
|
|
661
|
+
async with self._send_lock:
|
|
662
|
+
await self._websocket.send(self._start_message())
|
|
663
|
+
try:
|
|
664
|
+
await asyncio.wait_for(self._protocol_response.wait(), timeout=15)
|
|
665
|
+
except asyncio.TimeoutError as error:
|
|
666
|
+
raise FaceModeProtocolError("FaceMode did not acknowledge protocol negotiation") from error
|
|
667
|
+
self._raise_protocol_error()
|
|
668
|
+
if not self._protocol_started.is_set():
|
|
669
|
+
raise FaceModeProtocolError("FaceMode protocol negotiation did not start")
|
|
670
|
+
|
|
671
|
+
async def _send_control(self, message_type: str, sequence: int) -> None:
|
|
672
|
+
self._raise_protocol_error()
|
|
673
|
+
if not self._protocol_started.is_set() and self._reconnecting():
|
|
674
|
+
await self._wait_for_send_ready()
|
|
675
|
+
if self._websocket is None:
|
|
676
|
+
if self._stopped:
|
|
677
|
+
return
|
|
678
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
679
|
+
async with self._send_lock:
|
|
680
|
+
if not self._protocol_started.is_set():
|
|
681
|
+
raise FaceModeProtocolError("FaceMode protocol is not ready")
|
|
682
|
+
await self._websocket.send(json.dumps({"type": message_type, "seq": sequence}, separators=(",", ":")))
|
|
683
|
+
|
|
684
|
+
async def _send_ping(self) -> None:
|
|
685
|
+
self._raise_protocol_error()
|
|
686
|
+
if not self._protocol_started.is_set() and self._reconnecting():
|
|
687
|
+
await self._wait_for_send_ready()
|
|
688
|
+
if self._websocket is None:
|
|
689
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
690
|
+
async with self._send_lock:
|
|
691
|
+
await self._websocket.send(json.dumps({
|
|
692
|
+
"type": "ping",
|
|
693
|
+
"ts": int(time.time() * 1000),
|
|
694
|
+
}, separators=(",", ":")))
|
|
695
|
+
|
|
696
|
+
async def _keepalive_loop(self) -> None:
|
|
697
|
+
try:
|
|
698
|
+
await self._protocol_response.wait()
|
|
699
|
+
if not self._protocol_started.is_set() or self._protocol_error is not None:
|
|
700
|
+
return
|
|
701
|
+
while not self._stopped:
|
|
702
|
+
await asyncio.sleep(15.0)
|
|
703
|
+
if self._websocket is None or self._stopped:
|
|
704
|
+
return
|
|
705
|
+
try:
|
|
706
|
+
await self._send_ping()
|
|
707
|
+
except Exception as error:
|
|
708
|
+
if not self._stopped:
|
|
709
|
+
protocol_error = FaceModeProtocolError(
|
|
710
|
+
f"FaceMode keepalive failed: {error.__class__.__name__}"
|
|
711
|
+
)
|
|
712
|
+
self._set_protocol_error(protocol_error)
|
|
713
|
+
logger.warning("%s", protocol_error)
|
|
714
|
+
return
|
|
715
|
+
except asyncio.CancelledError:
|
|
716
|
+
raise
|
|
717
|
+
|
|
718
|
+
async def _receive_events(self) -> None:
|
|
719
|
+
"""Read inbound messages, transparently re-attaching after drops.
|
|
720
|
+
|
|
721
|
+
A transport loss after a successful ``start`` triggers the
|
|
722
|
+
single-flight reconnect path instead of a protocol error. Intentional
|
|
723
|
+
close, session ``ended``, fatal protocol errors, and drops before the
|
|
724
|
+
first negotiation keep the original fail-fast behavior.
|
|
725
|
+
"""
|
|
726
|
+
try:
|
|
727
|
+
while True:
|
|
728
|
+
websocket = self._websocket
|
|
729
|
+
if websocket is None:
|
|
730
|
+
return
|
|
731
|
+
transport_error: Exception | None = None
|
|
732
|
+
try:
|
|
733
|
+
async for raw in websocket:
|
|
734
|
+
try:
|
|
735
|
+
fatal = self._dispatch_message(raw)
|
|
736
|
+
except FaceModeProtocolError as error:
|
|
737
|
+
self._set_protocol_error(error)
|
|
738
|
+
logger.warning("%s", error)
|
|
739
|
+
fatal = True
|
|
740
|
+
if fatal:
|
|
741
|
+
break
|
|
742
|
+
except asyncio.CancelledError:
|
|
743
|
+
raise
|
|
744
|
+
except Exception as error:
|
|
745
|
+
transport_error = error
|
|
746
|
+
if self._stopped or self._session_ended.is_set():
|
|
747
|
+
return
|
|
748
|
+
if self._protocol_error is not None:
|
|
749
|
+
return
|
|
750
|
+
task = self._start_reconnect()
|
|
751
|
+
if task is None:
|
|
752
|
+
if transport_error is not None:
|
|
753
|
+
protocol_error = FaceModeProtocolError(
|
|
754
|
+
"FaceMode WebSocket receiver stopped: "
|
|
755
|
+
f"{transport_error.__class__.__name__}"
|
|
756
|
+
f"{_websocket_close_details(transport_error)}"
|
|
757
|
+
)
|
|
758
|
+
else:
|
|
759
|
+
protocol_error = FaceModeProtocolError(
|
|
760
|
+
"FaceMode WebSocket closed unexpectedly"
|
|
761
|
+
f"{_websocket_close_details(websocket)}"
|
|
762
|
+
)
|
|
763
|
+
self._set_protocol_error(protocol_error)
|
|
764
|
+
logger.warning("%s", protocol_error)
|
|
765
|
+
return
|
|
766
|
+
await asyncio.wait({task})
|
|
767
|
+
if (
|
|
768
|
+
self._stopped
|
|
769
|
+
or self._session_ended.is_set()
|
|
770
|
+
or self._protocol_error is not None
|
|
771
|
+
or self._websocket is websocket
|
|
772
|
+
):
|
|
773
|
+
return
|
|
774
|
+
except asyncio.CancelledError:
|
|
775
|
+
raise
|
|
776
|
+
|
|
777
|
+
def _dispatch_message(self, raw) -> bool:
|
|
778
|
+
"""Handle one wire message; return True if the socket must be dropped."""
|
|
779
|
+
if isinstance(raw, bytes):
|
|
780
|
+
return False
|
|
781
|
+
try:
|
|
782
|
+
message = json.loads(raw)
|
|
783
|
+
except json.JSONDecodeError as error:
|
|
784
|
+
raise FaceModeProtocolError(
|
|
785
|
+
"FaceMode WebSocket message was not JSON"
|
|
786
|
+
) from error
|
|
787
|
+
if not isinstance(message, Mapping):
|
|
788
|
+
raise FaceModeProtocolError("FaceMode WebSocket message was not an object")
|
|
789
|
+
message_type = str(message.get("type", ""))
|
|
790
|
+
if message_type == "started":
|
|
791
|
+
self._handle_started(message)
|
|
792
|
+
elif message_type == "audio_ready":
|
|
793
|
+
self._avatar_ready.set()
|
|
794
|
+
elif message_type == "utterance_ended":
|
|
795
|
+
logger.debug(
|
|
796
|
+
"FaceMode utterance ended seq=%s cycles=%s",
|
|
797
|
+
message.get("seq"),
|
|
798
|
+
message.get("cycles"),
|
|
799
|
+
)
|
|
800
|
+
elif message_type == "pong":
|
|
801
|
+
logger.debug("FaceMode keepalive acknowledged")
|
|
802
|
+
elif message_type == "session_ending":
|
|
803
|
+
protocol_error = FaceModeProtocolError(
|
|
804
|
+
f"FaceMode session is ending: {message.get('reason', 'unknown')}"
|
|
805
|
+
)
|
|
806
|
+
self._set_protocol_error(protocol_error)
|
|
807
|
+
logger.warning("%s", protocol_error)
|
|
808
|
+
elif message_type == "ended":
|
|
809
|
+
self._session_ended.set()
|
|
810
|
+
self._protocol_response.set()
|
|
811
|
+
elif message_type == "error":
|
|
812
|
+
protocol_error = FaceModeProtocolError(
|
|
813
|
+
f"{message.get('code', 'INTERNAL_ERROR')}: {message.get('message', 'FaceMode error')}"
|
|
814
|
+
)
|
|
815
|
+
self._set_protocol_error(protocol_error)
|
|
816
|
+
logger.error("FaceMode protocol error: %s", protocol_error)
|
|
817
|
+
if bool(message.get("fatal", False)):
|
|
818
|
+
return True
|
|
819
|
+
else:
|
|
820
|
+
logger.debug("FaceMode WebSocket unhandled message type: %s", message_type)
|
|
821
|
+
return False
|
|
822
|
+
|
|
823
|
+
def _handle_started(self, message: Mapping[str, Any]) -> None:
|
|
824
|
+
if self.session is None:
|
|
825
|
+
self._set_protocol_error(FaceModeProtocolError("FaceMode session is not initialized"))
|
|
826
|
+
return
|
|
827
|
+
if str(message.get("session_id", "")) != self.session.session_id:
|
|
828
|
+
self._set_protocol_error(
|
|
829
|
+
FaceModeProtocolError("FaceMode started response session ID did not match")
|
|
830
|
+
)
|
|
831
|
+
return
|
|
832
|
+
if message.get("server_sample_rate") != 48_000 or message.get("server_channels") != 1:
|
|
833
|
+
self._set_protocol_error(
|
|
834
|
+
FaceModeProtocolError("FaceMode server reported an unsupported canonical audio format")
|
|
835
|
+
)
|
|
836
|
+
return
|
|
837
|
+
self._protocol_started.set()
|
|
838
|
+
self._protocol_response.set()
|
|
839
|
+
logger.info("FaceMode protocol started session=%s", self._session_log_marker)
|
|
840
|
+
|
|
841
|
+
async def _wait_for_video_track(self) -> None:
|
|
842
|
+
room = self._room
|
|
843
|
+
if room is None:
|
|
844
|
+
raise FaceModeNotReadyError("LiveKit room is not available")
|
|
845
|
+
if self._has_remote_video_track():
|
|
846
|
+
return
|
|
847
|
+
event = asyncio.Event()
|
|
848
|
+
|
|
849
|
+
def on_track_subscribed(track, _publication, participant):
|
|
850
|
+
if (
|
|
851
|
+
track.kind == rtc.TrackKind.KIND_VIDEO
|
|
852
|
+
and participant.identity == self.avatar_participant_identity
|
|
853
|
+
):
|
|
854
|
+
event.set()
|
|
855
|
+
|
|
856
|
+
room.on("track_subscribed", on_track_subscribed)
|
|
857
|
+
try:
|
|
858
|
+
if self._has_remote_video_track():
|
|
859
|
+
return
|
|
860
|
+
await event.wait()
|
|
861
|
+
finally:
|
|
862
|
+
room.off("track_subscribed", on_track_subscribed)
|
|
863
|
+
|
|
864
|
+
def _has_remote_video_track(self) -> bool:
|
|
865
|
+
if self._room is None:
|
|
866
|
+
return False
|
|
867
|
+
participant = self._room.remote_participants.get(self.avatar_participant_identity)
|
|
868
|
+
if participant is None:
|
|
869
|
+
return False
|
|
870
|
+
return any(
|
|
871
|
+
publication.track and publication.track.kind == rtc.TrackKind.KIND_VIDEO
|
|
872
|
+
for publication in participant.track_publications.values()
|
|
873
|
+
)
|
|
874
|
+
|
|
875
|
+
def _schedule_control(self, coroutine, name: str) -> None:
|
|
876
|
+
task = asyncio.create_task(coroutine, name=name)
|
|
877
|
+
self._control_tasks.add(task)
|
|
878
|
+
task.add_done_callback(self._control_task_done)
|
|
879
|
+
|
|
880
|
+
def _control_task_done(self, task: asyncio.Task) -> None:
|
|
881
|
+
self._control_tasks.discard(task)
|
|
882
|
+
if task.cancelled():
|
|
883
|
+
return
|
|
884
|
+
error = task.exception()
|
|
885
|
+
if error is None or self._stopped:
|
|
886
|
+
return
|
|
887
|
+
if self._reconnecting() or self._start_reconnect() is not None:
|
|
888
|
+
logger.warning(
|
|
889
|
+
"FaceMode control message failed during reconnect: %s", error
|
|
890
|
+
)
|
|
891
|
+
return
|
|
892
|
+
protocol_error = (
|
|
893
|
+
error
|
|
894
|
+
if isinstance(error, FaceModeProtocolError)
|
|
895
|
+
else FaceModeProtocolError(
|
|
896
|
+
f"FaceMode control message failed: {error.__class__.__name__}"
|
|
897
|
+
)
|
|
898
|
+
)
|
|
899
|
+
self._set_protocol_error(protocol_error)
|
|
900
|
+
logger.warning("%s", protocol_error)
|
|
901
|
+
|
|
902
|
+
async def _drain_control_tasks(self) -> None:
|
|
903
|
+
tasks = tuple(self._control_tasks)
|
|
904
|
+
if tasks:
|
|
905
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
906
|
+
self._raise_protocol_error()
|
|
907
|
+
|
|
908
|
+
async def _cancel_task(self, task: asyncio.Task | None) -> None:
|
|
909
|
+
if task is None or task is asyncio.current_task():
|
|
910
|
+
return
|
|
911
|
+
if not task.done():
|
|
912
|
+
task.cancel()
|
|
913
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
914
|
+
await task
|
|
915
|
+
|
|
916
|
+
def _set_protocol_error(self, error: FaceModeError) -> None:
|
|
917
|
+
if self._protocol_error is None:
|
|
918
|
+
self._protocol_error = error
|
|
919
|
+
self._protocol_response.set()
|
|
920
|
+
|
|
921
|
+
def _raise_protocol_error(self) -> None:
|
|
922
|
+
if self._protocol_error is not None:
|
|
923
|
+
raise self._protocol_error
|
|
924
|
+
|
|
925
|
+
def _next_sequence(self) -> int:
|
|
926
|
+
sequence = self._sequence
|
|
927
|
+
self._sequence += 1
|
|
928
|
+
return sequence
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def _token_identity_hint(token: str) -> str | None:
|
|
932
|
+
claims = _token_claims_hint(token)
|
|
933
|
+
identity = claims.get("sub") if claims else None
|
|
934
|
+
return identity if isinstance(identity, str) and identity else None
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _token_room_hint(token: str) -> str:
|
|
938
|
+
claims = _token_claims_hint(token)
|
|
939
|
+
video = claims.get("video") if claims else None
|
|
940
|
+
room = video.get("room") if isinstance(video, Mapping) else None
|
|
941
|
+
return room if isinstance(room, str) and room else ""
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def _token_claims_hint(token: str) -> Mapping[str, Any] | None:
|
|
945
|
+
try:
|
|
946
|
+
payload = token.split(".")[1]
|
|
947
|
+
padding = "=" * (-len(payload) % 4)
|
|
948
|
+
claims = json.loads(base64.urlsafe_b64decode(payload + padding))
|
|
949
|
+
except (IndexError, ValueError, TypeError, json.JSONDecodeError):
|
|
950
|
+
return None
|
|
951
|
+
return claims if isinstance(claims, Mapping) else None
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
def _sanitize_session_marker(session_id: str) -> str:
|
|
955
|
+
return "".join(
|
|
956
|
+
char if char.isascii() and (char.isalnum() or char in "_-") else "_"
|
|
957
|
+
for char in session_id
|
|
958
|
+
)[:96]
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def _websocket_close_details(value: Any) -> str:
|
|
962
|
+
if value is None:
|
|
963
|
+
return " (code=unknown)"
|
|
964
|
+
received = getattr(value, "rcvd", None)
|
|
965
|
+
code = getattr(value, "close_code", None) or getattr(value, "code", None)
|
|
966
|
+
reason = getattr(value, "close_reason", None) or getattr(value, "reason", None)
|
|
967
|
+
if received is not None:
|
|
968
|
+
code = code or getattr(received, "code", None)
|
|
969
|
+
reason = reason or getattr(received, "reason", None)
|
|
970
|
+
reason_text = str(reason or "").strip()[:160]
|
|
971
|
+
suffix = f", reason={reason_text}" if reason_text else ""
|
|
972
|
+
return f" (code={code if code is not None else 'unknown'}{suffix})"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""FaceMode LiveKit plugin exceptions."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class FaceModeError(RuntimeError):
|
|
5
|
+
"""Base error for FaceMode integration failures."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FaceModeAPIError(FaceModeError):
|
|
9
|
+
"""Raised when the FaceMode REST API rejects a request."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FaceModeProtocolError(FaceModeError):
|
|
13
|
+
"""Raised when the FaceMode WebSocket reports a protocol error."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FaceModeNotReadyError(FaceModeError):
|
|
17
|
+
"""Raised when the avatar does not publish its video track in time."""
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Typed FaceMode API request and response models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
SUPPORTED_INPUT_PROVIDERS = frozenset(
|
|
10
|
+
{
|
|
11
|
+
"deepgram",
|
|
12
|
+
"gemini",
|
|
13
|
+
"gnani",
|
|
14
|
+
"elevenlabs",
|
|
15
|
+
"openai",
|
|
16
|
+
"cartesia",
|
|
17
|
+
"sarvam",
|
|
18
|
+
"custom",
|
|
19
|
+
}
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class LiveKitRoom:
|
|
25
|
+
"""Credentials for a customer-owned LiveKit room."""
|
|
26
|
+
|
|
27
|
+
url: str
|
|
28
|
+
token: str = field(repr=False)
|
|
29
|
+
name: str = ""
|
|
30
|
+
type: Literal["livekit"] = field(default="livekit", kw_only=True)
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
if self.type != "livekit":
|
|
34
|
+
raise ValueError("room.type must be 'livekit'")
|
|
35
|
+
if not self.url:
|
|
36
|
+
raise ValueError("room.url is required")
|
|
37
|
+
if not self.token:
|
|
38
|
+
raise ValueError("room.token is required")
|
|
39
|
+
|
|
40
|
+
def to_payload(self) -> dict[str, str]:
|
|
41
|
+
"""Return the API representation without exposing credentials in reprs."""
|
|
42
|
+
payload = {"type": self.type, "url": self.url, "token": self.token}
|
|
43
|
+
if self.name:
|
|
44
|
+
payload["name"] = self.name
|
|
45
|
+
return payload
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_value(cls, value: "LiveKitRoom | Mapping[str, Any]") -> "LiveKitRoom":
|
|
49
|
+
"""Normalize a typed room or mapping supplied by an integration caller."""
|
|
50
|
+
if isinstance(value, cls):
|
|
51
|
+
return value
|
|
52
|
+
if not isinstance(value, Mapping):
|
|
53
|
+
raise ValueError("room must be an object")
|
|
54
|
+
room_type = value.get("type")
|
|
55
|
+
if room_type != "livekit":
|
|
56
|
+
raise ValueError("room.type must be 'livekit'")
|
|
57
|
+
url = value.get("url")
|
|
58
|
+
token = value.get("token")
|
|
59
|
+
name = value.get("name", "")
|
|
60
|
+
if not isinstance(url, str) or not url:
|
|
61
|
+
raise ValueError("room.url is required")
|
|
62
|
+
if not isinstance(token, str) or not token:
|
|
63
|
+
raise ValueError("room.token is required")
|
|
64
|
+
if not isinstance(name, str):
|
|
65
|
+
raise ValueError("room.name must be a string")
|
|
66
|
+
return cls(url=url, token=token, name=name)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True)
|
|
70
|
+
class SessionRequest:
|
|
71
|
+
"""Request body used to create a FaceMode session."""
|
|
72
|
+
|
|
73
|
+
avatar_id: str
|
|
74
|
+
room: LiveKitRoom
|
|
75
|
+
room_name: str = ""
|
|
76
|
+
input_provider: str | None = None
|
|
77
|
+
|
|
78
|
+
def __post_init__(self) -> None:
|
|
79
|
+
if (
|
|
80
|
+
self.input_provider is not None
|
|
81
|
+
and self.input_provider not in SUPPORTED_INPUT_PROVIDERS
|
|
82
|
+
):
|
|
83
|
+
raise ValueError(
|
|
84
|
+
"input_provider must be one of: "
|
|
85
|
+
+ ", ".join(sorted(SUPPORTED_INPUT_PROVIDERS))
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def to_payload(self) -> dict[str, Any]:
|
|
89
|
+
"""Return the room-object API wire representation."""
|
|
90
|
+
payload: dict[str, Any] = {
|
|
91
|
+
"avatarId": self.avatar_id,
|
|
92
|
+
"room": self.room.to_payload(),
|
|
93
|
+
}
|
|
94
|
+
if self.room_name:
|
|
95
|
+
payload["livekit_room_id"] = self.room_name
|
|
96
|
+
if self.input_provider:
|
|
97
|
+
payload["inputProvider"] = self.input_provider
|
|
98
|
+
return payload
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True, slots=True)
|
|
102
|
+
class IngestionDetails:
|
|
103
|
+
ready: bool
|
|
104
|
+
url: str = ""
|
|
105
|
+
ws_token: str = field(default="", repr=False)
|
|
106
|
+
authority: str | None = None
|
|
107
|
+
headers: Mapping[str, str] = field(default_factory=dict, repr=False)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True, slots=True)
|
|
111
|
+
class SessionDetails:
|
|
112
|
+
session_id: str
|
|
113
|
+
room_name: str
|
|
114
|
+
room: LiveKitRoom
|
|
115
|
+
ingestion: IngestionDetails
|
|
116
|
+
worker_status: str | None = None
|
|
117
|
+
avatar_participant_identity: str | None = None
|
|
118
|
+
input_provider: str | None = None
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def from_api(
|
|
122
|
+
cls,
|
|
123
|
+
payload: Mapping[str, Any],
|
|
124
|
+
*,
|
|
125
|
+
fallback: "SessionDetails | None" = None,
|
|
126
|
+
) -> "SessionDetails":
|
|
127
|
+
"""Parse current and legacy response envelopes, including pending ingestion."""
|
|
128
|
+
root: Mapping[str, Any] = payload
|
|
129
|
+
nested = payload.get("data")
|
|
130
|
+
if isinstance(nested, Mapping):
|
|
131
|
+
root = nested
|
|
132
|
+
|
|
133
|
+
session_value = root.get("session")
|
|
134
|
+
session = session_value if isinstance(session_value, Mapping) else {}
|
|
135
|
+
ingestion_value = root.get("ingestion") or session.get("ingestion")
|
|
136
|
+
ingestion = ingestion_value if isinstance(ingestion_value, Mapping) else {}
|
|
137
|
+
|
|
138
|
+
session_id = _first_text(
|
|
139
|
+
session.get("id"),
|
|
140
|
+
session.get("sessionId"),
|
|
141
|
+
root.get("sessionId"),
|
|
142
|
+
root.get("id"),
|
|
143
|
+
root.get("jobId"),
|
|
144
|
+
)
|
|
145
|
+
if not session_id:
|
|
146
|
+
raise ValueError("FaceMode session response is missing a session ID")
|
|
147
|
+
|
|
148
|
+
ingestion_url = _first_text(
|
|
149
|
+
ingestion.get("url"),
|
|
150
|
+
ingestion.get("websocketUrl"),
|
|
151
|
+
root.get("websocketUrl"),
|
|
152
|
+
root.get("websocket_url"),
|
|
153
|
+
)
|
|
154
|
+
ws_token = _first_text(
|
|
155
|
+
ingestion.get("wsToken"),
|
|
156
|
+
ingestion.get("ws_token"),
|
|
157
|
+
ingestion.get("token"),
|
|
158
|
+
root.get("ingestionToken"),
|
|
159
|
+
root.get("ingestion_token"),
|
|
160
|
+
)
|
|
161
|
+
ready = ingestion.get("ready") is True or (
|
|
162
|
+
"ready" not in ingestion and bool(ingestion_url and ws_token)
|
|
163
|
+
)
|
|
164
|
+
if ready and (not ingestion_url or not ws_token):
|
|
165
|
+
raise ValueError("FaceMode reported ready ingestion without WebSocket credentials")
|
|
166
|
+
|
|
167
|
+
return cls(
|
|
168
|
+
session_id=session_id,
|
|
169
|
+
room_name=_first_text(
|
|
170
|
+
root.get("roomName"),
|
|
171
|
+
session.get("roomName"),
|
|
172
|
+
fallback.room_name if fallback else "",
|
|
173
|
+
),
|
|
174
|
+
room=_parse_room(root, session, fallback.room if fallback else None),
|
|
175
|
+
ingestion=IngestionDetails(
|
|
176
|
+
ready=ready,
|
|
177
|
+
url=ingestion_url,
|
|
178
|
+
ws_token=ws_token,
|
|
179
|
+
authority=_first_optional_text(ingestion.get("authority")),
|
|
180
|
+
headers=_parse_headers(ingestion.get("headers")),
|
|
181
|
+
),
|
|
182
|
+
worker_status=_first_optional_text(
|
|
183
|
+
root.get("workerStatus"),
|
|
184
|
+
root.get("worker_status"),
|
|
185
|
+
session.get("workerStatus"),
|
|
186
|
+
session.get("worker_status"),
|
|
187
|
+
),
|
|
188
|
+
avatar_participant_identity=_first_optional_text(
|
|
189
|
+
root.get("avatarParticipantIdentity"),
|
|
190
|
+
root.get("avatar_participant_identity"),
|
|
191
|
+
session.get("avatarParticipantIdentity"),
|
|
192
|
+
session.get("avatar_participant_identity"),
|
|
193
|
+
),
|
|
194
|
+
input_provider=_first_optional_text(
|
|
195
|
+
root.get("inputProvider"),
|
|
196
|
+
root.get("input_provider"),
|
|
197
|
+
session.get("inputProvider"),
|
|
198
|
+
session.get("input_provider"),
|
|
199
|
+
),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _parse_room(
|
|
204
|
+
root: Mapping[str, Any],
|
|
205
|
+
session: Mapping[str, Any],
|
|
206
|
+
fallback: LiveKitRoom | None,
|
|
207
|
+
) -> LiveKitRoom:
|
|
208
|
+
room_value = root.get("room") or session.get("room")
|
|
209
|
+
if isinstance(room_value, Mapping):
|
|
210
|
+
try:
|
|
211
|
+
return LiveKitRoom.from_value(room_value)
|
|
212
|
+
except ValueError:
|
|
213
|
+
if fallback is None:
|
|
214
|
+
raise
|
|
215
|
+
if fallback is not None:
|
|
216
|
+
return fallback
|
|
217
|
+
raise ValueError("FaceMode session response is missing a LiveKit room")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _parse_headers(value: Any) -> Mapping[str, str]:
|
|
221
|
+
if not isinstance(value, Mapping):
|
|
222
|
+
return {}
|
|
223
|
+
return {
|
|
224
|
+
str(name): header_value
|
|
225
|
+
for name, header_value in value.items()
|
|
226
|
+
if str(name) and isinstance(header_value, str)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _first_text(*values: Any) -> str:
|
|
231
|
+
"""Return the first non-empty value as text."""
|
|
232
|
+
for value in values:
|
|
233
|
+
if value is not None and str(value):
|
|
234
|
+
return str(value)
|
|
235
|
+
return ""
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _first_optional_text(*values: Any) -> str | None:
|
|
239
|
+
value = _first_text(*values)
|
|
240
|
+
return value or None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: livekit-plugins-facemode
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: FaceMode avatar integration for LiveKit Agents
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Requires-Python: >=3.13
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: aiohttp<4,>=3.10
|
|
10
|
+
Requires-Dist: livekit<2,>=1.1
|
|
11
|
+
Requires-Dist: livekit-agents<2,>=1.7
|
|
12
|
+
Requires-Dist: websockets<17,>=14
|
|
13
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
livekit_plugins_facemode/__init__.py,sha256=oCdtbDOEtAFfg7is8wgPIE9gSu3i-tOJGfDpnsieTRI,513
|
|
2
|
+
livekit_plugins_facemode/avatar.py,sha256=HwiPgm-ajkxZD9Wp6tsH6MRgSBltsPyp1oeBRXK-L_8,42322
|
|
3
|
+
livekit_plugins_facemode/exceptions.py,sha256=sIwc7imKlkm2gbY-yN52L0rRkSJAw1Wwmc7qQ-woAQw,494
|
|
4
|
+
livekit_plugins_facemode/models.py,sha256=nYu8w4u2C8ntRETlW7DYMqrTjiVB3ZRZWF4kcJh9-YQ,8180
|
|
5
|
+
livekit_plugins_facemode/version.py,sha256=QTYqXqSTHFRkM9TEgpDFcHvwLbvqHDqvqfQ9EiXkcAM,23
|
|
6
|
+
livekit_plugins_facemode-0.1.0.dist-info/licenses/LICENSE,sha256=PyobLPD0zR1SjN0Wky83vE67dOghwezK600Wj3lIR_A,590
|
|
7
|
+
livekit_plugins_facemode-0.1.0.dist-info/METADATA,sha256=gJqjWFCOpGRczSnR8PSlVJ8Z7nyMvFcvE-B1aFlNq-Q,419
|
|
8
|
+
livekit_plugins_facemode-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
9
|
+
livekit_plugins_facemode-0.1.0.dist-info/top_level.txt,sha256=HCiHfx7ZdAqBvkxF346Ri1dRr3PRSBDlnyQK25kaR8U,25
|
|
10
|
+
livekit_plugins_facemode-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright © 2026 InfinityLevel OPC Private Limited
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
livekit_plugins_facemode
|