fixed CDN and VAD Timeout

This commit is contained in:
karthikeyareddy183 2025-08-30 12:26:50 +05:30
parent 8f303e594c
commit 9d352e4d61
67 changed files with 3860 additions and 137 deletions

View file

@ -19,9 +19,9 @@ import opuslib
# --- Configuration ---
SERVER_IP = "139.59.7.72" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8002
MQTT_BROKER_HOST = "139.59.7.72" # MQTT gateway IP
SERVER_IP = "192.168.1.179" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8003
MQTT_BROKER_HOST = "192.168.1.179" # MQTT gateway IP
MQTT_BROKER_PORT = 1883

View file

@ -0,0 +1,98 @@
"""
CDN Handler for Audio Streaming
Provides API endpoints to test and use CDN functionality
"""
import json
from aiohttp import web
from config.logger import setup_logging
TAG = __name__
class CDNHandler:
def __init__(self, config: dict):
self.config = config
self.logger = setup_logging()
async def handle_get(self, request):
"""Handle GET requests for CDN status and testing"""
try:
# Import CDN helper
from utils.cdn_helper import cdn, get_audio_url, is_cdn_ready
# Get CDN status
status = cdn.get_status()
# Add some test URLs
test_files = [
"stories/Fantasy/goldilocks and the three bears.mp3",
"stories/Educational/twinkle twinkle little star song.mp3",
"stories/Fairy Tales/the boy who cried wolf.mp3"
]
test_urls = {}
for file in test_files:
test_urls[file] = get_audio_url(file)
response_data = {
"cdn_status": status,
"cdn_ready": is_cdn_ready(),
"test_urls": test_urls,
"message": "CDN is working correctly!" if is_cdn_ready() else "CDN not configured"
}
return web.json_response(response_data)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Error in CDN handler GET: {e}")
return web.json_response(
{"error": str(e), "message": "CDN handler error"},
status=500
)
async def handle_post(self, request):
"""Handle POST requests for CDN URL generation"""
try:
# Parse request body
data = await request.json()
audio_file = data.get('audio_file', '')
if not audio_file:
return web.json_response(
{"error": "audio_file parameter required"},
status=400
)
# Import CDN helper
from utils.cdn_helper import get_audio_url, get_cache_headers, is_cdn_ready
# Generate CDN URL
cdn_url = get_audio_url(audio_file)
cache_headers = get_cache_headers()
response_data = {
"audio_file": audio_file,
"cdn_url": cdn_url,
"cache_headers": cache_headers,
"cdn_ready": is_cdn_ready(),
"message": "CDN URL generated successfully"
}
return web.json_response(response_data)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Error in CDN handler POST: {e}")
return web.json_response(
{"error": str(e), "message": "CDN URL generation failed"},
status=500
)
async def handle_options(self, request):
"""Handle OPTIONS requests for CORS"""
return web.Response(
headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
}
)

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,204 @@
# from core.handle.sendAudioHandle import send_stt_message
# from core.handle.intentHandler import handle_user_intent
# from core.utils.output_counter import check_device_output_limit
# from core.handle.abortHandle import handleAbortMessage
# import time
# import asyncio
# import json
# from core.handle.sendAudioHandle import SentenceType
# from core.utils.util import audio_to_data
# TAG = __name__
# async def handleAudioMessage(conn, audio):
# # Log that we received audio (only log periodically to avoid spam)
# if not hasattr(conn, '_audio_log_counter'):
# conn._audio_log_counter = 0
# conn._audio_log_counter += 1
# if conn._audio_log_counter % 200 == 0: # Log every 200th packet (reduced from 50)
# conn.logger.bind(tag=TAG).debug(f"Received audio packet #{conn._audio_log_counter}, size: {len(audio)} bytes")
# # Skip VAD/ASR processing when server is speaking (streaming audio to client)
# # This prevents interruptions during TTS playback
# if conn.client_is_speaking:
# # conn.logger.bind(tag=TAG).debug("Server is speaking - skipping audio processing to prevent interruption")
# return
# # Whether the current segment has someone speaking
# have_voice = conn.vad.is_vad(conn, audio)
# # Track when voice recording starts in auto VAD mode (for 10-second timeout)
# if have_voice and not hasattr(conn, 'vad_recording_start_time'):
# conn.vad_recording_start_time = time.time()
# conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
# elif have_voice and hasattr(conn, 'vad_recording_start_time'):
# conn.logger.bind(tag=TAG).debug(f"VAD recording continues, started at: {conn.vad_recording_start_time}")
# # Check if this is the initial connection period (ignore first 1 second of audio)
# if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled:
# current_time = asyncio.get_event_loop().time()
# if current_time - conn.initial_connection_time < 1.0: # Ignore first 1 second
# have_voice = False
# conn.asr_audio.clear() # Clear any accumulated audio
# return
# else:
# conn.initial_connection_handled = True
# # If the device was just woken up, briefly ignore VAD detection
# if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
# have_voice = False
# # Set a brief delay before resuming VAD detection
# conn.asr_audio.clear()
# if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
# conn.vad_resume_task = asyncio.create_task(
# resume_vad_detection(conn))
# return
# if have_voice:
# if conn.client_is_speaking:
# await handleAbortMessage(conn)
# # Device long-term idle detection, used for say goodbye
# await no_voice_close_connect(conn, have_voice)
# # Receive audio
# await conn.asr.receive_audio(conn, audio, have_voice)
# async def resume_vad_detection(conn):
# # Wait 2 seconds before resuming VAD detection
# await asyncio.sleep(1)
# conn.just_woken_up = False
# async def startToChat(conn, text):
# # Check if input is in JSON format (containing speaker information)
# speaker_name = None
# actual_text = text
# try:
# # Try to parse JSON format input
# if text.strip().startswith('{') and text.strip().endswith('}'):
# data = json.loads(text)
# if 'speaker' in data and 'content' in data:
# speaker_name = data['speaker']
# actual_text = data['content']
# conn.logger.bind(tag=TAG).info(
# f"Parsed speaker information: {speaker_name}")
# # Use JSON format text directly, do not parse
# actual_text = text
# except (json.JSONDecodeError, KeyError):
# # If parsing fails, continue using original text
# pass
# # Save speaker information to connection object
# if speaker_name:
# conn.current_speaker = speaker_name
# else:
# conn.current_speaker = None
# if conn.need_bind:
# await check_bind_device(conn)
# return
# # If the daily output word count exceeds the limit
# if conn.max_output_size > 0:
# if check_device_output_limit(
# conn.headers.get("device-id"), conn.max_output_size
# ):
# await max_out_size(conn)
# return
# if conn.client_is_speaking:
# await handleAbortMessage(conn)
# # First perform intent analysis, using actual text content
# intent_handled = await handle_user_intent(conn, actual_text)
# if intent_handled:
# # If intent has been handled, no longer proceed with chat
# return
# # Intent not handled, continue with regular chat flow, using actual text content
# await send_stt_message(conn, actual_text)
# conn.executor.submit(conn.chat, actual_text)
# async def no_voice_close_connect(conn, have_voice):
# if have_voice:
# conn.last_activity_time = time.time() * 1000
# return
# # Only perform timeout check when timestamp has been initialized
# if conn.last_activity_time > 0.0:
# no_voice_time = time.time() * 1000 - conn.last_activity_time
# close_connection_no_voice_time = int(
# conn.config.get("close_connection_no_voice_time", 120)
# )
# if (
# not conn.close_after_chat
# and no_voice_time > 1000 * close_connection_no_voice_time
# ):
# conn.close_after_chat = True
# conn.client_abort = False
# end_prompt = conn.config.get("end_prompt", {})
# if end_prompt and end_prompt.get("enable", True) is False:
# conn.logger.bind(tag=TAG).info(
# "End conversation, no need to send ending prompt")
# await conn.close()
# return
# prompt = end_prompt.get("prompt")
# if not prompt:
# prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!"
# await startToChat(conn, prompt)
# async def max_out_size(conn):
# text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!"
# await send_stt_message(conn, text)
# file_path = "config/assets/max_output_size.wav"
# opus_packets, _ = audio_to_data(file_path)
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
# conn.close_after_chat = True
# async def check_bind_device(conn):
# if conn.bind_code:
# # Ensure bind_code is a 6-digit number
# if len(conn.bind_code) != 6:
# conn.logger.bind(tag=TAG).error(
# f"Invalid binding code format: {conn.bind_code}")
# text = "Binding code format error, please check configuration."
# await send_stt_message(conn, text)
# return
# text = f"Please log into the control panel and enter {conn.bind_code} to bind the device."
# await send_stt_message(conn, text)
# # Play notification sound
# music_path = "config/assets/bind_code.wav"
# opus_packets, _ = audio_to_data(music_path)
# conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# # Play digits one by one
# for i in range(6): # Ensure only 6 digits are played
# try:
# digit = conn.bind_code[i]
# num_path = f"config/assets/bind_code/{digit}.wav"
# num_packets, _ = audio_to_data(num_path)
# conn.tts.tts_audio_queue.put(
# (SentenceType.MIDDLE, num_packets, None))
# except Exception as e:
# conn.logger.bind(tag=TAG).error(
# f"Failed to play digit audio: {e}")
# continue
# conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
# else:
# text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware."
# await send_stt_message(conn, text)
# music_path = "config/assets/bind_not_found.wav"
# opus_packets, _ = audio_to_data(music_path)
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit
@ -30,11 +231,13 @@ async def handleAudioMessage(conn, audio):
have_voice = conn.vad.is_vad(conn, audio)
# Track when voice recording starts in auto VAD mode (for 10-second timeout)
if have_voice and not hasattr(conn, 'vad_recording_start_time'):
conn.vad_recording_start_time = time.time()
conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
elif have_voice and hasattr(conn, 'vad_recording_start_time'):
conn.logger.bind(tag=TAG).debug(f"VAD recording continues, started at: {conn.vad_recording_start_time}")
# Only set the timer once per recording session when transitioning from no-voice to voice
if have_voice:
if not hasattr(conn, 'vad_recording_start_time'):
# First voice detection in this session - set the timer
conn.vad_recording_start_time = time.time()
conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
# Don't overwrite existing timer during continuous voice detection
# Check if this is the initial connection period (ignore first 1 second of audio)
if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled:

