From e86e1878de549663bbe5bd6c1f3be8ba2756675b Mon Sep 17 00:00:00 2001 From: Alireza Jahanshahlou Date: Thu, 16 Oct 2025 21:10:33 +0330 Subject: [PATCH] tranaslate tranaslate to en --- 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 | 64 +-- .../xiaozhi-server/core/api/vision_handler.py | 72 ++-- main/xiaozhi-server/core/auth.py | 18 +- main/xiaozhi-server/core/connection.py | 386 +++++++++--------- .../xiaozhi-server/core/handle/abortHandle.py | 4 +- .../xiaozhi-server/core/handle/helloHandle.py | 54 +-- .../core/handle/intentHandler.py | 70 ++-- .../core/handle/receiveAudioHandle.py | 64 +-- .../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 | 54 +-- 28 files changed, 639 insertions(+), 639 deletions(-) diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 4f35b1fdc..66f046e98 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): - """从Java API获取配置""" - # 初始化API客户端 + """Get configuration from Java API""" + # Initialize the API client 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", ""), } - # server的配置以本地为准 + # The server configuration is based on the local 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): - """从Java API获取私有配置""" + """Get private configuration from 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() # 获取项目根目录 - # 日志文件目录 + project_dir = get_project_dir() # Get the project root directory + # Log file directory log_dir = config.get("log", {}).get("log_dir", "tmp") dirs_to_create.add(os.path.join(project_dir, log_dir)) - # ASR/TTS模块输出目录 + # ASR/TTS module output directory 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) - # 根据selected_module创建模型目录 + # Create a model directory based on 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) - # 统一创建目录(保留原data目录创建) + # Create a unified directory (keep the original data directory creation) for dir_path in dirs_to_create: try: os.makedirs(dir_path, exist_ok=True) except PermissionError: - print(f"警告:无法创建目录 {dir_path},请检查写入权限") + print(f"Warning: Unable to create directory {dir_path}, please check write permissions") def merge_configs(default_config, custom_config): """ - 递归合并配置,custom_config优先级更高 + Recursively merge configurations, custom_config takes priority Args: - default_config: 默认配置 - custom_config: 用户自定义配置 + default_config: default configuration + custom_config: User-defined configuration 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 + return merged \ No newline at end of file diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py index a16b6d574..46de2dc1a 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): - """获取模块名称的缩写,如果为空则返回00 - 如果名称中包含下划线,则返回下划线后面的前两个字符 + """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. """ 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): - """为没有 tag 的日志添加默认值,并处理动态模块字符串""" + """Add default values ​​for logs without tags and handle dynamic module strings""" record["extra"].setdefault("tag", record["name"]) - # 如果没有设置 selected_module,使用默认值 + # If selected_module is not set, use the default value record["extra"].setdefault("selected_module", "00000000000000") - # 将 selected_module 从 extra 提取到顶级,以支持 {selected_module} 格式 + # Extract selected_module from extra to top level to support {selected_module} format 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", # 每个文件最大10MB - retention="30 days", # 保留30天 + rotation="10 MB", # Each file is up to 10MB + retention="30 days", # retain for 30 days compression=None, encoding="utf-8", - enqueue=True, # 异步安全 + enqueue=True, # Asynchronous safety backtrace=True, diagnose=True, ) - _logger_initialized = True # 标记为已初始化 + _logger_initialized = True # Mark as initialized return logger def create_connection_logger(selected_module_str): - """为连接创建独立的日志器,绑定特定的模块字符串""" - return logger.bind(selected_module=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 diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index cd3f86c42..907abf46c 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"设备绑定异常,绑定码: {bind_code}") + super().__init__(f"Device binding exception, binding code: {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配置错误") + raise Exception("manager-api configuration error") if not cls.config.get("url") or not cls.config.get("secret"): - raise Exception("manager-api的url或secret配置错误") + raise Exception("Manager-API URL or secret configuration error") if "你" in cls.config.get("secret"): - raise Exception("请先配置manager-api的secret") + raise Exception("Please configure the manager-api secret first") cls._secret = cls.config.get("secret") - 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.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._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), # 默认超时时间30秒 + timeout=cls.config.get("timeout", 30), # The default timeout is 30 seconds ) @classmethod def _request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """发送单次HTTP请求并处理响应""" + """Send a single HTTP request and handle the response""" endpoint = endpoint.lstrip("/") response = cls._client.request(method, endpoint, **kwargs) response.raise_for_status() result = response.json() - # 处理API返回的业务错误 + # Handle business errors returned by the 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返回错误: {result.get('msg', '未知错误')}") + raise Exception(f"API returned an error: {result.get('msg', 'Unknown error')}") - # 返回成功数据 + # 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状态码错误 + HTTP Status Code Error 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} 请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试" + f"{method} {endpoint} request failed, will be retried for {retry_count} times after {cls.retry_delay:.1f} seconds" ) 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"存储短期记忆到服务器失败: {e}") + print(f"Failed to store short-term memory to server: {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上报失败: {e}") + print(f"TTS report failed: {e}") return None @@ -190,4 +190,4 @@ def init_service(config): def manage_api_http_safe_close(): - ManageApiClient.safe_close() + ManageApiClient.safe_close() \ No newline at end of file diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index fb8868b40..e4589dc24 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( - "找不到data/.config.yaml文件,请按教程确认该配置文件是否存在" + "Cannot find the data/.config.yaml file. Please follow the tutorial to confirm whether the configuration file exists." ) - # 检查是否从API读取配置 + # Check if configuration is read from API config = load_config() if config.get("read_config_from_api", False): - print("从API读取配置") + print("Read configuration from API") old_config_origin = read_config(custom_config_file) if old_config_origin.get("selected_module") is not None: - error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n" - error_msg += "\n建议您:\n" - error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n" - error_msg += "2、按教程配置好接口地址和密钥\n" + 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" raise ValueError(error_msg) - config_file_valid = True + config_file_valid = True \ No newline at end of file diff --git a/main/xiaozhi-server/core/api/base_handler.py b/main/xiaozhi-server/core/api/base_handler.py index 7330185e4..c11dd2235 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): - """添加CORS头信息""" + """Add cors header information""" 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 b93a7ed34..44858e66e 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -15,54 +15,54 @@ class OTAHandler(BaseHandler): super().__init__(config) def generate_password_signature(self, content: str, secret_key: str) -> str: - """生成MQTT密码签名 + """Generate MQTT cryptographic signature Args: - content: 签名内容 (clientId + '|' + username) - secret_key: 密钥 + content: Signature content (clientId + '|' + username) + secret_key: key Returns: - str: Base64编码的HMAC-SHA256签名 + str: Base64 encoded hmac sh a256 signature """ try: 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') except Exception as e: - self.logger.bind(tag=TAG).error(f"生成MQTT密码签名失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to generate mqtt password signature: {e}") return "" def _get_websocket_url(self, local_ip: str, port: int) -> str: - """获取websocket地址 + """Get the websocket address Args: - local_ip: 本地IP地址 - port: 端口号 + local_ip: local IP address + port: port number Returns: - str: websocket地址 + str: websocket address """ server_config = self.config["server"] websocket_config = server_config.get("websocket", "") - if "你的" not in websocket_config: + if "your" not in websocket_config: return websocket_config else: return f"ws://{local_ip}:{port}/xiaozhi/v1/" async def handle_post(self, request): - """处理 OTA POST 请求""" + """Handle OTA POST request""" try: data = await request.text() - 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}") + 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}") device_id = request.headers.get("device-id", "") if device_id: - self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}") + self.logger.bind(tag=TAG).info(f"OTA request device ID: {device_id}") else: - raise Exception("OTA请求设备ID为空") + raise Exception("OTA request device ID is empty") data_json = json.loads(data) @@ -84,8 +84,8 @@ class OTAHandler(BaseHandler): mqtt_gateway_endpoint = server_config.get("mqtt_gateway") - if mqtt_gateway_endpoint: # 如果配置了非空字符串 - # 尝试从请求数据中获取设备型号 + if mqtt_gateway_endpoint: # If a non-empty string is configured + # Try to get the device model from the request data device_model = "default" try: if "device" in data_json and isinstance(data_json["device"], dict): @@ -94,13 +94,13 @@ 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"获取设备型号失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to get device model: {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" } @@ -108,20 +108,20 @@ class OTAHandler(BaseHandler): user_data_json = json.dumps(user_data) username = base64.b64encode(user_data_json.encode('utf-8')).decode('utf-8') except Exception as e: - self.logger.bind(tag=TAG).error(f"生成用户名失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to generate username: {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) if not password: - password = "" # 签名失败则留空,由设备决定是否允许无密码 + password = "" # Leave it blank if the signature fails. The device decides whether to allow passwordless authentication. else: - self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空") + self.logger.bind(tag=TAG).warning("MQTT signature key missing, password left blank") - # 构建MQTT配置(直接使用 mqtt_gateway 字符串) + # Build MQTT configuration (use mqtt_gateway string directly) return_json["mqtt_gateway"] = { "endpoint": mqtt_gateway_endpoint, "client_id": mqtt_client_id, @@ -130,14 +130,14 @@ class OTAHandler(BaseHandler): "publish_topic": "device-server", "subscribe_topic": f"devices/p2p/{mac_address_safe}" } - self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置") + self.logger.bind(tag=TAG).info(f"Send MQTT gateway configuration for device {device_id}") - else: # 未配置 mqtt_gateway,下发 WebSocket + else: # mqtt_gateway is not configured, send WebSocket return_json["websocket"] = { "url": self._get_websocket_url(local_ip, port), } - self.logger.bind(tag=TAG).info(f"未配置MQTT网关,为设备 {device_id} 下发WebSocket配置") + self.logger.bind(tag=TAG).info(f"MQTT gateway not configured, send WebSocket configuration for device {device_id}") response = web.Response( text=json.dumps(return_json, separators=(",", ":")), @@ -154,17 +154,17 @@ class OTAHandler(BaseHandler): return response async def handle_get(self, request): - """处理 OTA GET 请求""" + """Handle OTA GET request""" 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接口运行正常,向设备发送的websocket地址是:{websocket_url}" + message = f"OTA interface is running normally. The websocket address sent to the device is: {websocket_url}" response = web.Response(text=message, content_type="text/plain") except Exception as e: - self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}") - response = web.Response(text="OTA接口异常", content_type="text/plain") + self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}") + response = web.Response(text="OTA interface exception", content_type="text/plain") finally: self._add_cors_headers(response) return response \ No newline at end of file diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py index 70be247af..91a3616a8 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__ -# 设置最大文件大小为5MB +# Set the maximum file size to 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]]: - """验证认证token""" + """Verify the authentication token""" auth_header = request.headers.get("Authorization", "") if not auth_header.startswith("Bearer "): return False, None - token = auth_header[7:] # 移除"Bearer "前缀 + token = auth_header[7:] # remove the "Bearer" prefix return self.auth.verify_token(token) async def handle_post(self, request): - """处理 MCP Vision POST 请求""" - response = None # 初始化response变量 + """Handle MCP Vision POST request""" + response = None # Initialize the response variable try: - # 验证token + # Verify the 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("无效的认证token或token已过期") + self._create_error_response("Invalid authentication token or token has expired") ), 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("设备ID与token不匹配") - # 解析multipart/form-data请求 + raise ValueError("Device ID does not match token") + # Parsing multipart/form-data requests reader = await request.multipart() - # 读取question字段 + # Read the question field question_field = await reader.next() if question_field is None: - raise ValueError("缺少问题字段") + raise ValueError("missing problem field") 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("缺少图片文件") + raise ValueError("missing image file") - # 读取图片数据 + # Read image data image_data = await image_field.read() if not image_data: - raise ValueError("图片数据为空") + raise ValueError("Image data is empty") - # 检查文件大小 + # Check file size if len(image_data) > MAX_FILE_SIZE: raise ValueError( - f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB" + f"The image size exceeds the limit, the maximum allowed is {MAX_FILE_SIZE/1024/1024}MB" ) - # 检查文件格式 + # Check file format if not is_valid_image_file(image_data): raise ValueError( - "不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)" + "File format not supported, please upload a valid image file (JPEG, PNG, GIF, BMP, TIFF, WEBP formats supported)" ) - # 将图片转换为base64编码 + # Convert the image to base64 encoding 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("您还未设置默认的视觉分析模块") + raise ValueError("You have not set the default visual analysis module") vllm_type = ( select_vllm_module @@ -113,7 +113,7 @@ class VisionHandler: ) if not vllm_type: - raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") + raise ValueError(f"Unable to find the provider corresponding to the VLLM module {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请求异常: {e}") + self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {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请求异常: {e}") - return_json = self._create_error_response("处理请求时发生错误") + 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") 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): - """处理 MCP Vision GET 请求""" + """Handle MCP Vision GET request""" try: vision_explain = get_vision_url(self.config) if vision_explain and len(vision_explain) > 0 and "null" != vision_explain: message = ( - f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}" + f"MCP Vision interface is running normally. The vision explanation interface address is: {vision_explain}" ) else: - message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址" + 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." response = web.Response(text=message, content_type="text/plain") except Exception as e: - self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}") - return_json = self._create_error_response("服务器内部错误") + self.logger.bind(tag=TAG).error(f"MCP Vision GET request exception: {e}") + return_json = self._create_error_response("Server internal error") 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): - """添加CORS头信息""" + """Add CORS header information""" 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"] = "*" + response.headers["Access-Control-Allow-Origin"] = "*" \ No newline at end of file diff --git a/main/xiaozhi-server/core/auth.py b/main/xiaozhi-server/core/auth.py index ef6431326..f898864e2 100755 --- a/main/xiaozhi-server/core/auth.py +++ b/main/xiaozhi-server/core/auth.py @@ -5,7 +5,7 @@ logger = setup_logging() class AuthenticationError(Exception): - """认证异常""" + """Authentication exception""" pass @@ -13,29 +13,29 @@ class AuthMiddleware: def __init__(self, config): self.config = config self.auth_config = config["server"].get("auth", {}) - # 构建token查找表 + # 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", []) ) 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 - # 验证Authorization header + 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") @@ -50,5 +50,5 @@ class AuthMiddleware: return True def get_token_name(self, token): - """获取token对应的设备名称""" - return self.tokens.get(token) + """Get the device name corresponding to the token""" + return self.tokens.get(token) \ No newline at end of file diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 8db70fbfe..18c4d16da 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -54,7 +54,7 @@ class ConnectionHandler: def __init__( self, config: Dict[str, Any], - _vad, + _What, _asr, _llm, _memory, @@ -65,7 +65,7 @@ class ConnectionHandler: self.config = copy.deepcopy(config) self.session_id = str(uuid.uuid4()) self.logger = setup_logging() - self.server = server # 保存server实例的引用 + self.server = server # Save the reference to the server instance self.auth = AuthMiddleware(config) self.need_bind = False @@ -82,97 +82,97 @@ 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 - # 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启 + # In the future, you can modify this to adjust the reporting of asr and tts. Currently, both are enabled by default. self.report_asr_enable = self.read_config_from_api self.report_tts_enable = self.read_config_from_api - # 依赖的组件 + # Dependent components self.vad = None self.asr = None self.tts = None self._asr = _asr - self._vad = _vad + self._what = _what self.llm = _llm self.memory = _memory self.intent = _intent - # 为每个连接单独管理声纹识别 + # Manage voiceprint recognition separately for each connection self.voiceprint_provider = None - # vad相关变量 + #vad related variables self.client_audio_buffer = bytearray() self.client_have_voice = False - self.last_activity_time = 0.0 # 统一的活动时间戳(毫秒) + self.last_activity_time = 0.0 # Unified activity timestamp (milliseconds) self.client_voice_stop = False self.client_voice_window = deque(maxlen=5) self.last_is_voice = False - # asr相关变量 - # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR - # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量 + # 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 self.asr_audio = [] self.asr_audio_queue = queue.Queue() - # llm相关变量 + #llm related variables self.llm_finish_task = True self.dialogue = Dialogue() - # tts相关变量 + # tts related variables self.sentence_id = None - # 处理TTS响应没有文本返回 + # Handle TTS response with no text returned self.tts_MessageText = "" - # iot相关变量 + #iot related variables 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 - ) # 在原来第一道关闭的基础上加60秒,进行二道关闭 + ) # Add 60 seconds to the original first closure and perform the second closure self.timeout_task = None - # {"mcp":true} 表示启用MCP功能 + # {"mcp":true} means to enable MCP function self.features = None - # 标记连接是否来自MQTT + # Mark whether the connection is from 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: - # 获取并验证headers + # Get and verify headers self.headers = dict(ws.request.headers) if self.headers.get("device-id", None) is None: - # 尝试从 URL 的查询参数中获取 device-id + # Try to get the device-id from the query parameters of the URL from urllib.parse import parse_qs, urlparse - # 从 WebSocket 请求中获取路径 + # Get the path from the WebSocket request request_path = ws.request.path if not request_path: - self.logger.bind(tag=TAG).error("无法获取请求路径") + self.logger.bind(tag=TAG).error("Unable to obtain request path") return parsed_url = urlparse(request_path) query_params = parse_qs(parsed_url.query) @@ -180,7 +180,7 @@ class ConnectionHandler: self.headers["device-id"] = query_params["device-id"][0] self.headers["client-id"] = query_params["client-id"][0] else: - await ws.send("端口正常,如需测试连接,请使用test_page.html") + 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( @@ -194,38 +194,38 @@ 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) - # 检查是否来自MQTT连接 + # Check if it is from MQTT connection 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("连接来自:MQTT网关") + self.logger.bind(tag=TAG).info("Connection from: MQTT Gateway") - # 初始化活动时间戳 + # 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("客户端断开连接") + self.logger.bind(tag=TAG).info("Client disconnected") except AuthenticationError as e: self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}") @@ -238,113 +238,113 @@ class ConnectionHandler: try: await self._save_and_close(ws) except Exception as final_error: - self.logger.bind(tag=TAG).error(f"最终清理时出错: {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 try: await self.close(ws) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"强制关闭连接时出错: {close_error}" + f"Error while forcing the connection to close: {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"保存记忆失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to save memory: {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"保存记忆失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to save memory: {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"保存记忆后关闭连接失败: {close_error}" + f"Failed to close the connection after saving the memory: {close_error}" ) async def _route_message(self, message): - """消息路由""" + """Message routing""" if isinstance(message, str): await handleTextMessage(self, message) elif isinstance(message, bytes): if self.vad is None or self.asr is None: return - # 处理来自MQTT网关的音频包 + # Process audio packets from the MQTT gateway 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): """ - 处理来自MQTT网关的音频消息,解析16字节头部并提取音频数据 + Processes audio messages from the MQTT gateway, parsing the 16-byte header and extracting the audio data Args: - message: 包含头部的音频消息 + message: audio message containing headers Returns: - bool: 是否成功处理了消息 + bool: Whether the message was processed successfully """ 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"解析WebSocket音频包失败: {e}") + self.logger.bind(tag=TAG).error(f"Parsing WebSocket audio packet failed: {e}") - # 处理失败,返回False表示需要继续处理 + # If the processing fails, returning False means that further processing is required. return False def _process_websocket_audio(self, audio_data, timestamp): - """处理WebSocket格式的音频包""" - # 初始化时间戳序列管理 + """Processing WebSocket format audio packets""" + # Initialize timestamp sequence management 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 +356,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("收到服务器重启指令,准备执行...") + self.logger.bind(tag=TAG).info("Received server restart instruction, ready to execute...") - # 发送确认响应 + # Send confirmation response await self.websocket.send( json.dumps( { "type": "server", "status": "success", - "message": "服务器重启中...", + "message": "Server restarting...", "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("执行服务器重启...") + self.logger.bind(tag=TAG).info("Execute server restart...") subprocess.Popen( [sys.executable, "app.py"], stdin=sys.stdin, @@ -394,11 +394,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"重启失败: {str(e)}") + self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}") await self.websocket.send( json.dumps( { @@ -417,60 +417,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"快速初始化组件: prompt成功 {prompt[:50]}..." + f"Quickly initialize component: prompt successful {prompt[:50]}..." ) - """初始化本地组件""" + """Initialize local components""" if self.vad is None: - self.vad = self._vad + self.what = self._what 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"实例化组件失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to instantiate component: {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("系统提示词已增强更新") + self.logger.bind(tag=TAG).info("System prompt words have been enhanced and updated") def _init_report_threads(self): - """初始化ASR和TTS上报线程""" + """Initialize ASR and TTS reporting threads""" if not self.read_config_from_api or self.need_bind: return if self.chat_history_conf == 0: @@ -480,10 +480,10 @@ class ConnectionHandler: target=self._report_worker, daemon=True ) self.report_thread.start() - self.logger.bind(tag=TAG).info("TTS上报线程已启动") + self.logger.bind(tag=TAG).info("TTS reporting thread has started") def _initialize_tts(self): - """初始化TTS""" + """Initialize TTS""" tts = None if not self.need_bind: tts = initialize_tts(self.config) @@ -494,39 +494,39 @@ class ConnectionHandler: return tts def _initialize_asr(self): - """初始化ASR""" + """Initialize ASR""" if self._asr.interface_type == InterfaceType.LOCAL: - # 如果公共ASR是本地服务,则直接返回 - # 因为本地一个实例ASR,可以被多个连接共享 + # If the public ASR is a local service, return directly + # Because a local instance of ASR can be shared by multiple connections asr = self._asr else: - # 如果公共ASR是远程服务,则初始化一个新实例 - # 因为远程ASR,涉及到websocket连接和接收线程,需要每个连接一个实例 + # 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 = 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("声纹识别功能已在连接时动态启用") + self.logger.bind(tag=TAG).info("Voiceprint recognition function has been dynamically enabled during connection") else: - self.logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整") + self.logger.bind(tag=TAG).warning("Voiceprint recognition function is enabled but configuration is incomplete") else: - self.logger.bind(tag=TAG).info("声纹识别功能未启用") + self.logger.bind(tag=TAG).info("Voiceprint recognition function is not enabled") except Exception as e: - self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}") + self.logger.bind(tag=TAG).warning(f"Voiceprint recognition initialization failed: {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 +536,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} 秒,获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" + f"{time.time() - begin_time} seconds, differential configuration is obtained successfully: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" ) except DeviceNotFoundException as e: self.need_bind = True @@ -547,7 +547,7 @@ class ConnectionHandler: private_config = {} except Exception as e: self.need_bind = True - self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to get differential configuration: {e}") private_config = {} init_llm, init_tts, init_memory, init_intent = ( @@ -560,10 +560,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_vad: - self.config["VAD"] = private_config["VAD"] + if init_what: + self.config["WHAT"] = private_config["WHAT"] self.config["selected_module"]["VAD"] = private_config["selected_module"][ - "VAD" + "WHAT" ] if init_asr: self.config["ASR"] = private_config["ASR"] @@ -598,7 +598,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 +609,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 +624,7 @@ class ConnectionHandler: modules = initialize_modules( self.logger, private_config, - init_vad, + init_what, init_asr, init_llm, init_tts, @@ -632,7 +632,7 @@ class ConnectionHandler: init_intent, ) except Exception as e: - self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to initialize component: {e}") modules = {} if modules.get("tts", None) is not None: self.tts = modules["tts"] @@ -650,7 +650,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 +658,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" ] - # 如果使用 nomen,直接返回 - if memory_type == "nomem": + # If nomen is used, return directly + if memory_type == "name": return - # 使用 mem_local_short 模式 + # Using mem_local_short mode elif memory_type == "mem_local_short": memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][ "llm" ] if memory_llm_name and memory_llm_name in self.config["LLM"]: - # 如果配置了专用LLM,则创建独立的LLM实例 + # If a dedicated LLM is configured, create a separate LLM instance from core.utils import llm as llm_utils memory_llm_config = self.config["LLM"][memory_llm_name] @@ -681,13 +681,13 @@ class ConnectionHandler: memory_llm_type, memory_llm_config ) self.logger.bind(tag=TAG).info( - f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}" + f"Created a dedicated LLM for memory summarization: {memory_llm_name}, type: {memory_llm_type}" ) self.memory.set_llm(memory_llm) else: - # 否则使用主LLM + # Otherwise use the main LLM self.memory.set_llm(self.llm) - self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型") + self.logger.bind(tag=TAG).info("Use the main LLM as the intent recognition model") def _initialize_intent(self): if self.intent is None: @@ -697,24 +697,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" ] - # 如果使用 nointent,直接返回 + # If nointent is used, return directly if intent_type == "nointent": return - # 使用 intent_llm 模式 + # Using intent_llm mode elif intent_type == "intent_llm": intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ "llm" ] if intent_llm_name and intent_llm_name in self.config["LLM"]: - # 如果配置了专用LLM,则创建独立的LLM实例 + # If a dedicated LLM is configured, create a separate LLM instance from core.utils import llm as llm_utils intent_llm_config = self.config["LLM"][intent_llm_name] @@ -723,31 +723,31 @@ class ConnectionHandler: intent_llm_type, intent_llm_config ) self.logger.bind(tag=TAG).info( - f"为意图识别创建了专用LLM: {intent_llm_name}, 类型: {intent_llm_type}" + f"Created a dedicated LLM for intent recognition: {intent_llm_name}, type: {intent_llm_type}" ) self.intent.set_llm(intent_llm) else: - # 否则使用主LLM + # Otherwise use the main LLM self.intent.set_llm(self.llm) - self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型") + self.logger.bind(tag=TAG).info("Use the main LLM as the intent recognition model") - """加载统一工具处理器""" + """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 - # 更新系统prompt至上下文 + # Update system prompt to context self.dialogue.update_system_message(self.prompt) def chat(self, query, depth=0): - self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") + self.logger.bind(tag=TAG).info(f"The large model received a user message: {query}") self.llm_finish_task = False - # 为最顶层时新建会话ID和发送FIRST请求 + # Create a new session ID and send the FIRST request when it is the top level if depth == 0: self.sentence_id = str(uuid.uuid4().hex) self.dialogue.put(Message(role="user", content=query)) @@ -766,7 +766,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 +775,7 @@ class ConnectionHandler: memory_str = future.result() if self.intent_type == "function_call" and functions is not None: - # 使用支持functions的streaming接口 + # Using streaming interfaces that support functions llm_responses = self.llm.response_with_functions( self.session_id, self.dialogue.get_llm_dialogue_with_memory( @@ -791,10 +791,10 @@ class ConnectionHandler: ), ) except Exception as e: - self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") + self.logger.bind(tag=TAG).error(f"LLM processing error {query}: {e}") return None - # 处理流式响应 + # Handling streaming responses tool_call_flag = False function_name = None function_id = None @@ -828,7 +828,7 @@ class ConnectionHandler: else: content = response - # 在llm回复中获取情绪表情,一轮对话只在开头获取一次 + # Get emotional expressions in llm replies. Only get them once at the beginning of a conversation. if emotion_flag and content is not None and content.strip(): asyncio.run_coroutine_threadsafe( textUtils.get_emotion(self, content), @@ -847,7 +847,7 @@ class ConnectionHandler: content_detail=content, ) ) - # 处理function call + # Handling function calls if tool_call_flag: bHasError = False if function_id is None: @@ -871,7 +871,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 +886,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 +895,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 +909,7 @@ class ConnectionHandler: ) ) self.llm_finish_task = True - # 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue() + # Use lambda to delay calculation and execute get_llm_dialogue() only at DEBUG level self.logger.bind(tag=TAG).debug( lambda: json.dumps( self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False @@ -919,11 +919,11 @@ class ConnectionHandler: return True def _handle_function_result(self, result, function_call_data, depth): - if result.action == Action.RESPONSE: # 直接回复前端 + if result.action == Action.RESPONSE: # Reply directly to the front end text = result.response self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text) self.dialogue.put(Message(role="assistant", content=text)) - elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 + elif result.action == Action.REQLLM: # After calling the function, request llm to generate a reply text = result.result if text is not None and len(text) > 0: function_id = function_call_data["id"] @@ -968,51 +968,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: # 检测毒丸对象 + if item is None: # Detect poison pill object 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"聊天记录上报线程异常: {e}") + self.logger.bind(tag=TAG).error(f"Chat record reporting thread exception: {e}") except queue.Empty: continue except Exception as e: - self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}") + self.logger.bind(tag=TAG).error(f"Chat record reporting work thread exception: {e}") - self.logger.bind(tag=TAG).info("聊天记录上报线程已退出") + self.logger.bind(tag=TAG).info("Chat record reporting thread has exited") 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"上报处理异常: {e}") + self.logger.bind(tag=TAG).error(f"Reporting processing exception: {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"清除服务端讲话状态") + self.logger.bind(tag=TAG).debug(f"Clear server speech status") 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 +1021,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"清理工具处理器时出错: {cleanup_error}" + f"Error in cleanup tool processor: {cleanup_error}" ) - # 触发停止事件 + # Trigger stop event if self.stop_event: self.stop_event.set() - # 清空任务队列 + # Clear the task queue self.clear_queues() - # 关闭WebSocket连接 + # Close the WebSocket connection try: if ws: - # 安全地检查WebSocket状态并关闭 + # Safely check WebSocket status and close try: if hasattr(ws, "closed") and not ws.closed: await ws.close() elif hasattr(ws, "state") and ws.state.name != "CLOSED": await ws.close() else: - # 如果没有closed属性,直接尝试关闭 + # If there is no closed attribute, try to close it directly await ws.close() except Exception: - # 如果关闭失败,忽略错误 + # If shutdown fails, ignore the error pass elif self.websocket: try: @@ -1065,43 +1065,43 @@ class ConnectionHandler: ): await self.websocket.close() else: - # 如果没有closed属性,直接尝试关闭 + # If there is no closed attribute, try to close it directly 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"关闭WebSocket连接时出错: {ws_error}") + self.logger.bind(tag=TAG).error(f"Error closing WebSocket connection: {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"关闭线程池时出错: {executor_error}" + f"Error shutting down thread pool: {executor_error}" ) self.executor = None - self.logger.bind(tag=TAG).info("连接资源已释放") + self.logger.bind(tag=TAG).info("Connection resources have been released") except Exception as e: - self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}") + self.logger.bind(tag=TAG).error(f"Error closing connection: {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"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}" + f"Start cleaning: TTS queue size = {self.tts.tts_text_queue.qsize()}, audio queue size = {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 +1116,7 @@ class ConnectionHandler: break self.logger.bind(tag=TAG).debug( - f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}" + f"Cleanup completed: TTS queue size = {self.tts.tts_text_queue.qsize()}, audio queue size = {self.tts.tts_audio_queue.qsize()}" ) def reset_vad_states(self): @@ -1137,10 +1137,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 +1148,20 @@ class ConnectionHandler: > self.timeout_seconds * 1000 ): if not self.stop_event.is_set(): - self.logger.bind(tag=TAG).info("连接超时,准备关闭") - # 设置停止事件,防止重复处理 + self.logger.bind(tag=TAG).info("Connection timed out, ready to close") + # Set the stop event to prevent repeated processing self.stop_event.set() - # 使用 try-except 包装关闭操作,确保不会因为异常而阻塞 + # Use try-except to wrap the shutdown operation to ensure that it is not blocked due to exceptions try: await self.close(self.websocket) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"超时关闭连接时出错: {close_error}" + f"Error closing connection timeout: {close_error}" ) break - # 每10秒检查一次,避免过于频繁 + # Check every 10 seconds to avoid too frequent await asyncio.sleep(10) except Exception as e: - self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}") + self.logger.bind(tag=TAG).error(f"Timeout check task error: {e}") finally: - self.logger.bind(tag=TAG).info("超时检查任务已退出") + self.logger.bind(tag=TAG).info("Timeout check task has exited") \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/abortHandle.py index ce6f22b6c..01ef59ebc 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") - # 设置成打断状态,会自动打断llm、tts任务 + # Set to interrupt state, which will automatically interrupt llm and tts tasks 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 75b9fcb23..ebd8dd5bb 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -18,34 +18,34 @@ TAG = __name__ WAKEUP_CONFIG = { "refresh_time": 5, - "words": ["你好", "你好啊", "嘿,你好", "嗨"], + "words": ["Hello", "Hello", "Hey, hello", "Hi"], } -# 创建全局的唤醒词配置管理器 +# Create a global wake-up word configuration manager wakeup_words_config = WakeupWordsConfig() -# 用于防止并发调用wakeupWordsResponse的锁 +# Lock used to prevent concurrent calls to wakeupWordsResponse _wakeup_response_lock = asyncio.Lock() async def handleHelloMessage(conn, msg_json): - """处理hello消息""" + """Process hello message""" audio_params = msg_json.get("audio_params") if audio_params: format = audio_params.get("format") - conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}") + conn.logger.bind(tag=TAG).info(f"Client audio format: {format}") conn.audio_format = format conn.welcome_msg["audio_params"] = audio_params features = msg_json.get("features") if features: - conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") + conn.logger.bind(tag=TAG).info(f"Client features: {features}") conn.features = features if features.get("mcp"): - conn.logger.bind(tag=TAG).info("客户端支持MCP") + conn.logger.bind(tag=TAG).info("Client supports MCP") conn.mcp_client = MCPClient() - # 发送初始化 + # Send initialization asyncio.create_task(send_mcp_initialize_message(conn)) - # 发送mcp消息,获取tools列表 + # Send mcp message to get tools list asyncio.create_task(send_mcp_tools_list_request(conn)) await conn.websocket.send(json.dumps(conn.welcome_msg)) @@ -56,7 +56,7 @@ async def checkWakeupWords(conn, text): "enable_wakeup_words_response_cache" ] - # 等待tts初始化,最多等待3秒 + # Wait for tts to initialize, wait up to 3 seconds start_time = time.time() while time.time() - start_time < 3: if conn.tts: @@ -75,34 +75,34 @@ async def checkWakeupWords(conn, text): conn.just_woken_up = True await send_stt_message(conn, text) - # 获取当前音色 + # 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", "time": 0, - "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦", + "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." } - # 获取音频数据 + # 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"播放唤醒词回复: {response.get('text')}") + conn.logger.bind(tag=TAG).info(f"Play wake-up word reply: {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)) @@ -114,38 +114,38 @@ async def wakeupWordsResponse(conn): 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 - + "```。\n请你根据以上用户的内容进行20-30字回复。要符合系统设置的角色情感和态度,不要像机器人一样说话。\n" - + "请勿对这条内容本身进行任何解释和回应,请勿返回表情符号,仅返回对用户的内容的回复。" + + "```.\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) if not result or len(result) == 0: return - # 生成TTS音频 + # Generate TTS audio 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 diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 23b2d0aa1..750b1c207 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): - # 预处理输入文本,处理可能的JSON格式 + # Preprocess the input text to handle possible JSON format try: if text.strip().startswith('{') and text.strip().endswith('}'): parsed_data = json.loads(text) if isinstance(parsed_data, dict) and "content" in parsed_data: - text = parsed_data["content"] # 提取content用于意图分析 - conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息 + text = parsed_data["content"] # Extract content for intent analysis + conn.current_speaker = parsed_data.get("speaker") # Keep speaker information 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": - # 使用支持function calling的聊天方法,不再进行意图分析 + # Use chat methods that support function calling and no longer perform intent analysis return False - # 使用LLM进行意图分析 + # Use LLM for intent analysis intent_result = await analyze_intent_with_llm(conn, text) if not intent_result: return False - # 会话开始时生成sentence_id + # Generate sentence_id when the session starts 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"识别到明确的退出命令: {text}") + conn.logger.bind(tag=TAG).info(f"A clear exit command was recognized: {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): - """使用LLM分析用户意图""" + """Using LLM to analyze user intent""" if not hasattr(conn, "intent") or not conn.intent: - conn.logger.bind(tag=TAG).warning("意图识别服务未初始化") + conn.logger.bind(tag=TAG).warning("Intent recognition service is not initialized") 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"意图识别失败: {str(e)}") + conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}") return None async def process_intent_result(conn, intent_result, original_text): - """处理意图识别结果""" + """Process intent recognition results""" try: - # 尝试将结果解析为JSON + # Try to parse the result as JSON intent_data = json.loads(intent_result) - # 检查是否有function_call + # Check if there is function_call if "function_call" in intent_data: - # 直接从意图识别获取了function_call + # Get function_call directly from intent recognition conn.logger.bind(tag=TAG).debug( - f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}" + f"Detected intent result in function_call format: {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() - # 构建带上下文的基础提示 - context_prompt = f"""当前时间:{current_time} - 今天日期:{today_date} ({today_weekday}) - 今天农历:{lunar_date} + # 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} - 请根据以上信息回答用户的问题:{original_text}""" + Please answer the user's question based on the above information: {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 = {} - # 确保参数是字符串格式的JSON + # Ensure the parameter is a JSON string 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 - # 使用executor执行函数调用和结果处理 + # Use executor to execute function calls and result processing 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"工具调用失败: {e}") + conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}") result = ActionResponse( action=Action.ERROR, result=str(e), response=str(e) ) if result: - if result.action == Action.RESPONSE: # 直接回复前端 + if result.action == Action.RESPONSE: # Reply directly to the front end text = result.response if text is not None: speak_txt(conn, text) - elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 + elif result.action == Action.REQLLM: # After calling the function, request llm to generate a reply 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"处理意图结果时出错: {e}") + conn.logger.bind(tag=TAG).error(f"Error processing intent result: {e}") return False @@ -204,4 +204,4 @@ def speak_txt(conn, text): content_type=ContentType.ACTION, ) ) - conn.dialogue.put(Message(role="assistant", content=text)) + conn.dialogue.put(Message(role="assistant", content=text)) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 8b6359091..a647d6d26 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -11,12 +11,12 @@ TAG = __name__ async def handleAudioMessage(conn, audio): - # 当前片段是否有人说话 + # Is there anyone speaking in the current segment? have_voice = conn.vad.is_vad(conn, audio) - # 如果设备刚刚被唤醒,短暂忽略VAD检测 + # 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: have_voice = False - # 设置一个短暂延迟后恢复VAD检测 + # Set a short delay before resuming VAD detection conn.asr_audio.clear() if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) @@ -24,39 +24,39 @@ async def handleAudioMessage(conn, audio): if have_voice: if conn.client_is_speaking: await handleAbortMessage(conn) - # 设备长时间空闲检测,用于say goodbye + # Device long-term idle detection, used to 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): - # 等待2秒后恢复VAD检测 + # Resume VAD detection after waiting 2 seconds await asyncio.sleep(1) conn.just_woken_up = False async def startToChat(conn, text): - # 检查输入是否是JSON格式(包含说话人信息) + # Check if the input is in JSON format (including speaker information) speaker_name = None actual_text = text try: - # 尝试解析JSON格式的输入 + # Try to parse JSON formatted input if text.strip().startswith("{") and text.strip().endswith("}"): data = json.loads(text) if "speaker" in data and "content" in data: speaker_name = data["speaker"] actual_text = data["content"] - conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}") + conn.logger.bind(tag=TAG).info(f"Parsed speaker information: {speaker_name}") - # 直接使用JSON格式的文本,不解析 + # Use JSON format text directly without parsing 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,7 +66,7 @@ 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 @@ -76,14 +76,14 @@ async def startToChat(conn, text): if conn.client_is_speaking: 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 +92,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 +106,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("结束对话,无需发送结束提示语") + conn.logger.bind(tag=TAG).info("End the conversation, no need to send an end prompt") await conn.close() return prompt = end_prompt.get("prompt") if not prompt: - prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!" + prompt = "Please end this conversation with a sentimental, nostalgic remark: 'Time flies!'" 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 = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!" + text = "Sorry, I'm busy right now. Let's talk again tomorrow at this time. Okay! See you tomorrow. Bye!" await send_stt_message(conn, text) file_path = "config/assets/max_output_size.wav" opus_packets = audio_to_data(file_path) @@ -128,37 +128,37 @@ async def max_out_size(conn): async def check_bind_device(conn): if conn.bind_code: - # 确保bind_code是6位数字 + # Make sure bind_code is 6 digits if len(conn.bind_code) != 6: - conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}") - text = "绑定码格式错误,请检查配置。" + 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." await send_stt_message(conn, text) return - text = f"请登录控制面板,输入{conn.bind_code},绑定设备。" + text = f"Please log in to the control panel and enter {conn.bind_code} to bind the device." 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)) - # 逐个播放数字 - for i in range(6): # 确保只播放6位数字 + # Play numbers one by one + for i in range(6): # Ensure only 6 digits are played try: digit = conn.bind_code[i] num_path = f"config/assets/bind_code/{digit}.wav" num_packets = audio_to_data(num_path) conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None)) except Exception as e: - conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}") + conn.logger.bind(tag=TAG).error(f"Failed to play digital audio: {e}") continue conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None)) else: - # 播放未绑定提示 + # Play unbound prompt conn.client_abort = False - text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。" + text = f"The version information of this device was not found. Please configure the OTA address correctly and then recompile the firmware." await send_stt_message(conn, text) music_path = "config/assets/bind_not_found.wav" opus_packets = audio_to_data(music_path) - conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) + conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py index 7b30f79c0..129e1864f 100644 --- a/main/xiaozhi-server/core/handle/reportHandle.py +++ b/main/xiaozhi-server/core/handle/reportHandle.py @@ -1,12 +1,12 @@ """ -TTS上报功能已集成到ConnectionHandler类中。 +The TTS reporting function has been integrated into the ConnectionHandler class. -上报功能包括: -1. 每个连接对象拥有自己的上报队列和处理线程 -2. 上报线程的生命周期与连接对象绑定 -3. 使用ConnectionHandler.enqueue_tts_report方法进行上报 +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 -具体实现请参考core/connection.py中的相关代码。 +For specific implementation, please refer to the relevant code in 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: 连接对象 - type: 上报类型,1为用户,2为智能体 - text: 合成文本 - opus_data: opus音频数据 - report_time: 上报时间 + conn: connection object + type: reporting type, 1 is user, 2 is agent + text: synthetic text + opus_data: opus audio data + report_time: reporting 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"聊天记录上报失败: {e}") + conn.logger.bind(tag=TAG).error(f"Chat record reporting failed: {e}") def opus_to_wav(conn, opus_data): - """将Opus数据转换为WAV格式的字节流 + """Convert Opus data into a byte stream in WAV format Args: - output_dir: 输出目录(保留参数以保持接口兼容) - opus_data: opus音频数据 + output_dir: output directory (retain parameters to maintain interface compatibility) + opus_data: opus audio data Returns: - bytes: WAV格式的音频数据 + bytes: audio data in WAV format """ - decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, mono 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解码错误: {e}", exc_info=True) + conn.logger.bind(tag=TAG).error(f"Opus decoding error: {e}", exc_info=True) if not pcm_data: - raise ValueError("没有有效的PCM数据") + raise ValueError("No valid PCM data") - # 创建WAV文件头 + # Create a WAV file header pcm_data_bytes = b"".join(pcm_data) num_samples = len(pcm_data_bytes) // 2 # 16-bit samples - # WAV文件头 + # WAV file header 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 - # 返回完整的WAV数据 + # Return complete WAV data 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 - """将TTS数据加入上报队列 + """Add TTS data to the reporting queue Args: - conn: 连接对象 - text: 合成文本 - opus_data: opus音频数据 + conn: connection object + text: synthetic text + opus_data: opus audio data """ 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数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " + f"TTS data has been added to the reporting queue: {conn.device_id}, audio size: {len(opus_data)}" ) else: conn.report_queue.put((2, text, None, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频" + f"TTS data has been added to the reporting queue: {conn.device_id}, no audio is reported" ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}") + conn.logger.bind(tag=TAG).error(f"Failed to join TTS reporting queue: {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 - """将ASR数据加入上报队列 + """Add ASR data to the reporting queue Args: - conn: 连接对象 - text: 合成文本 - opus_data: opus音频数据 + conn: connection object + text: synthetic text + opus_data: opus audio data """ 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数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " + f"ASR data has been added to the reporting queue: {conn.device_id}, audio size: {len(opus_data)}" ) else: conn.report_queue.put((1, text, None, int(time.time()))) conn.logger.bind(tag=TAG).debug( - f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频" + f"ASR data has been added to the reporting queue: {conn.device_id}, no audio is reported" ) except Exception as e: - conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}") + conn.logger.bind(tag=TAG).debug(f"Failed to join the ASR reporting queue: {text}, {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index 8beda5771..db2e4430f 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"发送第一段语音: {text}") + conn.logger.bind(tag=TAG).info(f"Send the first voice: {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"发送音频消息: {sentenceType}, {text}") + conn.logger.bind(tag=TAG).info(f"Send audio message: {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: 连接对象 - start_time: 起始时间(性能计数器值) - packet_index: 数据包索引 - frame_duration: 帧时长(毫秒),匹配 Opus 编码 + conn: connection object + start_time: start time (performance counter value) + packet_index: packet index + frame_duration: frame duration (milliseconds), matching Opus encoding 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 # 如果没有流控状态,直接使用索引 + sequence = packet_index # If there is no flow control status, use the index directly return timestamp, sequence async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence): """ - 发送带16字节头部的opus数据包给mqtt_gateway + Send an opus data packet with a 16-byte header to mqtt_gateway Args: - conn: 连接对象 - opus_packet: opus数据包 - timestamp: 时间戳 - sequence: 序列号 + conn: connection object + opus_packet: opus data packet + timestamp: timestamp + sequence: sequence number """ - # 为opus数据包添加16字节头部 + # Add a 16-byte header to the opus data packet 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") # 时间戳 + header[8:12] = timestamp.to_bytes(4, "big") # Timestamp 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): """ - 发送单个opus包,支持流控 + Send a single opus packet, support flow control Args: - conn: 连接对象 - opus_packet: 单个opus数据包 - pre_buffer: 快速发送音频 - frame_duration: 帧时长(毫秒),匹配 Opus 编码 + conn: connection object + opus_packet: single opus data packet + pre_buffer: Send audio quickly + frame_duration: frame duration (milliseconds), matching Opus encoding """ 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, # 添加序列号 + "sequence": 0, # add sequence number } 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: - # 直接发送opus数据包,不添加头部 + # Send opus data packets directly without adding headers 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: - # 直接发送opus数据包,不添加头部 + # Send opus data packets directly without adding headers await conn.websocket.send(opus_packet) play_position += frame_duration async def send_tts_message(conn, state, text=None): - """发送 TTS 状态消息""" + """Send TTS status message""" 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) - # TTS播放结束 + # End of TTS playback 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): - """发送 STT 状态消息""" + """Send STT status message""" 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 - # 解析JSON格式,提取实际的用户说话内容 + # Parse the JSON format and extract the actual user speech content display_text = text try: - # 尝试解析JSON格式 + # Try to parse JSON format if text.strip().startswith("{") and text.strip().endswith("}"): parsed_data = json.loads(text) if isinstance(parsed_data, dict) and "content" in parsed_data: - # 如果是包含说话人信息的JSON格式,只显示content部分 + # If the JSON format contains speaker information, only the content part is displayed display_text = parsed_data["content"] - # 保存说话人信息到conn对象 + # Save speaker information to conn object if "speaker" in parsed_data: conn.current_speaker = parsed_data["speaker"] except (json.JSONDecodeError, TypeError): - # 如果不是JSON格式,直接使用原始文本 + # If it is not in JSON format, use the original text directly display_text = text stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text) await conn.websocket.send( json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id}) ) conn.client_is_speaking = True - await send_tts_message(conn, "start") + await send_tts_message(conn, "start") \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index b5e877834..973305995 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 dc540d24a..d886a89d7 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消息处理器""" + """Abort message handler""" @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 1839814e6..28721cb67 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消息处理器""" + """Hello message handler""" @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 335d08b0f..f94bd55e0 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消息处理器""" + """IoT message processor""" @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 97286dfe0..fd9a02096 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消息处理器""" + """Listen message processor""" @property def message_type(self) -> TextMessageType: - return TextMessageType.LISTEN + return TextMessageType.LIST 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"客户端拾音模式:{conn.client_listen_mode}" + f"Client pickup mode: {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"] # 保留原始文本 + original_text = msg_json["text"] # Keep the original 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 - # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) - enqueue_asr_report(conn, "嘿,你好呀", []) - await startToChat(conn, "嘿,你好呀") + # 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") else: - # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) + # Report pure text data (reuse ASR reporting function, but do not provide audio data) enqueue_asr_report(conn, original_text, []) - # 否则需要LLM对文字内容进行答复 + # Otherwise, LLM needs to respond to the text content 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 65876f24b..50da3a161 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消息处理器""" + """Mcp message processor""" @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 b9a235888..f6a1a5cea 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消息处理器""" + """MCP message processor""" @property def message_type(self) -> TextMessageType: return TextMessageType.SERVER async def handle(self, conn, msg_json: Dict[str, Any]) -> None: - # 如果配置是从API读取的,则需要验证secret + # If the configuration is read from the API, the secret needs to be verified if not conn.read_config_from_api: return - # 获取post请求的secret + # Get the secret of the post request post_secret = msg_json.get("content", {}).get("secret", "") secret = conn.config["manager-api"].get("secret", "") - # 如果secret不匹配,则返回 + # If the secret does not match, return if post_secret != secret: await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": "服务器密钥验证失败", + "message": "Server key verification failed", } ) ) return - # 动态更新配置 + # Dynamically update configuration if msg_json["action"] == "update_config": try: - # 更新WebSocketServer的配置 + # Update the WebSocketServer configuration if not conn.server: await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": "无法获取服务器实例", + "message": "Unable to get server instance", "content": {"action": "update_config"}, } ) @@ -57,36 +57,36 @@ class ServerTextMessageHandler(TextMessageHandler): { "type": "server", "status": "error", - "message": "更新服务器配置失败", + "message": "Failed to update server configuration", "content": {"action": "update_config"}, } ) ) return - # 发送成功响应 + # Send successful response await conn.websocket.send( json.dumps( { "type": "server", "status": "success", - "message": "配置更新成功", + "message": "Configuration updated successfully", "content": {"action": "update_config"}, } ) ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}") + conn.logger.bind(tag=TAG).error(f"Update configuration failed: {str(e)}") await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": f"更新配置失败: {str(e)}", + "message": f"Failed to update configuration: {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 f94a0bac0..85c4d54e6 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 e90d72310..cd19aac22 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: - """获取支持的消息类型""" - return list(self._handlers.keys()) + """Get supported message types""" + return list(self._handlers.keys()) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/textMessageProcessor.py b/main/xiaozhi-server/core/handle/textMessageProcessor.py index 0cae5e099..b43e7659b 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: - # 解析JSON消息 + # Parsing JSON messages msg_json = json.loads(message) - # 处理JSON消息 + # Processing JSON messages if isinstance(msg_json, dict): message_type = msg_json.get("type") - # 记录日志 - conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}") + # Logging + conn.logger.bind(tag=TAG).info(f"Received {message_type} message: {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"收到未知类型消息:{message}") - # 处理纯数字消息 + conn.logger.bind(tag=TAG).error(f"Received unknown type message: {message}") + # Processing pure numeric messages elif isinstance(msg_json, int): - conn.logger.bind(tag=TAG).info(f"收到数字消息:{message}") + conn.logger.bind(tag=TAG).info(f"Received digital message: {message}") await conn.websocket.send(message) except json.JSONDecodeError: - # 非JSON消息直接转发 - conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}") - await conn.websocket.send(message) + # 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 diff --git a/main/xiaozhi-server/core/handle/textMessageType.py b/main/xiaozhi-server/core/handle/textMessageType.py index 53e71b711..8268737bf 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 edbdf1fee..4650851de 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: - """获取websocket地址 + """Get the websocket address Args: - local_ip: 本地IP地址 - port: 端口号 + local_ip: local IP address + port: port number Returns: - str: websocket地址 + str: websocket address """ 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: - # 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口 + # 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 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) # 每隔 1 小时检查一次 + await asyncio.sleep(3600) # Check every 1 hour \ No newline at end of file diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 09ba79615..d630bde27 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -43,76 +43,76 @@ class WebSocketServer: await asyncio.Future() async def _handle_connection(self, websocket): - """处理新连接,每次创建独立的ConnectionHandler""" - # 创建ConnectionHandler时传入当前server实例 + """Handle new connections, creating a separate ConnectionHandler each time""" + # Pass in the current server instance when creating a ConnectionHandler handler = ConnectionHandler( self.config, - self._vad, + self._what, self._asr, self._llm, self._memory, self._intent, - self, # 传入server实例 + self, # pass in server instance ) self.active_connections.add(handler) try: await handler.handle_connection(websocket) except Exception as e: - self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}") + self.logger.bind(tag=TAG).error(f"Error while processing connection: {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: - # 安全地检查WebSocket状态并关闭 + # Safely check WebSocket status and close if hasattr(websocket, "closed") and not websocket.closed: await websocket.close() elif hasattr(websocket, "state") and websocket.state.name != "CLOSED": await websocket.close() else: - # 如果没有closed属性,直接尝试关闭 + # If there is no closed attribute, try to close it directly await websocket.close() except Exception as close_error: self.logger.bind(tag=TAG).error( - f"服务器端强制关闭连接时出错: {close_error}" + f"Error when the server forcibly closed the connection: {close_error}" ) async def _http_response(self, websocket, request_headers): - # 检查是否为 WebSocket 升级请求 + # Check if it is a WebSocket upgrade request if request_headers.headers.get("connection", "").lower() == "upgrade": - # 如果是 WebSocket 请求,返回 None 允许握手继续 + # If it is a WebSocket request, return None to allow the handshake to continue return None else: - # 如果是普通 HTTP 请求,返回 "server is running" + # If it is a normal HTTP request, return "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: 更新是否成功 + bool: whether the update is successful """ 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("获取新配置失败") + self.logger.bind(tag=TAG).error("Failed to get new configuration") return False - self.logger.bind(tag=TAG).info(f"获取新配置成功") - # 检查 VAD 和 ASR 类型是否需要更新 + self.logger.bind(tag=TAG).info(f"Get new configuration successfully") + # Check if VAD and ASR types need to be updated 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"检查VAD和ASR类型是否需要更新: {update_vad} {update_asr}" + f"Check if VAD and ASR types need to be updated: {update_vad} {update_asr}" ) - # 更新配置 + # Update configuration self.config = new_config - # 重新初始化组件 + # Reinitialize components modules = initialize_modules( self.logger, new_config, - update_vad, + update_what, update_asr, "LLM" in new_config["selected_module"], False, @@ -120,7 +120,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 +131,8 @@ class WebSocketServer: self._intent = modules["intent"] if "memory" in modules: self._memory = modules["memory"] - self.logger.bind(tag=TAG).info(f"更新配置任务执行完毕") + self.logger.bind(tag=TAG).info(f"Update configuration task completed") return True except Exception as e: - self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}") - return False + self.logger.bind(tag=TAG).error(f"Failed to update server configuration: {str(e)}") + return False \ No newline at end of file