diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index 0b537e4f9..99ae87125 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -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 diff --git a/main/xiaozhi-server/core/api/cdn_handler.py b/main/xiaozhi-server/core/api/cdn_handler.py new file mode 100644 index 000000000..b7b1b698a --- /dev/null +++ b/main/xiaozhi-server/core/api/cdn_handler.py @@ -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", + } + ) \ No newline at end of file diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index cb5041114..48bc10291 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1,3 +1,1226 @@ +# import os +# import sys +# import copy +# import json +# import uuid +# import time +# import queue +# import asyncio +# import threading +# import traceback +# import subprocess +# import websockets +# from core.utils.util import ( +# extract_json_from_string, +# check_vad_update, +# check_asr_update, +# filter_sensitive_info, +# ) +# from typing import Dict, Any +# from collections import deque +# from core.utils.modules_initialize import ( +# initialize_modules, +# initialize_tts, +# initialize_asr, +# ) +# from core.handle.reportHandle import report +# from core.providers.tts.default import DefaultTTS +# from concurrent.futures import ThreadPoolExecutor +# from core.utils.dialogue import Message, Dialogue +# from core.providers.asr.dto.dto import InterfaceType +# from core.handle.textHandle import handleTextMessage +# from core.providers.tools.unified_tool_handler import UnifiedToolHandler +# from plugins_func.loadplugins import auto_import_modules +# from plugins_func.register import Action, ActionResponse +# from core.auth import AuthMiddleware, AuthenticationError +# from config.config_loader import get_private_config_from_api +# from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType +# from config.logger import setup_logging, build_module_string, create_connection_logger +# from config.manage_api_client import DeviceNotFoundException, DeviceBindException +# from core.utils.prompt_manager import PromptManager +# from core.utils.voiceprint_provider import VoiceprintProvider +# from core.utils import textUtils + +# TAG = __name__ + +# auto_import_modules("plugins_func.functions") + + +# class TTSException(RuntimeError): +# pass + + +# class ConnectionHandler: +# def __init__( +# self, +# config: Dict[str, Any], +# _vad, +# _asr, +# _llm, +# _memory, +# _intent, +# server=None, +# ): +# self.common_config = config +# self.config = copy.deepcopy(config) +# self.session_id = str(uuid.uuid4()) +# self.logger = setup_logging() +# self.server = server # Save a reference to the server instance + +# self.auth = AuthMiddleware(config) +# self.need_bind = False +# self.bind_code = None +# self.read_config_from_api = self.config.get( +# "read_config_from_api", False) + +# self.websocket = None +# self.headers = None +# self.device_id = None +# self.client_ip = None +# self.prompt = None +# self.welcome_msg = None +# self.max_output_size = 0 +# self.chat_history_conf = 0 +# self.audio_format = "opus" + +# # Client state related +# self.client_abort = False +# self.client_is_speaking = False +# self.client_listen_mode = "auto" + +# # Thread task related +# self.loop = asyncio.get_event_loop() +# self.stop_event = threading.Event() +# self.executor = ThreadPoolExecutor(max_workers=5) + +# # Add reporting thread pool +# self.report_queue = queue.Queue() +# self.report_thread = None +# # This can be modified in the future to adjust ASR and TTS reporting. Currently, both are enabled by default. +# self.report_asr_enable = self.read_config_from_api +# self.report_tts_enable = self.read_config_from_api + +# # Dependent components +# self.vad = None +# self.asr = None +# self.tts = None +# self._asr = _asr +# self._vad = _vad +# self.llm = _llm +# self.memory = _memory +# self.intent = _intent + +# # Manage voiceprint recognition separately for each connection +# self.voiceprint_provider = None + +# # VAD related variables +# self.client_audio_buffer = bytearray() +# self.client_have_voice = False +# # Unified activity timestamp (milliseconds) +# self.last_activity_time = 0.0 +# self.client_voice_stop = False +# self.client_voice_window = deque(maxlen=5) +# self.last_is_voice = False + +# # ASR related variables +# # Since a public local ASR might be used in actual deployment, variables cannot be exposed to the public ASR. +# # Therefore, variables related to ASR need to be defined here as private variables of the connection. +# self.asr_audio = [] +# self.asr_audio_queue = queue.Queue() + +# # Pre-buffer to store audio chunks before voice detection +# # This helps capture the beginning of speech that might be missed +# self.audio_pre_buffer = deque(maxlen=10) # Store last 10 chunks (600ms) before voice detection + +# # Audio recording timeout tracking +# self.audio_recording_start_time = None # When voice recording started +# self.max_audio_recording_seconds = 10 # Maximum recording duration in seconds + +# # LLM related variables +# self.llm_finish_task = True +# self.dialogue = Dialogue() + +# # TTS related variables +# self.sentence_id = None +# # Handle cases where TTS response has no text +# self.tts_MessageText = "" + +# # IoT related variables +# self.iot_descriptors = {} +# self.func_handler = None + +# self.cmd_exit = self.config["exit_commands"] +# self.max_cmd_length = 0 +# for cmd in self.cmd_exit: +# if len(cmd) > self.max_cmd_length: +# self.max_cmd_length = len(cmd) + +# # Whether to close the connection after the chat ends +# self.close_after_chat = False +# self.load_function_plugin = False +# self.intent_type = "nointent" + +# self.timeout_seconds = ( +# int(self.config.get("close_connection_no_voice_time", 120)) + 60 +# ) # Add 60 seconds to the original first-level close for a second-level close +# self.timeout_task = None + +# # {"mcp":true} indicates that the MCP function is enabled +# self.features = None + +# # Initialize prompt manager +# self.prompt_manager = PromptManager(config, self.logger) + +# async def handle_connection(self, ws): +# try: +# # Get and validate headers +# self.headers = dict(ws.request.headers) + +# if self.headers.get("device-id", None) is None: +# # Try to get device-id from the URL's query parameters +# from urllib.parse import parse_qs, urlparse + +# # Get the path from the WebSocket request +# request_path = ws.request.path +# if not request_path: +# self.logger.bind(tag=TAG).error( +# "Unable to get request path") +# return +# parsed_url = urlparse(request_path) +# query_params = parse_qs(parsed_url.query) +# if "device-id" in query_params: +# self.headers["device-id"] = query_params["device-id"][0] +# self.headers["client-id"] = query_params["client-id"][0] +# else: +# await ws.send("Port is normal. To test the connection, please use test_page.html") +# await self.close(ws) +# return +# real_ip = self.headers.get("x-real-ip") or self.headers.get( +# "x-forwarded-for" +# ) +# if real_ip: +# self.client_ip = real_ip.split(",")[0].strip() +# else: +# self.client_ip = ws.remote_address[0] +# self.logger.bind(tag=TAG).info( +# f"{self.client_ip} conn - Headers: {self.headers}" +# ) + +# # Perform authentication +# await self.auth.authenticate(self.headers) + +# # Authentication passed, continue processing +# self.websocket = ws +# self.device_id = self.headers.get("device-id", None) + +# # Initialize activity timestamp +# self.last_activity_time = time.time() * 1000 + +# # Start timeout check task +# self.timeout_task = asyncio.create_task(self._check_timeout()) + +# self.welcome_msg = self.config["xiaozhi"] +# self.welcome_msg["session_id"] = self.session_id + +# # Get differential configuration +# self._initialize_private_config() +# # Asynchronous initialization +# self.executor.submit(self._initialize_components) + +# try: +# async for message in self.websocket: +# await self._route_message(message) +# except websockets.exceptions.ConnectionClosed: +# self.logger.bind(tag=TAG).info("Client disconnected") + +# except AuthenticationError as e: +# self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}") +# return +# except Exception as e: +# stack_trace = traceback.format_exc() +# self.logger.bind(tag=TAG).error( +# f"Connection error: {str(e)}-{stack_trace}") +# return +# finally: +# try: +# await self._save_and_close(ws) +# except Exception as final_error: +# self.logger.bind(tag=TAG).error( +# f"Error during final cleanup: {final_error}") +# # Ensure the connection is closed even if saving memory fails +# try: +# await self.close(ws) +# except Exception as close_error: +# self.logger.bind(tag=TAG).error( +# f"Error during forced connection closure: {close_error}" +# ) + +# async def _save_and_close(self, ws): +# """Save memory and close the connection""" +# try: +# if self.memory: +# # Log where memory is being saved based on memory type +# memory_type = getattr(self, 'memory_type', 'unknown') +# if memory_type == "nomem": +# self.logger.bind(tag=TAG).info("Memory saving DISABLED (using nomem)") +# elif memory_type == "mem0ai": +# self.logger.bind(tag=TAG).info("Saving memory to MEM0 CLOUD") +# elif memory_type == "mem_local_short": +# self.logger.bind(tag=TAG).info("Saving memory to LOCAL STORAGE (mem_local_short)") +# else: +# self.logger.bind(tag=TAG).info(f"Saving memory using: {memory_type}") + +# # Use a thread pool to save memory asynchronously +# def save_memory_task(): +# try: +# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Starting memory save task for {memory_type}") +# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Dialogue messages count: {len(self.dialogue.dialogue) if self.dialogue and self.dialogue.dialogue else 0}") + +# # Create a new event loop (to avoid conflicts with the main loop) +# loop = asyncio.new_event_loop() +# asyncio.set_event_loop(loop) + +# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Calling memory.save_memory()") +# result = loop.run_until_complete( +# self.memory.save_memory(self.dialogue.dialogue) +# ) + +# if result: +# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Memory saved successfully using {memory_type}. Result: {result}") +# else: +# self.logger.bind(tag=TAG).warning(f"[MEM0-THREAD] Memory save returned None/False for {memory_type}") +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"[MEM0-THREAD] Failed to save memory: {e}") +# self.logger.bind(tag=TAG).error( +# f"[MEM0-THREAD] Exception traceback: {traceback.format_exc()}") +# finally: +# try: +# loop.close() +# except Exception: +# pass + +# # Start a thread to save memory, do not wait for completion +# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Starting new thread for memory save") +# threading.Thread(target=save_memory_task, daemon=True).start() +# except Exception as e: +# self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}") +# finally: +# # Close the connection immediately, do not wait for memory saving to complete +# try: +# await self.close(ws) +# except Exception as close_error: +# self.logger.bind(tag=TAG).error( +# f"Failed to close connection after saving memory: {close_error}" +# ) + +# async def _route_message(self, message): +# """Message routing""" +# if isinstance(message, str): +# await handleTextMessage(self, message) +# elif isinstance(message, bytes): +# if self.vad is None: +# return +# if self.asr is None: +# return +# self.asr_audio_queue.put(message) + +# async def handle_restart(self, message): +# """Handle server restart request""" +# try: + +# self.logger.bind(tag=TAG).info( +# "Received server restart command, preparing to execute...") + +# # Send confirmation response +# await self.websocket.send( +# json.dumps( +# { +# "type": "server", +# "status": "success", +# "message": "Server restarting...", +# "content": {"action": "restart"}, +# } +# ) +# ) + +# # Asynchronously execute the restart operation +# def restart_server(): +# """The actual method to execute the restart""" +# time.sleep(1) +# self.logger.bind(tag=TAG).info("Executing server restart...") +# subprocess.Popen( +# [sys.executable, "app.py"], +# stdin=sys.stdin, +# stdout=sys.stdout, +# stderr=sys.stderr, +# start_new_session=True, +# ) +# os._exit(0) + +# # Use a thread to execute the restart to avoid blocking the event loop +# threading.Thread(target=restart_server, daemon=True).start() + +# except Exception as e: +# self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}") +# await self.websocket.send( +# json.dumps( +# { +# "type": "server", +# "status": "error", +# "message": f"Restart failed: {str(e)}", +# "content": {"action": "restart"}, +# } +# ) +# ) + +# def _initialize_components(self): +# try: +# self.selected_module_str = build_module_string( +# self.config.get("selected_module", {}) +# ) +# self.logger = create_connection_logger(self.selected_module_str) + +# """Initialize components""" +# if self.config.get("prompt") is not None: +# user_prompt = self.config["prompt"] +# # Use a quick prompt for initialization +# prompt = self.prompt_manager.get_quick_prompt(user_prompt) +# self.change_system_prompt(prompt) +# self.logger.bind(tag=TAG).info( +# f"Quickly initialized component: prompt successful {prompt[:50]}..." +# ) + +# """Initialize local components""" +# if self.vad is None: +# self.vad = self._vad +# if self.asr is None: +# self.asr = self._initialize_asr() + +# # Initialize voiceprint recognition +# self._initialize_voiceprint() + +# # Open speech recognition channel +# asyncio.run_coroutine_threadsafe( +# self.asr.open_audio_channels(self), self.loop +# ) +# if self.tts is None: +# self.tts = self._initialize_tts() +# # Open speech synthesis channel +# asyncio.run_coroutine_threadsafe( +# self.tts.open_audio_channels(self), self.loop +# ) + +# """Load memory""" +# self._initialize_memory() +# """Load intent recognition""" +# self._initialize_intent() +# """Initialize reporting thread""" +# self._init_report_threads() +# """Update system prompt""" +# self._init_prompt_enhancement() + +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"Failed to instantiate components: {e}") + +# def _init_prompt_enhancement(self): +# # Update context information +# self.prompt_manager.update_context_info(self, self.client_ip) +# enhanced_prompt = self.prompt_manager.build_enhanced_prompt( +# self.config["prompt"], self.device_id, self.client_ip +# ) +# if enhanced_prompt: +# self.change_system_prompt(enhanced_prompt) +# self.logger.bind(tag=TAG).info( +# "System prompt has been enhanced and updated") + +# def _init_report_threads(self): +# """Initialize ASR and TTS reporting threads""" +# if not self.read_config_from_api or self.need_bind: +# return +# if self.chat_history_conf == 0: +# return +# if self.report_thread is None or not self.report_thread.is_alive(): +# self.report_thread = threading.Thread( +# target=self._report_worker, daemon=True +# ) +# self.report_thread.start() +# self.logger.bind(tag=TAG).info("TTS reporting thread started") + +# def _initialize_tts(self): +# """Initialize TTS""" +# tts = None +# if not self.need_bind: +# tts = initialize_tts(self.config) + +# if tts is None: +# tts = DefaultTTS(self.config, delete_audio_file=True) + +# return tts + +# def _initialize_asr(self): +# """Initialize ASR""" +# if self._asr.interface_type == InterfaceType.LOCAL: +# # If the public ASR is a local service, return directly +# # Because one local ASR instance can be shared by multiple connections +# asr = self._asr +# else: +# # If the public ASR is a remote service, initialize a new instance +# # Because a remote ASR involves a WebSocket connection and a receiving thread, each connection needs its own instance +# asr = initialize_asr(self.config) + +# return asr + +# def _initialize_voiceprint(self): +# """Initialize voiceprint recognition for the current connection""" +# try: +# voiceprint_config = self.config.get("voiceprint", {}) +# if voiceprint_config: +# self.voiceprint_provider = VoiceprintProvider( +# voiceprint_config) +# self.logger.bind(tag=TAG).info( +# "Voiceprint recognition function dynamically enabled on connection") +# else: +# self.logger.bind(tag=TAG).info( +# "Voiceprint recognition function not enabled or configuration is incomplete") +# except Exception as e: +# self.logger.bind(tag=TAG).warning( +# f"Voiceprint recognition initialization failed: {str(e)}") + +# def _initialize_private_config(self): +# """If getting from the configuration file, perform a second instantiation""" +# if not self.read_config_from_api: +# return +# """Get differential configuration from the interface for a second instantiation, not a full re-instantiation""" +# try: +# begin_time = time.time() +# private_config = get_private_config_from_api( +# self.config, +# self.headers.get("device-id"), +# self.headers.get("client-id", self.headers.get("device-id")), +# ) +# private_config["delete_audio"] = bool( +# self.config.get("delete_audio", True)) +# # Log the actual API key status for debugging (without exposing the full key) +# if "Memory" in private_config and "Memory_mem0ai" in private_config.get("Memory", {}): +# mem0_config = private_config["Memory"]["Memory_mem0ai"] +# api_key = mem0_config.get("api_key", "") + +# # DEBUG: Print the full API key to verify what's being received +# self.logger.bind(tag=TAG).info(f"[DEBUG] Raw mem0 API key received: '{api_key}'") + +# if api_key == "***": +# self.logger.bind(tag=TAG).warning( +# "Mem0 API key is MASKED (***) from manager API - please configure the actual API key in the Manager Web Dashboard under Provider Management" +# ) +# elif api_key: +# masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****" +# self.logger.bind(tag=TAG).debug(f"Mem0 API key received: {masked_key} (length: {len(api_key)})") +# else: +# self.logger.bind(tag=TAG).warning("Mem0 API key is empty in differential configuration") + +# self.logger.bind(tag=TAG).info( +# f"{time.time() - begin_time} seconds, successfully obtained differential configuration: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" +# ) +# except DeviceNotFoundException as e: +# self.need_bind = True +# private_config = {} +# except DeviceBindException as e: +# self.need_bind = True +# self.bind_code = e.bind_code +# private_config = {} +# except Exception as e: +# self.need_bind = True +# self.logger.bind(tag=TAG).error( +# f"Failed to get differential configuration: {e}") +# private_config = {} + +# init_llm, init_tts, init_memory, init_intent = ( +# False, +# False, +# False, +# False, +# ) + +# init_vad = check_vad_update(self.common_config, private_config) +# init_asr = check_asr_update(self.common_config, private_config) + +# if init_vad: +# self.config["VAD"] = private_config["VAD"] +# self.config["selected_module"]["VAD"] = private_config["selected_module"][ +# "VAD" +# ] +# if init_asr: +# self.config["ASR"] = private_config["ASR"] +# self.config["selected_module"]["ASR"] = private_config["selected_module"][ +# "ASR" +# ] +# if private_config.get("TTS", None) is not None: +# init_tts = True +# self.config["TTS"] = private_config["TTS"] +# self.config["selected_module"]["TTS"] = private_config["selected_module"][ +# "TTS" +# ] +# if private_config.get("LLM", None) is not None: +# init_llm = True +# self.config["LLM"] = private_config["LLM"] +# self.config["selected_module"]["LLM"] = private_config["selected_module"][ +# "LLM" +# ] +# if private_config.get("VLLM", None) is not None: +# self.config["VLLM"] = private_config["VLLM"] +# self.config["selected_module"]["VLLM"] = private_config["selected_module"][ +# "VLLM" +# ] +# if private_config.get("Memory", None) is not None: +# init_memory = True +# self.config["Memory"] = private_config["Memory"] +# self.config["selected_module"]["Memory"] = private_config[ +# "selected_module" +# ]["Memory"] +# if private_config.get("Intent", None) is not None: +# init_intent = True +# self.config["Intent"] = private_config["Intent"] +# model_intent = private_config.get( +# "selected_module", {}).get("Intent", {}) +# self.config["selected_module"]["Intent"] = model_intent +# # Load plugin configuration +# if model_intent != "Intent_nointent": +# plugin_from_server = private_config.get("plugins", {}) +# for plugin, config_str in plugin_from_server.items(): +# plugin_from_server[plugin] = json.loads(config_str) +# self.config["plugins"] = plugin_from_server +# self.config["Intent"][self.config["selected_module"]["Intent"]][ +# "functions" +# ] = list(plugin_from_server.keys()) +# if private_config.get("prompt", None) is not None: +# self.config["prompt"] = private_config["prompt"] +# # Get voiceprint information +# if private_config.get("voiceprint", None) is not None: +# self.config["voiceprint"] = private_config["voiceprint"] +# if private_config.get("summaryMemory", None) is not None: +# self.config["summaryMemory"] = private_config["summaryMemory"] +# if private_config.get("device_max_output_size", None) is not None: +# self.max_output_size = int( +# private_config["device_max_output_size"]) +# if private_config.get("chat_history_conf", None) is not None: +# self.chat_history_conf = int(private_config["chat_history_conf"]) +# if private_config.get("mcp_endpoint", None) is not None: +# self.config["mcp_endpoint"] = private_config["mcp_endpoint"] +# try: +# modules = initialize_modules( +# self.logger, +# private_config, +# init_vad, +# init_asr, +# init_llm, +# init_tts, +# init_memory, +# init_intent, +# ) +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"Failed to initialize components: {e}") +# modules = {} +# if modules.get("tts", None) is not None: +# self.tts = modules["tts"] +# if modules.get("vad", None) is not None: +# self.vad = modules["vad"] +# if modules.get("asr", None) is not None: +# self.asr = modules["asr"] +# if modules.get("llm", None) is not None: +# self.llm = modules["llm"] +# if modules.get("intent", None) is not None: +# self.intent = modules["intent"] +# if modules.get("memory", None) is not None: +# self.memory = modules["memory"] + +# def _initialize_memory(self): +# if self.memory is None: +# return +# """Initialize memory module""" +# self.memory.init_memory( +# role_id=self.device_id, +# llm=self.llm, +# summary_memory=self.config.get("summaryMemory", None), +# save_to_file=not self.read_config_from_api, +# ) + +# # Get memory summary configuration +# memory_config = self.config["Memory"] +# memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][ +# "type" +# ] +# # Store memory type for logging +# self.memory_type = memory_type + +# # If using nomem, return directly +# if memory_type == "nomem": +# self.logger.bind(tag=TAG).info("Memory module initialized: DISABLED (nomem)") +# return +# # Use mem_local_short mode +# elif memory_type == "mem_local_short": +# self.logger.bind(tag=TAG).info("Memory module initialized: LOCAL STORAGE (mem_local_short)") +# memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][ +# "llm" +# ] +# if memory_llm_name and memory_llm_name in self.config["LLM"]: +# # If a dedicated LLM is configured, create an independent LLM instance +# from core.utils import llm as llm_utils + +# memory_llm_config = self.config["LLM"][memory_llm_name] +# memory_llm_type = memory_llm_config.get( +# "type", memory_llm_name) +# memory_llm = llm_utils.create_instance( +# memory_llm_type, memory_llm_config +# ) +# self.logger.bind(tag=TAG).info( +# f"Created a dedicated LLM for memory summary: {memory_llm_name}, type: {memory_llm_type}" +# ) +# self.memory.set_llm(memory_llm) +# else: +# # Otherwise use main LLM +# self.memory.set_llm(self.llm) +# self.logger.bind(tag=TAG).info( +# "Using main LLM as memory model") +# elif memory_type == "mem0ai": +# self.logger.bind(tag=TAG).info("Memory module initialized: MEM0 CLOUD (mem0ai)") +# else: +# self.logger.bind(tag=TAG).info(f"Memory module initialized: {memory_type}") + +# def _initialize_intent(self): +# if self.intent is None: +# return +# self.intent_type = self.config["Intent"][ +# self.config["selected_module"]["Intent"] +# ]["type"] +# if self.intent_type == "function_call" or self.intent_type == "intent_llm": +# self.load_function_plugin = True +# """Initialize intent recognition module""" +# # Get intent recognition configuration +# intent_config = self.config["Intent"] +# intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][ +# "type" +# ] + +# # If using nointent, return directly +# if intent_type == "nointent": +# return +# # Use intent_llm mode +# elif intent_type == "intent_llm": +# intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ +# "llm" +# ] + +# if intent_llm_name and intent_llm_name in self.config["LLM"]: +# # If a dedicated LLM is configured, create an independent LLM instance +# from core.utils import llm as llm_utils + +# intent_llm_config = self.config["LLM"][intent_llm_name] +# intent_llm_type = intent_llm_config.get( +# "type", intent_llm_name) +# intent_llm = llm_utils.create_instance( +# intent_llm_type, intent_llm_config +# ) +# self.logger.bind(tag=TAG).info( +# f"Created a dedicated LLM for intent recognition: {intent_llm_name}, type: {intent_llm_type}" +# ) +# self.intent.set_llm(intent_llm) +# else: +# # Otherwise use main LLM +# self.intent.set_llm(self.llm) +# self.logger.bind(tag=TAG).info( +# "Using main LLM as intent recognition model") + +# """Load unified tool handler""" +# self.func_handler = UnifiedToolHandler(self) + +# # Asynchronously initialize tool handler +# if hasattr(self, "loop") and self.loop: +# asyncio.run_coroutine_threadsafe( +# self.func_handler._initialize(), self.loop) + +# def change_system_prompt(self, prompt): +# self.prompt = prompt +# # Update system prompt in the context +# self.dialogue.update_system_message(self.prompt) + +# def chat(self, query, tool_call=False, depth=0): +# self.logger.bind(tag=TAG).info(f"LLM received user message: {query}") +# self.llm_finish_task = False + +# if not tool_call: +# self.dialogue.put(Message(role="user", content=query)) + +# # Create a new session ID and send a FIRST request for the top-level call +# if depth == 0: +# self.sentence_id = str(uuid.uuid4().hex) +# self.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=self.sentence_id, +# sentence_type=SentenceType.FIRST, +# content_type=ContentType.ACTION, +# ) +# ) + +# # Define intent functions +# functions = None +# if self.intent_type == "function_call" and hasattr(self, "func_handler"): +# functions = self.func_handler.get_functions() +# response_message = [] + +# try: +# # Use dialogue with memory +# memory_str = None +# if self.memory is not None: +# future = asyncio.run_coroutine_threadsafe( +# self.memory.query_memory(query), self.loop +# ) +# memory_str = future.result() + +# if self.intent_type == "function_call" and functions is not None: +# # Use streaming interface that supports functions +# llm_responses = self.llm.response_with_functions( +# self.session_id, +# self.dialogue.get_llm_dialogue_with_memory( +# memory_str, self.config.get("voiceprint", {}) +# ), +# functions=functions, +# ) +# else: +# llm_responses = self.llm.response( +# self.session_id, +# self.dialogue.get_llm_dialogue_with_memory( +# memory_str, self.config.get("voiceprint", {}) +# ), +# ) +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"LLM processing error for '{query}': {e}") + +# ##Hre to + +# # Send error message to client and ensure proper completion +# if depth == 0: +# error_message = "Sorry, I'm having trouble understanding right now. Please try again." +# self.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=self.sentence_id, +# sentence_type=SentenceType.MIDDLE, +# content_type=ContentType.TEXT, +# content_detail=error_message, +# ) +# ) +# # Send completion signal +# self.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=self.sentence_id, +# sentence_type=SentenceType.LAST, +# content_type=ContentType.ACTION, +# ) +# ) + +# self.llm_finish_task = True + +# #here +# return None + +# # Handle streaming response +# tool_call_flag = False +# function_name = None +# function_id = None +# function_arguments = "" +# content_arguments = "" +# self.client_abort = False +# emotion_flag = True +# for response in llm_responses: +# if self.client_abort: +# break +# if self.intent_type == "function_call" and functions is not None: +# content, tools_call = response +# if "content" in response: +# content = response["content"] +# tools_call = None +# if content is not None and len(content) > 0: +# content_arguments += content + +# if not tool_call_flag and content_arguments.startswith(""): +# # print("content_arguments", content_arguments) +# tool_call_flag = True + +# if tools_call is not None and len(tools_call) > 0: +# tool_call_flag = True +# if tools_call[0].id is not None: +# function_id = tools_call[0].id +# if tools_call[0].function.name is not None: +# function_name = tools_call[0].function.name +# if tools_call[0].function.arguments is not None: +# function_arguments += tools_call[0].function.arguments +# else: +# content = response + +# # Get emotion from LLM reply, only once at the beginning of a conversation turn +# if emotion_flag and content is not None and content.strip(): +# asyncio.run_coroutine_threadsafe( +# textUtils.get_emotion(self, content), +# self.loop, +# ) +# emotion_flag = False + +# if content is not None and len(content) > 0: +# if not tool_call_flag: +# response_message.append(content) +# self.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=self.sentence_id, +# sentence_type=SentenceType.MIDDLE, +# content_type=ContentType.TEXT, +# content_detail=content, +# ) +# ) +# # Handle function call +# if tool_call_flag: +# bHasError = False +# if function_id is None: +# a = extract_json_from_string(content_arguments) +# if a is not None: +# try: +# content_arguments_json = json.loads(a) +# function_name = content_arguments_json["name"] +# function_arguments = json.dumps( +# content_arguments_json["arguments"], ensure_ascii=False +# ) +# function_id = str(uuid.uuid4().hex) +# except Exception as e: +# bHasError = True +# response_message.append(a) +# else: +# bHasError = True +# response_message.append(content_arguments) +# if bHasError: +# self.logger.bind(tag=TAG).error( +# f"function call error: {content_arguments}" +# ) +# if not bHasError: +# # If the LLM needs to process a turn first, add relevant processed log information +# if len(response_message) > 0: +# text_buff = "".join(response_message) +# self.tts_MessageText = text_buff +# self.dialogue.put( +# Message(role="assistant", content=text_buff)) +# response_message.clear() +# self.logger.bind(tag=TAG).debug( +# f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}" +# ) +# function_call_data = { +# "name": function_name, +# "id": function_id, +# "arguments": function_arguments, +# } + +# # Use unified tool handler to process all tool calls +# result = asyncio.run_coroutine_threadsafe( +# self.func_handler.handle_llm_function_call( +# self, function_call_data +# ), +# self.loop, +# ).result() +# self._handle_function_result( +# result, function_call_data, depth=depth) + +# # Store dialogue content +# if len(response_message) > 0: +# text_buff = "".join(response_message) +# self.tts_MessageText = text_buff +# self.dialogue.put(Message(role="assistant", content=text_buff)) +# if depth == 0: +# self.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=self.sentence_id, +# sentence_type=SentenceType.LAST, +# content_type=ContentType.ACTION, +# ) +# ) +# self.llm_finish_task = True +# # Use lambda for delayed calculation, get_llm_dialogue() is only executed at DEBUG level +# self.logger.bind(tag=TAG).debug( +# lambda: json.dumps( +# self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False +# ) +# ) + +# return True + +# def _handle_function_result(self, result, function_call_data, depth): +# if result.action == Action.RESPONSE: # Respond directly to the front-end +# text = result.response +# self.tts.tts_one_sentence( +# self, ContentType.TEXT, content_detail=text) +# self.dialogue.put(Message(role="assistant", content=text)) +# elif result.action == Action.REQLLM: # Request LLM to generate a reply after calling the function +# text = result.result +# if text is not None and len(text) > 0: +# function_id = function_call_data["id"] +# function_name = function_call_data["name"] +# function_arguments = function_call_data["arguments"] +# self.dialogue.put( +# Message( +# role="assistant", +# tool_calls=[ +# { +# "id": function_id, +# "function": { +# "arguments": "{}" if function_arguments == "" else function_arguments, +# "name": function_name, +# }, +# "type": "function", +# "index": 0, +# } +# ], +# ) +# ) + +# self.dialogue.put( +# Message( +# role="tool", +# tool_call_id=( +# str(uuid.uuid4()) if function_id is None else function_id +# ), +# content=text, +# ) +# ) +# self.chat(text, tool_call=True, depth=depth + 1) +# elif result.action == Action.NOTFOUND or result.action == Action.ERROR: +# text = result.response if result.response else result.result +# self.tts.tts_one_sentence( +# self, ContentType.TEXT, content_detail=text) +# self.dialogue.put(Message(role="assistant", content=text)) +# else: +# pass + +# def _report_worker(self): +# """Chat history reporting worker thread""" +# while not self.stop_event.is_set(): +# try: +# # Get data from the queue, set a timeout to periodically check the stop event +# item = self.report_queue.get(timeout=1) +# if item is None: # Detect the poison pill object +# break +# try: +# # Check the thread pool status +# if self.executor is None: +# continue +# # Submit the task to the thread pool +# self.executor.submit(self._process_report, *item) +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"Chat history reporting thread exception: {e}") +# except queue.Empty: +# continue +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"Chat history reporting worker thread exception: {e}") + +# self.logger.bind(tag=TAG).info("Chat history reporting thread exited") + +# def _process_report(self, type, text, audio_data, report_time): +# """Process the reporting task""" +# try: +# # Execute the report (pass binary data) +# report(self, type, text, audio_data, report_time) +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"Report processing exception: {e}") +# finally: +# # Mark the task as done +# self.report_queue.task_done() + +# def clearSpeakStatus(self): +# self.client_is_speaking = False +# self.logger.bind(tag=TAG).debug(f"Cleared server speaking status") + +# async def close(self, ws=None): +# """Resource cleanup method""" +# try: +# # Cancel the timeout task +# if self.timeout_task and not self.timeout_task.done(): +# self.timeout_task.cancel() +# try: +# await self.timeout_task +# except asyncio.CancelledError: +# pass +# self.timeout_task = None + +# # Clean up tool handler resources +# if hasattr(self, "func_handler") and self.func_handler: +# try: +# await self.func_handler.cleanup() +# except Exception as cleanup_error: +# self.logger.bind(tag=TAG).error( +# f"Error cleaning up tool handler: {cleanup_error}" +# ) + +# # Trigger the stop event +# if self.stop_event: +# self.stop_event.set() + +# # Clear task queues +# self.clear_queues() + +# # Close the WebSocket connection +# try: +# if ws: +# # Safely check WebSocket state and close +# try: +# if hasattr(ws, "closed") and not ws.closed: +# await ws.close() +# elif hasattr(ws, "state") and ws.state.name != "CLOSED": +# await ws.close() +# else: +# # If no closed attribute, try to close directly +# await ws.close() +# except Exception: +# # If closing fails, ignore the error +# pass +# elif self.websocket: +# try: +# if ( +# hasattr(self.websocket, "closed") +# and not self.websocket.closed +# ): +# await self.websocket.close() +# elif ( +# hasattr(self.websocket, "state") +# and self.websocket.state.name != "CLOSED" +# ): +# await self.websocket.close() +# else: +# # If no closed attribute, try to close directly +# await self.websocket.close() +# except Exception: +# # If closing fails, ignore the error +# pass +# except Exception as ws_error: +# self.logger.bind(tag=TAG).error( +# f"Error closing WebSocket connection: {ws_error}") + +# if self.tts: +# await self.tts.close() + +# # Finally close thread pool (avoid blocking) +# if self.executor: +# try: +# self.executor.shutdown(wait=False) +# except Exception as executor_error: +# self.logger.bind(tag=TAG).error( +# f"Error shutting down thread pool: {executor_error}" +# ) +# self.executor = None + +# self.logger.bind(tag=TAG).info("Connection resources released") +# except Exception as e: +# self.logger.bind(tag=TAG).error( +# f"Error occurred while closing connection: {e}") +# finally: +# # Ensure the stop event is set +# if self.stop_event: +# self.stop_event.set() + +# def clear_queues(self): +# """Clear all task queues""" +# if self.tts: +# self.logger.bind(tag=TAG).debug( +# f"Starting cleanup: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}" +# ) + +# # Use non-blocking method to clear queues +# for q in [ +# self.tts.tts_text_queue, +# self.tts.tts_audio_queue, +# self.report_queue, +# ]: +# if not q: +# continue +# while True: +# try: +# q.get_nowait() +# except queue.Empty: +# break + +# self.logger.bind(tag=TAG).debug( +# f"Cleanup completed: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}" +# ) + +# def reset_vad_states(self): +# self.client_audio_buffer = bytearray() +# self.client_have_voice = False +# self.client_voice_stop = False +# # Reset VAD provider internal states +# if hasattr(self, 'vad') and self.vad is not None: +# self.vad.reset() +# # Clear pre-buffer when resetting VAD states +# if hasattr(self, 'audio_pre_buffer'): +# self.audio_pre_buffer.clear() +# # Clear ASR audio buffer to prevent processing leftover audio +# if hasattr(self, 'asr_audio'): +# self.asr_audio.clear() +# # Clear ASR audio queue for this specific connection only +# if hasattr(self, 'asr_audio_queue'): +# # Empty the queue by getting all items without blocking +# cleared_count = 0 +# while not self.asr_audio_queue.empty(): +# try: +# self.asr_audio_queue.get_nowait() +# cleared_count += 1 +# except queue.Empty: +# break +# if cleared_count > 0: +# self.logger.bind(tag=TAG).debug(f"Cleared {cleared_count} audio chunks from ASR queue") +# self.logger.bind(tag=TAG).info("VAD states reset.") + +# def chat_and_close(self, text): +# """Chat with the user and then close the connection""" +# try: +# # Use the existing chat method +# self.chat(text) + +# # After chat is complete, close the connection +# self.close_after_chat = True +# except Exception as e: +# self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") + +# async def _check_timeout(self): +# """Check for connection timeout""" +# try: +# while not self.stop_event.is_set(): +# # Check for timeout (only if the timestamp has been initialized) +# if self.last_activity_time > 0.0: +# current_time = time.time() * 1000 +# if ( +# current_time - self.last_activity_time +# > self.timeout_seconds * 1000 +# ): +# if not self.stop_event.is_set(): +# self.logger.bind(tag=TAG).info( +# "Connection timed out, preparing to close") +# # Set the stop event to prevent duplicate processing +# self.stop_event.set() +# # Use try-except to wrap the close operation, ensuring no blocking due to exceptions +# try: +# await self.close(self.websocket) +# except Exception as close_error: +# self.logger.bind(tag=TAG).error( +# f"Error closing connection on timeout: {close_error}" +# ) +# break +# # Check every 10 seconds to avoid being too frequent +# await asyncio.sleep(10) +# except Exception as e: +# self.logger.bind(tag=TAG).error(f"Timeout check task error: {e}") +# finally: +# self.logger.bind(tag=TAG).info("Timeout check task has exited") + import os import sys import copy @@ -131,6 +1354,9 @@ class ConnectionHandler: # Pre-buffer to store audio chunks before voice detection # This helps capture the beginning of speech that might be missed self.audio_pre_buffer = deque(maxlen=10) # Store last 10 chunks (600ms) before voice detection + + # Timeout flag for preventing multiple timeout triggers + self._timeout_triggered = False # LLM related variables self.llm_finish_task = True diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 83acb044e..da427d168 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -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: diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index b179ea482..dd2b1037b 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -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): diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 6fc30a132..7462a9d46 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -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: diff --git a/main/xiaozhi-server/core/utils/cdn_manager.py b/main/xiaozhi-server/core/utils/cdn_manager.py new file mode 100644 index 000000000..5f85ccbf6 --- /dev/null +++ b/main/xiaozhi-server/core/utils/cdn_manager.py @@ -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 \ No newline at end of file diff --git a/main/xiaozhi-server/music/English/Baa Baa Black Sheep.mp3 b/main/xiaozhi-server/music/English/Baa Baa Black Sheep.mp3 deleted file mode 100644 index 766290be1..000000000 Binary files a/main/xiaozhi-server/music/English/Baa Baa Black Sheep.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/English/Baby Shark Dance.mp3 b/main/xiaozhi-server/music/English/Baby Shark Dance.mp3 deleted file mode 100644 index f922480f8..000000000 Binary files a/main/xiaozhi-server/music/English/Baby Shark Dance.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/English/Five Little Animals.mp3 b/main/xiaozhi-server/music/English/Five Little Animals.mp3 deleted file mode 100644 index ca1c87fa0..000000000 Binary files a/main/xiaozhi-server/music/English/Five Little Animals.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/English/Five Little Ducks.mp3 b/main/xiaozhi-server/music/English/Five Little Ducks.mp3 deleted file mode 100644 index 0298f93f3..000000000 Binary files a/main/xiaozhi-server/music/English/Five Little Ducks.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/English/Once I Caught A Fish Alive.mp3 b/main/xiaozhi-server/music/English/Once I Caught A Fish Alive.mp3 deleted file mode 100644 index df8b642ed..000000000 Binary files a/main/xiaozhi-server/music/English/Once I Caught A Fish Alive.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/English/Ten Little Dinos.mp3 b/main/xiaozhi-server/music/English/Ten Little Dinos.mp3 deleted file mode 100644 index 3caf3c6b8..000000000 Binary files a/main/xiaozhi-server/music/English/Ten Little Dinos.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/English/Wheels on the Bus Go.mp3 b/main/xiaozhi-server/music/English/Wheels on the Bus Go.mp3 deleted file mode 100644 index f90209354..000000000 Binary files a/main/xiaozhi-server/music/English/Wheels on the Bus Go.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/All is well.mp3 b/main/xiaozhi-server/music/Hindi/All is well.mp3 deleted file mode 100644 index 41d978d34..000000000 Binary files a/main/xiaozhi-server/music/Hindi/All is well.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Bandar Mama Aur Kele.mp3 b/main/xiaozhi-server/music/Hindi/Bandar Mama Aur Kele.mp3 deleted file mode 100644 index c26353454..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Bandar Mama Aur Kele.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Bum Bum Bole.mp3 b/main/xiaozhi-server/music/Hindi/Bum Bum Bole.mp3 deleted file mode 100644 index 130557800..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Bum Bum Bole.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Chidiya Rani Badi Sayani.mp3 b/main/xiaozhi-server/music/Hindi/Chidiya Rani Badi Sayani.mp3 deleted file mode 100644 index 4084c006f..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Chidiya Rani Badi Sayani.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Hanuman Chalisa .mp3 b/main/xiaozhi-server/music/Hindi/Hanuman Chalisa .mp3 deleted file mode 100644 index de1f99da9..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Hanuman Chalisa .mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Happy New Year Song.mp3 b/main/xiaozhi-server/music/Hindi/Happy New Year Song.mp3 deleted file mode 100644 index 33d1ac3cf..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Happy New Year Song.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Hathi Raja Kahan Chale.mp3 b/main/xiaozhi-server/music/Hindi/Hathi Raja Kahan Chale.mp3 deleted file mode 100644 index 1669af109..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Hathi Raja Kahan Chale.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Lakdi Ki Kathi.mp3 b/main/xiaozhi-server/music/Hindi/Lakdi Ki Kathi.mp3 deleted file mode 100644 index 4686162bd..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Lakdi Ki Kathi.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Hindi/Titli Udi Ud Na Saki.mp3 b/main/xiaozhi-server/music/Hindi/Titli Udi Ud Na Saki.mp3 deleted file mode 100644 index 87b39aba2..000000000 Binary files a/main/xiaozhi-server/music/Hindi/Titli Udi Ud Na Saki.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/Aane banthondu Aane.mp3 b/main/xiaozhi-server/music/Kannada/Aane banthondu Aane.mp3 deleted file mode 100644 index 1a3fc3747..000000000 Binary files a/main/xiaozhi-server/music/Kannada/Aane banthondu Aane.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/Indu maį¹…gaįø·avāra.mp3 b/main/xiaozhi-server/music/Kannada/Indu maį¹…gaįø·avāra.mp3 deleted file mode 100644 index 7c2c722d5..000000000 Binary files a/main/xiaozhi-server/music/Kannada/Indu maį¹…gaįø·avāra.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/Kothi Mattu Bale Hannu Haadu .mp3 b/main/xiaozhi-server/music/Kannada/Kothi Mattu Bale Hannu Haadu .mp3 deleted file mode 100644 index 743525ced..000000000 Binary files a/main/xiaozhi-server/music/Kannada/Kothi Mattu Bale Hannu Haadu .mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/Namma Maneyali.mp3 b/main/xiaozhi-server/music/Kannada/Namma Maneyali.mp3 deleted file mode 100644 index 9db9f244f..000000000 Binary files a/main/xiaozhi-server/music/Kannada/Namma Maneyali.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/Nayi mari Nayi mari Tindi beke.mp3 b/main/xiaozhi-server/music/Kannada/Nayi mari Nayi mari Tindi beke.mp3 deleted file mode 100644 index c58be1f1e..000000000 Binary files a/main/xiaozhi-server/music/Kannada/Nayi mari Nayi mari Tindi beke.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/Thotake Hogu Timma.mp3 b/main/xiaozhi-server/music/Kannada/Thotake Hogu Timma.mp3 deleted file mode 100644 index 6a1ba911b..000000000 Binary files a/main/xiaozhi-server/music/Kannada/Thotake Hogu Timma.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Kannada/nanna hasu, nanna hasu.mp3 b/main/xiaozhi-server/music/Kannada/nanna hasu, nanna hasu.mp3 deleted file mode 100644 index 2345a48ac..000000000 Binary files a/main/xiaozhi-server/music/Kannada/nanna hasu, nanna hasu.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Phonics/A For Apple , B For Ball, C For Cat.mp3 b/main/xiaozhi-server/music/Phonics/A For Apple , B For Ball, C For Cat.mp3 deleted file mode 100644 index 5efa1aac3..000000000 Binary files a/main/xiaozhi-server/music/Phonics/A For Apple , B For Ball, C For Cat.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Phonics/Fun! Learning ABC For Kindergart.mp3 b/main/xiaozhi-server/music/Phonics/Fun! Learning ABC For Kindergart.mp3 deleted file mode 100644 index 0532fc321..000000000 Binary files a/main/xiaozhi-server/music/Phonics/Fun! Learning ABC For Kindergart.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Telugu/Bava Bava Panneeru.mp3 b/main/xiaozhi-server/music/Telugu/Bava Bava Panneeru.mp3 deleted file mode 100644 index 9e92f46b1..000000000 Binary files a/main/xiaozhi-server/music/Telugu/Bava Bava Panneeru.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Telugu/Chanda mama raave.mp3 b/main/xiaozhi-server/music/Telugu/Chanda mama raave.mp3 deleted file mode 100644 index 22d2ec85e..000000000 Binary files a/main/xiaozhi-server/music/Telugu/Chanda mama raave.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Telugu/Enugamma Enugu.mp3 b/main/xiaozhi-server/music/Telugu/Enugamma Enugu.mp3 deleted file mode 100644 index 3d6545975..000000000 Binary files a/main/xiaozhi-server/music/Telugu/Enugamma Enugu.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Telugu/I am a Very Good Girl.mp3 b/main/xiaozhi-server/music/Telugu/I am a Very Good Girl.mp3 deleted file mode 100644 index efb91405f..000000000 Binary files a/main/xiaozhi-server/music/Telugu/I am a Very Good Girl.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/music/Telugu/chitti chilakamma.mp3 b/main/xiaozhi-server/music/Telugu/chitti chilakamma.mp3 deleted file mode 100644 index a84c48a55..000000000 Binary files a/main/xiaozhi-server/music/Telugu/chitti chilakamma.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index dbfc2e79f..7ee8aa700 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -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"Detailed error: {traceback.format_exc()}") \ No newline at end of file + 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.") \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/play_story.py b/main/xiaozhi-server/plugins_func/functions/play_story.py index 03a869a40..87266139a 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_story.py +++ b/main/xiaozhi-server/plugins_func/functions/play_story.py @@ -1,3 +1,839 @@ +# import os +# import re +# import time +# import random +# import difflib +# import traceback +# from pathlib import Path +# from core.handle.sendAudioHandle import send_stt_message +# from plugins_func.register import register_function, ToolType, ActionResponse, Action +# 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__ + +# STORY_CACHE = {} +# STORY_MULTILINGUAL_MATCHER = None + +# # S3 Configuration +# S3_CLIENT = None +# S3_BUCKET_NAME = "cheeko-audio-files" + +# # Story categories mapping for better recognition +# STORY_CATEGORIES = { +# "bedtime": ["Bedtime", "bedtime story", "sleep story", "night story"], +# "fantasy": ["Fantasy", "fantasy story", "magical story", "magic story"], +# "fairy tales": ["Fairy Tales", "fairy tale", "fairytale"], +# "educational": ["Educational", "educational story", "learning story", "education"], +# "adventure": ["Adventure", "adventure story", "exciting story"] +# } + +# play_story_function_desc = { +# "type": "function", +# "function": { +# "name": "play_story", +# "description": ( +# "CRITICAL: This function ONLY plays pre-recorded story audio files from the stories folder. " +# "NEVER generate, create, or tell stories using text. ALWAYS call this function for ANY story request. " +# "This plays actual audio story files, not generated text stories. " +# "MANDATORY: Use this function for ALL story requests including: 'tell me a story', 'story please', " +# "'I want to hear a story', 'play a bedtime story', 'tell me The Boy Who Cried Wolf', etc. " +# "DO NOT create stories with text - only play pre-recorded audio story files. " +# "Examples: 'tell me a story' → play random story file, 'bedtime story' → play bedtime category file, " +# "'ą¤•ą¤¹ą¤¾ą¤Øą„€ ą¤øą„ą¤Øą¤¾ą¤“' (Hindi) → play story file, 'ಕ಄ೆ ಹೇಳಿ' (Kannada) → play story file" +# ), +# "parameters": { +# "type": "object", +# "properties": { +# "user_request": { +# "type": "string", +# "description": "Complete user request for story. Examples: 'tell me a story', 'tell me The Boy Who Cried Wolf story', 'play a bedtime story', 'I want to hear a fantasy story', 'story please', 'ą¤•ą¤¹ą¤¾ą¤Øą„€ ą¤øą„ą¤Øą¤¾ą¤“', 'ಕ಄ೆ ಹೇಳಿ'", +# }, +# "story_type": { +# "type": "string", +# "enum": ["specific", "category", "random"], +# "description": "Use 'specific' for ANY story title, name, or specific story request (e.g., 'golden gift story', 'The Boy Who Cried Wolf', 'Cinderella', 'three little pigs'). Use 'category' for category requests like 'bedtime story', 'fantasy story'. Use 'random' ONLY for very general requests like 'tell me any story', 'play a story'." +# }, +# "category_preference": { +# "type": "string", +# "description": "Story category if mentioned: 'bedtime', 'fantasy', 'fairy tales', 'educational', 'adventure'. Only set if explicitly mentioned.", +# }, +# "requested_language": { +# "type": "string", +# "description": "Language user requested the story in (e.g., 'hindi', 'english', 'kannada'). Note: Stories may be available in multiple languages depending on metadata.", +# } +# }, +# "required": ["user_request", "story_type"], +# }, +# }, +# } + + +# @register_function("play_story", play_story_function_desc, ToolType.SYSTEM_CTL) +# def play_story(conn, user_request: str, story_type: str = "random", category_preference: str = None, requested_language: str = None): +# try: +# # Initialize multilingual story system +# initialize_multilingual_story_system(conn) + +# # Log the request for debugging +# conn.logger.bind(tag=TAG).info(f"Story request: '{user_request}', type: {story_type}, category: {category_preference}, language: {requested_language}") + +# # Check event loop status +# if not conn.loop.is_running(): +# conn.logger.bind(tag=TAG).error("Event loop not running, cannot submit task") +# return ActionResponse( +# action=Action.RESPONSE, result="System busy", response="Please try again later" +# ) + +# # Submit async task with enhanced parameters +# task = conn.loop.create_task( +# handle_multilingual_story_command(conn, user_request, story_type, category_preference, requested_language) +# ) + +# # Non-blocking callback handling +# def handle_done(f): +# try: +# f.result() +# conn.logger.bind(tag=TAG).info("Multilingual story playback completed") +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Multilingual story playback failed: {e}") + +# task.add_done_callback(handle_done) + +# return ActionResponse( +# action=Action.NONE, +# result="Multilingual story command received", +# response="Let me find a wonderful story for you!" +# ) +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Error handling multilingual story request: {e}") +# return ActionResponse( +# action=Action.RESPONSE, result=str(e), response="Error occurred while processing your story request" +# ) + + +# def normalize_category_name(category_input): +# """Normalize story category name to match folder names""" +# if not category_input: +# return None + +# category_lower = category_input.lower().strip() + +# # Direct mapping for exact matches from LLM +# direct_mappings = { +# "bedtime": "Bedtime", +# "fantasy": "Fantasy", +# "fairy tales": "Fairy Tales", +# "educational": "Educational", +# "adventure": "Adventure", +# "random": None # None means select random category +# } + +# # Check direct mappings first +# if category_lower in direct_mappings: +# return direct_mappings[category_lower] + +# # Check against category variations +# for key, variations in STORY_CATEGORIES.items(): +# for variation in variations: +# if variation.lower() in category_lower or category_lower in variation.lower(): +# # Return the actual folder name +# if key == "bedtime": +# return "Bedtime" +# elif key == "fantasy": +# return "Fantasy" +# elif key == "fairy tales": +# return "Fairy Tales" +# elif key == "educational": +# return "Educational" +# elif key == "adventure": +# return "Adventure" + +# # If no match, return None to trigger random selection +# return None + + +# def get_story_files(story_dir, story_ext): +# """Get all story files organized by category - S3 MODE: Read from metadata.json""" +# import json + +# story_dir = Path(story_dir) +# story_files_by_category = {} +# all_story_files = [] + +# # Check if stories directory exists +# if not story_dir.exists(): +# return {}, [] + +# # Iterate through category folders +# for category_folder in story_dir.iterdir(): +# if category_folder.is_dir(): +# category_name = category_folder.name +# story_files_by_category[category_name] = [] + +# # Check for metadata.json file first (S3 mode) +# metadata_file = category_folder / "metadata.json" +# if metadata_file.exists(): +# try: +# with open(metadata_file, 'r', encoding='utf-8') as f: +# metadata = json.load(f) + +# # Add stories from metadata +# for story_title, story_info in metadata.items(): +# filename = story_info.get('filename', f"{story_title}.mp3") +# relative_path = f"{category_name}/{filename}" +# story_files_by_category[category_name].append(relative_path) +# all_story_files.append(relative_path) + +# logging.info(f"Loaded {len(metadata)} stories from {category_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 category_folder.rglob("*"): +# if file.is_file(): +# ext = file.suffix.lower() +# if ext in story_ext: +# relative_path = str(file.relative_to(story_dir)) +# story_files_by_category[category_name].append(relative_path) +# all_story_files.append(relative_path) + +# return story_files_by_category, all_story_files + + +# 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 story 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_story_url(category, filename): +# """Generate CDN streaming URL for story file""" +# try: +# # Import CDN helper +# from utils.cdn_helper import get_audio_url + +# # Ensure proper capitalization for S3 key (S3 folders are capitalized) +# # Handle special cases like "Fairy Tales" +# if category.lower() == "fairy tales": +# category_capitalized = "Fairy Tales" +# else: +# category_capitalized = category.capitalize() + +# audio_path = f"stories/{category_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 story: {audio_path} -> {cdn_url}") +# return cdn_url + +# except Exception as e: +# logging.error(f"Error generating CDN URL for story: {e}") +# # Fallback to S3 presigned URL if CDN fails +# return generate_s3_story_url_fallback(category, filename) + +# def generate_s3_story_url_fallback(category, filename): +# """Fallback S3 streaming URL for story file""" +# global S3_CLIENT, S3_BUCKET_NAME + +# if not S3_CLIENT: +# return None + +# try: +# # Ensure proper capitalization for S3 key (S3 folders are capitalized) +# # Handle special cases like "Fairy Tales" +# if category.lower() == "fairy tales": +# category_capitalized = "Fairy Tales" +# else: +# category_capitalized = category.capitalize() + +# s3_key = f"stories/{category_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 story: {s3_key}") +# return url +# except ClientError as e: +# logging.error(f"Error generating fallback S3 URL for story: {e}") +# return None + +# def initialize_story_handler(conn): +# """Initialize story handler with configuration""" +# global STORY_CACHE +# # Initialize S3 client +# initialize_s3_client() + +# if STORY_CACHE == {}: +# if "play_story" in conn.config["plugins"]: +# STORY_CACHE["story_config"] = conn.config["plugins"]["play_story"] +# STORY_CACHE["story_dir"] = os.path.abspath( +# STORY_CACHE["story_config"].get("story_dir", "./stories") +# ) +# STORY_CACHE["story_ext"] = STORY_CACHE["story_config"].get( +# "story_ext", (".mp3", ".wav", ".p3") +# ) +# STORY_CACHE["refresh_time"] = STORY_CACHE["story_config"].get( +# "refresh_time", 300 # Refresh every 5 minutes +# ) +# else: +# STORY_CACHE["story_dir"] = os.path.abspath("./stories") +# STORY_CACHE["story_ext"] = (".mp3", ".wav", ".p3") +# STORY_CACHE["refresh_time"] = 300 + +# # Get story files organized by category +# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( +# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"] +# ) +# STORY_CACHE["scan_time"] = time.time() + +# # Log available categories +# if STORY_CACHE["story_files_by_category"]: +# conn.logger.bind(tag=TAG).info( +# f"Found story categories: {list(STORY_CACHE['story_files_by_category'].keys())}" +# ) +# for category, files in STORY_CACHE["story_files_by_category"].items(): +# conn.logger.bind(tag=TAG).info(f" {category}: {len(files)} stories") + +# return STORY_CACHE + +# def initialize_multilingual_story_system(conn): +# """Initialize the multilingual story matching system""" +# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE + +# # Initialize basic story cache first +# initialize_story_handler(conn) + +# # Initialize multilingual matcher if not already done +# if STORY_MULTILINGUAL_MATCHER is None: +# try: +# STORY_MULTILINGUAL_MATCHER = MultilingualMatcher( +# STORY_CACHE["story_dir"], +# STORY_CACHE["story_ext"] +# ) +# if STORY_MULTILINGUAL_MATCHER.language_folders: +# conn.logger.bind(tag=TAG).info(f"Multilingual story matcher initialized with languages: {STORY_MULTILINGUAL_MATCHER.language_folders}") +# else: +# conn.logger.bind(tag=TAG).info("Multilingual story matcher initialized (no metadata.json found, using filesystem fallback)") +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual story matcher: {e}") +# STORY_MULTILINGUAL_MATCHER = None + +# async def handle_multilingual_story_command(conn, user_request: str, story_type: str, category_preference: str = None, requested_language: str = None): +# """Enhanced story command handler with multilingual AI matching""" +# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE + +# conn.logger.bind(tag=TAG).debug(f"Processing multilingual story request: '{user_request}'") + +# # Check if stories directory exists +# if not os.path.exists(STORY_CACHE["story_dir"]): +# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}") +# await send_stt_message(conn, "Sorry, I couldn't find the story collection.") +# return + +# # Refresh cache if needed +# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]: +# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( +# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"] +# ) +# STORY_CACHE["scan_time"] = time.time() + +# selected_story = None +# match_info = None + +# # Try multilingual AI matching for specific stories +# if STORY_MULTILINGUAL_MATCHER and story_type == "specific": +# try: +# match_result = STORY_MULTILINGUAL_MATCHER.find_content_match(user_request, requested_language) +# if match_result: +# selected_story, detected_language, metadata_entry = match_result +# match_info = { +# 'method': 'ai_multilingual', +# 'language': detected_language, +# 'title': metadata_entry.get('romanized', 'Unknown'), +# 'original_title': list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[ +# list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry) +# ] if detected_language in STORY_MULTILINGUAL_MATCHER.metadata_cache else 'Unknown', +# 'category': 'unknown' +# } +# conn.logger.bind(tag=TAG).info(f"AI story match found: {selected_story} ({detected_language})") +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Error in AI story matching: {e}") + +# # Try language-specific selection if no AI match and language is specified +# if not selected_story and requested_language and STORY_MULTILINGUAL_MATCHER: +# try: +# language_content = STORY_MULTILINGUAL_MATCHER.get_language_specific_content(requested_language) +# if language_content: +# selected_path, metadata_entry = random.choice(language_content) +# selected_story = selected_path +# match_info = { +# 'method': 'language_random', +# 'language': requested_language, +# 'title': metadata_entry.get('romanized', 'Unknown'), +# 'category': 'unknown' +# } +# conn.logger.bind(tag=TAG).info(f"Language-specific story selection: {selected_story}") +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Error in language-specific story selection: {e}") + +# # Fallback to legacy category-based selection +# if not selected_story and category_preference: +# normalized_category = normalize_category_name(category_preference) +# if normalized_category and normalized_category in STORY_CACHE["story_files_by_category"]: +# if STORY_CACHE["story_files_by_category"][normalized_category]: +# selected_story = random.choice(STORY_CACHE["story_files_by_category"][normalized_category]) +# match_info = { +# 'method': 'category_selection', +# 'language': 'english', # Default assumption +# 'title': os.path.splitext(os.path.basename(selected_story))[0], +# 'category': normalized_category +# } +# conn.logger.bind(tag=TAG).info(f"Category-based story selection: {selected_story}") + +# # Try legacy specific story matching (for explicit specific requests) +# if not selected_story and story_type == "specific": +# # Extract story name and try fuzzy matching +# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"]) +# if story_name_match: +# selected_story = story_name_match +# match_info = { +# 'method': 'legacy_fuzzy', +# 'language': 'english', +# 'title': os.path.splitext(os.path.basename(selected_story))[0], +# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' +# } +# conn.logger.bind(tag=TAG).info(f"Legacy fuzzy story match: {selected_story}") + +# # SMART FALLBACK: Try specific story matching even for "random" requests that might contain story names +# # This handles cases where LLM misclassifies specific story requests as random +# if not selected_story and story_type != "specific": +# # Check if the request might contain a specific story name by trying fuzzy matching +# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"]) +# if story_name_match: +# selected_story = story_name_match +# match_info = { +# 'method': 'smart_fallback_fuzzy', +# 'language': 'english', +# 'title': os.path.splitext(os.path.basename(selected_story))[0], +# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' +# } +# conn.logger.bind(tag=TAG).info(f"Smart fallback story match (LLM misclassified): {selected_story}") + +# # Final fallback to random selection +# if not selected_story and STORY_CACHE["all_story_files"]: +# selected_story = random.choice(STORY_CACHE["all_story_files"]) +# match_info = { +# 'method': 'random_fallback', +# 'language': 'english', +# 'title': os.path.splitext(os.path.basename(selected_story))[0], +# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' +# } +# conn.logger.bind(tag=TAG).info(f"Random story fallback: {selected_story}") + +# # Play the selected story +# if selected_story: +# await play_multilingual_story(conn, selected_story, match_info, user_request) +# else: +# conn.logger.bind(tag=TAG).error("No stories found to play") +# await send_stt_message(conn, "Sorry, I couldn't find any stories to play.") + +# async def play_multilingual_story(conn, selected_story: str, match_info: dict, original_request: str): +# """Play selected story with contextual introduction - CDN STREAMING VERSION""" +# global STORY_CACHE + +# try: +# # Extract category and filename from selected_story path +# # selected_story format: "Fantasy/story.mp3" or "Adventure/story.mp3" +# path_parts = selected_story.split('/') +# if len(path_parts) >= 2: +# category = path_parts[0] +# filename = path_parts[1] +# else: +# # Fallback: try to get from match_info +# category = match_info.get('category', 'Fantasy') +# filename = os.path.basename(selected_story) + +# # Generate CDN streaming URL +# cdn_url = generate_cdn_story_url(category, filename) + +# if not cdn_url: +# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}") +# await send_stt_message(conn, "Sorry, I couldn't access the story file.") +# return + +# # CRITICAL CHANGE: Download from CDN to local file first +# local_file_path = await download_cdn_file(cdn_url, conn) +# if not local_file_path: +# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}") +# await send_stt_message(conn, "Sorry, I couldn't download the story file.") +# return + +# # Generate contextual introduction based on match info +# intro_text = generate_multilingual_story_intro(match_info, original_request) + +# await send_stt_message(conn, intro_text) +# conn.dialogue.put(Message(role="assistant", content=intro_text)) + +# # Queue TTS messages with S3 URL +# if conn.intent_type == "intent_llm": +# conn.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=conn.sentence_id, +# sentence_type=SentenceType.FIRST, +# content_type=ContentType.ACTION, +# ) +# ) + +# conn.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=conn.sentence_id, +# sentence_type=SentenceType.MIDDLE, +# content_type=ContentType.TEXT, +# content_detail=intro_text, +# ) +# ) + +# # 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=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, +# ) +# ) + +# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes +# conn.llm_finish_task = True + +# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}") + +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}") +# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}") + +# def generate_multilingual_story_intro(match_info: dict, original_request: str) -> str: +# """Generate contextual introduction based on matching method and info""" +# method = match_info.get('method', 'unknown') +# language = match_info.get('language', 'english') +# title = match_info.get('title', 'Unknown Story') +# category = match_info.get('category', 'story') +# original_title = match_info.get('original_title', title) + +# # Clean up the title (remove underscores, etc.) +# clean_title = title.replace("_", " ").replace("-", " ") + +# if method == 'ai_multilingual': +# if language != 'english': +# intros = [ +# f"Perfect! I found '{clean_title}' for you!", +# f"Great choice! Here's the story '{clean_title}'!", +# f"I found exactly what you wanted: '{clean_title}'!", +# f"Let me tell you '{clean_title}' - this should be perfect!" +# ] +# else: +# intros = [ +# f"I found '{clean_title}' which matches your request perfectly!", +# f"Here's '{clean_title}' - I think you'll love this story!", +# f"Playing '{clean_title}' based on your request!" +# ] +# elif method == 'language_random': +# intros = [ +# f"Here's a wonderful story for you: '{clean_title}'!", +# f"Let me tell you '{clean_title}' - a beautiful story!", +# f"I picked '{clean_title}' from our collection!" +# ] +# elif method == 'category_selection': +# if category != 'unknown': +# intros = [ +# f"Here's a lovely {category.lower()} story: '{clean_title}'!", +# f"Perfect! I have a {category.lower()} story for you: '{clean_title}'!", +# f"Let me tell you this {category.lower()} story called '{clean_title}'!" +# ] +# else: +# intros = [ +# f"Here's a wonderful story: '{clean_title}'!", +# f"Let me tell you '{clean_title}'!", +# f"I have a great story for you: '{clean_title}'!" +# ] +# elif method == 'legacy_fuzzy': +# intros = [ +# f"I think you'll love '{clean_title}'!", +# f"Here's '{clean_title}' - hope this is what you wanted!", +# f"Let me tell you the story of '{clean_title}'!" +# ] +# else: # random_fallback +# intros = [ +# f"Let me tell you a wonderful story: '{clean_title}'!", +# f"Here's a great story for you: '{clean_title}'!", +# f"I have a special story called '{clean_title}'!" +# ] + +# return random.choice(intros) + + +# def find_best_story_match(story_name, story_files): +# """Find the best matching story from available files with enhanced matching""" +# best_match = None +# highest_score = 0 + +# # Clean and normalize the input story name +# clean_story_name = story_name.lower().strip() +# # Remove common story words that don't help with matching +# story_words_to_remove = ['story', 'tale', 'a', 'the', 'play', 'tell', 'me'] +# story_name_words = [word for word in clean_story_name.split() if word not in story_words_to_remove] + +# for story_file in story_files: +# # Extract just the filename without path and extension +# file_name = os.path.splitext(os.path.basename(story_file))[0].lower() +# file_name_words = file_name.split() + +# # Method 1: Direct sequence matching (existing approach) +# sequence_ratio = difflib.SequenceMatcher(None, clean_story_name, file_name).ratio() + +# # Method 2: Word-based matching - check how many words match +# word_match_score = 0 +# if story_name_words: +# matching_words = 0 +# for word in story_name_words: +# if any(word in file_word for file_word in file_name_words): +# matching_words += 1 +# word_match_score = matching_words / len(story_name_words) + +# # Method 3: Partial string matching - check if story name is contained in filename +# containment_score = 0 +# if clean_story_name in file_name or file_name in clean_story_name: +# containment_score = 0.8 + +# # Combine scores with weights +# combined_score = (sequence_ratio * 0.4) + (word_match_score * 0.4) + (containment_score * 0.2) + +# # Lower threshold but use combined scoring for better matches +# if combined_score > highest_score and combined_score > 0.3: +# highest_score = combined_score +# best_match = story_file + +# return best_match + + +# async def handle_story_command(conn, category, specific_story=None, requested_language=None): +# """Handle story playback command""" +# initialize_story_handler(conn) +# global STORY_CACHE + +# conn.logger.bind(tag=TAG).debug(f"Handling story command - Category: {category}, Story: {specific_story}, Language: {requested_language}") + +# # Check if stories directory exists +# if not os.path.exists(STORY_CACHE["story_dir"]): +# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}") +# await send_stt_message(conn, "Sorry, I couldn't find the story collection.") +# return + +# # Refresh cache if needed +# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]: +# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( +# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"] +# ) +# STORY_CACHE["scan_time"] = time.time() + +# selected_story = None + +# # If specific story name is provided, try to find it +# if specific_story: +# selected_story = find_best_story_match(specific_story, STORY_CACHE["all_story_files"]) +# if selected_story: +# conn.logger.bind(tag=TAG).info(f"Found matching story: {selected_story}") + +# # If no specific story found, select based on category +# if not selected_story: +# if category and category.lower() != "random": +# # Normalize category name +# normalized_category = normalize_category_name(category) + +# # Try to find the category +# matching_category = None +# for cat_name in STORY_CACHE["story_files_by_category"].keys(): +# if cat_name.lower() == normalized_category.lower(): +# matching_category = cat_name +# break + +# if matching_category and STORY_CACHE["story_files_by_category"][matching_category]: +# selected_story = random.choice(STORY_CACHE["story_files_by_category"][matching_category]) +# conn.logger.bind(tag=TAG).info(f"Selected {matching_category} story: {selected_story}") +# else: +# conn.logger.bind(tag=TAG).warning(f"Category '{category}' not found or empty, selecting random story") +# if STORY_CACHE["all_story_files"]: +# selected_story = random.choice(STORY_CACHE["all_story_files"]) +# else: +# # Select random story from all available +# if STORY_CACHE["all_story_files"]: +# selected_story = random.choice(STORY_CACHE["all_story_files"]) +# conn.logger.bind(tag=TAG).info(f"Selected random story: {selected_story}") + +# if selected_story: +# await play_story_file(conn, selected_story, requested_language) +# else: +# conn.logger.bind(tag=TAG).error("No stories found in the collection") +# await send_stt_message(conn, "I'm sorry, I couldn't find any stories to play.") + + +# def get_story_intro(story_file, requested_language=None): +# """Generate an introduction for the story""" +# # Extract story name and category +# parts = story_file.split(os.sep) +# if len(parts) > 1: +# category = parts[0] +# story_name = os.path.splitext(parts[-1])[0] +# else: +# category = "story" +# story_name = os.path.splitext(story_file)[0] + +# # Clean up the story name (remove underscores, etc.) +# story_name = story_name.replace("_", " ").replace("-", " ") + +# # Always use English intros since stories are in English +# intros = [ +# f"Let me tell you a wonderful {category.lower()} story called '{story_name}'", +# f"Here's a {category.lower()} story for you: '{story_name}'", +# f"Get comfortable and enjoy this {category.lower()} story: '{story_name}'", +# f"I have a special {category.lower()} story for you called '{story_name}'", +# f"Listen carefully to this amazing story: '{story_name}'", +# f" Let's begin '{story_name}'", +# ] + +# intro = random.choice(intros) + +# # Add note if requested in another language +# if requested_language and requested_language != "english": +# intro = f"Playing English story. {intro}" + +# return intro + + +# async def play_story_file(conn, story_file, requested_language=None): +# """Play the selected story file - CDN STREAMING VERSION""" +# try: +# # Extract category and filename from story_file path +# path_parts = story_file.split('/') +# if len(path_parts) >= 2: +# category = path_parts[0] +# filename = path_parts[1] +# else: +# # Fallback +# category = "Fantasy" +# filename = os.path.basename(story_file) + +# # Generate CDN streaming URL +# cdn_url = generate_cdn_story_url(category, filename) + +# if not cdn_url: +# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}") +# await send_stt_message(conn, "Sorry, I couldn't access the story file.") +# return + +# # CRITICAL CHANGE: Download from CDN to local file first +# local_file_path = await download_cdn_file(cdn_url, conn) +# if not local_file_path: +# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}") +# await send_stt_message(conn, "Sorry, I couldn't download the story file.") +# return + +# # Generate and send introduction (always in English) +# intro_text = get_story_intro(story_file, requested_language) +# await send_stt_message(conn, intro_text) +# conn.dialogue.put(Message(role="assistant", content=intro_text)) + +# # Send TTS messages to play the story from CDN +# if conn.intent_type == "intent_llm": +# conn.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=conn.sentence_id, +# sentence_type=SentenceType.FIRST, +# content_type=ContentType.ACTION, +# ) +# ) + +# conn.tts.tts_text_queue.put( +# TTSMessageDTO( +# sentence_id=conn.sentence_id, +# sentence_type=SentenceType.MIDDLE, +# content_type=ContentType.TEXT, +# content_detail=intro_text, +# ) +# ) + +# # 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=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, +# ) +# ) + +# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes +# conn.llm_finish_task = True + +# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}") + +# except Exception as e: +# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}") +# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}") + + + import os import re import time @@ -11,11 +847,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__ STORY_CACHE = {} STORY_MULTILINGUAL_MATCHER = None +# S3 Configuration +S3_CLIENT = None +S3_BUCKET_NAME = "cheeko-audio-files" + # Story categories mapping for better recognition STORY_CATEGORIES = { "bedtime": ["Bedtime", "bedtime story", "sleep story", "night story"], @@ -52,11 +900,11 @@ play_story_function_desc = { "description": "ALWAYS use 'random' for general requests like 'tell me a story'. Use 'specific' only for named stories like 'The Boy Who Cried Wolf'. Use 'category' for requests like 'bedtime story', 'fantasy story'." }, "category_preference": { - "type": "string", + "type": ["string", "null"], "description": "Story category if mentioned: 'bedtime', 'fantasy', 'fairy tales', 'educational', 'adventure'. Only set if explicitly mentioned.", }, "requested_language": { - "type": "string", + "type": ["string", "null"], "description": "Language user requested the story in (e.g., 'hindi', 'english', 'kannada'). Note: Stories may be available in multiple languages depending on metadata.", } }, @@ -69,6 +917,15 @@ play_story_function_desc = { @register_function("play_story", play_story_function_desc, ToolType.SYSTEM_CTL) def play_story(conn, user_request: str, story_type: str = "random", category_preference: str = None, requested_language: str = None): try: + # Check if audio 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"Audio already playing, ignoring duplicate request: '{user_request}'") + # return ActionResponse( + # action=Action.RESPONSE, + # result="Story already playing", + # response="I'm already telling you a story!" + # ) + # Initialize multilingual story system initialize_multilingual_story_system(conn) @@ -151,7 +1008,9 @@ def normalize_category_name(category_input): def get_story_files(story_dir, story_ext): - """Get all story files organized by category""" + """Get all story files organized by category - S3 MODE: Read from metadata.json""" + import json + story_dir = Path(story_dir) story_files_by_category = {} all_story_files = [] @@ -166,7 +1025,27 @@ def get_story_files(story_dir, story_ext): category_name = category_folder.name story_files_by_category[category_name] = [] - # Get all story files in this category + # Check for metadata.json file first (S3 mode) + metadata_file = category_folder / "metadata.json" + if metadata_file.exists(): + try: + with open(metadata_file, 'r', encoding='utf-8') as f: + metadata = json.load(f) + + # Add stories from metadata + for story_title, story_info in metadata.items(): + filename = story_info.get('filename', f"{story_title}.mp3") + relative_path = f"{category_name}/{filename}" + story_files_by_category[category_name].append(relative_path) + all_story_files.append(relative_path) + + logging.info(f"Loaded {len(metadata)} stories from {category_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 category_folder.rglob("*"): if file.is_file(): ext = file.suffix.lower() @@ -178,9 +1057,98 @@ def get_story_files(story_dir, story_ext): return story_files_by_category, all_story_files +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 story 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_story_url(category, filename): + """Generate CDN streaming URL for story file""" + try: + # Import CDN helper + from utils.cdn_helper import get_audio_url + + # Debug logging + logging.info(f"generate_cdn_story_url called with: category='{category}', filename='{filename}'") + + # Ensure proper capitalization for S3 key (S3 folders are capitalized) + # Handle special cases like "Fairy Tales" + if category and category.lower() == "fairy tales": + category_capitalized = "Fairy Tales" + elif category and category.lower() == "bedtime": + category_capitalized = "Bedtime" + elif category: + category_capitalized = category.capitalize() + else: + category_capitalized = "Unknown" # Fallback if category is None or empty + logging.warning(f"Category was empty or None, using 'Unknown' as fallback") + + audio_path = f"stories/{category_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 story: {audio_path} -> {cdn_url}") + return cdn_url + + except Exception as e: + logging.error(f"Error generating CDN URL for story: {e}") + # Fallback to S3 presigned URL if CDN fails + return generate_s3_story_url_fallback(category, filename) + +def generate_s3_story_url_fallback(category, filename): + """Fallback S3 streaming URL for story file""" + global S3_CLIENT, S3_BUCKET_NAME + + if not S3_CLIENT: + return None + + try: + # Ensure proper capitalization for S3 key (S3 folders are capitalized) + # Handle special cases like "Fairy Tales" + if category.lower() == "fairy tales": + category_capitalized = "Fairy Tales" + else: + category_capitalized = category.capitalize() + + s3_key = f"stories/{category_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 story: {s3_key}") + return url + except ClientError as e: + logging.error(f"Error generating fallback S3 URL for story: {e}") + return None + def initialize_story_handler(conn): """Initialize story handler with configuration""" global STORY_CACHE + # Initialize S3 client + initialize_s3_client() + if STORY_CACHE == {}: if "play_story" in conn.config["plugins"]: STORY_CACHE["story_config"] = conn.config["plugins"]["play_story"] @@ -264,14 +1232,22 @@ async def handle_multilingual_story_command(conn, user_request: str, story_type: match_result = STORY_MULTILINGUAL_MATCHER.find_content_match(user_request, requested_language) if match_result: selected_story, detected_language, metadata_entry = match_result + # Extract category from selected_story path (e.g., "Bedtime\A Golden Gift.mp3" -> "Bedtime") + story_category = 'unknown' + if selected_story and ('/' in selected_story or '\\' in selected_story): + # Handle both forward and backslash separators + path_parts = selected_story.replace('\\', '/').split('/') + if len(path_parts) >= 2: + story_category = path_parts[0] + match_info = { 'method': 'ai_multilingual', - 'language': detected_language, + 'language': 'english', # Stories are in English 'title': metadata_entry.get('romanized', 'Unknown'), 'original_title': list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[ list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry) ] if detected_language in STORY_MULTILINGUAL_MATCHER.metadata_cache else 'Unknown', - 'category': 'unknown' + 'category': detected_language.capitalize() if detected_language else story_category # Use detected_language which is actually the category folder } conn.logger.bind(tag=TAG).info(f"AI story match found: {selected_story} ({detected_language})") except Exception as e: @@ -284,11 +1260,18 @@ async def handle_multilingual_story_command(conn, user_request: str, story_type: if language_content: selected_path, metadata_entry = random.choice(language_content) selected_story = selected_path + # Extract category from selected_story path + story_category = 'unknown' + if selected_story and ('/' in selected_story or '\\' in selected_story): + path_parts = selected_story.replace('\\', '/').split('/') + if len(path_parts) >= 2: + story_category = path_parts[0] + match_info = { 'method': 'language_random', 'language': requested_language, 'title': metadata_entry.get('romanized', 'Unknown'), - 'category': 'unknown' + 'category': story_category } conn.logger.bind(tag=TAG).info(f"Language-specific story selection: {selected_story}") except Exception as e: @@ -322,6 +1305,21 @@ async def handle_multilingual_story_command(conn, user_request: str, story_type: } conn.logger.bind(tag=TAG).info(f"Legacy fuzzy story match: {selected_story}") + # SMART FALLBACK: Try specific story matching even for "random" requests that might contain story names + # This handles cases where LLM misclassifies specific story requests as random + if not selected_story and story_type != "specific": + # Check if the request might contain a specific story name by trying fuzzy matching + story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"]) + if story_name_match: + selected_story = story_name_match + match_info = { + 'method': 'smart_fallback_fuzzy', + 'language': 'english', + 'title': os.path.splitext(os.path.basename(selected_story))[0], + 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' + } + conn.logger.bind(tag=TAG).info(f"Smart fallback story match (LLM misclassified): {selected_story}") + # Final fallback to random selection if not selected_story and STORY_CACHE["all_story_files"]: selected_story = random.choice(STORY_CACHE["all_story_files"]) @@ -341,27 +1339,54 @@ async def handle_multilingual_story_command(conn, user_request: str, story_type: await send_stt_message(conn, "Sorry, I couldn't find any stories to play.") async def play_multilingual_story(conn, selected_story: str, match_info: dict, original_request: str): - """Play selected story with contextual introduction""" + """Play selected story with contextual introduction - CDN STREAMING VERSION""" global STORY_CACHE try: - # Ensure path correctness - if not os.path.isabs(selected_story): - story_path = os.path.join(STORY_CACHE["story_dir"], selected_story) + # Extract category and filename from selected_story path + # selected_story format: "Fantasy/story.mp3" or "Adventure/story.mp3" or "Bedtime\story.mp3" + # Handle both forward slash and backslash separators + normalized_path = selected_story.replace('\\', '/') + path_parts = normalized_path.split('/') + if len(path_parts) >= 2: + category = path_parts[0] + filename = path_parts[1] else: - story_path = selected_story + # Fallback: try to get from match_info + category = match_info.get('category', 'Fantasy') + filename = os.path.basename(selected_story) - if not os.path.exists(story_path): - conn.logger.bind(tag=TAG).error(f"Selected story file does not exist: {story_path}") + # Generate CDN streaming URL + conn.logger.bind(tag=TAG).info(f"Generating CDN URL for story: category='{category}', filename='{filename}', original_path='{selected_story}'") + + # Generate CDN streaming URL + cdn_url = generate_cdn_story_url(category, filename) + + if not cdn_url: + conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}") + await send_stt_message(conn, "Sorry, I couldn't access the story file.") + return + + # CRITICAL CHANGE: Download from CDN to local file first + local_file_path = await download_cdn_file(cdn_url, conn) + if not local_file_path: + conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}") + await send_stt_message(conn, "Sorry, I couldn't download the story file.") return # Generate contextual introduction based on match info intro_text = generate_multilingual_story_intro(match_info, original_request) + # Set client_is_speaking flag to prevent VAD during story playback + conn.client_is_speaking = True + # Set llm_finish_task to ensure "stop" message is sent when story finishes + conn.llm_finish_task = True + conn.logger.bind(tag=TAG).info("Story 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( @@ -380,28 +1405,29 @@ async def play_multilingual_story(conn, selected_story: 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=story_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 story: {story_path}") + conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}") except Exception as e: - conn.logger.bind(tag=TAG).error(f"Failed to play multilingual story: {str(e)}") + conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}") conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}") def generate_multilingual_story_intro(match_info: dict, original_request: str) -> str: @@ -465,16 +1491,44 @@ def generate_multilingual_story_intro(match_info: dict, original_request: str) - def find_best_story_match(story_name, story_files): - """Find the best matching story from available files""" + """Find the best matching story from available files with enhanced matching""" best_match = None - highest_ratio = 0 + highest_score = 0 + + # Clean and normalize the input story name + clean_story_name = story_name.lower().strip() + # Remove common story words that don't help with matching + story_words_to_remove = ['story', 'tale', 'a', 'the', 'play', 'tell', 'me'] + story_name_words = [word for word in clean_story_name.split() if word not in story_words_to_remove] for story_file in story_files: # Extract just the filename without path and extension - file_name = os.path.splitext(os.path.basename(story_file))[0] - ratio = difflib.SequenceMatcher(None, story_name.lower(), file_name.lower()).ratio() - if ratio > highest_ratio and ratio > 0.5: # Higher threshold for stories - highest_ratio = ratio + file_name = os.path.splitext(os.path.basename(story_file))[0].lower() + file_name_words = file_name.split() + + # Method 1: Direct sequence matching (existing approach) + sequence_ratio = difflib.SequenceMatcher(None, clean_story_name, file_name).ratio() + + # Method 2: Word-based matching - check how many words match + word_match_score = 0 + if story_name_words: + matching_words = 0 + for word in story_name_words: + if any(word in file_word for file_word in file_name_words): + matching_words += 1 + word_match_score = matching_words / len(story_name_words) + + # Method 3: Partial string matching - check if story name is contained in filename + containment_score = 0 + if clean_story_name in file_name or file_name in clean_story_name: + containment_score = 0.8 + + # Combine scores with weights + combined_score = (sequence_ratio * 0.4) + (word_match_score * 0.4) + (containment_score * 0.2) + + # Lower threshold but use combined scoring for better matches + if combined_score > highest_score and combined_score > 0.3: + highest_score = combined_score best_match = story_file return best_match @@ -575,20 +1629,48 @@ def get_story_intro(story_file, requested_language=None): async def play_story_file(conn, story_file, requested_language=None): - """Play the selected story file""" + """Play the selected story file - CDN STREAMING VERSION""" try: - story_path = os.path.join(STORY_CACHE["story_dir"], story_file) + # Extract category and filename from story_file path + # Handle both forward slash and backslash separators + normalized_path = story_file.replace('\\', '/') + path_parts = normalized_path.split('/') + if len(path_parts) >= 2: + category = path_parts[0] + filename = path_parts[1] + else: + # Fallback + category = "Fantasy" + filename = os.path.basename(story_file) + + # Generate CDN streaming URL + cdn_url = generate_cdn_story_url(category, filename) - if not os.path.exists(story_path): - conn.logger.bind(tag=TAG).error(f"Story file does not exist: {story_path}") + if not cdn_url: + conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}") + await send_stt_message(conn, "Sorry, I couldn't access the story file.") + return + + # CRITICAL CHANGE: Download from CDN to local file first + local_file_path = await download_cdn_file(cdn_url, conn) + if not local_file_path: + conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}") + await send_stt_message(conn, "Sorry, I couldn't download the story file.") return # Generate and send introduction (always in English) intro_text = get_story_intro(story_file, requested_language) + + # Set client_is_speaking flag to prevent VAD during story playback + conn.client_is_speaking = True + # Set llm_finish_task to ensure "stop" message is sent when story finishes + conn.llm_finish_task = True + conn.logger.bind(tag=TAG).info("Story playbook started - pausing audio listening to prevent interruption") + await send_stt_message(conn, intro_text) conn.dialogue.put(Message(role="assistant", content=intro_text)) - # Send TTS messages to play the story + # Send TTS messages to play the story from CDN if conn.intent_type == "intent_llm": conn.tts.tts_text_queue.put( TTSMessageDTO( @@ -607,26 +1689,27 @@ async def play_story_file(conn, story_file, requested_language=None): ) ) + # 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=story_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 story: {story_path}") + conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}") except Exception as e: - conn.logger.bind(tag=TAG).error(f"Failed to play story: {str(e)}") + conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}") conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}") \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/utils/multilingual_matcher.py b/main/xiaozhi-server/plugins_func/utils/multilingual_matcher.py index 59ebb5ae6..7e5412cbc 100644 --- a/main/xiaozhi-server/plugins_func/utils/multilingual_matcher.py +++ b/main/xiaozhi-server/plugins_func/utils/multilingual_matcher.py @@ -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 diff --git a/main/xiaozhi-server/simple_s3_test.py b/main/xiaozhi-server/simple_s3_test.py new file mode 100644 index 000000000..c7c6fa6ac --- /dev/null +++ b/main/xiaozhi-server/simple_s3_test.py @@ -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() \ No newline at end of file diff --git a/main/xiaozhi-server/stories/Adventure/Sherlock Holmes The Mystery of the Missing Colors.mp3 b/main/xiaozhi-server/stories/Adventure/Sherlock Holmes The Mystery of the Missing Colors.mp3 deleted file mode 100644 index 33b65c355..000000000 Binary files a/main/xiaozhi-server/stories/Adventure/Sherlock Holmes The Mystery of the Missing Colors.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Adventure/The Boy Who Cried Wolf.mp3 b/main/xiaozhi-server/stories/Adventure/The Boy Who Cried Wolf.mp3 deleted file mode 100644 index 21328175b..000000000 Binary files a/main/xiaozhi-server/stories/Adventure/The Boy Who Cried Wolf.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Adventure/The Enchanted Adventure.mp3 b/main/xiaozhi-server/stories/Adventure/The Enchanted Adventure.mp3 deleted file mode 100644 index adbc717ba..000000000 Binary files a/main/xiaozhi-server/stories/Adventure/The Enchanted Adventure.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Adventure/Twinkle and Glimmer's Adventure.mp3 b/main/xiaozhi-server/stories/Adventure/Twinkle and Glimmer's Adventure.mp3 deleted file mode 100644 index 501f5c6bb..000000000 Binary files a/main/xiaozhi-server/stories/Adventure/Twinkle and Glimmer's Adventure.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Bedtime/A Golden Gift.mp3 b/main/xiaozhi-server/stories/Bedtime/A Golden Gift.mp3 deleted file mode 100644 index ec822b2bb..000000000 Binary files a/main/xiaozhi-server/stories/Bedtime/A Golden Gift.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Bedtime/BEANS MAKE YOU FAST.mp3 b/main/xiaozhi-server/stories/Bedtime/BEANS MAKE YOU FAST.mp3 deleted file mode 100644 index e751cc062..000000000 Binary files a/main/xiaozhi-server/stories/Bedtime/BEANS MAKE YOU FAST.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Bedtime/Invincible Warrior.mp3 b/main/xiaozhi-server/stories/Bedtime/Invincible Warrior.mp3 deleted file mode 100644 index b756e880d..000000000 Binary files a/main/xiaozhi-server/stories/Bedtime/Invincible Warrior.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Bedtime/honest jack.mp3 b/main/xiaozhi-server/stories/Bedtime/honest jack.mp3 deleted file mode 100644 index a007e6211..000000000 Binary files a/main/xiaozhi-server/stories/Bedtime/honest jack.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Bedtime/princesspea-shorter.mp3 b/main/xiaozhi-server/stories/Bedtime/princesspea-shorter.mp3 deleted file mode 100644 index 76d877c3e..000000000 Binary files a/main/xiaozhi-server/stories/Bedtime/princesspea-shorter.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Educational/My Little Sister Taught Me Patience.mp3 b/main/xiaozhi-server/stories/Educational/My Little Sister Taught Me Patience.mp3 deleted file mode 100644 index fac4fa80d..000000000 Binary files a/main/xiaozhi-server/stories/Educational/My Little Sister Taught Me Patience.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Educational/THE WISE CHILD.mp3 b/main/xiaozhi-server/stories/Educational/THE WISE CHILD.mp3 deleted file mode 100644 index f5bc1b9aa..000000000 Binary files a/main/xiaozhi-server/stories/Educational/THE WISE CHILD.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Educational/The Arrogant Rose.mp3 b/main/xiaozhi-server/stories/Educational/The Arrogant Rose.mp3 deleted file mode 100644 index a22e3baaf..000000000 Binary files a/main/xiaozhi-server/stories/Educational/The Arrogant Rose.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Educational/The Magic Of Sharing.mp3 b/main/xiaozhi-server/stories/Educational/The Magic Of Sharing.mp3 deleted file mode 100644 index 3362b7969..000000000 Binary files a/main/xiaozhi-server/stories/Educational/The Magic Of Sharing.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Educational/The Secret of the Wooden Box Stories.mp3 b/main/xiaozhi-server/stories/Educational/The Secret of the Wooden Box Stories.mp3 deleted file mode 100644 index 6d2b04848..000000000 Binary files a/main/xiaozhi-server/stories/Educational/The Secret of the Wooden Box Stories.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Educational/Two Lazy Brothers.mp3 b/main/xiaozhi-server/stories/Educational/Two Lazy Brothers.mp3 deleted file mode 100644 index ee622ba8f..000000000 Binary files a/main/xiaozhi-server/stories/Educational/Two Lazy Brothers.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fairy Tales/THE PRINCESS AND THE SALT.mp3 b/main/xiaozhi-server/stories/Fairy Tales/THE PRINCESS AND THE SALT.mp3 deleted file mode 100644 index 559ddd943..000000000 Binary files a/main/xiaozhi-server/stories/Fairy Tales/THE PRINCESS AND THE SALT.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fairy Tales/hansel and gretel.mp3 b/main/xiaozhi-server/stories/Fairy Tales/hansel and gretel.mp3 deleted file mode 100644 index b2496d6a3..000000000 Binary files a/main/xiaozhi-server/stories/Fairy Tales/hansel and gretel.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fairy Tales/leap frog.mp3 b/main/xiaozhi-server/stories/Fairy Tales/leap frog.mp3 deleted file mode 100644 index bb5df322f..000000000 Binary files a/main/xiaozhi-server/stories/Fairy Tales/leap frog.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fairy Tales/snow white shorter.mp3 b/main/xiaozhi-server/stories/Fairy Tales/snow white shorter.mp3 deleted file mode 100644 index b0549ca85..000000000 Binary files a/main/xiaozhi-server/stories/Fairy Tales/snow white shorter.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fantasy/The Wind and the Sun.mp3 b/main/xiaozhi-server/stories/Fantasy/The Wind and the Sun.mp3 deleted file mode 100644 index 8d4316be2..000000000 Binary files a/main/xiaozhi-server/stories/Fantasy/The Wind and the Sun.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fantasy/emperor new clothes.mp3 b/main/xiaozhi-server/stories/Fantasy/emperor new clothes.mp3 deleted file mode 100644 index 7a9dfed2f..000000000 Binary files a/main/xiaozhi-server/stories/Fantasy/emperor new clothes.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fantasy/king of apes.mp3 b/main/xiaozhi-server/stories/Fantasy/king of apes.mp3 deleted file mode 100644 index 42dc9d866..000000000 Binary files a/main/xiaozhi-server/stories/Fantasy/king of apes.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/stories/Fantasy/thrushbeard.mp3 b/main/xiaozhi-server/stories/Fantasy/thrushbeard.mp3 deleted file mode 100644 index 640b38d2f..000000000 Binary files a/main/xiaozhi-server/stories/Fantasy/thrushbeard.mp3 and /dev/null differ diff --git a/main/xiaozhi-server/test_cdn_config.py b/main/xiaozhi-server/test_cdn_config.py new file mode 100644 index 000000000..f3031512f --- /dev/null +++ b/main/xiaozhi-server/test_cdn_config.py @@ -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) \ No newline at end of file diff --git a/main/xiaozhi-server/test_s3_access.py b/main/xiaozhi-server/test_s3_access.py new file mode 100644 index 000000000..01878ec76 --- /dev/null +++ b/main/xiaozhi-server/test_s3_access.py @@ -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() \ No newline at end of file diff --git a/main/xiaozhi-server/utils/cdn_helper.py b/main/xiaozhi-server/utils/cdn_helper.py new file mode 100644 index 000000000..f6e9c12eb --- /dev/null +++ b/main/xiaozhi-server/utils/cdn_helper.py @@ -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() \ No newline at end of file