View file

@ -1,3 +1,130 @@
# import json
# import asyncio
# import time
# from core.providers.tts.dto.dto import SentenceType
# from core.utils import textUtils
# TAG = __name__
# async def sendAudioMessage(conn, sentenceType, audios, text):
# # Send sentence start message
# conn.logger.bind(tag=TAG).info(
# f"Send audio message: {sentenceType}, {text}")
# pre_buffer = False
# if conn.tts.tts_audio_first_sentence:
# conn.logger.bind(tag=TAG).info(f"Send first audio segment: {text}")
# conn.tts.tts_audio_first_sentence = False
# pre_buffer = True
# await send_tts_message(conn, "sentence_start", text)
# await sendAudio(conn, audios, pre_buffer)
# # Send end message (if it's the last text)
# if conn.llm_finish_task and sentenceType == SentenceType.LAST:
# await send_tts_message(conn, "stop", None)
# conn.client_is_speaking = False
# if conn.close_after_chat:
# await conn.close()
# # Play audio
# async def sendAudio(conn, audios, pre_buffer=True):
# if audios is None or len(audios) == 0:
# return
# # Flow control parameter optimization
# # Frame duration (milliseconds), matching Opus encoding
# frame_duration = 60
# start_time = time.perf_counter()
# play_position = 0
# # Execute pre-buffering only for the first sentence
# if pre_buffer:
# pre_buffer_frames = min(3, len(audios))
# for i in range(pre_buffer_frames):
# await conn.websocket.send(audios[i])
# remaining_audios = audios[pre_buffer_frames:]
# else:
# remaining_audios = audios
# # Play remaining audio frames
# for opus_packet in remaining_audios:
# if conn.client_abort:
# break
# # Reset no-voice state
# conn.last_activity_time = time.time() * 1000
# # Calculate expected send time
# expected_time = start_time + (play_position / 1000)
# current_time = time.perf_counter()
# delay = expected_time - current_time
# if delay > 0:
# await asyncio.sleep(delay)
# await conn.websocket.send(opus_packet)
# play_position += frame_duration
# async def send_tts_message(conn, state, text=None):
# """Send TTS status message"""
# message = {"type": "tts", "state": state, "session_id": conn.session_id}
# if text is not None:
# message["text"] = textUtils.check_emoji(text)
# # TTS playback ended
# if state == "stop":
# # Play notification sound
# tts_notify = conn.config.get("enable_stop_tts_notify", False)
# if tts_notify:
# stop_tts_notify_voice = conn.config.get(
# "stop_tts_notify_voice", "config/assets/tts_notify.mp3"
# )
# audios, _ = conn.tts.audio_to_opus_data(stop_tts_notify_voice)
# await sendAudio(conn, audios)
# # Clear server speaking status and resume listening
# conn.clearSpeakStatus()
# conn.logger.bind(tag=TAG).info("TTS finished - resuming audio listening")
# # Send message to client
# await conn.websocket.send(json.dumps(message))
# async def send_stt_message(conn, text):
# end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
# if end_prompt_str and end_prompt_str == text:
# await send_tts_message(conn, "start")
# return
# """Send STT status message"""
# # Parse JSON format, extract actual user speech content
# display_text = text
# try:
# # Try to parse JSON format
# if text.strip().startswith('{') and text.strip().endswith('}'):
# parsed_data = json.loads(text)
# if isinstance(parsed_data, dict) and "content" in parsed_data:
# # If it's JSON format containing speaker information, only display the content part
# display_text = parsed_data["content"]
# # Save speaker information to conn object
# if "speaker" in parsed_data:
# conn.current_speaker = parsed_data["speaker"]
# except (json.JSONDecodeError, TypeError):
# # If it's not JSON format, use original text directly
# display_text = text
# stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
# await conn.websocket.send(
# json.dumps({"type": "stt", "text": stt_text,
# "session_id": conn.session_id})
# )
# conn.client_is_speaking = True
# conn.logger.bind(tag=TAG).info("TTS started - pausing audio listening to prevent interruption")
# await send_tts_message(conn, "start")
import json
import asyncio
import time
@ -91,6 +218,12 @@ async def send_tts_message(conn, state, text=None):
# Send message to client
await conn.websocket.send(json.dumps(message))
# await conn.websocket.send(json.dumps({
# "type": "tts",
# "state": "stop",
# "session_id": conn.session_id
# }))
async def send_stt_message(conn, text):

