From 3371c45608b492c8ffe958dd44cfe4188ccfb5f0 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Mon, 18 Aug 2025 13:09:04 +0530 Subject: [PATCH] fix: Improve ASR accuracy and eliminate phantom transcripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix audio length calculation to use WAV file metadata instead of PCM estimation - Implement comprehensive ASR logging system (CSV, JSON, TXT formats) - Disable audio file deletion for easier debugging - Add audio buffer clearing when VAD states reset - Implement echo suppression (100ms) to prevent speaker audio feedback - Add stale audio detection to skip leftover chunks after TTS - Clear ASR audio queue on VAD reset to prevent processing queued chunks - Add timestamp tracking for listen start events - Fix undefined send_initial_greeting function error │ │ These changes eliminate phantom transcripts like 'SHE', 'UP' that occurred when echo from the device's speaker was picked up by the microphone. --- main/xiaozhi-server/core/connection.py | 2276 ++++++++--------- .../xiaozhi-server/core/handle/helloHandle.py | 300 +-- main/xiaozhi-server/core/handle/textHandle.py | 374 +-- .../xiaozhi-server/core/providers/asr/base.py | 761 +++--- .../core/providers/asr/sherpa_onnx_local.py | 768 +++--- 5 files changed, 2245 insertions(+), 2234 deletions(-) diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index be482fbf9..82f1c67f6 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1,1138 +1,1138 @@ -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 - - # 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: - # Use a thread pool to save memory asynchronously - def save_memory_task(): - try: - # Create a new event loop (to avoid conflicts with the main loop) - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - loop.run_until_complete( - self.memory.save_memory(self.dialogue.dialogue) - ) - except Exception as e: - self.logger.bind(tag=TAG).error( - f"Failed to save memory: {e}") - finally: - try: - loop.close() - except Exception: - pass - - # Start a thread to save memory, do not wait for completion - 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)) - 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" - ] - # If using nomem, return directly - if memory_type == "nomem": - return - # Use mem_local_short mode - elif memory_type == "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 intent recognition model") - - 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}") - 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 - # 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).debug("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 +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 + + # 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: + # Use a thread pool to save memory asynchronously + def save_memory_task(): + try: + # Create a new event loop (to avoid conflicts with the main loop) + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.run_until_complete( + self.memory.save_memory(self.dialogue.dialogue) + ) + except Exception as e: + self.logger.bind(tag=TAG).error( + f"Failed to save memory: {e}") + finally: + try: + loop.close() + except Exception: + pass + + # Start a thread to save memory, do not wait for completion + 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)) + 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" + ] + # If using nomem, return directly + if memory_type == "nomem": + return + # Use mem_local_short mode + elif memory_type == "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 intent recognition model") + + 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}") + 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 + # 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).debug("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") diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 17a4b3973..f14018cdc 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -1,150 +1,150 @@ -import time -import json -import random -import asyncio -from core.utils.dialogue import Message -from core.utils.util import audio_to_data -from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message -from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes -from core.providers.tts.dto.dto import ContentType, SentenceType -from core.providers.tools.device_mcp import ( - MCPClient, - send_mcp_initialize_message, - send_mcp_tools_list_request, -) -from core.utils.wakeup_word import WakeupWordsConfig - -TAG = __name__ - -WAKEUP_CONFIG = { - "refresh_time": 5, - "words": ["你好", "你好啊", "嘿,你好", "嗨"], -} - -# Create global wakeup words configuration manager -wakeup_words_config = WakeupWordsConfig() - -# Lock to prevent concurrent calls to wakeupWordsResponse -_wakeup_response_lock = asyncio.Lock() - - -async def handleHelloMessage(conn, msg_json): - """Handle hello message""" - audio_params = msg_json.get("audio_params") - if audio_params: - format = audio_params.get("format") - conn.logger.bind(tag=TAG).info(f"Client audio format: {format}") - conn.audio_format = format - conn.welcome_msg["audio_params"] = audio_params - features = msg_json.get("features") - if features: - conn.logger.bind(tag=TAG).info(f"Client features: {features}") - conn.features = features - - # Handle both list and dictionary formats for features - has_mcp = False - if isinstance(features, list): - has_mcp = "mcp" in features - elif isinstance(features, dict): - has_mcp = features.get("mcp", False) - - if has_mcp: - conn.logger.bind(tag=TAG).info("Client supports MCP") - conn.mcp_client = MCPClient() - # Send initialization - asyncio.create_task(send_mcp_initialize_message(conn)) - # Send mcp message to get tools list - asyncio.create_task(send_mcp_tools_list_request(conn)) - - await conn.websocket.send(json.dumps(conn.welcome_msg)) - - -async def checkWakeupWords(conn, text): - enable_wakeup_words_response_cache = conn.config[ - "enable_wakeup_words_response_cache" - ] - - if not enable_wakeup_words_response_cache or not conn.tts: - return False - - _, filtered_text = remove_punctuation_and_length(text) - if filtered_text not in conn.config.get("wakeup_words"): - return False - - conn.just_woken_up = True - await send_stt_message(conn, text) - - # Get current voice - voice = getattr(conn.tts, "voice", "default") - if not voice: - voice = "default" - - # Get wakeup words reply configuration - response = wakeup_words_config.get_wakeup_response(voice) - if not response or not response.get("file_path"): - response = { - "voice": "default", - "file_path": "config/assets/wakeup_words.wav", - "time": 0, - "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦", - } - - # Play wakeup words reply - conn.client_abort = False - opus_packets, _ = audio_to_data(response.get("file_path")) - - conn.logger.bind(tag=TAG).info( - f"Playing wakeup words reply: {response.get('text')}") - await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text")) - await sendAudioMessage(conn, SentenceType.LAST, [], None) - - # Add to dialogue - conn.dialogue.put(Message(role="assistant", content=response.get("text"))) - - # Check if wakeup words reply needs to be updated - if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: - if not _wakeup_response_lock.locked(): - asyncio.create_task(wakeupWordsResponse(conn)) - return True - - -async def wakeupWordsResponse(conn): - if not conn.tts or not conn.llm or not conn.llm.response_no_stream: - return - - try: - # Try to acquire lock, return if cannot acquire - if not await _wakeup_response_lock.acquire(): - return - - # Generate wakeup words reply - wakeup_word = random.choice(WAKEUP_CONFIG["words"]) - question = ( - "The user is currently saying ```" - + wakeup_word - + "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n" - + "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content." - ) - - result = conn.llm.response_no_stream(conn.config["prompt"], question) - if not result or len(result) == 0: - return - - # Generate TTS audio - tts_result = await asyncio.to_thread(conn.tts.to_tts, result) - if not tts_result: - return - - # Get current voice - voice = getattr(conn.tts, "voice", "default") - - wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000) - file_path = wakeup_words_config.generate_file_path(voice) - with open(file_path, "wb") as f: - f.write(wav_bytes) - # Update configuration - wakeup_words_config.update_wakeup_response(voice, file_path, result) - finally: - # Ensure lock is released in any case - if _wakeup_response_lock.locked(): - _wakeup_response_lock.release() +import time +import json +import random +import asyncio +from core.utils.dialogue import Message +from core.utils.util import audio_to_data +from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message +from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes +from core.providers.tts.dto.dto import ContentType, SentenceType +from core.providers.tools.device_mcp import ( + MCPClient, + send_mcp_initialize_message, + send_mcp_tools_list_request, +) +from core.utils.wakeup_word import WakeupWordsConfig + +TAG = __name__ + +WAKEUP_CONFIG = { + "refresh_time": 5, + "words": ["你好", "你好啊", "嘿,你好", "嗨"], +} + +# Create global wakeup words configuration manager +wakeup_words_config = WakeupWordsConfig() + +# Lock to prevent concurrent calls to wakeupWordsResponse +_wakeup_response_lock = asyncio.Lock() + + +async def handleHelloMessage(conn, msg_json): + """Handle hello message""" + audio_params = msg_json.get("audio_params") + if audio_params: + format = audio_params.get("format") + conn.logger.bind(tag=TAG).info(f"Client audio format: {format}") + conn.audio_format = format + conn.welcome_msg["audio_params"] = audio_params + features = msg_json.get("features") + if features: + conn.logger.bind(tag=TAG).info(f"Client features: {features}") + conn.features = features + + # Handle both list and dictionary formats for features + has_mcp = False + if isinstance(features, list): + has_mcp = "mcp" in features + elif isinstance(features, dict): + has_mcp = features.get("mcp", False) + + if has_mcp: + conn.logger.bind(tag=TAG).info("Client supports MCP") + conn.mcp_client = MCPClient() + # Send initialization + asyncio.create_task(send_mcp_initialize_message(conn)) + # Send mcp message to get tools list + asyncio.create_task(send_mcp_tools_list_request(conn)) + + await conn.websocket.send(json.dumps(conn.welcome_msg)) + + +async def checkWakeupWords(conn, text): + enable_wakeup_words_response_cache = conn.config[ + "enable_wakeup_words_response_cache" + ] + + if not enable_wakeup_words_response_cache or not conn.tts: + return False + + _, filtered_text = remove_punctuation_and_length(text) + if filtered_text not in conn.config.get("wakeup_words"): + return False + + conn.just_woken_up = True + await send_stt_message(conn, text) + + # Get current voice + voice = getattr(conn.tts, "voice", "default") + if not voice: + voice = "default" + + # Get wakeup words reply configuration + response = wakeup_words_config.get_wakeup_response(voice) + if not response or not response.get("file_path"): + response = { + "voice": "default", + "file_path": "config/assets/wakeup_words.wav", + "time": 0, + "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦", + } + + # Play wakeup words reply + conn.client_abort = False + opus_packets, _ = audio_to_data(response.get("file_path")) + + conn.logger.bind(tag=TAG).info( + f"Playing wakeup words reply: {response.get('text')}") + await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text")) + await sendAudioMessage(conn, SentenceType.LAST, [], None) + + # Add to dialogue + conn.dialogue.put(Message(role="assistant", content=response.get("text"))) + + # Check if wakeup words reply needs to be updated + if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: + if not _wakeup_response_lock.locked(): + asyncio.create_task(wakeupWordsResponse(conn)) + return True + + +async def wakeupWordsResponse(conn): + if not conn.tts or not conn.llm or not conn.llm.response_no_stream: + return + + try: + # Try to acquire lock, return if cannot acquire + if not await _wakeup_response_lock.acquire(): + return + + # Generate wakeup words reply + wakeup_word = random.choice(WAKEUP_CONFIG["words"]) + question = ( + "The user is currently saying ```" + + wakeup_word + + "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n" + + "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content." + ) + + result = conn.llm.response_no_stream(conn.config["prompt"], question) + if not result or len(result) == 0: + return + + # Generate TTS audio + tts_result = await asyncio.to_thread(conn.tts.to_tts, result) + if not tts_result: + return + + # Get current voice + voice = getattr(conn.tts, "voice", "default") + + wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000) + file_path = wakeup_words_config.generate_file_path(voice) + with open(file_path, "wb") as f: + f.write(wav_bytes) + # Update configuration + wakeup_words_config.update_wakeup_response(voice, file_path, result) + finally: + # Ensure lock is released in any case + if _wakeup_response_lock.locked(): + _wakeup_response_lock.release() diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index 22e397938..6874c3e05 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -1,186 +1,188 @@ -import json -import time -from core.handle.abortHandle import handleAbortMessage -from core.handle.helloHandle import handleHelloMessage -from core.providers.tools.device_mcp import handle_mcp_message -from core.utils.util import remove_punctuation_and_length, filter_sensitive_info -from core.handle.receiveAudioHandle import startToChat, handleAudioMessage -from core.handle.sendAudioHandle import send_stt_message, send_tts_message -from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus -from core.handle.reportHandle import enqueue_asr_report -import asyncio - -TAG = __name__ - - -async def handleTextMessage(conn, message): - """Handle text messages""" - try: - msg_json = json.loads(message) - if isinstance(msg_json, int): - conn.logger.bind(tag=TAG).info(f"Received text message: {message}") - await conn.websocket.send(message) - return - if msg_json["type"] == "hello": - conn.logger.bind(tag=TAG).info( - f"Received hello message: {message}") - await handleHelloMessage(conn, msg_json) - elif msg_json["type"] == "abort": - conn.logger.bind(tag=TAG).info( - f"Received abort message: {message}") - await handleAbortMessage(conn) - elif msg_json["type"] == "listen": - conn.logger.bind(tag=TAG).info( - f"Received listen message: {message}") - if "mode" in msg_json: - conn.client_listen_mode = msg_json["mode"] - conn.logger.bind(tag=TAG).debug( - f"Client audio capture mode: {conn.client_listen_mode}" - ) - if msg_json["state"] == "start": - # Reset VAD states to clear any leftover audio from previous session - conn.reset_vad_states() - # Mark that we just started listening to prevent processing stale audio - conn.just_started_listening = True - # Add initial connection flag to prevent false positive on first audio - if not hasattr(conn, "initial_connection_handled"): - conn.initial_connection_handled = False - conn.initial_connection_time = asyncio.get_event_loop().time() - conn.client_have_voice = True - conn.client_voice_stop = False - elif msg_json["state"] == "stop": - conn.client_have_voice = True - conn.client_voice_stop = True - if len(conn.asr_audio) > 0: - await handleAudioMessage(conn, b"") - elif msg_json["state"] == "detect": - conn.client_have_voice = False - conn.asr_audio.clear() - if "text" in msg_json: - conn.last_activity_time = time.time() * 1000 - original_text = msg_json["text"] # Preserve original text - filtered_len, filtered_text = remove_punctuation_and_length( - original_text - ) - - # Identify if it's a wake-up word - is_wakeup_words = filtered_text in conn.config.get( - "wakeup_words") - # Whether wake-up word reply is enabled - enable_greeting = conn.config.get("enable_greeting", True) - - if is_wakeup_words and not enable_greeting: - # If it's a wake-up word and wake-up word reply is disabled, no need to respond - await send_stt_message(conn, original_text) - await send_tts_message(conn, "stop", None) - conn.client_is_speaking = False - elif is_wakeup_words: - conn.just_woken_up = True - # Report plain text data (reuse ASR reporting function, but provide no audio data) - enqueue_asr_report(conn, "Hey, hello there", []) - await startToChat(conn, "Hey, hello there") - else: - # Report plain text data (reuse ASR reporting function, but provide no audio data) - enqueue_asr_report(conn, original_text, []) - # Otherwise, need LLM to respond to text content - await startToChat(conn, original_text) - elif msg_json["type"] == "iot": - conn.logger.bind(tag=TAG).info(f"Received iot message: {message}") - if "descriptors" in msg_json: - asyncio.create_task(handleIotDescriptors( - conn, msg_json["descriptors"])) - if "states" in msg_json: - asyncio.create_task(handleIotStatus(conn, msg_json["states"])) - elif msg_json["type"] == "mcp": - conn.logger.bind(tag=TAG).info( - f"Received mcp message: {message[:100]}") - if "payload" in msg_json: - asyncio.create_task( - handle_mcp_message(conn, conn.mcp_client, - msg_json["payload"]) - ) - elif msg_json["type"] == "server": - # Filter sensitive information when logging - conn.logger.bind(tag=TAG).info( - f"Received server message: {filter_sensitive_info(msg_json)}" - ) - # If configuration is read from API, need to verify secret - if not conn.read_config_from_api: - return - # Get secret from post request - post_secret = msg_json.get("content", {}).get("secret", "") - secret = conn.config["manager-api"].get("secret", "") - # If secret doesn't match, return - if post_secret != secret: - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": "Server secret verification failed", - } - ) - ) - return - # Dynamically update configuration - if msg_json["action"] == "update_config": - try: - # Update WebSocketServer configuration - if not conn.server: - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": "Cannot get server instance", - "content": {"action": "update_config"}, - } - ) - ) - return - - if not await conn.server.update_config(): - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": "Failed to update server configuration", - "content": {"action": "update_config"}, - } - ) - ) - return - - # Send success response - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "success", - "message": "Configuration updated successfully", - "content": {"action": "update_config"}, - } - ) - ) - except Exception as e: - conn.logger.bind(tag=TAG).error( - f"Failed to update configuration: {str(e)}") - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": f"Failed to update configuration: {str(e)}", - "content": {"action": "update_config"}, - } - ) - ) - # Restart server - elif msg_json["action"] == "restart": - await conn.handle_restart(msg_json) - else: - conn.logger.bind(tag=TAG).error( - f"Received unknown type message: {message}") - except json.JSONDecodeError: - await conn.websocket.send(message) +import json +import time +from core.handle.abortHandle import handleAbortMessage +from core.handle.helloHandle import handleHelloMessage +from core.providers.tools.device_mcp import handle_mcp_message +from core.utils.util import remove_punctuation_and_length, filter_sensitive_info +from core.handle.receiveAudioHandle import startToChat, handleAudioMessage +from core.handle.sendAudioHandle import send_stt_message, send_tts_message +from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus +from core.handle.reportHandle import enqueue_asr_report +import asyncio + +TAG = __name__ + + +async def handleTextMessage(conn, message): + """Handle text messages""" + try: + msg_json = json.loads(message) + if isinstance(msg_json, int): + conn.logger.bind(tag=TAG).info(f"Received text message: {message}") + await conn.websocket.send(message) + return + if msg_json["type"] == "hello": + conn.logger.bind(tag=TAG).info( + f"Received hello message: {message}") + await handleHelloMessage(conn, msg_json) + elif msg_json["type"] == "abort": + conn.logger.bind(tag=TAG).info( + f"Received abort message: {message}") + await handleAbortMessage(conn) + elif msg_json["type"] == "listen": + conn.logger.bind(tag=TAG).info( + f"Received listen message: {message}") + if "mode" in msg_json: + conn.client_listen_mode = msg_json["mode"] + conn.logger.bind(tag=TAG).debug( + f"Client audio capture mode: {conn.client_listen_mode}" + ) + if msg_json["state"] == "start": + # Reset VAD states to clear any leftover audio from previous session + conn.reset_vad_states() + # Mark that we just started listening to prevent processing stale audio + conn.just_started_listening = True + # Set a timestamp for when we started listening + conn.listen_start_time = time.time() + # Add initial connection flag to prevent false positive on first audio + if not hasattr(conn, "initial_connection_handled"): + conn.initial_connection_handled = False + conn.initial_connection_time = asyncio.get_event_loop().time() + conn.client_have_voice = True + conn.client_voice_stop = False + elif msg_json["state"] == "stop": + conn.client_have_voice = True + conn.client_voice_stop = True + if len(conn.asr_audio) > 0: + await handleAudioMessage(conn, b"") + elif msg_json["state"] == "detect": + conn.client_have_voice = False + conn.asr_audio.clear() + if "text" in msg_json: + conn.last_activity_time = time.time() * 1000 + original_text = msg_json["text"] # Preserve original text + filtered_len, filtered_text = remove_punctuation_and_length( + original_text + ) + + # Identify if it's a wake-up word + is_wakeup_words = filtered_text in conn.config.get( + "wakeup_words") + # Whether wake-up word reply is enabled + enable_greeting = conn.config.get("enable_greeting", True) + + if is_wakeup_words and not enable_greeting: + # If it's a wake-up word and wake-up word reply is disabled, no need to respond + await send_stt_message(conn, original_text) + await send_tts_message(conn, "stop", None) + conn.client_is_speaking = False + elif is_wakeup_words: + conn.just_woken_up = True + # Report plain text data (reuse ASR reporting function, but provide no audio data) + enqueue_asr_report(conn, "Hey, hello there", []) + await startToChat(conn, "Hey, hello there") + else: + # Report plain text data (reuse ASR reporting function, but provide no audio data) + enqueue_asr_report(conn, original_text, []) + # Otherwise, need LLM to respond to text content + await startToChat(conn, original_text) + elif msg_json["type"] == "iot": + conn.logger.bind(tag=TAG).info(f"Received iot message: {message}") + if "descriptors" in msg_json: + asyncio.create_task(handleIotDescriptors( + conn, msg_json["descriptors"])) + if "states" in msg_json: + asyncio.create_task(handleIotStatus(conn, msg_json["states"])) + elif msg_json["type"] == "mcp": + conn.logger.bind(tag=TAG).info( + f"Received mcp message: {message[:100]}") + if "payload" in msg_json: + asyncio.create_task( + handle_mcp_message(conn, conn.mcp_client, + msg_json["payload"]) + ) + elif msg_json["type"] == "server": + # Filter sensitive information when logging + conn.logger.bind(tag=TAG).info( + f"Received server message: {filter_sensitive_info(msg_json)}" + ) + # If configuration is read from API, need to verify secret + if not conn.read_config_from_api: + return + # Get secret from post request + post_secret = msg_json.get("content", {}).get("secret", "") + secret = conn.config["manager-api"].get("secret", "") + # If secret doesn't match, return + if post_secret != secret: + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": "Server secret verification failed", + } + ) + ) + return + # Dynamically update configuration + if msg_json["action"] == "update_config": + try: + # Update WebSocketServer configuration + if not conn.server: + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": "Cannot get server instance", + "content": {"action": "update_config"}, + } + ) + ) + return + + if not await conn.server.update_config(): + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": "Failed to update server configuration", + "content": {"action": "update_config"}, + } + ) + ) + return + + # Send success response + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "success", + "message": "Configuration updated successfully", + "content": {"action": "update_config"}, + } + ) + ) + except Exception as e: + conn.logger.bind(tag=TAG).error( + f"Failed to update configuration: {str(e)}") + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": f"Failed to update configuration: {str(e)}", + "content": {"action": "update_config"}, + } + ) + ) + # Restart server + elif msg_json["action"] == "restart": + await conn.handle_restart(msg_json) + else: + conn.logger.bind(tag=TAG).error( + f"Received unknown type message: {message}") + except json.JSONDecodeError: + await conn.websocket.send(message) diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 77e167abb..b095661ea 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -1,376 +1,385 @@ -import os -import wave -import uuid -import queue -import asyncio -import traceback -import threading -import opuslib_next -import json -import io -import time -import concurrent.futures -import csv -from datetime import datetime -from abc import ABC, abstractmethod -from config.logger import setup_logging -from typing import Optional, Tuple, List, Dict, Any -from core.handle.receiveAudioHandle import startToChat -from core.handle.reportHandle import enqueue_asr_report -from core.utils.util import remove_punctuation_and_length -from core.handle.receiveAudioHandle import handleAudioMessage - -TAG = __name__ -logger = setup_logging() - - -class ASRProviderBase(ABC): - def __init__(self): - pass - - # Open audio channels - async def open_audio_channels(self, conn): - conn.asr_priority_thread = threading.Thread( - target=self.asr_text_priority_thread, args=(conn,), daemon=True - ) - conn.asr_priority_thread.start() - - # Process ASR audio in order - def asr_text_priority_thread(self, conn): - while not conn.stop_event.is_set(): - try: - message = conn.asr_audio_queue.get(timeout=1) - future = asyncio.run_coroutine_threadsafe( - handleAudioMessage(conn, message), - conn.loop, - ) - future.result() - except queue.Empty: - continue - except Exception as e: - logger.bind(tag=TAG).error( - f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" - ) - continue - - # Receive audio - async def receive_audio(self, conn, audio, audio_have_voice): - if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime": - have_voice = audio_have_voice - else: - have_voice = conn.client_have_voice - - # Always add audio to pre-buffer (rolling buffer) - conn.audio_pre_buffer.append(audio) - - # If voice is detected and we're not already collecting - if have_voice and not conn.client_have_voice: - # Clear the just_started_listening flag when actual voice is detected - if hasattr(conn, 'just_started_listening'): - conn.just_started_listening = False - # Add pre-buffered audio to the beginning of ASR audio - conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio - conn.audio_pre_buffer.clear() - - conn.asr_audio.append(audio) - if not have_voice and not conn.client_have_voice: - conn.asr_audio = conn.asr_audio[-10:] - return - - if conn.client_voice_stop: - # Check if we just started listening - if so, skip this audio - if hasattr(conn, 'just_started_listening') and conn.just_started_listening: - logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start") - conn.just_started_listening = False - conn.asr_audio.clear() - conn.reset_vad_states() - return - - asr_audio_task = conn.asr_audio.copy() - conn.asr_audio.clear() - conn.reset_vad_states() - - if len(asr_audio_task) > 20: # Increased from 15 to 20 chunks (1.2 seconds) - logger.bind(tag=TAG).debug(f"Processing {len(asr_audio_task)} audio chunks") - await self.handle_voice_stop(conn, asr_audio_task) - - # Handle voice stop - async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): - """Parallel processing of ASR and voiceprint recognition""" - try: - total_start_time = time.monotonic() - - # Prepare audio data - if conn.audio_format == "pcm": - pcm_data = asr_audio_task - else: - pcm_data = self.decode_opus(asr_audio_task) - - combined_pcm_data = b"".join(pcm_data) - - # Pre-prepare WAV data - wav_data = None - # Use connection's voiceprint provider - if conn.voiceprint_provider and combined_pcm_data: - wav_data = self._pcm_to_wav(combined_pcm_data) - - # Define ASR task - - def run_asr(): - start_time = time.monotonic() - try: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - result = loop.run_until_complete( - self.speech_to_text( - asr_audio_task, conn.session_id, conn.audio_format) - ) - end_time = time.monotonic() - logger.bind(tag=TAG).info( - f"ASR time: {end_time - start_time:.3f}s") - return result - finally: - loop.close() - except Exception as e: - end_time = time.monotonic() - logger.bind(tag=TAG).error(f"ASR failed: {e}") - return ("", None) - - # Define voiceprint recognition task - def run_voiceprint(): - if not wav_data: - return None - try: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - # Use connection's voiceprint provider - result = loop.run_until_complete( - conn.voiceprint_provider.identify_speaker( - wav_data, conn.session_id) - ) - return result - finally: - loop.close() - except Exception as e: - logger.bind(tag=TAG).error( - f"Voiceprint recognition failed: {e}") - return None - - # Run in parallel using thread pool executor - parallel_start_time = time.monotonic() - - with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor: - asr_future = thread_executor.submit(run_asr) - - if conn.voiceprint_provider and wav_data: - voiceprint_future = thread_executor.submit(run_voiceprint) - - # Wait for both threads to complete - asr_result = asr_future.result(timeout=15) - voiceprint_result = voiceprint_future.result(timeout=15) - - results = {"asr": asr_result, - "voiceprint": voiceprint_result} - else: - asr_result = asr_future.result(timeout=15) - results = {"asr": asr_result, "voiceprint": None} - - # Process results - raw_text, file_path = results.get("asr", ("", None)) - speaker_name = results.get("voiceprint", None) - - # Log recognition results - if raw_text: - logger.bind(tag=TAG).info(f"Recognized text: {raw_text}") - if speaker_name: - logger.bind(tag=TAG).info( - f"Identified speaker: {speaker_name}") - - # Performance monitoring - total_time = time.monotonic() - total_start_time - logger.bind(tag=TAG).info( - f"Total processing time: {total_time:.3f}s") - - # Check text length - text_len, _ = remove_punctuation_and_length(raw_text) - self.stop_ws_connection() - - if text_len > 0: - # Build JSON string with speaker information - enhanced_text = self._build_enhanced_text( - raw_text, speaker_name) - - # Use custom module for reporting - await startToChat(conn, enhanced_text) - enqueue_asr_report(conn, enhanced_text, asr_audio_task) - - except Exception as e: - logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}") - import traceback - logger.bind(tag=TAG).debug( - f"Exception details: {traceback.format_exc()}") - - def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str: - """Build text with speaker information""" - if speaker_name and speaker_name.strip(): - return json.dumps({ - "speaker": speaker_name, - "content": text - }, ensure_ascii=False) - else: - return text - - def _pcm_to_wav(self, pcm_data: bytes) -> bytes: - """Convert PCM data to WAV format""" - if len(pcm_data) == 0: - logger.bind(tag=TAG).warning( - "PCM data is empty, cannot convert to WAV") - return b"" - - # Ensure data length is even (16-bit audio) - if len(pcm_data) % 2 != 0: - pcm_data = pcm_data[:-1] - - # Create WAV file header - wav_buffer = io.BytesIO() - try: - with wave.open(wav_buffer, 'wb') as wav_file: - wav_file.setnchannels(1) # Mono - wav_file.setsampwidth(2) # 16-bit - wav_file.setframerate(16000) # 16kHz sample rate - wav_file.writeframes(pcm_data) - - wav_buffer.seek(0) - wav_data = wav_buffer.read() - - return wav_data - except Exception as e: - logger.bind(tag=TAG).error(f"WAV conversion failed: {e}") - return b"" - - def stop_ws_connection(self): - pass - - def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str: - """Save PCM data as WAV file""" - module_name = __name__.split(".")[-1] - file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav" - file_path = os.path.join(self.output_dir, file_name) - - with wave.open(file_path, "wb") as wf: - wf.setnchannels(1) - wf.setsampwidth(2) # 2 bytes = 16-bit - wf.setframerate(16000) - wf.writeframes(b"".join(pcm_data)) - - return file_path - - def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str): - """Log audio file information to CSV file""" - try: - # Create logs directory at the same level as output_dir - log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs") - os.makedirs(log_dir, exist_ok=True) - - # Create both CSV and JSON log files for easy inspection - csv_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.csv") - json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json") - - # Write to CSV file - csv_exists = os.path.exists(csv_log_file) - with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile: - fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript'] - writer = csv.DictWriter(csvfile, fieldnames=fieldnames) - - if not csv_exists: - writer.writeheader() - - writer.writerow({ - 'timestamp': datetime.now().isoformat(), - 'filename': os.path.basename(file_path), - 'file_path': file_path, - 'audio_length_seconds': round(audio_length_seconds, 2), - 'transcript': transcript - }) - - # Also write to JSON file for easier parsing - log_entry = { - 'timestamp': datetime.now().isoformat(), - 'filename': os.path.basename(file_path), - 'file_path': file_path, - 'audio_length_seconds': round(audio_length_seconds, 2), - 'transcript': transcript - } - - # Read existing JSON logs or create new list - json_logs = [] - if os.path.exists(json_log_file): - try: - with open(json_log_file, 'r', encoding='utf-8') as f: - json_logs = json.load(f) - except: - json_logs = [] - - json_logs.append(log_entry) - - # Write updated JSON logs - with open(json_log_file, 'w', encoding='utf-8') as f: - json.dump(json_logs, f, ensure_ascii=False, indent=2) - - # Also create a simple text log for quick inspection - txt_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.txt") - with open(txt_log_file, 'a', encoding='utf-8') as f: - f.write(f"\n{'='*80}\n") - f.write(f"Timestamp: {datetime.now().isoformat()}\n") - f.write(f"Filename: {os.path.basename(file_path)}\n") - f.write(f"Full Path: {file_path}\n") - f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n") - f.write(f"Transcript: {transcript}\n") - f.write(f"{'='*80}\n") - - logger.bind(tag=TAG).info( - f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, " - f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..." - ) - except Exception as e: - logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}") - - @abstractmethod - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """Convert speech data to text""" - pass - - @staticmethod - def decode_opus(opus_data: List[bytes]) -> List[bytes]: - """Decode Opus audio data to PCM data""" - try: - decoder = opuslib_next.Decoder(16000, 1) - pcm_data = [] - buffer_size = 960 # Process 960 samples each time (60ms at 16kHz) - - for i, opus_packet in enumerate(opus_data): - try: - if not opus_packet or len(opus_packet) == 0: - continue - - pcm_frame = decoder.decode(opus_packet, buffer_size) - if pcm_frame and len(pcm_frame) > 0: - pcm_data.append(pcm_frame) - - except opuslib_next.OpusError as e: - logger.bind(tag=TAG).warning( - f"Opus decode error, skipping packet {i}: {e}") - except Exception as e: - logger.bind(tag=TAG).error( - f"Audio processing error, packet {i}: {e}") - - return pcm_data - - except Exception as e: - logger.bind(tag=TAG).error( - f"Error occurred during audio decoding: {e}") - return [] +import os +import wave +import uuid +import queue +import asyncio +import traceback +import threading +import opuslib_next +import json +import io +import time +import concurrent.futures +import csv +from datetime import datetime +from abc import ABC, abstractmethod +from config.logger import setup_logging +from typing import Optional, Tuple, List, Dict, Any +from core.handle.receiveAudioHandle import startToChat +from core.handle.reportHandle import enqueue_asr_report +from core.utils.util import remove_punctuation_and_length +from core.handle.receiveAudioHandle import handleAudioMessage + +TAG = __name__ +logger = setup_logging() + + +class ASRProviderBase(ABC): + def __init__(self): + pass + + # Open audio channels + async def open_audio_channels(self, conn): + conn.asr_priority_thread = threading.Thread( + target=self.asr_text_priority_thread, args=(conn,), daemon=True + ) + conn.asr_priority_thread.start() + + # Process ASR audio in order + def asr_text_priority_thread(self, conn): + while not conn.stop_event.is_set(): + try: + message = conn.asr_audio_queue.get(timeout=1) + future = asyncio.run_coroutine_threadsafe( + handleAudioMessage(conn, message), + conn.loop, + ) + future.result() + except queue.Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( + f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" + ) + continue + + # Receive audio + async def receive_audio(self, conn, audio, audio_have_voice): + if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime": + have_voice = audio_have_voice + else: + have_voice = conn.client_have_voice + + # Echo suppression: Ignore audio for a brief period after starting to listen + if hasattr(conn, 'listen_start_time'): + time_since_listen_start = time.time() - conn.listen_start_time + if time_since_listen_start < 0.1: # Ignore first 300ms of audio (echo period) + if have_voice: + logger.bind(tag=TAG).debug(f"Ignoring potential echo audio ({time_since_listen_start:.2f}s after listen start)") + have_voice = False + + # Always add audio to pre-buffer (rolling buffer) + conn.audio_pre_buffer.append(audio) + + # If voice is detected and we're not already collecting + if have_voice and not conn.client_have_voice: + # Clear the just_started_listening flag when actual voice is detected + if hasattr(conn, 'just_started_listening'): + conn.just_started_listening = False + # Add pre-buffered audio to the beginning of ASR audio + conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio + conn.audio_pre_buffer.clear() + + conn.asr_audio.append(audio) + if not have_voice and not conn.client_have_voice: + conn.asr_audio = conn.asr_audio[-10:] + return + + if conn.client_voice_stop: + # Check if we just started listening - if so, skip this audio + if hasattr(conn, 'just_started_listening') and conn.just_started_listening: + logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start") + conn.just_started_listening = False + conn.asr_audio.clear() + conn.reset_vad_states() + return + + asr_audio_task = conn.asr_audio.copy() + conn.asr_audio.clear() + conn.reset_vad_states() + + if len(asr_audio_task) > 20: # Increased from 15 to 20 chunks (1.2 seconds) + logger.bind(tag=TAG).debug(f"Processing {len(asr_audio_task)} audio chunks") + await self.handle_voice_stop(conn, asr_audio_task) + + # Handle voice stop + async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): + """Parallel processing of ASR and voiceprint recognition""" + try: + total_start_time = time.monotonic() + + # Prepare audio data + if conn.audio_format == "pcm": + pcm_data = asr_audio_task + else: + pcm_data = self.decode_opus(asr_audio_task) + + combined_pcm_data = b"".join(pcm_data) + + # Pre-prepare WAV data + wav_data = None + # Use connection's voiceprint provider + if conn.voiceprint_provider and combined_pcm_data: + wav_data = self._pcm_to_wav(combined_pcm_data) + + # Define ASR task + + def run_asr(): + start_time = time.monotonic() + try: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + result = loop.run_until_complete( + self.speech_to_text( + asr_audio_task, conn.session_id, conn.audio_format) + ) + end_time = time.monotonic() + logger.bind(tag=TAG).info( + f"ASR time: {end_time - start_time:.3f}s") + return result + finally: + loop.close() + except Exception as e: + end_time = time.monotonic() + logger.bind(tag=TAG).error(f"ASR failed: {e}") + return ("", None) + + # Define voiceprint recognition task + def run_voiceprint(): + if not wav_data: + return None + try: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + # Use connection's voiceprint provider + result = loop.run_until_complete( + conn.voiceprint_provider.identify_speaker( + wav_data, conn.session_id) + ) + return result + finally: + loop.close() + except Exception as e: + logger.bind(tag=TAG).error( + f"Voiceprint recognition failed: {e}") + return None + + # Run in parallel using thread pool executor + parallel_start_time = time.monotonic() + + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor: + asr_future = thread_executor.submit(run_asr) + + if conn.voiceprint_provider and wav_data: + voiceprint_future = thread_executor.submit(run_voiceprint) + + # Wait for both threads to complete + asr_result = asr_future.result(timeout=15) + voiceprint_result = voiceprint_future.result(timeout=15) + + results = {"asr": asr_result, + "voiceprint": voiceprint_result} + else: + asr_result = asr_future.result(timeout=15) + results = {"asr": asr_result, "voiceprint": None} + + # Process results + raw_text, file_path = results.get("asr", ("", None)) + speaker_name = results.get("voiceprint", None) + + # Log recognition results + if raw_text: + logger.bind(tag=TAG).info(f"Recognized text: {raw_text}") + if speaker_name: + logger.bind(tag=TAG).info( + f"Identified speaker: {speaker_name}") + + # Performance monitoring + total_time = time.monotonic() - total_start_time + logger.bind(tag=TAG).info( + f"Total processing time: {total_time:.3f}s") + + # Check text length + text_len, _ = remove_punctuation_and_length(raw_text) + self.stop_ws_connection() + + if text_len > 0: + # Build JSON string with speaker information + enhanced_text = self._build_enhanced_text( + raw_text, speaker_name) + + # Use custom module for reporting + await startToChat(conn, enhanced_text) + enqueue_asr_report(conn, enhanced_text, asr_audio_task) + + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}") + import traceback + logger.bind(tag=TAG).debug( + f"Exception details: {traceback.format_exc()}") + + def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str: + """Build text with speaker information""" + if speaker_name and speaker_name.strip(): + return json.dumps({ + "speaker": speaker_name, + "content": text + }, ensure_ascii=False) + else: + return text + + def _pcm_to_wav(self, pcm_data: bytes) -> bytes: + """Convert PCM data to WAV format""" + if len(pcm_data) == 0: + logger.bind(tag=TAG).warning( + "PCM data is empty, cannot convert to WAV") + return b"" + + # Ensure data length is even (16-bit audio) + if len(pcm_data) % 2 != 0: + pcm_data = pcm_data[:-1] + + # Create WAV file header + wav_buffer = io.BytesIO() + try: + with wave.open(wav_buffer, 'wb') as wav_file: + wav_file.setnchannels(1) # Mono + wav_file.setsampwidth(2) # 16-bit + wav_file.setframerate(16000) # 16kHz sample rate + wav_file.writeframes(pcm_data) + + wav_buffer.seek(0) + wav_data = wav_buffer.read() + + return wav_data + except Exception as e: + logger.bind(tag=TAG).error(f"WAV conversion failed: {e}") + return b"" + + def stop_ws_connection(self): + pass + + def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str: + """Save PCM data as WAV file""" + module_name = __name__.split(".")[-1] + file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav" + file_path = os.path.join(self.output_dir, file_name) + + with wave.open(file_path, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) # 2 bytes = 16-bit + wf.setframerate(16000) + wf.writeframes(b"".join(pcm_data)) + + return file_path + + def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str): + """Log audio file information to CSV file""" + try: + # Create logs directory at the same level as output_dir + log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs") + os.makedirs(log_dir, exist_ok=True) + + # Create both CSV and JSON log files for easy inspection + csv_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.csv") + json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json") + + # Write to CSV file + csv_exists = os.path.exists(csv_log_file) + with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile: + fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript'] + writer = csv.DictWriter(csvfile, fieldnames=fieldnames) + + if not csv_exists: + writer.writeheader() + + writer.writerow({ + 'timestamp': datetime.now().isoformat(), + 'filename': os.path.basename(file_path), + 'file_path': file_path, + 'audio_length_seconds': round(audio_length_seconds, 2), + 'transcript': transcript + }) + + # Also write to JSON file for easier parsing + log_entry = { + 'timestamp': datetime.now().isoformat(), + 'filename': os.path.basename(file_path), + 'file_path': file_path, + 'audio_length_seconds': round(audio_length_seconds, 2), + 'transcript': transcript + } + + # Read existing JSON logs or create new list + json_logs = [] + if os.path.exists(json_log_file): + try: + with open(json_log_file, 'r', encoding='utf-8') as f: + json_logs = json.load(f) + except: + json_logs = [] + + json_logs.append(log_entry) + + # Write updated JSON logs + with open(json_log_file, 'w', encoding='utf-8') as f: + json.dump(json_logs, f, ensure_ascii=False, indent=2) + + # Also create a simple text log for quick inspection + txt_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.txt") + with open(txt_log_file, 'a', encoding='utf-8') as f: + f.write(f"\n{'='*80}\n") + f.write(f"Timestamp: {datetime.now().isoformat()}\n") + f.write(f"Filename: {os.path.basename(file_path)}\n") + f.write(f"Full Path: {file_path}\n") + f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n") + f.write(f"Transcript: {transcript}\n") + f.write(f"{'='*80}\n") + + # Logging disabled - comment out the log message + # logger.bind(tag=TAG).info( + # f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, " + # f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..." + # ) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}") + + @abstractmethod + async def speech_to_text( + self, opus_data: List[bytes], session_id: str, audio_format="opus" + ) -> Tuple[Optional[str], Optional[str]]: + """Convert speech data to text""" + pass + + @staticmethod + def decode_opus(opus_data: List[bytes]) -> List[bytes]: + """Decode Opus audio data to PCM data""" + try: + decoder = opuslib_next.Decoder(16000, 1) + pcm_data = [] + buffer_size = 960 # Process 960 samples each time (60ms at 16kHz) + + for i, opus_packet in enumerate(opus_data): + try: + if not opus_packet or len(opus_packet) == 0: + continue + + pcm_frame = decoder.decode(opus_packet, buffer_size) + if pcm_frame and len(pcm_frame) > 0: + pcm_data.append(pcm_frame) + + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).warning( + f"Opus decode error, skipping packet {i}: {e}") + except Exception as e: + logger.bind(tag=TAG).error( + f"Audio processing error, packet {i}: {e}") + + return pcm_data + + except Exception as e: + logger.bind(tag=TAG).error( + f"Error occurred during audio decoding: {e}") + return [] diff --git a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py index 3af249e36..a78d3003f 100644 --- a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py +++ b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py @@ -1,384 +1,384 @@ -import time -import wave -import os -import sys -import io -from config.logger import setup_logging -from typing import Optional, Tuple, List -from core.providers.asr.dto.dto import InterfaceType -from core.providers.asr.base import ASRProviderBase - -import numpy as np -import sherpa_onnx - -from modelscope.hub.file_download import model_file_download -try: - from huggingface_hub import hf_hub_download - HF_AVAILABLE = True -except ImportError: - HF_AVAILABLE = False - -import requests -import tarfile -import urllib.request - -TAG = __name__ -logger = setup_logging() - - -# Capture standard output -class CaptureOutput: - def __enter__(self): - self._output = io.StringIO() - self._original_stdout = sys.stdout - sys.stdout = self._output - - def __exit__(self, exc_type, exc_value, traceback): - sys.stdout = self._original_stdout - self.output = self._output.getvalue() - self._output.close() - - # Output captured content through logger - if self.output: - logger.bind(tag=TAG).info(self.output.strip()) - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - super().__init__() - self.interface_type = InterfaceType.LOCAL - self.model_dir = config.get("model_dir") - self.output_dir = config.get("output_dir") - self.model_type = config.get( - "model_type", "sense_voice") # Support paraformer - self.delete_audio_file = delete_audio_file - - # Ensure output directory exists - os.makedirs(self.output_dir, exist_ok=True) - - # Initialize model file paths based on model type - model_files = self._get_model_files_for_type() - - # Download and check model files - try: - # Determine model source and ID based on model directory name - model_info = self._get_model_id_from_dir() - - # Check if we need to download the entire model from GitHub - if model_info["source"] == "github": - # For GitHub models, check if any files are missing and download the whole archive - missing_files = [f for f in model_files.values() if not os.path.isfile(f)] - if missing_files: - logger.bind(tag=TAG).info("Downloading complete model from GitHub...") - self._download_from_github(model_info["url"], self.model_dir) - else: - # For individual file downloads (HuggingFace/ModelScope) - for file_name, file_path in model_files.items(): - if not os.path.isfile(file_path): - logger.bind(tag=TAG).info( - f"Downloading model file: {file_name}") - - if model_info["source"] == "huggingface" and HF_AVAILABLE: - # Use Hugging Face Hub - try: - hf_hub_download( - repo_id=model_info["model_id"], - filename=file_name, - local_dir=self.model_dir, - local_dir_use_symlinks=False - ) - except Exception as e: - logger.bind(tag=TAG).warning( - f"HuggingFace download failed: {e}, trying ModelScope...") - # Fallback to ModelScope - model_file_download( - model_id=model_info["model_id"], - file_path=file_name, - local_dir=self.model_dir, - ) - else: - # Use ModelScope - model_file_download( - model_id=model_info["model_id"], - file_path=file_name, - local_dir=self.model_dir, - ) - - # Verify all files exist after download - for file_name, file_path in model_files.items(): - if not os.path.isfile(file_path): - raise FileNotFoundError( - f"Model file not found after download: {file_path}") - - # Set model paths based on type - if self.model_type == "whisper": - self.encoder_path = list(model_files.values())[0] # encoder - self.decoder_path = list(model_files.values())[1] # decoder - self.tokens_path = list(model_files.values())[2] # tokens - elif self.model_type == "zipformer": - # Handle different zipformer file naming patterns - model_name = os.path.basename(self.model_dir) - if "gigaspeech" in model_name: - self.encoder_path = model_files["encoder-epoch-30-avg-1.onnx"] - self.decoder_path = model_files["decoder-epoch-30-avg-1.onnx"] - self.joiner_path = model_files["joiner-epoch-30-avg-1.onnx"] - else: - self.encoder_path = model_files["encoder-epoch-99-avg-1.onnx"] - self.decoder_path = model_files["decoder-epoch-99-avg-1.onnx"] - self.joiner_path = model_files["joiner-epoch-99-avg-1.onnx"] - self.tokens_path = model_files["tokens.txt"] - else: - self.model_path = model_files["model.int8.onnx"] - self.tokens_path = model_files["tokens.txt"] - - except Exception as e: - logger.bind(tag=TAG).error( - f"Model file processing failed: {str(e)}") - raise - - # Initialize the model - self._initialize_model() - - def _get_model_id_from_dir(self) -> str: - """Determine ModelScope model ID based on model directory name""" - dir_name = os.path.basename(self.model_dir) - - # Map directory names to model sources (ModelScope and HuggingFace) - model_mapping = { - # Multilingual models - "sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17": { - "source": "modelscope", - "model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue" - }, - - # English-only Whisper models (HuggingFace - more reliable) - "sherpa-onnx-whisper-tiny.en": { - "source": "huggingface", - "model_id": "csukuangfj/sherpa-onnx-whisper-tiny.en" - }, - "sherpa-onnx-whisper-base.en": { - "source": "huggingface", - "model_id": "csukuangfj/sherpa-onnx-whisper-base.en" - }, - "sherpa-onnx-whisper-small.en": { - "source": "huggingface", - "model_id": "csukuangfj/sherpa-onnx-whisper-small.en" - }, - "sherpa-onnx-whisper-medium.en": { - "source": "huggingface", - "model_id": "csukuangfj/sherpa-onnx-whisper-medium.en" - }, - - # English-only Zipformer models (HuggingFace) - "sherpa-onnx-zipformer-en-2023-04-01": { - "source": "huggingface", - "model_id": "csukuangfj/sherpa-onnx-zipformer-en-2023-04-01" - }, - "sherpa-onnx-zipformer-gigaspeech-2023-12-12": { - "source": "github", - "model_id": "sherpa-onnx-zipformer-gigaspeech-2023-12-12", - "url": "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-zipformer-gigaspeech-2023-12-12.tar.bz2" - }, - } - - return model_mapping.get(dir_name, { - "source": "modelscope", - "model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue" - }) - - def _get_model_files_for_type(self) -> dict: - """Get required model files based on model type""" - if self.model_type == "whisper": - # Dynamic file names based on model directory - model_name = os.path.basename(self.model_dir) - if "tiny.en" in model_name: - prefix = "tiny.en" - elif "base.en" in model_name: - prefix = "base.en" - elif "small.en" in model_name: - prefix = "small.en" - elif "medium.en" in model_name: - prefix = "medium.en" - else: - prefix = "tiny.en" # default - - return { - f"{prefix}-encoder.onnx": os.path.join(self.model_dir, f"{prefix}-encoder.onnx"), - f"{prefix}-decoder.onnx": os.path.join(self.model_dir, f"{prefix}-decoder.onnx"), - f"{prefix}-tokens.txt": os.path.join(self.model_dir, f"{prefix}-tokens.txt"), - } - elif self.model_type == "zipformer": - # Check for different zipformer file naming patterns - model_name = os.path.basename(self.model_dir) - if "gigaspeech" in model_name: - return { - "encoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-30-avg-1.onnx"), - "decoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-30-avg-1.onnx"), - "joiner-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-30-avg-1.onnx"), - "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), - } - else: - return { - "encoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-99-avg-1.onnx"), - "decoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-99-avg-1.onnx"), - "joiner-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-99-avg-1.onnx"), - "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), - } - else: # sense_voice or paraformer - return { - "model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"), - "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), - } - - def _download_from_github(self, url: str, model_dir: str): - """Download and extract model from GitHub releases""" - try: - # Create parent directory - parent_dir = os.path.dirname(model_dir) - os.makedirs(parent_dir, exist_ok=True) - - # Download the tar.bz2 file to a temporary location - tar_filename = os.path.join(parent_dir, "temp_model.tar.bz2") - logger.bind(tag=TAG).info(f"Downloading from GitHub: {url}") - - urllib.request.urlretrieve(url, tar_filename) - - # Extract the tar.bz2 file - logger.bind(tag=TAG).info("Extracting model files...") - with tarfile.open(tar_filename, 'r:bz2') as tar: - # Extract to parent directory - tar.extractall(parent_dir) - - # Clean up the tar file - os.remove(tar_filename) - - # Verify the extracted directory exists - if os.path.exists(model_dir): - logger.bind(tag=TAG).info("GitHub model download completed successfully") - else: - raise FileNotFoundError(f"Extracted model directory not found: {model_dir}") - - except Exception as e: - logger.bind(tag=TAG).error(f"GitHub download failed: {e}") - raise - - def _initialize_model(self): - """Initialize the appropriate model based on type""" - with CaptureOutput(): - if self.model_type == "paraformer": - self.model = sherpa_onnx.OfflineRecognizer.from_paraformer( - paraformer=self.model_path, - tokens=self.tokens_path, - num_threads=2, - decoding_method="greedy_search", - debug=False, - ) - elif self.model_type == "whisper": - self.model = sherpa_onnx.OfflineRecognizer.from_whisper( - encoder=self.encoder_path, - decoder=self.decoder_path, - tokens=self.tokens_path, - num_threads=2, - decoding_method="greedy_search", - debug=False, - ) - elif self.model_type == "zipformer": - self.model = sherpa_onnx.OfflineRecognizer.from_transducer( - encoder=self.encoder_path, - decoder=self.decoder_path, - joiner=self.joiner_path, - tokens=self.tokens_path, - num_threads=2, - decoding_method="greedy_search", - debug=False, - ) - else: # sense_voice - self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice( - model=self.model_path, - tokens=self.tokens_path, - num_threads=2, - decoding_method="greedy_search", - debug=False, - use_itn=True, - ) - - def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]: - """ - Args: - wave_filename: - Path to a wave file. It should be single channel and each sample should - be 16-bit. Its sample rate does not need to be 16kHz. - Returns: - Return a tuple containing: - - A 1-D array of dtype np.float32 containing the samples, which are - normalized to the range [-1, 1]. - - sample rate of the wave file - """ - - with wave.open(wave_filename) as f: - assert f.getnchannels() == 1, f.getnchannels() - assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes - num_samples = f.getnframes() - samples = f.readframes(num_samples) - samples_int16 = np.frombuffer(samples, dtype=np.int16) - samples_float32 = samples_int16.astype(np.float32) - - samples_float32 = samples_float32 / 32768 - return samples_float32, f.getframerate() - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """Main processing logic for speech to text""" - file_path = None - try: - # Save audio file - start_time = time.time() - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - file_path = self.save_audio_to_file(pcm_data, session_id) - logger.bind(tag=TAG).debug( - f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}" - ) - - # Speech recognition - start_time = time.time() - s = self.model.create_stream() - samples, sample_rate = self.read_wave(file_path) - s.accept_waveform(sample_rate, samples) - self.model.decode_stream(s) - text = s.result.text - logger.bind(tag=TAG).debug( - f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}" - ) - - # Calculate audio length from WAV file - with wave.open(file_path, 'rb') as wav_file: - frames = wav_file.getnframes() - rate = wav_file.getframerate() - audio_length_seconds = frames / float(rate) - - # Log the transcript information - self.log_audio_transcript(file_path, audio_length_seconds, text) - - return text, file_path - - except Exception as e: - logger.bind(tag=TAG).error( - f"Speech recognition failed: {e}", exc_info=True) - return "", file_path - finally: - # File cleanup logic - DISABLED to preserve audio files - if self.delete_audio_file and file_path and os.path.exists(file_path): - logger.bind(tag=TAG).info( - f"Audio file preserved (deletion disabled): {file_path}") - # Commented out deletion code to preserve audio files - # try: - # os.remove(file_path) - # logger.bind(tag=TAG).debug( - # f"Deleted temporary audio file: {file_path}") - # except Exception as e: - # logger.bind(tag=TAG).error( - # f"File deletion failed: {file_path} | Error: {e}") +import time +import wave +import os +import sys +import io +from config.logger import setup_logging +from typing import Optional, Tuple, List +from core.providers.asr.dto.dto import InterfaceType +from core.providers.asr.base import ASRProviderBase + +import numpy as np +import sherpa_onnx + +from modelscope.hub.file_download import model_file_download +try: + from huggingface_hub import hf_hub_download + HF_AVAILABLE = True +except ImportError: + HF_AVAILABLE = False + +import requests +import tarfile +import urllib.request + +TAG = __name__ +logger = setup_logging() + + +# Capture standard output +class CaptureOutput: + def __enter__(self): + self._output = io.StringIO() + self._original_stdout = sys.stdout + sys.stdout = self._output + + def __exit__(self, exc_type, exc_value, traceback): + sys.stdout = self._original_stdout + self.output = self._output.getvalue() + self._output.close() + + # Output captured content through logger + if self.output: + logger.bind(tag=TAG).info(self.output.strip()) + + +class ASRProvider(ASRProviderBase): + def __init__(self, config: dict, delete_audio_file: bool): + super().__init__() + self.interface_type = InterfaceType.LOCAL + self.model_dir = config.get("model_dir") + self.output_dir = config.get("output_dir") + self.model_type = config.get( + "model_type", "sense_voice") # Support paraformer + self.delete_audio_file = delete_audio_file + + # Ensure output directory exists + os.makedirs(self.output_dir, exist_ok=True) + + # Initialize model file paths based on model type + model_files = self._get_model_files_for_type() + + # Download and check model files + try: + # Determine model source and ID based on model directory name + model_info = self._get_model_id_from_dir() + + # Check if we need to download the entire model from GitHub + if model_info["source"] == "github": + # For GitHub models, check if any files are missing and download the whole archive + missing_files = [f for f in model_files.values() if not os.path.isfile(f)] + if missing_files: + logger.bind(tag=TAG).info("Downloading complete model from GitHub...") + self._download_from_github(model_info["url"], self.model_dir) + else: + # For individual file downloads (HuggingFace/ModelScope) + for file_name, file_path in model_files.items(): + if not os.path.isfile(file_path): + logger.bind(tag=TAG).info( + f"Downloading model file: {file_name}") + + if model_info["source"] == "huggingface" and HF_AVAILABLE: + # Use Hugging Face Hub + try: + hf_hub_download( + repo_id=model_info["model_id"], + filename=file_name, + local_dir=self.model_dir, + local_dir_use_symlinks=False + ) + except Exception as e: + logger.bind(tag=TAG).warning( + f"HuggingFace download failed: {e}, trying ModelScope...") + # Fallback to ModelScope + model_file_download( + model_id=model_info["model_id"], + file_path=file_name, + local_dir=self.model_dir, + ) + else: + # Use ModelScope + model_file_download( + model_id=model_info["model_id"], + file_path=file_name, + local_dir=self.model_dir, + ) + + # Verify all files exist after download + for file_name, file_path in model_files.items(): + if not os.path.isfile(file_path): + raise FileNotFoundError( + f"Model file not found after download: {file_path}") + + # Set model paths based on type + if self.model_type == "whisper": + self.encoder_path = list(model_files.values())[0] # encoder + self.decoder_path = list(model_files.values())[1] # decoder + self.tokens_path = list(model_files.values())[2] # tokens + elif self.model_type == "zipformer": + # Handle different zipformer file naming patterns + model_name = os.path.basename(self.model_dir) + if "gigaspeech" in model_name: + self.encoder_path = model_files["encoder-epoch-30-avg-1.onnx"] + self.decoder_path = model_files["decoder-epoch-30-avg-1.onnx"] + self.joiner_path = model_files["joiner-epoch-30-avg-1.onnx"] + else: + self.encoder_path = model_files["encoder-epoch-99-avg-1.onnx"] + self.decoder_path = model_files["decoder-epoch-99-avg-1.onnx"] + self.joiner_path = model_files["joiner-epoch-99-avg-1.onnx"] + self.tokens_path = model_files["tokens.txt"] + else: + self.model_path = model_files["model.int8.onnx"] + self.tokens_path = model_files["tokens.txt"] + + except Exception as e: + logger.bind(tag=TAG).error( + f"Model file processing failed: {str(e)}") + raise + + # Initialize the model + self._initialize_model() + + def _get_model_id_from_dir(self) -> str: + """Determine ModelScope model ID based on model directory name""" + dir_name = os.path.basename(self.model_dir) + + # Map directory names to model sources (ModelScope and HuggingFace) + model_mapping = { + # Multilingual models + "sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17": { + "source": "modelscope", + "model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue" + }, + + # English-only Whisper models (HuggingFace - more reliable) + "sherpa-onnx-whisper-tiny.en": { + "source": "huggingface", + "model_id": "csukuangfj/sherpa-onnx-whisper-tiny.en" + }, + "sherpa-onnx-whisper-base.en": { + "source": "huggingface", + "model_id": "csukuangfj/sherpa-onnx-whisper-base.en" + }, + "sherpa-onnx-whisper-small.en": { + "source": "huggingface", + "model_id": "csukuangfj/sherpa-onnx-whisper-small.en" + }, + "sherpa-onnx-whisper-medium.en": { + "source": "huggingface", + "model_id": "csukuangfj/sherpa-onnx-whisper-medium.en" + }, + + # English-only Zipformer models (HuggingFace) + "sherpa-onnx-zipformer-en-2023-04-01": { + "source": "huggingface", + "model_id": "csukuangfj/sherpa-onnx-zipformer-en-2023-04-01" + }, + "sherpa-onnx-zipformer-gigaspeech-2023-12-12": { + "source": "github", + "model_id": "sherpa-onnx-zipformer-gigaspeech-2023-12-12", + "url": "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-zipformer-gigaspeech-2023-12-12.tar.bz2" + }, + } + + return model_mapping.get(dir_name, { + "source": "modelscope", + "model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue" + }) + + def _get_model_files_for_type(self) -> dict: + """Get required model files based on model type""" + if self.model_type == "whisper": + # Dynamic file names based on model directory + model_name = os.path.basename(self.model_dir) + if "tiny.en" in model_name: + prefix = "tiny.en" + elif "base.en" in model_name: + prefix = "base.en" + elif "small.en" in model_name: + prefix = "small.en" + elif "medium.en" in model_name: + prefix = "medium.en" + else: + prefix = "tiny.en" # default + + return { + f"{prefix}-encoder.onnx": os.path.join(self.model_dir, f"{prefix}-encoder.onnx"), + f"{prefix}-decoder.onnx": os.path.join(self.model_dir, f"{prefix}-decoder.onnx"), + f"{prefix}-tokens.txt": os.path.join(self.model_dir, f"{prefix}-tokens.txt"), + } + elif self.model_type == "zipformer": + # Check for different zipformer file naming patterns + model_name = os.path.basename(self.model_dir) + if "gigaspeech" in model_name: + return { + "encoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-30-avg-1.onnx"), + "decoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-30-avg-1.onnx"), + "joiner-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-30-avg-1.onnx"), + "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), + } + else: + return { + "encoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-99-avg-1.onnx"), + "decoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-99-avg-1.onnx"), + "joiner-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-99-avg-1.onnx"), + "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), + } + else: # sense_voice or paraformer + return { + "model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"), + "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), + } + + def _download_from_github(self, url: str, model_dir: str): + """Download and extract model from GitHub releases""" + try: + # Create parent directory + parent_dir = os.path.dirname(model_dir) + os.makedirs(parent_dir, exist_ok=True) + + # Download the tar.bz2 file to a temporary location + tar_filename = os.path.join(parent_dir, "temp_model.tar.bz2") + logger.bind(tag=TAG).info(f"Downloading from GitHub: {url}") + + urllib.request.urlretrieve(url, tar_filename) + + # Extract the tar.bz2 file + logger.bind(tag=TAG).info("Extracting model files...") + with tarfile.open(tar_filename, 'r:bz2') as tar: + # Extract to parent directory + tar.extractall(parent_dir) + + # Clean up the tar file + os.remove(tar_filename) + + # Verify the extracted directory exists + if os.path.exists(model_dir): + logger.bind(tag=TAG).info("GitHub model download completed successfully") + else: + raise FileNotFoundError(f"Extracted model directory not found: {model_dir}") + + except Exception as e: + logger.bind(tag=TAG).error(f"GitHub download failed: {e}") + raise + + def _initialize_model(self): + """Initialize the appropriate model based on type""" + with CaptureOutput(): + if self.model_type == "paraformer": + self.model = sherpa_onnx.OfflineRecognizer.from_paraformer( + paraformer=self.model_path, + tokens=self.tokens_path, + num_threads=2, + decoding_method="greedy_search", + debug=False, + ) + elif self.model_type == "whisper": + self.model = sherpa_onnx.OfflineRecognizer.from_whisper( + encoder=self.encoder_path, + decoder=self.decoder_path, + tokens=self.tokens_path, + num_threads=2, + decoding_method="greedy_search", + debug=False, + ) + elif self.model_type == "zipformer": + self.model = sherpa_onnx.OfflineRecognizer.from_transducer( + encoder=self.encoder_path, + decoder=self.decoder_path, + joiner=self.joiner_path, + tokens=self.tokens_path, + num_threads=2, + decoding_method="greedy_search", + debug=False, + ) + else: # sense_voice + self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice( + model=self.model_path, + tokens=self.tokens_path, + num_threads=2, + decoding_method="greedy_search", + debug=False, + use_itn=True, + ) + + def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]: + """ + Args: + wave_filename: + Path to a wave file. It should be single channel and each sample should + be 16-bit. Its sample rate does not need to be 16kHz. + Returns: + Return a tuple containing: + - A 1-D array of dtype np.float32 containing the samples, which are + normalized to the range [-1, 1]. + - sample rate of the wave file + """ + + with wave.open(wave_filename) as f: + assert f.getnchannels() == 1, f.getnchannels() + assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes + num_samples = f.getnframes() + samples = f.readframes(num_samples) + samples_int16 = np.frombuffer(samples, dtype=np.int16) + samples_float32 = samples_int16.astype(np.float32) + + samples_float32 = samples_float32 / 32768 + return samples_float32, f.getframerate() + + async def speech_to_text( + self, opus_data: List[bytes], session_id: str, audio_format="opus" + ) -> Tuple[Optional[str], Optional[str]]: + """Main processing logic for speech to text""" + file_path = None + try: + # Save audio file + start_time = time.time() + if audio_format == "pcm": + pcm_data = opus_data + else: + pcm_data = self.decode_opus(opus_data) + file_path = self.save_audio_to_file(pcm_data, session_id) + logger.bind(tag=TAG).debug( + f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}" + ) + + # Speech recognition + start_time = time.time() + s = self.model.create_stream() + samples, sample_rate = self.read_wave(file_path) + s.accept_waveform(sample_rate, samples) + self.model.decode_stream(s) + text = s.result.text + logger.bind(tag=TAG).debug( + f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}" + ) + + # Calculate audio length from WAV file + with wave.open(file_path, 'rb') as wav_file: + frames = wav_file.getnframes() + rate = wav_file.getframerate() + audio_length_seconds = frames / float(rate) + + # Log the transcript information - TEMPORARILY DISABLED + # self.log_audio_transcript(file_path, audio_length_seconds, text) + + return text, file_path + + except Exception as e: + logger.bind(tag=TAG).error( + f"Speech recognition failed: {e}", exc_info=True) + return "", file_path + finally: + # File cleanup logic - DISABLED to preserve audio files + if self.delete_audio_file and file_path and os.path.exists(file_path): + logger.bind(tag=TAG).info( + f"Audio file preserved (deletion disabled): {file_path}") + # Commented out deletion code to preserve audio files + try: + os.remove(file_path) + logger.bind(tag=TAG).debug( + f"Deleted temporary audio file: {file_path}") + except Exception as e: + logger.bind(tag=TAG).error( + f"File deletion failed: {file_path} | Error: {e}")