Spaces:
Running
Running
Create realtime_session_manager.py
Browse files- realtime_session_manager.py +47 -0
realtime_session_manager.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Helper functions for realtime session management
|
3 |
+
"""
|
4 |
+
import base64
|
5 |
+
from typing import Optional
|
6 |
+
from datetime import datetime
|
7 |
+
import sys
|
8 |
+
|
9 |
+
from logger import log_info, log_error, log_debug
|
10 |
+
|
11 |
+
def log(message: str):
|
12 |
+
"""Log helper with timestamp"""
|
13 |
+
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
|
14 |
+
print(f"[{timestamp}] {message}")
|
15 |
+
sys.stdout.flush()
|
16 |
+
|
17 |
+
async def send_tts_welcome_message(websocket, session_id: str, tts_provider, text: str):
|
18 |
+
"""Send welcome message TTS audio"""
|
19 |
+
try:
|
20 |
+
# Generate TTS
|
21 |
+
audio_data = await tts_provider.synthesize(text)
|
22 |
+
|
23 |
+
# Convert to base64
|
24 |
+
audio_base64 = base64.b64encode(audio_data).decode('utf-8')
|
25 |
+
|
26 |
+
# Send in chunks
|
27 |
+
chunk_size = 16384
|
28 |
+
total_length = len(audio_base64)
|
29 |
+
total_chunks = (total_length + chunk_size - 1) // chunk_size
|
30 |
+
|
31 |
+
for i in range(0, total_length, chunk_size):
|
32 |
+
chunk = audio_base64[i:i + chunk_size]
|
33 |
+
chunk_index = i // chunk_size
|
34 |
+
|
35 |
+
await websocket.send_json({
|
36 |
+
"type": "tts_audio",
|
37 |
+
"data": chunk,
|
38 |
+
"chunk_index": chunk_index,
|
39 |
+
"total_chunks": total_chunks,
|
40 |
+
"is_last": chunk_index == total_chunks - 1,
|
41 |
+
"mime_type": "audio/mpeg"
|
42 |
+
})
|
43 |
+
|
44 |
+
log_info(f"✅ Welcome message TTS sent", session_id=session_id)
|
45 |
+
|
46 |
+
except Exception as e:
|
47 |
+
log_error(f"Failed to send welcome TTS", error=str(e), session_id=session_id)
|