View file

@ -62,23 +62,23 @@ class ASRProviderBase(ABC):
else:
have_voice = conn.client_have_voice
# Check for maximum recording timeout (default 10 seconds)
# This applies when we're actively recording (have accumulated audio)
# Check for maximum recording timeout (hardcoded 10 seconds)
# This applies when we're actively recording
recording_start_time = None
if hasattr(conn, 'listen_start_time'):
recording_start_time = conn.listen_start_time # Manual listen mode
logger.bind(tag=TAG).debug(f"Using manual listen start time: {recording_start_time}")
elif hasattr(conn, 'vad_recording_start_time'):
if hasattr(conn, 'vad_recording_start_time'):
recording_start_time = conn.vad_recording_start_time # Auto VAD mode
logger.bind(tag=TAG).debug(f"Using VAD recording start time: {recording_start_time}")
else:
logger.bind(tag=TAG).debug("No recording start time found")
elif hasattr(conn, 'listen_start_time'):
recording_start_time = conn.listen_start_time # Manual listen mode
if len(conn.asr_audio) > 0 and recording_start_time and not conn.client_voice_stop:
if recording_start_time and not conn.client_voice_stop:
current_time = time.time()
recording_duration = current_time - recording_start_time
max_recording_time = conn.config.get('max_recording_time', 10.0)
logger.bind(tag=TAG).debug(f"Recording duration: {recording_duration:.2f}s, max: {max_recording_time}s, audio chunks: {len(conn.asr_audio)}")
max_recording_time = 10.0 # Hardcoded 10 second maximum
# Log every 50 chunks or when approaching timeout
if len(conn.asr_audio) % 50 == 0 or recording_duration >= (max_recording_time - 1):
logger.bind(tag=TAG).debug(f"Recording duration: {recording_duration:.2f}s, max: {max_recording_time}s, audio chunks: {len(conn.asr_audio)}")
if recording_duration >= max_recording_time:
# Use a timeout flag to prevent multiple timeout messages
if not hasattr(conn, '_timeout_triggered') or not conn._timeout_triggered:
@ -91,16 +91,16 @@ class ASRProviderBase(ABC):
# Process any accumulated audio before resetting (same as normal VAD flow)
if len(conn.asr_audio) > 20:
logger.bind(tag=TAG).info(f"Processing {len(conn.asr_audio)} audio chunks after 10-second timeout")
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
conn.reset_vad_states()
conn._timeout_triggered = False # Reset for next session
# Process the accumulated audio
# Process the accumulated audio asynchronously
asyncio.create_task(self.handle_voice_stop(conn, asr_audio_task))
else:
logger.bind(tag=TAG).debug(f"Timeout reached but insufficient audio ({len(conn.asr_audio)} chunks) - resetting without processing")
# No significant audio to process, just reset everything
conn.reset_vad_states()
conn._timeout_triggered = False # Reset for next session
return # Exit early like VAD does
else:

View file

