""" Helper functions for realtime session management """ import base64 from typing import Optional from datetime import datetime import sys import traceback from logger import log_info, log_error, log_debug, log_warning 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: log_info(f"🎙️ Generating welcome TTS for: '{text[:50]}...'", session_id=session_id) # Generate TTS audio_data = await tts_provider.synthesize(text) log_info(f"✅ Welcome TTS generated: {len(audio_data)} bytes", session_id=session_id) # Convert to base64 log_debug(f"📦 Converting welcome audio to base64...") audio_base64 = base64.b64encode(audio_data).decode('utf-8') log_info(f"📊 Welcome base64 ready: {len(audio_base64)} chars", session_id=session_id) # Log preview log_debug(f"🔍 Welcome base64 preview: {audio_base64[:100]}...") # Send in chunks chunk_size = 16384 total_length = len(audio_base64) total_chunks = (total_length + chunk_size - 1) // chunk_size log_info(f"📤 Sending welcome TTS in {total_chunks} chunks", session_id=session_id) for i in range(0, total_length, chunk_size): chunk = audio_base64[i:i + chunk_size] chunk_index = i // chunk_size is_last = chunk_index == total_chunks - 1 log_debug(f"📨 Welcome chunk {chunk_index}/{total_chunks}, size: {len(chunk)}") await websocket.send_json({ "type": "tts_audio", "data": chunk, "chunk_index": chunk_index, "total_chunks": total_chunks, "is_last": is_last, "mime_type": "audio/mpeg" }) log_info(f"✅ Welcome message TTS sent successfully", session_id=session_id, chunks=total_chunks) except Exception as e: log_error( f"❌ Failed to send welcome TTS", error=str(e), traceback=traceback.format_exc(), session_id=session_id )