-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.py
More file actions
404 lines (340 loc) · 14 KB
/
client.py
File metadata and controls
404 lines (340 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
from typing import Callable, Optional, Union
import asyncio
import base64
import logging
from pathlib import Path
from urllib.parse import urlparse, quote
import aiohttp
from aiortc import MediaStreamTrack
from pydantic import BaseModel
from .audio_stream_manager import AudioStreamManager
from .webrtc_manager import WebRTCManager, WebRTCConfiguration
from .messages import PromptMessage, SessionIdMessage, GenerationTickMessage
from .subscribe import (
SubscribeClient,
SubscribeOptions,
encode_subscribe_token,
decode_subscribe_token,
)
from .types import ConnectionState, RealtimeConnectOptions
from ..types import FileInput
from ..models import RealTimeModels
from ..errors import DecartSDKError, InvalidInputError, WebRTCError
from ..process.request import file_input_to_bytes
logger = logging.getLogger(__name__)
PROMPT_TIMEOUT_S = 15.0
UPDATE_TIMEOUT_S = 30.0
class SetInput(BaseModel):
prompt: Optional[str] = None
enhance: bool = True
image: Optional[Union[bytes, str]] = None
async def _image_to_base64(
image: Union[bytes, str, Path],
http_session: aiohttp.ClientSession,
) -> str:
if isinstance(image, Path):
image_bytes, _ = await file_input_to_bytes(image, http_session)
return base64.b64encode(image_bytes).decode("utf-8")
if isinstance(image, bytes):
return base64.b64encode(image).decode("utf-8")
if isinstance(image, str):
parsed = urlparse(image)
if parsed.scheme == "data":
return image.split(",", 1)[1]
if parsed.scheme in ("http", "https"):
async with http_session.get(image) as resp:
resp.raise_for_status()
data = await resp.read()
return base64.b64encode(data).decode("utf-8")
if Path(image).exists():
image_bytes, _ = await file_input_to_bytes(image, http_session)
return base64.b64encode(image_bytes).decode("utf-8")
# Non-URL, non-file string — treat as raw base64 (matches TS SDK behavior)
return image
class RealtimeClient:
def __init__(
self,
manager: WebRTCManager,
http_session: Optional[aiohttp.ClientSession] = None,
model_name: Optional[str] = None,
):
self._manager = manager
self._http_session = http_session
self._model_name = model_name
self._audio_stream_manager: Optional[AudioStreamManager] = None
self._connection_callbacks: list[Callable[[ConnectionState], None]] = []
self._error_callbacks: list[Callable[[DecartSDKError], None]] = []
self._generation_tick_callbacks: list[Callable[[GenerationTickMessage], None]] = []
self._session_id: Optional[str] = None
self._subscribe_token: Optional[str] = None
self._buffering = True
self._buffer: list[tuple[str, object]] = []
@property
def session_id(self) -> Optional[str]:
return self._session_id
@property
def subscribe_token(self) -> Optional[str]:
return self._subscribe_token
def _handle_session_id(self, msg: SessionIdMessage) -> None:
self._session_id = msg.session_id
self._subscribe_token = encode_subscribe_token(
msg.session_id, msg.server_ip, msg.server_port
)
@classmethod
async def connect(
cls,
base_url: str,
api_key: str,
local_track: Optional[MediaStreamTrack],
options: RealtimeConnectOptions,
integration: Optional[str] = None,
) -> "RealtimeClient":
ws_url = f"{base_url}{options.model.url_path}"
ws_url += f"?api_key={quote(api_key)}&model={quote(options.model.name)}"
model_name: RealTimeModels = options.model.name # type: ignore[assignment]
is_avatar_live = model_name == "live_avatar"
audio_stream_manager: Optional[AudioStreamManager] = None
if is_avatar_live and local_track is None:
audio_stream_manager = AudioStreamManager()
local_track = audio_stream_manager.get_track()
config = WebRTCConfiguration(
webrtc_url=ws_url,
api_key=api_key,
session_id="",
fps=options.model.fps,
on_remote_stream=options.on_remote_stream,
on_connection_state_change=None,
on_error=None,
on_session_id=None,
initial_state=options.initial_state,
customize_offer=options.customize_offer,
integration=integration,
model_name=model_name,
)
http_session = aiohttp.ClientSession()
manager = WebRTCManager(config)
client = cls(
manager=manager,
http_session=http_session,
model_name=model_name,
)
client._audio_stream_manager = audio_stream_manager
config.on_connection_state_change = client._emit_connection_change
config.on_error = lambda error: client._emit_error(WebRTCError(str(error), cause=error))
config.on_session_id = client._handle_session_id
config.on_generation_tick = client._emit_generation_tick
try:
initial_image: Optional[str] = None
if options.initial_state and options.initial_state.image:
initial_image = await _image_to_base64(options.initial_state.image, http_session)
initial_prompt: Optional[dict] = None
if options.initial_state and options.initial_state.prompt:
initial_prompt = {
"text": options.initial_state.prompt.text,
"enhance": options.initial_state.prompt.enhance,
}
await manager.connect(
local_track,
initial_image=initial_image,
initial_prompt=initial_prompt,
)
except Exception as e:
if audio_stream_manager:
audio_stream_manager.cleanup()
await manager.cleanup()
await http_session.close()
raise WebRTCError(str(e), cause=e)
client._flush()
return client
@classmethod
async def subscribe(
cls,
base_url: str,
api_key: str,
options: SubscribeOptions,
integration: Optional[str] = None,
) -> SubscribeClient:
token_data = decode_subscribe_token(options.token)
subscribe_url = (
f"{base_url}/subscribe/{quote(token_data.sid)}"
f"?IP={quote(token_data.ip)}"
f"&port={quote(str(token_data.port))}"
f"&api_key={quote(api_key)}"
)
config = WebRTCConfiguration(
webrtc_url=subscribe_url,
api_key=api_key,
session_id=token_data.sid,
fps=0,
on_remote_stream=options.on_remote_stream,
on_connection_state_change=None,
on_error=None,
integration=integration,
)
manager = WebRTCManager(config)
sub_client = SubscribeClient(manager)
config.on_connection_state_change = sub_client._emit_connection_change
config.on_error = sub_client._emit_error
try:
await manager.connect(None)
except Exception as e:
await manager.cleanup()
raise WebRTCError(str(e), cause=e)
sub_client._flush()
return sub_client
def _flush(self) -> None:
# Defer to next tick so caller can register handlers before buffered events fire
asyncio.get_running_loop().call_soon(self._do_flush)
def _do_flush(self) -> None:
self._buffering = False
for event, data in self._buffer:
if event == "connection_change":
self._dispatch_connection_change(data) # type: ignore[arg-type]
elif event == "error":
self._dispatch_error(data) # type: ignore[arg-type]
elif event == "generation_tick":
self._dispatch_generation_tick(data) # type: ignore[arg-type]
self._buffer.clear()
def _dispatch_connection_change(self, state: ConnectionState) -> None:
for callback in list(self._connection_callbacks):
try:
callback(state)
except Exception as e:
logger.exception(f"Error in connection_change callback: {e}")
def _dispatch_error(self, error: DecartSDKError) -> None:
for callback in list(self._error_callbacks):
try:
callback(error)
except Exception as e:
logger.exception(f"Error in error callback: {e}")
def _emit_connection_change(self, state: ConnectionState) -> None:
if self._buffering:
self._buffer.append(("connection_change", state))
else:
self._dispatch_connection_change(state)
def _emit_error(self, error: DecartSDKError) -> None:
if self._buffering:
self._buffer.append(("error", error))
else:
self._dispatch_error(error)
def _dispatch_generation_tick(self, message: GenerationTickMessage) -> None:
for callback in list(self._generation_tick_callbacks):
try:
callback(message)
except Exception as e:
logger.exception(f"Error in generation_tick callback: {e}")
def _emit_generation_tick(self, message: GenerationTickMessage) -> None:
if self._buffering:
self._buffer.append(("generation_tick", message))
else:
self._dispatch_generation_tick(message)
async def set(self, input: SetInput) -> None:
if input.prompt is None and input.image is None:
raise InvalidInputError("At least one of 'prompt' or 'image' must be provided")
if input.prompt is not None and not input.prompt.strip():
raise InvalidInputError("Prompt cannot be empty")
image_base64: Optional[str] = None
if input.image is not None:
if not self._http_session:
raise InvalidInputError("HTTP session not available")
image_base64 = await _image_to_base64(input.image, self._http_session)
await self._manager.set_image(
image_base64,
{
"prompt": input.prompt,
"enhance": input.enhance,
"timeout": UPDATE_TIMEOUT_S,
},
)
async def set_prompt(
self,
prompt: str,
enhance: bool = True,
enrich: Optional[bool] = None,
) -> None:
if enrich is not None:
import warnings
warnings.warn(
"set_prompt(enrich=...) is deprecated, use set_prompt(enhance=...) instead",
DeprecationWarning,
stacklevel=2,
)
enhance = enrich
if not prompt or not prompt.strip():
raise InvalidInputError("Prompt cannot be empty")
event, result = self._manager.register_prompt_wait(prompt)
try:
await self._manager.send_message(
PromptMessage(type="prompt", prompt=prompt, enhance_prompt=enhance)
)
try:
await asyncio.wait_for(event.wait(), timeout=PROMPT_TIMEOUT_S)
except asyncio.TimeoutError:
raise DecartSDKError("Prompt acknowledgment timed out")
if not result["success"]:
raise DecartSDKError(result["error"] or "Prompt failed")
finally:
self._manager.unregister_prompt_wait(prompt)
async def play_audio(self, audio: Union[bytes, str, Path]) -> None:
"""Play audio through the avatar stream. Resolves when audio finishes.
Only available for live_avatar connections without a user-provided audio track.
"""
if self._audio_stream_manager is None:
raise InvalidInputError(
"play_audio() is only available for live_avatar without a user-provided audio track"
)
await self._audio_stream_manager.play_audio(audio)
async def set_image(
self,
image: Optional[FileInput],
prompt: Optional[str] = None,
enhance: bool = True,
timeout: float = UPDATE_TIMEOUT_S,
) -> None:
image_base64: Optional[str] = None
if image is not None:
if not self._http_session:
raise InvalidInputError("HTTP session not available")
image_bytes, _ = await file_input_to_bytes(image, self._http_session)
image_base64 = base64.b64encode(image_bytes).decode("utf-8")
opts: dict = {"timeout": timeout}
if prompt is not None:
opts["prompt"] = prompt
opts["enhance"] = enhance
await self._manager.set_image(image_base64, opts)
def is_connected(self) -> bool:
return self._manager.is_connected()
def get_connection_state(self) -> ConnectionState:
return self._manager.get_connection_state()
async def disconnect(self) -> None:
self._buffering = False
self._buffer.clear()
if self._audio_stream_manager:
self._audio_stream_manager.cleanup()
self._audio_stream_manager = None
await self._manager.cleanup()
if self._http_session and not self._http_session.closed:
await self._http_session.close()
def on(self, event: str, callback: Callable) -> None:
if event == "connection_change":
self._connection_callbacks.append(callback)
elif event == "error":
self._error_callbacks.append(callback)
elif event == "generation_tick":
self._generation_tick_callbacks.append(callback)
def off(self, event: str, callback: Callable) -> None:
if event == "connection_change":
try:
self._connection_callbacks.remove(callback)
except ValueError:
pass
elif event == "error":
try:
self._error_callbacks.remove(callback)
except ValueError:
pass
elif event == "generation_tick":
try:
self._generation_tick_callbacks.remove(callback)
except ValueError:
pass