@ -0,0 +1,385 @@
"""
CDN Download Manager for xiaozhi-server
Manages downloading CDN files for local streaming to solve completion signal issues
"""
import asyncio
import tempfile
import aiohttp
import aiofiles
from pathlib import Path
import logging
import hashlib
import json
import time
import shutil
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
TAG = __name__
class CDNDownloadManager:
"""Basic CDN file download manager"""
def __init__(self, temp_dir: str = None):
"""
Initialize CDN download manager
Args:
temp_dir: Directory for temporary files (default: system temp)
"""
if temp_dir:
self.temp_dir = Path(temp_dir)
self.temp_dir.mkdir(parents=True, exist_ok=True)
else:
self.temp_dir = None
async def download_file(self, cdn_url: str, conn) -> str:
"""
Download CDN file to temporary location
Args:
cdn_url: CDN URL to download
conn: Connection object for logging
Returns:
str: Path to downloaded temporary file
Raises:
Exception: If download fails
"""
try:
conn.logger.bind(tag=TAG).info(f"Starting CDN download: {cdn_url}")
# Create temporary file
with tempfile.NamedTemporaryFile(
suffix=".mp3",
dir=self.temp_dir,
delete=False
) as tmp_file:
temp_path = tmp_file.name
# Download with progress tracking
timeout = aiohttp.ClientTimeout(total=120) # 2 minute timeout
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(cdn_url) as response:
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
downloaded = 0
conn.logger.bind(tag=TAG).debug(f"CDN file size: {total_size} bytes")
async for chunk in response.content.iter_chunked(8192):
tmp_file.write(chunk)
downloaded += len(chunk)
# Log progress every 25%
if total_size > 0 and downloaded % (total_size // 4) < 8192:
progress = (downloaded / total_size) * 100
conn.logger.bind(tag=TAG).debug(f"Download progress: {progress:.1f}%")
conn.logger.bind(tag=TAG).info(f"CDN download completed: {downloaded} bytes -> {temp_path}")
# Schedule cleanup after 10 minutes
asyncio.create_task(self._cleanup_file(temp_path, 600))
return temp_path
except asyncio.TimeoutError:
conn.logger.bind(tag=TAG).error(f"CDN download timeout: {cdn_url}")
raise Exception(f"Download timeout for {cdn_url}")
except aiohttp.ClientError as e:
conn.logger.bind(tag=TAG).error(f"CDN download network error: {e}")
raise Exception(f"Network error downloading {cdn_url}: {e}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"CDN download failed: {e}")
raise Exception(f"Failed to download {cdn_url}: {e}")
async def _cleanup_file(self, filepath: str, delay: int):
"""
Clean up temporary file after delay
Args:
filepath: Path to file to clean up
delay: Delay in seconds before cleanup
"""
await asyncio.sleep(delay)
try:
file_path = Path(filepath)
if file_path.exists():
file_path.unlink()
logging.debug(f"Cleaned up temporary CDN file: {filepath}")
except Exception as e:
logging.warning(f"Failed to cleanup CDN temp file {filepath}: {e}")
class SmartCDNCacheManager(CDNDownloadManager):
"""Enhanced CDN manager with intelligent caching"""
def __init__(self, cache_dir: str = "./cache/cdn_audio", max_cache_size_mb: int = 500):
"""
Initialize smart cache manager
Args:
cache_dir: Directory for cached files
max_cache_size_mb: Maximum cache size in MB
"""
super().__init__()
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.max_cache_size = max_cache_size_mb * 1024 * 1024
self.cache_index_file = self.cache_dir / "cache_index.json"
self.cache_index = self._load_cache_index()
logging.info(f"CDN cache initialized: {cache_dir} (max: {max_cache_size_mb}MB)")
def _load_cache_index(self) -> Dict[str, Any]:
"""Load cache index from disk"""
try:
if self.cache_index_file.exists():
with open(self.cache_index_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logging.warning(f"Failed to load cache index: {e}")
return {}
def _save_cache_index(self):
"""Save cache index to disk"""
try:
with open(self.cache_index_file, 'w', encoding='utf-8') as f:
json.dump(self.cache_index, f, indent=2, ensure_ascii=False)
except Exception as e:
logging.error(f"Failed to save cache index: {e}")
def _get_cache_key(self, cdn_url: str) -> str:
"""Generate cache key from URL"""
return hashlib.md5(cdn_url.encode()).hexdigest()
def _extract_title_from_url(self, cdn_url: str) -> str:
"""Extract title from CDN URL"""
try:
# Extract filename from URL path
from urllib.parse import urlparse, unquote
parsed = urlparse(cdn_url)
filename = Path(unquote(parsed.path)).name
# Remove extension and decode URL encoding
title = Path(filename).stem
return title
except Exception:
return "Unknown"
async def get_or_download(self, cdn_url: str, conn) -> str:
"""
Get from cache or download if not cached
Args:
cdn_url: CDN URL to get/download
conn: Connection object for logging
Returns:
str: Path to local file (cached or downloaded)
"""
cache_key = self._get_cache_key(cdn_url)
cache_path = self.cache_dir / f"{cache_key}.mp3"
# Check if cached and valid
if cache_key in self.cache_index:
cache_info = self.cache_index[cache_key]
if cache_path.exists() and cache_path.stat().st_size > 0:
# Update access statistics
cache_info['last_accessed'] = datetime.now().isoformat()
cache_info['access_count'] = cache_info.get('access_count', 0) + 1
self._save_cache_index()
title = cache_info.get('title', 'Unknown')
conn.logger.bind(tag=TAG).info(f"CDN cache hit: {title}")
return str(cache_path)
# Not cached or invalid, download
conn.logger.bind(tag=TAG).info(f"CDN cache miss, downloading: {cdn_url}")
try:
# Download to temp first
temp_path = await super().download_file(cdn_url, conn)
# Cross-platform move to cache (handles Windows cross-drive issue)
try:
# Try rename first (faster on same drive)
Path(temp_path).rename(cache_path)
except OSError:
# If rename fails (cross-drive on Windows), use copy + delete
shutil.copy2(temp_path, cache_path)
Path(temp_path).unlink() # Delete temp file after copy
# Update cache index
self.cache_index[cache_key] = {
'url': cdn_url,
'path': str(cache_path),
'size': cache_path.stat().st_size,
'created': datetime.now().isoformat(),
'last_accessed': datetime.now().isoformat(),
'access_count': 1,
'title': self._extract_title_from_url(cdn_url)
}
self._save_cache_index()
# Manage cache size
await self._manage_cache_size()
conn.logger.bind(tag=TAG).info(f"CDN file cached: {cache_path}")
return str(cache_path)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"CDN download/cache failed: {e}")
raise
async def _manage_cache_size(self):
"""Remove old files if cache exceeds size limit"""
try:
total_size = sum(
info['size'] for info in self.cache_index.values()
if Path(info['path']).exists()
)
if total_size > self.max_cache_size:
# Sort by last accessed (LRU - Least Recently Used)
sorted_items = sorted(
self.cache_index.items(),
key=lambda x: x[1].get('last_accessed', '1970-01-01')
)
# Remove oldest 25% of files
to_remove = sorted_items[:len(sorted_items)//4] if len(sorted_items) > 4 else sorted_items[:1]
for cache_key, info in to_remove:
cache_path = Path(info['path'])
if cache_path.exists():
cache_path.unlink()
del self.cache_index[cache_key]
title = info.get('title', cache_key)
logging.info(f"Evicted from CDN cache: {title}")
self._save_cache_index()
logging.info(f"CDN cache cleanup: removed {len(to_remove)} files")
except Exception as e:
logging.error(f"CDN cache cleanup failed: {e}")
async def download_with_retry(self, cdn_url: str, conn, max_retries: int = 3) -> Optional[str]:
"""
Download with automatic retry on failure
Args:
cdn_url: CDN URL to download
conn: Connection object for logging
max_retries: Maximum retry attempts
Returns:
str: Path to local file, or None if all attempts failed
"""
last_error = None
for attempt in range(max_retries):
try:
return await self.get_or_download(cdn_url, conn)
except Exception as e:
last_error = e
conn.logger.bind(tag=TAG).warning(
f"CDN download attempt {attempt + 1}/{max_retries} failed: {e}"
)
# Wait before retry (exponential backoff)
if attempt < max_retries - 1:
wait_time = 2 ** attempt
await asyncio.sleep(wait_time)
# All retries failed
conn.logger.bind(tag=TAG).error(f"CDN download failed after {max_retries} attempts: {last_error}")
return None
def get_cache_stats(self) -> Dict[str, Any]:
"""Get cache statistics"""
try:
total_files = len(self.cache_index)
total_size = sum(info['size'] for info in self.cache_index.values())
most_accessed = sorted(
self.cache_index.items(),
key=lambda x: x[1].get('access_count', 0),
reverse=True
)[:5]
return {
'total_files': total_files,
'total_size_mb': round(total_size / (1024 * 1024), 2),
'cache_usage_percent': round((total_size / self.max_cache_size) * 100, 1),
'most_played': [
{
'title': info.get('title', 'Unknown'),
'count': info.get('access_count', 0)
}
for _, info in most_accessed
]
}
except Exception as e:
logging.error(f"Failed to get cache stats: {e}")
return {'error': str(e)}
async def preload_popular_content(self, urls_and_titles: list, conn):
"""
Preload popular content during off-peak hours
Args:
urls_and_titles: List of (url, title) tuples to preload
conn: Connection object for logging
"""
conn.logger.bind(tag=TAG).info(f"Preloading {len(urls_and_titles)} popular items")
for i, (url, title) in enumerate(urls_and_titles):
try:
await self.get_or_download(url, conn)
conn.logger.bind(tag=TAG).debug(f"Preloaded {i+1}/{len(urls_and_titles)}: {title}")
# Small delay to avoid overwhelming the CDN
await asyncio.sleep(0.5)
except Exception as e:
conn.logger.bind(tag=TAG).warning(f"Failed to preload {title}: {e}")
conn.logger.bind(tag=TAG).info("Content preloading completed")
# Global instance - can be configured via environment/config
cdn_manager = SmartCDNCacheManager()
async def download_cdn_file(cdn_url: str, conn, use_cache: bool = True) -> Optional[str]:
"""
Convenience function to download CDN file
Args:
cdn_url: CDN URL to download
conn: Connection object for logging
use_cache: Whether to use caching (default: True)
Returns:
str: Path to local file, or None if failed
"""
try:
if use_cache:
return await cdn_manager.download_with_retry(cdn_url, conn)
else:
basic_manager = CDNDownloadManager()
return await basic_manager.download_file(cdn_url, conn)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"CDN download failed: {e}")
return None

View file

@ -11,11 +11,23 @@ from core.utils.dialogue import Message
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
from plugins_func.utils.multilingual_matcher import MultilingualMatcher
# S3 Streaming imports
import boto3
from botocore.exceptions import ClientError
import logging
# CDN Download imports
from core.utils.cdn_manager import download_cdn_file
TAG = __name__
MUSIC_CACHE = {}
MULTILINGUAL_MATCHER = None
# S3 Configuration
S3_CLIENT = None
S3_BUCKET_NAME = "cheeko-audio-files"
play_music_function_desc = {
"type": "function",
"function": {
@ -28,8 +40,8 @@ play_music_function_desc = {
"type": "string",
"description": "Complete user request for music. Include the full original request to enable intelligent matching. Examples: 'play Baa Baa Black Sheep', 'sing Hanuman Chalisa', 'play any Hindi song', 'I want Telugu music', 'play phonics songs', 'something energetic', 'play music for kids'",
},
"language_preference": {
"type": "string",
"requested_language": {
"type": ["string", "null"],
"description": "Detected or requested language preference. Options: 'english', 'hindi', 'telugu', 'kannada', 'tamil', 'phonics', or 'any'. Only set if explicitly mentioned or clearly implied.",
},
"song_type": {
@ -45,13 +57,22 @@ play_music_function_desc = {
@register_function("play_music", play_music_function_desc, ToolType.SYSTEM_CTL)
def play_music(conn, user_request: str, song_type: str = "random", language_preference: str = None):
def play_music(conn, user_request: str, song_type: str = "random", requested_language: str = None):
try:
# Check if music is already playing to prevent multiple simultaneous requests
# if hasattr(conn, 'client_is_speaking') and conn.client_is_speaking:
# conn.logger.bind(tag=TAG).info(f"Music already playing, ignoring duplicate request: '{user_request}'")
# return ActionResponse(
# action=Action.RESPONSE,
# result="Music already playing",
# response="I'm already playing music for you!"
# )
# Initialize multilingual matcher
initialize_multilingual_music_system(conn)
# Log the request for debugging
conn.logger.bind(tag=TAG).info(f"Music request: '{user_request}', type: {song_type}, language: {language_preference}")
conn.logger.bind(tag=TAG).info(f"Music request: '{user_request}', type: {song_type}, language: {requested_language}")
# Check event loop status
if not conn.loop.is_running():
@ -62,7 +83,7 @@ def play_music(conn, user_request: str, song_type: str = "random", language_pref
# Submit async task with enhanced parameters
task = conn.loop.create_task(
handle_multilingual_music_command(conn, user_request, song_type, language_preference)
handle_multilingual_music_command(conn, user_request, song_type, requested_language)
)
# Non-blocking callback handling
@ -83,7 +104,9 @@ def play_music(conn, user_request: str, song_type: str = "random", language_pref
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Error handling multilingual music request: {e}")
return ActionResponse(
action=Action.RESPONSE, result=str(e), response="Error occurred while processing your music request"
action=Action.RESPONSE,
result="Song not available",
response="The song you requested is not available right now, but it will be available soon. Please try again later."
)
@ -224,26 +247,123 @@ def _find_best_match(potential_song, music_files):
def get_music_files(music_dir, music_ext):
"""Get all music files - S3 MODE: Read from metadata.json"""
import json
music_dir = Path(music_dir)
music_files = []
music_file_names = []
for file in music_dir.rglob("*"):
# Check if it's a file
if file.is_file():
# Get file extension
ext = file.suffix.lower()
# Check if extension is in the list
if ext in music_ext:
# Add relative path
music_files.append(str(file.relative_to(music_dir)))
music_file_names.append(
os.path.splitext(str(file.relative_to(music_dir)))[0]
)
# Iterate through language folders
for language_folder in music_dir.iterdir():
if language_folder.is_dir():
language_name = language_folder.name
# Check for metadata.json file first (S3 mode)
metadata_file = language_folder / "metadata.json"
if metadata_file.exists():
try:
with open(metadata_file, 'r', encoding='utf-8') as f:
metadata = json.load(f)
# Add music from metadata
for song_title, song_info in metadata.items():
filename = song_info.get('filename', f"{song_title}.mp3")
relative_path = f"{language_name}/{filename}"
music_files.append(relative_path)
music_file_names.append(os.path.splitext(relative_path)[0])
logging.info(f"Loaded {len(metadata)} songs from {language_name} metadata")
continue
except Exception as e:
logging.error(f"Error reading metadata from {metadata_file}: {e}")
# Fallback: scan for actual audio files (legacy mode)
for file in language_folder.rglob("*"):
if file.is_file():
ext = file.suffix.lower()
if ext in music_ext:
relative_path = str(file.relative_to(music_dir))
music_files.append(relative_path)
music_file_names.append(os.path.splitext(relative_path)[0])
return music_files, music_file_names
def initialize_s3_client():
"""Initialize S3 client for streaming with SigV4"""
global S3_CLIENT
if S3_CLIENT is None:
try:
from botocore.config import Config
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
if aws_access_key and aws_secret_key:
S3_CLIENT = boto3.client(
's3',
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
region_name=aws_region,
config=Config(signature_version="s3v4")
)
logging.info(f"S3 client initialized for music streaming (region: {aws_region})")
else:
logging.warning("AWS credentials not found, S3 streaming disabled")
except Exception as e:
logging.error(f"Failed to initialize S3 client: {e}")
S3_CLIENT = None
def generate_cdn_music_url(language, filename):
"""Generate CDN streaming URL for music file"""
try:
# Import CDN helper
from utils.cdn_helper import get_audio_url
# Ensure proper capitalization for S3 key (S3 folders are capitalized)
language_capitalized = language.capitalize()
audio_path = f"music/{language_capitalized}/{filename}"
# Use CDN helper to generate URL with automatic encoding
cdn_url = get_audio_url(audio_path)
logging.info(f"Generated CDN URL for music: {audio_path} -> {cdn_url}")
return cdn_url
except Exception as e:
logging.error(f"Error generating CDN URL for music: {e}")
# Fallback to S3 presigned URL if CDN fails
return generate_s3_music_url_fallback(language, filename)
def generate_s3_music_url_fallback(language, filename):
"""Fallback S3 streaming URL for music file"""
global S3_CLIENT, S3_BUCKET_NAME
if not S3_CLIENT:
return None
try:
# Ensure proper capitalization for S3 key (S3 folders are capitalized)
language_capitalized = language.capitalize()
s3_key = f"music/{language_capitalized}/{filename}"
url = S3_CLIENT.generate_presigned_url(
'get_object',
Params={'Bucket': S3_BUCKET_NAME, 'Key': s3_key},
ExpiresIn=7200 # 2 hours for streaming
)
logging.info(f"Generated fallback S3 URL for music: {s3_key}")
return url
except ClientError as e:
logging.error(f"Error generating fallback S3 URL for music: {e}")
return None
def initialize_music_handler(conn):
global MUSIC_CACHE
# Initialize S3 client
initialize_s3_client()
if MUSIC_CACHE == {}:
if "play_music" in conn.config["plugins"]:
MUSIC_CACHE["music_config"] = conn.config["plugins"]["play_music"]
@ -286,7 +406,7 @@ def initialize_multilingual_music_system(conn):
conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual matcher: {e}")
MULTILINGUAL_MATCHER = None
async def handle_multilingual_music_command(conn, user_request: str, song_type: str, language_preference: str = None):
async def handle_multilingual_music_command(conn, user_request: str, song_type: str, requested_language: str = None):
"""Enhanced music command handler with multilingual AI matching"""
global MULTILINGUAL_MATCHER, MUSIC_CACHE
@ -295,7 +415,7 @@ async def handle_multilingual_music_command(conn, user_request: str, song_type:
# Check if music directory exists
if not os.path.exists(MUSIC_CACHE["music_dir"]):
conn.logger.bind(tag=TAG).error(f"Music directory does not exist: {MUSIC_CACHE['music_dir']}")
await send_stt_message(conn, "Sorry, I couldn't find the music collection.")
await send_stt_message(conn, "The music collection is being set up. Songs will be available soon. Please try again later.")
return
# Refresh cache if needed
@ -309,8 +429,8 @@ async def handle_multilingual_music_command(conn, user_request: str, song_type:
match_info = None
# Detect language from request if not provided
if not language_preference and MULTILINGUAL_MATCHER:
language_preference = MULTILINGUAL_MATCHER.detect_language_from_request(user_request)
if not requested_language and MULTILINGUAL_MATCHER:
requested_language = MULTILINGUAL_MATCHER.detect_language_from_request(user_request)
# Check if this is a language-only request
is_language_only = MULTILINGUAL_MATCHER and MULTILINGUAL_MATCHER.is_language_only_request(user_request)
@ -330,20 +450,20 @@ async def handle_multilingual_music_command(conn, user_request: str, song_type:
list(MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry)
] if detected_language in MULTILINGUAL_MATCHER.metadata_cache else 'Unknown'
}
conn.logger.bind(tag=TAG).info(f"AI match found: {selected_music} ({detected_language}) - overriding LLM language hint: {language_preference}")
conn.logger.bind(tag=TAG).info(f"AI match found: {selected_music} ({detected_language}) - overriding LLM language hint: {requested_language}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Error in AI matching: {e}")
# Try language-specific selection for language requests or when language is detected
if not selected_music and language_preference and MULTILINGUAL_MATCHER:
if not selected_music and requested_language and MULTILINGUAL_MATCHER:
try:
language_content = MULTILINGUAL_MATCHER.get_language_specific_content(language_preference)
language_content = MULTILINGUAL_MATCHER.get_language_specific_content(requested_language)
if language_content:
selected_path, metadata_entry = random.choice(language_content)
selected_music = selected_path
match_info = {
'method': 'language_random',
'language': language_preference,
'language': requested_language,
'title': metadata_entry.get('romanized', 'Unknown')
}
conn.logger.bind(tag=TAG).info(f"Language-specific random selection: {selected_music}")
@ -395,31 +515,67 @@ async def handle_multilingual_music_command(conn, user_request: str, song_type:
if selected_music:
await play_multilingual_music(conn, selected_music, match_info, user_request)
else:
conn.logger.bind(tag=TAG).error("No music found to play")
await send_stt_message(conn, "Sorry, I couldn't find any music to play.")
# Provide a user-friendly message when song is not available
conn.logger.bind(tag=TAG).info(f"Song not found for request: {user_request}")
not_available_message = "The song you requested is not available right now, but it will be available soon. Please try again later or ask for a different song."
await send_stt_message(conn, not_available_message)
async def play_multilingual_music(conn, selected_music: str, match_info: dict, original_request: str):
"""Play selected music with contextual introduction"""
"""Play selected music with contextual introduction - CDN STREAMING VERSION"""
global MUSIC_CACHE
try:
# Ensure path correctness
if not os.path.isabs(selected_music):
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
# Extract language and filename from selected_music path
# selected_music format: "Hindi/song.mp3" or "English/song.mp3"
path_parts = selected_music.split('/')
if len(path_parts) >= 2:
language = path_parts[0]
filename = path_parts[1]
else:
music_path = selected_music
# Fallback: try to get from match_info
language = match_info.get('language', 'English')
filename = os.path.basename(selected_music)
if not os.path.exists(music_path):
conn.logger.bind(tag=TAG).error(f"Selected music file does not exist: {music_path}")
# Generate CDN streaming URL
cdn_url = generate_cdn_music_url(language, filename)
if not cdn_url:
conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {language}/{filename}")
await send_stt_message(conn, "The song is not available right now, but it will be available soon. Please try again later.")
return
# CRITICAL CHANGE: Download from CDN to local file first
# Try CDN download, fallback to presigned URL if needed
local_file_path = await download_cdn_file(cdn_url, conn)
if not local_file_path:
conn.logger.bind(tag=TAG).warning(f"CDN download failed for: {cdn_url}")
# Try direct presigned URL as fallback
try:
presigned_url = generate_s3_music_url_fallback(language, filename)
if presigned_url:
conn.logger.bind(tag=TAG).info(f"Using presigned URL fallback: {presigned_url[:50]}...")
local_file_path = await download_cdn_file(presigned_url, conn)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Presigned URL fallback failed: {e}")
if not local_file_path:
conn.logger.bind(tag=TAG).error(f"All download methods failed for: {language}/{filename}")
await send_stt_message(conn, "The song is not available right now, but it will be available soon. Please try again later.")
return
# Generate contextual introduction based on match info
intro_text = generate_multilingual_intro(match_info, original_request)
# Set client_is_speaking flag to prevent VAD during music playback
conn.client_is_speaking = True
# Set llm_finish_task to ensure "stop" message is sent when music finishes
conn.llm_finish_task = True
conn.logger.bind(tag=TAG).info("Music playback started - pausing audio listening to prevent interruption")
await send_stt_message(conn, intro_text)
conn.dialogue.put(Message(role="assistant", content=intro_text))
# Queue TTS messages
# Queue TTS messages with S3 URL
if conn.intent_type == "intent_llm":
conn.tts.tts_text_queue.put(
TTSMessageDTO(
@ -438,29 +594,31 @@ async def play_multilingual_music(conn, selected_music: str, match_info: dict, o
)
)
# Use CDN URL instead of local file path
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.MIDDLE,
content_type=ContentType.FILE,
content_file=music_path,
content_file=local_file_path, # LOCAL FILE, NOT CDN URL!
)
)
if conn.intent_type == "intent_llm":
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.LAST,
content_type=ContentType.ACTION,
)
# Always send LAST message to ensure proper TTS stop signal
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.LAST,
content_type=ContentType.ACTION,
)
)
conn.logger.bind(tag=TAG).info(f"Playing multilingual music: {music_path}")
conn.logger.bind(tag=TAG).info(f"Streaming music from local cache: {local_file_path}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to play multilingual music: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Failed to stream music from CDN: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
await send_stt_message(conn, "The song is not available right now, but it will be available soon. Please try again later.")
def generate_multilingual_intro(match_info: dict, original_request: str) -> str:
"""Generate contextual introduction based on matching method and info"""
@ -589,28 +747,59 @@ def _get_random_play_prompt(song_name):
async def play_local_music(conn, specific_file=None):
global MUSIC_CACHE
"""Play local music file"""
"""Play music from S3 - UPDATED FOR S3 STREAMING"""
try:
if not os.path.exists(MUSIC_CACHE["music_dir"]):
conn.logger.bind(tag=TAG).error(
f"Music directory does not exist: " + MUSIC_CACHE["music_dir"]
)
return
# Ensure path correctness
if specific_file:
selected_music = specific_file
music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file)
else:
if not MUSIC_CACHE["music_files"]:
conn.logger.bind(tag=TAG).error("No MP3 music files found")
conn.logger.bind(tag=TAG).error("No music files found in metadata")
return
selected_music = random.choice(MUSIC_CACHE["music_files"])
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
if not os.path.exists(music_path):
conn.logger.bind(tag=TAG).error(f"Selected music file does not exist: {music_path}")
# Extract language and filename from path
path_parts = selected_music.split('/')
if len(path_parts) >= 2:
language = path_parts[0]
filename = path_parts[1]
else:
# Fallback
language = "English"
filename = os.path.basename(selected_music)
# Generate CDN streaming URL (CloudFront)
cdn_url = generate_cdn_music_url(language, filename)
if not cdn_url:
conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {language}/{filename}")
await send_stt_message(conn, "The song is not available right now, but it will be available soon. Please try again later.")
return
# Download from CDN to local file first (same as multilingual function)
local_file_path = await download_cdn_file(cdn_url, conn)
if not local_file_path:
conn.logger.bind(tag=TAG).warning(f"CDN download failed for: {cdn_url}")
# Try presigned URL fallback
try:
presigned_url = generate_s3_music_url_fallback(language, filename)
if presigned_url:
conn.logger.bind(tag=TAG).info(f"Using presigned URL fallback: {presigned_url[:50]}...")
local_file_path = await download_cdn_file(presigned_url, conn)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Presigned URL fallback failed: {e}")
if not local_file_path:
conn.logger.bind(tag=TAG).error(f"All download methods failed for: {language}/{filename}")
await send_stt_message(conn, "The song is not available right now, but it will be available soon. Please try again later.")
return
# Set client_is_speaking flag to prevent VAD during music playback
conn.client_is_speaking = True
# Set llm_finish_task to ensure "stop" message is sent when music finishes
conn.llm_finish_task = True
conn.logger.bind(tag=TAG).info("Music playback started - pausing audio listening to prevent interruption")
text = _get_random_play_prompt(selected_music)
await send_stt_message(conn, text)
conn.dialogue.put(Message(role="assistant", content=text))
@ -631,23 +820,28 @@ async def play_local_music(conn, specific_file=None):
content_detail=text,
)
)
# Use local downloaded file instead of streaming URL
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.MIDDLE,
content_type=ContentType.FILE,
content_file=music_path,
content_file=local_file_path, # LOCAL FILE, NOT STREAMING URL!
)
)
if conn.intent_type == "intent_llm":
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.LAST,
content_type=ContentType.ACTION,
)
# Always send LAST message to ensure proper TTS stop signal
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.LAST,
content_type=ContentType.ACTION,
)
)
conn.logger.bind(tag=TAG).info(f"Streaming music from local cache: {local_file_path}")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"Failed to play music: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Failed to stream music from CDN: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
await send_stt_message(conn, "The song is not available right now, but it will be available soon. Please try again later.")

