From d3000aa61fd7af73779735a3c53b564d44626f03 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Tue, 12 Aug 2025 13:26:38 +0530 Subject: [PATCH] updated code from mainserver --- main/xiaozhi-server/app.py | 15 +- main/xiaozhi-server/client.py | 16 +- main/xiaozhi-server/config/config_loader.py | 20 +- main/xiaozhi-server/config/logger.py | 88 +-- main/xiaozhi-server/core/api/ota_handler.py | 31 + main/xiaozhi-server/core/connection.py | 249 +++++-- .../core/handle/intentHandler.py | 36 +- .../core/handle/receiveAudioHandle.py | 38 +- .../core/handle/sendAudioHandle.py | 68 +- main/xiaozhi-server/core/handle/textHandle.py | 4 +- .../core/providers/asr/aliyun_stream.py | 343 +++++++++ .../xiaozhi-server/core/providers/asr/base.py | 208 +++++- .../core/providers/asr/doubao_stream.py | 534 ++++++-------- .../core/providers/asr/sherpa_onnx_local.py | 34 +- .../providers/intent/intent_llm/intent_llm.py | 63 +- .../memory/mem_local_short/mem_local_short.py | 16 +- .../tools/server_plugins/plugin_executor.py | 6 +- .../core/providers/tts/aliyun.py | 7 +- .../core/providers/tts/aliyun_stream.py | 653 ++++++++++++++++++ .../xiaozhi-server/core/providers/tts/base.py | 28 +- .../providers/tts/huoshan_double_stream.py | 157 +++-- .../core/providers/tts/index_stream.py | 264 +++++++ .../core/providers/tts/linkerai.py | 13 +- .../core/providers/tts/minimax_httpstream.py | 230 ++++++ .../core/providers/tts/minimax_webSocket.py | 180 +++++ .../core/providers/tts/paddle_speech.py | 152 ++++ .../core/providers/vllm/openai.py | 3 +- .../xiaozhi-server/core/utils/cache/config.py | 58 ++ .../core/utils/cache/manager.py | 216 ++++++ .../core/utils/cache/strategies.py | 43 ++ main/xiaozhi-server/core/utils/dialogue.py | 56 +- .../core/utils/modules_initialize.py | 22 + .../core/utils/prompt_manager.py | 245 +++++++ main/xiaozhi-server/core/utils/textUtils.py | 89 ++- main/xiaozhi-server/core/utils/util.py | 591 +--------------- .../core/utils/voiceprint_provider.py | 134 ++++ main/xiaozhi-server/core/websocket_server.py | 19 +- .../plugins_func/functions/get_time.py | 79 +-- .../plugins_func/functions/get_weather.py | 41 +- .../plugins_func/functions/hass_get_state.py | 12 +- .../plugins_func/functions/play_music.py | 51 +- main/xiaozhi-server/requirements.txt | 5 +- 42 files changed, 3745 insertions(+), 1372 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/asr/aliyun_stream.py create mode 100644 main/xiaozhi-server/core/providers/tts/aliyun_stream.py create mode 100644 main/xiaozhi-server/core/providers/tts/index_stream.py create mode 100644 main/xiaozhi-server/core/providers/tts/minimax_httpstream.py create mode 100644 main/xiaozhi-server/core/providers/tts/minimax_webSocket.py create mode 100644 main/xiaozhi-server/core/providers/tts/paddle_speech.py create mode 100644 main/xiaozhi-server/core/utils/cache/config.py create mode 100644 main/xiaozhi-server/core/utils/cache/manager.py create mode 100644 main/xiaozhi-server/core/utils/cache/strategies.py create mode 100644 main/xiaozhi-server/core/utils/prompt_manager.py create mode 100644 main/xiaozhi-server/core/utils/voiceprint_provider.py diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index defc8b02f..65e3a74b2 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -5,7 +5,7 @@ import asyncio from aioconsole import ainput from config.settings import load_config from config.logger import setup_logging -from core.utils.util import get_local_ip +from core.utils.util import get_local_ip, validate_mcp_endpoint from core.http_server import SimpleHttpServer from core.websocket_server import WebSocketServer from core.utils.util import check_ffmpeg_installed @@ -73,6 +73,19 @@ async def main(): get_local_ip(), port, ) + + mcp_endpoint = config.get("mcp_endpoint", None) + if mcp_endpoint is not None and "你" not in mcp_endpoint: + # 校验MCP接入点格式 + if validate_mcp_endpoint(mcp_endpoint): + logger.bind(tag=TAG).info("mcp接入点是\t{}", mcp_endpoint) + # 将mcp计入点地址转成调用点 + mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/") + config["mcp_endpoint"] = mcp_endpoint + else: + logger.bind(tag=TAG).error("mcp接入点不符合规范") + config["mcp_endpoint"] = "你的接入点 websocket地址" + logger.bind(tag=TAG).info( "视觉分析接口是\thttp://{}:{}/mcp/vision/explain", get_local_ip(), diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index ba7e58500..5565fb1bf 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -18,9 +18,9 @@ from queue import Queue, Empty import opuslib # --- Configuration --- -SERVER_IP = "192.168.1.3" # !!! UPDATE with your server's local IP address !!! +SERVER_IP = "192.168.1.102" # !!! UPDATE with your server's local IP address !!! OTA_PORT = 8003 -MQTT_BROKER_HOST = "192.168.1.3" # MQTT gateway IP +MQTT_BROKER_HOST = "192.168.1.102" # MQTT gateway IP MQTT_BROKER_PORT = 1883 # DEVICE_MAC is now dynamically generated for uniqueness PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback @@ -321,11 +321,16 @@ class TestClient: """Requests OTA configuration from the server.""" logger.info(f"▶️ STEP 1: Requesting OTA config from http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/") try: + # Generate a client ID for this session + import uuid + session_client_id = str(uuid.uuid4()) + headers = {"device-id": self.device_mac_formatted} data = { "application": { "version": "1.0.0" - } + }, + "client_id": session_client_id } response = requests.post(f"http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/", headers=headers, json=data, timeout=5) response.raise_for_status() @@ -527,6 +532,8 @@ class TestClient: # Initialize the decoder with the sample rate provided by the server decoder = opuslib.Decoder(audio_params["sample_rate"], audio_params["channels"]) frame_size_samples = int(audio_params["sample_rate"] * audio_params["frame_duration"] / 1000) + # Maximum frame size for Opus (120ms at 48kHz = 5760 samples, but we'll use a larger buffer) + max_frame_size = int(audio_params["sample_rate"] * 0.12) # 120ms worth of samples while not stop_threads.is_set() and self.session_active: try: @@ -554,7 +561,8 @@ class TestClient: opus_payload = decryptor.update(encrypted) + decryptor.finalize() # Decode the Opus payload to PCM and put it in the playback queue - pcm_payload = decoder.decode(opus_payload, frame_size_samples) + # Use max_frame_size to provide enough buffer space for variable frame sizes + pcm_payload = decoder.decode(opus_payload, max_frame_size) self.audio_playback_queue.put(pcm_payload) except socket.timeout: diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index b1b45f07f..4c1b3f73a 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -1,14 +1,9 @@ import os -import argparse import yaml from collections.abc import Mapping from config.manage_api_client import init_service, get_server_config, get_agent_models -# 添加全局配置缓存 -_config_cache = None - - def get_project_dir(): """获取项目根目录""" return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/" @@ -22,9 +17,12 @@ def read_config(config_path): def load_config(): """加载配置文件""" - global _config_cache - if _config_cache is not None: - return _config_cache + from core.utils.cache.manager import cache_manager, CacheType + + # 检查缓存 + cached_config = cache_manager.get(CacheType.CONFIG, "main_config") + if cached_config is not None: + return cached_config default_config_path = get_project_dir() + "config.yaml" custom_config_path = get_project_dir() + "data/.config.yaml" @@ -40,7 +38,9 @@ def load_config(): config = merge_configs(default_config, custom_config) # 初始化目录 ensure_directories(config) - _config_cache = config + + # 缓存配置 + cache_manager.set(CacheType.CONFIG, "main_config", config) return config @@ -145,4 +145,4 @@ def merge_configs(default_config, custom_config): else: merged[key] = value - return merged + return merged \ No newline at end of file diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py index 47be87390..6bd50e3f4 100644 --- a/main/xiaozhi-server/config/logger.py +++ b/main/xiaozhi-server/config/logger.py @@ -5,7 +5,7 @@ from config.config_loader import load_config from config.settings import check_config_file from datetime import datetime -SERVER_VERSION = "0.6.2" +SERVER_VERSION = "0.7.4" _logger_initialized = False @@ -31,12 +31,17 @@ def build_module_string(selected_module): + get_module_abbreviation("TTS", selected_module) + get_module_abbreviation("Memory", selected_module) + get_module_abbreviation("Intent", selected_module) + + get_module_abbreviation("VLLM", selected_module) ) def formatter(record): - """为没有 tag 的日志添加默认值""" + """为没有 tag 的日志添加默认值,并处理动态模块字符串""" record["extra"].setdefault("tag", record["name"]) + # 如果没有设置 selected_module,使用默认值 + record["extra"].setdefault("selected_module", "00000000000000") + # 将 selected_module 从 extra 提取到顶级,以支持 {selected_module} 格式 + record["selected_module"] = record["extra"]["selected_module"] return record["message"] @@ -49,11 +54,12 @@ def setup_logging(): # 第一次初始化时配置日志 if not _logger_initialized: + # 使用默认的模块字符串进行初始化 logger.configure( extra={ - "selected_module": log_config.get("selected_module", "00000000000000") - } - ) # 新增配置 + "selected_module": log_config.get("selected_module", "00000000000000"), + }) + log_format = log_config.get( "log_format", "{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][{extra[tag]}]-{level}-{message}", @@ -62,14 +68,8 @@ def setup_logging(): "log_format_file", "{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}", ) - selected_module_str = logger._core.extra["selected_module"] - log_format = log_format.replace("{version}", SERVER_VERSION) - log_format = log_format.replace("{selected_module}", selected_module_str) log_format_file = log_format_file.replace("{version}", SERVER_VERSION) - log_format_file = log_format_file.replace( - "{selected_module}", selected_module_str - ) log_level = log_config.get("log_level", "INFO") log_dir = log_config.get("log_dir", "tmp") @@ -108,66 +108,6 @@ def setup_logging(): return logger -def update_module_string(selected_module_str): - """更新模块字符串并重新配置日志处理器""" - logger.debug(f"更新日志配置组件") - current_module = logger._core.extra["selected_module"] - - if current_module == selected_module_str: - logger.debug(f"组件未更改无需更新") - return - - try: - logger.configure(extra={"selected_module": selected_module_str}) - - config = load_config() - log_config = config["log"] - - log_format = log_config.get( - "log_format", - "{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][{extra[tag]}]-{level}-{message}", - ) - log_format_file = log_config.get( - "log_format_file", - "{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}", - ) - - log_format = log_format.replace("{version}", SERVER_VERSION) - log_format = log_format.replace("{selected_module}", selected_module_str) - log_format_file = log_format_file.replace("{version}", SERVER_VERSION) - log_format_file = log_format_file.replace( - "{selected_module}", selected_module_str - ) - - logger.remove() - logger.add( - sys.stdout, - format=log_format, - level=log_config.get("log_level", "INFO"), - filter=formatter, - ) - - # 更新文件日志配置 - 统一目录,按大小轮转 - log_dir = log_config.get("log_dir", "tmp") - log_file = log_config.get("log_file", "server.log") - - # 日志文件完整路径 - log_file_path = os.path.join(log_dir, log_file) - - logger.add( - log_file_path, - format=log_format_file, - level=log_config.get("log_level", "INFO"), - filter=formatter, - rotation="10 MB", # 每个文件最大10MB - retention="30 days", # 保留30天 - compression=None, - encoding="utf-8", - enqueue=True, # 异步安全 - backtrace=True, - diagnose=True, - ) - - except Exception as e: - logger.error(f"日志配置更新失败: {str(e)}") - raise +def create_connection_logger(selected_module_str): + """为连接创建独立的日志器,绑定特定的模块字符串""" + return logger.bind(selected_module=selected_module_str) diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py index 763c9c49e..857b02cd3 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -62,6 +62,37 @@ class OTAHandler(BaseHandler): "url": self._get_websocket_url(local_ip, port), }, } + + # Add MQTT gateway configuration if enabled + mqtt_config = server_config.get("mqtt_gateway", {}) + if mqtt_config.get("enabled", False): + return_json["mqtt_gateway"] = { + "broker": mqtt_config.get("broker", local_ip), + "port": mqtt_config.get("port", 1883), + "udp_port": mqtt_config.get("udp_port", 8884) + } + + # Also add MQTT credentials section for client authentication + import base64 + import hmac + import hashlib + + client_id = f"GID_test@@@{device_id}@@@{data_json.get('client_id', 'default-client')}" + + # Create username (base64 encoded JSON) - must match client format + username_data = {"ip": "192.168.1.100"} # Placeholder IP + username = base64.b64encode(json.dumps(username_data).encode()).decode() + + # Generate password using HMAC (must match gateway's signature key) + secret_key = "test-signature-key-12345" # Must match MQTT_SIGNATURE_KEY in gateway's .env + content = f"{client_id}|{username}" + password = base64.b64encode(hmac.new(secret_key.encode(), content.encode(), hashlib.sha256).digest()).decode() + + return_json["mqtt"] = { + "client_id": client_id, + "username": username, + "password": password + } response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index a30a1f969..6b7e3d1fb 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -35,9 +35,11 @@ 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, update_module_string +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__ @@ -74,7 +76,6 @@ class ConnectionHandler: self.headers = None self.device_id = None self.client_ip = None - self.client_ip_info = {} self.prompt = None self.welcome_msg = None self.max_output_size = 0 @@ -108,6 +109,9 @@ class ConnectionHandler: self.memory = _memory self.intent = _intent + # 为每个连接单独管理声纹识别 + self.voiceprint_provider = None + # vad相关变量 self.client_audio_buffer = bytearray() self.client_have_voice = False @@ -128,6 +132,8 @@ class ConnectionHandler: # tts相关变量 self.sentence_id = None + # 处理TTS响应没有文本返回 + self.tts_MessageText = "" # iot相关变量 self.iot_descriptors = {} @@ -152,6 +158,9 @@ class ConnectionHandler: # {"mcp":true} 表示启用MCP功能 self.features = None + # 初始化提示词管理器 + self.prompt_manager = PromptManager(config, self.logger) + async def handle_connection(self, ws): try: # 获取并验证headers @@ -175,8 +184,13 @@ class ConnectionHandler: await ws.send("端口正常,如需测试连接,请使用test_page.html") await self.close(ws) return - # 获取客户端ip地址 - self.client_ip = ws.remote_address[0] + 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}" ) @@ -196,7 +210,6 @@ class ConnectionHandler: self.welcome_msg = self.config["xiaozhi"] self.welcome_msg["session_id"] = self.session_id - await self.websocket.send(json.dumps(self.welcome_msg)) # 获取差异化配置 self._initialize_private_config() @@ -217,7 +230,17 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}") return finally: - await self._save_and_close(ws) + try: + await self._save_and_close(ws) + except Exception as final_error: + self.logger.bind(tag=TAG).error(f"最终清理时出错: {final_error}") + # 确保即使保存记忆失败,也要关闭连接 + try: + await self.close(ws) + except Exception as close_error: + self.logger.bind(tag=TAG).error( + f"强制关闭连接时出错: {close_error}" + ) async def _save_and_close(self, ws): """保存记忆并关闭连接""" @@ -235,7 +258,10 @@ class ConnectionHandler: except Exception as e: self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}") finally: - loop.close() + try: + loop.close() + except Exception: + pass # 启动线程保存记忆,不等待完成 threading.Thread(target=save_memory_task, daemon=True).start() @@ -243,12 +269,16 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}") finally: # 立即关闭连接,不等待记忆保存完成 - await self.close(ws) + try: + await self.close(ws) + except Exception as close_error: + self.logger.bind(tag=TAG).error( + f"保存记忆后关闭连接失败: {close_error}" + ) async def _route_message(self, message): """消息路由""" if isinstance(message, str): - self.last_activity_time = time.time() * 1000 await handleTextMessage(self, message) elif isinstance(message, bytes): if self.vad is None: @@ -310,13 +340,16 @@ class ConnectionHandler: self.selected_module_str = build_module_string( self.config.get("selected_module", {}) ) - update_module_string(self.selected_module_str) + self.logger = create_connection_logger(self.selected_module_str) + """初始化组件""" if self.config.get("prompt") is not None: - self.prompt = self.config["prompt"] - self.change_system_prompt(self.prompt) + user_prompt = self.config["prompt"] + # 使用快速提示词进行初始化 + prompt = self.prompt_manager.get_quick_prompt(user_prompt) + self.change_system_prompt(prompt) self.logger.bind(tag=TAG).info( - f"初始化组件: prompt成功 {self.prompt[:50]}..." + f"快速初始化组件: prompt成功 {prompt[:50]}..." ) """初始化本地组件""" @@ -324,6 +357,10 @@ class ConnectionHandler: self.vad = self._vad if self.asr is None: self.asr = self._initialize_asr() + + # 初始化声纹识别 + self._initialize_voiceprint() + # 打开语音识别通道 asyncio.run_coroutine_threadsafe( self.asr.open_audio_channels(self), self.loop @@ -341,9 +378,22 @@ class ConnectionHandler: self._initialize_intent() """初始化上报线程""" self._init_report_threads() + """更新系统提示词""" + self._init_prompt_enhancement() + except Exception as e: self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") + def _init_prompt_enhancement(self): + # 更新上下文信息 + 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("系统提示词已增强更新") + def _init_report_threads(self): """初始化ASR和TTS上报线程""" if not self.read_config_from_api or self.need_bind: @@ -381,6 +431,18 @@ class ConnectionHandler: return asr + def _initialize_voiceprint(self): + """为当前连接初始化声纹识别""" + try: + voiceprint_config = self.config.get("voiceprint", {}) + if voiceprint_config: + self.voiceprint_provider = VoiceprintProvider(voiceprint_config) + self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用") + else: + self.logger.bind(tag=TAG).info("声纹识别功能未启用或配置不完整") + except Exception as e: + self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}") + def _initialize_private_config(self): """如果是从配置文件获取,则进行二次实例化""" if not self.read_config_from_api: @@ -441,6 +503,11 @@ class ConnectionHandler: 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"] @@ -463,6 +530,9 @@ class ConnectionHandler: ] = plugin_from_server.keys() if private_config.get("prompt", None) is not None: self.config["prompt"] = private_config["prompt"] + # 获取声纹信息 + 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: @@ -594,13 +664,24 @@ class ConnectionHandler: # 更新系统prompt至上下文 self.dialogue.update_system_message(self.prompt) - def chat(self, query, tool_call=False): + def chat(self, query, tool_call=False, depth=0): self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") self.llm_finish_task = False if not tool_call: self.dialogue.put(Message(role="user", content=query)) + # 为最顶层时新建会话ID和发送FIRST请求 + 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"): @@ -616,19 +697,21 @@ class ConnectionHandler: ) memory_str = future.result() - self.sentence_id = str(uuid.uuid4().hex) - if self.intent_type == "function_call" and functions is not None: # 使用支持functions的streaming接口 llm_responses = self.llm.response_with_functions( self.session_id, - self.dialogue.get_llm_dialogue_with_memory(memory_str), + 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.dialogue.get_llm_dialogue_with_memory( + memory_str, self.config.get("voiceprint", {}) + ), ) except Exception as e: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") @@ -640,8 +723,8 @@ class ConnectionHandler: function_id = None function_arguments = "" content_arguments = "" - text_index = 0 self.client_abort = False + emotion_flag = True for response in llm_responses: if self.client_abort: break @@ -667,17 +750,18 @@ class ConnectionHandler: function_arguments += tools_call[0].function.arguments else: content = response + + # 在llm回复中获取情绪表情,一轮对话只在开头获取一次 + 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) - if text_index == 0: - self.tts.tts_text_queue.put( - TTSMessageDTO( - sentence_id=self.sentence_id, - sentence_type=SentenceType.FIRST, - content_type=ContentType.ACTION, - ) - ) self.tts.tts_text_queue.put( TTSMessageDTO( sentence_id=self.sentence_id, @@ -686,7 +770,6 @@ class ConnectionHandler: content_detail=content, ) ) - text_index += 1 # 处理function call if tool_call_flag: bHasError = False @@ -711,6 +794,11 @@ class ConnectionHandler: f"function call error: {content_arguments}" ) if not bHasError: + # 如需要大模型先处理一轮,添加相关处理后的日志情况 + 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}" @@ -728,14 +816,14 @@ class ConnectionHandler: ), self.loop, ).result() - self._handle_function_result(result, function_call_data) + self._handle_function_result(result, function_call_data, depth=depth) # 存储对话内容 if len(response_message) > 0: - self.dialogue.put( - Message(role="assistant", content="".join(response_message)) - ) - if text_index > 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, @@ -744,13 +832,16 @@ class ConnectionHandler: ) ) self.llm_finish_task = True + # 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue() self.logger.bind(tag=TAG).debug( - json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False) + lambda: json.dumps( + self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False + ) ) return True - def _handle_function_result(self, result, function_call_data): + def _handle_function_result(self, result, function_call_data, depth): if result.action == Action.RESPONSE: # 直接回复前端 text = result.response self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text) @@ -768,7 +859,7 @@ class ConnectionHandler: { "id": function_id, "function": { - "arguments": function_arguments, + "arguments": "{}" if function_arguments == "" else function_arguments, "name": function_name, }, "type": "function", @@ -787,7 +878,7 @@ class ConnectionHandler: content=text, ) ) - self.chat(text, tool_call=True) + 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) @@ -803,15 +894,12 @@ class ConnectionHandler: item = self.report_queue.get(timeout=1) if item is None: # 检测毒丸对象 break - type, text, audio_data, report_time = item try: # 检查线程池状态 if self.executor is None: continue # 提交任务到线程池 - self.executor.submit( - self._process_report, type, text, audio_data, report_time - ) + self.executor.submit(self._process_report, *item) except Exception as e: self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}") except queue.Empty: @@ -840,13 +928,22 @@ class ConnectionHandler: """资源清理方法""" try: # 取消超时任务 - if self.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 # 清理工具处理器资源 if hasattr(self, "func_handler") and self.func_handler: - await self.func_handler.cleanup() + try: + await self.func_handler.cleanup() + except Exception as cleanup_error: + self.logger.bind(tag=TAG).error( + f"清理工具处理器时出错: {cleanup_error}" + ) # 触发停止事件 if self.stop_event: @@ -856,19 +953,61 @@ class ConnectionHandler: self.clear_queues() # 关闭WebSocket连接 - if ws: - await ws.close() - elif self.websocket: - await self.websocket.close() + try: + if ws: + # 安全地检查WebSocket状态并关闭 + 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: + # 如果没有closed属性,直接尝试关闭 + await ws.close() + except Exception: + # 如果关闭失败,忽略错误 + 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: + # 如果没有closed属性,直接尝试关闭 + await self.websocket.close() + except Exception: + # 如果关闭失败,忽略错误 + pass + except Exception as ws_error: + self.logger.bind(tag=TAG).error(f"关闭WebSocket连接时出错: {ws_error}") + + if self.tts: + await self.tts.close() # 最后关闭线程池(避免阻塞) if self.executor: - self.executor.shutdown(wait=False) + try: + self.executor.shutdown(wait=False) + except Exception as executor_error: + self.logger.bind(tag=TAG).error( + f"关闭线程池时出错: {executor_error}" + ) self.executor = None self.logger.bind(tag=TAG).info("连接资源已释放") except Exception as e: self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}") + finally: + # 确保停止事件被设置 + if self.stop_event: + self.stop_event.set() def clear_queues(self): """清空所有任务队列""" @@ -925,9 +1064,19 @@ class ConnectionHandler: ): if not self.stop_event.is_set(): self.logger.bind(tag=TAG).info("连接超时,准备关闭") - await self.close(self.websocket) + # 设置停止事件,防止重复处理 + self.stop_event.set() + # 使用 try-except 包装关闭操作,确保不会因为异常而阻塞 + try: + await self.close(self.websocket) + except Exception as close_error: + self.logger.bind(tag=TAG).error( + f"超时关闭连接时出错: {close_error}" + ) break # 每10秒检查一次,避免过于频繁 await asyncio.sleep(10) except Exception as e: self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}") + finally: + self.logger.bind(tag=TAG).info("超时检查任务已退出") \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 2d0baca48..d04f9e6b8 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -6,14 +6,23 @@ from core.handle.helloHandle import checkWakeupWords from core.utils.util import remove_punctuation_and_length from core.providers.tts.dto.dto import ContentType from core.utils.dialogue import Message -from core.providers.tools.device_mcp import call_mcp_tool from plugins_func.register import Action, ActionResponse -from loguru import logger +from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType TAG = __name__ async def handle_user_intent(conn, text): + # 预处理输入文本,处理可能的JSON格式 + try: + if text.strip().startswith('{') and text.strip().endswith('}'): + parsed_data = json.loads(text) + if isinstance(parsed_data, dict) and "content" in parsed_data: + text = parsed_data["content"] # 提取content用于意图分析 + conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息 + except (json.JSONDecodeError, TypeError): + pass + # 检查是否有明确的退出命令 filtered_text = remove_punctuation_and_length(text)[1] if await check_direct_exit(conn, filtered_text): @@ -29,6 +38,8 @@ async def handle_user_intent(conn, text): intent_result = await analyze_intent_with_llm(conn, text) if not intent_result: return False + # 会话开始时生成sentence_id + conn.sentence_id = str(uuid.uuid4().hex) # 处理各种意图 return await process_intent_result(conn, intent_result, text) @@ -79,11 +90,6 @@ async def process_intent_result(conn, intent_result, original_text): if function_name == "continue_chat": return False - if function_name == "play_music": - funcItem = conn.func_handler.get_function(function_name) - if not funcItem: - conn.func_handler.function_registry.register_function("play_music") - function_args = {} if "arguments" in intent_data["function_call"]: function_args = intent_data["function_call"]["arguments"] @@ -158,5 +164,19 @@ async def process_intent_result(conn, intent_result, original_text): def speak_txt(conn, text): + conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=conn.sentence_id, + sentence_type=SentenceType.FIRST, + content_type=ContentType.ACTION, + ) + ) conn.tts.tts_one_sentence(conn, ContentType.TEXT, content_detail=text) - conn.dialogue.put(Message(role="assistant", content=text)) + conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=conn.sentence_id, + sentence_type=SentenceType.LAST, + content_type=ContentType.ACTION, + ) + ) + conn.dialogue.put(Message(role="assistant", content=text)) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 465b081aa..506ef02d1 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -4,6 +4,7 @@ from core.utils.output_counter import check_device_output_limit from core.handle.abortHandle import handleAbortMessage import time import asyncio +import json from core.handle.sendAudioHandle import SentenceType from core.utils.util import audio_to_data @@ -38,6 +39,31 @@ async def resume_vad_detection(conn): async def startToChat(conn, text): + # 检查输入是否是JSON格式(包含说话人信息) + speaker_name = None + actual_text = text + + try: + # 尝试解析JSON格式的输入 + if text.strip().startswith('{') and text.strip().endswith('}'): + data = json.loads(text) + if 'speaker' in data and 'content' in data: + speaker_name = data['speaker'] + actual_text = data['content'] + conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}") + + # 直接使用JSON格式的文本,不解析 + actual_text = text + except (json.JSONDecodeError, KeyError): + # 如果解析失败,继续使用原始文本 + pass + + # 保存说话人信息到连接对象 + if speaker_name: + conn.current_speaker = speaker_name + else: + conn.current_speaker = None + if conn.need_bind: await check_bind_device(conn) return @@ -52,16 +78,16 @@ async def startToChat(conn, text): if conn.client_is_speaking: await handleAbortMessage(conn) - # 首先进行意图分析 - intent_handled = await handle_user_intent(conn, text) + # 首先进行意图分析,使用实际文本内容 + intent_handled = await handle_user_intent(conn, actual_text) if intent_handled: # 如果意图已被处理,不再进行聊天 return - # 意图未被处理,继续常规聊天流程 - await send_stt_message(conn, text) - conn.executor.submit(conn.chat, text) + # 意图未被处理,继续常规聊天流程,使用实际文本内容 + await send_stt_message(conn, actual_text) + conn.executor.submit(conn.chat, actual_text) async def no_voice_close_connect(conn, have_voice): @@ -133,4 +159,4 @@ async def check_bind_device(conn): await send_stt_message(conn, text) music_path = "config/assets/bind_not_found.wav" opus_packets, _ = audio_to_data(music_path) - conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) + conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index eb9f565fb..0d606dead 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -2,54 +2,17 @@ import json import asyncio import time from core.providers.tts.dto.dto import SentenceType -from core.utils.util import get_string_no_punctuation_or_emoji, analyze_emotion -from loguru import logger +from core.utils import textUtils TAG = __name__ -emoji_map = { - "neutral": "😶", - "happy": "🙂", - "laughing": "😆", - "funny": "😂", - "sad": "😔", - "angry": "😠", - "crying": "😭", - "loving": "😍", - "embarrassed": "😳", - "surprised": "😲", - "shocked": "😱", - "thinking": "🤔", - "winking": "😉", - "cool": "😎", - "relaxed": "😌", - "delicious": "🤤", - "kissy": "😘", - "confident": "😏", - "sleepy": "😴", - "silly": "😜", - "confused": "🙄", -} - async def sendAudioMessage(conn, sentenceType, audios, text): # 发送句子开始消息 conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") - if text is not None: - emotion = analyze_emotion(text) - emoji = emoji_map.get(emotion, "🙂") # 默认使用笑脸 - await conn.websocket.send( - json.dumps( - { - "type": "llm", - "text": emoji, - "emotion": emotion, - "session_id": conn.session_id, - } - ) - ) + pre_buffer = False - if conn.tts.tts_audio_first_sentence and text is not None: + if conn.tts.tts_audio_first_sentence: conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}") conn.tts.tts_audio_first_sentence = False pre_buffer = True @@ -58,8 +21,6 @@ async def sendAudioMessage(conn, sentenceType, audios, text): await sendAudio(conn, audios, pre_buffer) - await send_tts_message(conn, "sentence_end", text) - # 发送结束消息(如果是最后一个文本) if conn.llm_finish_task and sentenceType == SentenceType.LAST: await send_tts_message(conn, "stop", None) @@ -76,7 +37,6 @@ async def sendAudio(conn, audios, pre_buffer=True): frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码 start_time = time.perf_counter() play_position = 0 - last_reset_time = time.perf_counter() # 记录最后的重置时间 # 仅当第一句话时执行预缓冲 if pre_buffer: @@ -111,7 +71,7 @@ async def send_tts_message(conn, state, text=None): """发送 TTS 状态消息""" message = {"type": "tts", "state": state, "session_id": conn.session_id} if text is not None: - message["text"] = text + message["text"] = textUtils.check_emoji(text) # TTS播放结束 if state == "stop": @@ -137,9 +97,25 @@ async def send_stt_message(conn, text): return """发送 STT 状态消息""" - stt_text = get_string_no_punctuation_or_emoji(text) + + # 解析JSON格式,提取实际的用户说话内容 + display_text = text + try: + # 尝试解析JSON格式 + if text.strip().startswith('{') and text.strip().endswith('}'): + parsed_data = json.loads(text) + if isinstance(parsed_data, dict) and "content" in parsed_data: + # 如果是包含说话人信息的JSON格式,只显示content部分 + display_text = parsed_data["content"] + # 保存说话人信息到conn对象 + if "speaker" in parsed_data: + conn.current_speaker = parsed_data["speaker"] + except (json.JSONDecodeError, TypeError): + # 如果不是JSON格式,直接使用原始文本 + display_text = text + stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text) await conn.websocket.send( json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id}) ) conn.client_is_speaking = True - await send_tts_message(conn, "start") + await send_tts_message(conn, "start") \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index cdb20ac58..d72673194 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -1,4 +1,5 @@ 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 @@ -45,6 +46,7 @@ async def handleTextMessage(conn, message): 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"] # 保留原始文本 filtered_len, filtered_text = remove_punctuation_and_length( original_text @@ -164,4 +166,4 @@ async def handleTextMessage(conn, message): else: conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") except json.JSONDecodeError: - await conn.websocket.send(message) + await conn.websocket.send(message) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py new file mode 100644 index 000000000..1d7e775e6 --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py @@ -0,0 +1,343 @@ +import json +import time +import uuid +import hmac +import base64 +import hashlib +import asyncio +import requests +import websockets +import opuslib_next +import random +from typing import Optional, Tuple, List +from urllib import parse +from datetime import datetime +from config.logger import setup_logging +from core.providers.asr.base import ASRProviderBase +from core.providers.asr.dto.dto import InterfaceType + +TAG = __name__ +logger = setup_logging() + + +class AccessToken: + @staticmethod + def _encode_text(text): + encoded_text = parse.quote_plus(text) + return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") + + @staticmethod + def _encode_dict(dic): + keys = dic.keys() + dic_sorted = [(key, dic[key]) for key in sorted(keys)] + encoded_text = parse.urlencode(dic_sorted) + return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") + + @staticmethod + def create_token(access_key_id, access_key_secret): + parameters = { + "AccessKeyId": access_key_id, + "Action": "CreateToken", + "Format": "JSON", + "RegionId": "cn-shanghai", + "SignatureMethod": "HMAC-SHA1", + "SignatureNonce": str(uuid.uuid1()), + "SignatureVersion": "1.0", + "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "Version": "2019-02-28", + } + query_string = AccessToken._encode_dict(parameters) + string_to_sign = ( + "GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string) + ) + secreted_string = hmac.new( + bytes(access_key_secret + "&", encoding="utf-8"), + bytes(string_to_sign, encoding="utf-8"), + hashlib.sha1, + ).digest() + signature = base64.b64encode(secreted_string) + signature = AccessToken._encode_text(signature) + full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string) + response = requests.get(full_url) + if response.ok: + root_obj = response.json() + if "Token" in root_obj: + return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"] + return None, None + + +class ASRProvider(ASRProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__() + self.interface_type = InterfaceType.STREAM + self.config = config + self.text = "" + self.decoder = opuslib_next.Decoder(16000, 1) + self.asr_ws = None + self.forward_task = None + self.is_processing = False + self.server_ready = False # 服务器准备状态 + + # 基础配置 + self.access_key_id = config.get("access_key_id") + self.access_key_secret = config.get("access_key_secret") + self.appkey = config.get("appkey") + self.token = config.get("token") + self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com") + # 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议 + if "-internal." in self.host: + self.ws_url = f"ws://{self.host}/ws/v1" + else: + # 默认使用wss协议 + self.ws_url = f"wss://{self.host}/ws/v1" + + self.max_sentence_silence = config.get("max_sentence_silence") + self.output_dir = config.get("output_dir", "./audio_output") + self.delete_audio_file = delete_audio_file + self.expire_time = None + + # Token管理 + if self.access_key_id and self.access_key_secret: + self._refresh_token() + elif not self.token: + raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token") + + def _refresh_token(self): + """刷新Token""" + self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret) + if not self.token: + raise ValueError("无法获取有效的访问Token") + + try: + expire_str = str(expire_time_str).strip() + if expire_str.isdigit(): + expire_time = datetime.fromtimestamp(int(expire_str)) + else: + expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") + self.expire_time = expire_time.timestamp() - 60 + except: + self.expire_time = None + + def _is_token_expired(self): + """检查Token是否过期""" + return self.expire_time and time.time() > self.expire_time + + async def open_audio_channels(self, conn): + await super().open_audio_channels(conn) + + async def receive_audio(self, conn, audio, audio_have_voice): + # 初始化音频缓存 + if not hasattr(conn, 'asr_audio_for_voiceprint'): + conn.asr_audio_for_voiceprint = [] + + # 存储音频数据 + if audio: + conn.asr_audio_for_voiceprint.append(audio) + + conn.asr_audio.append(audio) + conn.asr_audio = conn.asr_audio[-10:] + + # 只在有声音且没有连接时建立连接 + if audio_have_voice and not self.is_processing: + try: + await self._start_recognition(conn) + except Exception as e: + logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}") + await self._cleanup(conn) + return + + if self.asr_ws and self.is_processing and self.server_ready: + try: + pcm_frame = self.decoder.decode(audio, 960) + await self.asr_ws.send(pcm_frame) + except Exception as e: + logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}") + await self._cleanup(conn) + + async def _start_recognition(self, conn): + """开始识别会话""" + if self._is_token_expired(): + self._refresh_token() + + # 建立连接 + headers = {"X-NLS-Token": self.token} + self.asr_ws = await websockets.connect( + self.ws_url, + additional_headers=headers, + max_size=1000000000, + ping_interval=None, + ping_timeout=None, + close_timeout=5, + ) + + self.is_processing = True + self.server_ready = False # 重置服务器准备状态 + self.forward_task = asyncio.create_task(self._forward_results(conn)) + + # 发送开始请求 + start_request = { + "header": { + "namespace": "SpeechTranscriber", + "name": "StartTranscription", + "status": 20000000, + "message_id": ''.join(random.choices('0123456789abcdef', k=32)), + "task_id": ''.join(random.choices('0123456789abcdef', k=32)), + "status_text": "Gateway:SUCCESS:Success.", + "appkey": self.appkey + }, + "payload": { + "format": "pcm", + "sample_rate": 16000, + "enable_intermediate_result": True, + "enable_punctuation_prediction": True, + "enable_inverse_text_normalization": True, + "max_sentence_silence": self.max_sentence_silence, + "enable_voice_detection": False, + } + } + await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False)) + logger.bind(tag=TAG).info("已发送开始请求,等待服务器准备...") + + async def _forward_results(self, conn): + """转发识别结果""" + try: + while self.asr_ws and not conn.stop_event.is_set(): + try: + response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0) + result = json.loads(response) + + header = result.get("header", {}) + payload = result.get("payload", {}) + message_name = header.get("name", "") + status = header.get("status", 0) + + if status != 20000000: + if status in [40000004, 40010004]: # 连接超时或客户端断开 + logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}") + break + elif status in [40270002, 40270003]: # 音频问题 + logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}") + continue + else: + logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}") + continue + + # 收到TranscriptionStarted表示服务器准备好接收音频数据 + if message_name == "TranscriptionStarted": + self.server_ready = True + logger.bind(tag=TAG).info("服务器已准备,开始发送缓存音频...") + + # 发送缓存音频 + if conn.asr_audio: + for cached_audio in conn.asr_audio[-10:]: + try: + pcm_frame = self.decoder.decode(cached_audio, 960) + await self.asr_ws.send(pcm_frame) + except Exception as e: + logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}") + break + continue + + if message_name == "TranscriptionResultChanged": + # 中间结果 + text = payload.get("result", "") + if text: + self.text = text + elif message_name == "SentenceEnd": + # 最终结果 + text = payload.get("result", "") + if text: + self.text = text + conn.reset_vad_states() + # 传递缓存的音频数据 + audio_data = getattr(conn, 'asr_audio_for_voiceprint', []) + await self.handle_voice_stop(conn, audio_data) + # 清空缓存 + conn.asr_audio_for_voiceprint = [] + break + elif message_name == "TranscriptionCompleted": + # 识别完成 + self.is_processing = False + break + + except asyncio.TimeoutError: + continue + except websockets.exceptions.ConnectionClosed: + break + except Exception as e: + logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}") + break + + except Exception as e: + logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}") + finally: + await self._cleanup(conn) + + async def _cleanup(self, conn): + """清理资源""" + logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}") + + # 清理连接的音频缓存 + if conn and hasattr(conn, 'asr_audio_for_voiceprint'): + conn.asr_audio_for_voiceprint = [] + + # 判断是否需要发送终止请求 + should_stop = self.is_processing or self.server_ready + + # 发送停止识别请求 + if self.asr_ws and should_stop: + try: + stop_msg = { + "header": { + "namespace": "SpeechTranscriber", + "name": "StopTranscription", + "status": 20000000, + "message_id": ''.join(random.choices('0123456789abcdef', k=32)), + "status_text": "Client:Stop", + "appkey": self.appkey + } + } + logger.bind(tag=TAG).info("正在发送ASR终止请求") + await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False)) + await asyncio.sleep(0.1) + logger.bind(tag=TAG).info("ASR终止请求已发送") + except Exception as e: + logger.bind(tag=TAG).error(f"ASR终止请求发送失败: {e}") + + # 状态重置(在终止请求发送后) + self.is_processing = False + self.server_ready = False + logger.bind(tag=TAG).info("ASR状态已重置") + + # 清理任务 + if self.forward_task and not self.forward_task.done(): + self.forward_task.cancel() + try: + await asyncio.wait_for(self.forward_task, timeout=1.0) + except Exception as e: + logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}") + finally: + self.forward_task = None + + # 关闭连接 + if self.asr_ws: + try: + logger.bind(tag=TAG).debug("正在关闭WebSocket连接") + await asyncio.wait_for(self.asr_ws.close(), timeout=2.0) + logger.bind(tag=TAG).debug("WebSocket连接已关闭") + except Exception as e: + logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}") + finally: + self.asr_ws = None + + logger.bind(tag=TAG).info("ASR会话清理完成") + + async def speech_to_text(self, opus_data, session_id, audio_format): + """获取识别结果""" + result = self.text + self.text = "" + return result, None + + async def close(self): + """关闭资源""" + await self._cleanup() \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 71098a200..4529e6f62 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -1,15 +1,18 @@ import os import wave -import copy import uuid import queue import asyncio import traceback import threading import opuslib_next +import json +import io +import time +import concurrent.futures from abc import ABC, abstractmethod from config.logger import setup_logging -from typing import Optional, Tuple, List +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 @@ -24,10 +27,7 @@ class ASRProviderBase(ABC): pass # 打开音频通道 - # 这里默认是非流式的处理方式 - # 流式处理方式请在子类中重写 async def open_audio_channels(self, conn): - # tts 消化线程 conn.asr_priority_thread = threading.Thread( target=self.asr_text_priority_thread, args=(conn,), daemon=True ) @@ -52,41 +52,171 @@ class ASRProviderBase(ABC): continue # 接收音频 - # 这里默认是非流式的处理方式 - # 流式处理方式请在子类中重写 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 - # 如果本次没有声音,本段也没声音,就把声音丢弃了 + conn.asr_audio.append(audio) - if have_voice == False and conn.client_have_voice == False: + if not have_voice and not conn.client_have_voice: conn.asr_audio = conn.asr_audio[-10:] return - # 如果本段有声音,且已经停止了 if conn.client_voice_stop: - asr_audio_task = copy.deepcopy(conn.asr_audio) + asr_audio_task = conn.asr_audio.copy() conn.asr_audio.clear() - - # 音频太短了,无法识别 conn.reset_vad_states() + if len(asr_audio_task) > 15: await self.handle_voice_stop(conn, asr_audio_task) # 处理语音停止 - async def handle_voice_stop(self, conn, asr_audio_task): - raw_text, _ = await self.speech_to_text( - asr_audio_task, conn.session_id, conn.audio_format - ) # 确保ASR模块返回原始文本 - conn.logger.bind(tag=TAG).info(f"识别文本: {raw_text}") - text_len, _ = remove_punctuation_and_length(raw_text) - self.stop_ws_connection() - if text_len > 0: - # 使用自定义模块进行上报 - await startToChat(conn, raw_text) - enqueue_asr_report(conn, raw_text, asr_audio_task) + async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): + """并行处理ASR和声纹识别""" + try: + total_start_time = time.monotonic() + + # 准备音频数据 + 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) + + # 预先准备WAV数据 + wav_data = None + # 使用连接的声纹识别提供者 + if conn.voiceprint_provider and combined_pcm_data: + wav_data = self._pcm_to_wav(combined_pcm_data) + + + # 定义ASR任务 + 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耗时: {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失败: {e}") + return ("", None) + + # 定义声纹识别任务 + def run_voiceprint(): + if not wav_data: + return None + try: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + # 使用连接的声纹识别提供者 + 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"声纹识别失败: {e}") + return None + + # 使用线程池执行器并行运行 + 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) + + # 等待两个线程都完成 + 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} + + + # 处理结果 + raw_text, file_path = results.get("asr", ("", None)) + speaker_name = results.get("voiceprint", None) + + # 记录识别结果 + if raw_text: + logger.bind(tag=TAG).info(f"识别文本: {raw_text}") + if speaker_name: + logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}") + + # 性能监控 + total_time = time.monotonic() - total_start_time + logger.bind(tag=TAG).info(f"总处理耗时: {total_time:.3f}s") + + # 检查文本长度 + text_len, _ = remove_punctuation_and_length(raw_text) + self.stop_ws_connection() + + if text_len > 0: + # 构建包含说话人信息的JSON字符串 + enhanced_text = self._build_enhanced_text(raw_text, speaker_name) + + # 使用自定义模块进行上报 + await startToChat(conn, enhanced_text) + enqueue_asr_report(conn, enhanced_text, asr_audio_task) + + except Exception as e: + logger.bind(tag=TAG).error(f"处理语音停止失败: {e}") + import traceback + logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}") + + def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str: + """构建包含说话人信息的文本""" + 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: + """将PCM数据转换为WAV格式""" + if len(pcm_data) == 0: + logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV") + return b"" + + # 确保数据长度是偶数(16位音频) + if len(pcm_data) % 2 != 0: + pcm_data = pcm_data[:-1] + + # 创建WAV文件头 + wav_buffer = io.BytesIO() + try: + with wave.open(wav_buffer, 'wb') as wav_file: + wav_file.setnchannels(1) # 单声道 + wav_file.setsampwidth(2) # 16位 + wav_file.setframerate(16000) # 16kHz采样率 + 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转换失败: {e}") + return b"" def stop_ws_connection(self): pass @@ -113,27 +243,29 @@ class ASRProviderBase(ABC): pass @staticmethod - def decode_opus(opus_data: List[bytes]) -> bytes: + def decode_opus(opus_data: List[bytes]) -> List[bytes]: """将Opus音频数据解码为PCM数据""" try: - decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + decoder = opuslib_next.Decoder(16000, 1) pcm_data = [] - buffer_size = 960 # 每次处理960个采样点 - - for opus_packet in opus_data: + buffer_size = 960 # 每次处理960个采样点 (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: + 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解码错误,跳过当前数据包: {e}") - continue + logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}") except Exception as e: - logger.bind(tag=TAG).error(f"音频处理错误: {e}", exc_info=True) - continue - + logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}") + return pcm_data + except Exception as e: - logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}", exc_info=True) - return [] + logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}") + return [] \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/asr/doubao_stream.py b/main/xiaozhi-server/core/providers/asr/doubao_stream.py index 31704b969..35dce8882 100644 --- a/main/xiaozhi-server/core/providers/asr/doubao_stream.py +++ b/main/xiaozhi-server/core/providers/asr/doubao_stream.py @@ -1,351 +1,271 @@ +import time +import os +import uuid import json import gzip -import uuid -import asyncio import websockets -import opuslib_next -from core.providers.asr.base import ASRProviderBase from config.logger import setup_logging +from typing import Optional, Tuple, List +from core.providers.asr.base import ASRProviderBase from core.providers.asr.dto.dto import InterfaceType + TAG = __name__ logger = setup_logging() +CLIENT_FULL_REQUEST = 0b0001 +CLIENT_AUDIO_ONLY_REQUEST = 0b0010 + +NO_SEQUENCE = 0b0000 +NEG_SEQUENCE = 0b0010 + +SERVER_FULL_RESPONSE = 0b1001 +SERVER_ACK = 0b1011 +SERVER_ERROR_RESPONSE = 0b1111 + +NO_SERIALIZATION = 0b0000 +JSON = 0b0001 +THRIFT = 0b0011 +CUSTOM_TYPE = 0b1111 +NO_COMPRESSION = 0b0000 +GZIP = 0b0001 +CUSTOM_COMPRESSION = 0b1111 + + +def parse_response(res): + """ + protocol_version(4 bits), header_size(4 bits), + message_type(4 bits), message_type_specific_flags(4 bits) + serialization_method(4 bits) message_compression(4 bits) + reserved (8bits) 保留字段 + header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) + payload 类似与http 请求体 + """ + protocol_version = res[0] >> 4 + header_size = res[0] & 0x0F + message_type = res[1] >> 4 + message_type_specific_flags = res[1] & 0x0F + serialization_method = res[2] >> 4 + message_compression = res[2] & 0x0F + reserved = res[3] + header_extensions = res[4 : header_size * 4] + payload = res[header_size * 4 :] + result = {} + payload_msg = None + payload_size = 0 + if message_type == SERVER_FULL_RESPONSE: + payload_size = int.from_bytes(payload[:4], "big", signed=True) + payload_msg = payload[4:] + elif message_type == SERVER_ACK: + seq = int.from_bytes(payload[:4], "big", signed=True) + result["seq"] = seq + if len(payload) >= 8: + payload_size = int.from_bytes(payload[4:8], "big", signed=False) + payload_msg = payload[8:] + elif message_type == SERVER_ERROR_RESPONSE: + code = int.from_bytes(payload[:4], "big", signed=False) + result["code"] = code + payload_size = int.from_bytes(payload[4:8], "big", signed=False) + payload_msg = payload[8:] + if payload_msg is None: + return result + if message_compression == GZIP: + payload_msg = gzip.decompress(payload_msg) + if serialization_method == JSON: + payload_msg = json.loads(str(payload_msg, "utf-8")) + elif serialization_method != NO_SERIALIZATION: + payload_msg = str(payload_msg, "utf-8") + result["payload_msg"] = payload_msg + result["payload_size"] = payload_size + return result + class ASRProvider(ASRProviderBase): - def __init__(self, config, delete_audio_file): + def __init__(self, config: dict, delete_audio_file: bool): super().__init__() - self.interface_type = InterfaceType.STREAM - self.config = config - self.text = "" - self.max_retries = 3 - self.retry_delay = 2 - self.decoder = opuslib_next.Decoder(16000, 1) - self.asr_ws = None - self.forward_task = None - self.is_processing = False # 添加处理状态标志 - - # 配置参数 - self.appid = str(config.get("appid")) + self.interface_type = InterfaceType.NON_STREAM + self.appid = config.get("appid") self.cluster = config.get("cluster") self.access_token = config.get("access_token") self.boosting_table_name = config.get("boosting_table_name", "") self.correct_table_name = config.get("correct_table_name", "") - self.output_dir = config.get("output_dir", "tmp/") + self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file - # 火山引擎ASR配置 - self.ws_url = "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel" - self.uid = config.get("uid", "streaming_asr_service") - self.workflow = config.get( - "workflow", "audio_in,resample,partition,vad,fe,decode,itn,nlu_punctuate" - ) - self.result_type = config.get("result_type", "single") - self.format = config.get("format", "pcm") - self.codec = config.get("codec", "pcm") - self.rate = config.get("sample_rate", 16000) - self.language = config.get("language", "zh-CN") - self.bits = config.get("bits", 16) - self.channel = config.get("channel", 1) - self.auth_method = config.get("auth_method", "token") - self.secret = config.get("secret", "access_secret") + self.host = "openspeech.bytedance.com" + self.ws_url = f"wss://{self.host}/api/v2/asr" + self.success_code = 1000 + self.seg_duration = 15000 - async def open_audio_channels(self, conn): - await super().open_audio_channels(conn) + # 确保输出目录存在 + os.makedirs(self.output_dir, exist_ok=True) - async def receive_audio(self, conn, audio, audio_have_voice): - conn.asr_audio.append(audio) - conn.asr_audio = conn.asr_audio[-10:] + @staticmethod + def _generate_header( + message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE + ) -> bytearray: + """Generate protocol header.""" + header = bytearray() + header_size = 1 + header.append((0b0001 << 4) | header_size) # Protocol version + header.append((message_type << 4) | message_type_specific_flags) + header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression + header.append(0x00) # reserved + return header - # 如果本次有声音,且之前没有建立连接 - if audio_have_voice and self.asr_ws is None and not self.is_processing: - try: - self.is_processing = True - # 建立新的WebSocket连接 - headers = self.token_auth() if self.auth_method == "token" else None - logger.bind(tag=TAG).info(f"正在连接ASR服务,headers: {headers}") - - self.asr_ws = await websockets.connect( - self.ws_url, - additional_headers=headers, - max_size=1000000000, - ping_interval=None, - ping_timeout=None, - close_timeout=10, - ) - - # 发送初始化请求 - request_params = self.construct_request(str(uuid.uuid4())) - try: - payload_bytes = str.encode(json.dumps(request_params)) - payload_bytes = gzip.compress(payload_bytes) - full_client_request = self.generate_header() - full_client_request.extend((len(payload_bytes)).to_bytes(4, "big")) - full_client_request.extend(payload_bytes) - - logger.bind(tag=TAG).info(f"发送初始化请求: {request_params}") - await self.asr_ws.send(full_client_request) - - # 等待初始化响应 - init_res = await self.asr_ws.recv() - result = self.parse_response(init_res) - logger.bind(tag=TAG).info(f"收到初始化响应: {result}") - - # 检查初始化响应 - if "code" in result and result["code"] != 1000: - error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}" - logger.bind(tag=TAG).error(error_msg) - raise Exception(error_msg) - - except Exception as e: - logger.bind(tag=TAG).error(f"发送初始化请求失败: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - raise e - - # 启动接收ASR结果的异步任务 - self.forward_task = asyncio.create_task(self._forward_asr_results(conn)) - - # 发送缓存的音频数据 - if conn.asr_audio and len(conn.asr_audio) > 0: - for cached_audio in conn.asr_audio[-10:]: - try: - pcm_frame = self.decoder.decode(cached_audio, 960) - payload = gzip.compress(pcm_frame) - audio_request = bytearray( - self.generate_audio_default_header() - ) - audio_request.extend(len(payload).to_bytes(4, "big")) - audio_request.extend(payload) - await self.asr_ws.send(audio_request) - except Exception as e: - logger.bind(tag=TAG).info( - f"发送缓存音频数据时发生错误: {e}" - ) - - except Exception as e: - logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None - self.is_processing = False - return - - # 发送当前音频数据 - if self.asr_ws and self.is_processing: - try: - pcm_frame = self.decoder.decode(audio, 960) - payload = gzip.compress(pcm_frame) - audio_request = bytearray(self.generate_audio_default_header()) - audio_request.extend(len(payload).to_bytes(4, "big")) - audio_request.extend(payload) - await self.asr_ws.send(audio_request) - except Exception as e: - logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}") - - async def _forward_asr_results(self, conn): - try: - while self.asr_ws and not conn.stop_event.is_set(): - try: - response = await self.asr_ws.recv() - result = self.parse_response(response) - logger.bind(tag=TAG).debug(f"收到ASR结果: {result}") - - if "payload_msg" in result: - payload = result["payload_msg"] - # 检查是否是错误码1013(无有效语音) - if "code" in payload and payload["code"] == 1013: - # 静默处理,不记录错误日志 - continue - - if "result" in payload: - utterances = payload["result"].get("utterances", []) - # 检查duration和空文本的情况 - if ( - payload.get("audio_info", {}).get("duration", 0) > 2000 - and not utterances - and not payload["result"].get("text") - ): - logger.bind(tag=TAG).error(f"识别文本:空") - self.text = "" - conn.reset_vad_states() - await self.handle_voice_stop(conn, None) - break - - for utterance in utterances: - if utterance.get("definite", False): - self.text = utterance["text"] - logger.bind(tag=TAG).info( - f"识别到文本: {self.text}" - ) - conn.reset_vad_states() - await self.handle_voice_stop(conn, None) - break - elif "error" in payload: - error_msg = payload.get("error", "未知错误") - logger.bind(tag=TAG).error(f"ASR服务返回错误: {error_msg}") - break - - except websockets.ConnectionClosed: - logger.bind(tag=TAG).info("ASR服务连接已关闭") - self.is_processing = False - break - except Exception as e: - logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - self.is_processing = False - break - - except Exception as e: - logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - finally: - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None - self.is_processing = False - - def stop_ws_connection(self): - if self.asr_ws: - asyncio.create_task(self.asr_ws.close()) - self.asr_ws = None - self.is_processing = False - - def construct_request(self, reqid): - req = { + def _construct_request(self, reqid) -> dict: + """Construct the request payload.""" + return { "app": { - "appid": self.appid, + "appid": f"{self.appid}", "cluster": self.cluster, "token": self.access_token, }, - "user": {"uid": self.uid}, + "user": { + "uid": str(uuid.uuid4()), + }, "request": { "reqid": reqid, - "workflow": self.workflow, - "show_utterances": True, - "result_type": self.result_type, + "show_utterances": False, "sequence": 1, "boosting_table_name": self.boosting_table_name, "correct_table_name": self.correct_table_name, - "end_window_size": 200, }, "audio": { - "format": self.format, - "codec": self.codec, - "rate": self.rate, - "language": self.language, - "bits": self.bits, - "channel": self.channel, - "sample_rate": self.rate, + "format": "raw", + "rate": 16000, + "language": "zh-CN", + "bits": 16, + "channel": 1, + "codec": "raw", }, } - logger.bind(tag=TAG).debug( - f"构造请求参数: {json.dumps(req, ensure_ascii=False)}" - ) - return req - def token_auth(self): - return { - "X-Api-App-Key": self.appid, - "X-Api-Access-Key": self.access_token, - "X-Api-Resource-Id": "volc.bigasr.sauc.duration", - "X-Api-Connect-Id": str(uuid.uuid4()), - } - - def generate_header( - self, - version=0x01, - message_type=0x01, - message_type_specific_flags=0x00, - serial_method=0x01, - compression_type=0x01, - reserved_data=0x00, - extension_header: bytes = b"", - ): - header = bytearray() - header_size = int(len(extension_header) / 4) + 1 - header.append((version << 4) | header_size) - header.append((message_type << 4) | message_type_specific_flags) - header.append((serial_method << 4) | compression_type) - header.append(reserved_data) - header.extend(extension_header) - return header - - def generate_audio_default_header(self): - return self.generate_header( - version=0x01, - message_type=0x02, - message_type_specific_flags=0x00, - serial_method=0x01, - compression_type=0x01, - ) - - def generate_last_audio_default_header(self): - return self.generate_header( - version=0x01, - message_type=0x02, - message_type_specific_flags=0x02, - serial_method=0x01, - compression_type=0x01, - ) - - def parse_response(self, res: bytes) -> dict: + async def _send_request( + self, audio_data: List[bytes], segment_size: int + ) -> Optional[str]: + """Send request to Volcano ASR service.""" try: - # 检查响应长度 - if len(res) < 4: - logger.bind(tag=TAG).error(f"响应数据长度不足: {len(res)}") - return {"error": "响应数据长度不足"} + auth_header = {"Authorization": "Bearer; {}".format(self.access_token)} + async with websockets.connect( + self.ws_url, additional_headers=auth_header + ) as websocket: + # Prepare request data + request_params = self._construct_request(str(uuid.uuid4())) + payload_bytes = str.encode(json.dumps(request_params)) + payload_bytes = gzip.compress(payload_bytes) + full_client_request = self._generate_header() + full_client_request.extend( + (len(payload_bytes)).to_bytes(4, "big") + ) # payload size(4 bytes) + full_client_request.extend(payload_bytes) # payload - # 获取消息头 - header = res[:4] - message_type = header[1] >> 4 + # Send header and metadata + # full_client_request + await websocket.send(full_client_request) + res = await websocket.recv() + result = parse_response(res) + if ( + "payload_msg" in result + and result["payload_msg"]["code"] != self.success_code + and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误 + ): + logger.bind(tag=TAG).error(f"ASR error: {result}") + return None - # 如果是错误响应 - if message_type == 0x0F: # SERVER_ERROR_RESPONSE - code = int.from_bytes(res[4:8], "big", signed=False) - msg_length = int.from_bytes(res[8:12], "big", signed=False) - error_msg = json.loads(res[12:].decode("utf-8")) - return { - "code": code, - "msg_length": msg_length, - "payload_msg": error_msg, - } + for seq, (chunk, last) in enumerate( + self.slice_data(audio_data, segment_size), 1 + ): + if last: + audio_only_request = self._generate_header( + message_type=CLIENT_AUDIO_ONLY_REQUEST, + message_type_specific_flags=NEG_SEQUENCE, + ) + else: + audio_only_request = self._generate_header( + message_type=CLIENT_AUDIO_ONLY_REQUEST + ) + payload_bytes = gzip.compress(chunk) + audio_only_request.extend( + (len(payload_bytes)).to_bytes(4, "big") + ) # payload size(4 bytes) + audio_only_request.extend(payload_bytes) # payload + # Send audio data + await websocket.send(audio_only_request) - # 获取JSON数据(跳过12字节头部) - try: - json_data = res[12:].decode("utf-8") - result = json.loads(json_data) - logger.bind(tag=TAG).debug(f"成功解析JSON响应: {result}") - return {"payload_msg": result} - except (UnicodeDecodeError, json.JSONDecodeError) as e: - logger.bind(tag=TAG).error(f"JSON解析失败: {str(e)}") - logger.bind(tag=TAG).error(f"原始数据: {res}") - raise + # Receive response + response = await websocket.recv() + result = parse_response(response) + + if ( + "payload_msg" in result + and result["payload_msg"]["code"] == self.success_code + ): + if len(result["payload_msg"]["result"]) > 0: + return result["payload_msg"]["result"][0]["text"] + return None + elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: + # 无有效语音,返回空字符串 + return "" + else: + logger.bind(tag=TAG).error(f"ASR error: {result}") + return None except Exception as e: - logger.bind(tag=TAG).error(f"解析响应失败: {str(e)}") - logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}") - raise + logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True) + return None - async def speech_to_text(self, opus_data, session_id, audio_format): - result = self.text - self.text = "" # 清空text - return result, None + @staticmethod + def slice_data(data: bytes, chunk_size: int) -> (list, bool): + """ + slice data + :param data: wav data + :param chunk_size: the segment size in one request + :return: segment data, last flag + """ + data_len = len(data) + offset = 0 + while offset + chunk_size < data_len: + yield data[offset : offset + chunk_size], False + offset += chunk_size + else: + yield data[offset:data_len], True - async def close(self): - """资源清理方法""" - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None - if self.forward_task: - self.forward_task.cancel() - try: - await self.forward_task - except asyncio.CancelledError: + async def speech_to_text( + self, opus_data: List[bytes], session_id: str, audio_format="opus" + ) -> Tuple[Optional[str], Optional[str]]: + """将语音数据转换为文本""" + + file_path = None + try: + # 合并所有opus数据包 + if audio_format == "pcm": + pcm_data = opus_data + else: + pcm_data = self.decode_opus(opus_data) + combined_pcm_data = b"".join(pcm_data) + + # 判断是否保存为WAV文件 + if self.delete_audio_file: pass - self.forward_task = None - self.is_processing = False + else: + file_path = self.save_audio_to_file(pcm_data, session_id) + + # 直接使用PCM数据 + # 计算分段大小 (单声道, 16bit, 16kHz采样率) + size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate + segment_size = int(size_per_sec * self.seg_duration / 1000) + + # 语音识别 + start_time = time.time() + text = await self._send_request(combined_pcm_data, segment_size) + if text: + logger.bind(tag=TAG).debug( + f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" + ) + return text, file_path + return "", file_path + + except Exception as e: + logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) + return "", file_path \ No newline at end of file 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 9e5ade806..634e0ce31 100644 --- a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py +++ b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py @@ -40,6 +40,7 @@ class ASRProvider(ASRProviderBase): 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") # 支持 paraformer self.delete_audio_file = delete_audio_file # 确保输出目录存在 @@ -73,16 +74,27 @@ class ASRProvider(ASRProviderBase): raise with CaptureOutput(): - self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice( - model=self.model_path, - tokens=self.tokens_path, - num_threads=2, - sample_rate=16000, - feature_dim=80, - decoding_method="greedy_search", - debug=False, - use_itn=True, - ) + if self.model_type == "paraformer": + self.model = sherpa_onnx.OfflineRecognizer.from_paraformer( + paraformer=self.model_path, + tokens=self.tokens_path, + num_threads=2, + sample_rate=16000, + feature_dim=80, + 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, + sample_rate=16000, + feature_dim=80, + decoding_method="greedy_search", + debug=False, + use_itn=True, + ) def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]: """ @@ -148,4 +160,4 @@ class ASRProvider(ASRProviderBase): os.remove(file_path) logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") except Exception as e: - logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") + logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index d13c4df4a..89770780a 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -16,10 +16,11 @@ class IntentProvider(IntentProviderBase): super().__init__(config) self.llm = None self.promot = "" - # 添加缓存管理 - self.intent_cache = {} # 缓存意图识别结果 - self.cache_expiry = 600 # 缓存有效期10分钟 - self.cache_max_size = 100 # 最多缓存100个意图 + # 导入全局缓存管理器 + from core.utils.cache.manager import cache_manager, CacheType + + self.cache_manager = cache_manager + self.CacheType = CacheType self.history_count = 4 # 默认使用最近4条对话记录 def get_intent_system_prompt(self, functions_list: str) -> str: @@ -102,27 +103,6 @@ class IntentProvider(IntentProviderBase): ) return prompt - def clean_cache(self): - """清理过期缓存""" - now = time.time() - # 找出过期键 - expired_keys = [ - k - for k, v in self.intent_cache.items() - if now - v["timestamp"] > self.cache_expiry - ] - for key in expired_keys: - del self.intent_cache[key] - - # 如果缓存太大,移除最旧的条目 - if len(self.intent_cache) > self.cache_max_size: - # 按时间戳排序并保留最新的条目 - sorted_items = sorted( - self.intent_cache.items(), key=lambda x: x[1]["timestamp"] - ) - for key, _ in sorted_items[: len(sorted_items) - self.cache_max_size]: - del self.intent_cache[key] - def replyResult(self, text: str, original_text: str): llm_result = self.llm.response_no_stream( system_prompt=text, @@ -145,21 +125,16 @@ class IntentProvider(IntentProviderBase): logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}") # 计算缓存键 - cache_key = hashlib.md5(text.encode()).hexdigest() + cache_key = hashlib.md5((conn.device_id + text).encode()).hexdigest() # 检查缓存 - if cache_key in self.intent_cache: - cache_entry = self.intent_cache[cache_key] - # 检查缓存是否过期 - if time.time() - cache_entry["timestamp"] <= self.cache_expiry: - cache_time = time.time() - total_start_time - logger.bind(tag=TAG).debug( - f"使用缓存的意图: {cache_key} -> {cache_entry['intent']}, 耗时: {cache_time:.4f}秒" - ) - return cache_entry["intent"] - - # 清理缓存 - self.clean_cache() + cached_intent = self.cache_manager.get(self.CacheType.INTENT, cache_key) + if cached_intent is not None: + cache_time = time.time() - total_start_time + logger.bind(tag=TAG).debug( + f"使用缓存的意图: {cache_key} -> {cached_intent}, 耗时: {cache_time:.4f}秒" + ) + return cached_intent if self.promot == "": functions = conn.func_handler.get_functions() @@ -259,10 +234,7 @@ class IntentProvider(IntentProviderBase): conn.dialogue.dialogue = clean_history # 添加到缓存 - self.intent_cache[cache_key] = { - "intent": intent, - "timestamp": time.time(), - } + self.cache_manager.set(self.CacheType.INTENT, cache_key, intent) # 后处理时间 postprocess_time = time.time() - postprocess_start_time @@ -272,10 +244,7 @@ class IntentProvider(IntentProviderBase): return intent else: # 添加到缓存 - self.intent_cache[cache_key] = { - "intent": intent, - "timestamp": time.time(), - } + self.cache_manager.set(self.CacheType.INTENT, cache_key, intent) # 后处理时间 postprocess_time = time.time() - postprocess_start_time @@ -290,4 +259,4 @@ class IntentProvider(IntentProviderBase): f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒" ) # 如果解析失败,默认返回继续聊天意图 - return '{"intent": "继续聊天"}' + return '{"intent": "继续聊天"}' \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py index 7f114d9c1..bc7909593 100644 --- a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py +++ b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py @@ -79,10 +79,11 @@ short_term_memory_prompt_only_content = """ 1、总结user的重要信息,以便在未来的对话中提供更个性化的服务 2、不要重复总结,不要遗忘之前记忆,除非原来的记忆超过了1800字内,否则不要遗忘、不要压缩用户的历史记忆 3、用户操控的设备音量、播放音乐、天气、退出、不想对话等和用户本身无关的内容,这些信息不需要加入到总结中 -4、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中 -5、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的 -6、只需要返回总结摘要,严格控制在1800字内 -7、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容 +4、聊天内容中的今天的日期时间、今天的天气情况与用户事件无关的数据,这些信息如果当成记忆存储会影响后序对话,这些信息不需要加入到总结中 +5、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中 +6、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的 +7、只需要返回总结摘要,严格控制在1800字内 +8、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容 """ @@ -143,11 +144,6 @@ class MemoryProvider(MemoryProviderBase): yaml.dump(all_memory, f, allow_unicode=True) async def save_memory(self, msgs): - # Check if llm is set - if not hasattr(self, 'llm') or self.llm is None: - logger.bind(tag=TAG).error("LLM is not set for memory provider") - return None - # 打印使用的模型信息 model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__)) logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}") @@ -203,4 +199,4 @@ class MemoryProvider(MemoryProviderBase): return self.short_memory async def query_memory(self, query: str) -> str: - return self.short_memory + return self.short_memory \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index 728493ec8..fe613b0c1 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -51,13 +51,13 @@ class ServerPluginExecutor(ToolExecutor): tools = {} # 获取必要的函数 - necessary_functions = ["handle_exit_intent", "get_time", "get_lunar"] + necessary_functions = ["handle_exit_intent", "get_lunar"] # 获取配置中的函数 config_functions = self.config["Intent"][ self.config["selected_module"]["Intent"] ].get("functions", []) - + # 转换为列表 if not isinstance(config_functions, list): try: @@ -81,4 +81,4 @@ class ServerPluginExecutor(ToolExecutor): def has_tool(self, tool_name: str) -> bool: """检查是否有指定的服务端插件工具""" - return tool_name in all_function_registry + return tool_name in all_function_registry \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/aliyun.py b/main/xiaozhi-server/core/providers/tts/aliyun.py index c9b3d1307..fe5b1896d 100644 --- a/main/xiaozhi-server/core/providers/tts/aliyun.py +++ b/main/xiaozhi-server/core/providers/tts/aliyun.py @@ -6,11 +6,14 @@ import base64 import requests from datetime import datetime from core.providers.tts.base import TTSProviderBase - +from config.logger import setup_logging import time import uuid from urllib import parse +TAG = __name__ +logger = setup_logging() + class AccessToken: @staticmethod @@ -199,4 +202,4 @@ class TTSProvider(TTSProviderBase): f"{__name__} status_code: {resp.status_code} response: {resp.content}" ) except Exception as e: - raise Exception(f"{__name__} error: {e}") + raise Exception(f"{__name__} error: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py new file mode 100644 index 000000000..55b93b790 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py @@ -0,0 +1,653 @@ +import uuid +import json +import hmac +import hashlib +import base64 +import time +import queue +import asyncio +import traceback +from asyncio import Task +import websockets +import os +from datetime import datetime +from urllib import parse +from core.providers.tts.base import TTSProviderBase +from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType +from core.utils.tts import MarkdownCleaner +from core.utils import opus_encoder_utils, textUtils +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +class AccessToken: + @staticmethod + def _encode_text(text): + encoded_text = parse.quote_plus(text) + return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") + + @staticmethod + def _encode_dict(dic): + keys = dic.keys() + dic_sorted = [(key, dic[key]) for key in sorted(keys)] + encoded_text = parse.urlencode(dic_sorted) + return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") + + @staticmethod + def create_token(access_key_id, access_key_secret): + parameters = { + "AccessKeyId": access_key_id, + "Action": "CreateToken", + "Format": "JSON", + "RegionId": "cn-shanghai", # 使用上海地域进行Token获取 + "SignatureMethod": "HMAC-SHA1", + "SignatureNonce": str(uuid.uuid1()), + "SignatureVersion": "1.0", + "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "Version": "2019-02-28", + } + + query_string = AccessToken._encode_dict(parameters) + string_to_sign = ( + "GET" + + "&" + + AccessToken._encode_text("/") + + "&" + + AccessToken._encode_text(query_string) + ) + + secreted_string = hmac.new( + bytes(access_key_secret + "&", encoding="utf-8"), + bytes(string_to_sign, encoding="utf-8"), + hashlib.sha1, + ).digest() + signature = base64.b64encode(secreted_string) + signature = AccessToken._encode_text(signature) + + full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % ( + signature, + query_string, + ) + + import requests + + response = requests.get(full_url) + if response.ok: + root_obj = response.json() + key = "Token" + if key in root_obj: + token = root_obj[key]["Id"] + expire_time = root_obj[key]["ExpireTime"] + return token, expire_time + return None, None + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + + # 设置为流式接口类型 + self.interface_type = InterfaceType.DUAL_STREAM + + # 基础配置 + self.access_key_id = config.get("access_key_id") + self.access_key_secret = config.get("access_key_secret") + self.appkey = config.get("appkey") + self.format = config.get("format", "pcm") + self.audio_file_type = config.get("format", "pcm") + + # 采样率配置 + sample_rate = config.get("sample_rate", "16000") + self.sample_rate = int(sample_rate) if sample_rate else 16000 + + # 音色配置 - CosyVoice大模型音色 + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice", "longxiaochun") # CosyVoice默认音色 + + # 音频参数配置 + volume = config.get("volume", "50") + self.volume = int(volume) if volume else 50 + + speech_rate = config.get("speech_rate", "0") + self.speech_rate = int(speech_rate) if speech_rate else 0 + + pitch_rate = config.get("pitch_rate", "0") + self.pitch_rate = int(pitch_rate) if pitch_rate else 0 + + # WebSocket配置 + self.host = config.get("host", "nls-gateway-cn-beijing.aliyuncs.com") + # 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议 + if "-internal." in self.host: + self.ws_url = f"ws://{self.host}/ws/v1" + else: + # 默认使用wss协议 + self.ws_url = f"wss://{self.host}/ws/v1" + self.ws = None + self._monitor_task = None + self.last_active_time = None + + # 专属tts设置 + self.message_id = "" + + # 创建Opus编码器 + self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( + sample_rate=16000, channels=1, frame_size_ms=60 + ) + + # Token管理 + if self.access_key_id and self.access_key_secret: + self._refresh_token() + else: + self.token = config.get("token") + self.expire_time = None + + def _refresh_token(self): + """刷新Token并记录过期时间""" + if self.access_key_id and self.access_key_secret: + self.token, expire_time_str = AccessToken.create_token( + self.access_key_id, self.access_key_secret + ) + if not expire_time_str: + raise ValueError("无法获取有效的Token过期时间") + + expire_str = str(expire_time_str).strip() + + try: + if expire_str.isdigit(): + expire_time = datetime.fromtimestamp(int(expire_str)) + else: + expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") + self.expire_time = expire_time.timestamp() - 60 + except Exception as e: + raise ValueError(f"无效的过期时间格式: {expire_str}") from e + else: + self.expire_time = None + + if not self.token: + raise ValueError("无法获取有效的访问Token") + + def _is_token_expired(self): + """检查Token是否过期""" + if not self.expire_time: + return False + return time.time() > self.expire_time + + async def _ensure_connection(self): + """确保WebSocket连接可用""" + try: + if self._is_token_expired(): + logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...") + self._refresh_token() + current_time = time.time() + if self.ws and current_time - self.last_active_time < 10: + # 10秒内才可以复用链接进行连续对话 + logger.bind(tag=TAG).info(f"使用已有链接...") + return self.ws + logger.bind(tag=TAG).info("开始建立新连接...") + + self.ws = await websockets.connect( + self.ws_url, + additional_headers={"X-NLS-Token": self.token}, + ping_interval=30, + ping_timeout=10, + close_timeout=10, + ) + logger.bind(tag=TAG).info("WebSocket连接建立成功") + self.last_active_time = time.time() + return self.ws + except Exception as e: + logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}") + self.ws = None + self.last_active_time = None + raise + + def tts_text_priority_thread(self): + """流式文本处理线程""" + while not self.conn.stop_event.is_set(): + try: + message = self.tts_text_queue.get(timeout=1) + logger.bind(tag=TAG).debug( + f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}" + ) + + if message.sentence_type == SentenceType.FIRST: + self.conn.client_abort = False + + if self.conn.client_abort: + logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") + continue + + if message.sentence_type == SentenceType.FIRST: + # 初始化参数 + try: + if not getattr(self.conn, "sentence_id", None): + self.conn.sentence_id = uuid.uuid4().hex + logger.bind(tag=TAG).info( + f"自动生成新的 会话ID: {self.conn.sentence_id}" + ) + + # aliyunStream独有的参数生成 + self.message_id = str(uuid.uuid4().hex) + + logger.bind(tag=TAG).info("开始启动TTS会话...") + future = asyncio.run_coroutine_threadsafe( + self.start_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + future.result() + self.before_stop_play_files.clear() + logger.bind(tag=TAG).info("TTS会话启动成功") + + except Exception as e: + logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") + continue + + elif ContentType.TEXT == message.content_type: + if message.content_detail: + try: + logger.bind(tag=TAG).debug( + f"开始发送TTS文本: {message.content_detail}" + ) + future = asyncio.run_coroutine_threadsafe( + self.text_to_speak(message.content_detail, None), + loop=self.conn.loop, + ) + future.result() + logger.bind(tag=TAG).debug("TTS文本发送成功") + except Exception as e: + logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}") + continue + + elif ContentType.FILE == message.content_type: + logger.bind(tag=TAG).info( + f"添加音频文件到待播放列表: {message.content_file}" + ) + if message.content_file and os.path.exists(message.content_file): + # 先处理文件音频数据 + file_audio = self._process_audio_file(message.content_file) + self.before_stop_play_files.append( + (file_audio, message.content_detail) + ) + + if message.sentence_type == SentenceType.LAST: + try: + logger.bind(tag=TAG).info("开始结束TTS会话...") + future = asyncio.run_coroutine_threadsafe( + self.finish_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + future.result() + except Exception as e: + logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}") + continue + + except queue.Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( + f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + ) + + async def text_to_speak(self, text, _): + try: + if self.ws is None: + logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本") + return + filtered_text = MarkdownCleaner.clean_markdown(text) + run_request = { + "header": { + "message_id": self.message_id, + "task_id": self.conn.sentence_id, + "namespace": "FlowingSpeechSynthesizer", + "name": "RunSynthesis", + "appkey": self.appkey, + }, + "payload": {"text": filtered_text}, + } + await self.ws.send(json.dumps(run_request)) + self.last_active_time = time.time() + return + + except Exception as e: + logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}") + if self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None + raise + + async def start_session(self, session_id): + logger.bind(tag=TAG).info(f"开始会话~~{session_id}") + try: + # 会话开始时检测上个会话的监听状态 + if ( + self._monitor_task is not None + and isinstance(self._monitor_task, Task) + and not self._monitor_task.done() + ): + logger.bind(tag=TAG).info( + "检测到未完成的上个会话,关闭监听任务和连接..." + ) + await self.close() + + # 建立新连接 + await self._ensure_connection() + + # 启动监听任务 + self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) + + start_request = { + "header": { + "message_id": self.message_id, + "task_id": self.conn.sentence_id, + "namespace": "FlowingSpeechSynthesizer", + "name": "StartSynthesis", + "appkey": self.appkey, + }, + "payload": { + "voice": self.voice, + "format": self.format, + "sample_rate": self.sample_rate, + "volume": self.volume, + "speech_rate": self.speech_rate, + "pitch_rate": self.pitch_rate, + "enable_subtitle": True, + }, + } + await self.ws.send(json.dumps(start_request)) + self.last_active_time = time.time() + logger.bind(tag=TAG).info("会话启动请求已发送") + except Exception as e: + logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") + # 确保清理资源 + await self.close() + raise + + async def finish_session(self, session_id): + logger.bind(tag=TAG).info(f"关闭会话~~{session_id}") + try: + if self.ws: + stop_request = { + "header": { + "message_id": self.message_id, + "task_id": self.conn.sentence_id, + "namespace": "FlowingSpeechSynthesizer", + "name": "StopSynthesis", + "appkey": self.appkey, + } + } + await self.ws.send(json.dumps(stop_request)) + logger.bind(tag=TAG).info("会话结束请求已发送") + self.last_active_time = time.time() + if self._monitor_task: + try: + await self._monitor_task + except Exception as e: + logger.bind(tag=TAG).error( + f"等待监听任务完成时发生错误: {str(e)}" + ) + finally: + self._monitor_task = None + except Exception as e: + logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}") + # 确保清理资源 + await self.close() + raise + + async def close(self): + """资源清理""" + if self._monitor_task: + try: + self._monitor_task.cancel() + await self._monitor_task + except asyncio.CancelledError: + pass + except Exception as e: + logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}") + self._monitor_task = None + + if self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None + self.last_active_time = None + + async def _start_monitor_tts_response(self): + """监听TTS响应""" + opus_datas_cache = [] + is_first_sentence = True + first_sentence_segment_count = 0 # 添加计数器 + try: + session_finished = False # 标记会话是否正常结束 + while not self.conn.stop_event.is_set(): + try: + msg = await self.ws.recv() + self.last_active_time = time.time() + # 检查客户端是否中止 + if self.conn.client_abort: + logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应") + break + if isinstance(msg, str): # 文本控制消息 + try: + data = json.loads(msg) + header = data.get("header", {}) + event_name = header.get("name") + if event_name == "SynthesisStarted": + logger.bind(tag=TAG).debug("TTS合成已启动") + self.tts_audio_queue.put( + (SentenceType.FIRST, [], None) + ) + elif event_name == "SentenceBegin": + opus_datas_cache = [] + elif event_name == "SentenceEnd": + if ( + not is_first_sentence + or first_sentence_segment_count > 10 + ): + # 发送缓存的数据 + if self.conn.tts_MessageText: + logger.bind(tag=TAG).info( + f"句子语音生成成功: {self.conn.tts_MessageText}" + ) + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus_datas_cache, self.conn.tts_MessageText) + ) + self.conn.tts_MessageText = None + else: + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus_datas_cache, None) + ) + # 第一句话结束后,将标志设置为False + is_first_sentence = False + elif event_name == "SynthesisCompleted": + logger.bind(tag=TAG).debug(f"会话结束~~") + self._process_before_stop_play_files() + session_finished = True + break + except json.JSONDecodeError: + logger.bind(tag=TAG).warning("收到无效的JSON消息") + # 二进制消息(音频数据) + elif isinstance(msg, (bytes, bytearray)): + logger.bind(tag=TAG).debug(f"推送数据到队列里面~~") + opus_datas = self.opus_encoder.encode_pcm_to_opus(msg, False) + logger.bind(tag=TAG).debug( + f"推送数据到队列里面帧数~~{len(opus_datas)}" + ) + if is_first_sentence: + first_sentence_segment_count += 1 + if first_sentence_segment_count <= 6: + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus_datas, None) + ) + else: + opus_datas_cache.extend(opus_datas) + else: + # 后续句子缓存 + opus_datas_cache.extend(opus_datas) + + except websockets.ConnectionClosed: + logger.bind(tag=TAG).warning("WebSocket连接已关闭") + break + except Exception as e: + logger.bind(tag=TAG).error( + f"处理TTS响应时出错: {e}\n{traceback.format_exc()}" + ) + break + # 仅在连接异常时才关闭 + if not session_finished and self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None + # 监听任务退出时清理引用 + finally: + self._monitor_task = None + + def to_tts(self, text: str) -> list: + """非流式TTS处理,用于测试及保存音频文件的场景""" + try: + # 创建新的事件循环 + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + # 生成会话ID + session_id = uuid.uuid4().hex + # 存储音频数据 + audio_data = [] + + async def _generate_audio(): + # 刷新Token(如果需要) + if self._is_token_expired(): + self._refresh_token() + + # 建立WebSocket连接 + ws = await websockets.connect( + self.ws_url, + additional_headers={"X-NLS-Token": self.token}, + ping_interval=30, + ping_timeout=10, + close_timeout=10, + ) + try: + # 发送StartSynthesis请求 + start_message_id = str(uuid.uuid4().hex) + start_request = { + "header": { + "message_id": start_message_id, + "task_id": session_id, + "namespace": "FlowingSpeechSynthesizer", + "name": "StartSynthesis", + "appkey": self.appkey, + }, + "payload": { + "voice": self.voice, + "format": self.format, + "sample_rate": self.sample_rate, + "volume": self.volume, + "speech_rate": self.speech_rate, + "pitch_rate": self.pitch_rate, + "enable_subtitle": True, + }, + } + await ws.send(json.dumps(start_request)) + + # 等待SynthesisStarted响应 + synthesis_started = False + while not synthesis_started: + msg = await ws.recv() + if isinstance(msg, str): + data = json.loads(msg) + header = data.get("header", {}) + if header.get("name") == "SynthesisStarted": + synthesis_started = True + logger.bind(tag=TAG).debug("TTS合成已启动") + elif header.get("name") == "TaskFailed": + error_info = data.get("payload", {}).get( + "error_info", {} + ) + error_code = error_info.get("error_code") + error_message = error_info.get( + "error_message", "未知错误" + ) + raise Exception( + f"启动合成失败: {error_code} - {error_message}" + ) + + # 发送文本合成请求 + filtered_text = MarkdownCleaner.clean_markdown(text) + run_message_id = str(uuid.uuid4().hex) + run_request = { + "header": { + "message_id": run_message_id, + "task_id": session_id, + "namespace": "FlowingSpeechSynthesizer", + "name": "RunSynthesis", + "appkey": self.appkey, + }, + "payload": {"text": filtered_text}, + } + await ws.send(json.dumps(run_request)) + + # 发送停止合成请求 + stop_message_id = str(uuid.uuid4().hex) + stop_request = { + "header": { + "message_id": stop_message_id, + "task_id": session_id, + "namespace": "FlowingSpeechSynthesizer", + "name": "StopSynthesis", + "appkey": self.appkey, + } + } + await ws.send(json.dumps(stop_request)) + + # 接收音频数据 + synthesis_completed = False + while not synthesis_completed: + msg = await ws.recv() + if isinstance(msg, (bytes, bytearray)): + # 编码为Opus并收集 + opus_frames = self.opus_encoder.encode_pcm_to_opus( + msg, False + ) + audio_data.extend(opus_frames) + elif isinstance(msg, str): + data = json.loads(msg) + header = data.get("header", {}) + event_name = header.get("name") + if event_name == "SynthesisCompleted": + synthesis_completed = True + logger.bind(tag=TAG).debug("TTS合成完成") + elif event_name == "TaskFailed": + error_info = data.get("payload", {}).get( + "error_info", {} + ) + error_code = error_info.get("error_code") + error_message = error_info.get( + "error_message", "未知错误" + ) + raise Exception( + f"合成失败: {error_code} - {error_message}" + ) + finally: + try: + await ws.close() + except: + pass + + loop.run_until_complete(_generate_audio()) + loop.close() + + return audio_data + except Exception as e: + logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}") + return [] \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 223cb807a..c9b4041a8 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -50,6 +50,7 @@ class TTSProviderBase(ABC): ";", ";", ":", + "~", ) self.first_sentence_punctuations = ( ",", @@ -159,15 +160,8 @@ class TTSProviderBase(ABC): if conn.sentence_id: sentence_id = conn.sentence_id else: - sentence_id = str(uuid.uuid4()).replace("-", "") + sentence_id = str(uuid.uuid4().hex) conn.sentence_id = sentence_id - self.tts_text_queue.put( - TTSMessageDTO( - sentence_id=sentence_id, - sentence_type=SentenceType.FIRST, - content_type=ContentType.ACTION, - ) - ) # 对于单句的文本,进行分段处理 segments = re.split(r"([。!?!?;;\n])", content_detail) for seg in segments: @@ -180,13 +174,6 @@ class TTSProviderBase(ABC): content_file=content_file, ) ) - self.tts_text_queue.put( - TTSMessageDTO( - sentence_id=sentence_id, - sentence_type=SentenceType.LAST, - content_type=ContentType.ACTION, - ) - ) async def open_audio_channels(self, conn): self.conn = conn @@ -209,6 +196,8 @@ class TTSProviderBase(ABC): while not self.conn.stop_event.is_set(): try: message = self.tts_text_queue.get(timeout=1) + if message.sentence_type == SentenceType.FIRST: + self.conn.client_abort = False if self.conn.client_abort: logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") continue @@ -344,7 +333,6 @@ class TTSProviderBase(ABC): Returns: tuple: (sentence_type, audio_datas, content_detail) """ - audio_datas = [] if tts_file.endswith(".p3"): audio_datas, _ = p3.decode_opus_from_file(tts_file) elif self.conn.audio_format == "pcm": @@ -362,10 +350,8 @@ class TTSProviderBase(ABC): return audio_datas def _process_before_stop_play_files(self): - for tts_file, text in self.before_stop_play_files: - if tts_file and os.path.exists(tts_file): - audio_datas = self._process_audio_file(tts_file) - self.tts_audio_queue.put((SentenceType.MIDDLE, audio_datas, text)) + for audio_datas, text in self.before_stop_play_files: + self.tts_audio_queue.put((SentenceType.MIDDLE, audio_datas, text)) self.before_stop_play_files.clear() self.tts_audio_queue.put((SentenceType.LAST, [], None)) @@ -394,4 +380,4 @@ class TTSProviderBase(ABC): ) self.processed_chars += len(full_text) return True - return False + return False \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py index 1ebaf15a0..d4c89140e 100644 --- a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py +++ b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py @@ -10,7 +10,6 @@ from config.logger import setup_logging from core.utils import opus_encoder_utils from core.utils.util import check_model_key from core.providers.tts.base import TTSProviderBase -from core.handle.abortHandle import handleAbortMessage from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType from asyncio import Task @@ -53,10 +52,11 @@ EVENT_ConnectionFinished = 52 # 连接结束 # 上行Session事件 EVENT_StartSession = 100 - +EVENT_CancelSession = 101 EVENT_FinishSession = 102 # 下行Session事件 EVENT_SessionStarted = 150 +EVENT_SessionCanceled = 151 EVENT_SessionFinished = 152 EVENT_SessionFailed = 153 @@ -152,6 +152,12 @@ class TTSProvider(TTSProviderBase): self.voice = config.get("private_voice") else: self.voice = config.get("speaker") + speech_rate = config.get("speech_rate", "0") + loudness_rate = config.get("loudness_rate", "0") + pitch = config.get("pitch", "0") + self.speech_rate = int(speech_rate) if speech_rate else 0 + self.loudness_rate = int(loudness_rate) if loudness_rate else 0 + self.pitch = int(pitch) if pitch else 0 self.ws_url = config.get("ws_url") self.authorization = config.get("authorization") self.header = {"Authorization": f"{self.authorization}{self.access_token}"} @@ -175,6 +181,9 @@ class TTSProvider(TTSProviderBase): async def _ensure_connection(self): """建立新的WebSocket连接""" try: + if self.ws: + logger.bind(tag=TAG).info(f"使用已有链接...") + return self.ws logger.bind(tag=TAG).info("开始建立新连接...") ws_header = { "X-Api-App-Key": self.appId, @@ -200,9 +209,21 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug( f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}" ) + + if message.sentence_type == SentenceType.FIRST: + self.conn.client_abort = False + if self.conn.client_abort: - logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") - continue + try: + logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") + asyncio.run_coroutine_threadsafe( + self.cancel_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + continue + except Exception as e: + logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}") + continue if message.sentence_type == SentenceType.FIRST: # 初始化参数 @@ -217,7 +238,6 @@ class TTSProvider(TTSProviderBase): loop=self.conn.loop, ) future.result() - self.tts_audio_first_sentence = True self.before_stop_play_files.clear() logger.bind(tag=TAG).info("TTS会话启动成功") except Exception as e: @@ -244,9 +264,12 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).info( f"添加音频文件到待播放列表: {message.content_file}" ) - self.before_stop_play_files.append( - (message.content_file, message.content_detail) - ) + if message.content_file and os.path.exists(message.content_file): + # 先处理文件音频数据 + file_audio = self._process_audio_file(message.content_file) + self.before_stop_play_files.append( + (file_audio, message.content_detail) + ) if message.sentence_type == SentenceType.LAST: try: @@ -295,25 +318,15 @@ class TTSProvider(TTSProviderBase): async def start_session(self, session_id): logger.bind(tag=TAG).info(f"开始会话~~{session_id}") try: - task = self._monitor_task + # 会话开始时检测上个会话的监听状态 if ( - task is not None - and isinstance(task, Task) - and not task.done() + self._monitor_task is not None + and isinstance(self._monitor_task, Task) + and not self._monitor_task.done() ): - logger.bind(tag=TAG).info("等待上一个监听任务结束...") - if self.ws is not None: - logger.bind(tag=TAG).info("强制关闭上一个WebSocket连接以唤醒监听任务...") - try: - await self.ws.close() - except Exception as e: - logger.bind(tag=TAG).warning(f"关闭上一个ws异常: {e}") - self.ws = None - try: - await asyncio.wait_for(task, timeout=8) - except Exception as e: - logger.bind(tag=TAG).warning(f"等待监听任务异常: {e}") - self._monitor_task = None + logger.bind(tag=TAG).info("检测到未完成的上个会话,关闭监听任务和连接...") + await self.close() + # 建立新连接 await self._ensure_connection() @@ -336,19 +349,7 @@ class TTSProvider(TTSProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") # 确保清理资源 - if hasattr(self, "_monitor_task"): - try: - self._monitor_task.cancel() - await self._monitor_task - except: - pass - self._monitor_task = None - if self.ws: - try: - await self.ws.close() - except: - pass - self.ws = None + await self.close() raise async def finish_session(self, session_id): @@ -368,7 +369,7 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).info("会话结束请求已发送") # 等待监听任务完成 - if hasattr(self, "_monitor_task"): + if self._monitor_task: try: await self._monitor_task except Exception as e: @@ -378,28 +379,46 @@ class TTSProvider(TTSProviderBase): finally: self._monitor_task = None - # 关闭连接 - await self.close() except Exception as e: logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}") # 确保清理资源 - if hasattr(self, "_monitor_task"): - try: - self._monitor_task.cancel() - await self._monitor_task - except: - pass - self._monitor_task = None + await self.close() + raise + + async def cancel_session(self,session_id): + logger.bind(tag=TAG).info(f"取消会话,释放服务端资源~~{session_id}") + try: if self.ws: - try: - await self.ws.close() - except: - pass - self.ws = None + header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + serial_method=JSON, + ).as_bytes() + optional = Optional( + event=EVENT_CancelSession, sessionId=session_id + ).as_bytes() + payload = str.encode("{}") + await self.send_event(self.ws, header, optional, payload) + logger.bind(tag=TAG).info("会话取消请求已发送") + except Exception as e: + logger.bind(tag=TAG).error(f"取消会话失败: {str(e)}") + # 确保清理资源 + await self.close() raise async def close(self): """资源清理方法""" + # 取消监听任务 + if self._monitor_task: + try: + self._monitor_task.cancel() + await self._monitor_task + except asyncio.CancelledError: + pass + except Exception as e: + logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}") + self._monitor_task = None + if self.ws: try: await self.ws.close() @@ -413,6 +432,7 @@ class TTSProvider(TTSProviderBase): is_first_sentence = True first_sentence_segment_count = 0 # 添加计数器 try: + session_finished = False # 标记会话是否正常结束 while not self.conn.stop_event.is_set(): try: # 确保 `recv()` 运行在同一个 event loop @@ -420,12 +440,11 @@ class TTSProvider(TTSProviderBase): res = self.parser_response(msg) self.print_response(res, "send_text res:") - # 检查客户端是否中止 - if self.conn.client_abort: - logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应") + if res.optional.event == EVENT_SessionCanceled: + logger.bind(tag=TAG).debug(f"释放服务端资源成功~~") + session_finished = True break - - if res.optional.event == EVENT_TTSSentenceStart: + elif res.optional.event == EVENT_TTSSentenceStart: json_data = json.loads(res.payload.decode("utf-8")) self.tts_text = json_data.get("text", "") logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}") @@ -450,10 +469,10 @@ class TTSProvider(TTSProviderBase): (SentenceType.MIDDLE, opus_datas, None) ) else: - opus_datas_cache = opus_datas_cache + opus_datas + opus_datas_cache.extend(opus_datas) else: # 后续句子缓存 - opus_datas_cache = opus_datas_cache + opus_datas + opus_datas_cache.extend(opus_datas) elif res.optional.event == EVENT_TTSSentenceEnd: logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}") if not is_first_sentence or first_sentence_segment_count > 10: @@ -466,6 +485,7 @@ class TTSProvider(TTSProviderBase): elif res.optional.event == EVENT_SessionFinished: logger.bind(tag=TAG).debug(f"会话结束~~") self._process_before_stop_play_files() + session_finished = True break except websockets.ConnectionClosed: logger.bind(tag=TAG).warning("WebSocket连接已关闭") @@ -476,15 +496,15 @@ class TTSProvider(TTSProviderBase): ) traceback.print_exc() break - finally: - # 确保清理资源 - if self.ws: + # 仅在连接异常时才关闭 + if not session_finished and self.ws: try: await self.ws.close() except: pass self.ws = None - # 监听任务退出时清理引用 + # 监听任务退出时清理引用 + finally: self._monitor_task = None async def send_event( @@ -622,8 +642,15 @@ class TTSProvider(TTSProviderBase): "audio_params": { "format": audio_format, "sample_rate": audio_sample_rate, + "speech_rate": self.speech_rate, + "loudness_rate": self.loudness_rate }, }, + "additions": { + "post_process": { + "pitch": self.pitch + } + } } ) ) @@ -734,4 +761,4 @@ class TTSProvider(TTSProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}") - return [] + return [] \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/index_stream.py b/main/xiaozhi-server/core/providers/tts/index_stream.py new file mode 100644 index 000000000..c05614a3c --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/index_stream.py @@ -0,0 +1,264 @@ +import os +import queue +import asyncio +import traceback +import aiohttp +import requests +import time +from config.logger import setup_logging +from core.utils.tts import MarkdownCleaner +from core.providers.tts.base import TTSProviderBase +from core.utils import opus_encoder_utils, textUtils +from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.interface_type = InterfaceType.SINGLE_STREAM + self.voice = config.get("voice", "xiao_he") + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice", "xiao_he") + self.api_url = config.get("api_url", "http://8.138.114.124:11996/tts") + self.audio_format = "pcm" + self.before_stop_play_files = [] + self.segment_count = 0 + + # 创建Opus编码器 需注意接口返回的采样率为24000 + self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( + sample_rate=24000, channels=1, frame_size_ms=60 + ) + + # 文本缓冲区和PCM缓冲区 + self.text_buffer = "" + self.pcm_buffer = bytearray() + + def tts_text_priority_thread(self): + """流式文本处理线程""" + while not self.conn.stop_event.is_set(): + try: + message = self.tts_text_queue.get(timeout=1) + if message.sentence_type == SentenceType.FIRST: + # 初始化参数 + self.tts_stop_request = False + self.processed_chars = 0 + self.tts_text_buff = [] + self.segment_count = 0 + self.before_stop_play_files.clear() + elif ContentType.TEXT == message.content_type: + self.tts_text_buff.append(message.content_detail) + segment_text = self._get_segment_text() + if segment_text: + self.to_tts_single_stream(segment_text) + + elif ContentType.FILE == message.content_type: + logger.bind(tag=TAG).info( + f"添加音频文件到待播放列表: {message.content_file}" + ) + if message.content_file and os.path.exists(message.content_file): + # 先处理文件音频数据 + file_audio = self._process_audio_file(message.content_file) + self.before_stop_play_files.append( + (file_audio, message.content_detail) + ) + + if message.sentence_type == SentenceType.LAST: + # 处理剩余的文本 + self._process_remaining_text(True) + + except queue.Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( + f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + ) + + def _process_remaining_text(self, is_last=False): + """处理剩余的文本并生成语音 + Returns: + bool: 是否成功处理了文本 + """ + full_text = "".join(self.tts_text_buff) + remaining_text = full_text[self.processed_chars :] + if remaining_text: + segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text) + if segment_text: + self.to_tts_single_stream(segment_text, is_last) + self.processed_chars += len(full_text) + else: + self._process_before_stop_play_files() + else: + self._process_before_stop_play_files() + + def to_tts_single_stream(self, text, is_last=False): + try: + max_repeat_time = 5 + text = MarkdownCleaner.clean_markdown(text) + try: + asyncio.run(self.text_to_speak(text, is_last)) + except Exception as e: + logger.bind(tag=TAG).warning( + f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}" + ) + max_repeat_time -= 1 + + if max_repeat_time > 0: + logger.bind(tag=TAG).info( + f"语音生成成功: {text},重试{5 - max_repeat_time}次" + ) + else: + logger.bind(tag=TAG).error( + f"语音生成失败: {text},请检查网络或服务是否正常" + ) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}") + finally: + return None + + async def text_to_speak(self, text, is_last): + """流式处理TTS音频,每句只推送一次音频列表""" + payload = {"text": text, "character": self.voice} + + frame_bytes = int( + self.opus_encoder.sample_rate + * self.opus_encoder.channels # 1 + * self.opus_encoder.frame_size_ms + / 1000 + * 2 + ) # 16-bit = 2 bytes + try: + async with aiohttp.ClientSession() as session: + async with session.post(self.api_url, json=payload, timeout=10) as resp: + + if resp.status != 200: + logger.bind(tag=TAG).error( + f"TTS请求失败: {resp.status}, {await resp.text()}" + ) + self.tts_audio_queue.put((SentenceType.LAST, [], None)) + return + + self.pcm_buffer.clear() + opus_datas_cache = [] + + self.tts_audio_queue.put((SentenceType.FIRST, [], text)) + + # 处理音频流数据 + async for chunk in resp.content.iter_any(): + data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk + if not data: + continue + + self.pcm_buffer.extend(data) + + while len(self.pcm_buffer) >= frame_bytes: + frame = bytes(self.pcm_buffer[:frame_bytes]) + del self.pcm_buffer[:frame_bytes] + opus = self.opus_encoder.encode_pcm_to_opus( + frame, end_of_stream=False + ) + if opus: + if self.segment_count < 10: # 前10个片段直接发送 + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus, None) + ) + self.segment_count += 1 + else: + opus_datas_cache.extend(opus) + + # flush 剩余不足一帧的数据 + if self.pcm_buffer: + opus = self.opus_encoder.encode_pcm_to_opus( + bytes(self.pcm_buffer), end_of_stream=True + ) + if opus: + if self.segment_count < 10: # 前10个片段直接发送 + # 直接发送 + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus, None) + ) + self.segment_count += 1 + else: + # 后续片段缓存 + opus_datas_cache.extend(opus) + self.pcm_buffer.clear() + + # 如果不是前10个片段,发送缓存的数据 + if self.segment_count >= 10 and opus_datas_cache: + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus_datas_cache, None) + ) + + # 如果是最后一段,输出音频获取完毕 + if is_last: + self._process_before_stop_play_files() + + except Exception as e: + logger.bind(tag=TAG).error(f"TTS请求异常: {e}") + self.tts_audio_queue.put((SentenceType.LAST, [], None)) + + async def close(self): + """资源清理""" + await super().close() + if hasattr(self, "opus_encoder"): + self.opus_encoder.close() + + def to_tts(self, text: str) -> list: + """非流式TTS处理,用于测试及保存音频文件的场景 + + Args: + text: 要转换的文本 + + Returns: + list: 返回opus编码后的音频数据列表 + """ + start_time = time.time() + text = MarkdownCleaner.clean_markdown(text) + + payload = {"text": text, "character": self.character} + + try: + with requests.post(self.api_url, json=payload, timeout=5) as response: + if response.status_code != 200: + logger.bind(tag=TAG).error( + f"TTS请求失败: {response.status_code}, {response.text}" + ) + return [] + + logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒") + + # 使用opus编码器处理PCM数据 + opus_datas = [] + pcm_data = response.content + + # 计算每帧的字节数 + frame_bytes = int( + self.opus_encoder.sample_rate + * self.opus_encoder.channels + * self.opus_encoder.frame_size_ms + / 1000 + * 2 + ) + + # 分帧处理PCM数据 + for i in range(0, len(pcm_data), frame_bytes): + frame = pcm_data[i : i + frame_bytes] + if len(frame) < frame_bytes: + # 最后一帧可能不足,用0填充 + frame = frame + b"\x00" * (frame_bytes - len(frame)) + + opus = self.opus_encoder.encode_pcm_to_opus( + frame, end_of_stream=(i + frame_bytes >= len(pcm_data)) + ) + if opus: + opus_datas.extend(opus) + + return opus_datas + + except Exception as e: + logger.bind(tag=TAG).error(f"TTS请求异常: {e}") + return [] \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/linkerai.py b/main/xiaozhi-server/core/providers/tts/linkerai.py index ee1085406..94da16213 100644 --- a/main/xiaozhi-server/core/providers/tts/linkerai.py +++ b/main/xiaozhi-server/core/providers/tts/linkerai.py @@ -1,3 +1,4 @@ +import os import queue import asyncio import traceback @@ -51,7 +52,6 @@ class TTSProvider(TTSProviderBase): self.processed_chars = 0 self.tts_text_buff = [] self.segment_count = 0 - self.tts_audio_first_sentence = True self.before_stop_play_files.clear() elif ContentType.TEXT == message.content_type: self.tts_text_buff.append(message.content_detail) @@ -63,9 +63,12 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).info( f"添加音频文件到待播放列表: {message.content_file}" ) - self.before_stop_play_files.append( - (message.content_file, message.content_detail) - ) + if message.content_file and os.path.exists(message.content_file): + # 先处理文件音频数据 + file_audio = self._process_audio_file(message.content_file) + self.before_stop_play_files.append( + (file_audio, message.content_detail) + ) if message.sentence_type == SentenceType.LAST: # 处理剩余的文本 @@ -302,4 +305,4 @@ class TTSProvider(TTSProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"TTS请求异常: {e}") - return [] + return [] \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py b/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py new file mode 100644 index 000000000..605b3efd4 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py @@ -0,0 +1,230 @@ +import os +import uuid +import json +import requests +from datetime import datetime +from typing import Iterator, Optional, Union +from core.providers.tts.base import TTSProviderBase +from core.utils.util import parse_string_to_list + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.group_id = config.get("group_id") + self.api_key = config.get("api_key") + self.model = config.get("model") + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice_id") + + default_voice_setting = { + "voice_id": "female-shaonv", + "speed": 1, + "vol": 1, + "pitch": 0, + "emotion": "happy", + } + default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} + defult_audio_setting = { + "sample_rate": 32000, + "bitrate": 128000, + "format": "mp3", + "channel": 1, + } + self.voice_setting = { + **default_voice_setting, + **config.get("voice_setting", {}), + } + self.pronunciation_dict = { + **default_pronunciation_dict, + **config.get("pronunciation_dict", {}), + } + self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})} + self.timber_weights = parse_string_to_list(config.get("timber_weights")) + + if self.voice: + self.voice_setting["voice_id"] = self.voice + + self.host = "api.minimax.chat" + self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}" + self.header = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.api_key}", + } + self.audio_file_type = defult_audio_setting.get("format", "mp3") + + def generate_filename(self, extension=".mp3"): + return os.path.join( + self.output_file, + f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}", + ) + + async def text_to_speak(self, text, output_file): + """非流式语音合成(保留原有实现)""" + request_json = { + "model": self.model, + "text": text, + "stream": False, + "voice_setting": self.voice_setting, + "pronunciation_dict": self.pronunciation_dict, + "audio_setting": self.audio_setting, + } + + if type(self.timber_weights) is list and len(self.timber_weights) > 0: + request_json["timber_weights"] = self.timber_weights + request_json["voice_setting"]["voice_id"] = "" + + try: + resp = requests.post( + self.api_url, json.dumps(request_json), headers=self.header + ) + if resp.json()["base_resp"]["status_code"] == 0: + data = resp.json()["data"]["audio"] + audio_bytes = bytes.fromhex(data) + if output_file: + with open(output_file, "wb") as file_to_save: + file_to_save.write(audio_bytes) + else: + return audio_bytes + else: + raise Exception( + f"{__name__} status_code: {resp.status_code} response: {resp.content}" + ) + except Exception as e: + raise Exception(f"{__name__} error: {e}") + + def text_to_speak_stream( + self, + text: str, + chunk_callback: Optional[callable] = None + ) -> Iterator[bytes]: + """ + 流式语音合成方法 + :param text: 要合成的文本 + :param chunk_callback: 可选的回调函数,用于处理每个音频块 + :return: 生成器,每次产生一个音频数据块(bytes) + """ + request_json = { + "model": self.model, + "text": text, + "stream": True, + "voice_setting": self.voice_setting, + "pronunciation_dict": self.pronunciation_dict, + "audio_setting": self.audio_setting, + } + + if isinstance(self.timber_weights, list) and len(self.timber_weights) > 0: + request_json["timber_weights"] = self.timber_weights + request_json["voice_setting"]["voice_id"] = "" + + try: + with requests.post( + self.api_url, + data=json.dumps(request_json), + headers=self.header, + stream=True + ) as response: + + # 检查HTTP状态码 + if response.status_code != 200: + raise Exception( + f"HTTP error: {response.status_code}, response: {response.text}" + ) + + # 处理流式响应 + for line in response.iter_lines(): + if line: # 过滤空行 + # 检查是否为数据行 (SSE格式) + if line.startswith(b'data:'): + try: + data = json.loads(line[5:].strip()) # 去掉"data:"前缀 + + # 检查API状态码 + if data.get("base_resp", {}).get("status_code", -1) != 0: + raise Exception( + f"API error: {data.get('base_resp', {}).get('status_msg')}" + ) + + # 跳过非音频数据块 + if "extra_info" in data: + continue + + # 提取音频数据 + audio_hex = data.get("data", {}).get("audio") + if audio_hex: + audio_chunk = bytes.fromhex(audio_hex) + if chunk_callback: + chunk_callback(audio_chunk) + yield audio_chunk + + except json.JSONDecodeError: + # 忽略JSON解析错误(可能是心跳包等) + continue + except Exception as e: + raise e + + except Exception as e: + raise Exception(f"{__name__} stream error: {e}") + + def save_stream_to_file( + self, + text: str, + output_file: Optional[str] = None, + progress_callback: Optional[callable] = None + ) -> str: + """ + 流式合成并保存到文件 + :param text: 要合成的文本 + :param output_file: 输出文件路径,如果为None则自动生成 + :param progress_callback: 可选的回调函数,接收已写入的字节数 + :return: 保存的文件路径 + """ + if not output_file: + output_file = self.generate_filename(extension=f".{self.audio_file_type}") + + os.makedirs(os.path.dirname(output_file), exist_ok=True) + + total_bytes = 0 + try: + with open(output_file, "wb") as audio_file: + for audio_chunk in self.text_to_speak_stream(text): + audio_file.write(audio_chunk) + audio_file.flush() + total_bytes += len(audio_chunk) + if progress_callback: + progress_callback(total_bytes) + return output_file + except Exception as e: + # 清理可能创建的不完整文件 + if os.path.exists(output_file): + os.remove(output_file) + raise e + + def stream_to_audio_player(self, text: str, player_command: list = None): + """ + 流式合成并直接播放音频 + :param text: 要合成的文本 + :param player_command: 音频播放器命令,默认使用mpv + """ + if player_command is None: + player_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"] + + try: + import subprocess + player_process = subprocess.Popen( + player_command, + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + for audio_chunk in self.text_to_speak_stream(text): + player_process.stdin.write(audio_chunk) + player_process.stdin.flush() + + player_process.stdin.close() + player_process.wait() + except Exception as e: + raise Exception(f"Audio player error: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py b/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py new file mode 100644 index 000000000..bda6b47fa --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py @@ -0,0 +1,180 @@ +import os +import uuid +import json +import asyncio +import websockets +import ssl +from datetime import datetime +from core.providers.tts.base import TTSProviderBase +from core.utils.util import parse_string_to_list + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.group_id = config.get("group_id") + self.api_key = config.get("api_key") + self.model = config.get("model") + + # 初始化语音设置 + default_voice_setting = { + "voice_id": "female-shaonv", + "speed": 1, + "vol": 1, + "pitch": 0, + "emotion": "happy", + } + default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} + default_audio_setting = { + "sample_rate": 32000, + "bitrate": 128000, + "format": "mp3", + "channel": 1, + } + + # 合并配置 + self.voice_setting = { + **default_voice_setting, + **config.get("voice_setting", {}), + } + self.pronunciation_dict = { + **default_pronunciation_dict, + **config.get("pronunciation_dict", {}), + } + self.audio_setting = { + **default_audio_setting, + **config.get("audio_setting", {}) + } + self.timber_weights = parse_string_to_list(config.get("timber_weights")) + + # 设置语音ID + if config.get("private_voice"): + self.voice_setting["voice_id"] = config.get("private_voice") + elif config.get("voice_id"): + self.voice_setting["voice_id"] = config.get("voice_id") + + # WebSocket配置 + self.ws_url = "wss://api.minimaxi.com/ws/v1/t2a_v2" + self.headers = { + "Authorization": f"Bearer {self.api_key}", + "GroupId": self.group_id + } + self.audio_file_type = self.audio_setting.get("format", "mp3") + + def generate_filename(self, extension=".mp3"): + """生成唯一的音频文件名""" + return os.path.join( + self.output_file, + f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}", + ) + + async def _establish_connection(self): + """建立WebSocket连接""" + ssl_context = ssl.create_default_context() + ssl_context.check_hostname = False + ssl_context.verify_mode = ssl.CERT_NONE + + try: + ws = await websockets.connect( + self.ws_url, + additional_headers=self.headers, + ssl=ssl_context + ) + connected = json.loads(await ws.recv()) + if connected.get("event") == "connected_success": + print("连接成功") + return ws + return None + except Exception as e: + print(f"连接失败: {e}") + return None + + async def _start_task(self, websocket): + """发送任务开始请求""" + start_msg = { + "event": "task_start", + "model": self.model, + "voice_setting": self.voice_setting, + "pronunciation_dict": self.pronunciation_dict, + "audio_setting": self.audio_setting + } + + if self.timber_weights and len(self.timber_weights) > 0: + start_msg["timber_weights"] = self.timber_weights + start_msg["voice_setting"]["voice_id"] = "" + + await websocket.send(json.dumps(start_msg)) + response = json.loads(await websocket.recv()) + return response.get("event") == "task_started" + + async def _continue_task(self, websocket, text): + """发送继续请求并收集音频数据""" + await websocket.send(json.dumps({ + "event": "task_continue", + "text": text + })) + + audio_chunks = [] + while True: + response = json.loads(await websocket.recv()) + if "data" in response and "audio" in response["data"]: + audio_chunks.append(response["data"]["audio"]) + if response.get("is_final"): + break + return "".join(audio_chunks) + + async def _close_connection(self, websocket): + """关闭连接""" + if websocket: + await websocket.send(json.dumps({"event": "task_finish"})) + await websocket.close() + print("连接已关闭") + + async def text_to_speak(self, text, output_file=None): + """主方法:文本转语音""" + ws = await self._establish_connection() + if not ws: + raise Exception("无法建立WebSocket连接") + + try: + if not await self._start_task(ws): + raise Exception("任务启动失败") + + hex_audio = await self._continue_task(ws, text) + audio_bytes = bytes.fromhex(hex_audio) + + # 保存到文件或返回二进制数据 + if output_file: + with open(output_file, "wb") as f: + f.write(audio_bytes) + print(f"音频已保存为{output_file}") + return output_file + else: + # 返回音频二进制数据(不播放) + return audio_bytes + + finally: + await self._close_connection(ws) + + +async def main(): + """测试用主函数""" + # 示例配置 + config = { + "group_id": "YOUR_GROUP_ID", # 替换为实际的group_id + "api_key": "YOUR_API_KEY", # 替换为实际的api_key + "model": "your-model", # 替换为实际的模型名称 + "voice_id": "male-qn-qingse", + "voice_setting": { + "speed": 1.2, + "emotion": "happy" + } + } + + tts = TTSProvider(config, delete_audio_file=True) + output_file = tts.generate_filename() + await tts.text_to_speak("这是一个测试文本,用于验证流式语音合成功能", output_file) + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/paddle_speech.py b/main/xiaozhi-server/core/providers/tts/paddle_speech.py new file mode 100644 index 000000000..891678e07 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/paddle_speech.py @@ -0,0 +1,152 @@ +import asyncio +import json +import base64 +import aiohttp +import numpy as np +import io +import wave +import websockets +from core.providers.tts.base import TTSProviderBase +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.url = config.get("url", "ws://192.168.1.10:8092/paddlespeech/tts/streaming") + self.protocol = config.get("protocol", "websocket") + self.spk_id = config.get("spk_id", 0) + self.sample_rate = config.get("sample_rate", 24000) + self.speed = config.get("speed", 1.0) + self.volume = config.get("volume", 1.0) + self.save_path = config.get("save_path", "./streaming_tts.wav") + + async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1, + bits_per_sample: int = 16) -> bytes: + """ + 将 PCM 数据转换为 WAV 文件并返回字节数据 + :param pcm_data: PCM 数据(原始字节流) + :param sample_rate: 音频采样率,默认为24000 + :param num_channels: 声道数,默认为单声道 + :param bits_per_sample: 每个样本的位数,默认为16 + :return: WAV 格式的字节数据 + """ + byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16位PCM + wav_io = io.BytesIO() + + with wave.open(wav_io, "wb") as wav_file: + wav_file.setnchannels(num_channels) + wav_file.setsampwidth(bits_per_sample // 8) + wav_file.setframerate(sample_rate) + wav_file.writeframes(byte_data.tobytes()) + + return wav_io.getvalue() + + async def text_to_speak(self, text, output_file): + if self.protocol == "websocket": + return await self.text_streaming(text, output_file) + elif self.protocol == "http": + return await self.text(text, output_file) + else: + raise ValueError("Unsupported protocol. Please use 'websocket' or 'http'.") + + async def text(self, text, output_file): + request_json = { + "text": text, + "spk_id": self.spk_id, + "speed": self.speed, + "volume": self.volume, + "sample_rate": self.sample_rate, + "save_path": self.save_path + } + + try: + async with aiohttp.ClientSession() as session: + async with session.post(self.url, json=request_json) as resp: + if resp.status == 200: + resp_json = await resp.json() + if resp_json.get("success"): + data = resp_json["result"] + audio_bytes = base64.b64decode(data["audio"]) + if output_file: + with open(output_file, "wb") as file_to_save: + file_to_save.write(audio_bytes) + else: + return audio_bytes + else: + raise Exception( + f"Error: {resp_json.get('message', 'Unknown error')} while processing text: {text}") + else: + raise Exception( + f"HTTP Error: {resp.status} - {await resp.text()} while processing text: {text}") + except Exception as e: + raise Exception(f"Error during TTS HTTP request: {e} while processing text: {text}") + + async def text_streaming(self, text, output_file): + try: + # 使用 websockets 异步连接到 WebSocket 服务器 + async with websockets.connect(self.url) as ws: + # 发送开始请求 + start_request = { + "task": "tts", + "signal": "start" + } + await ws.send(json.dumps(start_request)) + + # 接收开始响应并提取 session_id + start_response = await ws.recv() + start_response = json.loads(start_response) # 解析 JSON 响应 + if start_response.get("status") != 0: + raise Exception(f"连接失败: {start_response.get('signal')}") + + session_id = start_response.get("session") + + # 发送待合成的文本数据 + data_request = { + "text": text, + "spk_id": self.spk_id, + } + await ws.send(json.dumps(data_request)) + + audio_chunks = b"" + timeout_seconds = 60 # 设置超时 + try: + while True: + response = await asyncio.wait_for(ws.recv(), timeout=timeout_seconds) + response = json.loads(response) # 解析 JSON 响应 + status = response.get("status") + + if status == 2: # 最后一个数据包 + break + else: + # 拼接音频数据(base64 编码的 PCM 数据) + audio_chunks += base64.b64decode(response.get("audio")) + except asyncio.TimeoutError: + raise Exception(f"WebSocket 超时:等待音频数据超过 {timeout_seconds} 秒") + + # 将拼接后的 PCM 数据转换为 WAV 格式 + wav_data = await self.pcm_to_wav(audio_chunks) + + # 结束请求 + end_request = { + "task": "tts", + "signal": "end", + "session": session_id # 会话 ID 必须与开始请求中的一致 + } + await ws.send(json.dumps(end_request)) + + # 接收结束响应避免服务抛出异常 + await ws.recv() + + # 返回或保存音频数据 + if output_file: + with open(output_file, "wb") as file_to_save: + file_to_save.write(wav_data) + else: + return wav_data + + except Exception as e: + raise Exception(f"Error during TTS WebSocket request: {e} while processing text: {text}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/vllm/openai.py b/main/xiaozhi-server/core/providers/vllm/openai.py index 12d8198dc..35bc1d7a3 100644 --- a/main/xiaozhi-server/core/providers/vllm/openai.py +++ b/main/xiaozhi-server/core/providers/vllm/openai.py @@ -40,6 +40,7 @@ class VLLMProvider(VLLMProviderBase): self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url) def response(self, question, base64_image): + question = question + "(请使用中文回复)" try: messages = [ { @@ -64,4 +65,4 @@ class VLLMProvider(VLLMProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") - raise + raise \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/cache/config.py b/main/xiaozhi-server/core/utils/cache/config.py new file mode 100644 index 000000000..194daf97d --- /dev/null +++ b/main/xiaozhi-server/core/utils/cache/config.py @@ -0,0 +1,58 @@ +""" +缓存配置管理 +""" + +from enum import Enum +from typing import Dict, Any, Optional +from dataclasses import dataclass +from .strategies import CacheStrategy + + +class CacheType(Enum): + """缓存类型枚举""" + + LOCATION = "location" + WEATHER = "weather" + LUNAR = "lunar" + INTENT = "intent" + IP_INFO = "ip_info" + CONFIG = "config" + DEVICE_PROMPT = "device_prompt" + + +@dataclass +class CacheConfig: + """缓存配置类""" + + strategy: CacheStrategy = CacheStrategy.TTL + ttl: Optional[float] = 300 # 默认5分钟 + max_size: Optional[int] = 1000 # 默认最大1000条 + cleanup_interval: float = 60 # 清理间隔(秒) + + @classmethod + def for_type(cls, cache_type: CacheType) -> "CacheConfig": + """根据缓存类型返回预设配置""" + configs = { + CacheType.LOCATION: cls( + strategy=CacheStrategy.TTL, ttl=None, max_size=1000 # 手动失效 + ), + CacheType.IP_INFO: cls( + strategy=CacheStrategy.TTL, ttl=86400, max_size=1000 # 24小时 + ), + CacheType.WEATHER: cls( + strategy=CacheStrategy.TTL, ttl=28800, max_size=1000 # 8小时 + ), + CacheType.LUNAR: cls( + strategy=CacheStrategy.TTL, ttl=2592000, max_size=365 # 30天过期 + ), + CacheType.INTENT: cls( + strategy=CacheStrategy.TTL_LRU, ttl=600, max_size=1000 # 10分钟 + ), + CacheType.CONFIG: cls( + strategy=CacheStrategy.FIXED_SIZE, ttl=None, max_size=20 # 手动失效 + ), + CacheType.DEVICE_PROMPT: cls( + strategy=CacheStrategy.TTL, ttl=None, max_size=1000 # 手动失效 + ), + } + return configs.get(cache_type, cls()) \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/cache/manager.py b/main/xiaozhi-server/core/utils/cache/manager.py new file mode 100644 index 000000000..57f84c590 --- /dev/null +++ b/main/xiaozhi-server/core/utils/cache/manager.py @@ -0,0 +1,216 @@ +""" +全局缓存管理器 +""" + +import time +import threading +from typing import Any, Optional, Dict +from collections import OrderedDict +from .strategies import CacheStrategy, CacheEntry +from .config import CacheConfig, CacheType + + +class GlobalCacheManager: + """全局缓存管理器""" + + def __init__(self): + self._logger = None + self._caches: Dict[str, Dict[str, CacheEntry]] = {} + self._configs: Dict[str, CacheConfig] = {} + self._locks: Dict[str, threading.RLock] = {} + self._global_lock = threading.RLock() + self._last_cleanup = time.time() + self._stats = {"hits": 0, "misses": 0, "evictions": 0, "cleanups": 0} + + @property + def logger(self): + """延迟初始化 logger 以避免循环导入""" + if self._logger is None: + from config.logger import setup_logging + + self._logger = setup_logging() + return self._logger + + def _get_cache_name(self, cache_type: CacheType, namespace: str = "") -> str: + """生成缓存名称""" + if namespace: + return f"{cache_type.value}:{namespace}" + return cache_type.value + + def _get_or_create_cache( + self, cache_name: str, config: CacheConfig + ) -> Dict[str, CacheEntry]: + """获取或创建缓存空间""" + with self._global_lock: + if cache_name not in self._caches: + self._caches[cache_name] = ( + OrderedDict() + if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU] + else {} + ) + self._configs[cache_name] = config + self._locks[cache_name] = threading.RLock() + return self._caches[cache_name] + + def set( + self, + cache_type: CacheType, + key: str, + value: Any, + ttl: Optional[float] = None, + namespace: str = "", + ) -> None: + """设置缓存值""" + cache_name = self._get_cache_name(cache_type, namespace) + config = self._configs.get(cache_name) or CacheConfig.for_type(cache_type) + cache = self._get_or_create_cache(cache_name, config) + + # 使用配置的TTL或传入的TTL + effective_ttl = ttl if ttl is not None else config.ttl + + with self._locks[cache_name]: + # 创建缓存条目 + entry = CacheEntry(value=value, timestamp=time.time(), ttl=effective_ttl) + + # 处理不同策略 + if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]: + # LRU策略:如果已存在则移动到末尾 + if key in cache: + del cache[key] + cache[key] = entry + + # 检查大小限制 + if config.max_size and len(cache) > config.max_size: + # 移除最旧的条目 + oldest_key = next(iter(cache)) + del cache[oldest_key] + self._stats["evictions"] += 1 + + else: + cache[key] = entry + + # 检查大小限制 + if config.max_size and len(cache) > config.max_size: + # 简单策略:随机移除一个条目 + victim_key = next(iter(cache)) + del cache[victim_key] + self._stats["evictions"] += 1 + + # 定期清理过期条目 + self._maybe_cleanup(cache_name) + + def get( + self, cache_type: CacheType, key: str, namespace: str = "" + ) -> Optional[Any]: + """获取缓存值""" + cache_name = self._get_cache_name(cache_type, namespace) + + if cache_name not in self._caches: + self._stats["misses"] += 1 + return None + + cache = self._caches[cache_name] + config = self._configs[cache_name] + + with self._locks[cache_name]: + if key not in cache: + self._stats["misses"] += 1 + return None + + entry = cache[key] + + # 检查过期 + if entry.is_expired(): + del cache[key] + self._stats["misses"] += 1 + return None + + # 更新访问信息 + entry.touch() + + # LRU策略:移动到末尾 + if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]: + del cache[key] + cache[key] = entry + + self._stats["hits"] += 1 + return entry.value + + def delete(self, cache_type: CacheType, key: str, namespace: str = "") -> bool: + """删除缓存条目""" + cache_name = self._get_cache_name(cache_type, namespace) + + if cache_name not in self._caches: + return False + + cache = self._caches[cache_name] + + with self._locks[cache_name]: + if key in cache: + del cache[key] + return True + return False + + def clear(self, cache_type: CacheType, namespace: str = "") -> None: + """清空指定缓存""" + cache_name = self._get_cache_name(cache_type, namespace) + + if cache_name not in self._caches: + return + + with self._locks[cache_name]: + self._caches[cache_name].clear() + + def invalidate_pattern( + self, cache_type: CacheType, pattern: str, namespace: str = "" + ) -> int: + """按模式失效缓存条目""" + cache_name = self._get_cache_name(cache_type, namespace) + + if cache_name not in self._caches: + return 0 + + cache = self._caches[cache_name] + deleted_count = 0 + + with self._locks[cache_name]: + keys_to_delete = [key for key in cache.keys() if pattern in key] + for key in keys_to_delete: + del cache[key] + deleted_count += 1 + + return deleted_count + + def _cleanup_expired(self, cache_name: str) -> int: + """清理过期条目""" + if cache_name not in self._caches: + return 0 + + cache = self._caches[cache_name] + deleted_count = 0 + + with self._locks[cache_name]: + expired_keys = [key for key, entry in cache.items() if entry.is_expired()] + for key in expired_keys: + del cache[key] + deleted_count += 1 + + return deleted_count + + def _maybe_cleanup(self, cache_name: str): + """定期清理检查""" + config = self._configs.get(cache_name) + if not config: + return + + now = time.time() + if now - self._last_cleanup > config.cleanup_interval: + self._last_cleanup = now + deleted = self._cleanup_expired(cache_name) + if deleted > 0: + self._stats["cleanups"] += 1 + self.logger.debug(f"清理缓存 {cache_name}: 删除 {deleted} 个过期条目") + + +# 创建全局缓存管理器实例 +cache_manager = GlobalCacheManager() \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/cache/strategies.py b/main/xiaozhi-server/core/utils/cache/strategies.py new file mode 100644 index 000000000..396b9540c --- /dev/null +++ b/main/xiaozhi-server/core/utils/cache/strategies.py @@ -0,0 +1,43 @@ +""" +缓存策略和数据结构定义 +""" + +import time +from enum import Enum +from typing import Any, Optional +from dataclasses import dataclass + + +class CacheStrategy(Enum): + """缓存策略枚举""" + + TTL = "ttl" # 基于时间过期 + LRU = "lru" # 最近最少使用 + FIXED_SIZE = "fixed_size" # 固定大小 + TTL_LRU = "ttl_lru" # TTL + LRU混合策略 + + +@dataclass +class CacheEntry: + """缓存条目数据结构""" + + value: Any + timestamp: float + ttl: Optional[float] = None # 生存时间(秒) + access_count: int = 0 + last_access: float = None + + def __post_init__(self): + if self.last_access is None: + self.last_access = self.timestamp + + def is_expired(self) -> bool: + """检查是否过期""" + if self.ttl is None: + return False + return time.time() - self.timestamp > self.ttl + + def touch(self): + """更新访问时间和计数""" + self.last_access = time.time() + self.access_count += 1 \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py index 2ee30d4ae..6adadfdcb 100644 --- a/main/xiaozhi-server/core/utils/dialogue.py +++ b/main/xiaozhi-server/core/utils/dialogue.py @@ -1,4 +1,5 @@ import uuid +import re from typing import List, Dict from datetime import datetime @@ -45,10 +46,9 @@ class Dialogue: dialogue.append({"role": m.role, "content": m.content}) def get_llm_dialogue(self) -> List[Dict[str, str]]: - dialogue = [] - for m in self.dialogue: - self.getMessages(m, dialogue) - return dialogue + # 直接调用get_llm_dialogue_with_memory,传入None作为memory_str + # 这样确保说话人功能在所有调用路径下都生效 + return self.get_llm_dialogue_with_memory(None, None) def update_system_message(self, new_content: str): """更新或添加系统消息""" @@ -60,12 +60,9 @@ class Dialogue: self.put(Message(role="system", content=new_content)) def get_llm_dialogue_with_memory( - self, memory_str: str = None + self, memory_str: str = None, voiceprint_config: dict = None ) -> List[Dict[str, str]]: - if memory_str is None or len(memory_str) == 0: - return self.get_llm_dialogue() - - # 构建带记忆的对话 + # 构建对话 dialogue = [] # 添加系统提示和记忆 @@ -74,10 +71,43 @@ class Dialogue: ) if system_message: - enhanced_system_prompt = ( - f"{system_message.content}\n\n" - f"以下是用户的历史记忆:\n```\n{memory_str}\n```" + # 基础系统提示 + enhanced_system_prompt = system_message.content + # 替换时间占位符 + enhanced_system_prompt = enhanced_system_prompt.replace( + "{{current_time}}", datetime.now().strftime("%H:%M") ) + + # 添加说话人个性化描述 + try: + speakers = voiceprint_config.get("speakers", []) + if speakers: + enhanced_system_prompt += "\n\n" + for speaker_str in speakers: + try: + parts = speaker_str.split(",", 2) + if len(parts) >= 2: + name = parts[1].strip() + # 如果描述为空,则为"" + description = ( + parts[2].strip() if len(parts) >= 3 else "" + ) + enhanced_system_prompt += f"\n- {name}:{description}" + except: + pass + enhanced_system_prompt += "\n\n" + except: + # 配置读取失败时忽略错误,不影响其他功能 + pass + + # 使用正则表达式匹配 标签,不管中间有什么内容 + if memory_str is not None: + enhanced_system_prompt = re.sub( + r".*?", + f"\n{memory_str}\n", + enhanced_system_prompt, + flags=re.DOTALL, + ) dialogue.append({"role": "system", "content": enhanced_system_prompt}) # 添加用户和助手的对话 @@ -85,4 +115,4 @@ class Dialogue: if m.role != "system": # 跳过原始的系统消息 self.getMessages(m, dialogue) - return dialogue + return dialogue \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/modules_initialize.py b/main/xiaozhi-server/core/utils/modules_initialize.py index f2e3968e2..bf27df92e 100644 --- a/main/xiaozhi-server/core/utils/modules_initialize.py +++ b/main/xiaozhi-server/core/utils/modules_initialize.py @@ -125,4 +125,26 @@ def initialize_asr(config): config["ASR"][select_asr_module], str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"), ) + logger.bind(tag=TAG).info("ASR模块初始化完成") return new_asr + + +def initialize_voiceprint(asr_instance, config): + """初始化声纹识别功能""" + voiceprint_config = config.get("voiceprint") + if not voiceprint_config: + return False + + # 应用配置 + if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"): + logger.bind(tag=TAG).warning("声纹识别配置不完整") + return False + + try: + asr_instance.init_voiceprint(voiceprint_config) + logger.bind(tag=TAG).info("ASR模块声纹识别功能已动态启用") + logger.bind(tag=TAG).info(f"配置说话人数量: {len(voiceprint_config['speakers'])}") + return True + except Exception as e: + logger.bind(tag=TAG).error(f"动态初始化声纹识别功能失败: {str(e)}") + return False diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py new file mode 100644 index 000000000..a81fd9aac --- /dev/null +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -0,0 +1,245 @@ +""" +系统提示词管理器模块 +负责管理和更新系统提示词,包括快速初始化和异步增强功能 +""" + +import os +import cnlunar +from typing import Dict, Any +from config.logger import setup_logging +from jinja2 import Template + +TAG = __name__ + +WEEKDAY_MAP = { + "Monday": "星期一", + "Tuesday": "星期二", + "Wednesday": "星期三", + "Thursday": "星期四", + "Friday": "星期五", + "Saturday": "星期六", + "Sunday": "星期日", +} + +EMOJI_List = [ + "😶", + "🙂", + "😆", + "😂", + "😔", + "😠", + "😭", + "😍", + "😳", + "😲", + "😱", + "🤔", + "😉", + "😎", + "😌", + "🤤", + "😘", + "😏", + "😴", + "😜", + "🙄", +] + + +class PromptManager: + """系统提示词管理器,负责管理和更新系统提示词""" + + def __init__(self, config: Dict[str, Any], logger=None): + self.config = config + self.logger = logger or setup_logging() + self.base_prompt_template = None + self.last_update_time = 0 + + # 导入全局缓存管理器 + from core.utils.cache.manager import cache_manager, CacheType + + self.cache_manager = cache_manager + self.CacheType = CacheType + + self._load_base_template() + + def _load_base_template(self): + """加载基础提示词模板""" + try: + template_path = "agent-base-prompt.txt" + cache_key = f"prompt_template:{template_path}" + + # 先从缓存获取 + cached_template = self.cache_manager.get(self.CacheType.CONFIG, cache_key) + if cached_template is not None: + self.base_prompt_template = cached_template + self.logger.bind(tag=TAG).debug("从缓存加载基础提示词模板") + return + + # 缓存未命中,从文件读取 + if os.path.exists(template_path): + with open(template_path, "r", encoding="utf-8") as f: + template_content = f.read() + + # 存入缓存(CONFIG类型默认不自动过期,需要手动失效) + self.cache_manager.set( + self.CacheType.CONFIG, cache_key, template_content + ) + self.base_prompt_template = template_content + self.logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存") + else: + self.logger.bind(tag=TAG).warning("未找到agent-base-prompt.txt文件") + except Exception as e: + self.logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}") + + def get_quick_prompt(self, user_prompt: str, device_id: str = None) -> str: + """快速获取系统提示词(使用用户配置)""" + device_cache_key = f"device_prompt:{device_id}" + cached_device_prompt = self.cache_manager.get( + self.CacheType.DEVICE_PROMPT, device_cache_key + ) + if cached_device_prompt is not None: + self.logger.bind(tag=TAG).debug(f"使用设备 {device_id} 的缓存提示词") + return cached_device_prompt + else: + self.logger.bind(tag=TAG).debug( + f"设备 {device_id} 无缓存提示词,使用传入的提示词" + ) + + # 使用传入的提示词并缓存(如果有设备ID) + if device_id: + device_cache_key = f"device_prompt:{device_id}" + self.cache_manager.set(self.CacheType.CONFIG, device_cache_key, user_prompt) + self.logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存") + + self.logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...") + return user_prompt + + def _get_current_time_info(self) -> tuple: + """获取当前时间信息""" + from datetime import datetime + + now = datetime.now() + today_date = now.strftime("%Y-%m-%d") + today_weekday = WEEKDAY_MAP[now.strftime("%A")] + today_lunar = cnlunar.Lunar(now, godType="8char") + lunar_date = "%s年%s%s\n" % ( + today_lunar.lunarYearCn, + today_lunar.lunarMonthCn[:-1], + today_lunar.lunarDayCn, + ) + + return today_date, today_weekday, lunar_date + + def _get_location_info(self, client_ip: str) -> str: + """获取位置信息""" + try: + # 先从缓存获取 + cached_location = self.cache_manager.get(self.CacheType.LOCATION, client_ip) + if cached_location is not None: + return cached_location + + # 缓存未命中,调用API获取 + from core.utils.util import get_ip_info + + ip_info = get_ip_info(client_ip, self.logger) + city = ip_info.get("city", "未知位置") + location = f"{city}" + + # 存入缓存 + self.cache_manager.set(self.CacheType.LOCATION, client_ip, location) + return location + except Exception as e: + self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}") + return "未知位置" + + def _get_weather_info(self, conn, location: str) -> str: + """获取天气信息""" + try: + # 先从缓存获取 + cached_weather = self.cache_manager.get(self.CacheType.WEATHER, location) + if cached_weather is not None: + return cached_weather + + # 缓存未命中,调用get_weather函数获取 + from plugins_func.functions.get_weather import get_weather + from plugins_func.register import ActionResponse + + # 调用get_weather函数 + result = get_weather(conn, location=location, lang="zh_CN") + if isinstance(result, ActionResponse): + weather_report = result.result + self.cache_manager.set(self.CacheType.WEATHER, location, weather_report) + return weather_report + return "天气信息获取失败" + + except Exception as e: + self.logger.bind(tag=TAG).error(f"获取天气信息失败: {e}") + return "天气信息获取失败" + + def update_context_info(self, conn, client_ip: str): + """同步更新上下文信息""" + try: + # 获取位置信息(使用全局缓存) + local_address = self._get_location_info(client_ip) + # 获取天气信息(使用全局缓存) + self._get_weather_info(conn, local_address) + self.logger.bind(tag=TAG).info(f"上下文信息更新完成") + + except Exception as e: + self.logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}") + + def build_enhanced_prompt( + self, user_prompt: str, device_id: str, client_ip: str = None + ) -> str: + """构建增强的系统提示词""" + if not self.base_prompt_template: + return user_prompt + + try: + # 获取最新的时间信息(不缓存) + today_date, today_weekday, lunar_date = ( + self._get_current_time_info() + ) + + # 获取缓存的上下文信息 + local_address = "" + weather_info = "" + + if client_ip: + # 获取位置信息(从全局缓存) + local_address = ( + self.cache_manager.get(self.CacheType.LOCATION, client_ip) or "" + ) + + # 获取天气信息(从全局缓存) + if local_address: + weather_info = ( + self.cache_manager.get(self.CacheType.WEATHER, local_address) + or "" + ) + + # 替换模板变量 + template = Template(self.base_prompt_template) + enhanced_prompt = template.render( + base_prompt=user_prompt, + current_time="{{current_time}}", + today_date=today_date, + today_weekday=today_weekday, + lunar_date=lunar_date, + local_address=local_address, + weather_info=weather_info, + emojiList=EMOJI_List, + ) + device_cache_key = f"device_prompt:{device_id}" + self.cache_manager.set( + self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt + ) + self.logger.bind(tag=TAG).info( + f"构建增强提示词成功,长度: {len(enhanced_prompt)}" + ) + return enhanced_prompt + + except Exception as e: + self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}") + return user_prompt \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/textUtils.py b/main/xiaozhi-server/core/utils/textUtils.py index 603d964c6..ae4e16228 100644 --- a/main/xiaozhi-server/core/utils/textUtils.py +++ b/main/xiaozhi-server/core/utils/textUtils.py @@ -1,3 +1,40 @@ +import json + +TAG = __name__ +EMOJI_MAP = { + "😂": "laughing", + "😭": "crying", + "😠": "angry", + "😔": "sad", + "😍": "loving", + "😲": "surprised", + "😱": "shocked", + "🤔": "thinking", + "😌": "relaxed", + "😴": "sleepy", + "😜": "silly", + "🙄": "confused", + "😶": "neutral", + "🙂": "happy", + "😆": "laughing", + "😳": "embarrassed", + "😉": "winking", + "😎": "cool", + "🤤": "delicious", + "😘": "kissy", + "😏": "confident", +} +EMOJI_RANGES = [ + (0x1F600, 0x1F64F), + (0x1F300, 0x1F5FF), + (0x1F680, 0x1F6FF), + (0x1F900, 0x1F9FF), + (0x1FA70, 0x1FAFF), + (0x2600, 0x26FF), + (0x2700, 0x27BF), +] + + def get_string_no_punctuation_or_emoji(s): """去除字符串首尾的空格、标点符号和表情符号""" chars = list(s) @@ -22,6 +59,11 @@ def is_punctuation_or_emoji(char): ".", # 中文句号 + 英文句号 "!", "!", # 中文感叹号 + 英文感叹号 + "“", + "”", + '"', # 中文双引号 + 英文引号 + ":", + ":", # 中文冒号 + 英文冒号 "-", "-", # 英文连字符 + 中文全角横线 "、", # 中文顿号 @@ -32,15 +74,40 @@ def is_punctuation_or_emoji(char): } if char.isspace() or char in punctuation_set: return True - # 检查表情符号(保留原有逻辑) + return is_emoji(char) + + +async def get_emotion(conn, text): + """获取文本内的情绪消息""" + emoji = "🙂" + emotion = "happy" + for char in text: + if char in EMOJI_MAP: + emoji = char + emotion = EMOJI_MAP[char] + break + try: + await conn.websocket.send( + json.dumps( + { + "type": "llm", + "text": emoji, + "emotion": emotion, + "session_id": conn.session_id, + } + ) + ) + except Exception as e: + conn.logger.bind(tag=TAG).warning(f"发送情绪表情失败,错误:{e}") + return + + +def is_emoji(char): + """检查字符是否为emoji表情""" code_point = ord(char) - emoji_ranges = [ - (0x1F600, 0x1F64F), - (0x1F300, 0x1F5FF), - (0x1F680, 0x1F6FF), - (0x1F900, 0x1F9FF), - (0x1FA70, 0x1FAFF), - (0x2600, 0x26FF), - (0x2700, 0x27BF), - ] - return any(start <= code_point <= end for start, end in emoji_ranges) + return any(start <= code_point <= end for start, end in EMOJI_RANGES) + + +def check_emoji(text): + """去除文本中的所有emoji表情""" + return ''.join(char for char in text if not is_emoji(char) and char != "\n") \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 35417abc0..2c407c3ab 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -96,11 +96,23 @@ def is_private_ip(ip_addr): def get_ip_info(ip_addr, logger): try: + # 导入全局缓存管理器 + from core.utils.cache.manager import cache_manager, CacheType + + # 先从缓存获取 + cached_ip_info = cache_manager.get(CacheType.IP_INFO, ip_addr) + if cached_ip_info is not None: + return cached_ip_info + + # 缓存未命中,调用API if is_private_ip(ip_addr): ip_addr = "" url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}" resp = requests.get(url).json() ip_info = {"city": resp.get("city")} + + # 存入缓存 + cache_manager.set(CacheType.IP_INFO, ip_addr, ip_info) return ip_info except Exception as e: logger.bind(tag=TAG).error(f"Error getting client ip info: {e}") @@ -113,51 +125,6 @@ def write_json_file(file_path, data): json.dump(data, file, ensure_ascii=False, indent=4) -def is_punctuation_or_emoji(char): - """检查字符是否为空格、指定标点或表情符号""" - # 定义需要去除的中英文标点(包括全角/半角) - punctuation_set = { - ",", - ",", # 中文逗号 + 英文逗号 - "-", - "-", # 英文连字符 + 中文全角横线 - "、", # 中文顿号 - "“", - "”", - '"', # 中文双引号 + 英文引号 - ":", - ":", # 中文冒号 + 英文冒号 - } - if char.isspace() or char in punctuation_set: - return True - # 检查表情符号(保留原有逻辑) - code_point = ord(char) - emoji_ranges = [ - (0x1F600, 0x1F64F), - (0x1F300, 0x1F5FF), - (0x1F680, 0x1F6FF), - (0x1F900, 0x1F9FF), - (0x1FA70, 0x1FAFF), - (0x2600, 0x26FF), - (0x2700, 0x27BF), - ] - return any(start <= code_point <= end for start, end in emoji_ranges) - - -def get_string_no_punctuation_or_emoji(s): - """去除字符串首尾的空格、标点符号和表情符号""" - chars = list(s) - # 处理开头的字符 - start = 0 - while start < len(chars) and is_punctuation_or_emoji(chars[start]): - start += 1 - # 处理结尾的字符 - end = len(chars) - 1 - while end >= start and is_punctuation_or_emoji(chars[end]): - end -= 1 - return "".join(chars[start : end + 1]) - - def remove_punctuation_and_length(text): # 全角符号和半角符号的Unicode范围 full_width_punctuations = ( @@ -244,515 +211,6 @@ def extract_json_from_string(input_string): return None -def analyze_emotion(text): - """ - 分析文本情感并返回对应的emoji名称(支持中英文) - """ - if not text or not isinstance(text, str): - return "neutral" - - original_text = text - text = text.lower().strip() - - # 检查是否包含现有emoji - for emotion, emoji in emoji_map.items(): - if emoji in original_text: - return emotion - - # 标点符号分析 - has_exclamation = "!" in original_text or "!" in original_text - has_question = "?" in original_text or "?" in original_text - has_ellipsis = "..." in original_text or "…" in original_text - - # 定义情感关键词映射(中英文扩展版) - emotion_keywords = { - "happy": [ - "开心", - "高兴", - "快乐", - "愉快", - "幸福", - "满意", - "棒", - "好", - "不错", - "完美", - "棒极了", - "太好了", - "好呀", - "好的", - "happy", - "joy", - "great", - "good", - "nice", - "awesome", - "fantastic", - "wonderful", - ], - "laughing": [ - "哈哈", - "哈哈哈", - "呵呵", - "嘿嘿", - "嘻嘻", - "笑死", - "太好笑了", - "笑死我了", - "lol", - "lmao", - "haha", - "hahaha", - "hehe", - "rofl", - "funny", - "laugh", - ], - "funny": [ - "搞笑", - "滑稽", - "逗", - "幽默", - "笑点", - "段子", - "笑话", - "太逗了", - "hilarious", - "joke", - "comedy", - ], - "sad": [ - "伤心", - "难过", - "悲哀", - "悲伤", - "忧郁", - "郁闷", - "沮丧", - "失望", - "想哭", - "难受", - "不开心", - "唉", - "呜呜", - "sad", - "upset", - "unhappy", - "depressed", - "sorrow", - "gloomy", - ], - "angry": [ - "生气", - "愤怒", - "气死", - "讨厌", - "烦人", - "可恶", - "烦死了", - "恼火", - "暴躁", - "火大", - "愤怒", - "气炸了", - "angry", - "mad", - "annoyed", - "furious", - "pissed", - "hate", - ], - "crying": [ - "哭泣", - "泪流", - "大哭", - "伤心欲绝", - "泪目", - "流泪", - "哭死", - "哭晕", - "想哭", - "泪崩", - "cry", - "crying", - "tears", - "sob", - "weep", - ], - "loving": [ - "爱你", - "喜欢", - "爱", - "亲爱的", - "宝贝", - "么么哒", - "抱抱", - "想你", - "思念", - "最爱", - "亲亲", - "喜欢你", - "love", - "like", - "adore", - "darling", - "sweetie", - "honey", - "miss you", - "heart", - ], - "embarrassed": [ - "尴尬", - "不好意思", - "害羞", - "脸红", - "难为情", - "社死", - "丢脸", - "出丑", - "embarrassed", - "awkward", - "shy", - "blush", - ], - "surprised": [ - "惊讶", - "吃惊", - "天啊", - "哇塞", - "哇", - "居然", - "竟然", - "没想到", - "出乎意料", - "surprise", - "wow", - "omg", - "oh my god", - "amazing", - "unbelievable", - ], - "shocked": [ - "震惊", - "吓到", - "惊呆了", - "不敢相信", - "震撼", - "吓死", - "恐怖", - "害怕", - "吓人", - "shocked", - "shocking", - "scared", - "frightened", - "terrified", - "horror", - ], - "thinking": [ - "思考", - "考虑", - "想一下", - "琢磨", - "沉思", - "冥想", - "想", - "思考中", - "在想", - "think", - "thinking", - "consider", - "ponder", - "meditate", - ], - "winking": [ - "调皮", - "眨眼", - "你懂的", - "坏笑", - "邪恶", - "奸笑", - "使眼色", - "wink", - "teasing", - "naughty", - "mischievous", - ], - "cool": [ - "酷", - "帅", - "厉害", - "棒极了", - "真棒", - "牛逼", - "强", - "优秀", - "杰出", - "出色", - "完美", - "cool", - "awesome", - "amazing", - "great", - "impressive", - "perfect", - ], - "relaxed": [ - "放松", - "舒服", - "惬意", - "悠闲", - "轻松", - "舒适", - "安逸", - "自在", - "relax", - "relaxed", - "comfortable", - "cozy", - "chill", - "peaceful", - ], - "delicious": [ - "好吃", - "美味", - "香", - "馋", - "可口", - "香甜", - "大餐", - "大快朵颐", - "流口水", - "垂涎", - "delicious", - "yummy", - "tasty", - "yum", - "appetizing", - "mouthwatering", - ], - "kissy": [ - "亲亲", - "么么", - "吻", - "mua", - "muah", - "亲一下", - "飞吻", - "kiss", - "xoxo", - "hug", - "muah", - "smooch", - ], - "confident": [ - "自信", - "肯定", - "确定", - "毫无疑问", - "当然", - "必须的", - "毫无疑问", - "确信", - "坚信", - "confident", - "sure", - "certain", - "definitely", - "positive", - ], - "sleepy": [ - "困", - "睡觉", - "晚安", - "想睡", - "好累", - "疲惫", - "疲倦", - "困了", - "想休息", - "睡意", - "sleep", - "sleepy", - "tired", - "exhausted", - "bedtime", - "good night", - ], - "silly": [ - "傻", - "笨", - "呆", - "憨", - "蠢", - "二", - "憨憨", - "傻乎乎", - "呆萌", - "silly", - "stupid", - "dumb", - "foolish", - "goofy", - "ridiculous", - ], - "confused": [ - "疑惑", - "不明白", - "不懂", - "困惑", - "疑问", - "为什么", - "怎么回事", - "啥意思", - "不清楚", - "confused", - "puzzled", - "doubt", - "question", - "what", - "why", - "how", - ], - } - - # 特殊句型判断(中英文) - # 赞美他人 - if any( - phrase in text - for phrase in [ - "你真", - "你好", - "您真", - "你真棒", - "你好厉害", - "你太强了", - "你真好", - "你真聪明", - "you are", - "you're", - "you look", - "you seem", - "so smart", - "so kind", - ] - ): - return "loving" - # 自我赞美 - if any( - phrase in text - for phrase in [ - "我真", - "我最", - "我太棒了", - "我厉害", - "我聪明", - "我优秀", - "i am", - "i'm", - "i feel", - "so good", - "so happy", - ] - ): - return "cool" - # 晚安/睡觉相关 - if any( - phrase in text - for phrase in [ - "睡觉", - "晚安", - "睡了", - "好梦", - "休息了", - "去睡了", - "sleep", - "good night", - "bedtime", - "go to bed", - ] - ): - return "sleepy" - # 疑问句 - if has_question and not has_exclamation: - return "thinking" - # 强烈情感(感叹号) - if has_exclamation and not has_question: - # 检查是否是积极内容 - positive_words = ( - emotion_keywords["happy"] - + emotion_keywords["laughing"] - + emotion_keywords["cool"] - ) - if any(word in text for word in positive_words): - return "laughing" - # 检查是否是消极内容 - negative_words = ( - emotion_keywords["angry"] - + emotion_keywords["sad"] - + emotion_keywords["crying"] - ) - if any(word in text for word in negative_words): - return "angry" - return "surprised" - # 省略号(表示犹豫或思考) - if has_ellipsis: - return "thinking" - - # 关键词匹配(带权重) - emotion_scores = {emotion: 0 for emotion in emoji_map.keys()} - - # 给匹配到的关键词加分 - for emotion, keywords in emotion_keywords.items(): - for keyword in keywords: - if keyword in text: - emotion_scores[emotion] += 1 - - # 给长文本中的重复关键词额外加分 - if len(text) > 20: # 长文本 - for emotion, keywords in emotion_keywords.items(): - for keyword in keywords: - emotion_scores[emotion] += text.count(keyword) * 0.5 - - # 根据分数选择最可能的情感 - max_score = max(emotion_scores.values()) - if max_score == 0: - return "happy" # 默认 - - # 可能有多个情感同分,根据上下文选择最合适的 - top_emotions = [e for e, s in emotion_scores.items() if s == max_score] - - # 如果多个情感同分,使用以下优先级 - priority_order = [ - "laughing", - "crying", - "angry", - "surprised", - "shocked", # 强烈情感优先 - "loving", - "happy", - "funny", - "cool", # 积极情感 - "sad", - "embarrassed", - "confused", # 消极情感 - "thinking", - "winking", - "relaxed", # 中性情感 - "delicious", - "kissy", - "confident", - "sleepy", - "silly", # 特殊场景 - ] - - for emotion in priority_order: - if emotion in top_emotions: - return emotion - - return top_emotions[0] # 如果都不在优先级列表里,返回第一个 - - def audio_to_data(audio_file_path, is_opus=True): # 获取文件后缀名 file_type = os.path.splitext(audio_file_path)[1] @@ -982,3 +440,28 @@ def sanitize_tool_name(name: str) -> str: """Sanitize tool names for OpenAI compatibility.""" # 支持中文、英文字母、数字、下划线和连字符 return re.sub(r"[^a-zA-Z0-9_\-\u4e00-\u9fff]", "_", name) + + +def validate_mcp_endpoint(mcp_endpoint: str) -> bool: + """ + 校验MCP接入点格式 + + Args: + mcp_endpoint: MCP接入点字符串 + + Returns: + bool: 是否有效 + """ + # 1. 检查是否以ws开头 + if not mcp_endpoint.startswith("ws"): + return False + + # 2. 检查是否包含key、call字样 + if "key" in mcp_endpoint.lower() or "call" in mcp_endpoint.lower(): + return False + + # 3. 检查是否包含/mcp/字样 + if "/mcp/" not in mcp_endpoint: + return False + + return True \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/voiceprint_provider.py b/main/xiaozhi-server/core/utils/voiceprint_provider.py new file mode 100644 index 000000000..fb830defc --- /dev/null +++ b/main/xiaozhi-server/core/utils/voiceprint_provider.py @@ -0,0 +1,134 @@ +import asyncio +import json +import time +import aiohttp +from urllib.parse import urlparse, parse_qs +from typing import Optional, Dict +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +class VoiceprintProvider: + """声纹识别服务提供者""" + + def __init__(self, config: dict): + self.original_url = config.get("url", "") + self.speakers = config.get("speakers", []) + self.speaker_map = self._parse_speakers() + + # 解析API地址和密钥 + self.api_url = None + self.api_key = None + self.speaker_ids = [] + + if not self.original_url: + logger.bind(tag=TAG).warning("声纹识别URL未配置,声纹识别将被禁用") + self.enabled = False + else: + # 解析URL和key + parsed_url = urlparse(self.original_url) + base_url = f"{parsed_url.scheme}://{parsed_url.netloc}" + + # 从查询参数中提取key + query_params = parse_qs(parsed_url.query) + self.api_key = query_params.get('key', [''])[0] + + if not self.api_key: + logger.bind(tag=TAG).error("URL中未找到key参数,声纹识别将被禁用") + self.enabled = False + else: + # 构造identify接口地址 + self.api_url = f"{base_url}/voiceprint/identify" + + # 提取speaker_ids + for speaker_str in self.speakers: + try: + parts = speaker_str.split(",", 2) + if len(parts) >= 1: + speaker_id = parts[0].strip() + self.speaker_ids.append(speaker_id) + except Exception: + continue + + # 检查是否有有效的说话人配置 + if not self.speaker_ids: + logger.bind(tag=TAG).warning("未配置有效的说话人,声纹识别将被禁用") + self.enabled = False + else: + self.enabled = True + logger.bind(tag=TAG).info(f"声纹识别已配置: API={self.api_url}, 说话人={len(self.speaker_ids)}个") + + def _parse_speakers(self) -> Dict[str, Dict[str, str]]: + """解析说话人配置""" + speaker_map = {} + for speaker_str in self.speakers: + try: + parts = speaker_str.split(",", 2) + if len(parts) >= 3: + speaker_id, name, description = parts[0].strip(), parts[1].strip(), parts[2].strip() + speaker_map[speaker_id] = { + "name": name, + "description": description + } + except Exception as e: + logger.bind(tag=TAG).warning(f"解析说话人配置失败: {speaker_str}, 错误: {e}") + return speaker_map + + async def identify_speaker(self, audio_data: bytes, session_id: str) -> Optional[str]: + """识别说话人""" + if not self.enabled or not self.api_url or not self.api_key: + logger.bind(tag=TAG).debug("声纹识别功能已禁用或未配置,跳过识别") + return None + + try: + api_start_time = time.monotonic() + + # 准备请求头 + headers = { + 'Authorization': f'Bearer {self.api_key}', + 'Accept': 'application/json' + } + + # 准备multipart/form-data数据 + data = aiohttp.FormData() + data.add_field('speaker_ids', ','.join(self.speaker_ids)) + data.add_field('file', audio_data, filename='audio.wav', content_type='audio/wav') + + timeout = aiohttp.ClientTimeout(total=10) + + # 网络请求 + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.post(self.api_url, headers=headers, data=data) as response: + + if response.status == 200: + result = await response.json() + speaker_id = result.get("speaker_id") + score = result.get("score", 0) + total_elapsed_time = time.monotonic() - api_start_time + + logger.bind(tag=TAG).info(f"声纹识别耗时: {total_elapsed_time:.3f}s") + + # 置信度检查 + if score < 0.5: + logger.bind(tag=TAG).warning(f"声纹识别置信度较低: {score:.3f}") + + if speaker_id and speaker_id in self.speaker_map: + result_name = self.speaker_map[speaker_id]["name"] + return result_name + else: + logger.bind(tag=TAG).warning(f"未识别的说话人ID: {speaker_id}") + return "未知说话人" + else: + logger.bind(tag=TAG).error(f"声纹识别API错误: HTTP {response.status}") + return None + + except asyncio.TimeoutError: + elapsed = time.monotonic() - api_start_time + logger.bind(tag=TAG).error(f"声纹识别超时: {elapsed:.3f}s") + return None + except Exception as e: + elapsed = time.monotonic() - api_start_time + logger.bind(tag=TAG).error(f"声纹识别失败: {e}") + return None \ No newline at end of file diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 1a1ba4c04..bebce3a42 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -57,8 +57,25 @@ class WebSocketServer: self.active_connections.add(handler) try: await handler.handle_connection(websocket) + except Exception as e: + self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}") finally: + # 确保从活动连接集合中移除 self.active_connections.discard(handler) + # 强制关闭连接(如果还没有关闭的话) + try: + # 安全地检查WebSocket状态并关闭 + if hasattr(websocket, "closed") and not websocket.closed: + await websocket.close() + elif hasattr(websocket, "state") and websocket.state.name != "CLOSED": + await websocket.close() + else: + # 如果没有closed属性,直接尝试关闭 + await websocket.close() + except Exception as close_error: + self.logger.bind(tag=TAG).error( + f"服务器端强制关闭连接时出错: {close_error}" + ) async def _http_response(self, websocket, request_headers): # 检查是否为 WebSocket 升级请求 @@ -118,4 +135,4 @@ class WebSocketServer: return True except Exception as e: self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}") - return False + return False \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/get_time.py b/main/xiaozhi-server/plugins_func/functions/get_time.py index 44732bbac..c5a4a53dd 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_time.py +++ b/main/xiaozhi-server/plugins_func/functions/get_time.py @@ -2,59 +2,27 @@ from datetime import datetime import cnlunar from plugins_func.register import register_function, ToolType, ActionResponse, Action -# 添加星期映射字典 -WEEKDAY_MAP = { - "Monday": "星期一", - "Tuesday": "星期二", - "Wednesday": "星期三", - "Thursday": "星期四", - "Friday": "星期五", - "Saturday": "星期六", - "Sunday": "星期日", -} - -get_time_function_desc = { - "type": "function", - "function": { - "name": "get_time", - "description": "获取今天日期或者当前时间信息", - "parameters": {"type": "object", "properties": {}, "required": []}, - }, -} - - -@register_function("get_time", get_time_function_desc, ToolType.WAIT) -def get_time(): - """ - 获取当前的日期时间信息 - """ - now = datetime.now() - current_time = now.strftime("%H:%M:%S") - current_date = now.strftime("%Y-%m-%d") - current_weekday = WEEKDAY_MAP[now.strftime("%A")] - response_text = ( - f"当前日期: {current_date},当前时间: {current_time}, {current_weekday}" - ) - - return ActionResponse(Action.REQLLM, response_text, None) - - get_lunar_function_desc = { "type": "function", "function": { "name": "get_lunar", "description": ( - "用于获取今天的阴历/农历和黄历信息。" + "用于具体日期的阴历/农历和黄历信息。" "用户可以指定查询内容,如:阴历日期、天干地支、节气、生肖、星座、八字、宜忌等。" "如果没有指定查询内容,则默认查询干支年和农历日期。" + "对于'今天农历是多少'、'今天农历日期'这样的基本查询,请直接使用context中的信息,不要调用此工具。" ), "parameters": { "type": "object", "properties": { + "date": { + "type": "string", + "description": "要查询的日期,格式为YYYY-MM-DD,例如2024-01-01。如果不提供,则使用当前日期", + }, "query": { "type": "string", "description": "要查询的内容,例如阴历日期、天干地支、节日、节气、生肖、星座、八字、宜忌等", - } + }, }, "required": [], }, @@ -63,23 +31,41 @@ get_lunar_function_desc = { @register_function("get_lunar", get_lunar_function_desc, ToolType.WAIT) -def get_lunar(query=None): +def get_lunar(date=None, query=None): """ 用于获取当前的阴历/农历,和天干地支、节气、生肖、星座、八字、宜忌等黄历信息 """ - now = datetime.now() - current_time = now.strftime("%H:%M:%S") + from core.utils.cache.manager import cache_manager, CacheType + + # 如果提供了日期参数,则使用指定日期;否则使用当前日期 + if date: + try: + now = datetime.strptime(date, "%Y-%m-%d") + except ValueError: + return ActionResponse( + Action.REQLLM, + f"日期格式错误,请使用YYYY-MM-DD格式,例如:2024-01-01", + None, + ) + else: + now = datetime.now() + current_date = now.strftime("%Y-%m-%d") - current_weekday = WEEKDAY_MAP[now.strftime("%A")] # 如果 query 为 None,则使用默认文本 if query is None: query = "默认查询干支年和农历日期" + + # 尝试从缓存获取农历信息 + lunar_cache_key = f"lunar_info_{current_date}" + cached_lunar_info = cache_manager.get(CacheType.LUNAR, lunar_cache_key) + if cached_lunar_info: + return ActionResponse(Action.REQLLM, cached_lunar_info, None) + response_text = f"根据以下信息回应用户的查询请求,并提供与{query}相关的信息:\n" lunar = cnlunar.Lunar(now, godType="8char") response_text += ( - f"当前公历日期: {current_date},当前时间: {current_time},{current_weekday}\n" "农历信息:\n" "%s年%s%s\n" % (lunar.lunarYearCn, lunar.lunarMonthCn[:-1], lunar.lunarDayCn) + "干支: %s年 %s月 %s日\n" % (lunar.year8Char, lunar.month8Char, lunar.day8Char) @@ -135,4 +121,7 @@ def get_lunar(query=None): + "(默认返回干支年和农历日期;仅在要求查询宜忌信息时才返回本日宜忌)" ) - return ActionResponse(Action.REQLLM, response_text, None) + # 缓存农历信息 + cache_manager.set(CacheType.LUNAR, lunar_cache_key, response_text) + + return ActionResponse(Action.REQLLM, response_text, None) \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py index 75c15c7b8..8b191b272 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_weather.py +++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py @@ -151,20 +151,44 @@ def parse_weather_info(soup): @register_function("get_weather", GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL) def get_weather(conn, location: str = None, lang: str = "zh_CN"): - api_host = conn.config["plugins"]["get_weather"].get("api_host", "mj7p3y7naa.re.qweatherapi.com") - api_key = conn.config["plugins"]["get_weather"].get("api_key", "a861d0d5e7bf4ee1a83d9a9e4f96d4da") + from core.utils.cache.manager import cache_manager, CacheType + + api_host = conn.config["plugins"]["get_weather"].get( + "api_host", "mj7p3y7naa.re.qweatherapi.com" + ) + api_key = conn.config["plugins"]["get_weather"].get( + "api_key", "a861d0d5e7bf4ee1a83d9a9e4f96d4da" + ) default_location = conn.config["plugins"]["get_weather"]["default_location"] client_ip = conn.client_ip + # 优先使用用户提供的location参数 if not location: # 通过客户端IP解析城市 if client_ip: - # 动态解析IP对应的城市信息 - ip_info = get_ip_info(client_ip, logger) - location = ip_info.get("city") if ip_info and "city" in ip_info else None + # 先从缓存获取IP对应的城市信息 + cached_ip_info = cache_manager.get(CacheType.IP_INFO, client_ip) + if cached_ip_info: + location = cached_ip_info.get("city") + else: + # 缓存未命中,调用API获取 + ip_info = get_ip_info(client_ip, logger) + if ip_info: + cache_manager.set(CacheType.IP_INFO, client_ip, ip_info) + location = ip_info.get("city") + + if not location: + location = default_location else: - # 若IP解析失败或无IP,使用默认位置 + # 若无IP,使用默认位置 location = default_location + # 尝试从缓存获取完整天气报告 + weather_cache_key = f"full_weather_{location}_{lang}" + cached_weather_report = cache_manager.get(CacheType.WEATHER, weather_cache_key) + if cached_weather_report: + return ActionResponse(Action.REQLLM, cached_weather_report, None) + + # 缓存未命中,获取实时天气数据 city_info = fetch_city_info(location, api_key, api_host) if not city_info: return ActionResponse( @@ -192,4 +216,7 @@ def get_weather(conn, location: str = None, lang: str = "zh_CN"): # 提示语 weather_report += "\n(如需某一天的具体天气,请告诉我日期)" - return ActionResponse(Action.REQLLM, weather_report, None) + # 缓存完整的天气报告 + cache_manager.set(CacheType.WEATHER, weather_cache_key, weather_report) + + return ActionResponse(Action.REQLLM, weather_report, None) \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py index e8167db46..13b3febbd 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py @@ -33,10 +33,16 @@ def hass_get_state(conn, entity_id=""): future = asyncio.run_coroutine_threadsafe( handle_hass_get_state(conn, entity_id), conn.loop ) - ha_response = future.result() + # 添加10秒超时 + ha_response = future.result(timeout=10) return ActionResponse(Action.REQLLM, ha_response, None) + except asyncio.TimeoutError: + logger.bind(tag=TAG).error("获取Home Assistant状态超时") + return ActionResponse(Action.ERROR, "请求超时", None) except Exception as e: - logger.bind(tag=TAG).error(f"处理设置属性意图错误: {e}") + error_msg = f"执行Home Assistant操作失败" + logger.bind(tag=TAG).error(error_msg) + return ActionResponse(Action.ERROR, error_msg, None) async def handle_hass_get_state(conn, entity_id): @@ -91,4 +97,4 @@ async def handle_hass_get_state(conn, entity_id): # response.attributes else: - return f"切换失败,错误码: {response.status_code}" + return f"切换失败,错误码: {response.status_code}" \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 6d184b6b4..2b879253f 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -1,13 +1,10 @@ -from config.logger import setup_logging import os import re import time import random -import asyncio import difflib import traceback from pathlib import Path -from core.utils import p3 from core.handle.sendAudioHandle import send_stt_message from plugins_func.register import register_function, ToolType, ActionResponse, Action from core.utils.dialogue import Message @@ -51,8 +48,8 @@ def play_music(conn, song_name: str): ) # 提交异步任务 - future = asyncio.run_coroutine_threadsafe( - handle_music_command(conn, music_intent), conn.loop + task = conn.loop.create_task( + handle_music_command(conn, music_intent) # 封装异步逻辑 ) # 非阻塞回调处理 @@ -63,7 +60,7 @@ def play_music(conn, song_name: str): except Exception as e: conn.logger.bind(tag=TAG).error(f"播放失败: {e}") - future.add_done_callback(handle_done) + task.add_done_callback(handle_done) return ActionResponse( action=Action.NONE, result="指令已接收", response="正在为您播放音乐" @@ -178,13 +175,13 @@ def _get_random_play_prompt(song_name): # 移除文件扩展名 clean_name = os.path.splitext(song_name)[0] prompts = [ - f"正在为您播放,{clean_name}", - f"请欣赏歌曲,{clean_name}", - f"即将为您播放,{clean_name}", - f"为您带来,{clean_name}", - f"让我们聆听,{clean_name}", - f"接下来请欣赏,{clean_name}", - f"为您献上,{clean_name}", + f"正在为您播放,《{clean_name}》", + f"请欣赏歌曲,《{clean_name}》", + f"即将为您播放,《{clean_name}》", + f"现在为您带来,《{clean_name}》", + f"让我们一起聆听,《{clean_name}》", + f"接下来请欣赏,《{clean_name}》", + f"此刻为您献上,《{clean_name}》", ] # 直接使用random.choice,不设置seed return random.choice(prompts) @@ -218,13 +215,14 @@ async def play_local_music(conn, specific_file=None): await send_stt_message(conn, text) conn.dialogue.put(Message(role="assistant", content=text)) - conn.tts.tts_text_queue.put( - TTSMessageDTO( - sentence_id=conn.sentence_id, - sentence_type=SentenceType.FIRST, - content_type=ContentType.ACTION, + if conn.intent_type == "intent_llm": + conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=conn.sentence_id, + sentence_type=SentenceType.FIRST, + content_type=ContentType.ACTION, + ) ) - ) conn.tts.tts_text_queue.put( TTSMessageDTO( sentence_id=conn.sentence_id, @@ -241,14 +239,15 @@ async def play_local_music(conn, specific_file=None): content_file=music_path, ) ) - conn.tts.tts_text_queue.put( - TTSMessageDTO( - sentence_id=conn.sentence_id, - sentence_type=SentenceType.LAST, - content_type=ContentType.ACTION, + if conn.intent_type == "intent_llm": + conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=conn.sentence_id, + sentence_type=SentenceType.LAST, + content_type=ContentType.ACTION, + ) ) - ) except Exception as e: conn.logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") - conn.logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + conn.logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") \ No newline at end of file diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index c9e839535..9e621c437 100755 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -21,7 +21,7 @@ cozepy==0.12.0 mem0ai==0.1.62 bs4==0.0.2 modelscope==1.23.2 -sherpa_onnx +sherpa_onnx==1.12.8 mcp==1.8.1 cnlunar==0.2.0 PySocks==1.7.1 @@ -33,4 +33,5 @@ markitdown==0.1.1 mcp-proxy==0.8.0 PyJWT==2.8.0 psutil==7.0.0 -portalocker==2.10.1 \ No newline at end of file +portalocker==2.10.1 +Jinja2==3.1.6 \ No newline at end of file