From fe83c50d898f38617ec92482343ea5281adccba0 Mon Sep 17 00:00:00 2001 From: Alireza Jahanshahlou Date: Thu, 16 Oct 2025 23:50:32 +0330 Subject: [PATCH] rev --- .../config/assets/wakeup_words_short.wav | Bin 0 -> 49964 bytes main/xiaozhi-server/config/config_loader.py | 48 +-- main/xiaozhi-server/config/logger.py | 40 +- .../config/manage_api_client.py | 60 +-- main/xiaozhi-server/config/settings.py | 18 +- main/xiaozhi-server/core/api/base_handler.py | 2 +- main/xiaozhi-server/core/api/ota_handler.py | 127 +++--- .../xiaozhi-server/core/api/vision_handler.py | 72 ++-- main/xiaozhi-server/core/auth.py | 110 +++-- main/xiaozhi-server/core/connection.py | 407 +++++++++--------- .../xiaozhi-server/core/handle/abortHandle.py | 4 +- .../xiaozhi-server/core/handle/helloHandle.py | 80 ++-- .../core/handle/intentHandler.py | 70 +-- .../core/handle/receiveAudioHandle.py | 72 ++-- .../core/handle/reportHandle.py | 80 ++-- .../core/handle/sendAudioHandle.py | 114 ++--- main/xiaozhi-server/core/handle/textHandle.py | 6 +- .../handle/textHandler/abortMessageHandler.py | 2 +- .../handle/textHandler/helloMessageHandler.py | 2 +- .../handle/textHandler/iotMessageHandler.py | 2 +- .../textHandler/listenMessageHandler.py | 24 +- .../handle/textHandler/mcpMessageHandler.py | 2 +- .../textHandler/serverMessageHandler.py | 28 +- .../core/handle/textMessageHandler.py | 6 +- .../core/handle/textMessageHandlerRegistry.py | 12 +- .../core/handle/textMessageProcessor.py | 26 +- .../core/handle/textMessageType.py | 2 +- main/xiaozhi-server/core/http_server.py | 18 +- main/xiaozhi-server/core/websocket_server.py | 121 ++++-- 29 files changed, 826 insertions(+), 729 deletions(-) create mode 100644 main/xiaozhi-server/config/assets/wakeup_words_short.wav diff --git a/main/xiaozhi-server/config/assets/wakeup_words_short.wav b/main/xiaozhi-server/config/assets/wakeup_words_short.wav new file mode 100644 index 0000000000000000000000000000000000000000..7a9fb82641e3f8dc7fd7babc998cac1b9519e610 GIT binary patch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BP-*nuclYdk3Rh94k_iBYcDgM3x NK4~}KZS< literal 0 HcmV?d00001 diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 66f046e98..4f35b1fdc 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -5,7 +5,7 @@ from config.manage_api_client import init_service, get_server_config, get_agent_ def get_project_dir(): - """Get the project root directory""" + """获取项目根目录""" return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/" @@ -16,10 +16,10 @@ def read_config(config_path): def load_config(): - """Load configuration file""" + """加载配置文件""" from core.utils.cache.manager import cache_manager, CacheType - # Check cache + # 检查缓存 cached_config = cache_manager.get(CacheType.CONFIG, "main_config") if cached_config is not None: return cached_config @@ -27,29 +27,29 @@ def load_config(): default_config_path = get_project_dir() + "config.yaml" custom_config_path = get_project_dir() + "data/.config.yaml" - # Load the default configuration + # 加载默认配置 default_config = read_config(default_config_path) custom_config = read_config(custom_config_path) if custom_config.get("manager-api", {}).get("url"): config = get_config_from_api(custom_config) else: - # Merge configuration + # 合并配置 config = merge_configs(default_config, custom_config) - # Initialize the directory + # 初始化目录 ensure_directories(config) - # Cache Configuration + # 缓存配置 cache_manager.set(CacheType.CONFIG, "main_config", config) return config def get_config_from_api(config): - """Get configuration from Java API""" - # Initialize the API client + """从Java API获取配置""" + # 初始化API客户端 init_service(config) - # Get server configuration + # 获取服务器配置 config_data = get_server_config() if config_data is None: raise Exception("Failed to fetch server config from API") @@ -59,7 +59,7 @@ def get_config_from_api(config): "url": config["manager-api"].get("url", ""), "secret": config["manager-api"].get("secret", ""), } - # The server configuration is based on the local + # server的配置以本地为准 if config.get("server"): config_data["server"] = { "ip": config["server"].get("ip", ""), @@ -72,19 +72,19 @@ def get_config_from_api(config): def get_private_config_from_api(config, device_id, client_id): - """Get private configuration from Java API""" + """从Java API获取私有配置""" return get_agent_models(device_id, client_id, config["selected_module"]) def ensure_directories(config): - """Make sure all configuration paths exist""" + """确保所有配置路径存在""" dirs_to_create = set() - project_dir = get_project_dir() # Get the project root directory - # Log file directory + project_dir = get_project_dir() # 获取项目根目录 + # 日志文件目录 log_dir = config.get("log", {}).get("log_dir", "tmp") dirs_to_create.add(os.path.join(project_dir, log_dir)) - # ASR/TTS module output directory + # ASR/TTS模块输出目录 for module in ["ASR", "TTS"]: if config.get(module) is None: continue @@ -93,7 +93,7 @@ def ensure_directories(config): if output_dir: dirs_to_create.add(output_dir) - # Create a model directory based on selected_module + # 根据selected_module创建模型目录 selected_modules = config.get("selected_module", {}) for module_type in ["ASR", "LLM", "TTS"]: selected_provider = selected_modules.get(module_type) @@ -109,24 +109,24 @@ def ensure_directories(config): full_model_dir = os.path.join(project_dir, output_dir) dirs_to_create.add(full_model_dir) - # Create a unified directory (keep the original data directory creation) + # 统一创建目录(保留原data目录创建) for dir_path in dirs_to_create: try: os.makedirs(dir_path, exist_ok=True) except PermissionError: - print(f"Warning: Unable to create directory {dir_path}, please check write permissions") + print(f"警告:无法创建目录 {dir_path},请检查写入权限") def merge_configs(default_config, custom_config): """ - Recursively merge configurations, custom_config takes priority + 递归合并配置,custom_config优先级更高 Args: - default_config: default configuration - custom_config: User-defined configuration + default_config: 默认配置 + custom_config: 用户自定义配置 Returns: - Merged configuration + 合并后的配置 """ if not isinstance(default_config, Mapping) or not isinstance( custom_config, Mapping @@ -145,4 +145,4 @@ def merge_configs(default_config, custom_config): else: merged[key] = value - return merged \ No newline at end of file + return merged diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py index 46de2dc1a..a16b6d574 100644 --- a/main/xiaozhi-server/config/logger.py +++ b/main/xiaozhi-server/config/logger.py @@ -10,8 +10,8 @@ _logger_initialized = False def get_module_abbreviation(module_name, module_dict): - """Get the module name abbreviation, if it is empty, return 00 - If the name contains an underscore, the first two characters after the underscore are returned. + """获取模块名称的缩写,如果为空则返回00 + 如果名称中包含下划线,则返回下划线后面的前两个字符 """ module_value = module_dict.get(module_name, "") if not module_value: @@ -23,7 +23,7 @@ def get_module_abbreviation(module_name, module_dict): def build_module_string(selected_module): - """Building module string""" + """构建模块字符串""" return ( get_module_abbreviation("VAD", selected_module) + get_module_abbreviation("ASR", selected_module) @@ -36,25 +36,25 @@ def build_module_string(selected_module): def formatter(record): - """Add default values ​​for logs without tags and handle dynamic module strings""" + """为没有 tag 的日志添加默认值,并处理动态模块字符串""" record["extra"].setdefault("tag", record["name"]) - # If selected_module is not set, use the default value + # 如果没有设置 selected_module,使用默认值 record["extra"].setdefault("selected_module", "00000000000000") - # Extract selected_module from extra to top level to support {selected_module} format + # 将 selected_module 从 extra 提取到顶级,以支持 {selected_module} 格式 record["selected_module"] = record["extra"]["selected_module"] return record["message"] def setup_logging(): check_config_file() - """Read the log configuration from the configuration file and set the log output format and level""" + """从配置文件中读取日志配置,并设置日志输出格式和级别""" config = load_config() log_config = config["log"] global _logger_initialized - #Configure logging during first initialization + # 第一次初始化时配置日志 if not _logger_initialized: - # Initialize with default module string + # 使用默认的模块字符串进行初始化 logger.configure( extra={ "selected_module": log_config.get("selected_module", "00000000000000"), @@ -80,35 +80,35 @@ def setup_logging(): os.makedirs(log_dir, exist_ok=True) os.makedirs(data_dir, exist_ok=True) - # Configure log output + # 配置日志输出 logger.remove() - # Output to console + # 输出到控制台 logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter) - # Output to file - unified directory, rotate by size - # Full path to the log file + # 输出到文件 - 统一目录,按大小轮转 + # 日志文件完整路径 log_file_path = os.path.join(log_dir, log_file) - # Add a log processor + # 添加日志处理器 logger.add( log_file_path, format=log_format_file, level=log_level, filter=formatter, - rotation="10 MB", # Each file is up to 10MB - retention="30 days", # retain for 30 days + rotation="10 MB", # 每个文件最大10MB + retention="30 days", # 保留30天 compression=None, encoding="utf-8", - enqueue=True, # Asynchronous safety + enqueue=True, # 异步安全 backtrace=True, diagnose=True, ) - _logger_initialized = True # Mark as initialized + _logger_initialized = True # 标记为已初始化 return logger def create_connection_logger(selected_module_str): - """Create a separate logger for the connection, binding the specified module string""" - return logger.bind(selected_module=selected_module_str) \ No newline at end of file + """为连接创建独立的日志器,绑定特定的模块字符串""" + return logger.bind(selected_module=selected_module_str) diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index 907abf46c..cd3f86c42 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -15,7 +15,7 @@ class DeviceNotFoundException(Exception): class DeviceBindException(Exception): def __init__(self, bind_code): self.bind_code = bind_code - super().__init__(f"Device binding exception, binding code: {bind_code}") + super().__init__(f"设备绑定异常,绑定码: {bind_code}") class ManageApiClient: @@ -24,7 +24,7 @@ class ManageApiClient: _secret = None def __new__(cls, config): - """Singleton mode ensures a globally unique instance and supports passing in configuration parameters""" + """单例模式确保全局唯一实例,并支持传入配置参数""" if cls._instance is None: cls._instance = super().__new__(cls) cls._init_client(config) @@ -32,23 +32,23 @@ class ManageApiClient: @classmethod def _init_client(cls, config): - """Initialize the persistent connection pool""" + """初始化持久化连接池""" cls.config = config.get("manager-api") if not cls.config: - raise Exception("manager-api configuration error") + raise Exception("manager-api配置错误") if not cls.config.get("url") or not cls.config.get("secret"): - raise Exception("Manager-API URL or secret configuration error") + raise Exception("manager-api的url或secret配置错误") if "你" in cls.config.get("secret"): - raise Exception("Please configure the manager-api secret first") + raise Exception("请先配置manager-api的secret") cls._secret = cls.config.get("secret") - cls.max_retries = cls.config.get("max_retries", 6) # Maximum number of retries - cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay (seconds) - # NOTE(goody): 2025/4/16 Unified management of http related resources, thread pool or timeout can be added later - # You can also configure apiToken and other common Auth methods later. + cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数 + cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒) + # NOTE(goody): 2025/4/16 http相关资源统一管理,后续可以增加线程池或者超时 + # 后续也可以统一配置apiToken之类的走通用的Auth cls._client = httpx.Client( base_url=cls.config.get("url"), headers={ @@ -56,39 +56,39 @@ class ManageApiClient: "Accept": "application/json", "Authorization": "Bearer " + cls._secret, }, - timeout=cls.config.get("timeout", 30), # The default timeout is 30 seconds + timeout=cls.config.get("timeout", 30), # 默认超时时间30秒 ) @classmethod def _request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """Send a single HTTP request and handle the response""" + """发送单次HTTP请求并处理响应""" endpoint = endpoint.lstrip("/") response = cls._client.request(method, endpoint, **kwargs) response.raise_for_status() result = response.json() - # Handle business errors returned by the API + # 处理API返回的业务错误 if result.get("code") == 10041: raise DeviceNotFoundException(result.get("msg")) elif result.get("code") == 10042: raise DeviceBindException(result.get("msg")) elif result.get("code") != 0: - raise Exception(f"API returned an error: {result.get('msg', 'Unknown error')}") + raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") - # Return success data + # 返回成功数据 return result.get("data") if result.get("code") == 0 else None @classmethod def _should_retry(cls, exception: Exception) -> bool: - """Determine whether the exception should be retried""" - # Network connection related errors + """判断异常是否应该重试""" + # 网络连接相关错误 if isinstance( exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) ): return True - HTTP Status Code Error + # HTTP状态码错误 if isinstance(exception, httpx.HTTPStatusError): status_code = exception.response.status_code return status_code in [408, 429, 500, 502, 503, 504] @@ -97,43 +97,43 @@ class ManageApiClient: @classmethod def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """Request executor with retry mechanism""" + """带重试机制的请求执行器""" retry_count = 0 while retry_count <= cls.max_retries: try: - # Execute the request + # 执行请求 return cls._request(method, endpoint, **kwargs) except Exception as e: - # Determine whether to retry + # 判断是否应该重试 if retry_count < cls.max_retries and cls._should_retry(e): retry_count += 1 print( - f"{method} {endpoint} request failed, will be retried for {retry_count} times after {cls.retry_delay:.1f} seconds" + f"{method} {endpoint} 请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试" ) time.sleep(cls.retry_delay) continue else: - # Do not retry, throw an exception directly + # 不重试,直接抛出异常 raise @classmethod def safe_close(cls): - """Safely shut down the connection pool""" + """安全关闭连接池""" if cls._client: cls._client.close() cls._instance = None def get_server_config() -> Optional[Dict]: - """Get the basic server configuration""" + """获取服务器基础配置""" return ManageApiClient._instance._execute_request("POST", "/config/server-base") def get_agent_models( mac_address: str, client_id: str, selected_module: Dict ) -> Optional[Dict]: - """Get proxy model configuration""" + """获取代理模型配置""" return ManageApiClient._instance._execute_request( "POST", "/config/agent-models", @@ -155,14 +155,14 @@ def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[Dict]: }, ) except Exception as e: - print(f"Failed to store short-term memory to server: {e}") + print(f"存储短期记忆到服务器失败: {e}") return None def report( mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time ) -> Optional[Dict]: - """Business method example with circuit breaker""" + """带熔断的业务方法示例""" if not content or not ManageApiClient._instance: return None try: @@ -181,7 +181,7 @@ def report( }, ) except Exception as e: - print(f"TTS report failed: {e}") + print(f"TTS上报失败: {e}") return None @@ -190,4 +190,4 @@ def init_service(config): def manage_api_http_safe_close(): - ManageApiClient.safe_close() \ No newline at end of file + ManageApiClient.safe_close() diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index e4589dc24..fb8868b40 100644 --- a/main/xiaozhi-server/config/settings.py +++ b/main/xiaozhi-server/config/settings.py @@ -11,23 +11,23 @@ def check_config_file(): if config_file_valid: return """ - Simplified configuration check, only prompting the use of user configuration files + 简化的配置检查,仅提示用户配置文件的使用情况 """ custom_config_file = get_project_dir() + "data/." + default_config_file if not os.path.exists(custom_config_file): raise FileNotFoundError( - "Cannot find the data/.config.yaml file. Please follow the tutorial to confirm whether the configuration file exists." + "找不到data/.config.yaml文件,请按教程确认该配置文件是否存在" ) - # Check if configuration is read from API + # 检查是否从API读取配置 config = load_config() if config.get("read_config_from_api", False): - print("Read configuration from API") + print("从API读取配置") old_config_origin = read_config(custom_config_file) if old_config_origin.get("selected_module") is not None: - error_msg = "Your configuration file seems to contain both the console configuration and the local configuration:\n" - error_msg += "\nSuggestions:\n" - error_msg += "1. Copy the config_from_api.yaml file in the root directory to data and rename it to .config.yaml\n" - error_msg += "2. Configure the interface address and key according to the tutorial\n" + error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n" + error_msg += "\n建议您:\n" + error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n" + error_msg += "2、按教程配置好接口地址和密钥\n" raise ValueError(error_msg) - config_file_valid = True \ No newline at end of file + config_file_valid = True diff --git a/main/xiaozhi-server/core/api/base_handler.py b/main/xiaozhi-server/core/api/base_handler.py index c11dd2235..7330185e4 100644 --- a/main/xiaozhi-server/core/api/base_handler.py +++ b/main/xiaozhi-server/core/api/base_handler.py @@ -8,7 +8,7 @@ class BaseHandler: self.logger = setup_logging() def _add_cors_headers(self, response): - """Add cors header information""" + """添加CORS头信息""" response.headers["Access-Control-Allow-Headers"] = ( "client-id, content-type, device-id" ) diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py index 44858e66e..d3d37348f 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -4,6 +4,8 @@ import base64 import hashlib import hmac from aiohttp import web + +from core.auth import AuthManager from core.utils.util import get_local_ip from core.api.base_handler import BaseHandler @@ -13,56 +15,71 @@ TAG = __name__ class OTAHandler(BaseHandler): def __init__(self, config: dict): super().__init__(config) - + auth_config = config["server"].get("auth", {}) + self.auth_enable = auth_config.get("enabled", False) + # 设备白名单 + self.allowed_devices = set(auth_config.get("allowed_devices", [])) + secret_key = config["server"]["auth_key"] + expire_seconds = auth_config.get("expire_seconds") + self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds) + def generate_password_signature(self, content: str, secret_key: str) -> str: - """Generate MQTT cryptographic signature - + """生成MQTT密码签名 + Args: - content: Signature content (clientId + '|' + username) - secret_key: key - + content: 签名内容 (clientId + '|' + username) + secret_key: 密钥 + Returns: - str: Base64 encoded hmac sh a256 signature + str: Base64编码的HMAC-SHA256签名 """ try: - hmac_obj = hmac.new(secret_key.encode('utf-8'), content.encode('utf-8'), hashlib.sha256) + hmac_obj = hmac.new( + secret_key.encode("utf-8"), content.encode("utf-8"), hashlib.sha256 + ) signature = hmac_obj.digest() - return base64.b64encode(signature).decode('utf-8') + return base64.b64encode(signature).decode("utf-8") except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to generate mqtt password signature: {e}") + self.logger.bind(tag=TAG).error(f"生成MQTT密码签名失败: {e}") return "" def _get_websocket_url(self, local_ip: str, port: int) -> str: - """Get the websocket address + """获取websocket地址 Args: - local_ip: local IP address - port: port number + local_ip: 本地IP地址 + port: 端口号 Returns: - str: websocket address + str: websocket地址 """ server_config = self.config["server"] websocket_config = server_config.get("websocket", "") - if "your" not in websocket_config: + if "你的" not in websocket_config: return websocket_config else: return f"ws://{local_ip}:{port}/xiaozhi/v1/" async def handle_post(self, request): - """Handle OTA POST request""" + """处理 OTA POST 请求""" try: data = await request.text() - self.logger.bind(tag=TAG).debug(f"OTA request method: {request.method}") - self.logger.bind(tag=TAG).debug(f"OTA request header: {request.headers}") - self.logger.bind(tag=TAG).debug(f"OTA request data: {data}") + self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}") + self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}") + self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}") device_id = request.headers.get("device-id", "") if device_id: - self.logger.bind(tag=TAG).info(f"OTA request device ID: {device_id}") + self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}") else: - raise Exception("OTA request device ID is empty") + raise Exception("OTA请求设备ID为空") + + client_id = request.headers.get("client-id", "") + if client_id: + self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}") + else: + raise Exception("OTA请求ClientID为空") data_json = json.loads(data) @@ -80,12 +97,11 @@ class OTAHandler(BaseHandler): "url": "", }, } - mqtt_gateway_endpoint = server_config.get("mqtt_gateway") - - if mqtt_gateway_endpoint: # If a non-empty string is configured - # Try to get the device model from the request data + + if mqtt_gateway_endpoint: # 如果配置了非空字符串 + # 尝试从请求数据中获取设备型号 device_model = "default" try: if "device" in data_json and isinstance(data_json["device"], dict): @@ -94,51 +110,64 @@ class OTAHandler(BaseHandler): device_model = data_json["model"] group_id = f"GID_{device_model}".replace(":", "_").replace(" ", "_") except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to get device model: {e}") + self.logger.bind(tag=TAG).error(f"获取设备型号失败: {e}") group_id = "GID_default" mac_address_safe = device_id.replace(":", "_") mqtt_client_id = f"{group_id}@@@{mac_address_safe}@@@{mac_address_safe}" - # Build user data - user_data = { - "ip": "unknown" - } + # 构建用户数据 + user_data = {"ip": "unknown"} try: user_data_json = json.dumps(user_data) - username = base64.b64encode(user_data_json.encode('utf-8')).decode('utf-8') + username = base64.b64encode(user_data_json.encode("utf-8")).decode( + "utf-8" + ) except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to generate username: {e}") + self.logger.bind(tag=TAG).error(f"生成用户名失败: {e}") username = "" - # Generate password + # 生成密码 password = "" signature_key = server_config.get("mqtt_signature_key", "") if signature_key: - password = self.generate_password_signature(mqtt_client_id + "|" + username, signature_key) + password = self.generate_password_signature( + mqtt_client_id + "|" + username, signature_key + ) if not password: - password = "" # Leave it blank if the signature fails. The device decides whether to allow passwordless authentication. + password = "" # 签名失败则留空,由设备决定是否允许无密码 else: - self.logger.bind(tag=TAG).warning("MQTT signature key missing, password left blank") + self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空") - # Build MQTT configuration (use mqtt_gateway string directly) + # 构建MQTT配置(直接使用 mqtt_gateway 字符串) return_json["mqtt_gateway"] = { "endpoint": mqtt_gateway_endpoint, "client_id": mqtt_client_id, "username": username, "password": password, "publish_topic": "device-server", - "subscribe_topic": f"devices/p2p/{mac_address_safe}" + "subscribe_topic": f"devices/p2p/{mac_address_safe}", } - self.logger.bind(tag=TAG).info(f"Send MQTT gateway configuration for device {device_id}") - - - else: # mqtt_gateway is not configured, send WebSocket + self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置") + + else: # 未配置 mqtt_gateway,下发 WebSocket + # 如果开启了认证,则进行认证校验 + token = "" + if self.auth_enable: + if self.allowed_devices: + if device_id not in self.allowed_devices: + token = self.auth.generate_token(client_id, device_id) + else: + token = self.auth.generate_token(client_id, device_id) return_json["websocket"] = { "url": self._get_websocket_url(local_ip, port), + "token": token, } - self.logger.bind(tag=TAG).info(f"MQTT gateway not configured, send WebSocket configuration for device {device_id}") - + self.logger.bind(tag=TAG).info( + f"未配置MQTT网关,为设备 {device_id} 下发WebSocket配置" + ) + self.logger.bind(tag=TAG).info(f"{return_json}") + response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", @@ -154,17 +183,17 @@ class OTAHandler(BaseHandler): return response async def handle_get(self, request): - """Handle OTA GET request""" + """处理 OTA GET 请求""" try: server_config = self.config["server"] local_ip = get_local_ip() port = int(server_config.get("port", 8000)) websocket_url = self._get_websocket_url(local_ip, port) - message = f"OTA interface is running normally. The websocket address sent to the device is: {websocket_url}" + message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}" response = web.Response(text=message, content_type="text/plain") except Exception as e: - self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}") - response = web.Response(text="OTA interface exception", content_type="text/plain") + self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}") + response = web.Response(text="OTA接口异常", content_type="text/plain") finally: self._add_cors_headers(response) - return response \ No newline at end of file + return response diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py index 91a3616a8..70be247af 100644 --- a/main/xiaozhi-server/core/api/vision_handler.py +++ b/main/xiaozhi-server/core/api/vision_handler.py @@ -12,7 +12,7 @@ from plugins_func.register import Action TAG = __name__ -# Set the maximum file size to 5MB +# 设置最大文件大小为5MB MAX_FILE_SIZE = 5 * 1024 * 1024 @@ -20,79 +20,79 @@ class VisionHandler: def __init__(self, config: dict): self.config = config self.logger = setup_logging() - # Initialize the authentication tool + # 初始化认证工具 self.auth = AuthToken(config["server"]["auth_key"]) def _create_error_response(self, message: str) -> dict: - """Create a unified error response format""" + """创建统一的错误响应格式""" return {"success": False, "message": message} def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]: - """Verify the authentication token""" + """验证认证token""" auth_header = request.headers.get("Authorization", "") if not auth_header.startswith("Bearer "): return False, None - token = auth_header[7:] # remove the "Bearer" prefix + token = auth_header[7:] # 移除"Bearer "前缀 return self.auth.verify_token(token) async def handle_post(self, request): - """Handle MCP Vision POST request""" - response = None # Initialize the response variable + """处理 MCP Vision POST 请求""" + response = None # 初始化response变量 try: - # Verify the token + # 验证token is_valid, token_device_id = self._verify_auth_token(request) if not is_valid: response = web.Response( text=json.dumps( - self._create_error_response("Invalid authentication token or token has expired") + self._create_error_response("无效的认证token或token已过期") ), content_type="application/json", status=401, ) return response - # Get request header information + # 获取请求头信息 device_id = request.headers.get("Device-Id", "") client_id = request.headers.get("Client-Id", "") if device_id != token_device_id: - raise ValueError("Device ID does not match token") - # Parsing multipart/form-data requests + raise ValueError("设备ID与token不匹配") + # 解析multipart/form-data请求 reader = await request.multipart() - # Read the question field + # 读取question字段 question_field = await reader.next() if question_field is None: - raise ValueError("missing problem field") + raise ValueError("缺少问题字段") question = await question_field.text() self.logger.bind(tag=TAG).debug(f"Question: {question}") - # Read image file + # 读取图片文件 image_field = await reader.next() if image_field is None: - raise ValueError("missing image file") + raise ValueError("缺少图片文件") - # Read image data + # 读取图片数据 image_data = await image_field.read() if not image_data: - raise ValueError("Image data is empty") + raise ValueError("图片数据为空") - # Check file size + # 检查文件大小 if len(image_data) > MAX_FILE_SIZE: raise ValueError( - f"The image size exceeds the limit, the maximum allowed is {MAX_FILE_SIZE/1024/1024}MB" + f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB" ) - # Check file format + # 检查文件格式 if not is_valid_image_file(image_data): raise ValueError( - "File format not supported, please upload a valid image file (JPEG, PNG, GIF, BMP, TIFF, WEBP formats supported)" + "不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)" ) - # Convert the image to base64 encoding + # 将图片转换为base64编码 image_base64 = base64.b64encode(image_data).decode("utf-8") - # If the smart console is turned on, get the model configuration from the smart console + # 如果开启了智控台,则从智控台获取模型配置 current_config = copy.deepcopy(self.config) read_config_from_api = current_config.get("read_config_from_api", False) if read_config_from_api: @@ -104,7 +104,7 @@ class VisionHandler: select_vllm_module = current_config["selected_module"].get("VLLM") if not select_vllm_module: - raise ValueError("You have not set the default visual analysis module") + raise ValueError("您还未设置默认的视觉分析模块") vllm_type = ( select_vllm_module @@ -113,7 +113,7 @@ class VisionHandler: ) if not vllm_type: - raise ValueError(f"Unable to find the provider corresponding to the VLLM module {vllm_type}") + raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") vllm = create_instance( vllm_type, current_config["VLLM"][select_vllm_module] @@ -132,15 +132,15 @@ class VisionHandler: content_type="application/json", ) except ValueError as e: - self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}") + self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}") return_json = self._create_error_response(str(e)) response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", ) except Exception as e: - self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}") - return_json = self._create_error_response("An error occurred while processing the request") + self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}") + return_json = self._create_error_response("处理请求时发生错误") response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", @@ -151,20 +151,20 @@ class VisionHandler: return response async def handle_get(self, request): - """Handle MCP Vision GET request""" + """处理 MCP Vision GET 请求""" try: vision_explain = get_vision_url(self.config) if vision_explain and len(vision_explain) > 0 and "null" != vision_explain: message = ( - f"MCP Vision interface is running normally. The vision explanation interface address is: {vision_explain}" + f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}" ) else: - message = "The MCP Vision interface is not running properly. Please open the .config.yaml file in the data directory, find [server.vision_explain], and set the address." + message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址" response = web.Response(text=message, content_type="text/plain") except Exception as e: - self.logger.bind(tag=TAG).error(f"MCP Vision GET request exception: {e}") - return_json = self._create_error_response("Server internal error") + self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}") + return_json = self._create_error_response("服务器内部错误") response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", @@ -174,9 +174,9 @@ class VisionHandler: return response def _add_cors_headers(self, response): - """Add CORS header information""" + """添加CORS头信息""" response.headers["Access-Control-Allow-Headers"] = ( "client-id, content-type, device-id" ) response.headers["Access-Control-Allow-Credentials"] = "true" - response.headers["Access-Control-Allow-Origin"] = "*" \ No newline at end of file + response.headers["Access-Control-Allow-Origin"] = "*" diff --git a/main/xiaozhi-server/core/auth.py b/main/xiaozhi-server/core/auth.py index f898864e2..be95da21e 100755 --- a/main/xiaozhi-server/core/auth.py +++ b/main/xiaozhi-server/core/auth.py @@ -1,54 +1,72 @@ -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() +import hmac +import base64 +import hashlib +import time class AuthenticationError(Exception): - """Authentication exception""" + """认证异常""" + pass -class AuthMiddleware: - def __init__(self, config): - self.config = config - self.auth_config = config["server"].get("auth", {}) - # Build a token lookup table - self.tokens = { - item["token"]: item["name"] - for item in self.auth_config.get("tokens", []) - } - # Device Whitelist - self.allowed_devices = set( - self.auth_config.get("allowed_devices", []) - ) +class AuthManager: + """ + 统一授权认证管理器 + 生成与验证 client_id device_id token(HMAC-SHA256)认证三元组 + token 中不含明文 client_id/device_id,只携带签名 + 时间戳; client_id/device_id在连接时传递 + 在 MQTT 中 client_id: client_id, username: device_id, password: token + 在 Websocket 中,header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......} + """ + + def __init__(self, secret_key: str, expire_seconds: int = 60 * 60 * 24 * 30): + if not expire_seconds or expire_seconds < 0: + self.expire_seconds = 60 * 60 * 24 * 30 + else: + self.expire_seconds = expire_seconds + self.secret_key = secret_key + + def _sign(self, content: str) -> str: + """HMAC-SHA256签名并Base64编码""" + sig = hmac.new( + self.secret_key.encode("utf-8"), content.encode("utf-8"), hashlib.sha256 + ).digest() + return base64.urlsafe_b64encode(sig).decode("utf-8").rstrip("=") + + def generate_token(self, client_id: str, username: str) -> str: + """ + 生成 token + Args: + client_id: 设备连接ID + username: 设备用户名(通常为deviceId) + Returns: + str: token字符串 + """ + ts = int(time.time()) + content = f"{client_id}|{username}|{ts}" + signature = self._sign(content) + # token仅包含签名与时间戳,不包含明文信息 + token = f"{signature}.{ts}" + return token + + def verify_token(self, token: str, client_id: str, username: str) -> bool: + """ + 验证token有效性 + Args: + token: 客户端传入的token + client_id: 连接使用的client_id + username: 连接使用的username + """ + try: + sig_part, ts_str = token.split(".") + ts = int(ts_str) + if int(time.time()) - ts > self.expire_seconds: + return False # 过期 + + expected_sig = self._sign(f"{client_id}|{username}|{ts}") + if not hmac.compare_digest(sig_part, expected_sig): + return False - async def authenticate(self, headers): - """Verify connection request""" - # Check if authentication is enabled - if not self.auth_config.get("enabled", False): return True - - # Check if the device is in the whitelist - device_id = headers.get("device-id", "") - - if self.allowed_devices and device_id in self.allowed_devices: - return True - - Verify the Authorization header - auth_header = headers.get("authorization", "") - if not auth_header.startswith("Bearer "): - logger.bind(tag=TAG).error("Missing or invalid Authorization header") - raise AuthenticationError("Missing or invalid Authorization header") - - token = auth_header.split(" ")[1] - if token not in self.tokens: - logger.bind(tag=TAG).error(f"Invalid token: {token}") - raise AuthenticationError("Invalid token") - - logger.bind(tag=TAG).info(f"Authentication successful - Device: {device_id}, Token: {self.tokens[token]}") - return True - - def get_token_name(self, token): - """Get the device name corresponding to the token""" - return self.tokens.get(token) \ No newline at end of file + except Exception: + return False diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 18c4d16da..4337a488a 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -10,6 +10,7 @@ import threading import traceback import subprocess import websockets + from core.utils.util import ( extract_json_from_string, check_vad_update, @@ -31,8 +32,8 @@ from core.providers.asr.dto.dto import InterfaceType from core.handle.textHandle import handleTextMessage from core.providers.tools.unified_tool_handler import UnifiedToolHandler from plugins_func.loadplugins import auto_import_modules -from plugins_func.register import Action, ActionResponse -from core.auth import AuthMiddleware, AuthenticationError +from plugins_func.register import Action +from core.auth import AuthenticationError from config.config_loader import get_private_config_from_api from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType from config.logger import setup_logging, build_module_string, create_connection_logger @@ -54,7 +55,7 @@ class ConnectionHandler: def __init__( self, config: Dict[str, Any], - _What, + _vad, _asr, _llm, _memory, @@ -65,9 +66,8 @@ class ConnectionHandler: self.config = copy.deepcopy(config) self.session_id = str(uuid.uuid4()) self.logger = setup_logging() - self.server = server # Save the reference to the server instance + self.server = server # 保存server实例的引用 - self.auth = AuthMiddleware(config) self.need_bind = False self.bind_code = None self.read_config_from_api = self.config.get("read_config_from_api", False) @@ -82,107 +82,88 @@ class ConnectionHandler: self.chat_history_conf = 0 self.audio_format = "opus" - # Client status related + # 客户端状态相关 self.client_abort = False self.client_is_speaking = False self.client_listen_mode = "auto" - #Thread task related + # 线程任务相关 self.loop = asyncio.get_event_loop() self.stop_event = threading.Event() self.executor = ThreadPoolExecutor(max_workers=5) - # Add reporting thread pool + # 添加上报线程池 self.report_queue = queue.Queue() self.report_thread = None - # In the future, you can modify this to adjust the reporting of asr and tts. Currently, both are enabled by default. + # 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启 self.report_asr_enable = self.read_config_from_api self.report_tts_enable = self.read_config_from_api - # Dependent components + # 依赖的组件 self.vad = None self.asr = None self.tts = None self._asr = _asr - self._what = _what + self._vad = _vad self.llm = _llm self.memory = _memory self.intent = _intent - # Manage voiceprint recognition separately for each connection + # 为每个连接单独管理声纹识别 self.voiceprint_provider = None - #vad related variables + # vad相关变量 self.client_audio_buffer = bytearray() self.client_have_voice = False - self.last_activity_time = 0.0 # Unified activity timestamp (milliseconds) + self.last_activity_time = 0.0 # 统一的活动时间戳(毫秒) self.client_voice_stop = False self.client_voice_window = deque(maxlen=5) self.last_is_voice = False - # asr related variables - # Because the public local ASR may be used in actual deployment, the variables cannot be exposed to the public ASR - # Therefore, variables related to ASR need to be defined here and belong to the private variables of connection + # asr相关变量 + # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR + # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量 self.asr_audio = [] self.asr_audio_queue = queue.Queue() - #llm related variables + # llm相关变量 self.llm_finish_task = True self.dialogue = Dialogue() - # tts related variables + # tts相关变量 self.sentence_id = None - # Handle TTS response with no text returned + # 处理TTS响应没有文本返回 self.tts_MessageText = "" - #iot related variables + # iot相关变量 self.iot_descriptors = {} self.func_handler = None self.cmd_exit = self.config["exit_commands"] - # Whether to close the connection after the chat ends + # 是否在聊天结束后关闭连接 self.close_after_chat = False self.load_function_plugin = False self.intent_type = "nointent" self.timeout_seconds = ( int(self.config.get("close_connection_no_voice_time", 120)) + 60 - ) # Add 60 seconds to the original first closure and perform the second closure + ) # 在原来第一道关闭的基础上加60秒,进行二道关闭 self.timeout_task = None - # {"mcp":true} means to enable MCP function + # {"mcp":true} 表示启用MCP功能 self.features = None - # Mark whether the connection is from MQTT + # 标记连接是否来自MQTT self.conn_from_mqtt_gateway = False - # Initialize the prompt word manager + # 初始化提示词管理器 self.prompt_manager = PromptManager(config, self.logger) async def handle_connection(self, ws): try: - # Get and verify headers + # 获取并验证headers self.headers = dict(ws.request.headers) - - if self.headers.get("device-id", None) is None: - # Try to get the device-id from the query parameters of the URL - from urllib.parse import parse_qs, urlparse - - # Get the path from the WebSocket request - request_path = ws.request.path - if not request_path: - self.logger.bind(tag=TAG).error("Unable to obtain request path") - return - parsed_url = urlparse(request_path) - query_params = parse_qs(parsed_url.query) - if "device-id" in query_params: - self.headers["device-id"] = query_params["device-id"][0] - self.headers["client-id"] = query_params["client-id"][0] - else: - await ws.send("The port is normal. To test the connection, please use test_page.html") - await self.close(ws) - return real_ip = self.headers.get("x-real-ip") or self.headers.get( "x-forwarded-for" ) @@ -194,38 +175,36 @@ class ConnectionHandler: f"{self.client_ip} conn - Headers: {self.headers}" ) - # Authentication - await self.auth.authenticate(self.headers) - - # Authentication passed, continue processing - self.websocket = ws self.device_id = self.headers.get("device-id", None) - # Check if it is from MQTT connection + # 认证通过,继续处理 + self.websocket = ws + + # 检查是否来自MQTT连接 request_path = ws.request.path self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway") if self.conn_from_mqtt_gateway: - self.logger.bind(tag=TAG).info("Connection from: MQTT Gateway") + self.logger.bind(tag=TAG).info("连接来自:MQTT网关") - # Initialize activity timestamp + # 初始化活动时间戳 self.last_activity_time = time.time() * 1000 - # Start the timeout check task + # 启动超时检查任务 self.timeout_task = asyncio.create_task(self._check_timeout()) self.welcome_msg = self.config["xiaozhi"] self.welcome_msg["session_id"] = self.session_id - # Get differential configuration + # 获取差异化配置 self._initialize_private_config() - # Asynchronous initialization + # 异步初始化 self.executor.submit(self._initialize_components) try: async for message in self.websocket: await self._route_message(message) except websockets.exceptions.ConnectionClosed: - self.logger.bind(tag=TAG).info("Client disconnected") + self.logger.bind(tag=TAG).info("客户端断开连接") except AuthenticationError as e: self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}") @@ -238,113 +217,113 @@ class ConnectionHandler: try: await self._save_and_close(ws) except Exception as final_error: - self.logger.bind(tag=TAG).error(f"Error in final cleanup: {final_error}") - # Ensure the connection is closed even if saving the memory fails + 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"Error while forcing the connection to close: {close_error}" + f"强制关闭连接时出错: {close_error}" ) async def _save_and_close(self, ws): - """Save memory and close the connection""" + """保存记忆并关闭连接""" try: if self.memory: - # Using thread pool to save memory asynchronously + # 使用线程池异步保存记忆 def save_memory_task(): try: - # Create a new event loop (to avoid conflicts with the main loop) + # 创建新事件循环(避免与主循环冲突) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete( self.memory.save_memory(self.dialogue.dialogue) ) except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}") + self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}") finally: try: loop.close() except Exception: pass - # Start the thread to save the memory, do not wait for completion + # 启动线程保存记忆,不等待完成 threading.Thread(target=save_memory_task, daemon=True).start() except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}") + self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}") finally: - # Close the connection immediately without waiting for the memory save to complete + # 立即关闭连接,不等待记忆保存完成 try: await self.close(ws) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"Failed to close the connection after saving the memory: {close_error}" + f"保存记忆后关闭连接失败: {close_error}" ) async def _route_message(self, message): - """Message routing""" + """消息路由""" if isinstance(message, str): await handleTextMessage(self, message) elif isinstance(message, bytes): if self.vad is None or self.asr is None: return - # Process audio packets from the MQTT gateway + # 处理来自MQTT网关的音频包 if self.conn_from_mqtt_gateway and len(message) >= 16: handled = await self._process_mqtt_audio_message(message) if handled: return - # When header processing is not required or there is no header, process the original message directly + # 不需要头部处理或没有头部时,直接处理原始消息 self.asr_audio_queue.put(message) async def _process_mqtt_audio_message(self, message): """ - Processes audio messages from the MQTT gateway, parsing the 16-byte header and extracting the audio data + 处理来自MQTT网关的音频消息,解析16字节头部并提取音频数据 Args: - message: audio message containing headers + message: 包含头部的音频消息 Returns: - bool: Whether the message was processed successfully + bool: 是否成功处理了消息 """ try: - # Extract header information + # 提取头部信息 timestamp = int.from_bytes(message[8:12], "big") audio_length = int.from_bytes(message[12:16], "big") - # Extract audio data + # 提取音频数据 if audio_length > 0 and len(message) >= 16 + audio_length: - # With specified length, extract accurate audio data + # 有指定长度,提取精确的音频数据 audio_data = message[16 : 16 + audio_length] - # Sort by timestamp + # 基于时间戳进行排序处理 self._process_websocket_audio(audio_data, timestamp) return True elif len(message) > 16: - # No length is specified or the length is invalid, remove the header and process the remaining data + # 没有指定长度或长度无效,去掉头部后处理剩余数据 audio_data = message[16:] self.asr_audio_queue.put(audio_data) return True except Exception as e: - self.logger.bind(tag=TAG).error(f"Parsing WebSocket audio packet failed: {e}") + self.logger.bind(tag=TAG).error(f"解析WebSocket音频包失败: {e}") - # If the processing fails, returning False means that further processing is required. + # 处理失败,返回False表示需要继续处理 return False def _process_websocket_audio(self, audio_data, timestamp): - """Processing WebSocket format audio packets""" - # Initialize timestamp sequence management + """处理WebSocket格式的音频包""" + # 初始化时间戳序列管理 if not hasattr(self, "audio_timestamp_buffer"): self.audio_timestamp_buffer = {} self.last_processed_timestamp = 0 self.max_timestamp_buffer_size = 20 - # If the timestamp is increasing, process it directly + # 如果时间戳是递增的,直接处理 if timestamp >= self.last_processed_timestamp: self.asr_audio_queue.put(audio_data) self.last_processed_timestamp = timestamp - # Process subsequent packets in the buffer + # 处理缓冲区中的后续包 processed_any = True while processed_any: processed_any = False @@ -356,35 +335,35 @@ class ConnectionHandler: processed_any = True break else: - # Out-of-order packets, temporarily stored + # 乱序包,暂存 if len(self.audio_timestamp_buffer) < self.max_timestamp_buffer_size: self.audio_timestamp_buffer[timestamp] = audio_data else: self.asr_audio_queue.put(audio_data) async def handle_restart(self, message): - """Handle server restart request""" + """处理服务器重启请求""" try: - self.logger.bind(tag=TAG).info("Received server restart instruction, ready to execute...") + self.logger.bind(tag=TAG).info("收到服务器重启指令,准备执行...") - # Send confirmation response + # 发送确认响应 await self.websocket.send( json.dumps( { "type": "server", "status": "success", - "message": "Server restarting...", + "message": "服务器重启中...", "content": {"action": "restart"}, } ) ) - # Asynchronously execute the restart operation + # 异步执行重启操作 def restart_server(): - """How to actually perform the reboot""" + """实际执行重启的方法""" time.sleep(1) - self.logger.bind(tag=TAG).info("Execute server restart...") + self.logger.bind(tag=TAG).info("执行服务器重启...") subprocess.Popen( [sys.executable, "app.py"], stdin=sys.stdin, @@ -394,11 +373,11 @@ class ConnectionHandler: ) os._exit(0) - # Use threads to restart to avoid blocking the event loop + # 使用线程执行重启避免阻塞事件循环 threading.Thread(target=restart_server, daemon=True).start() except Exception as e: - self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}") + self.logger.bind(tag=TAG).error(f"重启失败: {str(e)}") await self.websocket.send( json.dumps( { @@ -417,60 +396,60 @@ class ConnectionHandler: ) self.logger = create_connection_logger(self.selected_module_str) - """Initialize components""" + """初始化组件""" if self.config.get("prompt") is not None: user_prompt = self.config["prompt"] - # Initialize with quick prompt words + # 使用快速提示词进行初始化 prompt = self.prompt_manager.get_quick_prompt(user_prompt) self.change_system_prompt(prompt) self.logger.bind(tag=TAG).info( - f"Quickly initialize component: prompt successful {prompt[:50]}..." + f"快速初始化组件: prompt成功 {prompt[:50]}..." ) - """Initialize local components""" + """初始化本地组件""" if self.vad is None: - self.what = self._what + self.vad = self._vad if self.asr is None: self.asr = self._initialize_asr() - # Initialize voiceprint recognition + # 初始化声纹识别 self._initialize_voiceprint() - # Open the speech recognition channel + # 打开语音识别通道 asyncio.run_coroutine_threadsafe( self.asr.open_audio_channels(self), self.loop ) if self.tts is None: self.tts = self._initialize_tts() - # Open the speech synthesis channel + # 打开语音合成通道 asyncio.run_coroutine_threadsafe( self.tts.open_audio_channels(self), self.loop ) - """Loading memory""" + """加载记忆""" self._initialize_memory() - """Load intent recognition""" + """加载意图识别""" self._initialize_intent() - """Initialize reporting thread""" + """初始化上报线程""" self._init_report_threads() - """Update system prompt words""" + """更新系统提示词""" self._init_prompt_enhancement() except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to instantiate component: {e}") + self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") def _init_prompt_enhancement(self): - # Update context information + # 更新上下文信息 self.prompt_manager.update_context_info(self, self.client_ip) enhanced_prompt = self.prompt_manager.build_enhanced_prompt( self.config["prompt"], self.device_id, self.client_ip ) if enhanced_prompt: self.change_system_prompt(enhanced_prompt) - self.logger.bind(tag=TAG).info("System prompt words have been enhanced and updated") + self.logger.bind(tag=TAG).info("系统提示词已增强更新") def _init_report_threads(self): - """Initialize ASR and TTS reporting threads""" + """初始化ASR和TTS上报线程""" if not self.read_config_from_api or self.need_bind: return if self.chat_history_conf == 0: @@ -480,10 +459,10 @@ class ConnectionHandler: target=self._report_worker, daemon=True ) self.report_thread.start() - self.logger.bind(tag=TAG).info("TTS reporting thread has started") + self.logger.bind(tag=TAG).info("TTS上报线程已启动") def _initialize_tts(self): - """Initialize TTS""" + """初始化TTS""" tts = None if not self.need_bind: tts = initialize_tts(self.config) @@ -494,39 +473,39 @@ class ConnectionHandler: return tts def _initialize_asr(self): - """Initialize ASR""" + """初始化ASR""" if self._asr.interface_type == InterfaceType.LOCAL: - # If the public ASR is a local service, return directly - # Because a local instance of ASR can be shared by multiple connections + # 如果公共ASR是本地服务,则直接返回 + # 因为本地一个实例ASR,可以被多个连接共享 asr = self._asr else: - # If the public ASR is a remote service, initialize a new instance - # Because remote ASR involves websocket connections and receiving threads, one instance per connection is required + # 如果公共ASR是远程服务,则初始化一个新实例 + # 因为远程ASR,涉及到websocket连接和接收线程,需要每个连接一个实例 asr = initialize_asr(self.config) return asr def _initialize_voiceprint(self): - """Initialize voiceprint recognition for the current connection""" + """为当前连接初始化声纹识别""" try: voiceprint_config = self.config.get("voiceprint", {}) if voiceprint_config: voiceprint_provider = VoiceprintProvider(voiceprint_config) if voiceprint_provider is not None and voiceprint_provider.enabled: self.voiceprint_provider = voiceprint_provider - self.logger.bind(tag=TAG).info("Voiceprint recognition function has been dynamically enabled during connection") + self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用") else: - self.logger.bind(tag=TAG).warning("Voiceprint recognition function is enabled but configuration is incomplete") + self.logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整") else: - self.logger.bind(tag=TAG).info("Voiceprint recognition function is not enabled") + self.logger.bind(tag=TAG).info("声纹识别功能未启用") except Exception as e: - self.logger.bind(tag=TAG).warning(f"Voiceprint recognition initialization failed: {str(e)}") + self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}") def _initialize_private_config(self): - """If it is obtained from the configuration file, a second instantiation is performed""" + """如果是从配置文件获取,则进行二次实例化""" if not self.read_config_from_api: return - """Get differentiated configuration from the interface for secondary instantiation, not full re-instantiation""" + """从接口获取差异化的配置进行二次实例化,非全量重新实例化""" try: begin_time = time.time() private_config = get_private_config_from_api( @@ -536,7 +515,7 @@ class ConnectionHandler: ) private_config["delete_audio"] = bool(self.config.get("delete_audio", True)) self.logger.bind(tag=TAG).info( - f"{time.time() - begin_time} seconds, differential configuration is obtained successfully: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" + f"{time.time() - begin_time} 秒,获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" ) except DeviceNotFoundException as e: self.need_bind = True @@ -547,7 +526,7 @@ class ConnectionHandler: private_config = {} except Exception as e: self.need_bind = True - self.logger.bind(tag=TAG).error(f"Failed to get differential configuration: {e}") + self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}") private_config = {} init_llm, init_tts, init_memory, init_intent = ( @@ -560,10 +539,10 @@ class ConnectionHandler: init_vad = check_vad_update(self.common_config, private_config) init_asr = check_asr_update(self.common_config, private_config) - if init_what: - self.config["WHAT"] = private_config["WHAT"] + if init_vad: + self.config["VAD"] = private_config["VAD"] self.config["selected_module"]["VAD"] = private_config["selected_module"][ - "WHAT" + "VAD" ] if init_asr: self.config["ASR"] = private_config["ASR"] @@ -598,7 +577,7 @@ class ConnectionHandler: self.config["Intent"] = private_config["Intent"] model_intent = private_config.get("selected_module", {}).get("Intent", {}) self.config["selected_module"]["Intent"] = model_intent - # Load plugin configuration + # 加载插件配置 if model_intent != "Intent_nointent": plugin_from_server = private_config.get("plugins", {}) for plugin, config_str in plugin_from_server.items(): @@ -609,7 +588,7 @@ class ConnectionHandler: ] = plugin_from_server.keys() if private_config.get("prompt", None) is not None: self.config["prompt"] = private_config["prompt"] - # Get voiceprint information + # 获取声纹信息 if private_config.get("voiceprint", None) is not None: self.config["voiceprint"] = private_config["voiceprint"] if private_config.get("summaryMemory", None) is not None: @@ -624,7 +603,7 @@ class ConnectionHandler: modules = initialize_modules( self.logger, private_config, - init_what, + init_vad, init_asr, init_llm, init_tts, @@ -632,7 +611,7 @@ class ConnectionHandler: init_intent, ) except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to initialize component: {e}") + self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}") modules = {} if modules.get("tts", None) is not None: self.tts = modules["tts"] @@ -650,7 +629,7 @@ class ConnectionHandler: def _initialize_memory(self): if self.memory is None: return - """Initialize memory module""" + """初始化记忆模块""" self.memory.init_memory( role_id=self.device_id, llm=self.llm, @@ -658,21 +637,21 @@ class ConnectionHandler: save_to_file=not self.read_config_from_api, ) - # Get memory summary configuration + # 获取记忆总结配置 memory_config = self.config["Memory"] memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][ "type" ] - # If nomen is used, return directly - if memory_type == "name": + # 如果使用 nomen,直接返回 + if memory_type == "nomem": return - # Using mem_local_short mode + # 使用 mem_local_short 模式 elif memory_type == "mem_local_short": memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][ "llm" ] if memory_llm_name and memory_llm_name in self.config["LLM"]: - # If a dedicated LLM is configured, create a separate LLM instance + # 如果配置了专用LLM,则创建独立的LLM实例 from core.utils import llm as llm_utils memory_llm_config = self.config["LLM"][memory_llm_name] @@ -681,13 +660,13 @@ class ConnectionHandler: memory_llm_type, memory_llm_config ) self.logger.bind(tag=TAG).info( - f"Created a dedicated LLM for memory summarization: {memory_llm_name}, type: {memory_llm_type}" + f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}" ) self.memory.set_llm(memory_llm) else: - # Otherwise use the main LLM + # 否则使用主LLM self.memory.set_llm(self.llm) - self.logger.bind(tag=TAG).info("Use the main LLM as the intent recognition model") + self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型") def _initialize_intent(self): if self.intent is None: @@ -697,24 +676,24 @@ class ConnectionHandler: ]["type"] if self.intent_type == "function_call" or self.intent_type == "intent_llm": self.load_function_plugin = True - """Initialize the intent recognition module""" - # Get intent recognition configuration + """初始化意图识别模块""" + # 获取意图识别配置 intent_config = self.config["Intent"] intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][ "type" ] - # If nointent is used, return directly + # 如果使用 nointent,直接返回 if intent_type == "nointent": return - # Using intent_llm mode + # 使用 intent_llm 模式 elif intent_type == "intent_llm": intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ "llm" ] if intent_llm_name and intent_llm_name in self.config["LLM"]: - # If a dedicated LLM is configured, create a separate LLM instance + # 如果配置了专用LLM,则创建独立的LLM实例 from core.utils import llm as llm_utils intent_llm_config = self.config["LLM"][intent_llm_name] @@ -723,31 +702,31 @@ class ConnectionHandler: intent_llm_type, intent_llm_config ) self.logger.bind(tag=TAG).info( - f"Created a dedicated LLM for intent recognition: {intent_llm_name}, type: {intent_llm_type}" + f"为意图识别创建了专用LLM: {intent_llm_name}, 类型: {intent_llm_type}" ) self.intent.set_llm(intent_llm) else: - # Otherwise use the main LLM + # 否则使用主LLM self.intent.set_llm(self.llm) - self.logger.bind(tag=TAG).info("Use the main LLM as the intent recognition model") + self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型") - """Load the Unified Tool Processor""" + """加载统一工具处理器""" self.func_handler = UnifiedToolHandler(self) - # Asynchronous initialization tool processor + # 异步初始化工具处理器 if hasattr(self, "loop") and self.loop: asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop) def change_system_prompt(self, prompt): self.prompt = prompt - # Update system prompt to context + # 更新系统prompt至上下文 self.dialogue.update_system_message(self.prompt) def chat(self, query, depth=0): - self.logger.bind(tag=TAG).info(f"The large model received a user message: {query}") + self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") self.llm_finish_task = False - # Create a new session ID and send the FIRST request when it is the top level + # 为最顶层时新建会话ID和发送FIRST请求 if depth == 0: self.sentence_id = str(uuid.uuid4().hex) self.dialogue.put(Message(role="user", content=query)) @@ -766,7 +745,7 @@ class ConnectionHandler: response_message = [] try: - # Using remembered conversations + # 使用带记忆的对话 memory_str = None if self.memory is not None: future = asyncio.run_coroutine_threadsafe( @@ -775,7 +754,7 @@ class ConnectionHandler: memory_str = future.result() if self.intent_type == "function_call" and functions is not None: - # Using streaming interfaces that support functions + # 使用支持functions的streaming接口 llm_responses = self.llm.response_with_functions( self.session_id, self.dialogue.get_llm_dialogue_with_memory( @@ -791,10 +770,10 @@ class ConnectionHandler: ), ) except Exception as e: - self.logger.bind(tag=TAG).error(f"LLM processing error {query}: {e}") + self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") return None - # Handling streaming responses + # 处理流式响应 tool_call_flag = False function_name = None function_id = None @@ -828,7 +807,7 @@ class ConnectionHandler: else: content = response - # Get emotional expressions in llm replies. Only get them once at the beginning of a conversation. + # 在llm回复中获取情绪表情,一轮对话只在开头获取一次 if emotion_flag and content is not None and content.strip(): asyncio.run_coroutine_threadsafe( textUtils.get_emotion(self, content), @@ -847,7 +826,7 @@ class ConnectionHandler: content_detail=content, ) ) - # Handling function calls + # 处理function call if tool_call_flag: bHasError = False if function_id is None: @@ -871,7 +850,7 @@ class ConnectionHandler: f"function call error: {content_arguments}" ) if not bHasError: - # If you need to process the large model first, add the log information after the relevant processing + # 如需要大模型先处理一轮,添加相关处理后的日志情况 if len(response_message) > 0: text_buff = "".join(response_message) self.tts_MessageText = text_buff @@ -886,7 +865,7 @@ class ConnectionHandler: "arguments": function_arguments, } - # Use a unified tool handler to handle all tool calls + # 使用统一工具处理器处理所有工具调用 result = asyncio.run_coroutine_threadsafe( self.func_handler.handle_llm_function_call( self, function_call_data @@ -895,7 +874,7 @@ class ConnectionHandler: ).result() self._handle_function_result(result, function_call_data, depth=depth) - #Store the conversation content + # 存储对话内容 if len(response_message) > 0: text_buff = "".join(response_message) self.tts_MessageText = text_buff @@ -909,7 +888,7 @@ class ConnectionHandler: ) ) self.llm_finish_task = True - # Use lambda to delay calculation and execute get_llm_dialogue() only at DEBUG level + # 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue() self.logger.bind(tag=TAG).debug( lambda: json.dumps( self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False @@ -919,11 +898,11 @@ class ConnectionHandler: return True def _handle_function_result(self, result, function_call_data, depth): - if result.action == Action.RESPONSE: # Reply directly to the front end + if result.action == Action.RESPONSE: # 直接回复前端 text = result.response self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text) self.dialogue.put(Message(role="assistant", content=text)) - elif result.action == Action.REQLLM: # After calling the function, request llm to generate a reply + elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 text = result.result if text is not None and len(text) > 0: function_id = function_call_data["id"] @@ -968,51 +947,51 @@ class ConnectionHandler: pass def _report_worker(self): - """Chat record reporting work thread""" + """聊天记录上报工作线程""" while not self.stop_event.is_set(): try: - # Get data from the queue, set a timeout to periodically check for stop events + # 从队列获取数据,设置超时以便定期检查停止事件 item = self.report_queue.get(timeout=1) - if item is None: # Detect poison pill object + if item is None: # 检测毒丸对象 break try: - # Check thread pool status + # 检查线程池状态 if self.executor is None: continue - # Submit tasks to the thread pool + # 提交任务到线程池 self.executor.submit(self._process_report, *item) except Exception as e: - self.logger.bind(tag=TAG).error(f"Chat record reporting thread exception: {e}") + self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}") except queue.Empty: continue except Exception as e: - self.logger.bind(tag=TAG).error(f"Chat record reporting work thread exception: {e}") + self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}") - self.logger.bind(tag=TAG).info("Chat record reporting thread has exited") + self.logger.bind(tag=TAG).info("聊天记录上报线程已退出") def _process_report(self, type, text, audio_data, report_time): - """Processing reporting tasks""" + """处理上报任务""" try: - # Execute report (input binary data) + # 执行上报(传入二进制数据) report(self, type, text, audio_data, report_time) except Exception as e: - self.logger.bind(tag=TAG).error(f"Reporting processing exception: {e}") + self.logger.bind(tag=TAG).error(f"上报处理异常: {e}") finally: - # Mark the task completed + # 标记任务完成 self.report_queue.task_done() def clearSpeakStatus(self): self.client_is_speaking = False - self.logger.bind(tag=TAG).debug(f"Clear server speech status") + self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态") async def close(self, ws=None): - """Resource cleanup method""" + """资源清理方法""" try: - # Clear the audio buffer + # 清理音频缓冲区 if hasattr(self, "audio_buffer"): self.audio_buffer.clear() - # Cancel timeout task + # 取消超时任务 if self.timeout_task and not self.timeout_task.done(): self.timeout_task.cancel() try: @@ -1021,36 +1000,36 @@ class ConnectionHandler: pass self.timeout_task = None - # Cleanup tool processor resources + # 清理工具处理器资源 if hasattr(self, "func_handler") and self.func_handler: try: await self.func_handler.cleanup() except Exception as cleanup_error: self.logger.bind(tag=TAG).error( - f"Error in cleanup tool processor: {cleanup_error}" + f"清理工具处理器时出错: {cleanup_error}" ) - # Trigger stop event + # 触发停止事件 if self.stop_event: self.stop_event.set() - # Clear the task queue + # 清空任务队列 self.clear_queues() - # Close the WebSocket connection + # 关闭WebSocket连接 try: if ws: - # Safely check WebSocket status and close + # 安全地检查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: - # If there is no closed attribute, try to close it directly + # 如果没有closed属性,直接尝试关闭 await ws.close() except Exception: - # If shutdown fails, ignore the error + # 如果关闭失败,忽略错误 pass elif self.websocket: try: @@ -1065,43 +1044,43 @@ class ConnectionHandler: ): await self.websocket.close() else: - # If there is no closed attribute, try to close it directly + # 如果没有closed属性,直接尝试关闭 await self.websocket.close() except Exception: - # If shutdown fails, ignore the error + # 如果关闭失败,忽略错误 pass except Exception as ws_error: - self.logger.bind(tag=TAG).error(f"Error closing WebSocket connection: {ws_error}") + self.logger.bind(tag=TAG).error(f"关闭WebSocket连接时出错: {ws_error}") if self.tts: await self.tts.close() - #Finally close the thread pool (to avoid blocking) + # 最后关闭线程池(避免阻塞) if self.executor: try: self.executor.shutdown(wait=False) except Exception as executor_error: self.logger.bind(tag=TAG).error( - f"Error shutting down thread pool: {executor_error}" + f"关闭线程池时出错: {executor_error}" ) self.executor = None - self.logger.bind(tag=TAG).info("Connection resources have been released") + self.logger.bind(tag=TAG).info("连接资源已释放") except Exception as e: - self.logger.bind(tag=TAG).error(f"Error closing connection: {e}") + self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}") finally: - # Make sure the stop event is set + # 确保停止事件被设置 if self.stop_event: self.stop_event.set() def clear_queues(self): - """Clear all task queues""" + """清空所有任务队列""" if self.tts: self.logger.bind(tag=TAG).debug( - f"Start cleaning: TTS queue size = {self.tts.tts_text_queue.qsize()}, audio queue size = {self.tts.tts_audio_queue.qsize()}" + f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}" ) - # Clear the queue using non-blocking method + # 使用非阻塞方式清空队列 for q in [ self.tts.tts_text_queue, self.tts.tts_audio_queue, @@ -1116,7 +1095,7 @@ class ConnectionHandler: break self.logger.bind(tag=TAG).debug( - f"Cleanup completed: TTS queue size = {self.tts.tts_text_queue.qsize()}, audio queue size = {self.tts.tts_audio_queue.qsize()}" + f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}" ) def reset_vad_states(self): @@ -1137,10 +1116,10 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") async def _check_timeout(self): - """Check connection timeout""" + """检查连接超时""" try: while not self.stop_event.is_set(): - # Check if timeout has occurred (only if timestamps have been initialized) + # 检查是否超时(只有在时间戳已初始化的情况下) if self.last_activity_time > 0.0: current_time = time.time() * 1000 if ( @@ -1148,20 +1127,20 @@ class ConnectionHandler: > self.timeout_seconds * 1000 ): if not self.stop_event.is_set(): - self.logger.bind(tag=TAG).info("Connection timed out, ready to close") - # Set the stop event to prevent repeated processing + self.logger.bind(tag=TAG).info("连接超时,准备关闭") + # 设置停止事件,防止重复处理 self.stop_event.set() - # Use try-except to wrap the shutdown operation to ensure that it is not blocked due to exceptions + # 使用 try-except 包装关闭操作,确保不会因为异常而阻塞 try: await self.close(self.websocket) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"Error closing connection timeout: {close_error}" + f"超时关闭连接时出错: {close_error}" ) break - # Check every 10 seconds to avoid too frequent + # 每10秒检查一次,避免过于频繁 await asyncio.sleep(10) except Exception as e: - self.logger.bind(tag=TAG).error(f"Timeout check task error: {e}") + self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}") finally: - self.logger.bind(tag=TAG).info("Timeout check task has exited") \ No newline at end of file + self.logger.bind(tag=TAG).info("超时检查任务已退出") diff --git a/main/xiaozhi-server/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/abortHandle.py index 01ef59ebc..ce6f22b6c 100644 --- a/main/xiaozhi-server/core/handle/abortHandle.py +++ b/main/xiaozhi-server/core/handle/abortHandle.py @@ -5,10 +5,10 @@ TAG = __name__ async def handleAbortMessage(conn): conn.logger.bind(tag=TAG).info("Abort message received") - # Set to interrupt state, which will automatically interrupt llm and tts tasks + # 设置成打断状态,会自动打断llm、tts任务 conn.client_abort = True conn.clear_queues() - # Interrupt client speaking state + # 打断客户端说话状态 await conn.websocket.send( json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id}) ) diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index ebd8dd5bb..e5df55c7b 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -6,7 +6,7 @@ from core.utils.dialogue import Message from core.utils.util import audio_to_data from core.providers.tts.dto.dto import SentenceType from core.utils.wakeup_word import WakeupWordsConfig -from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message +from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes from core.providers.tools.device_mcp import ( MCPClient, @@ -17,35 +17,45 @@ from core.providers.tools.device_mcp import ( TAG = __name__ WAKEUP_CONFIG = { - "refresh_time": 5, - "words": ["Hello", "Hello", "Hey, hello", "Hi"], + "refresh_time": 10, + "responses": [ + "我一直都在呢,您请说。", + "在的呢,请随时吩咐我。", + "来啦来啦,请告诉我吧。", + "您请说,我正听着。", + "请您讲话,我准备好了。", + "请您说出指令吧。", + "我认真听着呢,请讲。", + "请问您需要什么帮助?", + "我在这里,等候您的指令。", + ], } -# Create a global wake-up word configuration manager +# 创建全局的唤醒词配置管理器 wakeup_words_config = WakeupWordsConfig() -# Lock used to prevent concurrent calls to wakeupWordsResponse +# 用于防止并发调用wakeupWordsResponse的锁 _wakeup_response_lock = asyncio.Lock() async def handleHelloMessage(conn, msg_json): - """Process hello message""" + """处理hello消息""" audio_params = msg_json.get("audio_params") if audio_params: format = audio_params.get("format") - conn.logger.bind(tag=TAG).info(f"Client audio format: {format}") + conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}") conn.audio_format = format conn.welcome_msg["audio_params"] = audio_params features = msg_json.get("features") if features: - conn.logger.bind(tag=TAG).info(f"Client features: {features}") + conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") conn.features = features if features.get("mcp"): - conn.logger.bind(tag=TAG).info("Client supports MCP") + conn.logger.bind(tag=TAG).info("客户端支持MCP") conn.mcp_client = MCPClient() - # Send initialization + # 发送初始化 asyncio.create_task(send_mcp_initialize_message(conn)) - # Send mcp message to get tools list + # 发送mcp消息,获取tools列表 asyncio.create_task(send_mcp_tools_list_request(conn)) await conn.websocket.send(json.dumps(conn.welcome_msg)) @@ -56,7 +66,7 @@ async def checkWakeupWords(conn, text): "enable_wakeup_words_response_cache" ] - # Wait for tts to initialize, wait up to 3 seconds + # 等待tts初始化,最多等待3秒 start_time = time.time() while time.time() - start_time < 3: if conn.tts: @@ -73,36 +83,36 @@ async def checkWakeupWords(conn, text): return False conn.just_woken_up = True - await send_stt_message(conn, text) + await send_tts_message(conn, "start") - # Get the current timbre + # 获取当前音色 voice = getattr(conn.tts, "voice", "default") if not voice: voice = "default" - # Get the wake-up word reply configuration + # 获取唤醒词回复配置 response = wakeup_words_config.get_wakeup_response(voice) if not response or not response.get("file_path"): response = { "voice": "default", - "file_path": "config/assets/wakeup_words.wav", + "file_path": "config/assets/wakeup_words_short.wav", "time": 0, - "text": "Hello, I'm Xiaozhi, a Taiwanese girl with a nice voice. I'm so happy to meet you. What are you busy with recently? Don't forget to give me some interesting information. I love to hear gossip." + "text": "我在这里哦!", } - # Get audio data + # 获取音频数据 opus_packets = audio_to_data(response.get("file_path")) - # Play wake-up word reply + # 播放唤醒词回复 conn.client_abort = False - conn.logger.bind(tag=TAG).info(f"Play wake-up word reply: {response.get('text')}") + conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}") await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text")) await sendAudioMessage(conn, SentenceType.LAST, [], None) - # Additional dialogue + # 补充对话 conn.dialogue.put(Message(role="assistant", content=response.get("text"))) - # Check if the wakeup word reply needs to be updated + # 检查是否需要更新唤醒词回复 if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: if not _wakeup_response_lock.locked(): asyncio.create_task(wakeupWordsResponse(conn)) @@ -110,42 +120,34 @@ async def checkWakeupWords(conn, text): async def wakeupWordsResponse(conn): - if not conn.tts or not conn.llm or not conn.llm.response_no_stream: + if not conn.tts: return try: - # Try to acquire the lock, and return if it cannot be acquired + # 尝试获取锁,如果获取不到就返回 if not await _wakeup_response_lock.acquire(): return - # Generate wake-up word response - wakeup_word = random.choice(WAKEUP_CONFIG["words"]) - question = ( - "The user is talking to you at this moment" - + wakeup_word - + "```.\nPlease write a 20-30 word reply based on the above user's content. Please be consistent with the character's emotions and attitude set by the system, and do not speak like a robot.\n" - + "Please do not provide any explanation or response to this content. Do not return emoticons. Only return replies to the user's content." - ) - - result = conn.llm.response_no_stream(conn.config["prompt"], question) + # 从预定义回复列表中随机选择一个回复 + result = random.choice(WAKEUP_CONFIG["responses"]) if not result or len(result) == 0: return - # Generate TTS audio + # 生成TTS音频 tts_result = await asyncio.to_thread(conn.tts.to_tts, result) if not tts_result: return - # Get the current timbre + # 获取当前音色 voice = getattr(conn.tts, "voice", "default") wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000) file_path = wakeup_words_config.generate_file_path(voice) with open(file_path, "wb") as f: f.write(wav_bytes) - # Update configuration + # 更新配置 wakeup_words_config.update_wakeup_response(voice, file_path, result) finally: - # Make sure the lock is released in any case + # 确保在任何情况下都释放锁 if _wakeup_response_lock.locked(): - _wakeup_response_lock.release() \ No newline at end of file + _wakeup_response_lock.release() diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 750b1c207..23b2d0aa1 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -13,45 +13,45 @@ TAG = __name__ async def handle_user_intent(conn, text): - # Preprocess the input text to handle possible JSON format + # 预处理输入文本,处理可能的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"] # Extract content for intent analysis - conn.current_speaker = parsed_data.get("speaker") # Keep speaker information + text = parsed_data["content"] # 提取content用于意图分析 + conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息 except (json.JSONDecodeError, TypeError): pass - # Check if there is an explicit exit command + # 检查是否有明确的退出命令 _, filtered_text = remove_punctuation_and_length(text) if await check_direct_exit(conn, filtered_text): return True - # Check if it is a wake-up word + # 检查是否是唤醒词 if await checkWakeupWords(conn, filtered_text): return True if conn.intent_type == "function_call": - # Use chat methods that support function calling and no longer perform intent analysis + # 使用支持function calling的聊天方法,不再进行意图分析 return False - # Use LLM for intent analysis + # 使用LLM进行意图分析 intent_result = await analyze_intent_with_llm(conn, text) if not intent_result: return False - # Generate sentence_id when the session starts + # 会话开始时生成sentence_id conn.sentence_id = str(uuid.uuid4().hex) - # Handling various intents + # 处理各种意图 return await process_intent_result(conn, intent_result, text) async def check_direct_exit(conn, text): - """Check if there is an explicit exit command""" + """检查是否有明确的退出命令""" _, text = remove_punctuation_and_length(text) cmd_exit = conn.cmd_exit for cmd in cmd_exit: if text == cmd: - conn.logger.bind(tag=TAG).info(f"A clear exit command was recognized: {text}") + conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}") await send_stt_message(conn, text) await conn.close() return True @@ -59,33 +59,33 @@ async def check_direct_exit(conn, text): async def analyze_intent_with_llm(conn, text): - """Using LLM to analyze user intent""" + """使用LLM分析用户意图""" if not hasattr(conn, "intent") or not conn.intent: - conn.logger.bind(tag=TAG).warning("Intent recognition service is not initialized") + conn.logger.bind(tag=TAG).warning("意图识别服务未初始化") return None - # Conversation History + # 对话历史记录 dialogue = conn.dialogue try: intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text) return intent_result except Exception as e: - conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}") + conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}") return None async def process_intent_result(conn, intent_result, original_text): - """Process intent recognition results""" + """处理意图识别结果""" try: - # Try to parse the result as JSON + # 尝试将结果解析为JSON intent_data = json.loads(intent_result) - # Check if there is function_call + # 检查是否有function_call if "function_call" in intent_data: - # Get function_call directly from intent recognition + # 直接从意图识别获取了function_call conn.logger.bind(tag=TAG).debug( - f"Detected intent result in function_call format: {intent_data['function_call']['name']}" + f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}" ) function_name = intent_data["function_call"]["name"] if function_name == "continue_chat": @@ -102,12 +102,12 @@ async def process_intent_result(conn, intent_result, original_text): current_time, today_date, today_weekday, lunar_date = get_current_time_info() - # Build a basic prompt with context - context_prompt = f"""Current time: {current_time} - Today's date: {today_date} ({today_weekday}) - Today's lunar calendar: {lunar_date} + # 构建带上下文的基础提示 + context_prompt = f"""当前时间:{current_time} + 今天日期:{today_date} ({today_weekday}) + 今天农历:{lunar_date} - Please answer the user's question based on the above information: {original_text}""" + 请根据以上信息回答用户的问题:{original_text}""" response = conn.intent.replyResult(context_prompt, original_text) speak_txt(conn, response) @@ -120,7 +120,7 @@ async def process_intent_result(conn, intent_result, original_text): function_args = intent_data["function_call"]["arguments"] if function_args is None: function_args = {} - # Ensure the parameter is a JSON string + # 确保参数是字符串格式的JSON if isinstance(function_args, dict): function_args = json.dumps(function_args) @@ -133,11 +133,11 @@ async def process_intent_result(conn, intent_result, original_text): await send_stt_message(conn, original_text) conn.client_abort = False - # Use executor to execute function calls and result processing + # 使用executor执行函数调用和结果处理 def process_function_call(): conn.dialogue.put(Message(role="user", content=original_text)) - # Use a unified tool handler to handle all tool calls + # 使用统一工具处理器处理所有工具调用 try: result = asyncio.run_coroutine_threadsafe( conn.func_handler.handle_llm_function_call( @@ -146,17 +146,17 @@ async def process_intent_result(conn, intent_result, original_text): conn.loop, ).result() except Exception as e: - conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}") + conn.logger.bind(tag=TAG).error(f"工具调用失败: {e}") result = ActionResponse( action=Action.ERROR, result=str(e), response=str(e) ) if result: - if result.action == Action.RESPONSE: # Reply directly to the front end + if result.action == Action.RESPONSE: # 直接回复前端 text = result.response if text is not None: speak_txt(conn, text) - elif result.action == Action.REQLLM: # After calling the function, request llm to generate a reply + elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 text = result.result conn.dialogue.put(Message(role="tool", content=text)) llm_result = conn.intent.replyResult(text, original_text) @@ -172,19 +172,19 @@ async def process_intent_result(conn, intent_result, original_text): speak_txt(conn, text) elif function_name != "play_music": # For backward compatibility with original code - # Get the latest text index + # 获取当前最新的文本索引 text = result.response if text is None: text = result.result if text is not None: speak_txt(conn, text) - # Put function execution in the thread pool + # 将函数执行放在线程池中 conn.executor.submit(process_function_call) return True return False except json.JSONDecodeError as e: - conn.logger.bind(tag=TAG).error(f"Error processing intent result: {e}") + conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}") return False @@ -204,4 +204,4 @@ def speak_txt(conn, text): content_type=ContentType.ACTION, ) ) - conn.dialogue.put(Message(role="assistant", content=text)) \ No newline at end of file + conn.dialogue.put(Message(role="assistant", content=text)) diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index a647d6d26..e7b6a1381 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -11,52 +11,53 @@ TAG = __name__ async def handleAudioMessage(conn, audio): - # Is there anyone speaking in the current segment? + # 当前片段是否有人说话 have_voice = conn.vad.is_vad(conn, audio) - # If the device has just been woken up, temporarily ignore VAD detection - if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up: + # 如果设备刚刚被唤醒,短暂忽略VAD检测 + if hasattr(conn, "just_woken_up") and conn.just_woken_up: have_voice = False - # Set a short delay before resuming VAD detection + # 设置一个短暂延迟后恢复VAD检测 conn.asr_audio.clear() if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) return + # manual 模式下不打断正在播放的内容 if have_voice: - if conn.client_is_speaking: + if conn.client_is_speaking and conn.client_listen_mode != "manual": await handleAbortMessage(conn) - # Device long-term idle detection, used to say goodbye + # 设备长时间空闲检测,用于say goodbye await no_voice_close_connect(conn, have_voice) - # Receive audio + # 接收音频 await conn.asr.receive_audio(conn, audio, have_voice) async def resume_vad_detection(conn): - # Resume VAD detection after waiting 2 seconds + # 等待2秒后恢复VAD检测 await asyncio.sleep(1) conn.just_woken_up = False async def startToChat(conn, text): - # Check if the input is in JSON format (including speaker information) + # 检查输入是否是JSON格式(包含说话人信息) speaker_name = None actual_text = text try: - # Try to parse JSON formatted input + # 尝试解析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"Parsed speaker information: {speaker_name}") + conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}") - # Use JSON format text directly without parsing + # 直接使用JSON格式的文本,不解析 actual_text = text except (json.JSONDecodeError, KeyError): - # If parsing fails, continue using the original text + # 如果解析失败,继续使用原始文本 pass - # Save speaker information to the connection object + # 保存说话人信息到连接对象 if speaker_name: conn.current_speaker = speaker_name else: @@ -66,24 +67,25 @@ async def startToChat(conn, text): await check_bind_device(conn) return - # If the number of words output on that day is greater than the limit + # 如果当日的输出字数大于限定的字数 if conn.max_output_size > 0: if check_device_output_limit( conn.headers.get("device-id"), conn.max_output_size ): await max_out_size(conn) return - if conn.client_is_speaking: + # manual 模式下不打断正在播放的内容 + if conn.client_is_speaking and conn.client_listen_mode != "manual": await handleAbortMessage(conn) - # First perform intent analysis, using the actual text content + # 首先进行意图分析,使用实际文本内容 intent_handled = await handle_user_intent(conn, actual_text) if intent_handled: - # If the intent has been handled, no longer chat + # 如果意图已被处理,不再进行聊天 return - # The intent is not handled, continue the normal chat process, use the actual text content + # 意图未被处理,继续常规聊天流程,使用实际文本内容 await send_stt_message(conn, actual_text) conn.executor.submit(conn.chat, actual_text) @@ -92,7 +94,7 @@ async def no_voice_close_connect(conn, have_voice): if have_voice: conn.last_activity_time = time.time() * 1000 return - # Only perform timeout check if timestamp has been initialized + # 只有在已经初始化过时间戳的情况下才进行超时检查 if conn.last_activity_time > 0.0: no_voice_time = time.time() * 1000 - conn.last_activity_time close_connection_no_voice_time = int( @@ -106,19 +108,19 @@ async def no_voice_close_connect(conn, have_voice): conn.client_abort = False end_prompt = conn.config.get("end_prompt", {}) if end_prompt and end_prompt.get("enable", True) is False: - conn.logger.bind(tag=TAG).info("End the conversation, no need to send an end prompt") + conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语") await conn.close() return prompt = end_prompt.get("prompt") if not prompt: - prompt = "Please end this conversation with a sentimental, nostalgic remark: 'Time flies!'" + prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!" await startToChat(conn, prompt) async def max_out_size(conn): - # Play the prompt that the maximum output word count has been exceeded + # 播放超出最大输出字数的提示 conn.client_abort = False - text = "Sorry, I'm busy right now. Let's talk again tomorrow at this time. Okay! See you tomorrow. Bye!" + text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!" await send_stt_message(conn, text) file_path = "config/assets/max_output_size.wav" opus_packets = audio_to_data(file_path) @@ -128,37 +130,37 @@ async def max_out_size(conn): async def check_bind_device(conn): if conn.bind_code: - # Make sure bind_code is 6 digits + # 确保bind_code是6位数字 if len(conn.bind_code) != 6: - conn.logger.bind(tag=TAG).error(f"Invalid binding code format: {conn.bind_code}") - text = "The binding code format is incorrect. Please check the configuration." + conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}") + text = "绑定码格式错误,请检查配置。" await send_stt_message(conn, text) return - text = f"Please log in to the control panel and enter {conn.bind_code} to bind the device." + text = f"请登录控制面板,输入{conn.bind_code},绑定设备。" await send_stt_message(conn, text) - # Play prompt tone + # 播放提示音 music_path = "config/assets/bind_code.wav" opus_packets = audio_to_data(music_path) conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text)) - # Play numbers one by one - for i in range(6): # Ensure only 6 digits are played + # 逐个播放数字 + for i in range(6): # 确保只播放6位数字 try: digit = conn.bind_code[i] num_path = f"config/assets/bind_code/{digit}.wav" num_packets = audio_to_data(num_path) conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None)) except Exception as e: - conn.logger.bind(tag=TAG).error(f"Failed to play digital audio: {e}") + conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}") continue conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None)) else: - # Play unbound prompt + # 播放未绑定提示 conn.client_abort = False - text = f"The version information of this device was not found. Please configure the OTA address correctly and then recompile the firmware." + text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。" 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)) \ No newline at end of file + conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py index 129e1864f..7b30f79c0 100644 --- a/main/xiaozhi-server/core/handle/reportHandle.py +++ b/main/xiaozhi-server/core/handle/reportHandle.py @@ -1,12 +1,12 @@ """ -The TTS reporting function has been integrated into the ConnectionHandler class. +TTS上报功能已集成到ConnectionHandler类中。 -Reporting functions include: -1. Each connection object has its own reporting queue and processing thread -2. The life cycle of the reporting thread is bound to the connection object -3. Use the ConnectionHandler.enqueue_tts_report method to report +上报功能包括: +1. 每个连接对象拥有自己的上报队列和处理线程 +2. 上报线程的生命周期与连接对象绑定 +3. 使用ConnectionHandler.enqueue_tts_report方法进行上报 -For specific implementation, please refer to the relevant code in core/connection.py. +具体实现请参考core/connection.py中的相关代码。 """ import time @@ -19,21 +19,21 @@ TAG = __name__ def report(conn, type, text, opus_data, report_time): - """Execute chat record reporting operation + """执行聊天记录上报操作 Args: - conn: connection object - type: reporting type, 1 is user, 2 is agent - text: synthetic text - opus_data: opus audio data - report_time: reporting time + conn: 连接对象 + type: 上报类型,1为用户,2为智能体 + text: 合成文本 + opus_data: opus音频数据 + report_time: 上报时间 """ try: if opus_data: audio_data = opus_to_wav(conn, opus_data) else: audio_data = None - # Execution report + # 执行上报 manage_report( mac_address=conn.device_id, session_id=conn.session_id, @@ -43,20 +43,20 @@ def report(conn, type, text, opus_data, report_time): report_time=report_time, ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"Chat record reporting failed: {e}") + conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}") def opus_to_wav(conn, opus_data): - """Convert Opus data into a byte stream in WAV format + """将Opus数据转换为WAV格式的字节流 Args: - output_dir: output directory (retain parameters to maintain interface compatibility) - opus_data: opus audio data + output_dir: 输出目录(保留参数以保持接口兼容) + opus_data: opus音频数据 Returns: - bytes: audio data in WAV format + bytes: WAV格式的音频数据 """ - decoder = opuslib_next.Decoder(16000, 1) # 16kHz, mono + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 pcm_data = [] for opus_packet in opus_data: @@ -64,16 +64,16 @@ def opus_to_wav(conn, opus_data): pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms pcm_data.append(pcm_frame) except opuslib_next.OpusError as e: - conn.logger.bind(tag=TAG).error(f"Opus decoding error: {e}", exc_info=True) + conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) if not pcm_data: - raise ValueError("No valid PCM data") + raise ValueError("没有有效的PCM数据") - # Create a WAV file header + # 创建WAV文件头 pcm_data_bytes = b"".join(pcm_data) num_samples = len(pcm_data_bytes) // 2 # 16-bit samples - # WAV file header + # WAV文件头 wav_header = bytearray() wav_header.extend(b"RIFF") # ChunkID wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize @@ -89,7 +89,7 @@ def opus_to_wav(conn, opus_data): wav_header.extend(b"data") # Subchunk2ID wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size - # Return complete WAV data + # 返回完整的WAV数据 return bytes(wav_header) + pcm_data_bytes @@ -98,27 +98,27 @@ def enqueue_tts_report(conn, text, opus_data): return if conn.chat_history_conf == 0: return - """Add TTS data to the reporting queue + """将TTS数据加入上报队列 Args: - conn: connection object - text: synthetic text - opus_data: opus audio data + conn: 连接对象 + text: 合成文本 + opus_data: opus音频数据 """ try: - # Use the connection object's queue to pass in text and binary data instead of file paths + # 使用连接对象的队列,传入文本和二进制数据而非文件路径 if conn.chat_history_conf == 2: conn.report_queue.put((2, text, opus_data, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"TTS data has been added to the reporting queue: {conn.device_id}, audio size: {len(opus_data)}" + f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " ) else: conn.report_queue.put((2, text, None, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"TTS data has been added to the reporting queue: {conn.device_id}, no audio is reported" + f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频" ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"Failed to join TTS reporting queue: {text}, {e}") + conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}") def enqueue_asr_report(conn, text, opus_data): @@ -126,24 +126,24 @@ def enqueue_asr_report(conn, text, opus_data): return if conn.chat_history_conf == 0: return - """Add ASR data to the reporting queue + """将ASR数据加入上报队列 Args: - conn: connection object - text: synthetic text - opus_data: opus audio data + conn: 连接对象 + text: 合成文本 + opus_data: opus音频数据 """ try: - # Use the connection object's queue to pass in text and binary data instead of file paths + # 使用连接对象的队列,传入文本和二进制数据而非文件路径 if conn.chat_history_conf == 2: conn.report_queue.put((1, text, opus_data, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"ASR data has been added to the reporting queue: {conn.device_id}, audio size: {len(opus_data)}" + f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " ) else: conn.report_queue.put((1, text, None, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"ASR data has been added to the reporting queue: {conn.device_id}, no audio is reported" + f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频" ) except Exception as e: - conn.logger.bind(tag=TAG).debug(f"Failed to join the ASR reporting queue: {text}, {e}") \ No newline at end of file + conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}") diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index db2e4430f..8beda5771 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -10,7 +10,7 @@ TAG = __name__ async def sendAudioMessage(conn, sentenceType, audios, text): if conn.tts.tts_audio_first_sentence: - conn.logger.bind(tag=TAG).info(f"Send the first voice: {text}") + conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}") conn.tts.tts_audio_first_sentence = False await send_tts_message(conn, "start", None) @@ -18,11 +18,11 @@ async def sendAudioMessage(conn, sentenceType, audios, text): await send_tts_message(conn, "sentence_start", text) await sendAudio(conn, audios) - # Send sentence start message + # 发送句子开始消息 if sentenceType is not SentenceType.MIDDLE: - conn.logger.bind(tag=TAG).info(f"Send audio message: {sentenceType}, {text}") + conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") - # Send end message (if it is the last text) + # 发送结束消息(如果是最后一个文本) if conn.llm_finish_task and sentenceType == SentenceType.LAST: await send_tts_message(conn, "stop", None) conn.client_is_speaking = False @@ -32,60 +32,60 @@ async def sendAudioMessage(conn, sentenceType, audios, text): def calculate_timestamp_and_sequence(conn, start_time, packet_index, frame_duration=60): """ - Calculate timestamps and sequence numbers for audio packets + 计算音频数据包的时间戳和序列号 Args: - conn: connection object - start_time: start time (performance counter value) - packet_index: packet index - frame_duration: frame duration (milliseconds), matching Opus encoding + conn: 连接对象 + start_time: 起始时间(性能计数器值) + packet_index: 数据包索引 + frame_duration: 帧时长(毫秒),匹配 Opus 编码 Returns: tuple: (timestamp, sequence) """ - # Calculate timestamp (using playback position) + # 计算时间戳(使用播放位置计算) timestamp = int((start_time + packet_index * frame_duration / 1000) * 1000) % ( 2**32 ) - # Calculate the sequence number + # 计算序列号 if hasattr(conn, "audio_flow_control"): sequence = conn.audio_flow_control["sequence"] else: - sequence = packet_index # If there is no flow control status, use the index directly + sequence = packet_index # 如果没有流控状态,直接使用索引 return timestamp, sequence async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence): """ - Send an opus data packet with a 16-byte header to mqtt_gateway + 发送带16字节头部的opus数据包给mqtt_gateway Args: - conn: connection object - opus_packet: opus data packet - timestamp: timestamp - sequence: sequence number + conn: 连接对象 + opus_packet: opus数据包 + timestamp: 时间戳 + sequence: 序列号 """ - # Add a 16-byte header to the opus data packet + # 为opus数据包添加16字节头部 header = bytearray(16) header[0] = 1 # type header[2:4] = len(opus_packet).to_bytes(2, "big") # payload length header[4:8] = sequence.to_bytes(4, "big") # sequence - header[8:12] = timestamp.to_bytes(4, "big") # Timestamp + header[8:12] = timestamp.to_bytes(4, "big") # 时间戳 header[12:16] = len(opus_packet).to_bytes(4, "big") # opus长度 - # Send a complete packet including the header + # 发送包含头部的完整数据包 complete_packet = bytes(header) + opus_packet await conn.websocket.send(complete_packet) -# Play Audio +# 播放音频 async def sendAudio(conn, audios, frame_duration=60): """ - Send a single opus packet, support flow control + 发送单个opus包,支持流控 Args: - conn: connection object - opus_packet: single opus data packet - pre_buffer: Send audio quickly - frame_duration: frame duration (milliseconds), matching Opus encoding + conn: 连接对象 + opus_packet: 单个opus数据包 + pre_buffer: 快速发送音频 + frame_duration: 帧时长(毫秒),匹配 Opus 编码 """ if audios is None or len(audios) == 0: return @@ -96,18 +96,18 @@ async def sendAudio(conn, audios, frame_duration=60): conn.last_activity_time = time.time() * 1000 - # Get or initialize flow control status + # 获取或初始化流控状态 if not hasattr(conn, "audio_flow_control"): conn.audio_flow_control = { "last_send_time": 0, "packet_count": 0, "start_time": time.perf_counter(), - "sequence": 0, # add sequence number + "sequence": 0, # 添加序列号 } flow_control = conn.audio_flow_control current_time = time.perf_counter() - # Calculate expected sending time + # 计算预期发送时间 expected_time = flow_control["start_time"] + ( flow_control["packet_count"] * frame_duration / 1000 ) @@ -115,56 +115,56 @@ async def sendAudio(conn, audios, frame_duration=60): if delay > 0: await asyncio.sleep(delay) else: - # Correct the error + # 纠正误差 flow_control["start_time"] += abs(delay) if conn.conn_from_mqtt_gateway: - # Calculate timestamp and sequence number + # 计算时间戳和序列号 timestamp, sequence = calculate_timestamp_and_sequence( conn, flow_control["start_time"], flow_control["packet_count"], frame_duration, ) - # Call the general function to send the data packet with the header + # 调用通用函数发送带头部的数据包 await _send_to_mqtt_gateway(conn, audios, timestamp, sequence) else: - # Send opus data packets directly without adding headers + # 直接发送opus数据包,不添加头部 await conn.websocket.send(audios) - # Update flow control status + # 更新流控状态 flow_control["packet_count"] += 1 flow_control["sequence"] += 1 flow_control["last_send_time"] = time.perf_counter() else: - # File-type audio plays normally + # 文件型音频走普通播放 start_time = time.perf_counter() play_position = 0 - # Perform pre-buffering + # 执行预缓冲 pre_buffer_frames = min(3, len(audios)) for i in range(pre_buffer_frames): if conn.conn_from_mqtt_gateway: - # Calculate timestamp and sequence number + # 计算时间戳和序列号 timestamp, sequence = calculate_timestamp_and_sequence( conn, start_time, i, frame_duration ) - # Call the general function to send the data packet with the header + # 调用通用函数发送带头部的数据包 await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence) else: - # Send the pre-buffered packet directly without adding a header + # 直接发送预缓冲包,不添加头部 await conn.websocket.send(audios[i]) remaining_audios = audios[pre_buffer_frames:] - # Play the remaining audio frames + # 播放剩余音频帧 for i, opus_packet in enumerate(remaining_audios): if conn.client_abort: break - # Reset the no sound state + # 重置没有声音的状态 conn.last_activity_time = time.time() * 1000 - # Calculate expected sending time + # 计算预期发送时间 expected_time = start_time + (play_position / 1000) current_time = time.perf_counter() delay = expected_time - current_time @@ -172,31 +172,31 @@ async def sendAudio(conn, audios, frame_duration=60): await asyncio.sleep(delay) if conn.conn_from_mqtt_gateway: - # Calculate timestamp and sequence number (use current packet index to ensure continuity) + # 计算时间戳和序列号(使用当前的数据包索引确保连续性) packet_index = pre_buffer_frames + i timestamp, sequence = calculate_timestamp_and_sequence( conn, start_time, packet_index, frame_duration ) - # Call the general function to send the data packet with the header + # 调用通用函数发送带头部的数据包 await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence) else: - # Send opus data packets directly without adding headers + # 直接发送opus数据包,不添加头部 await conn.websocket.send(opus_packet) play_position += frame_duration async def send_tts_message(conn, state, text=None): - """Send TTS status message""" + """发送 TTS 状态消息""" if text is None and state == "sentence_start": return message = {"type": "tts", "state": state, "session_id": conn.session_id} if text is not None: message["text"] = textUtils.check_emoji(text) - # End of TTS playback + # TTS播放结束 if state == "stop": - # Play prompt tone + # 播放提示音 tts_notify = conn.config.get("enable_stop_tts_notify", False) if tts_notify: stop_tts_notify_voice = conn.config.get( @@ -204,38 +204,38 @@ async def send_tts_message(conn, state, text=None): ) audios = audio_to_data(stop_tts_notify_voice, is_opus=True) await sendAudio(conn, audios) - # Clear the server's speech status + # 清除服务端讲话状态 conn.clearSpeakStatus() - # Send message to client + # 发送消息到客户端 await conn.websocket.send(json.dumps(message)) async def send_stt_message(conn, text): - """Send STT status message""" + """发送 STT 状态消息""" end_prompt_str = conn.config.get("end_prompt", {}).get("prompt") if end_prompt_str and end_prompt_str == text: await send_tts_message(conn, "start") return - # Parse the JSON format and extract the actual user speech content + # 解析JSON格式,提取实际的用户说话内容 display_text = text try: - # Try to parse JSON format + # 尝试解析JSON格式 if text.strip().startswith("{") and text.strip().endswith("}"): parsed_data = json.loads(text) if isinstance(parsed_data, dict) and "content" in parsed_data: - # If the JSON format contains speaker information, only the content part is displayed + # 如果是包含说话人信息的JSON格式,只显示content部分 display_text = parsed_data["content"] - # Save speaker information to conn object + # 保存说话人信息到conn对象 if "speaker" in parsed_data: conn.current_speaker = parsed_data["speaker"] except (json.JSONDecodeError, TypeError): - # If it is not in JSON format, use the original text directly + # 如果不是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") \ No newline at end of file + await send_tts_message(conn, "start") diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index 973305995..b5e877834 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -3,12 +3,12 @@ from core.handle.textMessageProcessor import TextMessageProcessor TAG = __name__ -# Global Processor Registry +# 全局处理器注册表 message_registry = TextMessageHandlerRegistry() -# Create a global message handler instance +# 创建全局消息处理器实例 message_processor = TextMessageProcessor(message_registry) async def handleTextMessage(conn, message): - """Process text messages""" + """处理文本消息""" await message_processor.process_message(conn, message) diff --git a/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py index d886a89d7..dc540d24a 100644 --- a/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py @@ -6,7 +6,7 @@ from core.handle.textMessageType import TextMessageType class AbortTextMessageHandler(TextMessageHandler): - """Abort message handler""" + """Abort消息处理器""" @property def message_type(self) -> TextMessageType: diff --git a/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py index 28721cb67..1839814e6 100644 --- a/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py @@ -6,7 +6,7 @@ from core.handle.textMessageType import TextMessageType class HelloTextMessageHandler(TextMessageHandler): - """Hello message handler""" + """Hello消息处理器""" @property def message_type(self) -> TextMessageType: diff --git a/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py index f94bd55e0..335d08b0f 100644 --- a/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py @@ -7,7 +7,7 @@ from core.providers.tools.device_iot import handleIotStatus, handleIotDescriptor class IotTextMessageHandler(TextMessageHandler): - """IoT message processor""" + """IOT消息处理器""" @property def message_type(self) -> TextMessageType: diff --git a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py index fd9a02096..97286dfe0 100644 --- a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py @@ -11,17 +11,17 @@ from core.utils.util import remove_punctuation_and_length TAG = __name__ class ListenTextMessageHandler(TextMessageHandler): - """Listen message processor""" + """Listen消息处理器""" @property def message_type(self) -> TextMessageType: - return TextMessageType.LIST + return TextMessageType.LISTEN async def handle(self, conn, msg_json: Dict[str, Any]) -> None: if "mode" in msg_json: conn.client_listen_mode = msg_json["mode"] conn.logger.bind(tag=TAG).debug( - f"Client pickup mode: {conn.client_listen_mode}" + f"客户端拾音模式:{conn.client_listen_mode}" ) if msg_json["state"] == "start": conn.client_have_voice = True @@ -36,28 +36,28 @@ class ListenTextMessageHandler(TextMessageHandler): conn.asr_audio.clear() if "text" in msg_json: conn.last_activity_time = time.time() * 1000 - original_text = msg_json["text"] # Keep the original text + original_text = msg_json["text"] # 保留原始文本 filtered_len, filtered_text = remove_punctuation_and_length( original_text ) - # Identify whether it is a wake-up word + # 识别是否是唤醒词 is_wakeup_words = filtered_text in conn.config.get("wakeup_words") - # Whether to enable wake-up word reply + # 是否开启唤醒词回复 enable_greeting = conn.config.get("enable_greeting", True) if is_wakeup_words and not enable_greeting: - # If it is a wake-up word and the wake-up word reply is turned off, there is no need to answer + # 如果是唤醒词,且关闭了唤醒词回复,就不用回答 await send_stt_message(conn, original_text) await send_tts_message(conn, "stop", None) conn.client_is_speaking = False elif is_wakeup_words: conn.just_woken_up = True - # Report pure text data (reuse ASR reporting function, but do not provide audio data) - enqueue_asr_report(conn, "Hey, hello", []) - await startToChat(conn, "Hey, hello") + # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) + enqueue_asr_report(conn, "嘿,你好呀", []) + await startToChat(conn, "嘿,你好呀") else: - # Report pure text data (reuse ASR reporting function, but do not provide audio data) + # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) enqueue_asr_report(conn, original_text, []) - # Otherwise, LLM needs to respond to the text content + # 否则需要LLM对文字内容进行答复 await startToChat(conn, original_text) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py index 50da3a161..65876f24b 100644 --- a/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py @@ -7,7 +7,7 @@ from core.providers.tools.device_mcp import handle_mcp_message class McpTextMessageHandler(TextMessageHandler): - """Mcp message processor""" + """MCP消息处理器""" @property def message_type(self) -> TextMessageType: diff --git a/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py index f6a1a5cea..b9a235888 100644 --- a/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py @@ -9,42 +9,42 @@ from core.providers.tools.device_mcp import handle_mcp_message TAG = __name__ class ServerTextMessageHandler(TextMessageHandler): - """MCP message processor""" + """MCP消息处理器""" @property def message_type(self) -> TextMessageType: return TextMessageType.SERVER async def handle(self, conn, msg_json: Dict[str, Any]) -> None: - # If the configuration is read from the API, the secret needs to be verified + # 如果配置是从API读取的,则需要验证secret if not conn.read_config_from_api: return - # Get the secret of the post request + # 获取post请求的secret post_secret = msg_json.get("content", {}).get("secret", "") secret = conn.config["manager-api"].get("secret", "") - # If the secret does not match, return + # 如果secret不匹配,则返回 if post_secret != secret: await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": "Server key verification failed", + "message": "服务器密钥验证失败", } ) ) return - # Dynamically update configuration + # 动态更新配置 if msg_json["action"] == "update_config": try: - # Update the WebSocketServer configuration + # 更新WebSocketServer的配置 if not conn.server: await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": "Unable to get server instance", + "message": "无法获取服务器实例", "content": {"action": "update_config"}, } ) @@ -57,36 +57,36 @@ class ServerTextMessageHandler(TextMessageHandler): { "type": "server", "status": "error", - "message": "Failed to update server configuration", + "message": "更新服务器配置失败", "content": {"action": "update_config"}, } ) ) return - # Send successful response + # 发送成功响应 await conn.websocket.send( json.dumps( { "type": "server", "status": "success", - "message": "Configuration updated successfully", + "message": "配置更新成功", "content": {"action": "update_config"}, } ) ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"Update configuration failed: {str(e)}") + conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}") await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": f"Failed to update configuration: {str(e)}", + "message": f"更新配置失败: {str(e)}", "content": {"action": "update_config"}, } ) ) - # Restart the server + # 重启服务器 elif msg_json["action"] == "restart": await conn.handle_restart(msg_json) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/textMessageHandler.py b/main/xiaozhi-server/core/handle/textMessageHandler.py index 85c4d54e6..f94a0bac0 100644 --- a/main/xiaozhi-server/core/handle/textMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textMessageHandler.py @@ -7,15 +7,15 @@ TAG = __name__ class TextMessageHandler(ABC): - """Message processor abstract base class""" + """消息处理器抽象基类""" @abstractmethod async def handle(self, conn, msg_json: Dict[str, Any]) -> None: - """Abstract methods for processing messages""" + """处理消息的抽象方法""" pass @property @abstractmethod def message_type(self) -> TextMessageType: - """Returns the message type processed""" + """返回处理的消息类型""" pass diff --git a/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py b/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py index cd19aac22..e90d72310 100644 --- a/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py +++ b/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py @@ -12,14 +12,14 @@ TAG = __name__ class TextMessageHandlerRegistry: - """Message Processor Registry""" + """消息处理器注册表""" def __init__(self): self._handlers: Dict[str, TextMessageHandler] = {} self._register_default_handlers() def _register_default_handlers(self) -> None: - """Register the default message handler""" + """注册默认的消息处理器""" handlers = [ HelloTextMessageHandler(), AbortTextMessageHandler(), @@ -33,13 +33,13 @@ class TextMessageHandlerRegistry: self.register_handler(handler) def register_handler(self, handler: TextMessageHandler) -> None: - """Register message handler""" + """注册消息处理器""" self._handlers[handler.message_type.value] = handler def get_handler(self, message_type: str) -> Optional[TextMessageHandler]: - """Get the message handler""" + """获取消息处理器""" return self._handlers.get(message_type) def get_supported_types(self) -> list: - """Get supported message types""" - return list(self._handlers.keys()) \ No newline at end of file + """获取支持的消息类型""" + return list(self._handlers.keys()) diff --git a/main/xiaozhi-server/core/handle/textMessageProcessor.py b/main/xiaozhi-server/core/handle/textMessageProcessor.py index b43e7659b..0cae5e099 100644 --- a/main/xiaozhi-server/core/handle/textMessageProcessor.py +++ b/main/xiaozhi-server/core/handle/textMessageProcessor.py @@ -6,36 +6,36 @@ TAG = __name__ class TextMessageProcessor: - """Message handler main class""" + """消息处理器主类""" def __init__(self, registry: TextMessageHandlerRegistry): self.registry = registry async def process_message(self, conn, message: str) -> None: - """The main entry point for processing messages""" + """处理消息的主入口""" try: - # Parsing JSON messages + # 解析JSON消息 msg_json = json.loads(message) - # Processing JSON messages + # 处理JSON消息 if isinstance(msg_json, dict): message_type = msg_json.get("type") - # Logging - conn.logger.bind(tag=TAG).info(f"Received {message_type} message: {message}") + # 记录日志 + conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}") - # Get and execute the processor + # 获取并执行处理器 handler = self.registry.get_handler(message_type) if handler: await handler.handle(conn, msg_json) else: - conn.logger.bind(tag=TAG).error(f"Received unknown type message: {message}") - # Processing pure numeric messages + conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") + # 处理纯数字消息 elif isinstance(msg_json, int): - conn.logger.bind(tag=TAG).info(f"Received digital message: {message}") + conn.logger.bind(tag=TAG).info(f"收到数字消息:{message}") await conn.websocket.send(message) except json.JSONDecodeError: - # Directly forward non-JSON messages - conn.logger.bind(tag=TAG).error(f"Parsed error message: {message}") - await conn.websocket.send(message) \ No newline at end of file + # 非JSON消息直接转发 + conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}") + await conn.websocket.send(message) diff --git a/main/xiaozhi-server/core/handle/textMessageType.py b/main/xiaozhi-server/core/handle/textMessageType.py index 8268737bf..53e71b711 100644 --- a/main/xiaozhi-server/core/handle/textMessageType.py +++ b/main/xiaozhi-server/core/handle/textMessageType.py @@ -2,7 +2,7 @@ from enum import Enum class TextMessageType(Enum): - """Message type enum""" + """消息类型枚举""" HELLO = "hello" ABORT = "abort" LISTEN = "listen" diff --git a/main/xiaozhi-server/core/http_server.py b/main/xiaozhi-server/core/http_server.py index 4650851de..edbdf1fee 100644 --- a/main/xiaozhi-server/core/http_server.py +++ b/main/xiaozhi-server/core/http_server.py @@ -15,14 +15,14 @@ class SimpleHttpServer: self.vision_handler = VisionHandler(config) def _get_websocket_url(self, local_ip: str, port: int) -> str: - """Get the websocket address + """获取websocket地址 Args: - local_ip: local IP address - port: port number + local_ip: 本地IP地址 + port: 端口号 Returns: - str: websocket address + str: websocket地址 """ server_config = self.config["server"] websocket_config = server_config.get("websocket") @@ -42,7 +42,7 @@ class SimpleHttpServer: app = web.Application() if not read_config_from_api: - # If the smart console is not enabled and only a single module is running, you need to add a simple OTA interface to send the websocket interface + # 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口 app.add_routes( [ web.get("/xiaozhi/ota/", self.ota_handler.handle_get), @@ -50,7 +50,7 @@ class SimpleHttpServer: web.options("/xiaozhi/ota/", self.ota_handler.handle_post), ] ) - # Add routes + # 添加路由 app.add_routes( [ web.get("/mcp/vision/explain", self.vision_handler.handle_get), @@ -59,12 +59,12 @@ class SimpleHttpServer: ] ) - # Run the service + # 运行服务 runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, host, port) await site.start() - # Keep the service running + # 保持服务运行 while True: - await asyncio.sleep(3600) # Check every 1 hour \ No newline at end of file + await asyncio.sleep(3600) # 每隔 1 小时检查一次 diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index d630bde27..c0c88fc57 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -1,8 +1,11 @@ import asyncio +import json + import websockets from config.logger import setup_logging from core.connection import ConnectionHandler from config.config_loader import get_config_from_api +from core.auth import AuthManager, AuthenticationError from core.utils.modules_initialize import initialize_modules from core.utils.util import check_vad_update, check_asr_update @@ -32,6 +35,14 @@ class WebSocketServer: self.active_connections = set() + auth_config = self.config["server"].get("auth", {}) + self.auth_enable = auth_config.get("enabled", False) + # 设备白名单 + self.allowed_devices = set(auth_config.get("allowed_devices", [])) + secret_key = self.config["server"]["auth_key"] + expire_seconds = auth_config.get("expire_seconds", None) + self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds) + async def start(self): server_config = self.config["server"] host = server_config.get("ip", "0.0.0.0") @@ -43,76 +54,109 @@ class WebSocketServer: await asyncio.Future() async def _handle_connection(self, websocket): - """Handle new connections, creating a separate ConnectionHandler each time""" - # Pass in the current server instance when creating a ConnectionHandler + headers = dict(websocket.request.headers) + if headers.get("device-id", None) is None: + # 尝试从 URL 的查询参数中获取 device-id + from urllib.parse import parse_qs, urlparse + + # 从 WebSocket 请求中获取路径 + request_path = websocket.request.path + if not request_path: + self.logger.bind(tag=TAG).error("无法获取请求路径") + await websocket.close() + return + parsed_url = urlparse(request_path) + query_params = parse_qs(parsed_url.query) + if "device-id" not in query_params: + await websocket.send("端口正常,如需测试连接,请使用test_page.html") + await websocket.close() + return + else: + websocket.request.headers["device-id"] = query_params["device-id"][0] + if "client-id" in query_params: + websocket.request.headers["client-id"] = query_params["client-id"][0] + if "authorization" in query_params: + websocket.request.headers["authorization"] = query_params[ + "authorization" + ][0] + + """处理新连接,每次创建独立的ConnectionHandler""" + # 先认证,后建立连接 + try: + await self._handle_auth(websocket) + except AuthenticationError: + await websocket.send("认证失败") + await websocket.close() + return + # 创建ConnectionHandler时传入当前server实例 handler = ConnectionHandler( self.config, - self._what, + self._vad, self._asr, self._llm, self._memory, self._intent, - self, # pass in server instance + self, # 传入server实例 ) self.active_connections.add(handler) try: await handler.handle_connection(websocket) except Exception as e: - self.logger.bind(tag=TAG).error(f"Error while processing connection: {e}") + self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}") finally: - # Make sure to remove from the set of active connections + # 确保从活动连接集合中移除 self.active_connections.discard(handler) - # Forcefully close the connection (if it hasn't already been closed) + # 强制关闭连接(如果还没有关闭的话) try: - # Safely check WebSocket status and close + # 安全地检查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: - # If there is no closed attribute, try to close it directly + # 如果没有closed属性,直接尝试关闭 await websocket.close() except Exception as close_error: self.logger.bind(tag=TAG).error( - f"Error when the server forcibly closed the connection: {close_error}" + f"服务器端强制关闭连接时出错: {close_error}" ) async def _http_response(self, websocket, request_headers): - # Check if it is a WebSocket upgrade request + # 检查是否为 WebSocket 升级请求 if request_headers.headers.get("connection", "").lower() == "upgrade": - # If it is a WebSocket request, return None to allow the handshake to continue + # 如果是 WebSocket 请求,返回 None 允许握手继续 return None else: - # If it is a normal HTTP request, return "server is running" + # 如果是普通 HTTP 请求,返回 "server is running" return websocket.respond(200, "Server is running\n") async def update_config(self) -> bool: - """Update server configuration and reinitialize components + """更新服务器配置并重新初始化组件 Returns: - bool: whether the update is successful + bool: 更新是否成功 """ try: async with self.config_lock: - # Re-obtain configuration + # 重新获取配置 new_config = get_config_from_api(self.config) if new_config is None: - self.logger.bind(tag=TAG).error("Failed to get new configuration") + self.logger.bind(tag=TAG).error("获取新配置失败") return False - self.logger.bind(tag=TAG).info(f"Get new configuration successfully") - # Check if VAD and ASR types need to be updated + self.logger.bind(tag=TAG).info(f"获取新配置成功") + # 检查 VAD 和 ASR 类型是否需要更新 update_vad = check_vad_update(self.config, new_config) update_asr = check_asr_update(self.config, new_config) self.logger.bind(tag=TAG).info( - f"Check if VAD and ASR types need to be updated: {update_vad} {update_asr}" + f"检查VAD和ASR类型是否需要更新: {update_vad} {update_asr}" ) - # Update configuration + # 更新配置 self.config = new_config - # Reinitialize components + # 重新初始化组件 modules = initialize_modules( self.logger, new_config, - update_what, + update_vad, update_asr, "LLM" in new_config["selected_module"], False, @@ -120,7 +164,7 @@ class WebSocketServer: "Intent" in new_config["selected_module"], ) - # Update component instance + # 更新组件实例 if "vad" in modules: self._vad = modules["vad"] if "asr" in modules: @@ -131,8 +175,31 @@ class WebSocketServer: self._intent = modules["intent"] if "memory" in modules: self._memory = modules["memory"] - self.logger.bind(tag=TAG).info(f"Update configuration task completed") + self.logger.bind(tag=TAG).info(f"更新配置任务执行完毕") return True except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to update server configuration: {str(e)}") - return False \ No newline at end of file + self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}") + return False + + async def _handle_auth(self, websocket): + # 先认证,后建立连接 + if self.auth_enable: + headers = dict(websocket.request.headers) + device_id = headers.get("device-id", None) + client_id = headers.get("client-id", None) + if self.allowed_devices and device_id in self.allowed_devices: + # 如果属于白名单内的设备,不校验token,直接放行 + return + else: + # 否则校验token + token = headers.get("authorization", "") + if token.startswith("Bearer "): + token = token[7:] # 移除'Bearer '前缀 + else: + raise AuthenticationError("Missing or invalid Authorization header") + # 进行认证 + auth_success = self.auth.verify_token( + token, client_id=client_id, username=device_id + ) + if not auth_success: + raise AuthenticationError("Invalid token")