File diff suppressed because it is too large Load diff

View file

@ -96,6 +96,7 @@ class MultilingualMatcher:
return None
def extract_content_name_from_request(self, request: str) -> Optional[str]:
"""
Extract content name from user request

View file

@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""
Simple S3 access test without Unicode characters
"""
import os
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def test_s3_simple():
"""Simple S3 test"""
# Get credentials
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
bucket_name = os.getenv('S3_BUCKET_NAME', 'cheeko-audio-files')
print("S3 ACCESS TEST")
print("Region:", aws_region)
print("Bucket:", bucket_name)
print("Access Key:", aws_access_key[:10] + "..." if aws_access_key else "NOT SET")
if not aws_access_key or not aws_secret_key:
print("ERROR: AWS credentials not found")
return False
try:
# Create S3 client
s3_client = boto3.client(
's3',
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
region_name=aws_region
)
# Test bucket access
print("Testing bucket access...")
response = s3_client.list_objects_v2(Bucket=bucket_name, MaxKeys=5)
if 'Contents' in response:
print("SUCCESS: Bucket accessible!")
for obj in response['Contents']:
print(f" File: {obj['Key']} ({obj['Size']} bytes)")
else:
print("WARNING: Bucket is empty")
# Test presigned URL
print("Testing presigned URL...")
test_key = "music/Hindi/Bum Bum Bole.mp3"
presigned_url = s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': test_key},
ExpiresIn=3600
)
print("SUCCESS: Presigned URL generated")
print("URL:", presigned_url[:100] + "...")
# Test URL access
import requests
response = requests.head(presigned_url, timeout=10)
print(f"URL Test: HTTP {response.status_code}")
if response.status_code == 200:
print("SUCCESS: File is accessible via presigned URL")
return True
elif response.status_code == 403:
print("ERROR: 403 Forbidden - Check bucket permissions")
return False
else:
print(f"ERROR: HTTP {response.status_code}")
return False
except ClientError as e:
print(f"AWS Error: {e.response['Error']['Code']} - {e.response['Error']['Message']}")
return False
except Exception as e:
print(f"Error: {e}")
return False
if __name__ == "__main__":
test_s3_simple()

