Spaces:
Running
Running
""" | |
Helper functions for realtime session management | |
""" | |
import base64 | |
from typing import Optional | |
from datetime import datetime | |
import sys | |
from logger import log_info, log_error, log_debug | |
def log(message: str): | |
"""Log helper with timestamp""" | |
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3] | |
print(f"[{timestamp}] {message}") | |
sys.stdout.flush() | |
async def send_tts_welcome_message(websocket, session_id: str, tts_provider, text: str): | |
"""Send welcome message TTS audio""" | |
try: | |
# Generate TTS | |
audio_data = await tts_provider.synthesize(text) | |
# Convert to base64 | |
audio_base64 = base64.b64encode(audio_data).decode('utf-8') | |
# Send in chunks | |
chunk_size = 16384 | |
total_length = len(audio_base64) | |
total_chunks = (total_length + chunk_size - 1) // chunk_size | |
for i in range(0, total_length, chunk_size): | |
chunk = audio_base64[i:i + chunk_size] | |
chunk_index = i // chunk_size | |
await websocket.send_json({ | |
"type": "tts_audio", | |
"data": chunk, | |
"chunk_index": chunk_index, | |
"total_chunks": total_chunks, | |
"is_last": chunk_index == total_chunks - 1, | |
"mime_type": "audio/mpeg" | |
}) | |
log_info(f"β Welcome message TTS sent", session_id=session_id) | |
except Exception as e: | |
log_error(f"Failed to send welcome TTS", error=str(e), session_id=session_id) |