View file

@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""
Test CDN configuration and URL generation
"""
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def test_cdn_config():
"""Test CDN configuration"""
print("CDN CONFIGURATION TEST")
print("=" * 50)
# Check environment variables
use_cdn = os.getenv("USE_CDN", "false")
cloudfront_domain = os.getenv("CLOUDFRONT_DOMAIN", "")
s3_base_url = os.getenv("S3_BASE_URL", "")
print(f"USE_CDN: {use_cdn}")
print(f"CLOUDFRONT_DOMAIN: {cloudfront_domain}")
print(f"S3_BASE_URL: {s3_base_url}")
# Test CDN Helper
print("\nTesting CDN Helper...")
try:
from utils.cdn_helper import cdn, get_audio_url, is_cdn_ready
status = cdn.get_status()
print("CDN Helper Status:")
for key, value in status.items():
print(f" {key}: {value}")
# Test URL generation
test_file = "music/Hindi/Bum Bum Bole.mp3"
generated_url = get_audio_url(test_file)
print(f"\nTest File: {test_file}")
print(f"Generated URL: {generated_url}")
print(f"Is CDN Ready: {is_cdn_ready()}")
# Verify the URL type
if "cloudfront" in generated_url:
print("SUCCESS: Using CloudFront URL")
elif "s3.amazonaws.com" in generated_url:
print("WARNING: Using direct S3 URL (will cause 403 errors)")
else:
print("UNKNOWN: Unexpected URL format")
return generated_url
except Exception as e:
print(f"ERROR: {e}")
import traceback
traceback.print_exc()
return None
def test_url_access(url):
"""Test URL accessibility"""
if not url:
return
print(f"\nTesting URL Access...")
print(f"URL: {url}")
try:
import requests
response = requests.head(url, timeout=10)
print(f"HTTP Status: {response.status_code}")
if response.status_code == 200:
print("SUCCESS: URL is accessible")
content_length = response.headers.get('content-length', 'unknown')
content_type = response.headers.get('content-type', 'unknown')
print(f"Content-Length: {content_length}")
print(f"Content-Type: {content_type}")
elif response.status_code == 403:
print("ERROR: 403 Forbidden - Check CloudFront/S3 configuration")
else:
print(f"ERROR: HTTP {response.status_code}")
except Exception as e:
print(f"Network Error: {e}")
if __name__ == "__main__":
url = test_cdn_config()
test_url_access(url)

View file

@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""
Test S3 access and generate presigned URLs
"""
import os
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def test_s3_access():
"""Test S3 access with current credentials"""
# Get credentials from environment
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
bucket_name = os.getenv('S3_BUCKET_NAME', 'cheeko-audio-files')
print("=" * 60)
print("S3 ACCESS TEST")
print("=" * 60)
print(f"AWS Region: {aws_region}")
print(f"S3 Bucket: {bucket_name}")
print(f"Access Key: {aws_access_key[:10]}..." if aws_access_key else "Access Key: NOT SET")
print(f"Secret Key: {'*' * 10}..." if aws_secret_key else "Secret Key: NOT SET")
print("-" * 60)
if not aws_access_key or not aws_secret_key:
print("❌ ERROR: AWS credentials not found in environment")
return False
try:
# Create S3 client
s3_client = boto3.client(
's3',
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
region_name=aws_region
)
# Test 1: List bucket contents (first 10 objects)
print("🔍 Testing bucket access...")
try:
response = s3_client.list_objects_v2(Bucket=bucket_name, MaxKeys=10)
if 'Contents' in response:
print(f"✅ Bucket accessible! Found {len(response['Contents'])} objects")
for obj in response['Contents'][:5]: # Show first 5
print(f" - {obj['Key']} ({obj['Size']} bytes)")
else:
print("⚠️ Bucket is empty or no access to contents")
except ClientError as e:
error_code = e.response['Error']['Code']
print(f"❌ Bucket access failed: {error_code} - {e.response['Error']['Message']}")
return False
# Test 2: Generate presigned URL for a test file
print("\n🔗 Testing presigned URL generation...")
test_key = "music/Hindi/Bum Bum Bole.mp3" # The file from the error log
try:
presigned_url = s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': bucket_name, 'Key': test_key},
ExpiresIn=3600 # 1 hour
)
print(f"✅ Presigned URL generated successfully:")
print(f" {presigned_url}")
# Test 3: Try to access the presigned URL
print("\n🌐 Testing presigned URL access...")
import requests
try:
response = requests.head(presigned_url, timeout=10)
if response.status_code == 200:
print(f"✅ Presigned URL works! File size: {response.headers.get('content-length', 'unknown')} bytes")
else:
print(f"❌ Presigned URL failed: HTTP {response.status_code}")
except Exception as e:
print(f"❌ Network error testing presigned URL: {e}")
except ClientError as e:
print(f"❌ Failed to generate presigned URL: {e}")
return False
# Test 4: Check bucket policy
print("\n🔒 Checking bucket policy...")
try:
policy_response = s3_client.get_bucket_policy(Bucket=bucket_name)
print("✅ Bucket policy exists")
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucketPolicy':
print("⚠️ No bucket policy found - this might explain the 403 errors")
print("💡 Consider adding a public read policy for the audio files")
else:
print(f"❌ Error checking bucket policy: {e}")
print("\n" + "=" * 60)
print("✅ S3 ACCESS TEST COMPLETED SUCCESSFULLY")
print("💡 The system should work with presigned URLs")
print("=" * 60)
return True
except NoCredentialsError:
print("❌ ERROR: Invalid AWS credentials")
return False
except Exception as e:
print(f"❌ ERROR: Unexpected error: {e}")
return False
def test_cdn_helper():
"""Test CDN helper functionality"""
print("\n" + "=" * 60)
print("CDN HELPER TEST")
print("=" * 60)
try:
from utils.cdn_helper import cdn, get_audio_url, is_cdn_ready
# Test CDN status
status = cdn.get_status()
print("CDN Configuration:")
for key, value in status.items():
print(f" {key}: {value}")
print(f"\nCDN Ready: {'✅ YES' if is_cdn_ready() else '❌ NO'}")
# Test URL generation
test_file = "music/Hindi/Bum Bum Bole.mp3"
cdn_url = get_audio_url(test_file)
print(f"\nTest URL: {cdn_url}")
except Exception as e:
print(f"❌ CDN Helper error: {e}")
if __name__ == "__main__":
test_s3_access()
test_cdn_helper()

View file

@ -0,0 +1,86 @@
"""
CDN Helper for Audio Streaming
Handles CloudFront CDN integration for audio file delivery
"""
import os
from typing import Optional
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
class CDNHelper:
def __init__(self):
self.use_cdn = os.getenv("USE_CDN", "false").lower() == "true"
self.cloudfront_domain = os.getenv("CLOUDFRONT_DOMAIN", "")
self.s3_base_url = os.getenv("S3_BASE_URL", "")
self.s3_bucket_name = os.getenv("S3_BUCKET_NAME", "")
# Fallback S3 URL if not provided
if not self.s3_base_url and self.s3_bucket_name:
region = os.getenv("AWS_DEFAULT_REGION", "us-east-1")
self.s3_base_url = f"https://{self.s3_bucket_name}.s3.{region}.amazonaws.com"
def get_audio_url(self, audio_file: str) -> str:
"""
Generate audio URL with CDN support
Args:
audio_file: Path to audio file (e.g., "uploads/audio123.mp3")
Returns:
Complete URL to audio file
"""
import urllib.parse
# Remove leading slash if present
audio_file = audio_file.lstrip('/')
# URL encode the file path to handle spaces and special characters
encoded_audio_file = urllib.parse.quote(audio_file, safe='/')
if self.use_cdn and self.cloudfront_domain:
return f"https://{self.cloudfront_domain}/{encoded_audio_file}"
else:
return f"{self.s3_base_url}/{encoded_audio_file}"
def get_cache_headers(self) -> dict:
"""
Get appropriate cache headers for audio responses
"""
return {
"Cache-Control": "public, max-age=86400", # 24 hours
"X-Content-Type-Options": "nosniff",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD",
}
def is_cdn_enabled(self) -> bool:
"""Check if CDN is properly configured and enabled"""
return self.use_cdn and bool(self.cloudfront_domain)
def get_status(self) -> dict:
"""Get CDN configuration status for debugging"""
return {
"cdn_enabled": self.use_cdn,
"cloudfront_domain": self.cloudfront_domain,
"s3_base_url": self.s3_base_url,
"s3_bucket": self.s3_bucket_name,
"cdn_ready": self.is_cdn_enabled()
}
# Global instance
cdn = CDNHelper()
# Convenience functions
def get_audio_url(audio_file: str) -> str:
"""Get audio URL with CDN support"""
return cdn.get_audio_url(audio_file)
def get_cache_headers() -> dict:
"""Get cache headers for audio responses"""
return cdn.get_cache_headers()
def is_cdn_ready() -> bool:
"""Check if CDN is ready to use"""
return cdn.is_cdn_enabled()