From 2a2b122edf7765a3c1c37d5e0940f1f5743be5fa Mon Sep 17 00:00:00 2001 From: karthikeyareddy183 Date: Wed, 13 Aug 2025 23:24:43 +0530 Subject: [PATCH] tranlated to english server and mqtt folders --- main/mqtt-gateway/README.md | 204 +-- main/mqtt-gateway/app.js | 1206 +++++++++-------- main/mqtt-gateway/generate_signature_key.js | 65 +- main/mqtt-gateway/mqtt-protocol.js | 928 ++++++------- main/mqtt-gateway/utils/config-manager.js | 127 +- main/mqtt-gateway/utils/mqtt_config_v2.js | 187 +-- main/mqtt-gateway/测试说明.md | 269 ++-- main/xiaozhi-server/app.py | 85 +- main/xiaozhi-server/client.py | 4 +- main/xiaozhi-server/config/config_loader.py | 92 +- main/xiaozhi-server/config/logger.py | 77 +- .../config/manage_api_client.py | 66 +- main/xiaozhi-server/config/settings.py | 23 +- main/xiaozhi-server/core/api/base_handler.py | 2 +- main/xiaozhi-server/core/api/ota_handler.py | 226 +-- .../xiaozhi-server/core/api/vision_handler.py | 80 +- main/xiaozhi-server/core/auth.py | 36 +- main/xiaozhi-server/core/connection.py | 388 +++--- .../xiaozhi-server/core/handle/abortHandle.py | 6 +- .../xiaozhi-server/core/handle/helloHandle.py | 51 +- .../core/handle/intentHandler.py | 67 +- .../core/handle/receiveAudioHandle.py | 76 +- .../core/handle/reportHandle.py | 80 +- .../core/handle/sendAudioHandle.py | 53 +- main/xiaozhi-server/core/handle/textHandle.py | 83 +- main/xiaozhi-server/core/http_server.py | 70 +- .../core/providers/asr/aliyun.py | 455 ++++--- .../core/providers/asr/aliyun_stream.py | 183 +-- .../core/providers/asr/baidu.py | 50 +- .../xiaozhi-server/core/providers/asr/base.py | 168 +-- .../core/providers/asr/doubao.py | 96 +- .../core/providers/asr/doubao_stream.py | 98 +- .../core/providers/asr/dto/dto.py | 8 +- .../core/providers/asr/fun_local.py | 58 +- .../core/providers/asr/fun_server.py | 54 +- .../core/providers/asr/groq_whisper.py | 36 +- .../core/providers/asr/openai.py | 31 +- .../core/providers/asr/sherpa_onnx_local.py | 43 +- .../core/providers/asr/tencent.py | 117 +- .../core/providers/intent/base.py | 22 +- .../intent/function_call/function_call.py | 9 +- .../providers/intent/intent_llm/intent_llm.py | 231 ++-- .../providers/intent/nointent/nointent.py | 9 +- .../core/providers/llm/AliBL/AliBL.py | 26 +- .../xiaozhi-server/core/providers/llm/base.py | 13 +- .../core/providers/llm/coze/coze.py | 23 +- .../core/providers/llm/dify/dify.py | 33 +- .../core/providers/llm/fastgpt/fastgpt.py | 18 +- .../core/providers/llm/gemini/gemini.py | 57 +- .../llm/homeassistant/homeassistant.py | 48 +- .../core/providers/llm/ollama/ollama.py | 95 +- .../core/providers/llm/openai/openai.py | 32 +- .../core/providers/llm/system_prompt.py | 35 +- .../providers/llm/xinference/xinference.py | 27 +- .../core/providers/memory/mem0ai/mem0ai.py | 17 +- .../memory/mem_local_short/mem_local_short.py | 141 +- .../core/providers/memory/nomem/nomem.py | 7 +- .../core/providers/tools/base/__init__.py | 2 +- .../providers/tools/base/tool_executor.py | 17 +- .../core/providers/tools/base/tool_types.py | 28 +- .../providers/tools/device_iot/__init__.py | 2 +- .../tools/device_iot/iot_descriptor.py | 17 +- .../tools/device_iot/iot_executor.py | 105 +- .../providers/tools/device_iot/iot_handler.py | 30 +- .../providers/tools/device_mcp/__init__.py | 4 +- .../providers/tools/device_mcp/mcp_client.py | 17 +- .../tools/device_mcp/mcp_executor.py | 34 +- .../providers/tools/device_mcp/mcp_handler.py | 227 ++-- .../providers/tools/mcp_endpoint/__init__.py | 4 +- .../tools/mcp_endpoint/mcp_endpoint_client.py | 27 +- .../mcp_endpoint/mcp_endpoint_executor.py | 25 +- .../mcp_endpoint/mcp_endpoint_handler.py | 172 ++- .../providers/tools/server_mcp/__init__.py | 2 +- .../providers/tools/server_mcp/mcp_client.py | 81 +- .../tools/server_mcp/mcp_executor.py | 28 +- .../providers/tools/server_mcp/mcp_manager.py | 77 +- .../tools/server_plugins/__init__.py | 4 +- .../tools/server_plugins/plugin_executor.py | 36 +- .../providers/tools/unified_tool_handler.py | 118 +- .../providers/tools/unified_tool_manager.py | 57 +- .../core/providers/tts/aliyun.py | 233 +++- .../core/providers/tts/aliyun_stream.py | 232 ++-- .../xiaozhi-server/core/providers/tts/base.py | 98 +- .../core/providers/tts/cozecn.py | 34 + .../core/providers/tts/custom.py | 49 +- .../core/providers/tts/default.py | 15 +- .../core/providers/tts/doubao.py | 75 +- .../core/providers/tts/dto/dto.py | 34 +- .../xiaozhi-server/core/providers/tts/edge.py | 51 +- .../core/providers/tts/elevenlabs.py | 118 +- .../core/providers/tts/fishspeech.py | 193 ++- .../core/providers/tts/gpt_sovits_v2.py | 92 +- .../core/providers/tts/gpt_sovits_v3.py | 55 +- .../providers/tts/huoshan_double_stream.py | 1005 +++++++++++--- .../core/providers/tts/index_stream.py | 113 +- .../core/providers/tts/linkerai.py | 189 +-- .../core/providers/tts/minimax.py | 25 +- .../core/providers/tts/minimax_httpstream.py | 106 +- .../core/providers/tts/minimax_webSocket.py | 79 +- .../core/providers/tts/openai.py | 12 +- .../core/providers/tts/paddle_speech.py | 93 +- .../core/providers/tts/siliconflow.py | 11 +- .../core/providers/tts/tencent.py | 110 +- .../core/providers/tts/ttson.py | 49 +- .../xiaozhi-server/core/providers/vad/base.py | 3 +- .../core/providers/vad/silero.py | 51 +- .../core/providers/vllm/openai.py | 6 +- main/xiaozhi-server/core/utils/asr.py | 6 +- main/xiaozhi-server/core/utils/auth.py | 81 +- .../xiaozhi-server/core/utils/cache/config.py | 37 +- .../core/utils/cache/manager.py | 136 +- .../core/utils/cache/strategies.py | 24 +- main/xiaozhi-server/core/utils/dialogue.py | 49 +- main/xiaozhi-server/core/utils/intent.py | 5 +- main/xiaozhi-server/core/utils/llm.py | 12 +- main/xiaozhi-server/core/utils/memory.py | 5 +- .../core/utils/modules_initialize.py | 68 +- .../core/utils/opus_encoder_utils.py | 93 +- .../core/utils/output_counter.py | 23 +- main/xiaozhi-server/core/utils/p3.py | 29 +- .../core/utils/prompt_manager.py | 155 ++- main/xiaozhi-server/core/utils/textUtils.py | 55 +- main/xiaozhi-server/core/utils/tts.py | 70 +- main/xiaozhi-server/core/utils/util.py | 181 +-- main/xiaozhi-server/core/utils/vad.py | 7 +- main/xiaozhi-server/core/utils/vllm.py | 9 +- .../core/utils/voiceprint_provider.py | 62 +- main/xiaozhi-server/core/utils/wakeup_word.py | 60 +- main/xiaozhi-server/core/websocket_server.py | 69 +- main/xiaozhi-server/performance_tester.py | 286 ++-- .../xiaozhi-server/performance_tester_vllm.py | 104 +- .../functions/get_news_from_chinanews.py | 184 ++- .../functions/get_news_from_newsnow.py | 207 +-- .../plugins_func/functions/get_time.py | 24 +- .../plugins_func/functions/get_weather.py | 209 +-- .../functions/handle_exit_intent.py | 19 +- .../plugins_func/functions/hass_get_state.py | 45 +- .../plugins_func/functions/hass_init.py | 14 +- .../plugins_func/functions/hass_play_music.py | 22 +- .../plugins_func/functions/hass_set_state.py | 72 +- .../plugins_func/functions/play_music.py | 142 +- .../plugins_func/loadplugins.py | 15 +- main/xiaozhi-server/plugins_func/register.py | 69 +- 143 files changed, 7811 insertions(+), 5873 deletions(-) diff --git a/main/mqtt-gateway/README.md b/main/mqtt-gateway/README.md index bb591758c..1d4cc3dcc 100644 --- a/main/mqtt-gateway/README.md +++ b/main/mqtt-gateway/README.md @@ -1,78 +1,81 @@ -# MQTT+UDP 到 WebSocket 桥接服务 +# MQTT+UDP to WebSocket Bridge Service -## 项目概述 +## Project Overview -这是一个用于物联网设备通信的桥接服务,实现了MQTT和UDP协议到WebSocket的转换。该服务允许设备通过MQTT协议进行控制消息传输,同时通过UDP协议高效传输音频数据,并将这些数据桥接到WebSocket服务。 +This is a bridge service for IoT device communication that implements conversion from MQTT and UDP protocols to WebSocket. The service allows devices to transmit control messages through MQTT protocol while efficiently transmitting audio data through UDP protocol, bridging this data to WebSocket services. -## 功能特点 +## Features -- **多协议支持**: 同时支持MQTT、UDP和WebSocket协议 -- **音频数据传输**: 专为音频数据流优化的传输机制 -- **加密通信**: 使用AES-128-CTR加密UDP数据传输 -- **会话管理**: 完整的设备会话生命周期管理 -- **自动重连**: 连接断开时自动重连机制 -- **心跳检测**: 定期检查连接活跃状态 -- **开发/生产环境配置**: 支持不同环境的配置切换 +- **Multi-protocol Support**: Simultaneous support for MQTT, UDP, and WebSocket protocols +- **Audio Data Transmission**: Transmission mechanism optimized for audio data streams +- **Encrypted Communication**: Uses AES-128-CTR encryption for UDP data transmission +- **Session Management**: Complete device session lifecycle management +- **Auto Reconnection**: Automatic reconnection mechanism when connections are lost +- **Heartbeat Detection**: Periodic checking of connection active status +- **Development/Production Environment Configuration**: Support for configuration switching between different environments -## 技术架构 +## Technical Architecture -- **MQTT服务器**: 处理设备控制消息 -- **UDP服务器**: 处理高效的音频数据传输 -- **WebSocket客户端**: 连接到聊天服务器 -- **桥接层**: 在不同协议间转换和路由消息 +- **MQTT Server**: Handles device control messages +- **UDP Server**: Handles efficient audio data transmission +- **WebSocket Client**: Connects to chat servers +- **Bridge Layer**: Converts and routes messages between different protocols -## 项目结构 +## Project Structure ``` -├── app.js # 主应用入口 -├── mqtt-protocol.js # MQTT协议实现 -├── ecosystem.config.js # PM2配置文件 -├── package.json # 项目依赖 -├── .env # 环境变量配置 +├── app.js # Main application entry point +├── mqtt-protocol.js # MQTT protocol implementation +├── ecosystem.config.js # PM2 configuration file +├── package.json # Project dependencies +├── .env # Environment variable configuration ├── utils/ -│ ├── config-manager.js # 配置管理工具 -│ ├── mqtt_config_v2.js # MQTT配置验证工具 -│ └── weixinAlert.js # 微信告警工具 -└── config/ # 配置文件目录 +│ ├── config-manager.js # Configuration management tool +│ ├── mqtt_config_v2.js # MQTT configuration validation tool +│ └── weixinAlert.js # WeChat alert tool +└── config/ # Configuration file directory ``` -## 依赖项 +## Dependencies -- **debug**: 调试日志输出 -- **dotenv**: 环境变量管理 -- **ws**: WebSocket客户端 -- **events**: Node.js 事件模块 +- **debug**: Debug log output +- **dotenv**: Environment variable management +- **ws**: WebSocket client +- **events**: Node.js event module -## 安装要求 +## Installation Requirements -- Node.js 14.x 或更高版本 -- npm 或 yarn 包管理器 -- PM2 (用于生产环境部署) +- Node.js 14.x or higher +- npm or yarn package manager +- PM2 (for production environment deployment) -## 安装步骤 +## Installation Steps + +1. Clone repository -1. 克隆仓库 ```bash -git clone <仓库地址> +git clone cd mqtt-websocket-bridge ``` -2. 安装依赖 +2. Install dependencies + ```bash npm install ``` -3. 创建配置文件 +3. Create configuration file + ```bash mkdir -p config cp config/mqtt.json.example config/mqtt.json ``` -4. 编辑配置文件 `config/mqtt.json`,设置适当的参数 +4. Edit configuration file `config/mqtt.json` and set appropriate parameters -## 配置说明 +## Configuration Instructions -配置文件 `config/mqtt.json` 需要包含以下内容: +Configuration file `config/mqtt.json` needs to contain the following content: ```json { @@ -87,63 +90,65 @@ cp config/mqtt.json.example config/mqtt.json } ``` -## 环境变量 +## Environment Variables -创建 `.env` 文件并设置以下环境变量: +Create `.env` file and set the following environment variables: ``` -MQTT_PORT=1883 # MQTT服务器端口 -UDP_PORT=8884 # UDP服务器端口 -PUBLIC_IP=your-ip # 服务器公网IP +MQTT_PORT=1883 # MQTT server port +UDP_PORT=8884 # UDP server port +PUBLIC_IP=your-ip # Server public IP ``` -## 运行服务 +## Running the Service -### 开发环境 +### Development Environment ```bash -# 直接运行 +# Run directly node app.js -# 调试模式运行 +# Run in debug mode DEBUG=mqtt-server node app.js ``` -### 生产环境 (使用PM2) +### Production Environment (Using PM2) ```bash -# 安装PM2 +# Install PM2 npm install -g pm2 -# 启动服务 +# Start service pm2 start ecosystem.config.js -# 查看日志 +# View logs pm2 logs xz-mqtt -# 监控服务 +# Monitor service pm2 monit ``` -服务将在以下端口启动: -- MQTT 服务器: 端口 1883 (可通过环境变量修改) -- UDP 服务器: 端口 8884 (可通过环境变量修改) +The service will start on the following ports: -## 协议说明 +- MQTT Server: Port 1883 (can be modified via environment variables) +- UDP Server: Port 8884 (can be modified via environment variables) -### 设备连接流程 +## Protocol Description -1. 设备通过MQTT协议连接到服务器 -2. 设备发送 `hello` 消息,包含音频参数和特性 -3. 服务器创建WebSocket连接到聊天服务器 -4. 服务器返回UDP连接参数给设备 -5. 设备通过UDP发送音频数据 -6. 服务器将音频数据转发到WebSocket -7. WebSocket返回的控制消息通过MQTT发送给设备 +### Device Connection Flow -### 消息格式 +1. Device connects to server via MQTT protocol +2. Device sends `hello` message containing audio parameters and features +3. Server creates WebSocket connection to chat server +4. Server returns UDP connection parameters to device +5. Device sends audio data via UDP +6. Server forwards audio data to WebSocket +7. Control messages returned by WebSocket are sent to device via MQTT + +### Message Format + +#### Hello Message (Device -> Server) -#### Hello 消息 (设备 -> 服务器) ```json { "type": "hello", @@ -153,7 +158,8 @@ pm2 monit } ``` -#### Hello 响应 (服务器 -> 设备) +#### Hello Response (Server -> Device) + ```json { "type": "hello", @@ -171,45 +177,45 @@ pm2 monit } ``` -## 安全说明 +## Security Description -- UDP通信使用AES-128-CTR加密 -- 每个会话使用唯一的加密密钥 -- 使用序列号防止重放攻击 -- 设备通过MAC地址进行身份验证 -- 支持设备分组和UUID验证 +- UDP communication uses AES-128-CTR encryption +- Each session uses a unique encryption key +- Uses sequence numbers to prevent replay attacks +- Device authentication via MAC address +- Supports device grouping and UUID verification -## 性能优化 +## Performance Optimization -- 使用预分配的缓冲区减少内存分配 -- UDP协议用于高效传输音频数据 -- 定期清理不活跃的连接 -- 连接数和活跃连接数监控 -- 支持多聊天服务器负载均衡 +- Uses pre-allocated buffers to reduce memory allocation +- UDP protocol for efficient audio data transmission +- Periodic cleanup of inactive connections +- Connection count and active connection monitoring +- Support for multi-chat server load balancing -## 故障排除 +## Troubleshooting -- 检查设备MAC地址格式是否正确 -- 确保UDP端口在防火墙中开放 -- 启用调试模式查看详细日志 -- 检查配置文件中的聊天服务器地址是否正确 -- 验证设备认证信息是否正确 +- Check if device MAC address format is correct +- Ensure UDP port is open in firewall +- Enable debug mode to view detailed logs +- Check if chat server address in configuration file is correct +- Verify device authentication information is correct -## 开发指南 +## Development Guide -### 添加新功能 +### Adding New Features -1. 修改 `mqtt-protocol.js` 以支持新的MQTT功能 -2. 在 `MQTTConnection` 类中添加新的消息处理方法 -3. 更新配置管理器以支持新的配置选项 -4. 在 `WebSocketBridge` 类中添加新的WebSocket处理逻辑 +1. Modify `mqtt-protocol.js` to support new MQTT functionality +2. Add new message handling methods in `MQTTConnection` class +3. Update configuration manager to support new configuration options +4. Add new WebSocket handling logic in `WebSocketBridge` class -### 调试技巧 +### Debugging Tips ```bash -# 启用所有调试输出 +# Enable all debug output DEBUG=* node app.js -# 只启用MQTT服务器调试 +# Enable only MQTT server debugging DEBUG=mqtt-server node app.js ``` diff --git a/main/mqtt-gateway/app.js b/main/mqtt-gateway/app.js index 962fab54a..9465c5c0a 100644 --- a/main/mqtt-gateway/app.js +++ b/main/mqtt-gateway/app.js @@ -1,645 +1,739 @@ -// Description: MQTT+UDP 到 WebSocket 的桥接 +// Description: MQTT+UDP to WebSocket bridge // Author: terrence@tenclass.com // Date: 2025-03-12 -require('dotenv').config(); -const net = require('net'); -const debugModule = require('debug'); -const debug = debugModule('mqtt-server'); -const crypto = require('crypto'); -const dgram = require('dgram'); -const Emitter = require('events'); -const WebSocket = require('ws'); -const { MQTTProtocol } = require('./mqtt-protocol'); -const { ConfigManager } = require('./utils/config-manager'); -const { validateMqttCredentials } = require('./utils/mqtt_config_v2'); +require("dotenv").config(); +const net = require("net"); +const debugModule = require("debug"); +const debug = debugModule("mqtt-server"); +const crypto = require("crypto"); +const dgram = require("dgram"); +const Emitter = require("events"); +const WebSocket = require("ws"); +const { MQTTProtocol } = require("./mqtt-protocol"); +const { ConfigManager } = require("./utils/config-manager"); +const { validateMqttCredentials } = require("./utils/mqtt_config_v2"); function setDebugEnabled(enabled) { - if (enabled) { - debugModule.enable('mqtt-server'); - } else { - debugModule.disable(); - } + if (enabled) { + debugModule.enable("mqtt-server"); + } else { + debugModule.disable(); + } } -const configManager = new ConfigManager('mqtt.json'); -configManager.on('configChanged', (config) => { - setDebugEnabled(config.debug); +const configManager = new ConfigManager("mqtt.json"); +configManager.on("configChanged", (config) => { + setDebugEnabled(config.debug); }); - -setDebugEnabled(configManager.get('debug')); +setDebugEnabled(configManager.get("debug")); class WebSocketBridge extends Emitter { - constructor(connection, protocolVersion, macAddress, uuid, userData) { - super(); - this.connection = connection; - this.macAddress = macAddress; - this.uuid = uuid; - this.userData = userData; - this.wsClient = null; - this.protocolVersion = protocolVersion; - this.deviceSaidGoodbye = false; - this.initializeChatServer(); + constructor(connection, protocolVersion, macAddress, uuid, userData) { + super(); + this.connection = connection; + this.macAddress = macAddress; + this.uuid = uuid; + this.userData = userData; + this.wsClient = null; + this.protocolVersion = protocolVersion; + this.deviceSaidGoodbye = false; + this.initializeChatServer(); + } + + initializeChatServer() { + const devMacAddresss = configManager.get("development")?.mac_addresss || []; + let chatServers; + if (devMacAddresss.includes(this.macAddress)) { + chatServers = configManager.get("development")?.chat_servers; + } else { + chatServers = configManager.get("production")?.chat_servers; } - initializeChatServer() { - const devMacAddresss = configManager.get('development')?.mac_addresss || []; - let chatServers; - if (devMacAddresss.includes(this.macAddress)) { - chatServers = configManager.get('development')?.chat_servers; - } else { - chatServers = configManager.get('production')?.chat_servers; - } - if (!chatServers) { - throw new Error(`未找到 ${this.macAddress} 的聊天服务器`); - } - this.chatServer = chatServers[Math.floor(Math.random() * chatServers.length)]; + if (!chatServers) { + throw new Error(`Chat server not found for ${this.macAddress}`); } - async connect(audio_params, features) { - return new Promise((resolve, reject) => { - const headers = { - 'device-id': this.macAddress, - 'protocol-version': '2', - 'authorization': `Bearer test-token` - }; - if (this.uuid) { - headers['client-id'] = this.uuid; - } - if (this.userData && this.userData.ip) { - headers['x-forwarded-for'] = this.userData.ip; - } - this.wsClient = new WebSocket(this.chatServer, { headers }); + this.chatServer = + chatServers[Math.floor(Math.random() * chatServers.length)]; + } - this.wsClient.on('open', () => { - this.sendJson({ - type: 'hello', - version: 2, - transport: 'websocket', - audio_params, - features - }); - }); + async connect(audio_params, features) { + return new Promise((resolve, reject) => { + const headers = { + "device-id": this.macAddress, + "protocol-version": "2", + authorization: `Bearer test-token`, + }; + if (this.uuid) { + headers["client-id"] = this.uuid; + } - this.wsClient.on('message', (data, isBinary) => { - if (isBinary) { - // xiaozhi-server sends raw Opus data directly as binary WebSocket messages - // No header parsing needed - the entire binary message is the Opus payload - console.log(`📦 WebSocket binary message: ${data.length} bytes of raw Opus data`); - console.log(`📦 First 8 bytes: ${data.subarray(0, Math.min(8, data.length)).toString('hex')}`); + if (this.userData && this.userData.ip) { + headers["x-forwarded-for"] = this.userData.ip; + } - // Generate timestamp for UDP packet (use relative timestamp to fit in 32-bit) - const timestamp = (Date.now() - this.connection.udp.startTime) & 0xFFFFFFFF; + this.wsClient = new WebSocket(this.chatServer, { headers }); - // Send the raw Opus data directly via UDP - this.connection.sendUdpMessage(data, timestamp); - } else { - // JSON数据通过MQTT发送 - const message = JSON.parse(data.toString()); - if (message.type === 'hello') { - resolve(message); - } else { - this.connection.sendMqttMessage(JSON.stringify(message)); - } - } - }); - - this.wsClient.on('error', (error) => { - console.error(`WebSocket error for device ${this.macAddress}:`, error); - this.emit('close'); - reject(error); - }); - - this.wsClient.on('close', () => { - this.emit('close'); - }); + this.wsClient.on("open", () => { + this.sendJson({ + type: "hello", + version: 2, + transport: "websocket", + audio_params, + features, }); - } + }); - sendJson(message) { - if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) { - this.wsClient.send(JSON.stringify(message)); + this.wsClient.on("message", (data, isBinary) => { + if (isBinary) { + // xiaozhi-server sends raw Opus data directly as binary WebSocket messages + // No header parsing needed - the entire binary message is the Opus payload + console.log( + `📦 WebSocket binary message: ${data.length} bytes of raw Opus data` + ); + console.log( + `📦 First 8 bytes: ${data + .subarray(0, Math.min(8, data.length)) + .toString("hex")}` + ); + // Generate timestamp for UDP packet (use relative timestamp to fit in 32-bit) + const timestamp = + (Date.now() - this.connection.udp.startTime) & 0xffffffff; + // Send the raw Opus data directly via UDP + this.connection.sendUdpMessage(data, timestamp); + } else { + // JSON data sent via MQTT + const message = JSON.parse(data.toString()); + if (message.type === "hello") { + resolve(message); + } else { + this.connection.sendMqttMessage(JSON.stringify(message)); + } } - } + }); - sendAudio(opus, timestamp) { - if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) { - // Send raw Opus data directly without header - // This avoids the need to strip headers in xiaozhi-server - this.wsClient.send(opus, { binary: true }); - } - } + this.wsClient.on("error", (error) => { + console.error(`WebSocket error for device ${this.macAddress}:`, error); + this.emit("close"); + reject(error); + }); - isAlive() { - return this.wsClient && this.wsClient.readyState === WebSocket.OPEN; - } + this.wsClient.on("close", () => { + this.emit("close"); + }); + }); + } - close() { - if (this.wsClient) { - this.wsClient.close(); - this.wsClient = null; - } + sendJson(message) { + if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) { + this.wsClient.send(JSON.stringify(message)); } + } + + sendAudio(opus, timestamp) { + if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) { + // Send raw Opus data directly without header + // This avoids the need to strip headers in xiaozhi-server + this.wsClient.send(opus, { binary: true }); + } + } + + isAlive() { + return this.wsClient && this.wsClient.readyState === WebSocket.OPEN; + } + + close() { + if (this.wsClient) { + this.wsClient.close(); + this.wsClient = null; + } + } } const MacAddressRegex = /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/; /** - * MQTT连接类 - * 负责应用层逻辑处理 + * MQTT connection class + * Responsible for application layer logic processing */ class MQTTConnection { - constructor(socket, connectionId, server) { - this.server = server; - this.connectionId = connectionId; - this.clientId = null; - this.username = null; - this.password = null; - this.bridge = null; - this.udp = { - remoteAddress: null, - cookie: null, - localSequence: 0, - remoteSequence: 0 - }; - this.headerBuffer = Buffer.alloc(16); + constructor(socket, connectionId, server) { + this.server = server; + this.connectionId = connectionId; + this.clientId = null; + this.username = null; + this.password = null; + this.bridge = null; + this.udp = { + remoteAddress: null, + cookie: null, + localSequence: 0, + remoteSequence: 0, + }; + this.headerBuffer = Buffer.alloc(16); - // 创建协议处理器,并传入socket - this.protocol = new MQTTProtocol(socket); + // Create protocol handler and pass in socket + this.protocol = new MQTTProtocol(socket); + this.setupProtocolHandlers(); + } - this.setupProtocolHandlers(); + setupProtocolHandlers() { + // Set protocol event handlers + this.protocol.on("connect", (connectData) => { + this.handleConnect(connectData); + }); + + this.protocol.on("publish", (publishData) => { + this.handlePublish(publishData); + }); + + this.protocol.on("subscribe", (subscribeData) => { + this.handleSubscribe(subscribeData); + }); + + this.protocol.on("disconnect", () => { + this.handleDisconnect(); + }); + + this.protocol.on("close", () => { + debug(`${this.clientId} client disconnected`); + this.server.removeConnection(this); + }); + + this.protocol.on("error", (err) => { + debug(`${this.clientId} connection error:`, err); + this.close(); + }); + + this.protocol.on("protocolError", (err) => { + debug(`${this.clientId} protocol error:`, err); + this.close(); + }); + } + + handleConnect(connectData) { + this.clientId = connectData.clientId; + this.username = connectData.username; + this.password = connectData.password; + + debug("Client connected:", { + clientId: this.clientId, + username: this.username, + password: this.password, + protocol: connectData.protocol, + protocolLevel: connectData.protocolLevel, + keepAlive: connectData.keepAlive, + }); + + const parts = this.clientId.split("@@@"); + if (parts.length === 3) { + // GID_test@@@mac_address@@@uuid + try { + const validated = validateMqttCredentials( + this.clientId, + this.username, + this.password + ); + this.groupId = validated.groupId; + this.macAddress = validated.macAddress; + this.uuid = validated.uuid; + this.userData = validated.userData; + } catch (error) { + debug("MQTT credentials validation failed:", error.message); + this.close(); + return; + } + } else if (parts.length === 2) { + // GID_test@@@mac_address + this.groupId = parts[0]; + this.macAddress = parts[1].replace(/_/g, ":"); + if (!MacAddressRegex.test(this.macAddress)) { + debug("Invalid macAddress:", this.macAddress); + this.close(); + return; + } + } else { + debug("Invalid clientId:", this.clientId); + this.close(); + return; } - setupProtocolHandlers() { - // 设置协议事件处理 - this.protocol.on('connect', (connectData) => { - this.handleConnect(connectData); - }); + this.replyTo = `devices/p2p/${parts[1]}`; + this.server.addConnection(this); + } - this.protocol.on('publish', (publishData) => { - this.handlePublish(publishData); - }); + handleSubscribe(subscribeData) { + debug("Client subscribed to topic:", { + clientId: this.clientId, + topic: subscribeData.topic, + packetId: subscribeData.packetId, + }); + // Send SUBACK + this.protocol.sendSuback(subscribeData.packetId, 0); + } - this.protocol.on('subscribe', (subscribeData) => { - this.handleSubscribe(subscribeData); - }); + handleDisconnect() { + debug("Received disconnect request:", { clientId: this.clientId }); + // Clean up connection + this.server.removeConnection(this); + } - this.protocol.on('disconnect', () => { - this.handleDisconnect(); - }); + close() { + this.closing = true; + if (this.bridge) { + this.bridge.close(); + this.bridge = null; + } else { + this.protocol.close(); + } + } - this.protocol.on('close', () => { - debug(`${this.clientId} 客户端断开连接`); - this.server.removeConnection(this); - }); + checkKeepAlive() { + const now = Date.now(); + const keepAliveInterval = this.protocol.getKeepAliveInterval(); + // If keepAliveInterval is 0, heartbeat check is not needed + if (keepAliveInterval === 0 || !this.protocol.isConnected) return; - this.protocol.on('error', (err) => { - debug(`${this.clientId} 连接错误:`, err); - this.close(); - }); + const lastActivity = this.protocol.getLastActivity(); + const timeSinceLastActivity = now - lastActivity; - this.protocol.on('protocolError', (err) => { - debug(`${this.clientId} 协议错误:`, err); - this.close(); - }); + // If heartbeat interval is exceeded, close connection + if (timeSinceLastActivity > keepAliveInterval) { + debug("Heartbeat timeout, closing connection:", this.clientId); + this.close(); + } + } + + handlePublish(publishData) { + debug("Received publish message:", { + clientId: this.clientId, + topic: publishData.topic, + payload: publishData.payload, + qos: publishData.qos, + }); + + if (publishData.qos !== 0) { + debug("Unsupported QoS level:", publishData.qos, "closing connection"); + this.close(); + return; } - handleConnect(connectData) { - this.clientId = connectData.clientId; - this.username = connectData.username; - this.password = connectData.password; + const json = JSON.parse(publishData.payload); + if (json.type === "hello") { + if (json.version !== 3) { + debug( + "Unsupported protocol version:", + json.version, + "closing connection" + ); + this.close(); + return; + } - debug('客户端连接:', { - clientId: this.clientId, - username: this.username, - password: this.password, - protocol: connectData.protocol, - protocolLevel: connectData.protocolLevel, - keepAlive: connectData.keepAlive - }); + this.parseHelloMessage(json).catch((error) => { + debug("Failed to process hello message:", error); + this.close(); + }); + } else { + this.parseOtherMessage(json).catch((error) => { + debug("Failed to process other message:", error); + this.close(); + }); + } + } - const parts = this.clientId.split('@@@'); - if (parts.length === 3) { // GID_test@@@mac_address@@@uuid - try { - const validated = validateMqttCredentials(this.clientId, this.username, this.password); - this.groupId = validated.groupId; - this.macAddress = validated.macAddress; - this.uuid = validated.uuid; - this.userData = validated.userData; - } catch (error) { - debug('MQTT凭据验证失败:', error.message); - this.close(); - return; - } - } else if (parts.length === 2) { // GID_test@@@mac_address - this.groupId = parts[0]; - this.macAddress = parts[1].replace(/_/g, ':'); - if (!MacAddressRegex.test(this.macAddress)) { - debug('无效的 macAddress:', this.macAddress); - this.close(); - return; - } - } else { - debug('无效的 clientId:', this.clientId); - this.close(); - return; - } - this.replyTo = `devices/p2p/${parts[1]}`; + sendMqttMessage(payload) { + debug(`Sending message to ${this.replyTo}: ${payload}`); + this.protocol.sendPublish(this.replyTo, payload, 0, false, false); + } - this.server.addConnection(this); + sendUdpMessage(payload, timestamp) { + if (!this.udp.remoteAddress) { + debug(`Device ${this.clientId} not connected, cannot send UDP message`); + return; } - handleSubscribe(subscribeData) { - debug('客户端订阅主题:', { - clientId: this.clientId, - topic: subscribeData.topic, - packetId: subscribeData.packetId - }); + this.udp.localSequence++; + const header = this.generateUdpHeader( + payload.length, + timestamp, + this.udp.localSequence + ); + console.log( + `🔐 Encrypting: payload=${payload.length}B, timestamp=${timestamp}, seq=${this.udp.localSequence}` + ); + console.log(`🔐 Header: ${header.toString("hex")}`); + console.log(`🔐 Key: ${this.udp.key.toString("hex")}`); + console.log( + `🔐 Payload first 8 bytes: ${payload.subarray(0, 8).toString("hex")}` + ); + const cipher = crypto.createCipheriv( + this.udp.encryption, + this.udp.key, + header + ); + const encryptedPayload = Buffer.concat([ + cipher.update(payload), + cipher.final(), + ]); + console.log( + `🔐 Encrypted first 8 bytes: ${encryptedPayload + .subarray(0, 8) + .toString("hex")}` + ); + const message = Buffer.concat([header, encryptedPayload]); + this.server.sendUdpMessage(message, this.udp.remoteAddress); + } - // 发送 SUBACK - this.protocol.sendSuback(subscribeData.packetId, 0); + generateUdpHeader(length, timestamp, sequence) { + // Reuse pre-allocated buffer + this.headerBuffer.writeUInt8(1, 0); // packet_type + this.headerBuffer.writeUInt8(0, 1); // flags + this.headerBuffer.writeUInt16BE(length, 2); // payload_len + this.headerBuffer.writeUInt32BE(this.connectionId, 4); // ssrc/connection_id + this.headerBuffer.writeUInt32BE(timestamp, 8); // timestamp + this.headerBuffer.writeUInt32BE(sequence, 12); // sequence + return Buffer.from(this.headerBuffer); // Return copy to avoid concurrency issues + } + + async parseHelloMessage(json) { + this.udp = { + ...this.udp, + key: crypto.randomBytes(16), + nonce: this.generateUdpHeader(0, 0, 0), + encryption: "aes-128-ctr", + remoteSequence: 0, + localSequence: 0, + startTime: Date.now(), + }; + + if (this.bridge) { + debug( + `${this.clientId} received duplicate hello message, closing previous bridge` + ); + this.bridge.close(); + await new Promise((resolve) => setTimeout(resolve, 100)); } - handleDisconnect() { - debug('收到断开连接请求:', { clientId: this.clientId }); - // 清理连接 - this.server.removeConnection(this); + this.bridge = new WebSocketBridge( + this, + json.version, + this.macAddress, + this.uuid, + this.userData + ); + this.bridge.on("close", () => { + const seconds = (Date.now() - this.udp.startTime) / 1000; + console.log( + `Call ended: ${this.clientId} Session: ${this.udp.session_id} Duration: ${seconds}s` + ); + this.sendMqttMessage( + JSON.stringify({ type: "goodbye", session_id: this.udp.session_id }) + ); + this.bridge = null; + if (this.closing) { + this.protocol.close(); + } + }); + + try { + console.log( + `Call started: ${this.clientId} Protocol: ${json.version} ${this.bridge.chatServer}` + ); + const helloReply = await this.bridge.connect( + json.audio_params, + json.features + ); + this.udp.session_id = helloReply.session_id; + + this.sendMqttMessage( + JSON.stringify({ + type: "hello", + version: json.version, + session_id: this.udp.session_id, + transport: "udp", + udp: { + server: this.server.publicIp, + port: this.server.udpPort, + encryption: this.udp.encryption, + key: this.udp.key.toString("hex"), + nonce: this.udp.nonce.toString("hex"), + }, + audio_params: helloReply.audio_params, + }) + ); + } catch (error) { + this.sendMqttMessage( + JSON.stringify({ + type: "error", + message: "Failed to process hello message", + }) + ); + console.error( + `${this.clientId} failed to process hello message: ${error}` + ); + } + } + + async parseOtherMessage(json) { + if (!this.bridge) { + if (json.type !== "goodbye") { + this.sendMqttMessage( + JSON.stringify({ type: "goodbye", session_id: json.session_id }) + ); + } + return; } - close() { - this.closing = true; - if (this.bridge) { - this.bridge.close(); - this.bridge = null; - } else { - this.protocol.close(); - } + if (json.type === "goodbye") { + this.bridge.close(); + this.bridge = null; + return; } - checkKeepAlive() { - const now = Date.now(); - const keepAliveInterval = this.protocol.getKeepAliveInterval(); + this.bridge.sendJson(json); + } - // 如果keepAliveInterval为0,表示不需要心跳检查 - if (keepAliveInterval === 0 || !this.protocol.isConnected) return; - - const lastActivity = this.protocol.getLastActivity(); - const timeSinceLastActivity = now - lastActivity; - - // 如果超过心跳间隔,关闭连接 - if (timeSinceLastActivity > keepAliveInterval) { - debug('心跳超时,关闭连接:', this.clientId); - this.close(); - } + onUdpMessage(rinfo, message, payloadLength, timestamp, sequence) { + if (!this.bridge) { + return; } - handlePublish(publishData) { - debug('收到发布消息:', { - clientId: this.clientId, - topic: publishData.topic, - payload: publishData.payload, - qos: publishData.qos - }); - - if (publishData.qos !== 0) { - debug('不支持的 QoS 级别:', publishData.qos, '关闭连接'); - this.close(); - return; - } - - const json = JSON.parse(publishData.payload); - if (json.type === 'hello') { - if (json.version !== 3) { - debug('不支持的协议版本:', json.version, '关闭连接'); - this.close(); - return; - } - this.parseHelloMessage(json).catch(error => { - debug('处理 hello 消息失败:', error); - this.close(); - }); - } else { - this.parseOtherMessage(json).catch(error => { - debug('处理其他消息失败:', error); - this.close(); - }); - } + if (this.udp.remoteAddress !== rinfo) { + this.udp.remoteAddress = rinfo; } - sendMqttMessage(payload) { - debug(`发送消息到 ${this.replyTo}: ${payload}`); - this.protocol.sendPublish(this.replyTo, payload, 0, false, false); + if (sequence < this.udp.remoteSequence) { + return; } - sendUdpMessage(payload, timestamp) { - if (!this.udp.remoteAddress) { - debug(`设备 ${this.clientId} 未连接,无法发送 UDP 消息`); - return; - } - this.udp.localSequence++; - const header = this.generateUdpHeader(payload.length, timestamp, this.udp.localSequence); + // Process encrypted data + const header = message.slice(0, 16); + const encryptedPayload = message.slice(16, 16 + payloadLength); + const cipher = crypto.createDecipheriv( + this.udp.encryption, + this.udp.key, + header + ); + const payload = Buffer.concat([ + cipher.update(encryptedPayload), + cipher.final(), + ]); - console.log(`🔐 Encrypting: payload=${payload.length}B, timestamp=${timestamp}, seq=${this.udp.localSequence}`); - console.log(`🔐 Header: ${header.toString('hex')}`); - console.log(`🔐 Key: ${this.udp.key.toString('hex')}`); - console.log(`🔐 Payload first 8 bytes: ${payload.subarray(0, 8).toString('hex')}`); - - const cipher = crypto.createCipheriv(this.udp.encryption, this.udp.key, header); - const encryptedPayload = Buffer.concat([cipher.update(payload), cipher.final()]); - - console.log(`🔐 Encrypted first 8 bytes: ${encryptedPayload.subarray(0, 8).toString('hex')}`); - - const message = Buffer.concat([header, encryptedPayload]); - this.server.sendUdpMessage(message, this.udp.remoteAddress); + // Check if this is a ping message + const payloadStr = payload.toString(); + if (payloadStr.startsWith("ping:")) { + debug( + `Received UDP ping message: ${payloadStr} from ${rinfo.address}:${rinfo.port}` + ); + // Ping message received, connection is now established + return; } - generateUdpHeader(length, timestamp, sequence) { - // 重用预分配的缓冲区 - this.headerBuffer.writeUInt8(1, 0); // packet_type - this.headerBuffer.writeUInt8(0, 1); // flags - this.headerBuffer.writeUInt16BE(length, 2); // payload_len - this.headerBuffer.writeUInt32BE(this.connectionId, 4); // ssrc/connection_id - this.headerBuffer.writeUInt32BE(timestamp, 8); // timestamp - this.headerBuffer.writeUInt32BE(sequence, 12); // sequence - return Buffer.from(this.headerBuffer); // 返回副本以避免并发问题 - } + this.bridge.sendAudio(payload, timestamp); + this.udp.remoteSequence = sequence; + } - async parseHelloMessage(json) { - this.udp = { - ...this.udp, - key: crypto.randomBytes(16), - nonce: this.generateUdpHeader(0, 0, 0), - encryption: 'aes-128-ctr', - remoteSequence: 0, - localSequence: 0, - startTime: Date.now() - } - - if (this.bridge) { - debug(`${this.clientId} 收到重复 hello 消息,关闭之前的 bridge`); - this.bridge.close(); - await new Promise(resolve => setTimeout(resolve, 100)); - } - this.bridge = new WebSocketBridge(this, json.version, this.macAddress, this.uuid, this.userData); - this.bridge.on('close', () => { - const seconds = (Date.now() - this.udp.startTime) / 1000; - console.log(`通话结束: ${this.clientId} Session: ${this.udp.session_id} Duration: ${seconds}s`); - this.sendMqttMessage(JSON.stringify({ type: 'goodbye', session_id: this.udp.session_id })); - this.bridge = null; - if (this.closing) { - this.protocol.close(); - } - }); - - try { - console.log(`通话开始: ${this.clientId} Protocol: ${json.version} ${this.bridge.chatServer}`); - const helloReply = await this.bridge.connect(json.audio_params, json.features); - this.udp.session_id = helloReply.session_id; - this.sendMqttMessage(JSON.stringify({ - type: 'hello', - version: json.version, - session_id: this.udp.session_id, - transport: 'udp', - udp: { - server: this.server.publicIp, - port: this.server.udpPort, - encryption: this.udp.encryption, - key: this.udp.key.toString('hex'), - nonce: this.udp.nonce.toString('hex'), - }, - audio_params: helloReply.audio_params - })); - } catch (error) { - this.sendMqttMessage(JSON.stringify({ type: 'error', message: '处理 hello 消息失败' })); - console.error(`${this.clientId} 处理 hello 消息失败: ${error}`); - } - } - - async parseOtherMessage(json) { - if (!this.bridge) { - if (json.type !== 'goodbye') { - this.sendMqttMessage(JSON.stringify({ type: 'goodbye', session_id: json.session_id })); - } - return; - } - - if (json.type === 'goodbye') { - this.bridge.close(); - this.bridge = null; - return; - } - - this.bridge.sendJson(json); - } - - onUdpMessage(rinfo, message, payloadLength, timestamp, sequence) { - if (!this.bridge) { - return; - } - if (this.udp.remoteAddress !== rinfo) { - this.udp.remoteAddress = rinfo; - } - if (sequence < this.udp.remoteSequence) { - return; - } - - // 处理加密数据 - const header = message.slice(0, 16); - const encryptedPayload = message.slice(16, 16 + payloadLength); - const cipher = crypto.createDecipheriv(this.udp.encryption, this.udp.key, header); - const payload = Buffer.concat([cipher.update(encryptedPayload), cipher.final()]); - - // Check if this is a ping message - const payloadStr = payload.toString(); - if (payloadStr.startsWith('ping:')) { - debug(`收到 UDP ping 消息: ${payloadStr} from ${rinfo.address}:${rinfo.port}`); - // Ping message received, connection is now established - return; - } - - this.bridge.sendAudio(payload, timestamp); - this.udp.remoteSequence = sequence; - } - - isAlive() { - return this.bridge && this.bridge.isAlive(); - } + isAlive() { + return this.bridge && this.bridge.isAlive(); + } } class MQTTServer { - constructor() { - this.mqttPort = parseInt(process.env.MQTT_PORT) || 1883; - this.udpPort = parseInt(process.env.UDP_PORT) || this.mqttPort; - this.publicIp = process.env.PUBLIC_IP || 'broker.emqx.io'; - this.connections = new Map(); // clientId -> MQTTConnection - this.keepAliveTimer = null; - this.keepAliveCheckInterval = 1000; // 默认每1秒检查一次 + constructor() { + this.mqttPort = parseInt(process.env.MQTT_PORT) || 1883; + this.udpPort = parseInt(process.env.UDP_PORT) || this.mqttPort; + this.publicIp = process.env.PUBLIC_IP || "broker.emqx.io"; + this.connections = new Map(); // clientId -> MQTTConnection + this.keepAliveTimer = null; + this.keepAliveCheckInterval = 1000; // Check every 1 second by default + this.headerBuffer = Buffer.alloc(16); + } - this.headerBuffer = Buffer.alloc(16); + generateNewConnectionId() { + // Generate a unique 32-bit integer + let id; + do { + id = Math.floor(Math.random() * 0xffffffff); + } while (this.connections.has(id)); + return id; + } + + start() { + this.mqttServer = net.createServer((socket) => { + const connectionId = this.generateNewConnectionId(); + debug(`New client connection: ${connectionId}`); + new MQTTConnection(socket, connectionId, this); + }); + + this.mqttServer.listen(this.mqttPort, "0.0.0.0", () => { + console.warn( + `MQTT server listening on port ${this.mqttPort} (all interfaces)` + ); + }); + + this.udpServer = dgram.createSocket("udp4"); + this.udpServer.on("message", this.onUdpMessage.bind(this)); + this.udpServer.on("error", (err) => { + console.error("UDP error", err); + setTimeout(() => { + process.exit(1); + }, 1000); + }); + + this.udpServer.bind(this.udpPort, () => { + console.warn(`UDP server listening on ${this.publicIp}:${this.udpPort}`); + }); + + // Start global heartbeat check timer + this.setupKeepAliveTimer(); + } + + /** + * Set up global heartbeat check timer + */ + setupKeepAliveTimer() { + // Clear existing timer + this.clearKeepAliveTimer(); + this.lastConnectionCount = 0; + this.lastActiveConnectionCount = 0; + + // Set new timer + this.keepAliveTimer = setInterval(() => { + // Check heartbeat status of all connections + for (const connection of this.connections.values()) { + connection.checkKeepAlive(); + } + + const activeCount = Array.from(this.connections.values()).filter( + (connection) => connection.isAlive() + ).length; + if ( + activeCount !== this.lastActiveConnectionCount || + this.connections.size !== this.lastConnectionCount + ) { + console.log( + `Connections: ${this.connections.size}, Active: ${activeCount}` + ); + this.lastActiveConnectionCount = activeCount; + this.lastConnectionCount = this.connections.size; + } + }, this.keepAliveCheckInterval); + } + + /** + * Clear heartbeat check timer + */ + clearKeepAliveTimer() { + if (this.keepAliveTimer) { + clearInterval(this.keepAliveTimer); + this.keepAliveTimer = null; + } + } + + addConnection(connection) { + // Check if a connection with the same clientId already exists + for (const [key, value] of this.connections.entries()) { + if (value.clientId === connection.clientId) { + debug( + `${connection.clientId} connection already exists, closing old connection` + ); + value.close(); + } + } + this.connections.set(connection.connectionId, connection); + } + + removeConnection(connection) { + debug(`Closing connection: ${connection.connectionId}`); + if (this.connections.has(connection.connectionId)) { + this.connections.delete(connection.connectionId); + } + } + + sendUdpMessage(message, remoteAddress) { + this.udpServer.send(message, remoteAddress.port, remoteAddress.address); + } + + onUdpMessage(message, rinfo) { + // message format: [type: 1u, flag: 1u, payloadLength: 2u, cookie: 4u, timestamp: 4u, sequence: 4u, payload: n] + if (message.length < 16) { + console.warn("Received incomplete UDP header", rinfo); + return; } - generateNewConnectionId() { - // 生成一个32位不重复的整数 - let id; - do { - id = Math.floor(Math.random() * 0xFFFFFFFF); - } while (this.connections.has(id)); - return id; + try { + const type = message.readUInt8(0); + if (type !== 1) return; + + const payloadLength = message.readUInt16BE(2); + if (message.length < 16 + payloadLength) return; + + const connectionId = message.readUInt32BE(4); + const connection = this.connections.get(connectionId); + if (!connection) return; + + const timestamp = message.readUInt32BE(8); + const sequence = message.readUInt32BE(12); + connection.onUdpMessage( + rinfo, + message, + payloadLength, + timestamp, + sequence + ); + } catch (error) { + console.error("UDP message processing error:", error); + } + } + + /** + * Stop server + */ + async stop() { + if (this.stopping) { + return; } - start() { - this.mqttServer = net.createServer((socket) => { - const connectionId = this.generateNewConnectionId(); - debug(`新客户端连接: ${connectionId}`); - new MQTTConnection(socket, connectionId, this); - }); + this.stopping = true; + // Clear heartbeat check timer + this.clearKeepAliveTimer(); - this.mqttServer.listen(this.mqttPort, '0.0.0.0', () => { - console.warn(`MQTT 服务器正在监听端口 ${this.mqttPort} (所有接口)`); - }); - - - this.udpServer = dgram.createSocket('udp4'); - this.udpServer.on('message', this.onUdpMessage.bind(this)); - this.udpServer.on('error', err => { - console.error('UDP 错误', err); - setTimeout(() => { process.exit(1); }, 1000); - }); - this.udpServer.bind(this.udpPort, () => { - console.warn(`UDP 服务器正在监听 ${this.publicIp}:${this.udpPort}`); - }); - - // 启动全局心跳检查定时器 - this.setupKeepAliveTimer(); + if (this.connections.size > 0) { + console.warn(`Waiting for ${this.connections.size} connections to close`); + for (const connection of this.connections.values()) { + connection.close(); + } } - /** - * 设置全局心跳检查定时器 - */ - setupKeepAliveTimer() { - // 清除现有定时器 - this.clearKeepAliveTimer(); - this.lastConnectionCount = 0; - this.lastActiveConnectionCount = 0; + await new Promise((resolve) => setTimeout(resolve, 300)); + debug("Waiting for connections to close"); + this.connections.clear(); - // 设置新的定时器 - this.keepAliveTimer = setInterval(() => { - // 检查所有连接的心跳状态 - for (const connection of this.connections.values()) { - connection.checkKeepAlive(); - } - - const activeCount = Array.from(this.connections.values()).filter(connection => connection.isAlive()).length; - if (activeCount !== this.lastActiveConnectionCount || this.connections.size !== this.lastConnectionCount) { - console.log(`连接数: ${this.connections.size}, 活跃数: ${activeCount}`); - this.lastActiveConnectionCount = activeCount; - this.lastConnectionCount = this.connections.size; - } - }, this.keepAliveCheckInterval); + if (this.udpServer) { + this.udpServer.close(); + this.udpServer = null; + console.warn("UDP server stopped"); } - /** - * 清除心跳检查定时器 - */ - clearKeepAliveTimer() { - if (this.keepAliveTimer) { - clearInterval(this.keepAliveTimer); - this.keepAliveTimer = null; - } + // Close MQTT server + if (this.mqttServer) { + this.mqttServer.close(); + this.mqttServer = null; + console.warn("MQTT server stopped"); } - addConnection(connection) { - // 检查是否已存在相同 clientId 的连接 - for (const [key, value] of this.connections.entries()) { - if (value.clientId === connection.clientId) { - debug(`${connection.clientId} 已存在连接,关闭旧连接`); - value.close(); - } - } - this.connections.set(connection.connectionId, connection); - } - - removeConnection(connection) { - debug(`关闭连接: ${connection.connectionId}`); - if (this.connections.has(connection.connectionId)) { - this.connections.delete(connection.connectionId); - } - } - - sendUdpMessage(message, remoteAddress) { - this.udpServer.send(message, remoteAddress.port, remoteAddress.address); - } - - onUdpMessage(message, rinfo) { - // message format: [type: 1u, flag: 1u, payloadLength: 2u, cookie: 4u, timestamp: 4u, sequence: 4u, payload: n] - if (message.length < 16) { - console.warn('收到不完整的 UDP Header', rinfo); - return; - } - - try { - const type = message.readUInt8(0); - if (type !== 1) return; - - const payloadLength = message.readUInt16BE(2); - if (message.length < 16 + payloadLength) return; - - const connectionId = message.readUInt32BE(4); - const connection = this.connections.get(connectionId); - if (!connection) return; - - const timestamp = message.readUInt32BE(8); - const sequence = message.readUInt32BE(12); - - connection.onUdpMessage(rinfo, message, payloadLength, timestamp, sequence); - } catch (error) { - console.error('UDP 消息处理错误:', error); - } - } - - /** - * 停止服务器 - */ - async stop() { - if (this.stopping) { - return; - } - this.stopping = true; - // 清除心跳检查定时器 - this.clearKeepAliveTimer(); - - if (this.connections.size > 0) { - console.warn(`等待 ${this.connections.size} 个连接关闭`); - for (const connection of this.connections.values()) { - connection.close(); - } - await new Promise(resolve => setTimeout(resolve, 300)); - debug('等待连接关闭完成'); - this.connections.clear(); - } - - if (this.udpServer) { - this.udpServer.close(); - this.udpServer = null; - console.warn('UDP 服务器已停止'); - } - - // 关闭MQTT服务器 - if (this.mqttServer) { - this.mqttServer.close(); - this.mqttServer = null; - console.warn('MQTT 服务器已停止'); - } - - process.exit(0); - } + process.exit(0); + } } -// 创建并启动服务器 +// Create and start server const server = new MQTTServer(); server.start(); -process.on('SIGINT', () => { - console.warn('收到 SIGINT 信号,开始关闭'); - server.stop(); + +process.on("SIGINT", () => { + console.warn("Received SIGINT signal, starting shutdown"); + server.stop(); }); diff --git a/main/mqtt-gateway/generate_signature_key.js b/main/mqtt-gateway/generate_signature_key.js index 89aa9a266..b08921a93 100644 --- a/main/mqtt-gateway/generate_signature_key.js +++ b/main/mqtt-gateway/generate_signature_key.js @@ -1,81 +1,78 @@ #!/usr/bin/env node -/** - * MQTT签名密钥生成器 - * 用于生成MQTT_SIGNATURE_KEY环境变量 - */ +/** + * MQTT signature key generator + * Used to generate MQTT_SIGNATURE_KEY environment variable + */ const crypto = require('crypto'); function generateSecureKey(length = 32) { - // 生成随机字节 + // Generate random bytes const randomBytes = crypto.randomBytes(length); - - // 转换为base64字符串 + // Convert to base64 string const base64Key = randomBytes.toString('base64'); - return base64Key; } function generateHexKey(length = 32) { - // 生成随机字节 + // Generate random bytes const randomBytes = crypto.randomBytes(length); - - // 转换为十六进制字符串 + // Convert to hexadecimal string const hexKey = randomBytes.toString('hex'); - return hexKey; } function generateUUIDKey() { - // 使用UUID v4作为密钥 + // Use UUID v4 as key const uuid = crypto.randomUUID(); return uuid; } console.log('='.repeat(60)); -console.log('MQTT签名密钥生成器'); +console.log('MQTT Signature Key Generator'); console.log('='.repeat(60)); -console.log('\n1. Base64格式密钥 (推荐):'); +console.log('\n1. Base64 format key (recommended):'); const base64Key = generateSecureKey(); -console.log(` ${base64Key}`); +console.log(` ${base64Key}`); -console.log('\n2. 十六进制格式密钥:'); +console.log('\n2. Hexadecimal format key:'); const hexKey = generateHexKey(); -console.log(` ${hexKey}`); +console.log(` ${hexKey}`); -console.log('\n3. UUID格式密钥:'); +console.log('\n3. UUID format key:'); const uuidKey = generateUUIDKey(); -console.log(` ${uuidKey}`); +console.log(` ${uuidKey}`); console.log('\n='.repeat(60)); -console.log('使用方法:'); +console.log('Usage:'); console.log('='.repeat(60)); -console.log('\n在Windows PowerShell中设置环境变量:'); + +console.log('\nSet environment variable in Windows PowerShell:'); console.log(`$env:MQTT_SIGNATURE_KEY="${base64Key}"`); -console.log('\n在Windows CMD中设置环境变量:'); +console.log('\nSet environment variable in Windows CMD:'); console.log(`set MQTT_SIGNATURE_KEY=${base64Key}`); -console.log('\n在Linux/macOS中设置环境变量:'); +console.log('\nSet environment variable in Linux/macOS:'); console.log(`export MQTT_SIGNATURE_KEY="${base64Key}"`); -console.log('\n在.env文件中设置:'); +console.log('\nSet in .env file:'); console.log(`MQTT_SIGNATURE_KEY=${base64Key}`); console.log('\n='.repeat(60)); -console.log('注意事项:'); +console.log('Notes:'); console.log('='.repeat(60)); -console.log('1. 请妥善保管生成的密钥,不要泄露给他人'); -console.log('2. 在生产环境中,建议使用更长的密钥 (64字节)'); -console.log('3. 密钥设置后需要重启MQTT服务器才能生效'); -console.log('4. 客户端连接时需要使用相同的密钥生成密码签名'); +console.log('1. Please keep the generated key secure and do not leak it to others'); +console.log('2. In production environment, longer keys are recommended (64 bytes)'); +console.log('3. MQTT server needs to be restarted after setting the key'); +console.log('4. Clients need to use the same key to generate password signatures when connecting'); -// 如果提供了命令行参数,生成指定长度的密钥 +// If command line arguments are provided, generate key with specified length if (process.argv[2]) { const customLength = parseInt(process.argv[2]); if (customLength > 0) { - console.log(`\n自定义长度密钥 (${customLength}字节):`); - console.log(` ${generateSecureKey(customLength)}`); + console.log(`\nCustom length key (${customLength} bytes):`); + console.log(` ${generateSecureKey(customLength)}`); } -} \ No newline at end of file +} diff --git a/main/mqtt-gateway/mqtt-protocol.js b/main/mqtt-gateway/mqtt-protocol.js index 09ba8a20f..6f80a59c5 100644 --- a/main/mqtt-gateway/mqtt-protocol.js +++ b/main/mqtt-gateway/mqtt-protocol.js @@ -1,499 +1,513 @@ -const debug = require('debug')('mqtt-server'); -const EventEmitter = require('events'); +const debug = require("debug")("mqtt-server"); +const EventEmitter = require("events"); -// MQTT 固定头部的类型 +// MQTT fixed header types const PacketType = { - CONNECT: 1, - CONNACK: 2, - PUBLISH: 3, - SUBSCRIBE: 8, - SUBACK: 9, - PINGREQ: 12, - PINGRESP: 13, - DISCONNECT: 14 // 添加 DISCONNECT + CONNECT: 1, + CONNACK: 2, + PUBLISH: 3, + SUBSCRIBE: 8, + SUBACK: 9, + PINGREQ: 12, + PINGRESP: 13, + DISCONNECT: 14, // Added DISCONNECT }; /** - * MQTT协议处理类 - * 负责MQTT协议的解析和封装,以及心跳维持 + * MQTT protocol handler class + * Responsible for MQTT protocol parsing and encapsulation, as well as heartbeat maintenance */ class MQTTProtocol extends EventEmitter { - constructor(socket) { - super(); - this.socket = socket; + constructor(socket) { + super(); + this.socket = socket; + this.buffer = Buffer.alloc(0); + this.isConnected = false; + this.keepAliveInterval = 0; + this.lastActivity = Date.now(); + this.setupSocketHandlers(); + } + + /** + * Set up Socket event handlers + */ + setupSocketHandlers() { + this.socket.on("data", (data) => { + this.lastActivity = Date.now(); + this.buffer = Buffer.concat([this.buffer, data]); + this.processBuffer(); + }); + + this.socket.on("close", () => { + this.emit("close"); + }); + + this.socket.on("error", (err) => { + this.emit("error", err); + }); + } + + /** + * Process all complete messages in buffer + */ + processBuffer() { + // Continue processing data in buffer until no complete messages can be processed + while (this.buffer.length > 0) { + // At least 2 bytes needed to start parsing (1 byte fixed header + at least 1 byte remaining length) + if (this.buffer.length < 2) return; + + try { + // Get message type + const firstByte = this.buffer[0]; + const type = firstByte >> 4; + + // Parse remaining length + const { value: remainingLength, bytesRead } = + this.decodeRemainingLength(this.buffer); + + // Calculate total message length + const messageLength = 1 + bytesRead + remainingLength; + + // Check if buffer has complete message + if (this.buffer.length < messageLength) { + // Message incomplete, wait for more data + return; + } + + // Extract complete message + const message = this.buffer.subarray(0, messageLength); + + if (!this.isConnected && type !== PacketType.CONNECT) { + debug( + "Received non-CONNECT message when not connected, closing connection" + ); + this.socket.end(); + return; + } + + // Process based on message type + switch (type) { + case PacketType.CONNECT: + this.parseConnect(message); + break; + case PacketType.PUBLISH: + this.parsePublish(message); + break; + case PacketType.SUBSCRIBE: + this.parseSubscribe(message); + break; + case PacketType.PINGREQ: + this.parsePingReq(message); + break; + case PacketType.DISCONNECT: + this.parseDisconnect(message); + break; + default: + debug("Unhandled packet type:", type, message); + this.emit( + "protocolError", + new Error(`Unhandled packet type: ${type}`) + ); + } + + // Remove processed message from buffer + this.buffer = this.buffer.subarray(messageLength); + } catch (err) { + // If parsing error, might be incomplete data, wait for more data + if (err.message === "Malformed Remaining Length") { + return; + } + + // Other errors might be protocol errors, clear buffer and emit error event this.buffer = Buffer.alloc(0); - this.isConnected = false; - this.keepAliveInterval = 0; - this.lastActivity = Date.now(); - - this.setupSocketHandlers(); + this.emit("protocolError", err); + return; + } + } + } + + /** + * Parse Remaining Length field in MQTT packet + * @param {Buffer} buffer - Message buffer + * @returns {{value: number, bytesRead: number}} Contains parsed value and bytes read + */ + decodeRemainingLength(buffer) { + let multiplier = 1; + let value = 0; + let bytesRead = 0; + let digit; + + do { + if (bytesRead >= 4 || bytesRead >= buffer.length - 1) { + throw new Error("Malformed Remaining Length"); + } + + digit = buffer[bytesRead + 1]; + bytesRead++; + value += (digit & 127) * multiplier; + multiplier *= 128; + } while ((digit & 128) !== 0); + + return { value, bytesRead }; + } + + /** + * Encode Remaining Length field in MQTT packet + * @param {number} length - Length value to encode + * @returns {{bytes: Buffer, bytesLength: number}} Contains encoded bytes and byte length + */ + encodeRemainingLength(length) { + let digit; + const bytes = Buffer.alloc(4); // Maximum 4 bytes + let bytesLength = 0; + + do { + digit = length % 128; + length = Math.floor(length / 128); + // If more bytes remain, set high bit + if (length > 0) { + digit |= 0x80; + } + + bytes[bytesLength++] = digit; + } while (length > 0 && bytesLength < 4); + + return { bytes, bytesLength }; + } + + /** + * Parse CONNECT message + * @param {Buffer} message - Complete CONNECT message + */ + parseConnect(message) { + // Parse remaining length + const { value: remainingLength, bytesRead } = + this.decodeRemainingLength(message); + // Position after fixed header (MQTT fixed header first byte + Remaining Length field bytes) + const headerLength = 1 + bytesRead; + + // Read protocol name length from variable header start position + const protocolLength = message.readUInt16BE(headerLength); + const protocol = message.toString( + "utf8", + headerLength + 2, + headerLength + 2 + protocolLength + ); + + // Update position pointer, skip protocol name + let pos = headerLength + 2 + protocolLength; + + // Protocol level, 4 for MQTT 3.1.1 + const protocolLevel = message[pos]; + + // Check protocol version + if (protocolLevel !== 4) { + // 4 represents MQTT 3.1.1 + debug("Unsupported protocol version:", protocolLevel); + // Send CONNACK with unsupported protocol version return code (0x01) + this.sendConnack(1, false); + // Close connection + this.socket.end(); + return; } - /** - * 设置Socket事件处理 - */ - setupSocketHandlers() { - this.socket.on('data', (data) => { - this.lastActivity = Date.now(); - this.buffer = Buffer.concat([this.buffer, data]); - this.processBuffer(); - }); + pos += 1; + // Connection flags + const connectFlags = message[pos]; + const hasUsername = (connectFlags & 0x80) !== 0; + const hasPassword = (connectFlags & 0x40) !== 0; + const cleanSession = (connectFlags & 0x02) !== 0; + pos += 1; - this.socket.on('close', () => { - this.emit('close'); - }); + // Keep alive time + const keepAlive = message.readUInt16BE(pos); + pos += 2; - this.socket.on('error', (err) => { - this.emit('error', err); - }); + // Parse clientId + const clientIdLength = message.readUInt16BE(pos); + pos += 2; + const clientId = message.toString("utf8", pos, pos + clientIdLength); + pos += clientIdLength; + + // Parse username (if exists) + let username = ""; + if (hasUsername) { + const usernameLength = message.readUInt16BE(pos); + pos += 2; + username = message.toString("utf8", pos, pos + usernameLength); + pos += usernameLength; } - /** - * 处理缓冲区中的所有完整消息 - */ - processBuffer() { - // 持续处理缓冲区中的数据,直到没有完整的消息可以处理 - while (this.buffer.length > 0) { - // 至少需要2个字节才能开始解析(1字节固定头部 + 至少1字节的剩余长度) - if (this.buffer.length < 2) return; - - try { - // 获取消息类型 - const firstByte = this.buffer[0]; - const type = (firstByte >> 4); - - // 解析剩余长度 - const { value: remainingLength, bytesRead } = this.decodeRemainingLength(this.buffer); - - // 计算整个消息的长度 - const messageLength = 1 + bytesRead + remainingLength; - - // 检查缓冲区中是否有完整的消息 - if (this.buffer.length < messageLength) { - // 消息不完整,等待更多数据 - return; - } - - // 提取完整的消息 - const message = this.buffer.subarray(0, messageLength); - if (!this.isConnected && type !== PacketType.CONNECT) { - debug('未连接时收到非CONNECT消息,关闭连接'); - this.socket.end(); - return; - } - - // 根据消息类型处理 - switch (type) { - case PacketType.CONNECT: - this.parseConnect(message); - break; - case PacketType.PUBLISH: - this.parsePublish(message); - break; - case PacketType.SUBSCRIBE: - this.parseSubscribe(message); - break; - case PacketType.PINGREQ: - this.parsePingReq(message); - break; - case PacketType.DISCONNECT: - this.parseDisconnect(message); - break; - default: - debug('未处理的包类型:', type, message); - this.emit('protocolError', new Error(`未处理的包类型: ${type}`)); - } - - // 从缓冲区中移除已处理的消息 - this.buffer = this.buffer.subarray(messageLength); - - } catch (err) { - // 如果解析出错,可能是数据不完整,等待更多数据 - if (err.message === 'Malformed Remaining Length') { - return; - } - // 其他错误可能是协议错误,清空缓冲区并发出错误事件 - this.buffer = Buffer.alloc(0); - this.emit('protocolError', err); - return; - } - } + // Parse password (if exists) + let password = ""; + if (hasPassword) { + const passwordLength = message.readUInt16BE(pos); + pos += 2; + password = message.toString("utf8", pos, pos + passwordLength); + pos += passwordLength; } - /** - * 解析MQTT报文中的Remaining Length字段 - * @param {Buffer} buffer - 消息缓冲区 - * @returns {{value: number, bytesRead: number}} 包含解析的值和读取的字节数 - */ - decodeRemainingLength(buffer) { - let multiplier = 1; - let value = 0; - let bytesRead = 0; - let digit; + // Set heartbeat interval (1.5 times client-specified keepAlive value, in seconds) + this.keepAliveInterval = keepAlive * 1000 * 1.5; - do { - if (bytesRead >= 4 || bytesRead >= buffer.length - 1) { - throw new Error('Malformed Remaining Length'); - } - - digit = buffer[bytesRead + 1]; - bytesRead++; - - value += (digit & 127) * multiplier; - multiplier *= 128; - - } while ((digit & 128) !== 0); + // Send CONNACK + this.sendConnack(0, false); - return { value, bytesRead }; + // Mark as connected + this.isConnected = true; + + // Emit connection event + this.emit("connect", { + clientId, + protocol, + protocolLevel, + keepAlive, + username, + password, + cleanSession, + }); + } + + /** + * Parse PUBLISH message + * @param {Buffer} message - Complete PUBLISH message + */ + parsePublish(message) { + // Extract QoS level from first byte (bits 1-2) + const firstByte = message[0]; + const qos = (firstByte & 0x06) >> 1; // 0x06 is binary 00000110, used as mask to extract QoS bits + const dup = (firstByte & 0x08) !== 0; // 0x08 is binary 00001000, used as mask to extract DUP flag + const retain = (firstByte & 0x01) !== 0; // 0x01 is binary 00000001, used as mask to extract RETAIN flag + + // Use common method to parse remaining length + const { value: remainingLength, bytesRead } = + this.decodeRemainingLength(message); + // Position after fixed header (MQTT fixed header first byte + Remaining Length field bytes) + const headerLength = 1 + bytesRead; + + // Parse topic + const topicLength = message.readUInt16BE(headerLength); + const topic = message.toString( + "utf8", + headerLength + 2, + headerLength + 2 + topicLength + ); + + // For QoS > 0, includes message ID + let packetId = null; + let payloadStart = headerLength + 2 + topicLength; + if (qos > 0) { + packetId = message.readUInt16BE(payloadStart); + payloadStart += 2; } - /** - * 编码MQTT报文中的Remaining Length字段 - * @param {number} length - 要编码的长度值 - * @returns {{bytes: Buffer, bytesLength: number}} 包含编码后的字节和字节长度 - */ - encodeRemainingLength(length) { - let digit; - const bytes = Buffer.alloc(4); // 最多4个字节 - let bytesLength = 0; - - do { - digit = length % 128; - length = Math.floor(length / 128); - // 如果还有更多字节,设置最高位 - if (length > 0) { - digit |= 0x80; - } - bytes[bytesLength++] = digit; - } while (length > 0 && bytesLength < 4); - - return { bytes, bytesLength }; + // Parse payload + const payload = message.slice(payloadStart).toString("utf8"); + + // Emit publish event + this.emit("publish", { + topic, + payload, + qos, + dup, + retain, + packetId, + }); + } + + /** + * Parse SUBSCRIBE message + * @param {Buffer} message - Complete SUBSCRIBE message + */ + parseSubscribe(message) { + const packetId = message.readUInt16BE(2); + const topicLength = message.readUInt16BE(4); + const topic = message.toString("utf8", 6, 6 + topicLength); + const qos = message[6 + topicLength]; // QoS value + + // Emit subscribe event + this.emit("subscribe", { + packetId, + topic, + qos, + }); + } + + /** + * Parse PINGREQ message + * @param {Buffer} message - Complete PINGREQ message + */ + parsePingReq(message) { + debug("Received heartbeat request"); + // Send PINGRESP + this.sendPingResp(); + debug("Sent heartbeat response"); + } + + /** + * Parse DISCONNECT message + * @param {Buffer} message - Complete DISCONNECT message + */ + parseDisconnect(message) { + // Mark as disconnected + this.isConnected = false; + // Emit disconnect event + this.emit("disconnect"); + // Close socket + this.socket.end(); + } + + /** + * Send CONNACK message + * @param {number} returnCode - Return code + * @param {boolean} sessionPresent - Session present flag + */ + sendConnack(returnCode = 0, sessionPresent = false) { + if (!this.socket.writable) return; + + const packet = Buffer.from([ + PacketType.CONNACK << 4, + 2, // Remaining length + sessionPresent ? 1 : 0, // Connect acknowledge flags + returnCode, // Return code + ]); + + this.socket.write(packet); + } + + /** + * Send PUBLISH message + * @param {string} topic - Topic + * @param {string} payload - Payload + * @param {number} qos - QoS level + * @param {boolean} dup - Duplicate flag + * @param {boolean} retain - Retain flag + * @param {number} packetId - Packet ID (only needed when QoS > 0) + */ + sendPublish( + topic, + payload, + qos = 0, + dup = false, + retain = false, + packetId = null + ) { + if (!this.isConnected || !this.socket.writable) return; + + const topicLength = Buffer.byteLength(topic); + const payloadLength = Buffer.byteLength(payload); + + // Calculate remaining length + let remainingLength = 2 + topicLength + payloadLength; + // If QoS > 0, need to include packet ID + if (qos > 0 && packetId) { + remainingLength += 2; } - /** - * 解析CONNECT消息 - * @param {Buffer} message - 完整的CONNECT消息 - */ - parseConnect(message) { - // 解析剩余长度 - const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message); - - // 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节) - const headerLength = 1 + bytesRead; - - // 从可变头部开始位置读取协议名长度 - const protocolLength = message.readUInt16BE(headerLength); - const protocol = message.toString('utf8', headerLength + 2, headerLength + 2 + protocolLength); - - // 更新位置指针,跳过协议名 - let pos = headerLength + 2 + protocolLength; - - // 协议级别,4为MQTT 3.1.1 - const protocolLevel = message[pos]; - - // 检查协议版本 - if (protocolLevel !== 4) { // 4 表示 MQTT 3.1.1 - debug('不支持的协议版本:', protocolLevel); - // 发送 CONNACK,使用不支持的协议版本的返回码 (0x01) - this.sendConnack(1, false); - // 关闭连接 - this.socket.end(); - return; - } - - pos += 1; - - // 连接标志 - const connectFlags = message[pos]; - const hasUsername = (connectFlags & 0x80) !== 0; - const hasPassword = (connectFlags & 0x40) !== 0; - const cleanSession = (connectFlags & 0x02) !== 0; - pos += 1; - - // 保持连接时间 - const keepAlive = message.readUInt16BE(pos); - pos += 2; - - // 解析 clientId - const clientIdLength = message.readUInt16BE(pos); - pos += 2; - const clientId = message.toString('utf8', pos, pos + clientIdLength); - pos += clientIdLength; + // Encode variable length + const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } = + this.encodeRemainingLength(remainingLength); - // 解析 username(如果存在) - let username = ''; - if (hasUsername) { - const usernameLength = message.readUInt16BE(pos); - pos += 2; - username = message.toString('utf8', pos, pos + usernameLength); - pos += usernameLength; - } + // Allocate buffer: fixed header(1 byte) + variable length field + remaining length value + const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength); - // 解析 password(如果存在) - let password = ''; - if (hasPassword) { - const passwordLength = message.readUInt16BE(pos); - pos += 2; - password = message.toString('utf8', pos, pos + passwordLength); - pos += passwordLength; - } + // Write fixed header + let firstByte = PacketType.PUBLISH << 4; + if (dup) firstByte |= 0x08; + if (qos > 0) firstByte |= qos << 1; + if (retain) firstByte |= 0x01; + packet[0] = firstByte; - // 设置心跳间隔(客户端指定的keepAlive值的1.5倍,单位为秒) - this.keepAliveInterval = keepAlive * 1000 * 1.5; - - // 发送 CONNACK - this.sendConnack(0, false); - - // 标记为已连接 - this.isConnected = true; - - // 发出连接事件 - this.emit('connect', { - clientId, - protocol, - protocolLevel, - keepAlive, - username, - password, - cleanSession - }); + // Write variable length field + remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize); + + // Write topic length and topic + const variableHeaderStart = 1 + remainingLengthSize; + packet.writeUInt16BE(topicLength, variableHeaderStart); + packet.write(topic, variableHeaderStart + 2); + + // If QoS > 0, write packet ID + let payloadStart = variableHeaderStart + 2 + topicLength; + if (qos > 0 && packetId) { + packet.writeUInt16BE(packetId, payloadStart); + payloadStart += 2; } - /** - * 解析PUBLISH消息 - * @param {Buffer} message - 完整的PUBLISH消息 - */ - parsePublish(message) { - // 从第一个字节中提取QoS级别(bits 1-2) - const firstByte = message[0]; - const qos = (firstByte & 0x06) >> 1; // 0x06 是二进制 00000110,用于掩码提取QoS位 - const dup = (firstByte & 0x08) !== 0; // 0x08 是二进制 00001000,用于掩码提取DUP标志 - const retain = (firstByte & 0x01) !== 0; // 0x01 是二进制 00000001,用于掩码提取RETAIN标志 - - // 使用通用方法解析剩余长度 - const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message); - - // 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节) - const headerLength = 1 + bytesRead; - - // 解析主题 - const topicLength = message.readUInt16BE(headerLength); - const topic = message.toString('utf8', headerLength + 2, headerLength + 2 + topicLength); - - // 对于QoS > 0,包含消息ID - let packetId = null; - let payloadStart = headerLength + 2 + topicLength; - - if (qos > 0) { - packetId = message.readUInt16BE(payloadStart); - payloadStart += 2; - } - - // 解析有效载荷 - const payload = message.slice(payloadStart).toString('utf8'); - - // 发出发布事件 - this.emit('publish', { - topic, - payload, - qos, - dup, - retain, - packetId - }); - } + // Write payload + packet.write(payload, payloadStart); - /** - * 解析SUBSCRIBE消息 - * @param {Buffer} message - 完整的SUBSCRIBE消息 - */ - parseSubscribe(message) { - const packetId = message.readUInt16BE(2); - const topicLength = message.readUInt16BE(4); - const topic = message.toString('utf8', 6, 6 + topicLength); - const qos = message[6 + topicLength]; // QoS值 - - // 发出订阅事件 - this.emit('subscribe', { - packetId, - topic, - qos - }); - } + this.socket.write(packet); + this.lastActivity = Date.now(); + } - /** - * 解析PINGREQ消息 - * @param {Buffer} message - 完整的PINGREQ消息 - */ - parsePingReq(message) { - debug('收到心跳请求'); - - // 发送 PINGRESP - this.sendPingResp(); - - debug('已发送心跳响应'); - } + /** + * Send SUBACK message + * @param {number} packetId - Packet ID + * @param {number} returnCode - Return code + */ + sendSuback(packetId, returnCode = 0) { + if (!this.isConnected || !this.socket.writable) return; - /** - * 解析DISCONNECT消息 - * @param {Buffer} message - 完整的DISCONNECT消息 - */ - parseDisconnect(message) { - // 标记为未连接 - this.isConnected = false; - - // 发出断开连接事件 - this.emit('disconnect'); - - // 关闭 socket - this.socket.end(); - } + const packet = Buffer.from([ + PacketType.SUBACK << 4, + 3, // Remaining length + packetId >> 8, // Packet ID MSB + packetId & 0xff, // Packet ID LSB + returnCode, // Return code + ]); - /** - * 发送CONNACK消息 - * @param {number} returnCode - 返回码 - * @param {boolean} sessionPresent - 会话存在标志 - */ - sendConnack(returnCode = 0, sessionPresent = false) { - if (!this.socket.writable) return; - - const packet = Buffer.from([ - PacketType.CONNACK << 4, - 2, // Remaining length - sessionPresent ? 1 : 0, // Connect acknowledge flags - returnCode // Return code - ]); - - this.socket.write(packet); - } + this.socket.write(packet); + this.lastActivity = Date.now(); + } - /** - * 发送PUBLISH消息 - * @param {string} topic - 主题 - * @param {string} payload - 有效载荷 - * @param {number} qos - QoS级别 - * @param {boolean} dup - 重复标志 - * @param {boolean} retain - 保留标志 - * @param {number} packetId - 包ID(仅QoS > 0时需要) - */ - sendPublish(topic, payload, qos = 0, dup = false, retain = false, packetId = null) { - if (!this.isConnected || !this.socket.writable) return; - - const topicLength = Buffer.byteLength(topic); - const payloadLength = Buffer.byteLength(payload); - - // 计算剩余长度 - let remainingLength = 2 + topicLength + payloadLength; - - // 如果QoS > 0,需要包含包ID - if (qos > 0 && packetId) { - remainingLength += 2; - } - - // 编码可变长度 - const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } = this.encodeRemainingLength(remainingLength); - - // 分配缓冲区:固定头部(1字节) + 可变长度字段 + 剩余长度值 - const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength); - - // 写入固定头部 - let firstByte = PacketType.PUBLISH << 4; - if (dup) firstByte |= 0x08; - if (qos > 0) firstByte |= (qos << 1); - if (retain) firstByte |= 0x01; - - packet[0] = firstByte; - - // 写入可变长度字段 - remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize); - - // 写入主题长度和主题 - const variableHeaderStart = 1 + remainingLengthSize; - packet.writeUInt16BE(topicLength, variableHeaderStart); - packet.write(topic, variableHeaderStart + 2); - - // 如果QoS > 0,写入包ID - let payloadStart = variableHeaderStart + 2 + topicLength; - if (qos > 0 && packetId) { - packet.writeUInt16BE(packetId, payloadStart); - payloadStart += 2; - } - - // 写入有效载荷 - packet.write(payload, payloadStart); - - this.socket.write(packet); - this.lastActivity = Date.now(); - } + /** + * Send PINGRESP message + */ + sendPingResp() { + if (!this.isConnected || !this.socket.writable) return; - /** - * 发送SUBACK消息 - * @param {number} packetId - 包ID - * @param {number} returnCode - 返回码 - */ - sendSuback(packetId, returnCode = 0) { - if (!this.isConnected || !this.socket.writable) return; - - const packet = Buffer.from([ - PacketType.SUBACK << 4, - 3, // Remaining length - packetId >> 8, // Packet ID MSB - packetId & 0xFF, // Packet ID LSB - returnCode // Return code - ]); - - this.socket.write(packet); - this.lastActivity = Date.now(); - } + const packet = Buffer.from([ + PacketType.PINGRESP << 4, // Fixed header + 0, // Remaining length + ]); - /** - * 发送PINGRESP消息 - */ - sendPingResp() { - if (!this.isConnected || !this.socket.writable) return; - - const packet = Buffer.from([ - PacketType.PINGRESP << 4, // Fixed header - 0 // Remaining length - ]); - - this.socket.write(packet); - this.lastActivity = Date.now(); - } + this.socket.write(packet); + this.lastActivity = Date.now(); + } - /** - * 获取上次活动时间 - */ - getLastActivity() { - return this.lastActivity; - } + /** + * Get last activity time + */ + getLastActivity() { + return this.lastActivity; + } - /** - * 获取心跳间隔 - */ - getKeepAliveInterval() { - return this.keepAliveInterval; - } + /** + * Get heartbeat interval + */ + getKeepAliveInterval() { + return this.keepAliveInterval; + } - /** - * 清空缓冲区 - */ - clearBuffer() { - this.buffer = Buffer.alloc(0); - } + /** + * Clear buffer + */ + clearBuffer() { + this.buffer = Buffer.alloc(0); + } - /** - * 关闭连接 - */ - close() { - if (this.socket.writable) { - this.socket.end(); - } + /** + * Close connection + */ + close() { + if (this.socket.writable) { + this.socket.end(); } + } } -// 导出 PacketType 和 MQTTProtocol 类 +// Export PacketType and MQTTProtocol class module.exports = { - PacketType, - MQTTProtocol -}; \ No newline at end of file + PacketType, + MQTTProtocol, +}; diff --git a/main/mqtt-gateway/utils/config-manager.js b/main/mqtt-gateway/utils/config-manager.js index 59d3c6614..84ed6274f 100644 --- a/main/mqtt-gateway/utils/config-manager.js +++ b/main/mqtt-gateway/utils/config-manager.js @@ -3,76 +3,75 @@ const path = require('path'); const EventEmitter = require('events'); class ConfigManager extends EventEmitter { - constructor(fileName) { - super(); - this.config = {}; // 移除默认的 apiKeys 配置 - this.configPath = path.join(__dirname, "..", "config", fileName); - this.loadConfig(); - this.watchConfig(); - // 添加防抖计时器变量 - this.watchDebounceTimer = null; - } - - loadConfig() { - try { - const data = fs.readFileSync(this.configPath, 'utf8'); - const newConfig = JSON.parse(data); - - // 检测配置是否发生变化 - if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) { - console.log('配置已更新', this.configPath); - this.config = newConfig; - // 发出配置更新事件 - this.emit('configChanged', this.config); - } - } catch (error) { - console.error('加载配置出错:', error, this.configPath); - if (error.code === 'ENOENT') { - this.createEmptyConfig(); - } + constructor(fileName) { + super(); + this.config = {}; // Remove default apiKeys configuration + this.configPath = path.join(__dirname, "..", "config", fileName); + this.loadConfig(); + this.watchConfig(); + // Add debounce timer variable + this.watchDebounceTimer = null; } - } - createEmptyConfig() { - try { - const dir = path.dirname(this.configPath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - const defaultConfig = {}; // 空配置对象 - fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2)); - console.log('已创建空配置文件', this.configPath); - } catch (error) { - console.error('创建空配置文件出错:', error, this.configPath); - } - } - - watchConfig() { - fs.watch(path.dirname(this.configPath), (eventType, filename) => { - if (filename === path.basename(this.configPath) && eventType === 'change') { - // 清除之前的计时器 - if (this.watchDebounceTimer) { - clearTimeout(this.watchDebounceTimer); + loadConfig() { + try { + const data = fs.readFileSync(this.configPath, 'utf8'); + const newConfig = JSON.parse(data); + // Check if configuration has changed + if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) { + console.log('Configuration updated', this.configPath); + this.config = newConfig; + // Emit configuration update event + this.emit('configChanged', this.config); + } + } catch (error) { + console.error('Error loading configuration:', error, this.configPath); + if (error.code === 'ENOENT') { + this.createEmptyConfig(); + } } - // 设置新的计时器,300ms 后执行 - this.watchDebounceTimer = setTimeout(() => { - this.loadConfig(); - }, 300); - } - }); - } + } - // 获取配置的方法 - getConfig() { - return this.config; - } + createEmptyConfig() { + try { + const dir = path.dirname(this.configPath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + const defaultConfig = {}; // Empty configuration object + fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2)); + console.log('Created empty configuration file', this.configPath); + } catch (error) { + console.error('Error creating empty configuration file:', error, this.configPath); + } + } - // 获取特定配置项的方法 - get(key) { - return this.config[key]; - } + watchConfig() { + fs.watch(path.dirname(this.configPath), (eventType, filename) => { + if (filename === path.basename(this.configPath) && eventType === 'change') { + // Clear previous timer + if (this.watchDebounceTimer) { + clearTimeout(this.watchDebounceTimer); + } + // Set new timer, execute after 300ms + this.watchDebounceTimer = setTimeout(() => { + this.loadConfig(); + }, 300); + } + }); + } + + // Method to get configuration + getConfig() { + return this.config; + } + + // Method to get specific configuration item + get(key) { + return this.config[key]; + } } module.exports = { ConfigManager -}; \ No newline at end of file +}; diff --git a/main/mqtt-gateway/utils/mqtt_config_v2.js b/main/mqtt-gateway/utils/mqtt_config_v2.js index 0fecd459f..c215fedc6 100644 --- a/main/mqtt-gateway/utils/mqtt_config_v2.js +++ b/main/mqtt-gateway/utils/mqtt_config_v2.js @@ -1,103 +1,116 @@ -require('dotenv').config(); -const crypto = require('crypto'); - +require("dotenv").config(); +const crypto = require("crypto"); function generatePasswordSignature(content, secretKey) { - // Create an HMAC object using SHA256 and the secretKey - const hmac = crypto.createHmac('sha256', secretKey); - - // Update the HMAC object with the clientId - hmac.update(content); - - // Generate the HMAC digest in binary format - const binarySignature = hmac.digest(); - - // Encode the binary signature to Base64 - const base64Signature = binarySignature.toString('base64'); - - return base64Signature; + // Create an HMAC object using SHA256 and the secretKey + const hmac = crypto.createHmac("sha256", secretKey); + // Update the HMAC object with the clientId + hmac.update(content); + // Generate the HMAC digest in binary format + const binarySignature = hmac.digest(); + // Encode the binary signature to Base64 + const base64Signature = binarySignature.toString("base64"); + return base64Signature; } function validateMqttCredentials(clientId, username, password) { - // 验证密码签名 - const signatureKey = process.env.MQTT_SIGNATURE_KEY; - if (signatureKey) { - const expectedSignature = generatePasswordSignature(clientId + '|' + username, signatureKey); - if (password !== expectedSignature) { - throw new Error('密码签名验证失败'); - } - } else { - console.warn('缺少MQTT_SIGNATURE_KEY环境变量,跳过密码签名验证'); + // Validate password signature + const signatureKey = process.env.MQTT_SIGNATURE_KEY; + if (signatureKey) { + const expectedSignature = generatePasswordSignature( + clientId + "|" + username, + signatureKey + ); + if (password !== expectedSignature) { + throw new Error("Password signature validation failed"); } + } else { + console.warn( + "Missing MQTT_SIGNATURE_KEY environment variable, skipping password signature validation" + ); + } - // 验证clientId - if (!clientId || typeof clientId !== 'string') { - throw new Error('clientId必须是非空字符串'); - } - - // 验证clientId格式(必须包含@@@分隔符) - const clientIdParts = clientId.split('@@@'); - // 新版本 MQTT 参数 - if (clientIdParts.length !== 3) { - throw new Error('clientId格式错误,必须包含@@@分隔符'); - } - - // 验证username - if (!username || typeof username !== 'string') { - throw new Error('username必须是非空字符串'); - } - - // 尝试解码username(应该是base64编码的JSON) - let userData; - try { - const decodedUsername = Buffer.from(username, 'base64').toString(); - userData = JSON.parse(decodedUsername); - } catch (error) { - throw new Error('username不是有效的base64编码JSON'); - } - - // 解析clientId中的信息 - const [groupId, macAddress, uuid] = clientIdParts; - - // 如果验证成功,返回解析后的有用信息 - return { - groupId, - macAddress: macAddress.replace(/_/g, ':'), - uuid, - userData - }; + // Validate clientId + if (!clientId || typeof clientId !== "string") { + throw new Error("clientId must be a non-empty string"); + } + + // Validate clientId format (must contain @@@ separator) + const clientIdParts = clientId.split("@@@"); + // New version MQTT parameters + if (clientIdParts.length !== 3) { + throw new Error("clientId format error, must contain @@@ separator"); + } + + // Validate username + if (!username || typeof username !== "string") { + throw new Error("username must be a non-empty string"); + } + + // Try to decode username (should be base64 encoded JSON) + let userData; + try { + const decodedUsername = Buffer.from(username, "base64").toString(); + userData = JSON.parse(decodedUsername); + } catch (error) { + throw new Error("username is not valid base64 encoded JSON"); + } + + // Parse information from clientId + const [groupId, macAddress, uuid] = clientIdParts; + // If validation succeeds, return parsed useful information + return { + groupId, + macAddress: macAddress.replace(/_/g, ":"), + uuid, + userData, + }; } function generateMqttConfig(groupId, macAddress, uuid, userData) { - const endpoint = process.env.MQTT_ENDPOINT; - const signatureKey = process.env.MQTT_SIGNATURE_KEY; - if (!signatureKey) { - console.warn('No signature key, skip generating MQTT config'); - return; - } - const deviceIdNoColon = macAddress.replace(/:/g, '_'); - const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`; - const username = Buffer.from(JSON.stringify(userData)).toString('base64'); - const password = generatePasswordSignature(clientId + '|' + username, signatureKey); - return { - endpoint, - port: 8883, - client_id: clientId, - username, - password, - publish_topic: 'device-server', - subscribe_topic: 'null' // 旧版本固件不返回此字段会出错 - } + const endpoint = process.env.MQTT_ENDPOINT; + const signatureKey = process.env.MQTT_SIGNATURE_KEY; + if (!signatureKey) { + console.warn("No signature key, skip generating MQTT config"); + return; + } + + const deviceIdNoColon = macAddress.replace(/:/g, "_"); + const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`; + const username = Buffer.from(JSON.stringify(userData)).toString("base64"); + const password = generatePasswordSignature( + clientId + "|" + username, + signatureKey + ); + + return { + endpoint, + port: 8883, + client_id: clientId, + username, + password, + publish_topic: "device-server", + subscribe_topic: "null", // Old version firmware will error if this field is not returned + }; } module.exports = { - generateMqttConfig, - validateMqttCredentials -} + generateMqttConfig, + validateMqttCredentials, +}; if (require.main === module) { - const config = generateMqttConfig('GID_test', '11:22:33:44:55:66', '36c98363-3656-43cb-a00f-8bced2391a90', { ip: '222.222.222.222' }); - console.log('config', config); - const credentials = validateMqttCredentials(config.client_id, config.username, config.password); - console.log('credentials', credentials); + const config = generateMqttConfig( + "GID_test", + "11:22:33:44:55:66", + "36c98363-3656-43cb-a00f-8bced2391a90", + { ip: "222.222.222.222" } + ); + console.log("config", config); + const credentials = validateMqttCredentials( + config.client_id, + config.username, + config.password + ); + console.log("credentials", credentials); } diff --git a/main/mqtt-gateway/测试说明.md b/main/mqtt-gateway/测试说明.md index 202147295..f7b1b7ee7 100644 --- a/main/mqtt-gateway/测试说明.md +++ b/main/mqtt-gateway/测试说明.md @@ -1,239 +1,258 @@ -# MQTT网关转发功能测试指南 +# MQTT Gateway Forwarding Function Test Guide -本文档说明如何测试MQTT网关的转发功能是否配置成功。 +This document explains how to test whether the MQTT gateway forwarding function is configured successfully. -## 快速测试 +## Quick Test -### 1. 基础连接测试 +### 1. Basic Connection Test -运行快速测试脚本: +Run the quick test script: ```bash node quick-test.js ``` -这个脚本会: -- ✅ 检查配置文件 -- ✅ 测试MQTT服务器连接(端口1883) -- ✅ 测试WebSocket后端服务连接 -- ✅ 显示测试结果和建议 +This script will: -### 2. 完整功能测试 +- ✅ Check configuration file +- ✅ Test MQTT server connection (port 1883) +- ✅ Test WebSocket backend service connection +- ✅ Display test results and recommendations -运行完整测试脚本: +### 2. Complete Function Test + +Run the complete test script: ```bash node test-mqtt.js ``` -这个脚本会: -- 🔗 连接到MQTT服务器 -- 🔐 使用配置的MAC地址进行认证 -- 📝 订阅回复主题 -- 📤 发送hello消息测试WebSocket转发 -- 📥 等待并显示服务器响应 -- 🧪 发送其他测试消息 +This script will: -## 手动测试步骤 +- 🔗 Connect to MQTT server +- 🔐 Authenticate using configured MAC address +- 📝 Subscribe to reply topic +- 📤 Send hello message to test WebSocket forwarding +- 📥 Wait for and display server response +- 🧪 Send other test messages -### 1. 启动MQTT网关 +## Manual Test Steps + +### 1. Start MQTT Gateway ```bash node app.js ``` -应该看到类似输出: +You should see similar output: + ``` -MQTT 服务器启动在端口 1883 -UDP 服务器启动在端口 1883 -连接数: 0, 活跃数: 0 +MQTT server started on port 1883 +UDP server started on port 1883 +Connections: 0, Active: 0 ``` -### 2. 检查配置文件 +### 2. Check Configuration File -确认 `config/mqtt.json` 配置正确: +Confirm that `config/mqtt.json` is configured correctly: ```json { - "production": { - "chat_servers": [ - "ws://192.168.68.66:8000/xiaozhi/v1/" - ] - }, - "development": { - "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"], - "mac_addresss": ["d8:43:ae:3e:4b:5a"] - }, - "debug": false + "production": { + "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"] + }, + "development": { + "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"], + "mac_addresss": ["d8:43:ae:3e:4b:5a"] + }, + "debug": false } ``` -### 3. 使用MQTT客户端工具测试 +### 3. Test Using MQTT Client Tools -#### 使用mosquitto客户端: +#### Using mosquitto client: + +**Connection test:** -**连接测试:** ```bash mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello" ``` -**订阅测试:** +**Subscription test:** + ```bash mosquitto_sub -h localhost -p 1883 -t "devices/p2p/d8_43_ae_3e_4b_5a" ``` -#### 使用MQTT.fx或其他GUI工具: +#### Using MQTT.fx or other GUI tools: -1. **连接设置:** - - 服务器:localhost - - 端口:1883 - - 客户端ID:`GID_test@@@d8_43_ae_3e_4b_5a` - - 用户名:test_user - - 密码:test_password +1. **Connection settings:** + + - Server: localhost + - Port: 1883 + - Client ID: `GID_test@@@d8_43_ae_3e_4b_5a` + - Username: test_user + - Password: test_password + +2. **Publish test message:** + + - Topic: `test/topic` + - Message: -2. **发布测试消息:** - - 主题:`test/topic` - - 消息: ```json { - "type": "hello", - "version": 3, - "transport": "mqtt", - "audio_params": { - "sample_rate": 16000, - "channels": 1, - "format": "opus" - }, - "features": ["tts", "asr"] + "type": "hello", + "version": 3, + "transport": "mqtt", + "audio_params": { + "sample_rate": 16000, + "channels": 1, + "format": "opus" + }, + "features": ["tts", "asr"] } ``` -3. **订阅回复主题:** - - 主题:`devices/p2p/d8_43_ae_3e_4b_5a` +3. **Subscribe to reply topic:** + - Topic: `devices/p2p/d8_43_ae_3e_4b_5a` -## 测试结果判断 +## Test Result Assessment -### ✅ 成功指标 +### ✅ Success Indicators + +1. **MQTT connection successful:** -1. **MQTT连接成功:** ``` - ✓ 成功连接到MQTT服务器 localhost:1883 - ✓ MQTT连接成功 + ✓ Successfully connected to MQTT server localhost:1883 + ✓ MQTT connection successful ``` -2. **WebSocket转发成功:** +2. **WebSocket forwarding successful:** + ``` - ✓ WebSocket服务器连接成功 - ✓ 收到PUBLISH消息 + ✓ WebSocket server connection successful + ✓ Received PUBLISH message ``` -3. **服务器日志正常:** +3. **Server logs normal:** ``` - 客户端连接: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... } - 收到发布消息: { topic: 'test/topic', payload: '...', qos: 0 } + Client connected: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... } + Received publish message: { topic: 'test/topic', payload: '...', qos: 0 } ``` -### ❌ 常见问题 +### ❌ Common Issues -1. **MQTT服务器连接失败:** - ``` - ✗ 连接错误: connect ECONNREFUSED 127.0.0.1:1883 - ``` - **解决方案:** 确保运行 `node app.js` 启动MQTT网关 +1. **MQTT server connection failed:** -2. **WebSocket连接失败:** ``` - ✗ WebSocket服务器连接失败: connect ECONNREFUSED + ✗ Connection error: connect ECONNREFUSED 127.0.0.1:1883 ``` - **解决方案:** 检查WebSocket后端服务是否运行,网络是否可达 -3. **认证失败:** - ``` - 无效的 clientId: xxx - ``` - **解决方案:** 检查客户端ID格式是否为 `GID_test@@@mac_address` + **Solution:** Ensure running `node app.js` to start MQTT gateway + +2. **WebSocket connection failed:** -4. **MAC地址不匹配:** ``` - 未找到 xx:xx:xx:xx:xx:xx 的聊天服务器 + ✗ WebSocket server connection failed: connect ECONNREFUSED ``` - **解决方案:** 确认MAC地址在配置文件的 `mac_addresss` 列表中 -## 调试技巧 + **Solution:** Check if WebSocket backend service is running and network is reachable -### 1. 开启调试模式 +3. **Authentication failed:** + + ``` + Invalid clientId: xxx + ``` + + **Solution:** Check if client ID format is `GID_test@@@mac_address` + +4. **MAC address mismatch:** + ``` + Chat server not found for xx:xx:xx:xx:xx:xx + ``` + **Solution:** Confirm MAC address is in the `mac_addresss` list in configuration file + +## Debugging Tips + +### 1. Enable Debug Mode + +Modify `config/mqtt.json`: -修改 `config/mqtt.json`: ```json { - "debug": true + "debug": true } ``` -或设置环境变量: +Or set environment variable: + ```bash DEBUG=mqtt-server node app.js ``` -### 2. 查看详细日志 +### 2. View Detailed Logs + +Debug mode will display detailed connection and message processing information: -调试模式下会显示详细的连接和消息处理信息: ``` -mqtt-server 客户端连接: { clientId: '...', username: '...', ... } -mqtt-server 收到发布消息: { topic: '...', payload: '...', qos: 0 } -mqtt-server 发送消息到 devices/p2p/...: {...} +mqtt-server Client connected: { clientId: '...', username: '...', ... } +mqtt-server Received publish message: { topic: '...', payload: '...', qos: 0 } +mqtt-server Sending message to devices/p2p/...: {...} ``` -### 3. 网络连通性测试 +### 3. Network Connectivity Test + +**Test WebSocket server:** -**测试WebSocket服务器:** ```bash curl -I http://192.168.68.66:8000/xiaozhi/v1/ ``` -**测试MQTT端口:** +**Test MQTT port:** + ```bash telnet localhost 1883 ``` -## 性能测试 +## Performance Testing -### 并发连接测试 +### Concurrent Connection Test -可以修改测试脚本创建多个并发连接: +You can modify the test script to create multiple concurrent connections: ```javascript -// 创建多个测试客户端 +// Create multiple test clients const clients = []; for (let i = 0; i < 10; i++) { - const client = new MQTTTestClient(); - clients.push(client); - // 连接和测试... + const client = new MQTTTestClient(); + clients.push(client); + // Connect and test... } ``` -### 消息吞吐量测试 +### Message Throughput Test -发送大量消息测试转发性能: +Send large number of messages to test forwarding performance: ```javascript -// 发送100条消息 +// Send 100 messages for (let i = 0; i < 100; i++) { - client.publish('test/topic', `测试消息 ${i}`); + client.publish("test/topic", `Test message ${i}`); } ``` -## 故障排除清单 +## Troubleshooting Checklist -- [ ] MQTT网关服务是否运行 (`node app.js`) -- [ ] 端口1883是否被占用 -- [ ] 配置文件格式是否正确 -- [ ] WebSocket后端服务是否运行 -- [ ] 网络连接是否正常 -- [ ] MAC地址是否在配置的白名单中 -- [ ] 客户端ID格式是否正确 -- [ ] 防火墙是否阻止连接 +- [ ] Is MQTT gateway service running (`node app.js`) +- [ ] Is port 1883 occupied +- [ ] Is configuration file format correct +- [ ] Is WebSocket backend service running +- [ ] Is network connection normal +- [ ] Is MAC address in configured whitelist +- [ ] Is client ID format correct +- [ ] Is firewall blocking connections -## 总结 +## Summary -通过以上测试方法,你可以全面验证MQTT网关的转发功能是否配置成功。建议先运行快速测试,如果有问题再进行详细的手动测试和调试。 \ No newline at end of file +Through the above testing methods, you can comprehensively verify whether the MQTT gateway forwarding function is configured successfully. It is recommended to run the quick test first, and if there are issues, proceed with detailed manual testing and debugging. diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index 65e3a74b2..f2e42996d 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -13,12 +13,11 @@ from core.utils.util import check_ffmpeg_installed TAG = __name__ logger = setup_logging() - async def wait_for_exit() -> None: """ - 阻塞直到收到 Ctrl‑C / SIGTERM。 - - Unix: 使用 add_signal_handler - - Windows: 依赖 KeyboardInterrupt + Block until receiving Ctrl-C / SIGTERM. + - Unix: Use add_signal_handler + - Windows: Rely on KeyboardInterrupt """ loop = asyncio.get_running_loop() stop_event = asyncio.Event() @@ -28,114 +27,116 @@ async def wait_for_exit() -> None: loop.add_signal_handler(sig, stop_event.set) await stop_event.wait() else: - # Windows:await一个永远pending的fut, - # 让 KeyboardInterrupt 冒泡到 asyncio.run,以此消除遗留普通线程导致进程退出阻塞的问题 + # Windows: await a forever pending future, + # let KeyboardInterrupt bubble up to asyncio.run, to eliminate process exit blocking caused by legacy normal threads try: await asyncio.Future() - except KeyboardInterrupt: # Ctrl‑C + except KeyboardInterrupt: # Ctrl-C pass - async def monitor_stdin(): - """监控标准输入,消费回车键""" + """Monitor standard input, consume enter key presses""" while True: - await ainput() # 异步等待输入,消费回车 - + await ainput() # Asynchronously wait for input, consume enter async def main(): check_ffmpeg_installed() config = load_config() - # 默认使用manager-api的secret作为auth_key - # 如果secret为空,则生成随机密钥 - # auth_key用于jwt认证,比如视觉分析接口的jwt认证 + # Default to using manager-api's secret as auth_key + # If secret is empty, generate random key + # auth_key is used for jwt authentication, such as jwt authentication for vision analysis interface auth_key = config.get("manager-api", {}).get("secret", "") if not auth_key or len(auth_key) == 0 or "你" in auth_key: auth_key = str(uuid.uuid4().hex) - config["server"]["auth_key"] = auth_key - logger.bind(tag=TAG).info(f"Generated auth_key: {auth_key}") + config["server"]["auth_key"] = auth_key + logger.bind(tag=TAG).info(f"Generated auth_key: {auth_key}") - # 添加 stdin 监控任务 + # Add stdin monitoring task stdin_task = asyncio.create_task(monitor_stdin()) - # 启动 WebSocket 服务器 + # Start WebSocket server ws_server = WebSocketServer(config) ws_task = asyncio.create_task(ws_server.start()) - # 启动 Simple http 服务器 + + # Start Simple http server ota_server = SimpleHttpServer(config) ota_task = asyncio.create_task(ota_server.start()) read_config_from_api = config.get("read_config_from_api", False) port = int(config["server"].get("http_port", 8003)) + if not read_config_from_api: logger.bind(tag=TAG).info( - "OTA接口是\t\thttp://{}:{}/xiaozhi/ota/", + "OTA interface is\t\thttp://{}:{}/xiaozhi/ota/", get_local_ip(), port, ) - mcp_endpoint = config.get("mcp_endpoint", None) - if mcp_endpoint is not None and "你" not in mcp_endpoint: - # 校验MCP接入点格式 - if validate_mcp_endpoint(mcp_endpoint): - logger.bind(tag=TAG).info("mcp接入点是\t{}", mcp_endpoint) - # 将mcp计入点地址转成调用点 - mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/") - config["mcp_endpoint"] = mcp_endpoint - else: - logger.bind(tag=TAG).error("mcp接入点不符合规范") - config["mcp_endpoint"] = "你的接入点 websocket地址" + mcp_endpoint = config.get("mcp_endpoint", None) + if mcp_endpoint is not None and "你" not in mcp_endpoint: + # Validate MCP endpoint format + if validate_mcp_endpoint(mcp_endpoint): + logger.bind(tag=TAG).info("MCP endpoint is\t{}", mcp_endpoint) + # Convert mcp endpoint address to call endpoint + mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/") + config["mcp_endpoint"] = mcp_endpoint + else: + logger.bind(tag=TAG).error("MCP endpoint does not conform to specifications") + config["mcp_endpoint"] = "Your endpoint websocket address" logger.bind(tag=TAG).info( - "视觉分析接口是\thttp://{}:{}/mcp/vision/explain", + "Vision analysis interface is\thttp://{}:{}/mcp/vision/explain", get_local_ip(), port, ) - # 获取WebSocket配置,使用安全的默认值 + # Get WebSocket configuration, use safe default values websocket_port = 8000 server_config = config.get("server", {}) if isinstance(server_config, dict): websocket_port = int(server_config.get("port", 8000)) logger.bind(tag=TAG).info( - "Websocket地址是\tws://{}:{}/xiaozhi/v1/", + "Websocket address is\tws://{}:{}/xiaozhi/v1/", get_local_ip(), websocket_port, ) logger.bind(tag=TAG).info( - "=======上面的地址是websocket协议地址,请勿用浏览器访问=======" + "=======The above address is websocket protocol address, please do not access with browser=======" ) + logger.bind(tag=TAG).info( - "如想测试websocket请用谷歌浏览器打开test目录下的test_page.html" + "If you want to test websocket please use Google Chrome to open test_page.html in test directory" ) + logger.bind(tag=TAG).info( "=============================================================\n" ) try: - await wait_for_exit() # 阻塞直到收到退出信号 + await wait_for_exit() # Block until receiving exit signal except asyncio.CancelledError: - print("任务被取消,清理资源中...") + print("Task was cancelled, cleaning up resources...") finally: - # 取消所有任务(关键修复点) + # Cancel all tasks (critical fix point) stdin_task.cancel() ws_task.cancel() if ota_task: ota_task.cancel() - # 等待任务终止(必须加超时) + # Wait for task termination (must add timeout) await asyncio.wait( [stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task], timeout=3.0, return_when=asyncio.ALL_COMPLETED, ) - print("服务器已关闭,程序退出。") + print("Server has been closed, program exiting.") if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: - print("手动中断,程序终止。") + print("Manual interruption, program terminated.") diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index 58cf1375c..a2295d345 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -19,9 +19,9 @@ import opuslib # --- Configuration --- -SERVER_IP = "192.168.1.101" # !!! UPDATE with your server's local IP address !!! +SERVER_IP = "192.168.1.254" # !!! UPDATE with your server's local IP address !!! OTA_PORT = 8003 -MQTT_BROKER_HOST = "192.168.1.101" # MQTT gateway IP +MQTT_BROKER_HOST = "192.168.1.254" # MQTT gateway IP MQTT_BROKER_PORT = 1883 # DEVICE_MAC is now dynamically generated for uniqueness PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 4c1b3f73a..cd03ce359 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -3,63 +3,62 @@ import yaml from collections.abc import Mapping from config.manage_api_client import init_service, get_server_config, get_agent_models - def get_project_dir(): - """获取项目根目录""" + """Get project root directory""" return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/" - def read_config(config_path): with open(config_path, "r", encoding="utf-8") as file: config = yaml.safe_load(file) return config - 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 - + default_config_path = get_project_dir() + "config.yaml" custom_config_path = get_project_dir() + "data/.config.yaml" - - # 加载默认配置 + + # Load 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 configurations config = merge_configs(default_config, custom_config) - # 初始化目录 + + # Initialize directories 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 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") - + config_data["read_config_from_api"] = True config_data["manager-api"] = { "url": config["manager-api"].get("url", ""), "secret": config["manager-api"].get("secret", ""), } - # server的配置以本地为准 + + # Use local server configuration as priority if config.get("server"): config_data["server"] = { "ip": config["server"].get("ip", ""), @@ -68,23 +67,23 @@ def get_config_from_api(config): "vision_explain": config["server"].get("vision_explain", ""), "auth_key": config["server"].get("auth_key", ""), } + return config_data - 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): - """确保所有配置路径存在""" + """Ensure all configuration paths exist""" dirs_to_create = set() - project_dir = get_project_dir() # 获取项目根目录 - # 日志文件目录 + project_dir = get_project_dir() # Get 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 directories for module in ["ASR", "TTS"]: if config.get(module) is None: continue @@ -92,49 +91,48 @@ def ensure_directories(config): output_dir = provider.get("output_dir", "") if output_dir: dirs_to_create.add(output_dir) - - # 根据selected_module创建模型目录 + + # Create model directories based on selected_module selected_modules = config.get("selected_module", {}) for module_type in ["ASR", "LLM", "TTS"]: selected_provider = selected_modules.get(module_type) if not selected_provider: continue - if config.get(module) is None: + if config.get(module_type) is None: continue if config.get(selected_provider) is None: continue + provider_config = config.get(module_type, {}).get(selected_provider, {}) output_dir = provider_config.get("output_dir") if output_dir: full_model_dir = os.path.join(project_dir, output_dir) dirs_to_create.add(full_model_dir) - - # 统一创建目录(保留原data目录创建) + + # Create directories uniformly (keep 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: Cannot create directory {dir_path}, please check write permissions") def merge_configs(default_config, custom_config): """ - 递归合并配置,custom_config优先级更高 - + Recursively merge configurations, custom_config has higher priority + Args: - default_config: 默认配置 - custom_config: 用户自定义配置 - + default_config: Default configuration + custom_config: User custom configuration + Returns: - 合并后的配置 + Merged configuration """ if not isinstance(default_config, Mapping) or not isinstance( custom_config, Mapping ): return custom_config - + merged = dict(default_config) - for key, value in custom_config.items(): if ( key in merged @@ -144,5 +142,5 @@ def merge_configs(default_config, custom_config): merged[key] = merge_configs(merged[key], value) else: merged[key] = value - - return merged \ No newline at end of file + + return merged diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py index 6bd50e3f4..ce90c1bad 100644 --- a/main/xiaozhi-server/config/logger.py +++ b/main/xiaozhi-server/config/logger.py @@ -8,22 +8,23 @@ from datetime import datetime SERVER_VERSION = "0.7.4" _logger_initialized = False - def get_module_abbreviation(module_name, module_dict): - """获取模块名称的缩写,如果为空则返回00 - 如果名称中包含下划线,则返回下划线后面的前两个字符 + """Get module name abbreviation, return 00 if empty + + If name contains underscore, return first two characters after underscore """ module_value = module_dict.get(module_name, "") if not module_value: return "00" + if "_" in module_value: parts = module_value.split("_") return parts[-1][:2] if parts[-1] else "00" + return module_value[:2] - def build_module_string(selected_module): - """构建模块字符串""" + """Build module string""" return ( get_module_abbreviation("VAD", selected_module) + get_module_abbreviation("ASR", selected_module) @@ -34,80 +35,90 @@ def build_module_string(selected_module): + get_module_abbreviation("VLLM", selected_module) ) - def formatter(record): - """为没有 tag 的日志添加默认值,并处理动态模块字符串""" + """Add default values for logs without tag, and handle dynamic module string""" record["extra"].setdefault("tag", record["name"]) - # 如果没有设置 selected_module,使用默认值 + # If selected_module is not set, use 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 update_module_string(selected_module_str): + """Update module string""" + logger.configure( + extra={ + "selected_module": selected_module_str, + } + ) def setup_logging(): check_config_file() - """从配置文件中读取日志配置,并设置日志输出格式和级别""" + """Read log configuration from config file and set log output format and level""" config = load_config() log_config = config["log"] + global _logger_initialized - - # 第一次初始化时配置日志 + + # Configure logging on first initialization if not _logger_initialized: - # 使用默认的模块字符串进行初始化 + # Initialize with default module string logger.configure( extra={ "selected_module": log_config.get("selected_module", "00000000000000"), - }) + } + ) log_format = log_config.get( "log_format", - "{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][{extra[tag]}]-{level}-{message}", + "{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][{extra[tag]}]-{level}-{message}", ) + log_format_file = log_config.get( "log_format_file", "{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}", ) + log_format = log_format.replace("{version}", SERVER_VERSION) log_format_file = log_format_file.replace("{version}", SERVER_VERSION) - + log_level = log_config.get("log_level", "INFO") log_dir = log_config.get("log_dir", "tmp") log_file = log_config.get("log_file", "server.log") data_dir = log_config.get("data_dir", "data") - + 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 + # Log file full path log_file_path = os.path.join(log_dir, log_file) - - # 添加日志处理器 + + # Add log handler 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 maximum 10MB + retention="30 days", # Keep for 30 days compression=None, encoding="utf-8", - enqueue=True, # 异步安全 + enqueue=True, # Async safe backtrace=True, diagnose=True, ) - _logger_initialized = True # 标记为已初始化 - + + _logger_initialized = True # Mark as initialized + return logger - def create_connection_logger(selected_module_str): - """为连接创建独立的日志器,绑定特定的模块字符串""" + """Create independent logger for connection, bind specific module string""" return logger.bind(selected_module=selected_module_str) diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index cd3f86c42..8c661164c 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -15,7 +15,8 @@ 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 +25,7 @@ class ManageApiClient: _secret = None def __new__(cls, config): - """单例模式确保全局唯一实例,并支持传入配置参数""" + """Singleton pattern to ensure a globally unique instance, supporting configuration parameters""" if cls._instance is None: cls._instance = super().__new__(cls) cls._init_client(config) @@ -32,23 +33,25 @@ class ManageApiClient: @classmethod def _init_client(cls, config): - """初始化持久化连接池""" + """Initialize 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 retry count + # Initial retry delay (seconds) + cls.retry_delay = cls.config.get("retry_delay", 10) + # NOTE(goody): 2025/4/16 Unified management of http-related resources, can add thread pools or timeouts later + # Later can also unify configuration of apiToken and other common Auth cls._client = httpx.Client( base_url=cls.config.get("url"), headers={ @@ -56,39 +59,42 @@ class ManageApiClient: "Accept": "application/json", "Authorization": "Bearer " + cls._secret, }, - timeout=cls.config.get("timeout", 30), # 默认超时时间30秒 + # Default timeout 30 seconds + timeout=cls.config.get("timeout", 30), ) @classmethod def _request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """发送单次HTTP请求并处理响应""" + """Send a single HTTP request and handle response""" endpoint = endpoint.lstrip("/") response = cls._client.request(method, endpoint, **kwargs) response.raise_for_status() result = response.json() - # 处理API返回的业务错误 + # Handle business errors returned by 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 error: {result.get('msg', 'Unknown error')}") - # 返回成功数据 + # Return successful data return result.get("data") if result.get("code") == 0 else None @classmethod def _should_retry(cls, exception: Exception) -> bool: - """判断异常是否应该重试""" - # 网络连接相关错误 + """Determine if exception should be retried""" + # Network connection related errors if isinstance( - exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) + exception, (httpx.ConnectError, + httpx.TimeoutException, httpx.NetworkError) ): return True - # HTTP状态码错误 + # HTTP status code errors if isinstance(exception, httpx.HTTPStatusError): status_code = exception.response.status_code return status_code in [408, 429, 500, 502, 503, 504] @@ -97,43 +103,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 request return cls._request(method, endpoint, **kwargs) except Exception as e: - # 判断是否应该重试 + # Determine if should 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 retry attempt {retry_count} after {cls.retry_delay:.1f} seconds" ) time.sleep(cls.retry_delay) continue else: - # 不重试,直接抛出异常 + # Don't retry, throw exception directly raise @classmethod def safe_close(cls): - """安全关闭连接池""" + """Safely close connection pool""" if cls._client: cls._client.close() cls._instance = None def get_server_config() -> Optional[Dict]: - """获取服务器基础配置""" + """Get server basic 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 agent model configuration""" return ManageApiClient._instance._execute_request( "POST", "/config/agent-models", @@ -155,14 +161,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 save 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 +187,7 @@ def report( }, ) except Exception as e: - print(f"TTS上报失败: {e}") + print(f"TTS reporting failed: {e}") return None diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index fb8868b40..0017189e8 100644 --- a/main/xiaozhi-server/config/settings.py +++ b/main/xiaozhi-server/config/settings.py @@ -1,33 +1,34 @@ import os from config.config_loader import read_config, get_project_dir, load_config - default_config_file = "config.yaml" config_file_valid = False - def check_config_file(): global config_file_valid if config_file_valid: return + """ - 简化的配置检查,仅提示用户配置文件的使用情况 + Simplified configuration check, only prompt user about config file usage """ 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 data/.config.yaml file, please confirm if this configuration file exists according to tutorial" ) - - # 检查是否从API读取配置 + + # Check if reading configuration from API config = load_config() if config.get("read_config_from_api", False): - print("从API读取配置") + print("Reading 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 smart control panel configuration and local configuration:\n" + error_msg += "\nRecommendations:\n" + error_msg += "1. Copy the config_from_api.yaml file from root directory to data folder, rename to .config.yaml\n" + error_msg += "2. Configure the API address and secret key according to tutorial\n" raise ValueError(error_msg) + config_file_valid = True diff --git a/main/xiaozhi-server/core/api/base_handler.py b/main/xiaozhi-server/core/api/base_handler.py index 7330185e4..aa097da70 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 6d613be05..ff56f7e07 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -1,130 +1,3 @@ -# import json -# import time -# from aiohttp import web -# from core.utils.util import get_local_ip -# from core.api.base_handler import BaseHandler - -# TAG = __name__ - - -# class OTAHandler(BaseHandler): -# def __init__(self, config: dict): -# super().__init__(config) - -# def _get_websocket_url(self, local_ip: str, port: int) -> str: -# """获取websocket地址 - -# Args: -# local_ip: 本地IP地址 -# port: 端口号 - -# Returns: -# str: websocket地址 -# """ -# server_config = self.config["server"] -# websocket_config = server_config.get("websocket", "") - -# if "你的" not in websocket_config: -# return websocket_config -# else: -# return f"ws://{local_ip}:{port}/xiaozhi/v1/" - -# async def handle_post(self, request): -# """处理 OTA POST 请求""" -# 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}") - -# device_id = request.headers.get("device-id", "") -# if device_id: -# self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}") -# else: -# raise Exception("OTA请求设备ID为空") - -# data_json = json.loads(data) - -# server_config = self.config["server"] -# port = int(server_config.get("port", 8000)) -# local_ip = get_local_ip() - -# return_json = { -# "server_time": { -# "timestamp": int(round(time.time() * 1000)), -# "timezone_offset": server_config.get("timezone_offset", 8) * 60, -# }, -# "firmware": { -# "version": data_json["application"].get("version", "1.0.0"), -# "url": "", -# }, -# "websocket": { -# "url": self._get_websocket_url(local_ip, port), -# }, -# } - -# # Add MQTT gateway configuration if enabled -# mqtt_config = server_config.get("mqtt_gateway", {}) -# if mqtt_config.get("enabled", False): -# return_json["mqtt_gateway"] = { -# "broker": mqtt_config.get("broker", local_ip), -# "port": mqtt_config.get("port", 1883), -# "udp_port": mqtt_config.get("udp_port", 8884) -# } - -# # Also add MQTT credentials section for client authentication -# import base64 -# import hmac -# import hashlib - -# client_id = f"GID_test@@@{device_id}@@@{data_json.get('client_id', 'default-client')}" - -# # Create username (base64 encoded JSON) - must match client format -# username_data = {"ip": "192.168.1.100"} # Placeholder IP -# username = base64.b64encode(json.dumps(username_data).encode()).decode() - -# # Generate password using HMAC (must match gateway's signature key) -# secret_key = "test-signature-key-12345" # Must match MQTT_SIGNATURE_KEY in gateway's .env -# content = f"{client_id}|{username}" -# password = base64.b64encode(hmac.new(secret_key.encode(), content.encode(), hashlib.sha256).digest()).decode() - -# return_json["mqtt"] = { -# "client_id": client_id, -# "username": username, -# "password": password -# } -# response = web.Response( -# text=json.dumps(return_json, separators=(",", ":")), -# content_type="application/json", -# ) -# except Exception as e: -# return_json = {"success": False, "message": "request error."} -# response = web.Response( -# text=json.dumps(return_json, separators=(",", ":")), -# content_type="application/json", -# ) -# finally: -# self._add_cors_headers(response) -# return response - -# async def handle_get(self, request): -# """处理 OTA GET 请求""" -# try: -# server_config = self.config["server"] -# local_ip = get_local_ip() -# port = int(server_config.get("port", 8000)) -# websocket_url = self._get_websocket_url(local_ip, port) -# message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}" -# response = web.Response(text=message, content_type="text/plain") -# except Exception as e: -# self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}") -# response = web.Response(text="OTA接口异常", content_type="text/plain") -# finally: -# self._add_cors_headers(response) -# return response - - - import json import time import uuid @@ -150,17 +23,18 @@ class OTAHandler(BaseHandler): def __init__(self, config: dict): super().__init__(config) # Load MQTT signature key from environment or config - self.mqtt_signature_key = os.getenv('MQTT_SIGNATURE_KEY', 'test-signature-key-12345') + self.mqtt_signature_key = os.getenv( + 'MQTT_SIGNATURE_KEY', 'test-signature-key-12345') def _get_websocket_url(self, local_ip: str, port: int) -> str: - """获取websocket地址 + """Get 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", "") @@ -171,35 +45,36 @@ class OTAHandler(BaseHandler): return f"ws://{local_ip}:{port}/xiaozhi/v1/" def _generate_mqtt_credentials(self, device_id: str, client_ip: str) -> dict: - """生成MQTT凭据 + """Generate MQTT credentials Args: - device_id: 设备ID (MAC地址格式) - client_ip: 客户端IP地址 + device_id: Device ID (MAC address format) + client_ip: Client IP address Returns: - dict: MQTT凭据信息 + dict: MQTT credential information """ # Convert MAC address format (remove colons, use underscores) mac_address = device_id.replace(":", "_") - + # Generate UUID for this session client_uuid = str(uuid.uuid4()) - + # Create client ID in format: GID_test@@@mac_address@@@uuid group_id = "GID_test" client_id = f"{group_id}@@@{mac_address}@@@{client_uuid}" - + # Create user data and encode as base64 JSON user_data = {"ip": client_ip} username = base64.b64encode(json.dumps(user_data).encode()).decode() - + # Generate password signature content = f"{client_id}|{username}" password = base64.b64encode( - hmac.new(self.mqtt_signature_key.encode(), content.encode(), hashlib.sha256).digest() + hmac.new(self.mqtt_signature_key.encode(), + content.encode(), hashlib.sha256).digest() ).decode() - + return { "client_id": client_id, "username": username, @@ -207,25 +82,29 @@ class OTAHandler(BaseHandler): } 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 headers: {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) - + # Get client IP address client_ip = request.remote if request.headers.get('X-Forwarded-For'): - client_ip = request.headers.get('X-Forwarded-For').split(',')[0].strip() + client_ip = request.headers.get( + 'X-Forwarded-For').split(',')[0].strip() elif request.headers.get('X-Real-IP'): client_ip = request.headers.get('X-Real-IP') @@ -239,12 +118,13 @@ class OTAHandler(BaseHandler): mqtt_broker = mqtt_config.get("broker", local_ip) mqtt_port = mqtt_config.get("port", 1883) udp_port = mqtt_config.get("udp_port", 8884) - + # Generate MQTT credentials if MQTT is enabled mqtt_credentials = None if mqtt_enabled: - mqtt_credentials = self._generate_mqtt_credentials(device_id, client_ip) - + mqtt_credentials = self._generate_mqtt_credentials( + device_id, client_ip) + return_json = { "server_time": { "timestamp": int(round(time.time() * 1000)), @@ -258,7 +138,7 @@ class OTAHandler(BaseHandler): "url": self._get_websocket_url(local_ip, port), }, } - + # Add MQTT credentials in the new format if enabled if mqtt_enabled and mqtt_credentials: return_json["mqtt"] = { @@ -290,13 +170,13 @@ class OTAHandler(BaseHandler): "frame_duration": 60 } }) - + response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", ) except Exception as e: - self.logger.bind(tag=TAG).error(f"OTA POST请求异常: {e}") + self.logger.bind(tag=TAG).error(f"OTA POST request exception: {e}") return_json = {"success": False, "message": "request error."} response = web.Response( text=json.dumps(return_json, separators=(",", ":")), @@ -307,35 +187,37 @@ 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)) http_port = server_config.get("http_port", 8003) websocket_url = self._get_websocket_url(local_ip, port) - + # Get MQTT gateway configuration mqtt_config = server_config.get("mqtt_gateway", {}) mqtt_enabled = mqtt_config.get("enabled", False) mqtt_broker = mqtt_config.get("broker", local_ip) mqtt_port = mqtt_config.get("port", 1883) udp_port = mqtt_config.get("udp_port", 8884) - - message = f"""OTA接口运行正常 -服务器配置信息: -- WebSocket地址: {websocket_url} -- HTTP端口: {http_port} -- WebSocket端口: {port} -- MQTT网关: {'启用' if mqtt_enabled else '禁用'} -- MQTT代理: {mqtt_broker}:{mqtt_port} -- UDP端口: {udp_port} -- 服务器IP: {local_ip}""" - - response = web.Response(text=message, content_type="text/plain; charset=utf-8") + + message = f"""OTA interface running normally +Server configuration information: +- WebSocket address: {websocket_url} +- HTTP port: {http_port} +- WebSocket port: {port} +- MQTT gateway: {'Enabled' if mqtt_enabled else 'Disabled'} +- MQTT broker: {mqtt_broker}:{mqtt_port} +- UDP port: {udp_port} +- Server IP: {local_ip}""" + + response = web.Response( + text=message, content_type="text/plain; charset=utf-8") 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 diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py index 70be247af..2c8b2466c 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 maximum file size to 5MB MAX_FILE_SIZE = 5 * 1024 * 1024 @@ -20,81 +20,83 @@ class VisionHandler: def __init__(self, config: dict): self.config = config self.logger = setup_logging() - # 初始化认证工具 + # Initialize authentication tool self.auth = AuthToken(config["server"]["auth_key"]) def _create_error_response(self, message: str) -> dict: - """创建统一的错误响应格式""" + """Create unified error response format""" return {"success": False, "message": message} def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]: - """验证认证token""" + """Verify 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 "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 response variable try: - # 验证token + # Verify 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 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") + # Parse multipart/form-data request reader = await request.multipart() - # 读取question字段 + # Read question field question_field = await reader.next() if question_field is None: - raise ValueError("缺少问题字段") + raise ValueError("Missing question 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"Image size exceeds limit, maximum allowed {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格式)" + "Unsupported file format, please upload a valid image file (supports JPEG, PNG, GIF, BMP, TIFF, WEBP formats)" ) - # 将图片转换为base64编码 + # Convert image to base64 encoding image_base64 = base64.b64encode(image_data).decode("utf-8") - # 如果开启了智控台,则从智控台获取模型配置 + # If smart control panel is enabled, get model configuration from smart control panel current_config = copy.deepcopy(self.config) - read_config_from_api = current_config.get("read_config_from_api", False) + read_config_from_api = current_config.get( + "read_config_from_api", False) if read_config_from_api: current_config = get_private_config_from_api( current_config, @@ -104,7 +106,8 @@ class VisionHandler: select_vllm_module = current_config["selected_module"].get("VLLM") if not select_vllm_module: - raise ValueError("您还未设置默认的视觉分析模块") + raise ValueError( + "You have not set a default vision analysis module yet") vllm_type = ( select_vllm_module @@ -113,7 +116,8 @@ class VisionHandler: ) if not vllm_type: - raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") + raise ValueError( + f"Cannot find VLLM module corresponding provider {vllm_type}") vllm = create_instance( vllm_type, current_config["VLLM"][select_vllm_module] @@ -132,15 +136,18 @@ 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( + "Error occurred while processing request") response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", @@ -151,20 +158,21 @@ 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 running normally, vision explanation interface address is: {vision_explain}" ) else: - message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址" + message = "MCP Vision interface not running normally, please open the .config.yaml file in the data directory, find [server.vision_explain], and set the address properly" 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("Internal server error") response = web.Response( text=json.dumps(return_json, separators=(",", ":")), content_type="application/json", @@ -174,7 +182,7 @@ 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" ) diff --git a/main/xiaozhi-server/core/auth.py b/main/xiaozhi-server/core/auth.py index ef6431326..061fa2302 100755 --- a/main/xiaozhi-server/core/auth.py +++ b/main/xiaozhi-server/core/auth.py @@ -1,54 +1,54 @@ from config.logger import setup_logging TAG = __name__ + logger = setup_logging() - class AuthenticationError(Exception): - """认证异常""" + """Authentication exception""" pass - class AuthMiddleware: def __init__(self, config): self.config = config self.auth_config = config["server"].get("auth", {}) - # 构建token查找表 + + # Build 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 device is in whitelist device_id = headers.get("device-id", "") - if self.allowed_devices and device_id in self.allowed_devices: return True - - # 验证Authorization header + + # Verify Authorization header auth_header = headers.get("authorization", "") if not auth_header.startswith("Bearer "): logger.bind(tag=TAG).error("Missing or invalid Authorization header") raise AuthenticationError("Missing or invalid Authorization header") - + token = auth_header.split(" ")[1] if token not in self.tokens: logger.bind(tag=TAG).error(f"Invalid token: {token}") raise AuthenticationError("Invalid token") - + logger.bind(tag=TAG).info(f"Authentication successful - Device: {device_id}, Token: {self.tokens[token]}") return True - + def get_token_name(self, token): - """获取token对应的设备名称""" - return self.tokens.get(token) + """Get device name corresponding to 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 6b7e3d1fb..7ce99a53f 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -65,12 +65,13 @@ 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 a reference to the server instance self.auth = AuthMiddleware(config) self.need_bind = False self.bind_code = None - self.read_config_from_api = self.config.get("read_config_from_api", False) + self.read_config_from_api = self.config.get( + "read_config_from_api", False) self.websocket = None self.headers = None @@ -82,24 +83,24 @@ class ConnectionHandler: self.chat_history_conf = 0 self.audio_format = "opus" - # 客户端状态相关 + # Client state related self.client_abort = False self.client_is_speaking = False self.client_listen_mode = "auto" - # 线程任务相关 + # Thread task related self.loop = asyncio.get_event_loop() self.stop_event = threading.Event() self.executor = ThreadPoolExecutor(max_workers=5) - # 添加上报线程池 + # Add reporting thread pool self.report_queue = queue.Queue() self.report_thread = None - # 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启 + # This can be modified in the future to adjust ASR and TTS reporting. Currently, both are enabled by default. self.report_asr_enable = self.read_config_from_api self.report_tts_enable = self.read_config_from_api - # 依赖的组件 + # Dependent components self.vad = None self.asr = None self.tts = None @@ -109,33 +110,34 @@ class ConnectionHandler: 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 # 统一的活动时间戳(毫秒) + # Unified activity timestamp (milliseconds) + self.last_activity_time = 0.0 self.client_voice_stop = False self.client_voice_window = deque(maxlen=5) self.last_is_voice = False - # asr相关变量 - # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR - # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量 + # ASR related variables + # Since a public local ASR might be used in actual deployment, variables cannot be exposed to the public ASR. + # Therefore, variables related to ASR need to be defined here as private variables of the connection. self.asr_audio = [] self.asr_audio_queue = queue.Queue() - # llm相关变量 + # LLM related variables self.llm_finish_task = True self.dialogue = Dialogue() - # tts相关变量 + # TTS related variables self.sentence_id = None - # 处理TTS响应没有文本返回 + # Handle cases where TTS response has no text self.tts_MessageText = "" - # iot相关变量 + # IoT related variables self.iot_descriptors = {} self.func_handler = None @@ -145,35 +147,36 @@ class ConnectionHandler: if len(cmd) > self.max_cmd_length: self.max_cmd_length = len(cmd) - # 是否在聊天结束后关闭连接 + # Whether to close the connection after the chat ends self.close_after_chat = False self.load_function_plugin = False self.intent_type = "nointent" self.timeout_seconds = ( int(self.config.get("close_connection_no_voice_time", 120)) + 60 - ) # 在原来第一道关闭的基础上加60秒,进行二道关闭 + ) # Add 60 seconds to the original first-level close for a second-level close self.timeout_task = None - # {"mcp":true} 表示启用MCP功能 + # {"mcp":true} indicates that the MCP function is enabled self.features = None - # 初始化提示词管理器 + # Initialize prompt manager self.prompt_manager = PromptManager(config, self.logger) async def handle_connection(self, ws): try: - # 获取并验证headers + # Get and validate headers self.headers = dict(ws.request.headers) if self.headers.get("device-id", None) is None: - # 尝试从 URL 的查询参数中获取 device-id + # Try to get device-id from the URL's query parameters 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 get request path") return parsed_url = urlparse(request_path) query_params = parse_qs(parsed_url.query) @@ -181,7 +184,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("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( @@ -195,89 +198,92 @@ class ConnectionHandler: f"{self.client_ip} conn - Headers: {self.headers}" ) - # 进行认证 + # Perform authentication await self.auth.authenticate(self.headers) - # 认证通过,继续处理 + # Authentication passed, continue processing self.websocket = ws self.device_id = self.headers.get("device-id", None) - # 初始化活动时间戳 + # Initialize activity timestamp self.last_activity_time = time.time() * 1000 - # 启动超时检查任务 + # Start timeout check task self.timeout_task = asyncio.create_task(self._check_timeout()) self.welcome_msg = self.config["xiaozhi"] self.welcome_msg["session_id"] = self.session_id - # 获取差异化配置 + # Get differential configuration self._initialize_private_config() - # 异步初始化 + # Asynchronous initialization self.executor.submit(self._initialize_components) try: async for message in self.websocket: await self._route_message(message) except websockets.exceptions.ConnectionClosed: - self.logger.bind(tag=TAG).info("客户端断开连接") + self.logger.bind(tag=TAG).info("Client disconnected") except AuthenticationError as e: self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}") return except Exception as e: stack_trace = traceback.format_exc() - self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}") + self.logger.bind(tag=TAG).error( + f"Connection error: {str(e)}-{stack_trace}") return finally: try: await self._save_and_close(ws) except Exception as final_error: - self.logger.bind(tag=TAG).error(f"最终清理时出错: {final_error}") - # 确保即使保存记忆失败,也要关闭连接 + self.logger.bind(tag=TAG).error( + f"Error during final cleanup: {final_error}") + # Ensure the connection is closed even if saving memory fails try: await self.close(ws) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"强制关闭连接时出错: {close_error}" + f"Error during forced connection closure: {close_error}" ) async def _save_and_close(self, ws): - """保存记忆并关闭连接""" + """Save memory and close the connection""" try: if self.memory: - # 使用线程池异步保存记忆 + # Use a thread pool to save memory asynchronously def save_memory_task(): try: - # 创建新事件循环(避免与主循环冲突) + # Create a new event loop (to avoid conflicts with the main loop) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete( self.memory.save_memory(self.dialogue.dialogue) ) except Exception as e: - self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}") + self.logger.bind(tag=TAG).error( + f"Failed to save memory: {e}") finally: try: loop.close() except Exception: pass - # 启动线程保存记忆,不等待完成 + # Start a thread to save memory, do not wait for completion threading.Thread(target=save_memory_task, daemon=True).start() except Exception as e: - self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}") + self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}") finally: - # 立即关闭连接,不等待记忆保存完成 + # Close the connection immediately, do not wait for memory saving to complete try: await self.close(ws) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"保存记忆后关闭连接失败: {close_error}" + f"Failed to close connection after saving memory: {close_error}" ) async def _route_message(self, message): - """消息路由""" + """Message routing""" if isinstance(message, str): await handleTextMessage(self, message) elif isinstance(message, bytes): @@ -288,28 +294,29 @@ class ConnectionHandler: self.asr_audio_queue.put(message) 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 command, preparing 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(): - """实际执行重启的方法""" + """The actual method to execute the restart""" time.sleep(1) - self.logger.bind(tag=TAG).info("执行服务器重启...") + self.logger.bind(tag=TAG).info("Executing server restart...") subprocess.Popen( [sys.executable, "app.py"], stdin=sys.stdin, @@ -319,11 +326,11 @@ class ConnectionHandler: ) os._exit(0) - # 使用线程执行重启避免阻塞事件循环 + # Use a thread to execute the restart to avoid blocking the event loop threading.Thread(target=restart_server, daemon=True).start() except Exception as e: - self.logger.bind(tag=TAG).error(f"重启失败: {str(e)}") + self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}") await self.websocket.send( json.dumps( { @@ -342,60 +349,62 @@ 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"] - # 使用快速提示词进行初始化 + # Use a quick prompt for initialization prompt = self.prompt_manager.get_quick_prompt(user_prompt) self.change_system_prompt(prompt) self.logger.bind(tag=TAG).info( - f"快速初始化组件: prompt成功 {prompt[:50]}..." + f"Quickly initialized component: prompt successful {prompt[:50]}..." ) - """初始化本地组件""" + """Initialize local components""" if self.vad is None: self.vad = self._vad if self.asr is None: self.asr = self._initialize_asr() - # 初始化声纹识别 + # Initialize voiceprint recognition self._initialize_voiceprint() - # 打开语音识别通道 + # Open speech recognition channel asyncio.run_coroutine_threadsafe( self.asr.open_audio_channels(self), self.loop ) if self.tts is None: self.tts = self._initialize_tts() - # 打开语音合成通道 + # Open speech synthesis channel asyncio.run_coroutine_threadsafe( self.tts.open_audio_channels(self), self.loop ) - """加载记忆""" + """Load memory""" self._initialize_memory() - """加载意图识别""" + """Load intent recognition""" self._initialize_intent() - """初始化上报线程""" + """Initialize reporting thread""" self._init_report_threads() - """更新系统提示词""" + """Update system prompt""" self._init_prompt_enhancement() except Exception as e: - self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") + self.logger.bind(tag=TAG).error( + f"Failed to instantiate components: {e}") def _init_prompt_enhancement(self): - # 更新上下文信息 + # Update context information self.prompt_manager.update_context_info(self, self.client_ip) enhanced_prompt = self.prompt_manager.build_enhanced_prompt( self.config["prompt"], self.device_id, self.client_ip ) if enhanced_prompt: self.change_system_prompt(enhanced_prompt) - self.logger.bind(tag=TAG).info("系统提示词已增强更新") + self.logger.bind(tag=TAG).info( + "System prompt has 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: @@ -405,10 +414,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 started") def _initialize_tts(self): - """初始化TTS""" + """Initialize TTS""" tts = None if not self.need_bind: tts = initialize_tts(self.config) @@ -419,35 +428,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 one local ASR instance 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 a remote ASR involves a WebSocket connection and a receiving thread, each connection needs its own instance asr = initialize_asr(self.config) return asr def _initialize_voiceprint(self): - """为当前连接初始化声纹识别""" + """Initialize voiceprint recognition for the current connection""" try: voiceprint_config = self.config.get("voiceprint", {}) if voiceprint_config: - self.voiceprint_provider = VoiceprintProvider(voiceprint_config) - self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用") + self.voiceprint_provider = VoiceprintProvider( + voiceprint_config) + self.logger.bind(tag=TAG).info( + "Voiceprint recognition function dynamically enabled on connection") else: - self.logger.bind(tag=TAG).info("声纹识别功能未启用或配置不完整") + self.logger.bind(tag=TAG).info( + "Voiceprint recognition function not enabled or configuration is incomplete") except Exception as e: - self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}") + self.logger.bind(tag=TAG).warning( + f"Voiceprint recognition initialization failed: {str(e)}") def _initialize_private_config(self): - """如果是从配置文件获取,则进行二次实例化""" + """If getting from the configuration file, perform a second instantiation""" if not self.read_config_from_api: return - """从接口获取差异化的配置进行二次实例化,非全量重新实例化""" + """Get differential configuration from the interface for a second instantiation, not a full re-instantiation""" try: begin_time = time.time() private_config = get_private_config_from_api( @@ -455,9 +468,10 @@ class ConnectionHandler: self.headers.get("device-id"), self.headers.get("client-id", self.headers.get("device-id")), ) - private_config["delete_audio"] = bool(self.config.get("delete_audio", True)) + 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, successfully obtained differential configuration: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" ) except DeviceNotFoundException as e: self.need_bind = True @@ -468,7 +482,8 @@ 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 = ( @@ -517,9 +532,10 @@ class ConnectionHandler: if private_config.get("Intent", None) is not None: init_intent = True self.config["Intent"] = private_config["Intent"] - model_intent = private_config.get("selected_module", {}).get("Intent", {}) + 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(): @@ -527,16 +543,17 @@ class ConnectionHandler: self.config["plugins"] = plugin_from_server self.config["Intent"][self.config["selected_module"]["Intent"]][ "functions" - ] = plugin_from_server.keys() + ] = list(plugin_from_server.keys()) if private_config.get("prompt", None) is not None: self.config["prompt"] = private_config["prompt"] - # 获取声纹信息 + # Get voiceprint information if private_config.get("voiceprint", None) is not None: self.config["voiceprint"] = private_config["voiceprint"] if private_config.get("summaryMemory", None) is not None: self.config["summaryMemory"] = private_config["summaryMemory"] if private_config.get("device_max_output_size", None) is not None: - self.max_output_size = int(private_config["device_max_output_size"]) + self.max_output_size = int( + private_config["device_max_output_size"]) if private_config.get("chat_history_conf", None) is not None: self.chat_history_conf = int(private_config["chat_history_conf"]) if private_config.get("mcp_endpoint", None) is not None: @@ -553,7 +570,8 @@ 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 components: {e}") modules = {} if modules.get("tts", None) is not None: self.tts = modules["tts"] @@ -571,7 +589,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, @@ -579,36 +597,38 @@ 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 using nomem, return directly if memory_type == "nomem": return - # 使用 mem_local_short 模式 + # Use mem_local_short mode elif memory_type == "mem_local_short": memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][ "llm" ] if memory_llm_name and memory_llm_name in self.config["LLM"]: - # 如果配置了专用LLM,则创建独立的LLM实例 + # If a dedicated LLM is configured, create an independent LLM instance from core.utils import llm as llm_utils memory_llm_config = self.config["LLM"][memory_llm_name] - memory_llm_type = memory_llm_config.get("type", memory_llm_name) + memory_llm_type = memory_llm_config.get( + "type", memory_llm_name) memory_llm = llm_utils.create_instance( memory_llm_type, memory_llm_config ) self.logger.bind(tag=TAG).info( - f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}" + f"Created a dedicated LLM for memory summary: {memory_llm_name}, type: {memory_llm_type}" ) self.memory.set_llm(memory_llm) else: - # 否则使用主LLM + # Otherwise use main LLM self.memory.set_llm(self.llm) - self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型") + self.logger.bind(tag=TAG).info( + "Using main LLM as intent recognition model") def _initialize_intent(self): if self.intent is None: @@ -618,60 +638,63 @@ class ConnectionHandler: ]["type"] if self.intent_type == "function_call" or self.intent_type == "intent_llm": self.load_function_plugin = True - """初始化意图识别模块""" - # 获取意图识别配置 + """Initialize intent recognition module""" + # Get intent recognition configuration intent_config = self.config["Intent"] intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][ "type" ] - # 如果使用 nointent,直接返回 + # If using nointent, return directly if intent_type == "nointent": return - # 使用 intent_llm 模式 + # Use intent_llm mode elif intent_type == "intent_llm": intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ "llm" ] if intent_llm_name and intent_llm_name in self.config["LLM"]: - # 如果配置了专用LLM,则创建独立的LLM实例 + # If a dedicated LLM is configured, create an independent LLM instance from core.utils import llm as llm_utils intent_llm_config = self.config["LLM"][intent_llm_name] - intent_llm_type = intent_llm_config.get("type", intent_llm_name) + intent_llm_type = intent_llm_config.get( + "type", intent_llm_name) intent_llm = llm_utils.create_instance( intent_llm_type, intent_llm_config ) self.logger.bind(tag=TAG).info( - f"为意图识别创建了专用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 main LLM self.intent.set_llm(self.llm) - self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型") + self.logger.bind(tag=TAG).info( + "Using main LLM as intent recognition model") - """加载统一工具处理器""" + """Load unified tool handler""" self.func_handler = UnifiedToolHandler(self) - # 异步初始化工具处理器 + # Asynchronously initialize tool handler if hasattr(self, "loop") and self.loop: - asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop) + asyncio.run_coroutine_threadsafe( + self.func_handler._initialize(), self.loop) def change_system_prompt(self, prompt): self.prompt = prompt - # 更新系统prompt至上下文 + # Update system prompt in the context self.dialogue.update_system_message(self.prompt) def chat(self, query, tool_call=False, depth=0): - self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") + self.logger.bind(tag=TAG).info(f"LLM received user message: {query}") self.llm_finish_task = False if not tool_call: self.dialogue.put(Message(role="user", content=query)) - # 为最顶层时新建会话ID和发送FIRST请求 + # Create a new session ID and send a FIRST request for the top-level call if depth == 0: self.sentence_id = str(uuid.uuid4().hex) self.tts.tts_text_queue.put( @@ -689,7 +712,7 @@ class ConnectionHandler: response_message = [] try: - # 使用带记忆的对话 + # Use dialogue with memory memory_str = None if self.memory is not None: future = asyncio.run_coroutine_threadsafe( @@ -698,7 +721,7 @@ class ConnectionHandler: memory_str = future.result() if self.intent_type == "function_call" and functions is not None: - # 使用支持functions的streaming接口 + # Use streaming interface that supports functions llm_responses = self.llm.response_with_functions( self.session_id, self.dialogue.get_llm_dialogue_with_memory( @@ -714,10 +737,11 @@ 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 for '{query}': {e}") return None - # 处理流式响应 + # Handle streaming response tool_call_flag = False function_name = None function_id = None @@ -751,7 +775,7 @@ class ConnectionHandler: else: content = response - # 在llm回复中获取情绪表情,一轮对话只在开头获取一次 + # Get emotion from LLM reply, only once at the beginning of a conversation turn if emotion_flag and content is not None and content.strip(): asyncio.run_coroutine_threadsafe( textUtils.get_emotion(self, content), @@ -770,7 +794,7 @@ class ConnectionHandler: content_detail=content, ) ) - # 处理function call + # Handle function call if tool_call_flag: bHasError = False if function_id is None: @@ -794,11 +818,12 @@ class ConnectionHandler: f"function call error: {content_arguments}" ) if not bHasError: - # 如需要大模型先处理一轮,添加相关处理后的日志情况 + # If the LLM needs to process a turn first, add relevant processed log information if len(response_message) > 0: text_buff = "".join(response_message) self.tts_MessageText = text_buff - self.dialogue.put(Message(role="assistant", content=text_buff)) + self.dialogue.put( + Message(role="assistant", content=text_buff)) response_message.clear() self.logger.bind(tag=TAG).debug( f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}" @@ -809,16 +834,17 @@ class ConnectionHandler: "arguments": function_arguments, } - # 使用统一工具处理器处理所有工具调用 + # Use unified tool handler to process all tool calls result = asyncio.run_coroutine_threadsafe( self.func_handler.handle_llm_function_call( self, function_call_data ), self.loop, ).result() - self._handle_function_result(result, function_call_data, depth=depth) + self._handle_function_result( + result, function_call_data, depth=depth) - # 存储对话内容 + # Store dialogue content if len(response_message) > 0: text_buff = "".join(response_message) self.tts_MessageText = text_buff @@ -832,7 +858,7 @@ class ConnectionHandler: ) ) self.llm_finish_task = True - # 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue() + # Use lambda for delayed calculation, get_llm_dialogue() is only executed at DEBUG level self.logger.bind(tag=TAG).debug( lambda: json.dumps( self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False @@ -842,11 +868,12 @@ class ConnectionHandler: return True def _handle_function_result(self, result, function_call_data, depth): - if result.action == Action.RESPONSE: # 直接回复前端 + if result.action == Action.RESPONSE: # Respond directly to the front-end text = result.response - self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text) + self.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: # Request LLM to generate a reply after calling the function text = result.result if text is not None and len(text) > 0: function_id = function_call_data["id"] @@ -881,53 +908,57 @@ class ConnectionHandler: self.chat(text, tool_call=True, depth=depth + 1) elif result.action == Action.NOTFOUND or result.action == Action.ERROR: text = result.response if result.response else result.result - self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text) + self.tts.tts_one_sentence( + self, ContentType.TEXT, content_detail=text) self.dialogue.put(Message(role="assistant", content=text)) else: pass def _report_worker(self): - """聊天记录上报工作线程""" + """Chat history reporting worker thread""" while not self.stop_event.is_set(): try: - # 从队列获取数据,设置超时以便定期检查停止事件 + # Get data from the queue, set a timeout to periodically check the stop event item = self.report_queue.get(timeout=1) - if item is None: # 检测毒丸对象 + if item is None: # Detect the poison pill object break try: - # 检查线程池状态 + # Check the thread pool status if self.executor is None: continue - # 提交任务到线程池 + # Submit the task to the thread pool self.executor.submit(self._process_report, *item) except Exception as e: - self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}") + self.logger.bind(tag=TAG).error( + f"Chat history reporting thread exception: {e}") except queue.Empty: continue except Exception as e: - self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}") + self.logger.bind(tag=TAG).error( + f"Chat history reporting worker thread exception: {e}") - self.logger.bind(tag=TAG).info("聊天记录上报线程已退出") + self.logger.bind(tag=TAG).info("Chat history reporting thread exited") def _process_report(self, type, text, audio_data, report_time): - """处理上报任务""" + """Process the reporting task""" try: - # 执行上报(传入二进制数据) + # Execute the report (pass binary data) report(self, type, text, audio_data, report_time) except Exception as e: - self.logger.bind(tag=TAG).error(f"上报处理异常: {e}") + self.logger.bind(tag=TAG).error( + f"Report processing exception: {e}") finally: - # 标记任务完成 + # Mark the task as done self.report_queue.task_done() def clearSpeakStatus(self): self.client_is_speaking = False - self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态") + self.logger.bind(tag=TAG).debug(f"Cleared server speaking status") async def close(self, ws=None): - """资源清理方法""" + """Resource cleanup method""" try: - # 取消超时任务 + # Cancel the timeout task if self.timeout_task and not self.timeout_task.done(): self.timeout_task.cancel() try: @@ -936,36 +967,36 @@ class ConnectionHandler: pass self.timeout_task = None - # 清理工具处理器资源 + # Clean up tool handler resources if hasattr(self, "func_handler") and self.func_handler: try: await self.func_handler.cleanup() except Exception as cleanup_error: self.logger.bind(tag=TAG).error( - f"清理工具处理器时出错: {cleanup_error}" + f"Error cleaning up tool handler: {cleanup_error}" ) - # 触发停止事件 + # Trigger the stop event if self.stop_event: self.stop_event.set() - # 清空任务队列 + # Clear task queues self.clear_queues() - # 关闭WebSocket连接 + # Close the WebSocket connection try: if ws: - # 安全地检查WebSocket状态并关闭 + # Safely check WebSocket state and close try: if hasattr(ws, "closed") and not ws.closed: await ws.close() elif hasattr(ws, "state") and ws.state.name != "CLOSED": await ws.close() else: - # 如果没有closed属性,直接尝试关闭 + # If no closed attribute, try to close directly await ws.close() except Exception: - # 如果关闭失败,忽略错误 + # If closing fails, ignore the error pass elif self.websocket: try: @@ -980,43 +1011,45 @@ class ConnectionHandler: ): await self.websocket.close() else: - # 如果没有closed属性,直接尝试关闭 + # If no closed attribute, try to close directly await self.websocket.close() except Exception: - # 如果关闭失败,忽略错误 + # If closing fails, ignore the error pass except Exception as ws_error: - self.logger.bind(tag=TAG).error(f"关闭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 thread pool (avoid blocking) if self.executor: try: self.executor.shutdown(wait=False) except Exception as executor_error: self.logger.bind(tag=TAG).error( - f"关闭线程池时出错: {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 released") except Exception as e: - self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}") + self.logger.bind(tag=TAG).error( + f"Error occurred while closing connection: {e}") finally: - # 确保停止事件被设置 + # Ensure the stop event is set if self.stop_event: self.stop_event.set() def clear_queues(self): - """清空所有任务队列""" + """Clear all task queues""" if self.tts: self.logger.bind(tag=TAG).debug( - f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}" + f"Starting cleanup: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}" ) - # 使用非阻塞方式清空队列 + # Use non-blocking method to clear queues for q in [ self.tts.tts_text_queue, self.tts.tts_audio_queue, @@ -1031,7 +1064,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): @@ -1052,10 +1085,10 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") async def _check_timeout(self): - """检查连接超时""" + """Check for connection timeout""" try: while not self.stop_event.is_set(): - # 检查是否超时(只有在时间戳已初始化的情况下) + # Check for timeout (only if the timestamp has been initialized) if self.last_activity_time > 0.0: current_time = time.time() * 1000 if ( @@ -1063,20 +1096,21 @@ 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, preparing to close") + # Set the stop event to prevent duplicate processing self.stop_event.set() - # 使用 try-except 包装关闭操作,确保不会因为异常而阻塞 + # Use try-except to wrap the close operation, ensuring no blocking due to exceptions try: await self.close(self.websocket) except Exception as close_error: self.logger.bind(tag=TAG).error( - f"超时关闭连接时出错: {close_error}" + f"Error closing connection on timeout: {close_error}" ) break - # 每10秒检查一次,避免过于频繁 + # Check every 10 seconds to avoid being 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("超时检查任务已退出") \ No newline at end of file + self.logger.bind(tag=TAG).info("Timeout check task has exited") diff --git a/main/xiaozhi-server/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/abortHandle.py index ce6f22b6c..d8808d471 100644 --- a/main/xiaozhi-server/core/handle/abortHandle.py +++ b/main/xiaozhi-server/core/handle/abortHandle.py @@ -5,12 +5,12 @@ TAG = __name__ async def handleAbortMessage(conn): conn.logger.bind(tag=TAG).info("Abort message received") - # 设置成打断状态,会自动打断llm、tts任务 + # Set to interrupt state, 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}) ) conn.clearSpeakStatus() - conn.logger.bind(tag=TAG).info("Abort message received-end") + conn.logger.bind(tag=TAG).info("Abort message received-end") \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 93f09c4d6..17a4b3973 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -21,39 +21,39 @@ WAKEUP_CONFIG = { "words": ["你好", "你好啊", "嘿,你好", "嗨"], } -# 创建全局的唤醒词配置管理器 +# Create global wakeup words configuration manager wakeup_words_config = WakeupWordsConfig() -# 用于防止并发调用wakeupWordsResponse的锁 +# Lock to prevent concurrent calls to wakeupWordsResponse _wakeup_response_lock = asyncio.Lock() async def handleHelloMessage(conn, msg_json): - """处理hello消息""" + """Handle hello message""" audio_params = msg_json.get("audio_params") if audio_params: format = audio_params.get("format") - conn.logger.bind(tag=TAG).info(f"客户端音频格式: {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 - + # Handle both list and dictionary formats for features has_mcp = False if isinstance(features, list): has_mcp = "mcp" in features elif isinstance(features, dict): has_mcp = features.get("mcp", False) - + if has_mcp: - conn.logger.bind(tag=TAG).info("客户端支持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)) @@ -74,12 +74,12 @@ async def checkWakeupWords(conn, text): conn.just_woken_up = True await send_stt_message(conn, text) - # 获取当前音色 + # Get current voice voice = getattr(conn.tts, "voice", "default") if not voice: voice = "default" - # 获取唤醒词回复配置 + # Get wakeup words reply configuration response = wakeup_words_config.get_wakeup_response(voice) if not response or not response.get("file_path"): response = { @@ -89,18 +89,19 @@ async def checkWakeupWords(conn, text): "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦", } - # 播放唤醒词回复 + # Play wakeup words reply conn.client_abort = False opus_packets, _ = audio_to_data(response.get("file_path")) - conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}") + conn.logger.bind(tag=TAG).info( + f"Playing wakeup words reply: {response.get('text')}") await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text")) await sendAudioMessage(conn, SentenceType.LAST, [], None) - # 补充对话 + # Add to dialogue conn.dialogue.put(Message(role="assistant", content=response.get("text"))) - # 检查是否需要更新唤醒词回复 + # Check if wakeup words reply needs to be updated if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: if not _wakeup_response_lock.locked(): asyncio.create_task(wakeupWordsResponse(conn)) @@ -112,38 +113,38 @@ async def wakeupWordsResponse(conn): return try: - # 尝试获取锁,如果获取不到就返回 + # Try to acquire lock, return if cannot acquire if not await _wakeup_response_lock.acquire(): return - # 生成唤醒词回复 + # Generate wakeup words reply wakeup_word = random.choice(WAKEUP_CONFIG["words"]) question = ( - "此刻用户正在和你说```" + "The user is currently saying ```" + wakeup_word - + "```。\n请你根据以上用户的内容进行20-30字回复。要符合系统设置的角色情感和态度,不要像机器人一样说话。\n" - + "请勿对这条内容本身进行任何解释和回应,请勿返回表情符号,仅返回对用户的内容的回复。" + + "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n" + + "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content." ) result = conn.llm.response_no_stream(conn.config["prompt"], question) if not result or len(result) == 0: return - # 生成TTS音频 + # Generate TTS audio tts_result = await asyncio.to_thread(conn.tts.to_tts, result) if not tts_result: return - # 获取当前音色 + # Get current voice voice = getattr(conn.tts, "voice", "default") wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000) file_path = wakeup_words_config.generate_file_path(voice) with open(file_path, "wb") as f: f.write(wav_bytes) - # 更新配置 + # Update configuration wakeup_words_config.update_wakeup_response(voice, file_path, result) finally: - # 确保在任何情况下都释放锁 + # Ensure lock is released in any case if _wakeup_response_lock.locked(): _wakeup_response_lock.release() diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index d04f9e6b8..9679dd48b 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -13,44 +13,47 @@ TAG = __name__ async def handle_user_intent(conn, text): - # 预处理输入文本,处理可能的JSON格式 + # Preprocess input text, 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") # 保留说话人信息 + # Extract content for intent analysis + text = parsed_data["content"] + conn.current_speaker = parsed_data.get( + "speaker") # Preserve speaker information except (json.JSONDecodeError, TypeError): pass - # 检查是否有明确的退出命令 + # Check if there is an explicit exit command filtered_text = remove_punctuation_and_length(text)[1] if await check_direct_exit(conn, filtered_text): return True - # 检查是否是唤醒词 + # Check if it's a wake-up word if await checkWakeupWords(conn, filtered_text): return True if conn.intent_type == "function_call": - # 使用支持function calling的聊天方法,不再进行意图分析 + # Use chat method that supports function calling, 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 at the beginning of the conversation conn.sentence_id = str(uuid.uuid4().hex) - # 处理各种意图 + # Handle 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"Recognized explicit exit command: {text}") await send_stt_message(conn, text) await conn.close() return True @@ -58,33 +61,34 @@ async def check_direct_exit(conn, text): async def analyze_intent_with_llm(conn, text): - """使用LLM分析用户意图""" + """Use 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 not initialized") return None - # 对话历史记录 + # Conversation history records 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 a function_call if "function_call" in intent_data: - # 直接从意图识别获取了function_call + # Directly obtained function_call from intent recognition conn.logger.bind(tag=TAG).debug( - f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}" + f"Detected function_call format intent result: {intent_data['function_call']['name']}" ) function_name = intent_data["function_call"]["name"] if function_name == "continue_chat": @@ -95,7 +99,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 parameters are in string format JSON if isinstance(function_args, dict): function_args = json.dumps(function_args) @@ -108,11 +112,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 unified tool handler to process all tool calls try: result = asyncio.run_coroutine_threadsafe( conn.func_handler.handle_llm_function_call( @@ -121,20 +125,21 @@ 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: # Directly reply to frontend text = result.response if text is not None: speak_txt(conn, text) - elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 + elif result.action == Action.REQLLM: # Call function then request LLM to generate reply text = result.result conn.dialogue.put(Message(role="tool", content=text)) - llm_result = conn.intent.replyResult(text, original_text) + llm_result = conn.intent.replyResult( + text, original_text) if llm_result is None: llm_result = text speak_txt(conn, llm_result) @@ -147,19 +152,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 current 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 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 @@ -179,4 +184,4 @@ def speak_txt(conn, text): content_type=ContentType.ACTION, ) ) - conn.dialogue.put(Message(role="assistant", content=text)) \ No newline at end of file + conn.dialogue.put(Message(role="assistant", content=text)) diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 506ef02d1..c8868d5b6 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -12,53 +12,55 @@ TAG = __name__ async def handleAudioMessage(conn, audio): - # 当前片段是否有人说话 + # Whether the current segment has someone speaking have_voice = conn.vad.is_vad(conn, audio) - # 如果设备刚刚被唤醒,短暂忽略VAD检测 + # If the device was just woken up, briefly ignore VAD detection if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up: have_voice = False - # 设置一个短暂延迟后恢复VAD检测 + # Set a brief delay before resuming VAD detection conn.asr_audio.clear() if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): - conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) + conn.vad_resume_task = asyncio.create_task( + resume_vad_detection(conn)) return if have_voice: if conn.client_is_speaking: await handleAbortMessage(conn) - # 设备长时间空闲检测,用于say goodbye + # Device long-term idle detection, used for say goodbye await no_voice_close_connect(conn, have_voice) - # 接收音频 + # Receive audio await conn.asr.receive_audio(conn, audio, have_voice) async def resume_vad_detection(conn): - # 等待2秒后恢复VAD检测 + # Wait 2 seconds before resuming VAD detection await asyncio.sleep(1) conn.just_woken_up = False async def startToChat(conn, text): - # 检查输入是否是JSON格式(包含说话人信息) + # Check if input is in JSON format (containing speaker information) speaker_name = None actual_text = text - + try: - # 尝试解析JSON格式的输入 + # Try to parse JSON format input if text.strip().startswith('{') and text.strip().endswith('}'): data = json.loads(text) if 'speaker' in data and 'content' in data: speaker_name = data['speaker'] actual_text = data['content'] - conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}") - - # 直接使用JSON格式的文本,不解析 + conn.logger.bind(tag=TAG).info( + f"Parsed speaker information: {speaker_name}") + + # Use JSON format text directly, do not parse actual_text = text except (json.JSONDecodeError, KeyError): - # 如果解析失败,继续使用原始文本 + # If parsing fails, continue using original text pass - - # 保存说话人信息到连接对象 + + # Save speaker information to connection object if speaker_name: conn.current_speaker = speaker_name else: @@ -68,7 +70,7 @@ async def startToChat(conn, text): await check_bind_device(conn) return - # 如果当日的输出字数大于限定的字数 + # If the daily output word count exceeds the limit if conn.max_output_size > 0: if check_device_output_limit( conn.headers.get("device-id"), conn.max_output_size @@ -78,14 +80,14 @@ async def startToChat(conn, text): if conn.client_is_speaking: await handleAbortMessage(conn) - # 首先进行意图分析,使用实际文本内容 + # First perform intent analysis, using actual text content intent_handled = await handle_user_intent(conn, actual_text) if intent_handled: - # 如果意图已被处理,不再进行聊天 + # If intent has been handled, no longer proceed with chat return - # 意图未被处理,继续常规聊天流程,使用实际文本内容 + # Intent not handled, continue with regular chat flow, using actual text content await send_stt_message(conn, actual_text) conn.executor.submit(conn.chat, actual_text) @@ -94,7 +96,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 when timestamp has been initialized if conn.last_activity_time > 0.0: no_voice_time = time.time() * 1000 - conn.last_activity_time close_connection_no_voice_time = int( @@ -108,17 +110,18 @@ 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 conversation, no need to send ending prompt") await conn.close() return prompt = end_prompt.get("prompt") if not prompt: - prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!" + prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!" await startToChat(conn, prompt) async def max_out_size(conn): - text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!" + text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!" await send_stt_message(conn, text) file_path = "config/assets/max_output_size.wav" opus_packets, _ = audio_to_data(file_path) @@ -128,35 +131,38 @@ async def max_out_size(conn): async def check_bind_device(conn): if conn.bind_code: - # 确保bind_code是6位数字 + # Ensure bind_code is a 6-digit number 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 = "Binding code format error, please check configuration." await send_stt_message(conn, text) return - text = f"请登录控制面板,输入{conn.bind_code},绑定设备。" + text = f"Please log into the control panel and enter {conn.bind_code} to bind the device." await send_stt_message(conn, text) - # 播放提示音 + # Play notification sound music_path = "config/assets/bind_code.wav" opus_packets, _ = audio_to_data(music_path) conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text)) - # 逐个播放数字 - for i in range(6): # 确保只播放6位数字 + # Play digits one by one + for i in range(6): # Ensure only 6 digits are played try: digit = conn.bind_code[i] num_path = f"config/assets/bind_code/{digit}.wav" num_packets, _ = audio_to_data(num_path) - conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None)) + 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 digit audio: {e}") continue conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None)) else: - text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。" + text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware." await send_stt_message(conn, text) music_path = "config/assets/bind_not_found.wav" opus_packets, _ = audio_to_data(music_path) - conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) \ No newline at end of file + conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text)) diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py index 7b30f79c0..2169d58c8 100644 --- a/main/xiaozhi-server/core/handle/reportHandle.py +++ b/main/xiaozhi-server/core/handle/reportHandle.py @@ -1,12 +1,12 @@ """ -TTS上报功能已集成到ConnectionHandler类中。 +TTS reporting functionality has been integrated into the ConnectionHandler class. -上报功能包括: -1. 每个连接对象拥有自己的上报队列和处理线程 -2. 上报线程的生命周期与连接对象绑定 -3. 使用ConnectionHandler.enqueue_tts_report方法进行上报 +Reporting functionality includes: +1. Each connection object has its own reporting queue and processing thread +2. The reporting thread's lifecycle is bound to the connection object +3. Use ConnectionHandler.enqueue_tts_report method for reporting -具体实现请参考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 history reporting operation Args: - conn: 连接对象 - type: 上报类型,1为用户,2为智能体 - text: 合成文本 - opus_data: opus音频数据 - report_time: 上报时间 + conn: Connection object + type: Report type, 1 for user, 2 for agent + text: Synthesized text + opus_data: Opus audio data + report_time: Report time """ try: if opus_data: audio_data = opus_to_wav(conn, opus_data) else: audio_data = None - # 执行上报 + # Execute reporting 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 history reporting failed: {e}") def opus_to_wav(conn, opus_data): - """将Opus数据转换为WAV格式的字节流 + """Convert Opus data to WAV format byte stream Args: - output_dir: 输出目录(保留参数以保持接口兼容) - opus_data: opus音频数据 + output_dir: Output directory (parameter retained for interface compatibility) + opus_data: Opus audio data Returns: - bytes: WAV格式的音频数据 + bytes: WAV format audio data """ - 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 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 reporting queue Args: - conn: 连接对象 - text: 合成文本 - opus_data: opus音频数据 + conn: Connection object + text: Synthesized text + opus_data: Opus audio data """ try: - # 使用连接对象的队列,传入文本和二进制数据而非文件路径 + # Use connection object's queue, pass text and binary data instead of file path 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 added to 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 added to reporting queue: {conn.device_id}, no audio reporting" ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}") + conn.logger.bind(tag=TAG).error(f"Failed to add TTS to 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 reporting queue Args: - conn: 连接对象 - text: 合成文本 - opus_data: opus音频数据 + conn: Connection object + text: Synthesized text + opus_data: Opus audio data """ try: - # 使用连接对象的队列,传入文本和二进制数据而非文件路径 + # Use connection object's queue, pass text and binary data instead of file path 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 added to 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 added to reporting queue: {conn.device_id}, no audio reporting" ) except Exception as e: - conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}") + conn.logger.bind(tag=TAG).debug(f"Failed to add ASR to 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 0d606dead..1bf9d9c56 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -8,12 +8,13 @@ TAG = __name__ async def sendAudioMessage(conn, sentenceType, audios, text): - # 发送句子开始消息 - conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") + # Send sentence start message + conn.logger.bind(tag=TAG).info( + f"Send audio message: {sentenceType}, {text}") pre_buffer = False if conn.tts.tts_audio_first_sentence: - conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}") + conn.logger.bind(tag=TAG).info(f"Send first audio segment: {text}") conn.tts.tts_audio_first_sentence = False pre_buffer = True @@ -21,7 +22,7 @@ async def sendAudioMessage(conn, sentenceType, audios, text): await sendAudio(conn, audios, pre_buffer) - # 发送结束消息(如果是最后一个文本) + # Send end message (if it's the last text) if conn.llm_finish_task and sentenceType == SentenceType.LAST: await send_tts_message(conn, "stop", None) conn.client_is_speaking = False @@ -29,16 +30,17 @@ async def sendAudioMessage(conn, sentenceType, audios, text): await conn.close() -# 播放音频 +# Play audio async def sendAudio(conn, audios, pre_buffer=True): if audios is None or len(audios) == 0: return - # 流控参数优化 - frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码 + # Flow control parameter optimization + # Frame duration (milliseconds), matching Opus encoding + frame_duration = 60 start_time = time.perf_counter() play_position = 0 - # 仅当第一句话时执行预缓冲 + # Execute pre-buffering only for the first sentence if pre_buffer: pre_buffer_frames = min(3, len(audios)) for i in range(pre_buffer_frames): @@ -47,15 +49,15 @@ async def sendAudio(conn, audios, pre_buffer=True): else: remaining_audios = audios - # 播放剩余音频帧 + # Play remaining audio frames for opus_packet in remaining_audios: if conn.client_abort: break - # 重置没有声音的状态 + # Reset no-voice state conn.last_activity_time = time.time() * 1000 - # 计算预期发送时间 + # Calculate expected send time expected_time = start_time + (play_position / 1000) current_time = time.perf_counter() delay = expected_time - current_time @@ -68,14 +70,14 @@ async def sendAudio(conn, audios, pre_buffer=True): async def send_tts_message(conn, state, text=None): - """发送 TTS 状态消息""" + """Send TTS status message""" message = {"type": "tts", "state": state, "session_id": conn.session_id} if text is not None: message["text"] = textUtils.check_emoji(text) - # TTS播放结束 + # TTS playback ended if state == "stop": - # 播放提示音 + # Play notification sound tts_notify = conn.config.get("enable_stop_tts_notify", False) if tts_notify: stop_tts_notify_voice = conn.config.get( @@ -83,10 +85,10 @@ async def send_tts_message(conn, state, text=None): ) audios, _ = conn.tts.audio_to_opus_data(stop_tts_notify_voice) await sendAudio(conn, audios) - # 清除服务端讲话状态 + # Clear server speaking status conn.clearSpeakStatus() - # 发送消息到客户端 + # Send message to client await conn.websocket.send(json.dumps(message)) @@ -96,26 +98,27 @@ async def send_stt_message(conn, text): await send_tts_message(conn, "start") return - """发送 STT 状态消息""" - - # 解析JSON格式,提取实际的用户说话内容 + """Send STT status message""" + + # Parse JSON format, extract 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 it's JSON format containing speaker information, only display the content part 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's not JSON format, use original text directly display_text = text stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text) await conn.websocket.send( - json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id}) + json.dumps({"type": "stt", "text": stt_text, + "session_id": conn.session_id}) ) conn.client_is_speaking = True - await send_tts_message(conn, "start") \ No newline at end of file + await send_tts_message(conn, "start") diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index d72673194..19a48f97b 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -14,25 +14,28 @@ TAG = __name__ async def handleTextMessage(conn, message): - """处理文本消息""" + """Handle text messages""" try: msg_json = json.loads(message) if isinstance(msg_json, int): - conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}") + conn.logger.bind(tag=TAG).info(f"Received text message: {message}") await conn.websocket.send(message) return if msg_json["type"] == "hello": - conn.logger.bind(tag=TAG).info(f"收到hello消息:{message}") + conn.logger.bind(tag=TAG).info( + f"Received hello message: {message}") await handleHelloMessage(conn, msg_json) elif msg_json["type"] == "abort": - conn.logger.bind(tag=TAG).info(f"收到abort消息:{message}") + conn.logger.bind(tag=TAG).info( + f"Received abort message: {message}") await handleAbortMessage(conn) elif msg_json["type"] == "listen": - conn.logger.bind(tag=TAG).info(f"收到listen消息:{message}") + conn.logger.bind(tag=TAG).info( + f"Received listen message: {message}") if "mode" in msg_json: conn.client_listen_mode = msg_json["mode"] conn.logger.bind(tag=TAG).debug( - f"客户端拾音模式:{conn.client_listen_mode}" + f"Client audio capture mode: {conn.client_listen_mode}" ) if msg_json["state"] == "start": conn.client_have_voice = True @@ -47,77 +50,81 @@ async def handleTextMessage(conn, message): 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"] # Preserve original text filtered_len, filtered_text = remove_punctuation_and_length( original_text ) - # 识别是否是唤醒词 - is_wakeup_words = filtered_text in conn.config.get("wakeup_words") - # 是否开启唤醒词回复 + # Identify if it's a wake-up word + is_wakeup_words = filtered_text in conn.config.get( + "wakeup_words") + # Whether wake-up word reply is enabled enable_greeting = conn.config.get("enable_greeting", True) if is_wakeup_words and not enable_greeting: - # 如果是唤醒词,且关闭了唤醒词回复,就不用回答 + # If it's a wake-up word and wake-up word reply is disabled, no need to respond await send_stt_message(conn, original_text) await send_tts_message(conn, "stop", None) conn.client_is_speaking = False elif is_wakeup_words: conn.just_woken_up = True - # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) - enqueue_asr_report(conn, "嘿,你好呀", []) - await startToChat(conn, "嘿,你好呀") + # Report plain text data (reuse ASR reporting function, but provide no audio data) + enqueue_asr_report(conn, "Hey, hello there", []) + await startToChat(conn, "Hey, hello there") else: - # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) + # Report plain text data (reuse ASR reporting function, but provide no audio data) enqueue_asr_report(conn, original_text, []) - # 否则需要LLM对文字内容进行答复 + # Otherwise, need LLM to respond to text content await startToChat(conn, original_text) elif msg_json["type"] == "iot": - conn.logger.bind(tag=TAG).info(f"收到iot消息:{message}") + conn.logger.bind(tag=TAG).info(f"Received iot message: {message}") if "descriptors" in msg_json: - asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"])) + asyncio.create_task(handleIotDescriptors( + conn, msg_json["descriptors"])) if "states" in msg_json: asyncio.create_task(handleIotStatus(conn, msg_json["states"])) elif msg_json["type"] == "mcp": - conn.logger.bind(tag=TAG).info(f"收到mcp消息:{message[:100]}") + conn.logger.bind(tag=TAG).info( + f"Received mcp message: {message[:100]}") if "payload" in msg_json: asyncio.create_task( - handle_mcp_message(conn, conn.mcp_client, msg_json["payload"]) + handle_mcp_message(conn, conn.mcp_client, + msg_json["payload"]) ) elif msg_json["type"] == "server": - # 记录日志时过滤敏感信息 + # Filter sensitive information when logging conn.logger.bind(tag=TAG).info( - f"收到服务器消息:{filter_sensitive_info(msg_json)}" + f"Received server message: {filter_sensitive_info(msg_json)}" ) - # 如果配置是从API读取的,则需要验证secret + # If configuration is read from API, need to verify secret if not conn.read_config_from_api: return - # 获取post请求的secret + # Get secret from post request post_secret = msg_json.get("content", {}).get("secret", "") secret = conn.config["manager-api"].get("secret", "") - # 如果secret不匹配,则返回 + # If secret doesn't match, return if post_secret != secret: await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": "服务器密钥验证失败", + "message": "Server secret verification failed", } ) ) return - # 动态更新配置 + # Dynamically update configuration if msg_json["action"] == "update_config": try: - # 更新WebSocketServer的配置 + # Update WebSocketServer configuration if not conn.server: await conn.websocket.send( json.dumps( { "type": "server", "status": "error", - "message": "无法获取服务器实例", + "message": "Cannot get server instance", "content": {"action": "update_config"}, } ) @@ -130,40 +137,42 @@ async def handleTextMessage(conn, message): { "type": "server", "status": "error", - "message": "更新服务器配置失败", + "message": "Failed to update server configuration", "content": {"action": "update_config"}, } ) ) return - # 发送成功响应 + # Send success response await conn.websocket.send( json.dumps( { "type": "server", "status": "success", - "message": "配置更新成功", + "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"Failed to update configuration: {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 server elif msg_json["action"] == "restart": await conn.handle_restart(msg_json) else: - conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") + conn.logger.bind(tag=TAG).error( + f"Received unknown type message: {message}") except json.JSONDecodeError: - await conn.websocket.send(message) \ No newline at end of file + await conn.websocket.send(message) diff --git a/main/xiaozhi-server/core/http_server.py b/main/xiaozhi-server/core/http_server.py index 9bdb672ad..b296268b7 100644 --- a/main/xiaozhi-server/core/http_server.py +++ b/main/xiaozhi-server/core/http_server.py @@ -15,19 +15,18 @@ class SimpleHttpServer: self.vision_handler = VisionHandler(config) def _get_websocket_url(self, local_ip: str, port: int) -> str: - """获取websocket地址 + """Get 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 websocket_config and "你" not in websocket_config: + if websocket_config and "you" not in websocket_config: return websocket_config else: return f"ws://{local_ip}:{port}/xiaozhi/v1/" @@ -39,43 +38,52 @@ class SimpleHttpServer: if port: try: - self.logger.bind(tag=TAG).info(f"Starting HTTP server on {host}:{port}") + self.logger.bind(tag=TAG).info( + f"Starting HTTP server on {host}:{port}") app = web.Application() - read_config_from_api = server_config.get("read_config_from_api", False) - self.logger.bind(tag=TAG).info(f"read_config_from_api: {read_config_from_api}") + read_config_from_api = server_config.get( + "read_config_from_api", False) + self.logger.bind(tag=TAG).info( + f"read_config_from_api: {read_config_from_api}") if not read_config_from_api: - # 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口 + # If smart control panel is not enabled, just running single module, need to add simple OTA interface for delivering websocket interface self.logger.bind(tag=TAG).info("Adding OTA routes") - app.add_routes( - [ - web.get("/xiaozhi/ota/", self.ota_handler.handle_get), - web.post("/xiaozhi/ota/", self.ota_handler.handle_post), - web.options("/xiaozhi/ota/", self.ota_handler.handle_post), - ] - ) - # 添加路由 - self.logger.bind(tag=TAG).info("Adding vision routes") - app.add_routes( - [ - web.get("/mcp/vision/explain", self.vision_handler.handle_get), - web.post("/mcp/vision/explain", self.vision_handler.handle_post), - web.options("/mcp/vision/explain", self.vision_handler.handle_post), - ] - ) + app.add_routes([ + web.get("/xiaozhi/ota/", self.ota_handler.handle_get), + web.post("/xiaozhi/ota/", + self.ota_handler.handle_post), + web.options("/xiaozhi/ota/", + self.ota_handler.handle_post), + ]) - # 运行服务 + # Add routes + self.logger.bind(tag=TAG).info("Adding vision routes") + app.add_routes([ + web.get("/mcp/vision/explain", + self.vision_handler.handle_get), + web.post("/mcp/vision/explain", + self.vision_handler.handle_post), + web.options("/mcp/vision/explain", + self.vision_handler.handle_post), + ]) + + # Run service self.logger.bind(tag=TAG).info("Setting up HTTP server runner") runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, host, port) await site.start() - self.logger.bind(tag=TAG).info(f"HTTP server started successfully on {host}:{port}") - # 保持服务运行 + self.logger.bind(tag=TAG).info( + f"HTTP server started successfully on {host}:{port}") + + # Keep service running while True: - await asyncio.sleep(3600) # 每隔 1 小时检查一次 + await asyncio.sleep(3600) # Check every hour + except Exception as e: - self.logger.bind(tag=TAG).error(f"Failed to start HTTP server: {e}") + self.logger.bind(tag=TAG).error( + f"Failed to start HTTP server: {e}") raise diff --git a/main/xiaozhi-server/core/providers/asr/aliyun.py b/main/xiaozhi-server/core/providers/asr/aliyun.py index 36f417457..fdc0aac9d 100644 --- a/main/xiaozhi-server/core/providers/asr/aliyun.py +++ b/main/xiaozhi-server/core/providers/asr/aliyun.py @@ -1,15 +1,16 @@ -import http.client import json -import asyncio -from typing import Optional, Tuple, List -import os +import time import uuid import hmac -import hashlib import base64 +import hashlib +import asyncio import requests +import websockets +import opuslib_next +import random +from typing import Optional, Tuple, List from urllib import parse -import time from datetime import datetime from config.logger import setup_logging from core.providers.asr.base import ASRProviderBase @@ -18,20 +19,19 @@ from core.providers.asr.dto.dto import InterfaceType TAG = __name__ logger = setup_logging() - class AccessToken: @staticmethod def _encode_text(text): encoded_text = parse.quote_plus(text) return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") - + @staticmethod def _encode_dict(dic): keys = dic.keys() dic_sorted = [(key, dic[key]) for key in sorted(keys)] encoded_text = parse.urlencode(dic_sorted) return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") - + @staticmethod def create_token(access_key_id, access_key_secret): parameters = { @@ -45,204 +45,301 @@ class AccessToken: "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "Version": "2019-02-28", } - # 构造规范化的请求字符串 + query_string = AccessToken._encode_dict(parameters) - # print('规范化的请求字符串: %s' % query_string) - # 构造待签名字符串 string_to_sign = ( - "GET" - + "&" - + AccessToken._encode_text("/") - + "&" - + AccessToken._encode_text(query_string) + "GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string) ) - # print('待签名的字符串: %s' % string_to_sign) - # 计算签名 + secreted_string = hmac.new( bytes(access_key_secret + "&", encoding="utf-8"), bytes(string_to_sign, encoding="utf-8"), hashlib.sha1, ).digest() signature = base64.b64encode(secreted_string) - # print('签名: %s' % signature) - # 进行URL编码 signature = AccessToken._encode_text(signature) - # print('URL编码后的签名: %s' % signature) - # 调用服务 - full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % ( - signature, - query_string, - ) - # print('url: %s' % full_url) - # 提交HTTP GET请求 + + full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string) response = requests.get(full_url) + if response.ok: root_obj = response.json() - key = "Token" - if key in root_obj: - token = root_obj[key]["Id"] - expire_time = root_obj[key]["ExpireTime"] - return token, expire_time - # print(response.text) + if "Token" in root_obj: + return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"] return None, None - class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): + def __init__(self, config, delete_audio_file): super().__init__() - self.interface_type = InterfaceType.NON_STREAM - """阿里云ASR初始化""" - # 新增空值判断逻辑 + self.interface_type = InterfaceType.STREAM + self.config = config + self.text = "" + self.decoder = opuslib_next.Decoder(16000, 1) + self.asr_ws = None + self.forward_task = None + self.is_processing = False + self.server_ready = False # Server ready status + + # Basic configuration self.access_key_id = config.get("access_key_id") self.access_key_secret = config.get("access_key_secret") - - self.app_key = config.get("appkey") - self.host = "nls-gateway-cn-shanghai.aliyuncs.com" - self.base_url = f"https://{self.host}/stream/v1/asr" - self.sample_rate = 16000 - self.format = "wav" + self.appkey = config.get("appkey") + self.token = config.get("token") + self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com") + + # If configured as internal address (containing -internal.aliyuncs.com), use ws protocol, default is wss protocol + if "-internal." in self.host: + self.ws_url = f"ws://{self.host}/ws/v1" + else: + # Default use wss protocol + self.ws_url = f"wss://{self.host}/ws/v1" + + self.max_sentence_silence = config.get("max_sentence_silence") self.output_dir = config.get("output_dir", "./audio_output") self.delete_audio_file = delete_audio_file - + self.expire_time = None + + # Token management if self.access_key_id and self.access_key_secret: - # 使用密钥对生成临时token self._refresh_token() - else: - # 直接使用预生成的长期token - self.token = config.get("token") - self.expire_time = None - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - + elif not self.token: + raise ValueError("Must provide access_key_id+access_key_secret or directly provide token") + def _refresh_token(self): - """刷新Token并记录过期时间""" - if self.access_key_id and self.access_key_secret: - self.token, expire_time_str = AccessToken.create_token( - self.access_key_id, self.access_key_secret - ) - if not expire_time_str: - raise ValueError("无法获取有效的Token过期时间") - - try: - # 统一转换为字符串处理 - expire_str = str(expire_time_str).strip() - - if expire_str.isdigit(): - expire_time = datetime.fromtimestamp(int(expire_str)) - else: - expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") - self.expire_time = expire_time.timestamp() - 60 - except Exception as e: - raise ValueError(f"无效的过期时间格式: {expire_str}") from e - - else: - self.expire_time = None - + """Refresh Token""" + self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret) if not self.token: - raise ValueError("无法获取有效的访问Token") - + raise ValueError("Unable to get valid access Token") + + try: + expire_str = str(expire_time_str).strip() + if expire_str.isdigit(): + expire_time = datetime.fromtimestamp(int(expire_str)) + else: + expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") + self.expire_time = expire_time.timestamp() - 60 + except: + self.expire_time = None + def _is_token_expired(self): - """检查Token是否过期""" - if not self.expire_time: - return False # 长期Token不过期 - # 新增调试日志 - # current_time = time.time() - # remaining = self.expire_time - current_time - # print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | " - # f"过期时间 {datetime.fromtimestamp(self.expire_time)} | " - # f"剩余 {remaining:.2f}秒") - return time.time() > self.expire_time - - def _construct_request_url(self) -> str: - """构造请求URL,包含参数""" - request = f"{self.base_url}?appkey={self.app_key}" - request += f"&format={self.format}" - request += f"&sample_rate={self.sample_rate}" - request += "&enable_punctuation_prediction=true" - request += "&enable_inverse_text_normalization=true" - request += "&enable_voice_detection=false" - return request - - async def _send_request(self, pcm_data: bytes) -> Optional[str]: - """发送请求到阿里云ASR服务""" - try: - # 设置HTTP头 - headers = { - "X-NLS-Token": self.token, - "Content-type": "application/octet-stream", - "Content-Length": str(len(pcm_data)), - } - - # 创建连接并发送请求 - conn = http.client.HTTPSConnection(self.host) - request_url = self._construct_request_url() - - loop = asyncio.get_event_loop() - await loop.run_in_executor( - None, - lambda: conn.request( - method="POST", url=request_url, body=pcm_data, headers=headers - ), - ) - - # 获取响应 - response = await loop.run_in_executor(None, conn.getresponse) - body = await loop.run_in_executor(None, response.read) - conn.close() - - # 解析响应 + """Check if Token has expired""" + return self.expire_time and time.time() > self.expire_time + + async def open_audio_channels(self, conn): + await super().open_audio_channels(conn) + + async def receive_audio(self, conn, audio, audio_have_voice): + # Initialize audio cache + if not hasattr(conn, 'asr_audio_for_voiceprint'): + conn.asr_audio_for_voiceprint = [] + + # Store audio data + if audio: + conn.asr_audio_for_voiceprint.append(audio) + conn.asr_audio.append(audio) + conn.asr_audio = conn.asr_audio[-10:] + + # Only establish connection when there is voice and no connection exists + if audio_have_voice and not self.is_processing: try: - body_json = json.loads(body) - status = body_json.get("status") - - if status == 20000000: - result = body_json.get("result", "") - logger.bind(tag=TAG).debug(f"ASR结果: {result}") - return result - else: - logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}") - return None - - except ValueError: - logger.bind(tag=TAG).error("响应不是JSON格式") - return None - - except Exception as e: - logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True) - return None - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" + await self._start_recognition(conn) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}") + await self._cleanup(conn) + return + + if self.asr_ws and self.is_processing and self.server_ready: + try: + pcm_frame = self.decoder.decode(audio, 960) + await self.asr_ws.send(pcm_frame) + except Exception as e: + logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}") + await self._cleanup(conn) + + async def _start_recognition(self, conn): + """Start recognition session""" if self._is_token_expired(): - logger.warning("Token已过期,正在自动刷新...") self._refresh_token() - - file_path = None + + # Establish connection + headers = {"X-NLS-Token": self.token} + self.asr_ws = await websockets.connect( + self.ws_url, + additional_headers=headers, + max_size=1000000000, + ping_interval=None, + ping_timeout=None, + close_timeout=5, + ) + + self.is_processing = True + self.server_ready = False # Reset server ready status + self.forward_task = asyncio.create_task(self._forward_results(conn)) + + # Send start request + start_request = { + "header": { + "namespace": "SpeechTranscriber", + "name": "StartTranscription", + "status": 20000000, + "message_id": ''.join(random.choices('0123456789abcdef', k=32)), + "task_id": ''.join(random.choices('0123456789abcdef', k=32)), + "status_text": "Gateway:SUCCESS:Success.", + "appkey": self.appkey + }, + "payload": { + "format": "pcm", + "sample_rate": 16000, + "enable_intermediate_result": True, + "enable_punctuation_prediction": True, + "enable_inverse_text_normalization": True, + "max_sentence_silence": self.max_sentence_silence, + "enable_voice_detection": False, + } + } + + await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False)) + logger.bind(tag=TAG).info("Start request sent, waiting for server ready...") + + async def _forward_results(self, conn): + """Forward recognition results""" try: - # 解码Opus为PCM - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - file_path = self.save_audio_to_file(pcm_data, session_id) - - # 发送请求并获取文本 - text = await self._send_request(combined_pcm_data) - - if text: - return text, file_path - - return "", file_path - + while self.asr_ws and not conn.stop_event.is_set(): + try: + response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0) + result = json.loads(response) + + header = result.get("header", {}) + payload = result.get("payload", {}) + message_name = header.get("name", "") + status = header.get("status", 0) + + if status != 20000000: + if status in [40000004, 40010004]: # Connection timeout or client disconnect + logger.bind(tag=TAG).warning(f"Connection issue, status code: {status}") + break + elif status in [40270002, 40270003]: # Audio issue + logger.bind(tag=TAG).warning(f"Audio processing issue, status code: {status}") + continue + else: + logger.bind(tag=TAG).error(f"Recognition error, status code: {status}, message: {header.get('status_text', '')}") + continue + + # Receiving TranscriptionStarted means server is ready to receive audio data + if message_name == "TranscriptionStarted": + self.server_ready = True + logger.bind(tag=TAG).info("Server ready, starting to send cached audio...") + # Send cached audio + if conn.asr_audio: + for cached_audio in conn.asr_audio[-10:]: + try: + pcm_frame = self.decoder.decode(cached_audio, 960) + await self.asr_ws.send(pcm_frame) + except Exception as e: + logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}") + break + continue + + if message_name == "TranscriptionResultChanged": + # Intermediate result + text = payload.get("result", "") + if text: + self.text = text + elif message_name == "SentenceEnd": + # Final result + text = payload.get("result", "") + if text: + self.text = text + conn.reset_vad_states() + # Pass cached audio data + audio_data = getattr(conn, 'asr_audio_for_voiceprint', []) + await self.handle_voice_stop(conn, audio_data) + # Clear cache + conn.asr_audio_for_voiceprint = [] + break + elif message_name == "TranscriptionCompleted": + # Recognition completed + self.is_processing = False + break + + except asyncio.TimeoutError: + continue + except websockets.exceptions.ConnectionClosed: + break + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to process result: {str(e)}") + break + except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", file_path + logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}") + finally: + await self._cleanup(conn) + + async def _cleanup(self, conn): + """Clean up resources""" + logger.bind(tag=TAG).info(f"Starting ASR session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}") + + # Clear connection audio cache + if conn and hasattr(conn, 'asr_audio_for_voiceprint'): + conn.asr_audio_for_voiceprint = [] + + # Determine if stop request needs to be sent + should_stop = self.is_processing or self.server_ready + + # Send stop recognition request + if self.asr_ws and should_stop: + try: + stop_msg = { + "header": { + "namespace": "SpeechTranscriber", + "name": "StopTranscription", + "status": 20000000, + "message_id": ''.join(random.choices('0123456789abcdef', k=32)), + "status_text": "Client:Stop", + "appkey": self.appkey + } + } + logger.bind(tag=TAG).info("Sending ASR termination request") + await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False)) + await asyncio.sleep(0.1) + logger.bind(tag=TAG).info("ASR termination request sent") + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to send ASR termination request: {e}") + + # Status reset (after termination request is sent) + self.is_processing = False + self.server_ready = False + logger.bind(tag=TAG).info("ASR status reset") + + # Clean up task + if self.forward_task and not self.forward_task.done(): + self.forward_task.cancel() + try: + await asyncio.wait_for(self.forward_task, timeout=1.0) + except Exception as e: + logger.bind(tag=TAG).debug(f"forward_task cancel exception: {e}") + finally: + self.forward_task = None + + # Close connection + if self.asr_ws: + try: + logger.bind(tag=TAG).debug("Closing WebSocket connection") + await asyncio.wait_for(self.asr_ws.close(), timeout=2.0) + logger.bind(tag=TAG).debug("WebSocket connection closed") + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}") + finally: + self.asr_ws = None + + logger.bind(tag=TAG).info("ASR session cleanup completed") + + async def speech_to_text(self, opus_data, session_id, audio_format): + """Get recognition result""" + result = self.text + self.text = "" + return result, None + + async def close(self): + """Close resources""" + await self._cleanup() diff --git a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py index 1d7e775e6..2ba77cf07 100644 --- a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py +++ b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py @@ -48,7 +48,9 @@ class AccessToken: } query_string = AccessToken._encode_dict(parameters) string_to_sign = ( - "GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string) + "GET" + "&" + + AccessToken._encode_text("/") + "&" + + AccessToken._encode_text(query_string) ) secreted_string = hmac.new( bytes(access_key_secret + "&", encoding="utf-8"), @@ -57,7 +59,8 @@ class AccessToken: ).digest() signature = base64.b64encode(secreted_string) signature = AccessToken._encode_text(signature) - full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string) + full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % ( + signature, query_string) response = requests.get(full_url) if response.ok: root_obj = response.json() @@ -76,19 +79,19 @@ class ASRProvider(ASRProviderBase): self.asr_ws = None self.forward_task = None self.is_processing = False - self.server_ready = False # 服务器准备状态 + self.server_ready = False # Server ready status - # 基础配置 + # Basic configuration self.access_key_id = config.get("access_key_id") self.access_key_secret = config.get("access_key_secret") self.appkey = config.get("appkey") self.token = config.get("token") self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com") - # 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议 + # If configured with internal address (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol if "-internal." in self.host: self.ws_url = f"ws://{self.host}/ws/v1" else: - # 默认使用wss协议 + # Default to wss protocol self.ws_url = f"wss://{self.host}/ws/v1" self.max_sentence_silence = config.get("max_sentence_silence") @@ -96,53 +99,57 @@ class ASRProvider(ASRProviderBase): self.delete_audio_file = delete_audio_file self.expire_time = None - # Token管理 + # Token management if self.access_key_id and self.access_key_secret: self._refresh_token() elif not self.token: - raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token") + raise ValueError( + "Must provide access_key_id+access_key_secret or provide token directly") def _refresh_token(self): - """刷新Token""" - self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret) + """Refresh Token""" + self.token, expire_time_str = AccessToken.create_token( + self.access_key_id, self.access_key_secret) if not self.token: - raise ValueError("无法获取有效的访问Token") - + raise ValueError("Unable to obtain valid access Token") + try: expire_str = str(expire_time_str).strip() if expire_str.isdigit(): expire_time = datetime.fromtimestamp(int(expire_str)) else: - expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") + expire_time = datetime.strptime( + expire_str, "%Y-%m-%dT%H:%M:%SZ") self.expire_time = expire_time.timestamp() - 60 except: self.expire_time = None def _is_token_expired(self): - """检查Token是否过期""" + """Check if Token is expired""" return self.expire_time and time.time() > self.expire_time async def open_audio_channels(self, conn): await super().open_audio_channels(conn) async def receive_audio(self, conn, audio, audio_have_voice): - # 初始化音频缓存 + # Initialize audio cache if not hasattr(conn, 'asr_audio_for_voiceprint'): conn.asr_audio_for_voiceprint = [] - - # 存储音频数据 + + # Store audio data if audio: conn.asr_audio_for_voiceprint.append(audio) - + conn.asr_audio.append(audio) conn.asr_audio = conn.asr_audio[-10:] - # 只在有声音且没有连接时建立连接 + # Only establish connection when there is voice and no existing connection if audio_have_voice and not self.is_processing: try: await self._start_recognition(conn) except Exception as e: - logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Failed to start recognition: {str(e)}") await self._cleanup(conn) return @@ -151,15 +158,15 @@ class ASRProvider(ASRProviderBase): pcm_frame = self.decoder.decode(audio, 960) await self.asr_ws.send(pcm_frame) except Exception as e: - logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}") + logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}") await self._cleanup(conn) async def _start_recognition(self, conn): - """开始识别会话""" + """Start recognition session""" if self._is_token_expired(): self._refresh_token() - - # 建立连接 + + # Establish connection headers = {"X-NLS-Token": self.token} self.asr_ws = await websockets.connect( self.ws_url, @@ -169,12 +176,12 @@ class ASRProvider(ASRProviderBase): ping_timeout=None, close_timeout=5, ) - + self.is_processing = True - self.server_ready = False # 重置服务器准备状态 + self.server_ready = False # Reset server ready status self.forward_task = asyncio.create_task(self._forward_results(conn)) - - # 发送开始请求 + + # Send start request start_request = { "header": { "namespace": "SpeechTranscriber", @@ -196,95 +203,106 @@ class ASRProvider(ASRProviderBase): } } await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False)) - logger.bind(tag=TAG).info("已发送开始请求,等待服务器准备...") + logger.bind(tag=TAG).info( + "Start request sent, waiting for server to be ready...") async def _forward_results(self, conn): - """转发识别结果""" + """Forward recognition results""" try: while self.asr_ws and not conn.stop_event.is_set(): try: response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0) result = json.loads(response) - + header = result.get("header", {}) payload = result.get("payload", {}) message_name = header.get("name", "") status = header.get("status", 0) - + if status != 20000000: - if status in [40000004, 40010004]: # 连接超时或客户端断开 - logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}") + # Connection timeout or client disconnect + if status in [40000004, 40010004]: + logger.bind(tag=TAG).warning( + f"Connection issue, status code: {status}") break - elif status in [40270002, 40270003]: # 音频问题 - logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}") + elif status in [40270002, 40270003]: # Audio issues + logger.bind(tag=TAG).warning( + f"Audio processing issue, status code: {status}") continue else: - logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}") + logger.bind(tag=TAG).error( + f"Recognition error, status code: {status}, message: {header.get('status_text', '')}") continue - - # 收到TranscriptionStarted表示服务器准备好接收音频数据 + + # TranscriptionStarted indicates server is ready to receive audio data if message_name == "TranscriptionStarted": self.server_ready = True - logger.bind(tag=TAG).info("服务器已准备,开始发送缓存音频...") - - # 发送缓存音频 + logger.bind(tag=TAG).info( + "Server is ready, starting to send cached audio...") + + # Send cached audio if conn.asr_audio: for cached_audio in conn.asr_audio[-10:]: try: - pcm_frame = self.decoder.decode(cached_audio, 960) + pcm_frame = self.decoder.decode( + cached_audio, 960) await self.asr_ws.send(pcm_frame) except Exception as e: - logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}") + logger.bind(tag=TAG).warning( + f"Failed to send cached audio: {e}") break continue - + if message_name == "TranscriptionResultChanged": - # 中间结果 + # Intermediate result text = payload.get("result", "") if text: self.text = text elif message_name == "SentenceEnd": - # 最终结果 + # Final result text = payload.get("result", "") if text: self.text = text conn.reset_vad_states() - # 传递缓存的音频数据 - audio_data = getattr(conn, 'asr_audio_for_voiceprint', []) + # Pass cached audio data + audio_data = getattr( + conn, 'asr_audio_for_voiceprint', []) await self.handle_voice_stop(conn, audio_data) - # 清空缓存 + # Clear cache conn.asr_audio_for_voiceprint = [] break elif message_name == "TranscriptionCompleted": - # 识别完成 + # Recognition completed self.is_processing = False break - + except asyncio.TimeoutError: continue except websockets.exceptions.ConnectionClosed: break except Exception as e: - logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Failed to process result: {str(e)}") break - + except Exception as e: - logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}") + logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}") finally: await self._cleanup(conn) async def _cleanup(self, conn): - """清理资源""" - logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}") - - # 清理连接的音频缓存 + """Clean up resources""" + logger.bind(tag=TAG).info( + f"Starting ASR session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}") + + # Clean up connection's audio cache if conn and hasattr(conn, 'asr_audio_for_voiceprint'): conn.asr_audio_for_voiceprint = [] - - # 判断是否需要发送终止请求 + + # Determine if stop request needs to be sent should_stop = self.is_processing or self.server_ready - - # 发送停止识别请求 + + # Send stop recognition request if self.asr_ws and should_stop: try: stop_msg = { @@ -297,47 +315,50 @@ class ASRProvider(ASRProviderBase): "appkey": self.appkey } } - logger.bind(tag=TAG).info("正在发送ASR终止请求") + logger.bind(tag=TAG).info("Sending ASR termination request") await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False)) await asyncio.sleep(0.1) - logger.bind(tag=TAG).info("ASR终止请求已发送") + logger.bind(tag=TAG).info("ASR termination request sent") except Exception as e: - logger.bind(tag=TAG).error(f"ASR终止请求发送失败: {e}") - - # 状态重置(在终止请求发送后) + logger.bind(tag=TAG).error( + f"ASR termination request failed to send: {e}") + + # Status reset (after termination request is sent) self.is_processing = False self.server_ready = False - logger.bind(tag=TAG).info("ASR状态已重置") + logger.bind(tag=TAG).info("ASR status has been reset") - # 清理任务 + # Clean up tasks if self.forward_task and not self.forward_task.done(): self.forward_task.cancel() try: await asyncio.wait_for(self.forward_task, timeout=1.0) except Exception as e: - logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}") + logger.bind(tag=TAG).debug( + f"forward_task cancellation exception: {e}") finally: self.forward_task = None - - # 关闭连接 + + # Close connection if self.asr_ws: try: - logger.bind(tag=TAG).debug("正在关闭WebSocket连接") + logger.bind(tag=TAG).debug("Closing WebSocket connection") await asyncio.wait_for(self.asr_ws.close(), timeout=2.0) - logger.bind(tag=TAG).debug("WebSocket连接已关闭") + logger.bind(tag=TAG).debug("WebSocket connection closed") except Exception as e: - logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}") + logger.bind(tag=TAG).error( + f"Failed to close WebSocket connection: {e}") finally: self.asr_ws = None - - logger.bind(tag=TAG).info("ASR会话清理完成") + + logger.bind(tag=TAG).info("ASR session cleanup completed") async def speech_to_text(self, opus_data, session_id, audio_format): - """获取识别结果""" + """Get recognition result""" result = self.text self.text = "" return result, None async def close(self): - """关闭资源""" - await self._cleanup() \ No newline at end of file + """Close resources""" + await self._cleanup() diff --git a/main/xiaozhi-server/core/providers/asr/baidu.py b/main/xiaozhi-server/core/providers/asr/baidu.py index aa8ea9015..55b50dba7 100644 --- a/main/xiaozhi-server/core/providers/asr/baidu.py +++ b/main/xiaozhi-server/core/providers/asr/baidu.py @@ -9,7 +9,6 @@ from core.providers.asr.dto.dto import InterfaceType TAG = __name__ logger = setup_logging() - class ASRProvider(ASRProviderBase): def __init__(self, config: dict, delete_audio_file: bool = True): super().__init__() @@ -17,48 +16,48 @@ class ASRProvider(ASRProviderBase): self.app_id = config.get("app_id") self.api_key = config.get("api_key") self.secret_key = config.get("secret_key") - dev_pid = config.get("dev_pid", "1537") self.dev_pid = int(dev_pid) if dev_pid else 1537 - self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file - + self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key) - - # 确保输出目录存在 + + # Ensure output directory exists os.makedirs(self.output_dir, exist_ok=True) - + async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" + """Convert speech data to text""" if not opus_data: - logger.bind(tag=TAG).warning("音频数据为空!") + logger.bind(tag=TAG).warning("Audio data is empty!") return None, None - + file_path = None try: - # 检查配置是否已设置 + # Check if configuration is set if not self.app_id or not self.api_key or not self.secret_key: - logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别") + logger.bind(tag=TAG).error("Baidu speech recognition configuration not set, cannot perform recognition") return None, file_path - - # 将Opus音频数据解码为PCM + + # Decode Opus audio data to PCM if audio_format == "pcm": pcm_data = opus_data else: pcm_data = self.decode_opus(opus_data) + combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 + + # Determine whether to save as WAV file if self.delete_audio_file: pass else: self.save_audio_to_file(pcm_data, session_id) - + start_time = time.time() - # 识别本地文件 + + # Recognize local file result = self.client.asr( combined_pcm_data, "pcm", @@ -67,19 +66,20 @@ class ASRProvider(ASRProviderBase): "dev_pid": str(self.dev_pid), }, ) - + if result and result["err_no"] == 0: logger.bind(tag=TAG).debug( - f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}" + f"Baidu speech recognition time: {time.time() - start_time:.3f}s | Result: {result}" ) result = result["result"][0] return result, file_path else: raise Exception( - f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}" + f"Baidu speech recognition failed, error code: {result['err_no']}, error message: {result['err_msg']}" ) - return None, file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) + + return None, file_path + + except Exception as e: + logger.bind(tag=TAG).error(f"Error occurred while processing audio! {e}", exc_info=True) return None, file_path diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 4529e6f62..7c680e998 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -26,14 +26,14 @@ class ASRProviderBase(ABC): def __init__(self): pass - # 打开音频通道 + # Open audio channels async def open_audio_channels(self, conn): conn.asr_priority_thread = threading.Thread( target=self.asr_text_priority_thread, args=(conn,), daemon=True ) conn.asr_priority_thread.start() - # 有序处理ASR音频 + # Process ASR audio in order def asr_text_priority_thread(self, conn): while not conn.stop_event.is_set(): try: @@ -47,17 +47,17 @@ class ASRProviderBase(ABC): continue except Exception as e: logger.bind(tag=TAG).error( - f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" ) continue - # 接收音频 + # Receive audio async def receive_audio(self, conn, audio, audio_have_voice): if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime": have_voice = audio_have_voice else: have_voice = conn.client_have_voice - + conn.asr_audio.append(audio) if not have_voice and not conn.client_have_voice: conn.asr_audio = conn.asr_audio[-10:] @@ -71,28 +71,28 @@ class ASRProviderBase(ABC): if len(asr_audio_task) > 15: await self.handle_voice_stop(conn, asr_audio_task) - # 处理语音停止 + # Handle voice stop async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): - """并行处理ASR和声纹识别""" + """Parallel processing of ASR and voiceprint recognition""" try: total_start_time = time.monotonic() - - # 准备音频数据 + + # Prepare audio data if conn.audio_format == "pcm": pcm_data = asr_audio_task else: pcm_data = self.decode_opus(asr_audio_task) - + combined_pcm_data = b"".join(pcm_data) - - # 预先准备WAV数据 + + # Pre-prepare WAV data wav_data = None - # 使用连接的声纹识别提供者 + # Use connection's voiceprint provider if conn.voiceprint_provider and combined_pcm_data: wav_data = self._pcm_to_wav(combined_pcm_data) - - - # 定义ASR任务 + + # Define ASR task + def run_asr(): start_time = time.monotonic() try: @@ -100,19 +100,21 @@ class ASRProviderBase(ABC): asyncio.set_event_loop(loop) try: result = loop.run_until_complete( - self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format) + self.speech_to_text( + asr_audio_task, conn.session_id, conn.audio_format) ) end_time = time.monotonic() - logger.bind(tag=TAG).info(f"ASR耗时: {end_time - start_time:.3f}s") + logger.bind(tag=TAG).info( + f"ASR time: {end_time - start_time:.3f}s") return result finally: loop.close() except Exception as e: end_time = time.monotonic() - logger.bind(tag=TAG).error(f"ASR失败: {e}") + logger.bind(tag=TAG).error(f"ASR failed: {e}") return ("", None) - - # 定义声纹识别任务 + + # Define voiceprint recognition task def run_voiceprint(): if not wav_data: return None @@ -120,69 +122,75 @@ class ASRProviderBase(ABC): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: - # 使用连接的声纹识别提供者 + # Use connection's voiceprint provider result = loop.run_until_complete( - conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id) + conn.voiceprint_provider.identify_speaker( + wav_data, conn.session_id) ) return result finally: loop.close() except Exception as e: - logger.bind(tag=TAG).error(f"声纹识别失败: {e}") + logger.bind(tag=TAG).error( + f"Voiceprint recognition failed: {e}") return None - - # 使用线程池执行器并行运行 + + # Run in parallel using thread pool executor parallel_start_time = time.monotonic() - + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor: asr_future = thread_executor.submit(run_asr) - + if conn.voiceprint_provider and wav_data: voiceprint_future = thread_executor.submit(run_voiceprint) - - # 等待两个线程都完成 + + # Wait for both threads to complete asr_result = asr_future.result(timeout=15) voiceprint_result = voiceprint_future.result(timeout=15) - - results = {"asr": asr_result, "voiceprint": voiceprint_result} + + results = {"asr": asr_result, + "voiceprint": voiceprint_result} else: asr_result = asr_future.result(timeout=15) results = {"asr": asr_result, "voiceprint": None} - - - # 处理结果 + + # Process results raw_text, file_path = results.get("asr", ("", None)) speaker_name = results.get("voiceprint", None) - - # 记录识别结果 + + # Log recognition results if raw_text: - logger.bind(tag=TAG).info(f"识别文本: {raw_text}") + logger.bind(tag=TAG).info(f"Recognized text: {raw_text}") if speaker_name: - logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}") - - # 性能监控 + logger.bind(tag=TAG).info( + f"Identified speaker: {speaker_name}") + + # Performance monitoring total_time = time.monotonic() - total_start_time - logger.bind(tag=TAG).info(f"总处理耗时: {total_time:.3f}s") - - # 检查文本长度 + logger.bind(tag=TAG).info( + f"Total processing time: {total_time:.3f}s") + + # Check text length text_len, _ = remove_punctuation_and_length(raw_text) self.stop_ws_connection() - + if text_len > 0: - # 构建包含说话人信息的JSON字符串 - enhanced_text = self._build_enhanced_text(raw_text, speaker_name) - - # 使用自定义模块进行上报 + # Build JSON string with speaker information + enhanced_text = self._build_enhanced_text( + raw_text, speaker_name) + + # Use custom module for reporting await startToChat(conn, enhanced_text) enqueue_asr_report(conn, enhanced_text, asr_audio_task) - + except Exception as e: - logger.bind(tag=TAG).error(f"处理语音停止失败: {e}") + logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}") import traceback - logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}") + logger.bind(tag=TAG).debug( + f"Exception details: {traceback.format_exc()}") def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str: - """构建包含说话人信息的文本""" + """Build text with speaker information""" if speaker_name and speaker_name.strip(): return json.dumps({ "speaker": speaker_name, @@ -192,37 +200,38 @@ class ASRProviderBase(ABC): return text def _pcm_to_wav(self, pcm_data: bytes) -> bytes: - """将PCM数据转换为WAV格式""" + """Convert PCM data to WAV format""" if len(pcm_data) == 0: - logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV") + logger.bind(tag=TAG).warning( + "PCM data is empty, cannot convert to WAV") return b"" - - # 确保数据长度是偶数(16位音频) + + # Ensure data length is even (16-bit audio) if len(pcm_data) % 2 != 0: pcm_data = pcm_data[:-1] - - # 创建WAV文件头 + + # Create WAV file header wav_buffer = io.BytesIO() try: with wave.open(wav_buffer, 'wb') as wav_file: - wav_file.setnchannels(1) # 单声道 - wav_file.setsampwidth(2) # 16位 - wav_file.setframerate(16000) # 16kHz采样率 + wav_file.setnchannels(1) # Mono + wav_file.setsampwidth(2) # 16-bit + wav_file.setframerate(16000) # 16kHz sample rate wav_file.writeframes(pcm_data) - + wav_buffer.seek(0) wav_data = wav_buffer.read() - + return wav_data except Exception as e: - logger.bind(tag=TAG).error(f"WAV转换失败: {e}") + logger.bind(tag=TAG).error(f"WAV conversion failed: {e}") return b"" def stop_ws_connection(self): pass def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str: - """PCM数据保存为WAV文件""" + """Save PCM data as WAV file""" module_name = __name__.split(".")[-1] file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav" file_path = os.path.join(self.output_dir, file_name) @@ -239,33 +248,36 @@ class ASRProviderBase(ABC): async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" + """Convert speech data to text""" pass @staticmethod def decode_opus(opus_data: List[bytes]) -> List[bytes]: - """将Opus音频数据解码为PCM数据""" + """Decode Opus audio data to PCM data""" try: decoder = opuslib_next.Decoder(16000, 1) pcm_data = [] - buffer_size = 960 # 每次处理960个采样点 (60ms at 16kHz) - + buffer_size = 960 # Process 960 samples each time (60ms at 16kHz) + for i, opus_packet in enumerate(opus_data): try: if not opus_packet or len(opus_packet) == 0: continue - + pcm_frame = decoder.decode(opus_packet, buffer_size) if pcm_frame and len(pcm_frame) > 0: pcm_data.append(pcm_frame) - + except opuslib_next.OpusError as e: - logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}") + logger.bind(tag=TAG).warning( + f"Opus decode error, skipping packet {i}: {e}") except Exception as e: - logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}") - + logger.bind(tag=TAG).error( + f"Audio processing error, packet {i}: {e}") + return pcm_data - + except Exception as e: - logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}") - return [] \ No newline at end of file + logger.bind(tag=TAG).error( + f"Error occurred during audio decoding: {e}") + return [] diff --git a/main/xiaozhi-server/core/providers/asr/doubao.py b/main/xiaozhi-server/core/providers/asr/doubao.py index f6cd79c62..ce8c94957 100644 --- a/main/xiaozhi-server/core/providers/asr/doubao.py +++ b/main/xiaozhi-server/core/providers/asr/doubao.py @@ -9,20 +9,16 @@ from typing import Optional, Tuple, List from core.providers.asr.base import ASRProviderBase from core.providers.asr.dto.dto import InterfaceType - TAG = __name__ logger = setup_logging() CLIENT_FULL_REQUEST = 0b0001 CLIENT_AUDIO_ONLY_REQUEST = 0b0010 - NO_SEQUENCE = 0b0000 NEG_SEQUENCE = 0b0010 - SERVER_FULL_RESPONSE = 0b1001 SERVER_ACK = 0b1011 SERVER_ERROR_RESPONSE = 0b1111 - NO_SERIALIZATION = 0b0000 JSON = 0b0001 THRIFT = 0b0011 @@ -37,9 +33,9 @@ def parse_response(res): protocol_version(4 bits), header_size(4 bits), message_type(4 bits), message_type_specific_flags(4 bits) serialization_method(4 bits) message_compression(4 bits) - reserved (8bits) 保留字段 - header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) - payload 类似与http 请求体 + reserved (8bits) reserved field + header_extensions extension header (size equals 8 * 4 * (header_size - 1)) + payload similar to http request body """ protocol_version = res[0] >> 4 header_size = res[0] & 0x0F @@ -48,11 +44,13 @@ def parse_response(res): serialization_method = res[2] >> 4 message_compression = res[2] & 0x0F reserved = res[3] - header_extensions = res[4 : header_size * 4] - payload = res[header_size * 4 :] + header_extensions = res[4: header_size * 4] + payload = res[header_size * 4:] + result = {} payload_msg = None payload_size = 0 + if message_type == SERVER_FULL_RESPONSE: payload_size = int.from_bytes(payload[:4], "big", signed=True) payload_msg = payload[4:] @@ -67,16 +65,21 @@ def parse_response(res): result["code"] = code payload_size = int.from_bytes(payload[4:8], "big", signed=False) payload_msg = payload[8:] + if payload_msg is None: return result + if message_compression == GZIP: payload_msg = gzip.decompress(payload_msg) + if serialization_method == JSON: payload_msg = json.loads(str(payload_msg, "utf-8")) elif serialization_method != NO_SERIALIZATION: payload_msg = str(payload_msg, "utf-8") + result["payload_msg"] = payload_msg result["payload_size"] = payload_size + return result @@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase): self.correct_table_name = config.get("correct_table_name", "") self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file - self.host = "openspeech.bytedance.com" self.ws_url = f"wss://{self.host}/api/v2/asr" self.success_code = 1000 self.seg_duration = 15000 - # 确保输出目录存在 + # Ensure output directory exists os.makedirs(self.output_dir, exist_ok=True) @staticmethod @@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase): """Generate protocol header.""" header = bytearray() header_size = 1 + header.append((0b0001 << 4) | header_size) # Protocol version header.append((message_type << 4) | message_type_specific_flags) - header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression + # JSON serialization & GZIP compression + header.append((0b0001 << 4) | 0b0001) header.append(0x00) # reserved + return header def _construct_request(self, reqid) -> dict: @@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase): ) -> Optional[str]: """Send request to Volcano ASR service.""" try: - auth_header = {"Authorization": "Bearer; {}".format(self.access_token)} + auth_header = { + "Authorization": "Bearer; {}".format(self.access_token)} async with websockets.connect( self.ws_url, additional_headers=auth_header ) as websocket: @@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase): request_params = self._construct_request(str(uuid.uuid4())) payload_bytes = str.encode(json.dumps(request_params)) payload_bytes = gzip.compress(payload_bytes) + full_client_request = self._generate_header() full_client_request.extend( (len(payload_bytes)).to_bytes(4, "big") @@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase): await websocket.send(full_client_request) res = await websocket.recv() result = parse_response(res) + if ( "payload_msg" in result and result["payload_msg"]["code"] != self.success_code - and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误 + # Ignore no valid voice error + and result["payload_msg"]["code"] != 1013 ): logger.bind(tag=TAG).error(f"ASR error: {result}") return None @@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase): audio_only_request = self._generate_header( message_type=CLIENT_AUDIO_ONLY_REQUEST ) + payload_bytes = gzip.compress(chunk) audio_only_request.extend( (len(payload_bytes)).to_bytes(4, "big") ) # payload size(4 bytes) audio_only_request.extend(payload_bytes) # payload + # Send audio data await websocket.send(audio_only_request) - # Receive response - response = await websocket.recv() - result = parse_response(response) + # Receive response + response = await websocket.recv() + result = parse_response(response) - if ( - "payload_msg" in result - and result["payload_msg"]["code"] == self.success_code - ): - if len(result["payload_msg"]["result"]) > 0: - return result["payload_msg"]["result"][0]["text"] - return None - elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: - # 无有效语音,返回空字符串 - return "" - else: - logger.bind(tag=TAG).error(f"ASR error: {result}") - return None + if ( + "payload_msg" in result + and result["payload_msg"]["code"] == self.success_code + ): + if len(result["payload_msg"]["result"]) > 0: + return result["payload_msg"]["result"][0]["text"] + return None + elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: + # No valid voice, return empty string + return "" + else: + logger.bind(tag=TAG).error(f"ASR error: {result}") + return None except Exception as e: - logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True) + logger.bind(tag=TAG).error( + f"ASR request failed: {e}", exc_info=True) return None @staticmethod @@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase): data_len = len(data) offset = 0 while offset + chunk_size < data_len: - yield data[offset : offset + chunk_size], False + yield data[offset: offset + chunk_size], False offset += chunk_size else: yield data[offset:data_len], True @@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase): async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - + """Convert speech data to text""" file_path = None try: - # 合并所有opus数据包 + # Merge all opus data packets if audio_format == "pcm": pcm_data = opus_data else: pcm_data = self.decode_opus(opus_data) combined_pcm_data = b"".join(pcm_data) - # 判断是否保存为WAV文件 + # Determine whether to save as WAV file if self.delete_audio_file: pass else: file_path = self.save_audio_to_file(pcm_data, session_id) - # 直接使用PCM数据 - # 计算分段大小 (单声道, 16bit, 16kHz采样率) + # Use PCM data directly + # Calculate segment size (mono, 16bit, 16kHz sample rate) size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate segment_size = int(size_per_sec * self.seg_duration / 1000) - # 语音识别 + # Speech recognition start_time = time.time() text = await self._send_request(combined_pcm_data, segment_size) + if text: logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" + f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}" ) return text, file_path + return "", file_path except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) + logger.bind(tag=TAG).error( + f"Speech recognition failed: {e}", exc_info=True) return "", file_path diff --git a/main/xiaozhi-server/core/providers/asr/doubao_stream.py b/main/xiaozhi-server/core/providers/asr/doubao_stream.py index 35dce8882..ce8c94957 100644 --- a/main/xiaozhi-server/core/providers/asr/doubao_stream.py +++ b/main/xiaozhi-server/core/providers/asr/doubao_stream.py @@ -9,20 +9,16 @@ from typing import Optional, Tuple, List from core.providers.asr.base import ASRProviderBase from core.providers.asr.dto.dto import InterfaceType - TAG = __name__ logger = setup_logging() CLIENT_FULL_REQUEST = 0b0001 CLIENT_AUDIO_ONLY_REQUEST = 0b0010 - NO_SEQUENCE = 0b0000 NEG_SEQUENCE = 0b0010 - SERVER_FULL_RESPONSE = 0b1001 SERVER_ACK = 0b1011 SERVER_ERROR_RESPONSE = 0b1111 - NO_SERIALIZATION = 0b0000 JSON = 0b0001 THRIFT = 0b0011 @@ -37,9 +33,9 @@ def parse_response(res): protocol_version(4 bits), header_size(4 bits), message_type(4 bits), message_type_specific_flags(4 bits) serialization_method(4 bits) message_compression(4 bits) - reserved (8bits) 保留字段 - header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) - payload 类似与http 请求体 + reserved (8bits) reserved field + header_extensions extension header (size equals 8 * 4 * (header_size - 1)) + payload similar to http request body """ protocol_version = res[0] >> 4 header_size = res[0] & 0x0F @@ -48,11 +44,13 @@ def parse_response(res): serialization_method = res[2] >> 4 message_compression = res[2] & 0x0F reserved = res[3] - header_extensions = res[4 : header_size * 4] - payload = res[header_size * 4 :] + header_extensions = res[4: header_size * 4] + payload = res[header_size * 4:] + result = {} payload_msg = None payload_size = 0 + if message_type == SERVER_FULL_RESPONSE: payload_size = int.from_bytes(payload[:4], "big", signed=True) payload_msg = payload[4:] @@ -67,16 +65,21 @@ def parse_response(res): result["code"] = code payload_size = int.from_bytes(payload[4:8], "big", signed=False) payload_msg = payload[8:] + if payload_msg is None: return result + if message_compression == GZIP: payload_msg = gzip.decompress(payload_msg) + if serialization_method == JSON: payload_msg = json.loads(str(payload_msg, "utf-8")) elif serialization_method != NO_SERIALIZATION: payload_msg = str(payload_msg, "utf-8") + result["payload_msg"] = payload_msg result["payload_size"] = payload_size + return result @@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase): self.correct_table_name = config.get("correct_table_name", "") self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file - self.host = "openspeech.bytedance.com" self.ws_url = f"wss://{self.host}/api/v2/asr" self.success_code = 1000 self.seg_duration = 15000 - # 确保输出目录存在 + # Ensure output directory exists os.makedirs(self.output_dir, exist_ok=True) @staticmethod @@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase): """Generate protocol header.""" header = bytearray() header_size = 1 + header.append((0b0001 << 4) | header_size) # Protocol version header.append((message_type << 4) | message_type_specific_flags) - header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression + # JSON serialization & GZIP compression + header.append((0b0001 << 4) | 0b0001) header.append(0x00) # reserved + return header def _construct_request(self, reqid) -> dict: @@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase): ) -> Optional[str]: """Send request to Volcano ASR service.""" try: - auth_header = {"Authorization": "Bearer; {}".format(self.access_token)} + auth_header = { + "Authorization": "Bearer; {}".format(self.access_token)} async with websockets.connect( self.ws_url, additional_headers=auth_header ) as websocket: @@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase): request_params = self._construct_request(str(uuid.uuid4())) payload_bytes = str.encode(json.dumps(request_params)) payload_bytes = gzip.compress(payload_bytes) + full_client_request = self._generate_header() full_client_request.extend( (len(payload_bytes)).to_bytes(4, "big") @@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase): await websocket.send(full_client_request) res = await websocket.recv() result = parse_response(res) + if ( "payload_msg" in result and result["payload_msg"]["code"] != self.success_code - and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误 + # Ignore no valid voice error + and result["payload_msg"]["code"] != 1013 ): logger.bind(tag=TAG).error(f"ASR error: {result}") return None @@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase): audio_only_request = self._generate_header( message_type=CLIENT_AUDIO_ONLY_REQUEST ) + payload_bytes = gzip.compress(chunk) audio_only_request.extend( (len(payload_bytes)).to_bytes(4, "big") ) # payload size(4 bytes) audio_only_request.extend(payload_bytes) # payload + # Send audio data await websocket.send(audio_only_request) - # Receive response - response = await websocket.recv() - result = parse_response(response) + # Receive response + response = await websocket.recv() + result = parse_response(response) - if ( - "payload_msg" in result - and result["payload_msg"]["code"] == self.success_code - ): - if len(result["payload_msg"]["result"]) > 0: - return result["payload_msg"]["result"][0]["text"] - return None - elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: - # 无有效语音,返回空字符串 - return "" - else: - logger.bind(tag=TAG).error(f"ASR error: {result}") - return None + if ( + "payload_msg" in result + and result["payload_msg"]["code"] == self.success_code + ): + if len(result["payload_msg"]["result"]) > 0: + return result["payload_msg"]["result"][0]["text"] + return None + elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: + # No valid voice, return empty string + return "" + else: + logger.bind(tag=TAG).error(f"ASR error: {result}") + return None except Exception as e: - logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True) + logger.bind(tag=TAG).error( + f"ASR request failed: {e}", exc_info=True) return None @staticmethod @@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase): data_len = len(data) offset = 0 while offset + chunk_size < data_len: - yield data[offset : offset + chunk_size], False + yield data[offset: offset + chunk_size], False offset += chunk_size else: yield data[offset:data_len], True @@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase): async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - + """Convert speech data to text""" file_path = None try: - # 合并所有opus数据包 + # Merge all opus data packets if audio_format == "pcm": pcm_data = opus_data else: pcm_data = self.decode_opus(opus_data) combined_pcm_data = b"".join(pcm_data) - # 判断是否保存为WAV文件 + # Determine whether to save as WAV file if self.delete_audio_file: pass else: file_path = self.save_audio_to_file(pcm_data, session_id) - # 直接使用PCM数据 - # 计算分段大小 (单声道, 16bit, 16kHz采样率) + # Use PCM data directly + # Calculate segment size (mono, 16bit, 16kHz sample rate) size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate segment_size = int(size_per_sec * self.seg_duration / 1000) - # 语音识别 + # Speech recognition start_time = time.time() text = await self._send_request(combined_pcm_data, segment_size) + if text: logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" + f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}" ) return text, file_path + return "", file_path except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", file_path \ No newline at end of file + logger.bind(tag=TAG).error( + f"Speech recognition failed: {e}", exc_info=True) + return "", file_path diff --git a/main/xiaozhi-server/core/providers/asr/dto/dto.py b/main/xiaozhi-server/core/providers/asr/dto/dto.py index 85b2d7b21..171c16bd9 100644 --- a/main/xiaozhi-server/core/providers/asr/dto/dto.py +++ b/main/xiaozhi-server/core/providers/asr/dto/dto.py @@ -3,7 +3,7 @@ from typing import Union, Optional class InterfaceType(Enum): - # 接口类型 - STREAM = "STREAM" # 流式接口 - NON_STREAM = "NON_STREAM" # 非流式接口 - LOCAL = "LOCAL" # 本地服务 + # Interface type + STREAM = "STREAM" # Streaming interface + NON_STREAM = "NON_STREAM" # Non-streaming interface + LOCAL = "LOCAL" # Local service diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py index 217f17ff7..527efcef1 100644 --- a/main/xiaozhi-server/core/providers/asr/fun_local.py +++ b/main/xiaozhi-server/core/providers/asr/fun_local.py @@ -15,10 +15,11 @@ TAG = __name__ logger = setup_logging() MAX_RETRIES = 2 -RETRY_DELAY = 1 # 重试延迟(秒) +RETRY_DELAY = 1 # Retry delay (seconds) + +# Capture standard output -# 捕获标准输出 class CaptureOutput: def __enter__(self): self._output = io.StringIO() @@ -30,7 +31,7 @@ class CaptureOutput: self.output = self._output.getvalue() self._output.close() - # 将捕获到的内容通过 logger 输出 + # Output captured content through logger if self.output: logger.bind(tag=TAG).info(self.output.strip()) @@ -38,59 +39,61 @@ class CaptureOutput: class ASRProvider(ASRProviderBase): def __init__(self, config: dict, delete_audio_file: bool): super().__init__() - - # 内存检测,要求大于2G + + # Memory detection, require more than 2G min_mem_bytes = 2 * 1024 * 1024 * 1024 total_mem = psutil.virtual_memory().total if total_mem < min_mem_bytes: - logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR") - + logger.bind(tag=TAG).error( + f"Insufficient memory (less than 2G), currently only {total_mem / (1024*1024):.2f} MB available, may not be able to start FunASR") + self.interface_type = InterfaceType.LOCAL self.model_dir = config.get("model_dir") - self.output_dir = config.get("output_dir") # 修正配置键名 + # Correct configuration key name + self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file - # 确保输出目录存在 + # Ensure output directory exists os.makedirs(self.output_dir, exist_ok=True) + with CaptureOutput(): self.model = AutoModel( model=self.model_dir, vad_kwargs={"max_single_segment_time": 30000}, disable_update=True, hub="hf", - # device="cuda:0", # 启用GPU加速 + # device="cuda:0", # Enable GPU acceleration ) async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """语音转文本主处理逻辑""" + """Speech to text main processing logic""" file_path = None retry_count = 0 while retry_count < MAX_RETRIES: try: - # 合并所有opus数据包 + # Merge all opus data packets if audio_format == "pcm": pcm_data = opus_data else: pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - # 检查磁盘空间 + # Check disk space if not self.delete_audio_file: free_space = shutil.disk_usage(self.output_dir).free - if free_space < len(combined_pcm_data) * 2: # 预留2倍空间 - raise OSError("磁盘空间不足") + if free_space < len(combined_pcm_data) * 2: # Reserve 2x space + raise OSError("Insufficient disk space") - # 判断是否保存为WAV文件 + # Determine whether to save as WAV file if self.delete_audio_file: pass else: file_path = self.save_audio_to_file(pcm_data, session_id) - # 语音识别 + # Speech recognition start_time = time.time() result = self.model.generate( input=combined_pcm_data, @@ -99,9 +102,11 @@ class ASRProvider(ASRProviderBase): use_itn=True, batch_size_s=60, ) + text = rich_transcription_postprocess(result[0]["text"]) + logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" + f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}" ) return text, file_path @@ -110,25 +115,28 @@ class ASRProvider(ASRProviderBase): retry_count += 1 if retry_count >= MAX_RETRIES: logger.bind(tag=TAG).error( - f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True + f"Speech recognition failed (retried {retry_count} times): {e}", exc_info=True ) return "", file_path + logger.bind(tag=TAG).warning( - f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}" + f"Speech recognition failed, retrying ({retry_count}/{MAX_RETRIES}): {e}" ) time.sleep(RETRY_DELAY) except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) + logger.bind(tag=TAG).error( + f"Speech recognition failed: {e}", exc_info=True) return "", file_path finally: - # 文件清理逻辑 + # File cleanup logic if self.delete_audio_file and file_path and os.path.exists(file_path): try: os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") + logger.bind(tag=TAG).debug( + f"Deleted temporary audio file: {file_path}") except Exception as e: logger.bind(tag=TAG).error( - f"文件删除失败: {file_path} | 错误: {e}" + f"File deletion failed: {file_path} | Error: {e}" ) diff --git a/main/xiaozhi-server/core/providers/asr/fun_server.py b/main/xiaozhi-server/core/providers/asr/fun_server.py index 7eb9e7848..82b83e9e8 100644 --- a/main/xiaozhi-server/core/providers/asr/fun_server.py +++ b/main/xiaozhi-server/core/providers/asr/fun_server.py @@ -11,11 +11,11 @@ import re TAG = __name__ logger = setup_logging() - class ASRProvider(ASRProviderBase): def __init__(self, config: dict, delete_audio_file: bool): """ Initialize the ASRProvider with server configuration. + :param config: Dictionary containing 'host', 'port', and 'is_ssl'. :param delete_audio_file: Boolean to indicate whether to delete audio files after processing. """ @@ -36,11 +36,12 @@ class ASRProvider(ASRProviderBase): if self.is_ssl else f"ws://{self.host}:{self.port}" ) + self.ssl_context = ssl.SSLContext() if self.is_ssl else None if self.ssl_context: self.ssl_context.check_hostname = False self.ssl_context.verify_mode = ssl.CERT_NONE - + async def _receive_responses(self, ws) -> None: """ Asynchronous generator to receive messages from the WebSocket. @@ -52,11 +53,13 @@ class ASRProvider(ASRProviderBase): response = await asyncio.wait_for(ws.recv(), timeout=5) response_data = json.loads(response) logger.bind(tag=TAG).debug(f"Received response: {response_data}") + if response_data.get("is_final", True): text += response_data.get("text", "") break else: text += response_data.get("text", "") + except asyncio.TimeoutError: logger.bind(tag=TAG).error( "Timeout while waiting for response from WebSocket." @@ -65,45 +68,45 @@ class ASRProvider(ASRProviderBase): except websockets.exceptions.ConnectionClosed as e: logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}") break + return text - + async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple: """ Internal method to handle WebSocket communication. Reuses the persistent WebSocket connection if available. + :param pcm_data: PCM audio data to send. :param session_id: Unique session identifier. :return: Tuple containing recognized text and optional timestamp. """ - # Send initial configuration message - config_message = json.dumps( - { - "mode": "offline", - "chunk_size": [5, 10, 5], - "chunk_interval": 10, - "wav_name": session_id, - "is_speaking": True, - "itn": False, - } - ) + config_message = json.dumps({ + "mode": "offline", + "chunk_size": [5, 10, 5], + "chunk_interval": 10, + "wav_name": session_id, + "is_speaking": True, + "itn": False, + }) await ws.send(config_message) logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}") - + # Send PCM data await ws.send(pcm_data) logger.bind(tag=TAG).debug(f"Sent PCM data of length: {len(pcm_data)} bytes") - + # Indicate end of speech end_message = json.dumps({"is_speaking": False}) await ws.send(end_message) logger.bind(tag=TAG).debug(f"Sent end message: {end_message}") - + async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: """ Convert speech data to text using FunASR. + :param opus_data: List of Opus-encoded audio data chunks. :param session_id: Unique session identifier. :return: Tuple containing recognized text and optional timestamp. @@ -114,12 +117,13 @@ class ASRProvider(ASRProviderBase): else: pcm_data = self.decode_opus(opus_data) combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 + + # Determine whether to save as WAV file if self.delete_audio_file: pass else: file_path = self.save_audio_to_file(pcm_data, session_id) + auth_header = {"Authorization": "Bearer; {}".format(self.api_key)} async with websockets.connect( self.uri, @@ -134,31 +138,33 @@ class ASRProvider(ASRProviderBase): self._send_data(ws, combined_pcm_data, session_id) ) receive_task = asyncio.create_task(self._receive_responses(ws)) - + # Gather tasks with error handling done, pending = await asyncio.wait( [send_task, receive_task], return_when=asyncio.FIRST_EXCEPTION ) - + # Cancel any pending tasks for task in pending: task.cancel() - + # Check for exceptions in completed tasks for task in done: if task.exception(): raise task.exception() - + # Get the result from the receive task result = receive_task.result() + match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result) if match: result = match.group(4).strip() + return ( result, file_path, ) # Return the recognized text and timestamp (if any) - + except websockets.exceptions.ConnectionClosed as e: logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}") return "", file_path diff --git a/main/xiaozhi-server/core/providers/asr/groq_whisper.py b/main/xiaozhi-server/core/providers/asr/groq_whisper.py index 32028190c..dfe0dd658 100644 --- a/main/xiaozhi-server/core/providers/asr/groq_whisper.py +++ b/main/xiaozhi-server/core/providers/asr/groq_whisper.py @@ -17,7 +17,7 @@ class ASRProvider(ASRProviderBase): Groq Whisper ASR Provider Uses Groq's API for Whisper-based speech-to-text transcription """ - + def __init__(self, config: dict, delete_audio_file: bool): super().__init__() self.interface_type = InterfaceType.NON_STREAM @@ -28,14 +28,14 @@ class ASRProvider(ASRProviderBase): self.response_format = config.get("response_format", "text") self.output_dir = config.get("output_dir", "./audio_files") self.delete_audio_file = delete_audio_file - + # Groq base URL (can be overridden in config) self.base_url = config.get("base_url", "https://api.groq.com") - + # Timeout configuration timeout = config.get("timeout", 60) self.timeout = int(timeout) if timeout else 60 - + # Initialize Groq client self.client = Groq( api_key=self.api_key, @@ -43,11 +43,11 @@ class ASRProvider(ASRProviderBase): timeout=self.timeout, max_retries=2 ) - + # Ensure output directory exists if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) - + logger.bind(tag=TAG).info( f"Groq Whisper ASR initialized with model: {self.model}, " f"language: {self.language}, temperature: {self.temperature}" @@ -57,9 +57,8 @@ class ASRProvider(ASRProviderBase): self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: """Convert speech data to text using Groq Whisper API""" - start_time = time.time() - + try: # Decode Opus to PCM if needed if audio_format == "opus": @@ -69,10 +68,10 @@ class ASRProvider(ASRProviderBase): return None, None else: pcm_data = opus_data - + # Save audio to temporary file (Groq API requires file upload) audio_file_path = self.save_audio_to_file(pcm_data, session_id) - + # Perform transcription try: with open(audio_file_path, "rb") as audio_file: @@ -88,7 +87,7 @@ class ASRProvider(ASRProviderBase): response_format=self.response_format ) ) - + # Extract text based on response format if self.response_format == "text": result_text = transcription @@ -96,33 +95,34 @@ class ASRProvider(ASRProviderBase): result_text = transcription.text else: result_text = str(transcription) - + elapsed_time = time.time() - start_time logger.bind(tag=TAG).info( f"Groq Whisper transcription completed in {elapsed_time:.2f}s: {result_text}" ) - + return result_text, audio_file_path - + except Exception as e: logger.bind(tag=TAG).error( f"Groq API error: {str(e)}, type: {type(e).__name__}" ) return None, audio_file_path - + finally: # Clean up audio file if configured if self.delete_audio_file and os.path.exists(audio_file_path): try: os.remove(audio_file_path) - logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}") + logger.bind(tag=TAG).debug( + f"Deleted audio file: {audio_file_path}") except Exception as e: logger.bind(tag=TAG).warning( f"Failed to delete audio file {audio_file_path}: {e}" ) - + except Exception as e: logger.bind(tag=TAG).error( f"Speech-to-text error: {str(e)}, type: {type(e).__name__}" ) - return None, None \ No newline at end of file + return None, None diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index 951c4bf8b..b1a2ba850 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -10,12 +10,13 @@ import requests TAG = __name__ logger = setup_logging() + class ASRProvider(ASRProviderBase): def __init__(self, config: dict, delete_audio_file: bool): self.interface_type = InterfaceType.NON_STREAM self.api_key = config.get("api_key") self.api_url = config.get("base_url") - self.model = config.get("model_name") + self.model = config.get("model_name") self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file @@ -32,21 +33,21 @@ class ASRProvider(ASRProviderBase): file_path = self.save_audio_to_file(pcm_data, session_id) logger.bind(tag=TAG).debug( - f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}" + f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}" ) logger.bind(tag=TAG).info(f"file path: {file_path}") headers = { "Authorization": f"Bearer {self.api_key}", } - - # 使用data参数传递模型名称 + + # Use data parameter to pass model name data = { "model": self.model } - - with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭 + # Use with statement to ensure file is closed + with open(file_path, "rb") as audio_file: files = { "file": audio_file } @@ -59,24 +60,26 @@ class ASRProvider(ASRProviderBase): headers=headers ) logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {response.text}" + f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {response.text}" ) if response.status_code == 200: text = response.json().get("text", "") return text, file_path else: - raise Exception(f"API请求失败: {response.status_code} - {response.text}") - + raise Exception( + f"API request failed: {response.status_code} - {response.text}") + except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}") + logger.bind(tag=TAG).error(f"Speech recognition failed: {e}") return "", None finally: - # 文件清理逻辑 + # File cleanup logic if self.delete_audio_file and file_path and os.path.exists(file_path): try: os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") + logger.bind(tag=TAG).debug( + f"Deleted temporary audio file: {file_path}") except Exception as e: - logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") - \ No newline at end of file + logger.bind(tag=TAG).error( + f"File deletion failed: {file_path} | Error: {e}") diff --git a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py index 634e0ce31..b6efbfb68 100644 --- a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py +++ b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py @@ -17,7 +17,7 @@ TAG = __name__ logger = setup_logging() -# 捕获标准输出 +# Capture standard output class CaptureOutput: def __enter__(self): self._output = io.StringIO() @@ -29,7 +29,7 @@ class CaptureOutput: self.output = self._output.getvalue() self._output.close() - # 将捕获到的内容通过 logger 输出 + # Output captured content through logger if self.output: logger.bind(tag=TAG).info(self.output.strip()) @@ -40,23 +40,25 @@ class ASRProvider(ASRProviderBase): self.interface_type = InterfaceType.LOCAL self.model_dir = config.get("model_dir") self.output_dir = config.get("output_dir") - self.model_type = config.get("model_type", "sense_voice") # 支持 paraformer + self.model_type = config.get( + "model_type", "sense_voice") # Support paraformer self.delete_audio_file = delete_audio_file - # 确保输出目录存在 + # Ensure output directory exists os.makedirs(self.output_dir, exist_ok=True) - # 初始化模型文件路径 + # Initialize model file paths model_files = { "model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"), "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), } - # 下载并检查模型文件 + # Download and check model files try: for file_name, file_path in model_files.items(): if not os.path.isfile(file_path): - logger.bind(tag=TAG).info(f"正在下载模型文件: {file_name}") + logger.bind(tag=TAG).info( + f"Downloading model file: {file_name}") model_file_download( model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue", file_path=file_name, @@ -64,13 +66,15 @@ class ASRProvider(ASRProviderBase): ) if not os.path.isfile(file_path): - raise FileNotFoundError(f"模型文件下载失败: {file_path}") + raise FileNotFoundError( + f"Model file download failed: {file_path}") self.model_path = model_files["model.int8.onnx"] self.tokens_path = model_files["tokens.txt"] except Exception as e: - logger.bind(tag=TAG).error(f"模型文件处理失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Model file processing failed: {str(e)}") raise with CaptureOutput(): @@ -123,10 +127,10 @@ class ASRProvider(ASRProviderBase): async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """语音转文本主处理逻辑""" + """Main processing logic for speech to text""" file_path = None try: - # 保存音频文件 + # Save audio file start_time = time.time() if audio_format == "pcm": pcm_data = opus_data @@ -134,10 +138,10 @@ class ASRProvider(ASRProviderBase): pcm_data = self.decode_opus(opus_data) file_path = self.save_audio_to_file(pcm_data, session_id) logger.bind(tag=TAG).debug( - f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}" + f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}" ) - # 语音识别 + # Speech recognition start_time = time.time() s = self.model.create_stream() samples, sample_rate = self.read_wave(file_path) @@ -145,19 +149,22 @@ class ASRProvider(ASRProviderBase): self.model.decode_stream(s) text = s.result.text logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" + f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}" ) return text, file_path except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) + logger.bind(tag=TAG).error( + f"Speech recognition failed: {e}", exc_info=True) return "", file_path finally: - # 文件清理逻辑 + # File cleanup logic if self.delete_audio_file and file_path and os.path.exists(file_path): try: os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") + logger.bind(tag=TAG).debug( + f"Deleted temporary audio file: {file_path}") except Exception as e: - logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") \ No newline at end of file + logger.bind(tag=TAG).error( + f"File deletion failed: {file_path} | Error: {e}") diff --git a/main/xiaozhi-server/core/providers/asr/tencent.py b/main/xiaozhi-server/core/providers/asr/tencent.py index 1fd1c6f42..5aba5a91a 100644 --- a/main/xiaozhi-server/core/providers/asr/tencent.py +++ b/main/xiaozhi-server/core/providers/asr/tencent.py @@ -18,7 +18,7 @@ logger = setup_logging() class ASRProvider(ASRProviderBase): API_URL = "https://asr.tencentcloudapi.com" API_VERSION = "2019-06-14" - FORMAT = "pcm" # 支持的音频格式:pcm, wav, mp3 + FORMAT = "pcm" # Supported audio formats: pcm, wav, mp3 def __init__(self, config: dict, delete_audio_file: bool = True): super().__init__() @@ -28,103 +28,106 @@ class ASRProvider(ASRProviderBase): self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file - # 确保输出目录存在 + # Ensure output directory exists os.makedirs(self.output_dir, exist_ok=True) async def speech_to_text( self, opus_data: List[bytes], session_id: str, audio_format="opus" ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" + """Convert speech data to text""" if not opus_data: - logger.bind(tag=TAG).warning("音频数据为空!") + logger.bind(tag=TAG).warning("Audio data is empty!") return None, None file_path = None try: - # 检查配置是否已设置 + # Check if configuration is set if not self.secret_id or not self.secret_key: - logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别") + logger.bind(tag=TAG).error( + "Tencent Cloud speech recognition configuration not set, unable to perform recognition") return None, file_path - # 将Opus音频数据解码为PCM + # Decode Opus audio data to PCM if audio_format == "pcm": pcm_data = opus_data else: pcm_data = self.decode_opus(opus_data) + combined_pcm_data = b"".join(pcm_data) - # 判断是否保存为WAV文件 + # Decide whether to save as WAV file if self.delete_audio_file: pass else: self.save_audio_to_file(pcm_data, session_id) - # 将音频数据转换为Base64编码 + # Convert audio data to Base64 encoding base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8") - # 构建请求体 + # Build request body request_body = self._build_request_body(base64_audio) - # 获取认证头 + # Get authentication headers timestamp, authorization = self._get_auth_headers(request_body) - # 发送请求 + # Send request start_time = time.time() result = self._send_request(request_body, timestamp, authorization) if result: logger.bind(tag=TAG).debug( - f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}" + f"Tencent Cloud speech recognition time: {time.time() - start_time:.3f}s | Result: {result}" ) - - return result, file_path + return result, file_path except Exception as e: - logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) + logger.bind(tag=TAG).error( + f"Error occurred while processing audio! {e}", exc_info=True) return None, file_path def _build_request_body(self, base64_audio: str) -> str: - """构建请求体""" + """Build request body""" request_map = { "ProjectId": 0, - "SubServiceType": 2, # 一句话识别 - "EngSerViceType": "16k_zh", # 中文普通话通用 - "SourceType": 1, # 音频数据来源为语音文件 - "VoiceFormat": self.FORMAT, # 音频格式 - "Data": base64_audio, # Base64编码的音频数据 - "DataLen": len(base64_audio), # 数据长度 + "SubServiceType": 2, # One-sentence recognition + "EngSerViceType": "16k_zh", # Chinese Mandarin general + "SourceType": 1, # Audio data source is speech file + "VoiceFormat": self.FORMAT, # Audio format + "Data": base64_audio, # Base64 encoded audio data + "DataLen": len(base64_audio), # Data length } + return json.dumps(request_map) def _get_auth_headers(self, request_body: str) -> Tuple[str, str]: - """获取认证头""" + """Get authentication headers""" try: - # 获取当前UTC时间戳 + # Get current UTC timestamp now = datetime.now(timezone.utc) timestamp = str(int(now.timestamp())) date = now.strftime("%Y-%m-%d") - # 服务名称必须是 "asr" + # Service name must be "asr" service = "asr" - # 拼接凭证范围 + # Concatenate credential scope credential_scope = f"{date}/{service}/tc3_request" - # 使用TC3-HMAC-SHA256签名方法 + # Use TC3-HMAC-SHA256 signature method algorithm = "TC3-HMAC-SHA256" - # 构建规范请求字符串 + # Build canonical request string http_request_method = "POST" canonical_uri = "/" canonical_query_string = "" - # 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写 - # 必须包含content-type和host头部 + # Note: Headers need to be sorted in ASCII order, and both key and value are converted to lowercase + # Must include content-type and host headers content_type = "application/json; charset=utf-8" host = "asr.tencentcloudapi.com" - action = "SentenceRecognition" # 接口名称 + action = "SentenceRecognition" # Interface name - # 构建规范头部信息,注意顺序和格式 + # Build canonical headers, note order and format canonical_headers = ( f"content-type:{content_type.lower()}\n" + f"host:{host.lower()}\n" @@ -133,10 +136,10 @@ class ASRProvider(ASRProviderBase): signed_headers = "content-type;host;x-tc-action" - # 请求体哈希值 + # Request body hash value payload_hash = self._sha256_hex(request_body) - # 构建规范请求字符串 + # Build canonical request string canonical_request = ( f"{http_request_method}\n" + f"{canonical_uri}\n" @@ -146,10 +149,10 @@ class ASRProvider(ASRProviderBase): + f"{payload_hash}" ) - # 计算规范请求的哈希值 + # Calculate hash value of canonical request hashed_canonical_request = self._sha256_hex(canonical_request) - # 构建待签名字符串 + # Build string to be signed string_to_sign = ( f"{algorithm}\n" + f"{timestamp}\n" @@ -157,17 +160,17 @@ class ASRProvider(ASRProviderBase): + f"{hashed_canonical_request}" ) - # 计算签名密钥 + # Calculate signature key secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date) secret_service = self._hmac_sha256(secret_date, service) secret_signing = self._hmac_sha256(secret_service, "tc3_request") - # 计算签名 + # Calculate signature signature = self._bytes_to_hex( self._hmac_sha256(secret_signing, string_to_sign) ) - # 构建授权头 + # Build authorization header authorization = ( f"{algorithm} " + f"Credential={self.secret_id}/{credential_scope}, " @@ -178,13 +181,15 @@ class ASRProvider(ASRProviderBase): return timestamp, authorization except Exception as e: - logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True) - raise RuntimeError(f"生成认证头失败: {e}") + logger.bind(tag=TAG).error( + f"Failed to generate authentication headers: {e}", exc_info=True) + raise RuntimeError( + f"Failed to generate authentication headers: {e}") def _send_request( self, request_body: str, timestamp: str, authorization: str ) -> Optional[str]: - """发送请求到腾讯云API""" + """Send request to Tencent Cloud API""" headers = { "Content-Type": "application/json; charset=utf-8", "Host": "asr.tencentcloudapi.com", @@ -196,43 +201,47 @@ class ASRProvider(ASRProviderBase): } try: - response = requests.post(self.API_URL, headers=headers, data=request_body) + response = requests.post( + self.API_URL, headers=headers, data=request_body) if not response.ok: - raise IOError(f"请求失败: {response.status_code} {response.reason}") + raise IOError( + f"Request failed: {response.status_code} {response.reason}") response_json = response.json() - # 检查是否有错误 + # Check for errors if "Response" in response_json and "Error" in response_json["Response"]: error = response_json["Response"]["Error"] error_code = error["Code"] error_message = error["Message"] - raise IOError(f"API返回错误: {error_code}: {error_message}") + raise IOError( + f"API returned error: {error_code}: {error_message}") - # 提取识别结果 + # Extract recognition result if "Response" in response_json and "Result" in response_json["Response"]: return response_json["Response"]["Result"] else: - logger.bind(tag=TAG).warning(f"响应中没有识别结果: {response_json}") + logger.bind(tag=TAG).warning( + f"No recognition result in response: {response_json}") return "" except Exception as e: - logger.bind(tag=TAG).error(f"发送请求失败: {e}", exc_info=True) + logger.bind(tag=TAG).error( + f"Failed to send request: {e}", exc_info=True) return None def _sha256_hex(self, data: str) -> str: - """计算字符串的SHA256哈希值""" + """Calculate SHA256 hash value of string""" digest = hashlib.sha256(data.encode("utf-8")).digest() return self._bytes_to_hex(digest) def _hmac_sha256(self, key, data: str) -> bytes: - """计算HMAC-SHA256""" + """Calculate HMAC-SHA256""" if isinstance(key, str): key = key.encode("utf-8") - return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest() def _bytes_to_hex(self, bytes_data: bytes) -> str: - """字节数组转十六进制字符串""" + """Convert byte array to hexadecimal string""" return "".join(f"{b:02x}" for b in bytes_data) diff --git a/main/xiaozhi-server/core/providers/intent/base.py b/main/xiaozhi-server/core/providers/intent/base.py index f6df10ddf..e05e283c8 100644 --- a/main/xiaozhi-server/core/providers/intent/base.py +++ b/main/xiaozhi-server/core/providers/intent/base.py @@ -2,6 +2,7 @@ from abc import ABC, abstractmethod from typing import List, Dict from config.logger import setup_logging + TAG = __name__ logger = setup_logging() @@ -12,22 +13,23 @@ class IntentProviderBase(ABC): def set_llm(self, llm): self.llm = llm - # 获取模型名称和类型信息 + # Get model name and type information model_name = getattr(llm, "model_name", str(llm.__class__.__name__)) - # 记录更详细的日志 - logger.bind(tag=TAG).info(f"意图识别设置LLM: {model_name}") + # Log more detailed information + logger.bind(tag=TAG).info( + f"Intent recognition setting LLM: {model_name}") @abstractmethod async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: """ - 检测用户最后一句话的意图 + Detect the intent of the user's last sentence Args: - dialogue_history: 对话历史记录列表,每条记录包含role和content + dialogue_history: List of dialogue history records, each record contains role and content Returns: - 返回识别出的意图,格式为: - - "继续聊天" - - "结束聊天" - - "播放音乐 歌名" 或 "随机播放音乐" - - "查询天气 地点名" 或 "查询天气 [当前位置]" + Returns the recognized intent in the following formats: + - "continue_chat" + - "end_chat" + - "play_music song_name" or "play_random_music" + - "query_weather location_name" or "query_weather [current_location]" """ pass diff --git a/main/xiaozhi-server/core/providers/intent/function_call/function_call.py b/main/xiaozhi-server/core/providers/intent/function_call/function_call.py index d43ada429..29d51dfea 100644 --- a/main/xiaozhi-server/core/providers/intent/function_call/function_call.py +++ b/main/xiaozhi-server/core/providers/intent/function_call/function_call.py @@ -2,6 +2,7 @@ from ..base import IntentProviderBase from typing import List, Dict from config.logger import setup_logging + TAG = __name__ logger = setup_logging() @@ -9,12 +10,12 @@ logger = setup_logging() class IntentProvider(IntentProviderBase): async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: """ - 默认的意图识别实现,始终返回继续聊天 + Default intent recognition implementation, always returns continue chat Args: - dialogue_history: 对话历史记录列表 - text: 本次对话记录 + dialogue_history: List of dialogue history records + text: Current conversation record Returns: - 固定返回"继续聊天" + Fixed return "continue chat" """ logger.bind(tag=TAG).debug( "Using functionCallProvider, always returning continue chat" diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index 89770780a..f9d65047c 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -16,35 +16,34 @@ class IntentProvider(IntentProviderBase): super().__init__(config) self.llm = None self.promot = "" - # 导入全局缓存管理器 - from core.utils.cache.manager import cache_manager, CacheType - - self.cache_manager = cache_manager - self.CacheType = CacheType - self.history_count = 4 # 默认使用最近4条对话记录 + # Add cache management + self.intent_cache = {} # Cache for intent recognition results + self.cache_expiry = 600 # Cache validity period of 10 minutes + self.cache_max_size = 100 # Maximum of 100 intents to cache + self.history_count = 4 # Default to using the last 4 conversation records def get_intent_system_prompt(self, functions_list: str) -> str: """ - 根据配置的意图选项和可用函数动态生成系统提示词 + Dynamically generate a system prompt based on configured intent options and available functions. Args: - functions: 可用的函数列表,JSON格式字符串 + functions: A list of available functions in JSON format string. Returns: - 格式化后的系统提示词 + A formatted system prompt. """ - # 构建函数说明部分 - functions_desc = "可用的函数列表:\n" + # Build the function description part + functions_desc = "Available functions list:\n" for func in functions_list: func_info = func.get("function", {}) name = func_info.get("name", "") desc = func_info.get("description", "") params = func_info.get("parameters", {}) - functions_desc += f"\n函数名: {name}\n" - functions_desc += f"描述: {desc}\n" + functions_desc += f"\nFunction Name: {name}\n" + functions_desc += f"Description: {desc}\n" if params: - functions_desc += "参数:\n" + functions_desc += "Parameters:\n" for param_name, param_info in params.get("properties", {}).items(): param_desc = param_info.get("description", "") param_type = param_info.get("type", "") @@ -53,60 +52,81 @@ class IntentProvider(IntentProviderBase): functions_desc += "---\n" prompt = ( - "你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n" - "- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n" - "- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n" + "You are an intent recognition assistant. Please analyze the user's last sentence to determine the user's intent and call the corresponding function.\n\n" + "- If the user uses question words (like 'how', 'why', 'what') to ask about exiting (e.g., 'How did it exit?'), note that this is not a request to exit. Please return {'function_call': {'name': 'continue_chat'}}\n" + "- Only trigger handle_exit_intent when the user explicitly uses commands like 'exit system', 'end conversation', 'I don't want to talk to you anymore'.\n\n" f"{functions_desc}\n" - "处理步骤:\n" - "1. 分析用户输入,确定用户意图\n" - "2. 从可用函数列表中选择最匹配的函数\n" - "3. 如果找到匹配的函数,生成对应的function_call 格式\n" - '4. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n' - "返回格式要求:\n" - "1. 必须返回纯JSON格式\n" - "2. 必须包含function_call字段\n" - "3. function_call必须包含name字段\n" - "4. 如果函数需要参数,必须包含arguments字段\n\n" - "示例:\n" + "Processing Steps:\n" + "1. Analyze user input to determine user intent.\n" + "2. Select the best matching function from the list of available functions.\n" + "3. If a matching function is found, generate the corresponding function_call format.\n" + '4. If no matching function is found, return {"function_call": {"name": "continue_chat"}}\n\n' + "Return Format Requirements:\n" + "1. Must return in pure JSON format.\n" + "2. Must include the function_call field.\n" + "3. function_call must include the name field.\n" + "4. If the function requires parameters, it must include the arguments field.\n\n" + "Examples:\n" "```\n" - "用户: 现在几点了?\n" - '返回: {"function_call": {"name": "get_time"}}\n' + "User: What time is it?\n" + 'Return: {"function_call": {"name": "get_time"}}\n' "```\n" "```\n" - "用户: 当前电池电量是多少?\n" - '返回: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "当前电池电量为{value}%", "response_failure": "无法获取Battery的当前电量百分比"}}}\n' + "User: What is the current battery level?\n" + 'Return: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "Current battery level is {value}%", "response_failure": "Unable to get the current battery percentage."}}}\n' "```\n" "```\n" - "用户: 当前屏幕亮度是多少?\n" - '返回: {"function_call": {"name": "self_screen_get_brightness"}}\n' + "User: What is the current screen brightness?\n" + 'Return: {"function_call": {"name": "self_screen_get_brightness"}}\n' "```\n" "```\n" - "用户: 设置屏幕亮度为50%\n" - '返回: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n' + "User: Set screen brightness to 50%.\n" + 'Return: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n' "```\n" "```\n" - "用户: 我想结束对话\n" - '返回: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n' + "User: I want to end the conversation.\n" + 'Return: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n' "```\n" "```\n" - "用户: 你好啊\n" - '返回: {"function_call": {"name": "continue_chat"}}\n' + "User: Hello.\n" + 'Return: {"function_call": {"name": "continue_chat"}}\n' "```\n\n" - "注意:\n" - "1. 只返回JSON格式,不要包含任何其他文字\n" - '2. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n' - "3. 确保返回的JSON格式正确,包含所有必要的字段\n" - "特殊说明:\n" - "- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n" - "- 请返回多个function_call组成的JSON数组\n" - "- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}" + "Note:\n" + "1. Only return in JSON format, do not include any other text.\n" + '2. If no matching function is found, return {"function_call": {"name": "continue_chat"}}.\n' + "3. Ensure the returned JSON format is correct and includes all necessary fields.\n" + "Special Instructions:\n" + "- When a single user input contains multiple commands (e.g., 'turn on the light and increase the volume').\n" + "- Please return a JSON array of multiple function_calls.\n" + "- Example: {'function_calls': [{'name':'light_on'}, {'name':'volume_up'}]}" ) return prompt + def clean_cache(self): + """Clean up expired cache.""" + now = time.time() + # Find expired keys + expired_keys = [ + k + for k, v in self.intent_cache.items() + if now - v["timestamp"] > self.cache_expiry + ] + for key in expired_keys: + del self.intent_cache[key] + + # If the cache is too large, remove the oldest entries + if len(self.intent_cache) > self.cache_max_size: + # Sort by timestamp and keep the newest entries + sorted_items = sorted( + self.intent_cache.items(), key=lambda x: x[1]["timestamp"] + ) + for key, _ in sorted_items[: len(sorted_items) - self.cache_max_size]: + del self.intent_cache[key] + def replyResult(self, text: str, original_text: str): llm_result = self.llm.response_no_stream( system_prompt=text, - user_prompt="请根据以上内容,像人类一样说话的口吻回复用户,要求简洁,请直接返回结果。用户现在说:" + user_prompt="Based on the content above, please reply to the user in a human-like tone, keep it concise, and return the result directly. The user now says: " + original_text, ) return llm_result @@ -117,24 +137,31 @@ class IntentProvider(IntentProviderBase): if conn.func_handler is None: return '{"function_call": {"name": "continue_chat"}}' - # 记录整体开始时间 + # Record the overall start time total_start_time = time.time() - # 打印使用的模型信息 - model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__)) - logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}") + # Print the model information being used + model_info = getattr(self.llm, "model_name", + str(self.llm.__class__.__name__)) + logger.bind(tag=TAG).debug( + f"Using intent recognition model: {model_info}") - # 计算缓存键 - cache_key = hashlib.md5((conn.device_id + text).encode()).hexdigest() + # Calculate the cache key + cache_key = hashlib.md5(text.encode()).hexdigest() - # 检查缓存 - cached_intent = self.cache_manager.get(self.CacheType.INTENT, cache_key) - if cached_intent is not None: - cache_time = time.time() - total_start_time - logger.bind(tag=TAG).debug( - f"使用缓存的意图: {cache_key} -> {cached_intent}, 耗时: {cache_time:.4f}秒" - ) - return cached_intent + # Check the cache + if cache_key in self.intent_cache: + cache_entry = self.intent_cache[cache_key] + # Check if the cache has expired + if time.time() - cache_entry["timestamp"] <= self.cache_expiry: + cache_time = time.time() - total_start_time + logger.bind(tag=TAG).debug( + f"Using cached intent: {cache_key} -> {cache_entry['intent']}, time taken: {cache_time:.4f} seconds" + ) + return cache_entry["intent"] + + # Clean the cache + self.clean_cache() if self.promot == "": functions = conn.func_handler.get_functions() @@ -157,17 +184,17 @@ class IntentProvider(IntentProviderBase): else: devices = [] if len(devices) > 0: - hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" + hass_prompt = "\nHere is a list of my smart home devices (location, device name, entity_id), which can be controlled via Home Assistant:\n" for device in devices: hass_prompt += device + "\n" prompt_music += hass_prompt logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}") - # 构建用户对话历史的提示 + # Build the user dialogue history prompt msgStr = "" - # 获取最近的对话历史 + # Get the recent dialogue history start_idx = max(0, len(dialogue_history) - self.history_count) for i in range(start_idx, len(dialogue_history)): msgStr += f"{dialogue_history[i].role}: {dialogue_history[i].content}\n" @@ -175,57 +202,59 @@ class IntentProvider(IntentProviderBase): msgStr += f"User: {text}\n" user_prompt = f"current dialogue:\n{msgStr}" - # 记录预处理完成时间 + # Record the preprocessing completion time preprocess_time = time.time() - total_start_time - logger.bind(tag=TAG).debug(f"意图识别预处理耗时: {preprocess_time:.4f}秒") + logger.bind(tag=TAG).debug( + f"Intent recognition preprocessing time: {preprocess_time:.4f} seconds") - # 使用LLM进行意图识别 + # Use LLM for intent recognition llm_start_time = time.time() - logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}") + logger.bind(tag=TAG).debug( + f"Starting LLM intent recognition call, model: {model_info}") intent = self.llm.response_no_stream( system_prompt=prompt_music, user_prompt=user_prompt ) - # 记录LLM调用完成时间 + # Record the LLM call completion time llm_time = time.time() - llm_start_time logger.bind(tag=TAG).debug( - f"LLM意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}秒" + f"LLM intent recognition complete, model: {model_info}, call time: {llm_time:.4f} seconds" ) - # 记录后处理开始时间 + # Record the post-processing start time postprocess_start_time = time.time() - # 清理和解析响应 + # Clean and parse the response intent = intent.strip() - # 尝试提取JSON部分 + # Try to extract the JSON part match = re.search(r"\{.*\}", intent, re.DOTALL) if match: intent = match.group(0) - # 记录总处理时间 + # Record the total processing time total_time = time.time() - total_start_time logger.bind(tag=TAG).debug( - f"【意图识别性能】模型: {model_info}, 总耗时: {total_time:.4f}秒, LLM调用: {llm_time:.4f}秒, 查询: '{text[:20]}...'" + f"【Intent Recognition Performance】Model: {model_info}, Total time: {total_time:.4f}s, LLM call: {llm_time:.4f}s, Query: '{text[:20]}...'" ) - # 尝试解析为JSON + # Try to parse as JSON try: intent_data = json.loads(intent) - # 如果包含function_call,则格式化为适合处理的格式 + # If it contains function_call, format it for processing if "function_call" in intent_data: function_data = intent_data["function_call"] function_name = function_data.get("name") function_args = function_data.get("arguments", {}) - # 记录识别到的function call + # Record the recognized function call logger.bind(tag=TAG).info( - f"llm 识别到意图: {function_name}, 参数: {function_args}" + f"LLM recognized intent: {function_name}, arguments: {function_args}" ) - # 如果是继续聊天,清理工具调用相关的历史消息 + # If continuing the chat, clean up tool call related history messages if function_name == "continue_chat": - # 保留非工具相关的消息 + # Keep non-tool related messages clean_history = [ msg for msg in conn.dialogue.dialogue @@ -233,30 +262,38 @@ class IntentProvider(IntentProviderBase): ] conn.dialogue.dialogue = clean_history - # 添加到缓存 - self.cache_manager.set(self.CacheType.INTENT, cache_key, intent) + # Add to cache + self.intent_cache[cache_key] = { + "intent": intent, + "timestamp": time.time(), + } - # 后处理时间 + # Post-processing time postprocess_time = time.time() - postprocess_start_time - logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒") + logger.bind(tag=TAG).debug( + f"Intent post-processing time: {postprocess_time:.4f} seconds") - # 确保返回完全序列化的JSON字符串 + # Ensure a fully serialized JSON string is returned return intent else: - # 添加到缓存 - self.cache_manager.set(self.CacheType.INTENT, cache_key, intent) + # Add to cache + self.intent_cache[cache_key] = { + "intent": intent, + "timestamp": time.time(), + } - # 后处理时间 + # Post-processing time postprocess_time = time.time() - postprocess_start_time - logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒") + logger.bind(tag=TAG).debug( + f"Intent post-processing time: {postprocess_time:.4f} seconds") - # 返回普通意图 + # Return normal intent return intent except json.JSONDecodeError: - # 后处理时间 + # Post-processing time postprocess_time = time.time() - postprocess_start_time logger.bind(tag=TAG).error( - f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒" + f"Failed to parse intent JSON: {intent}, post-processing time: {postprocess_time:.4f} seconds" ) - # 如果解析失败,默认返回继续聊天意图 - return '{"intent": "继续聊天"}' \ No newline at end of file + # If parsing fails, default to returning a continue chat intent + return '{"intent": "Continue Chat"}' diff --git a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py index 4b08ae8f1..d273b129f 100644 --- a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py +++ b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py @@ -2,6 +2,7 @@ from ..base import IntentProviderBase from typing import List, Dict from config.logger import setup_logging + TAG = __name__ logger = setup_logging() @@ -9,12 +10,12 @@ logger = setup_logging() class IntentProvider(IntentProviderBase): async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: """ - 默认的意图识别实现,始终返回继续聊天 + Default intent recognition implementation, always returns continue chat Args: - dialogue_history: 对话历史记录列表 - text: 本次对话记录 + dialogue_history: List of dialogue history records + text: Current conversation record Returns: - 固定返回"继续聊天" + Fixed return "continue chat" """ logger.bind(tag=TAG).debug( "Using NoIntentProvider, always returning continue chat" diff --git a/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py b/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py index 012035ee7..35d4b94e9 100644 --- a/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py +++ b/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py @@ -4,6 +4,7 @@ from dashscope import Application from core.providers.llm.base import LLMProviderBase from core.utils.util import check_model_key + TAG = __name__ logger = setup_logging() @@ -19,14 +20,14 @@ class LLMProvider(LLMProviderBase): def response(self, session_id, dialogue): try: - # 处理dialogue + # Process dialogue if self.is_No_prompt: dialogue.pop(0) logger.bind(tag=TAG).debug( - f"【阿里百练API服务】处理后的dialogue: {dialogue}" + f"[Alibaba Bailian API Service] Processed dialogue: {dialogue}" ) - # 构造调用参数 + # Construct call parameters call_params = { "api_key": self.api_key, "app_id": self.app_id, @@ -34,12 +35,12 @@ class LLMProvider(LLMProviderBase): "messages": dialogue, } if self.memory_id != False: - # 百练memory需要prompt参数 + # Bailian memory requires prompt parameter prompt = dialogue[-1].get("content") call_params["memory_id"] = self.memory_id call_params["prompt"] = prompt logger.bind(tag=TAG).debug( - f"【阿里百练API服务】处理后的prompt: {prompt}" + f"[Alibaba Bailian API Service] Processed prompt: {prompt}" ) responses = Application.call(**call_params) @@ -47,20 +48,21 @@ class LLMProvider(LLMProviderBase): logger.bind(tag=TAG).error( f"code={responses.status_code}, " f"message={responses.message}, " - f"请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" + f"Please refer to documentation: https://help.aliyun.com/zh/model-studio/developer-reference/error-code" ) - yield "【阿里百练API服务响应异常】" + yield "[Alibaba Bailian API Service Response Exception]" else: logger.bind(tag=TAG).debug( - f"【阿里百练API服务】构造参数: {call_params}" + f"[Alibaba Bailian API Service] Constructed parameters: {call_params}" ) yield responses.output.text except Exception as e: - logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}") - yield "【LLM服务响应异常】" + logger.bind(tag=TAG).error( + f"[Alibaba Bailian API Service] Response exception: {e}") + yield "[LLM Service Response Exception]" def response_with_functions(self, session_id, dialogue, functions=None): logger.bind(tag=TAG).error( - f"阿里百练暂未实现完整的工具调用(function call),建议使用其他意图识别" - ) + f"Alibaba Bailian has not yet implemented complete tool calling (function call), it is recommended to use other intent recognition methods" + ) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py index 777861403..eb3c4e85e 100644 --- a/main/xiaozhi-server/core/providers/llm/base.py +++ b/main/xiaozhi-server/core/providers/llm/base.py @@ -1,9 +1,11 @@ from abc import ABC, abstractmethod from config.logger import setup_logging + TAG = __name__ logger = setup_logging() + class LLMProviderBase(ABC): @abstractmethod def response(self, session_id, dialogue): @@ -12,7 +14,7 @@ class LLMProviderBase(ABC): def response_no_stream(self, system_prompt, user_prompt, **kwargs): try: - # 构造对话格式 + # Construct dialogue format dialogue = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} @@ -23,17 +25,18 @@ class LLMProviderBase(ABC): return result except Exception as e: - logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") - return "【LLM服务响应异常】" - + logger.bind(tag=TAG).error( + f"Error in Ollama response generation: {e}") + return "[LLM Service Response Exception]" + def response_with_functions(self, session_id, dialogue, functions=None): """ Default implementation for function calling (streaming) This should be overridden by providers that support function calls + Returns: generator that yields either text tokens or a special function call token """ # For providers that don't support functions, just return regular response for token in self.response(session_id, dialogue): yield token, None - diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py index 31a7d4ac3..06c643b88 100644 --- a/main/xiaozhi-server/core/providers/llm/coze/coze.py +++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py @@ -2,6 +2,7 @@ from config.logger import setup_logging import json from core.providers.llm.base import LLMProviderBase + # official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py) from cozepy import COZE_CN_BASE_URL from cozepy import ( @@ -13,34 +14,41 @@ from cozepy import ( from core.providers.llm.system_prompt import get_system_prompt_for_function from core.utils.util import check_model_key + TAG = __name__ logger = setup_logging() + class LLMProvider(LLMProviderBase): def __init__(self, config): self.personal_access_token = config.get("personal_access_token") self.bot_id = str(config.get("bot_id")) self.user_id = str(config.get("user_id")) - self.session_conversation_map = {} # 存储session_id和conversation_id的映射 + self.session_conversation_map = {} # Store mapping between session_id and conversation_id model_key_msg = check_model_key("CozeLLM", self.personal_access_token) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) + def response(self, session_id, dialogue, **kwargs): coze_api_token = self.personal_access_token coze_api_base = COZE_CN_BASE_URL + last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") + coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base) conversation_id = self.session_conversation_map.get(session_id) - # 如果没有找到conversation_id,则创建新的对话 + + # If no conversation_id is found, create a new conversation if not conversation_id: conversation = coze.conversations.create(messages=[]) conversation_id = conversation.id - self.session_conversation_map[session_id] = conversation_id # 更新映射 + self.session_conversation_map[session_id] = conversation_id # Update mapping + for event in coze.chat.stream( bot_id=self.bot_id, @@ -54,15 +62,17 @@ class LLMProvider(LLMProviderBase): print(event.message.content, end="", flush=True) yield event.message.content + def response_with_functions(self, session_id, dialogue, functions=None): if len(dialogue) == 2 and functions is not None and len(functions) > 0: - # 第一次调用llm, 取最后一条用户消息,附加tool提示词 + # First call to llm, get the last user message, append tool prompt last_msg = dialogue[-1]["content"] function_str = json.dumps(functions, ensure_ascii=False) modify_msg = get_system_prompt_for_function(function_str) + last_msg dialogue[-1]["content"] = modify_msg - # 如果最后一个是 role="tool",附加到user上 + + # If the last one is role="tool", append to user if len(dialogue) > 1 and dialogue[-1]["role"] == "tool": assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n" while len(dialogue) > 1: @@ -71,5 +81,6 @@ class LLMProvider(LLMProviderBase): break dialogue.pop() + for token in self.response(session_id, dialogue): - yield token, None + yield token, None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py index 4ec04ec76..16bc16e49 100644 --- a/main/xiaozhi-server/core/providers/llm/dify/dify.py +++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py @@ -5,27 +5,31 @@ from core.providers.llm.base import LLMProviderBase from core.providers.llm.system_prompt import get_system_prompt_for_function from core.utils.util import check_model_key + TAG = __name__ logger = setup_logging() + class LLMProvider(LLMProviderBase): def __init__(self, config): self.api_key = config["api_key"] self.mode = config.get("mode", "chat-messages") self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip("/") - self.session_conversation_map = {} # 存储session_id和conversation_id的映射 + self.session_conversation_map = {} # Store mapping between session_id and conversation_id model_key_msg = check_model_key("DifyLLM", self.api_key) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) + def response(self, session_id, dialogue, **kwargs): try: - # 取最后一条用户消息 + # Get the last user message last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") conversation_id = self.session_conversation_map.get(session_id) - # 发起流式请求 + + # Initiate streaming request if self.mode == "chat-messages": request_json = { "query": last_msg["content"], @@ -47,6 +51,7 @@ class LLMProvider(LLMProviderBase): "user": session_id, } + with requests.post( f"{self.base_url}/{self.mode}", headers={"Authorization": f"Bearer {self.api_key}"}, @@ -57,13 +62,13 @@ class LLMProvider(LLMProviderBase): for line in r.iter_lines(): if line.startswith(b"data: "): event = json.loads(line[6:]) - # 如果没有找到conversation_id,则获取此次conversation_id + # If no conversation_id is found, get the conversation_id from this response if not conversation_id: conversation_id = event.get("conversation_id") self.session_conversation_map[session_id] = ( - conversation_id # 更新映射 + conversation_id # Update mapping ) - # 过滤 message_replace 事件,此事件会全量推一次 + # Filter message_replace events, as they push the full content once if event.get("event") != "message_replace" and event.get( "answer" ): @@ -76,30 +81,33 @@ class LLMProvider(LLMProviderBase): if event["data"]["status"] == "succeeded": yield event["data"]["outputs"]["answer"] else: - yield "【服务响应异常】" + yield "[Service Response Exception]" elif self.mode == "completion-messages": for line in r.iter_lines(): if line.startswith(b"data: "): event = json.loads(line[6:]) - # 过滤 message_replace 事件,此事件会全量推一次 + # Filter message_replace events, as they push the full content once if event.get("event") != "message_replace" and event.get( "answer" ): yield event["answer"] + except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") - yield "【服务响应异常】" + yield "[Service Response Exception]" + def response_with_functions(self, session_id, dialogue, functions=None): if len(dialogue) == 2 and functions is not None and len(functions) > 0: - # 第一次调用llm, 取最后一条用户消息,附加tool提示词 + # First call to llm, get the last user message, append tool prompt last_msg = dialogue[-1]["content"] function_str = json.dumps(functions, ensure_ascii=False) modify_msg = get_system_prompt_for_function(function_str) + last_msg dialogue[-1]["content"] = modify_msg - # 如果最后一个是 role="tool",附加到user上 + + # If the last one is role="tool", append to user if len(dialogue) > 1 and dialogue[-1]["role"] == "tool": assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n" while len(dialogue) > 1: @@ -108,5 +116,6 @@ class LLMProvider(LLMProviderBase): break dialogue.pop() + for token in self.response(session_id, dialogue): - yield token, None + yield token, None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py b/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py index 4f3f4259c..f077225b5 100644 --- a/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py +++ b/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py @@ -4,10 +4,12 @@ import requests from core.providers.llm.base import LLMProviderBase from core.utils.util import check_model_key + TAG = __name__ logger = setup_logging() + class LLMProvider(LLMProviderBase): def __init__(self, config): self.api_key = config["api_key"] @@ -18,12 +20,14 @@ class LLMProvider(LLMProviderBase): if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) + def response(self, session_id, dialogue, **kwargs): try: - # 取最后一条用户消息 + # Get the last user message last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") - # 发起流式请求 + + # Initiate streaming request with requests.post( f"{self.base_url}/chat/completions", headers={"Authorization": f"Bearer {self.api_key}"}, @@ -43,6 +47,7 @@ class LLMProvider(LLMProviderBase): if line[6:].decode("utf-8") == "[DONE]": break + data = json.loads(line[6:]) if "choices" in data and len(data["choices"]) > 0: delta = data["choices"][0].get("delta", {}) @@ -58,16 +63,19 @@ class LLMProvider(LLMProviderBase): continue yield content + except json.JSONDecodeError as e: continue except Exception as e: continue + except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") - yield "【服务响应异常】" + yield "[Service Response Exception]" + def response_with_functions(self, session_id, dialogue, functions=None): logger.bind(tag=TAG).error( - f"fastgpt暂未实现完整的工具调用(function call),建议使用其他意图识别" - ) + f"FastGPT has not yet implemented complete tool calling (function call), it is recommended to use other intent recognition methods" + ) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py index 608e83878..d383867fc 100644 --- a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py +++ b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py @@ -1,24 +1,26 @@ -import os, json, uuid +import os +import json +import uuid from types import SimpleNamespace from typing import Any, Dict, List - import requests from google import generativeai as genai from google.generativeai import types, GenerationConfig - from core.providers.llm.base import LLMProviderBase from core.utils.util import check_model_key from config.logger import setup_logging from google.generativeai.types import GenerateContentResponse from requests import RequestException + log = setup_logging() TAG = __name__ def test_proxy(proxy_url: str, test_url: str) -> bool: try: - resp = requests.get(test_url, proxies={"http": proxy_url, "https": proxy_url}) + resp = requests.get(test_url, proxies={ + "http": proxy_url, "https": proxy_url}) return 200 <= resp.status_code < 400 except RequestException: return False @@ -26,8 +28,8 @@ def test_proxy(proxy_url: str, test_url: str) -> bool: def setup_proxy_env(http_proxy: str | None, https_proxy: str | None): """ - 分别测试 HTTP 和 HTTPS 代理是否可用,并设置环境变量。 - 如果 HTTPS 代理不可用但 HTTP 可用,会将 HTTPS_PROXY 也指向 HTTP。 + Test whether HTTP and HTTPS proxies are available separately, and set environment variables. + If HTTPS proxy is not available but HTTP is available, will also point HTTPS_PROXY to HTTP. """ test_http_url = "http://www.google.com" test_https_url = "https://www.google.com" @@ -38,32 +40,37 @@ def setup_proxy_env(http_proxy: str | None, https_proxy: str | None): ok_http = test_proxy(http_proxy, test_http_url) if ok_http: os.environ["HTTP_PROXY"] = http_proxy - log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {http_proxy}") + log.bind(tag=TAG).info( + f"Configured Gemini HTTP proxy connection successful: {http_proxy}") else: - log.bind(tag=TAG).warning(f"配置提供的Gemini HTTP代理不可用: {http_proxy}") + log.bind(tag=TAG).warning( + f"Configured Gemini HTTP proxy not available: {http_proxy}") if https_proxy: ok_https = test_proxy(https_proxy, test_https_url) if ok_https: os.environ["HTTPS_PROXY"] = https_proxy - log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {https_proxy}") + log.bind(tag=TAG).info( + f"Configured Gemini HTTPS proxy connection successful: {https_proxy}") else: log.bind(tag=TAG).warning( - f"配置提供的Gemini HTTPS代理不可用: {https_proxy}" + f"Configured Gemini HTTPS proxy not available: {https_proxy}" ) - # 如果https_proxy不可用,但http_proxy可用且能走通https,则复用http_proxy作为https_proxy + # If https_proxy is not available, but http_proxy is available and can handle https, reuse http_proxy as https_proxy if ok_http and not ok_https: if test_proxy(http_proxy, test_https_url): os.environ["HTTPS_PROXY"] = http_proxy ok_https = True - log.bind(tag=TAG).info(f"复用HTTP代理作为HTTPS代理: {http_proxy}") + log.bind(tag=TAG).info( + f"Reusing HTTP proxy as HTTPS proxy: {http_proxy}") if not ok_http and not ok_https: log.bind(tag=TAG).error( - f"Gemini 代理设置失败: HTTP 和 HTTPS 代理都不可用,请检查配置" + f"Gemini proxy setup failed: Both HTTP and HTTPS proxies are not available, please check configuration" ) - raise RuntimeError("HTTP 和 HTTPS 代理都不可用,请检查配置") + raise RuntimeError( + "Both HTTP and HTTPS proxies are not available, please check configuration") class LLMProvider(LLMProviderBase): @@ -79,11 +86,11 @@ class LLMProvider(LLMProviderBase): if http_proxy or https_proxy: log.bind(tag=TAG).info( - f"检测到Gemini代理配置,开始测试代理连通性和设置代理环境..." + f"Gemini proxy configuration detected, starting proxy connectivity test and proxy environment setup..." ) setup_proxy_env(http_proxy, https_proxy) log.bind(tag=TAG).info( - f"Gemini 代理设置成功 - HTTP: {http_proxy}, HTTPS: {https_proxy}" + f"Gemini proxy setup successful - HTTP: {http_proxy}, HTTPS: {https_proxy}" ) genai.configure(api_key=self.api_key) self.model = genai.GenerativeModel(self.model_name) @@ -112,7 +119,8 @@ class LLMProvider(LLMProviderBase): ) ] - # Gemini文档提到,无需维护session-id,直接用dialogue拼接而成 + # Gemini documentation mentions that there's no need to maintain session-id, just concatenate dialogue directly + def response(self, session_id, dialogue, **kwargs): yield from self._generate(dialogue, None) @@ -122,7 +130,7 @@ class LLMProvider(LLMProviderBase): def _generate(self, dialogue, tools): role_map = {"assistant": "model", "user": "user"} contents: list = [] - # 拼接对话 + # Concatenate dialogue for m in dialogue: r = m["role"] @@ -170,7 +178,7 @@ class LLMProvider(LLMProviderBase): for chunk in stream: cand = chunk.candidates[0] for part in cand.content.parts: - # a) 函数调用-通常是最后一段话才是函数调用 + # a) Function call - usually only the last part is a function call if getattr(part, "function_call", None): fc = part.function_call yield None, [ @@ -186,15 +194,16 @@ class LLMProvider(LLMProviderBase): ) ] return - # b) 普通文本 + # b) Plain text if getattr(part, "text", None): yield part.text if tools is None else (part.text, None) finally: if tools is not None: - yield None, None # function‑mode 结束,返回哑包 + yield None, None # function‑mode end, return dummy packet + + # Close stream, reserved for future conversation interruption functionality, official documentation recommends closing previous stream when interrupting conversation, which can effectively reduce quota billing and resource usage - # 关闭stream,预留后续打断对话功能的功能方法,官方文档推荐打断对话要关闭上一个流,可以有效减少配额计费和资源占用 @staticmethod def _safe_finish_stream(stream: GenerateContentResponse): if hasattr(stream, "resolve"): @@ -202,5 +211,5 @@ class LLMProvider(LLMProviderBase): elif hasattr(stream, "close"): stream.close() # Gemini SDK version < 0.5.0 else: - for _ in stream: # 兜底耗尽 - pass + for _ in stream: # Fallback to exhaust + pass \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py index f203e5f7d..c284a0033 100644 --- a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py +++ b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py @@ -9,43 +9,46 @@ logger = setup_logging() class LLMProvider(LLMProviderBase): def __init__(self, config): - self.agent_id = config.get("agent_id") # 对应 agent_id + self.agent_id = config.get("agent_id") # Corresponding agent_id self.api_key = config.get("api_key") - self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url - self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL + # Default to use base_url + self.base_url = config.get("base_url", config.get("url")) + # Concatenate complete API URL + self.api_url = f"{self.base_url}/api/conversation/process" def response(self, session_id, dialogue, **kwargs): try: - # home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可 + # Home Assistant voice assistant has built-in intents, no need to use xiaozhi ai's built-in ones, just pass what the user said to Home Assistant - # 提取最后一个 role 为 'user' 的 content + # Extract the content of the last message with role 'user' input_text = None - if isinstance(dialogue, list): # 确保 dialogue 是一个列表 - # 逆序遍历,找到最后一个 role 为 'user' 的消息 + if isinstance(dialogue, list): # Ensure dialogue is a list + # Iterate in reverse order to find the last message with role 'user' for message in reversed(dialogue): - if message.get("role") == "user": # 找到 role 为 'user' 的消息 + if message.get("role") == "user": # Find message with role 'user' input_text = message.get("content", "") - break # 找到后立即退出循环 + break # Exit loop immediately after finding - # 构造请求数据 + # Construct request data payload = { "text": input_text, "agent_id": self.agent_id, - "conversation_id": session_id, # 使用 session_id 作为 conversation_id + "conversation_id": session_id, # Use session_id as conversation_id } - # 设置请求头 + # Set request headers headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", } - # 发起 POST 请求 - response = requests.post(self.api_url, json=payload, headers=headers) + # Send POST request + response = requests.post( + self.api_url, json=payload, headers=headers) - # 检查请求是否成功 + # Check if request was successful response.raise_for_status() - # 解析返回数据 + # Parse returned data data = response.json() speech = ( data.get("response", {}) @@ -54,18 +57,19 @@ class LLMProvider(LLMProviderBase): .get("speech", "") ) - # 返回生成的内容 + # Return generated content if speech: yield speech else: - logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容") + logger.bind(tag=TAG).warning( + "No speech content in API returned data") except RequestException as e: - logger.bind(tag=TAG).error(f"HTTP 请求错误: {e}") + logger.bind(tag=TAG).error(f"HTTP request error: {e}") except Exception as e: - logger.bind(tag=TAG).error(f"生成响应时出错: {e}") + logger.bind(tag=TAG).error(f"Error generating response: {e}") def response_with_functions(self, session_id, dialogue, functions=None): logger.bind(tag=TAG).error( - f"homeassistant不支持(function call),建议使用其他意图识别" - ) + f"Home Assistant does not support (function call), it is recommended to use other intent recognition methods" + ) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py index c973cacd8..4c90f8ad6 100644 --- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py +++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py @@ -3,54 +3,63 @@ from openai import OpenAI import json from core.providers.llm.base import LLMProviderBase + TAG = __name__ logger = setup_logging() + class LLMProvider(LLMProviderBase): def __init__(self, config): self.model_name = config.get("model_name") self.base_url = config.get("base_url", "http://localhost:11434") # Initialize OpenAI client with Ollama base URL - # 如果没有v1,增加v1 + # If there's no v1, add v1 if not self.base_url.endswith("/v1"): self.base_url = f"{self.base_url}/v1" + self.client = OpenAI( base_url=self.base_url, api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one ) - # 检查是否是qwen3模型 + + # Check if it's a qwen3 model self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3") + def response(self, session_id, dialogue, **kwargs): try: - # 如果是qwen3模型,在用户最后一条消息中添加/no_think指令 + # If it's a qwen3 model, add /no_think instruction to the user's last message if self.is_qwen3: - # 复制对话列表,避免修改原始对话 + # Copy dialogue list to avoid modifying the original dialogue dialogue_copy = dialogue.copy() - # 找到最后一条用户消息 + + # Find the last user message for i in range(len(dialogue_copy) - 1, -1, -1): if dialogue_copy[i]["role"] == "user": - # 在用户消息前添加/no_think指令 + # Add /no_think instruction before user message dialogue_copy[i]["content"] = ( "/no_think " + dialogue_copy[i]["content"] ) - logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令") + logger.bind(tag=TAG).debug(f"Added /no_think instruction for qwen3 model") break - # 使用修改后的对话 + + # Use the modified dialogue dialogue = dialogue_copy + responses = self.client.chat.completions.create( model=self.model_name, messages=dialogue, stream=True ) is_active = True - # 用于处理跨chunk的标签 + # Used to handle cross-chunk tags buffer = "" + for chunk in responses: try: delta = ( @@ -60,59 +69,70 @@ class LLMProvider(LLMProviderBase): ) content = delta.content if hasattr(delta, "content") else "" + if content: - # 将内容添加到缓冲区 + # Add content to buffer buffer += content - # 处理缓冲区中的标签 + + # Process tags in buffer while "" in buffer and "" in buffer: - # 找到完整的标签并移除 + # Find and remove complete tags pre = buffer.split("", 1)[0] post = buffer.split("", 1)[1] buffer = pre + post - # 处理只有开始标签的情况 + + # Handle case with only opening tag if "" in buffer: is_active = False buffer = buffer.split("", 1)[0] - # 处理只有结束标签的情况 + + # Handle case with only closing tag if "" in buffer: is_active = True buffer = buffer.split("", 1)[1] - # 如果当前处于活动状态且缓冲区有内容,则输出 + + # If currently active and buffer has content, output if is_active and buffer: yield buffer - buffer = "" # 清空缓冲区 + buffer = "" # Clear buffer + except Exception as e: logger.bind(tag=TAG).error(f"Error processing chunk: {e}") + except Exception as e: logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") - yield "【Ollama服务响应异常】" + yield "[Ollama Service Response Exception]" + def response_with_functions(self, session_id, dialogue, functions=None): try: - # 如果是qwen3模型,在用户最后一条消息中添加/no_think指令 + # If it's a qwen3 model, add /no_think instruction to the user's last message if self.is_qwen3: - # 复制对话列表,避免修改原始对话 + # Copy dialogue list to avoid modifying the original dialogue dialogue_copy = dialogue.copy() - # 找到最后一条用户消息 + + # Find the last user message for i in range(len(dialogue_copy) - 1, -1, -1): if dialogue_copy[i]["role"] == "user": - # 在用户消息前添加/no_think指令 + # Add /no_think instruction before user message dialogue_copy[i]["content"] = ( "/no_think " + dialogue_copy[i]["content"] ) - logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令") + logger.bind(tag=TAG).debug(f"Added /no_think instruction for qwen3 model") break - # 使用修改后的对话 + + # Use the modified dialogue dialogue = dialogue_copy + stream = self.client.chat.completions.create( model=self.model_name, messages=dialogue, @@ -120,9 +140,11 @@ class LLMProvider(LLMProviderBase): tools=functions, ) + is_active = True buffer = "" + for chunk in stream: try: delta = ( @@ -135,41 +157,48 @@ class LLMProvider(LLMProviderBase): delta.tool_calls if hasattr(delta, "tool_calls") else None ) - # 如果是工具调用,直接传递 + + # If it's a tool call, pass directly if tool_calls: yield None, tool_calls continue - # 处理文本内容 + + # Process text content if content: - # 将内容添加到缓冲区 + # Add content to buffer buffer += content - # 处理缓冲区中的标签 + + # Process tags in buffer while "" in buffer and "" in buffer: - # 找到完整的标签并移除 + # Find and remove complete tags pre = buffer.split("", 1)[0] post = buffer.split("", 1)[1] buffer = pre + post - # 处理只有开始标签的情况 + + # Handle case with only opening tag if "" in buffer: is_active = False buffer = buffer.split("", 1)[0] - # 处理只有结束标签的情况 + + # Handle case with only closing tag if "" in buffer: is_active = True buffer = buffer.split("", 1)[1] - # 如果当前处于活动状态且缓冲区有内容,则输出 + + # If currently active and buffer has content, output if is_active and buffer: yield buffer, None - buffer = "" # 清空缓冲区 + buffer = "" # Clear buffer except Exception as e: logger.bind(tag=TAG).error(f"Error processing function chunk: {e}") continue + except Exception as e: logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}") - yield f"【Ollama服务响应异常: {str(e)}】", None + yield f"[Ollama Service Response Exception: {str(e)}]", None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 5c85c6478..5c22401a8 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -5,10 +5,12 @@ from config.logger import setup_logging from core.utils.util import check_model_key from core.providers.llm.base import LLMProviderBase + TAG = __name__ logger = setup_logging() + class LLMProvider(LLMProviderBase): def __init__(self, config): self.model_name = config.get("model_name") @@ -17,10 +19,11 @@ class LLMProvider(LLMProviderBase): self.base_url = config.get("base_url") else: self.base_url = config.get("url") - # 增加timeout的配置项,单位为秒 + # Add timeout configuration item, unit is seconds timeout = config.get("timeout", 300) self.timeout = int(timeout) if timeout else 300 + param_defaults = { "max_tokens": (500, int), "temperature": (0.7, lambda x: round(float(x), 1)), @@ -28,6 +31,7 @@ class LLMProvider(LLMProviderBase): "frequency_penalty": (0, lambda x: round(float(x), 1)), } + for param, (default, converter) in param_defaults.items(): value = config.get(param) try: @@ -39,15 +43,18 @@ class LLMProvider(LLMProviderBase): except (ValueError, TypeError): setattr(self, param, default) + logger.debug( - f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}" + f"Intent recognition parameter initialization: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}" ) + model_key_msg = check_model_key("LLM", self.api_key) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout)) + def response(self, session_id, dialogue, **kwargs): try: responses = self.client.chat.completions.create( @@ -62,10 +69,11 @@ class LLMProvider(LLMProviderBase): ), ) + is_active = True for chunk in responses: try: - # 检查是否存在有效的choice且content不为空 + # Check if valid choice exists and content is not empty delta = ( chunk.choices[0].delta if getattr(chunk, "choices", None) @@ -75,7 +83,7 @@ class LLMProvider(LLMProviderBase): except IndexError: content = "" if content: - # 处理标签跨多个chunk的情况 + # Handle case where tags span multiple chunks if "" in content: is_active = False content = content.split("")[0] @@ -85,30 +93,34 @@ class LLMProvider(LLMProviderBase): if is_active: yield content + except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") + def response_with_functions(self, session_id, dialogue, functions=None): try: stream = self.client.chat.completions.create( model=self.model_name, messages=dialogue, stream=True, tools=functions ) + for chunk in stream: - # 检查是否存在有效的choice且content不为空 + # Check if valid choice exists and content is not empty if getattr(chunk, "choices", None): yield chunk.choices[0].delta.content, chunk.choices[ 0 ].delta.tool_calls - # 存在 CompletionUsage 消息时,生成 Token 消耗 log + # When CompletionUsage message exists, generate Token consumption log elif isinstance(getattr(chunk, "usage", None), CompletionUsage): usage_info = getattr(chunk, "usage", None) logger.bind(tag=TAG).info( - f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," - f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," - f"共计 {getattr(usage_info, 'total_tokens', '未知')}" + f"Token consumption: input {getattr(usage_info, 'prompt_tokens', 'unknown')}, " + f"output {getattr(usage_info, 'completion_tokens', 'unknown')}, " + f"total {getattr(usage_info, 'total_tokens', 'unknown')}" ) + except Exception as e: logger.bind(tag=TAG).error(f"Error in function call streaming: {e}") - yield f"【OpenAI服务响应异常: {e}】", None + yield f"[OpenAI Service Response Exception: {e}]", None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/system_prompt.py b/main/xiaozhi-server/core/providers/llm/system_prompt.py index 606f0e4b9..2d0e2e557 100644 --- a/main/xiaozhi-server/core/providers/llm/system_prompt.py +++ b/main/xiaozhi-server/core/providers/llm/system_prompt.py @@ -1,23 +1,28 @@ def get_system_prompt_for_function(functions: str) -> str: """ - 生成系统提示信息 - :param functions: 可用的函数列表 - :return: 系统提示信息 + Generate system prompt message + :param functions: List of available functions + :return: System prompt message """ SYSTEM_PROMPT = f""" ==== + TOOL USE + You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use. + # Tool Use Formatting + Tool use is formatted using JSON-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure: + {{ "name": "function name", @@ -29,20 +34,22 @@ Here's the structure: }} + For example: if you got tool as follow + {{ "type": "function", "function": {{ "name": "handle_exit_intent", - "description": "当用户想结束对话或需要退出系统时调用", + "description": "Called when user wants to end conversation or needs to exit system", "parameters": {{ "type": "object", "properties": {{ "say_goodbye": {{ "type": "string", - "description": "和用户友好结束对话的告别语", + "description": "Friendly goodbye message to end conversation with user", }} }}, "required": ["say_goodbye"], @@ -50,26 +57,33 @@ if you got tool as follow }}, }} + you should respond with the following format: + {{ "name": "handle_exit_intent", "arguments": {{ - "say_goodbye": "再见,祝您生活愉快!" + "say_goodbye": "Goodbye, have a pleasant life!" }} }} + Always adhere to this format for the tool use to ensure proper parsing and execution. + # Tools + {functions} + # Tool Use Guidelines + 1. Tools must be called in a separate message, Do not add thoughts when calling tools. The message must start with and end with , with the tool invocation JSON data in between. No additional response content is needed. 2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information. For example using the list_files tool is more effective than running a command like \`ls\` in the terminal. It's critical that you think about each available tool and use the one that best fits the current step in the task. @@ -84,20 +98,25 @@ Always adhere to this format for the tool use to ensure proper parsing and execu 6. ALWAYS wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user. 7. Tool calls should contain no extra information. Only after receiving the tool's response should you integrate it into a complete reply. + It is crucial to proceed step-by-step, waiting for the user's message after each tool use before moving forward with the task. This approach allows you to: 1. Confirm the success of each step before proceeding. 2. Address any issues or errors that arise immediately. 3. Adapt your approach based on new information or unexpected results. 4. Ensure that each action builds correctly on the previous ones. + By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work. + ==== + USER CHAT CONTENT + The following additional message is the user's chat message, and should be followed to the best of your ability without interfering with the TOOL USE guidelines. -""" - return SYSTEM_PROMPT \ No newline at end of file +""" + return SYSTEM_PROMPT diff --git a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py index a4e9a5e6c..f454f726f 100644 --- a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py +++ b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py @@ -3,6 +3,7 @@ from openai import OpenAI import json from core.providers.llm.base import LLMProviderBase + TAG = __name__ logger = setup_logging() @@ -12,7 +13,7 @@ class LLMProvider(LLMProviderBase): self.model_name = config.get("model_name") self.base_url = config.get("base_url", "http://localhost:9997") # Initialize OpenAI client with Xinference base URL - # 如果没有v1,增加v1 + # If there's no v1, add v1 if not self.base_url.endswith("/v1"): self.base_url = f"{self.base_url}/v1" @@ -23,11 +24,14 @@ class LLMProvider(LLMProviderBase): try: self.client = OpenAI( base_url=self.base_url, - api_key="xinference", # Xinference has a similar setup to Ollama where it doesn't need an actual key + # Xinference has a similar setup to Ollama where it doesn't need an actual key + api_key="xinference", ) - logger.bind(tag=TAG).info("Xinference client initialized successfully") + logger.bind(tag=TAG).info( + "Xinference client initialized successfully") except Exception as e: - logger.bind(tag=TAG).error(f"Error initializing Xinference client: {e}") + logger.bind(tag=TAG).error( + f"Error initializing Xinference client: {e}") raise def response(self, session_id, dialogue, **kwargs): @@ -46,7 +50,8 @@ class LLMProvider(LLMProviderBase): if getattr(chunk, "choices", None) else None ) - content = delta.content if hasattr(delta, "content") else "" + content = delta.content if hasattr( + delta, "content") else "" if content: if "" in content: is_active = False @@ -60,8 +65,9 @@ class LLMProvider(LLMProviderBase): logger.bind(tag=TAG).error(f"Error processing chunk: {e}") except Exception as e: - logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}") - yield "【Xinference服务响应异常】" + logger.bind(tag=TAG).error( + f"Error in Xinference response generation: {e}") + yield "[Xinference Service Response Exception]" def response_with_functions(self, session_id, dialogue, functions=None): try: @@ -91,8 +97,9 @@ class LLMProvider(LLMProviderBase): yield None, tool_calls except Exception as e: - logger.bind(tag=TAG).error(f"Error in Xinference function call: {e}") + logger.bind(tag=TAG).error( + f"Error in Xinference function call: {e}") yield { "type": "content", - "content": f"【Xinference服务响应异常: {str(e)}】", - } + "content": f"[Xinference Service Response Exception: {str(e)}]", + } \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py index d61d73f3e..e31c933db 100644 --- a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py +++ b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py @@ -1,5 +1,4 @@ import traceback - from ..base import MemoryProviderBase, logger from mem0 import MemoryClient from core.utils.util import check_model_key @@ -22,10 +21,13 @@ class MemoryProvider(MemoryProviderBase): try: self.client = MemoryClient(api_key=self.api_key) - logger.bind(tag=TAG).info("成功连接到 Mem0ai 服务") + logger.bind(tag=TAG).info( + "Successfully connected to Mem0ai service") except Exception as e: - logger.bind(tag=TAG).error(f"连接到 Mem0ai 服务时发生错误: {str(e)}") - logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + logger.bind(tag=TAG).error( + f"Error occurred while connecting to Mem0ai service: {str(e)}") + logger.bind(tag=TAG).error( + f"Detailed error: {traceback.format_exc()}") self.use_mem0 = False async def save_memory(self, msgs): @@ -46,7 +48,7 @@ class MemoryProvider(MemoryProviderBase): ) logger.bind(tag=TAG).debug(f"Save memory result: {result}") except Exception as e: - logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") + logger.bind(tag=TAG).error(f"Failed to save memory: {str(e)}") return None async def query_memory(self, query: str) -> str: @@ -73,7 +75,8 @@ class MemoryProvider(MemoryProviderBase): memory = entry.get("memory", "") if timestamp and memory: # Store tuple of (timestamp, formatted_string) for sorting - memories.append((timestamp, f"[{formatted_time}] {memory}")) + memories.append( + (timestamp, f"[{formatted_time}] {memory}")) # Sort by timestamp in descending order (newest first) memories.sort(key=lambda x: x[0], reverse=True) @@ -83,5 +86,5 @@ class MemoryProvider(MemoryProviderBase): logger.bind(tag=TAG).debug(f"Query results: {memories_str}") return memories_str except Exception as e: - logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") + logger.bind(tag=TAG).error(f"Failed to query memory: {str(e)}") return "" diff --git a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py index bc7909593..acebc8c6b 100644 --- a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py +++ b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py @@ -9,81 +9,80 @@ from core.utils.util import check_model_key short_term_memory_prompt = """ -# 时空记忆编织者 +# Temporal Memory Weaver -## 核心使命 -构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹 -根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务 +## Core Mission +Build a growable dynamic memory network that retains key information within limited space while intelligently maintaining information evolution trajectories +Summarize important user information based on conversation records to provide more personalized services in future conversations -## 记忆法则 -### 1. 三维度记忆评估(每次更新必执行) -| 维度 | 评估标准 | 权重分 | -|------------|---------------------------|--------| -| 时效性 | 信息新鲜度(按对话轮次) | 40% | -| 情感强度 | 含💖标记/重复提及次数 | 35% | -| 关联密度 | 与其他信息的连接数量 | 25% | +## Memory Rules +### 1. Three-Dimensional Memory Assessment (Must execute on every update) +| Dimension | Assessment Criteria | Weight | +|----------------|----------------------------------|--------| +| Timeliness | Information freshness (by turns) | 40% | +| Emotional Intensity | Contains 💖 marks/repeat mentions | 35% | +| Association Density | Number of connections to other info | 25% | -### 2. 动态更新机制 -**名字变更处理示例:** -原始记忆:"曾用名": ["张三"], "现用名": "张三丰" -触发条件:当检测到「我叫X」「称呼我Y」等命名信号时 -操作流程: -1. 将旧名移入"曾用名"列表 -2. 记录命名时间轴:"2024-02-15 14:32:启用张三丰" -3. 在记忆立方追加:「从张三到张三丰的身份蜕变」 +### 2. Dynamic Update Mechanism +**Name Change Handling Example:** +Original memory: "former_names": ["Zhang San"], "current_name": "Zhang Sanfeng" +Trigger condition: When detecting naming signals like "My name is X" "Call me Y" +Operation process: +1. Move old name to "former_names" list +2. Record naming timeline: "2024-02-15 14:32: Activated Zhang Sanfeng" +3. Append to memory cube: "Identity transformation from Zhang San to Zhang Sanfeng" -### 3. 空间优化策略 -- **信息压缩术**:用符号体系提升密度 - - ✅"张三丰[北/软工/🐱]" - - ❌"北京软件工程师,养猫" -- **淘汰预警**:当总字数≥900时触发 - 1. 删除权重分<60且3轮未提及的信息 - 2. 合并相似条目(保留时间戳最近的) +### 3. Space Optimization Strategy +- **Information Compression**: Use symbol system to enhance density + - ✅"Zhang Sanfeng[Beijing/SoftEng/🐱]" + - ❌"Beijing software engineer, owns cat" +- **Elimination Warning**: Triggered when total word count ≥900 + 1. Delete info with weight score <60 and not mentioned for 3 rounds + 2. Merge similar entries (keep most recent timestamp) -## 记忆结构 -输出格式必须为可解析的json字符串,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容 +## Memory Structure +Output format must be parseable JSON string, no explanations, comments or descriptions needed, only extract information from conversations when saving memory, do not mix in example content ```json { - "时空档案": { - "身份图谱": { - "现用名": "", - "特征标记": [] + "temporal_profile": { + "identity_map": { + "current_name": "", + "feature_tags": [] }, - "记忆立方": [ + "memory_cube": [ { - "事件": "入职新公司", - "时间戳": "2024-03-20", - "情感值": 0.9, - "关联项": ["下午茶"], - "保鲜期": 30 + "event": "Started new job", + "timestamp": "2024-03-20", + "emotional_value": 0.9, + "related_items": ["afternoon tea"], + "freshness_period": 30 } ] }, - "关系网络": { - "高频话题": {"职场": 12}, - "暗线联系": [""] + "relationship_network": { + "frequent_topics": {"workplace": 12}, + "hidden_connections": [""] }, - "待响应": { - "紧急事项": ["需立即处理的任务"], - "潜在关怀": ["可主动提供的帮助"] + "pending_response": { + "urgent_matters": ["Tasks requiring immediate attention"], + "potential_care": ["Help that can be proactively offered"] }, - "高光语录": [ - "最打动人心的瞬间,强烈的情感表达,user的原话" + "highlight_quotes": [ + "Most touching moments, strong emotional expressions, user's original words" ] } ``` """ short_term_memory_prompt_only_content = """ -你是一个经验丰富的记忆总结者,擅长将对话内容进行总结摘要,遵循以下规则: -1、总结user的重要信息,以便在未来的对话中提供更个性化的服务 -2、不要重复总结,不要遗忘之前记忆,除非原来的记忆超过了1800字内,否则不要遗忘、不要压缩用户的历史记忆 -3、用户操控的设备音量、播放音乐、天气、退出、不想对话等和用户本身无关的内容,这些信息不需要加入到总结中 -4、聊天内容中的今天的日期时间、今天的天气情况与用户事件无关的数据,这些信息如果当成记忆存储会影响后序对话,这些信息不需要加入到总结中 -5、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中 -6、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的 -7、只需要返回总结摘要,严格控制在1800字内 -8、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容 +You are an experienced memory summarizer, skilled at summarizing conversation content, following these rules: +1. Summarize important user information to provide more personalized services in future conversations +2. Don't repeat summaries, don't forget previous memories, unless original memory exceeds 1800 words, otherwise don't forget or compress user's historical memory +3. User device control content like volume, music playback, weather, exit, not wanting to chat etc. that are unrelated to the user themselves, this information doesn't need to be included in the summary +4. Don't include device control success/failure results in the summary, and don't include user's meaningless chatter +5. Don't summarize for the sake of summarizing, if user's chat is meaningless, returning the original historical record is acceptable +6. Only return summary digest, strictly control within 1800 words +7. Don't include code, xml, no explanations, comments or descriptions needed, only extract information from conversations when saving memory, don't mix in example content """ @@ -99,7 +98,7 @@ def extract_json_data(json_code): except Exception as e: print("Error:", e) return "" - jsonData = json_code[start + 7 : end] + jsonData = json_code[start + 7: end] return jsonData @@ -122,7 +121,7 @@ class MemoryProvider(MemoryProviderBase): self.load_memory(summary_memory) def load_memory(self, summary_memory): - # api获取到总结记忆后直接返回 + # Return directly after API retrieves summary memory if summary_memory or not self.save_to_file: self.short_memory = summary_memory return @@ -144,11 +143,18 @@ class MemoryProvider(MemoryProviderBase): yaml.dump(all_memory, f, allow_unicode=True) async def save_memory(self, msgs): - # 打印使用的模型信息 - model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__)) - logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}") + # Check if llm is set + if not hasattr(self, 'llm') or self.llm is None: + logger.bind(tag=TAG).error("LLM is not set for memory provider") + return None + + # Print model information being used + model_info = getattr(self.llm, "model_name", + str(self.llm.__class__.__name__)) + logger.bind(tag=TAG).debug(f"Using memory saving model: {model_info}") api_key = getattr(self.llm, "api_key", None) - memory_key_msg = check_model_key("记忆总结专用LLM", api_key) + memory_key_msg = check_model_key( + "Memory Summary Dedicated LLM", api_key) if memory_key_msg: logger.bind(tag=TAG).error(memory_key_msg) if self.llm is None: @@ -165,12 +171,12 @@ class MemoryProvider(MemoryProviderBase): elif msg.role == "assistant": msgStr += f"Assistant: {msg.content}\n" if self.short_memory and len(self.short_memory) > 0: - msgStr += "历史记忆:\n" + msgStr += "Historical Memory:\n" msgStr += self.short_memory - # 当前时间 + # Current time time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) - msgStr += f"当前时间:{time_str}" + msgStr += f"Current time: {time_str}" if self.save_to_file: result = self.llm.response_no_stream( @@ -181,7 +187,7 @@ class MemoryProvider(MemoryProviderBase): ) json_str = extract_json_data(result) try: - json.loads(json_str) # 检查json格式是否正确 + json.loads(json_str) # Check if JSON format is correct self.short_memory = json_str self.save_memory_to_file() except Exception as e: @@ -194,9 +200,10 @@ class MemoryProvider(MemoryProviderBase): temperature=0.2, ) save_mem_local_short(self.role_id, result) - logger.bind(tag=TAG).info(f"Save memory successful - Role: {self.role_id}") + logger.bind(tag=TAG).info( + f"Save memory successful - Role: {self.role_id}") return self.short_memory async def query_memory(self, query: str) -> str: - return self.short_memory \ No newline at end of file + return self.short_memory diff --git a/main/xiaozhi-server/core/providers/memory/nomem/nomem.py b/main/xiaozhi-server/core/providers/memory/nomem/nomem.py index 51523be46..95c756f75 100644 --- a/main/xiaozhi-server/core/providers/memory/nomem/nomem.py +++ b/main/xiaozhi-server/core/providers/memory/nomem/nomem.py @@ -1,20 +1,21 @@ """ -不使用记忆,可以选择此模块 +If not using memory, you can choose this module """ from ..base import MemoryProviderBase, logger TAG = __name__ - class MemoryProvider(MemoryProviderBase): def __init__(self, config, summary_memory=None): super().__init__(config) + async def save_memory(self, msgs): logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.") return None + async def query_memory(self, query: str) -> str: logger.bind(tag=TAG).debug("nomem mode: No memory query is performed.") - return "" + return "" \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/base/__init__.py b/main/xiaozhi-server/core/providers/tools/base/__init__.py index 7476ddd55..89e8c8f88 100644 --- a/main/xiaozhi-server/core/providers/tools/base/__init__.py +++ b/main/xiaozhi-server/core/providers/tools/base/__init__.py @@ -1,4 +1,4 @@ -"""基础工具定义模块""" +"""Base tool definition module""" from .tool_types import ToolType, ToolDefinition from .tool_executor import ToolExecutor diff --git a/main/xiaozhi-server/core/providers/tools/base/tool_executor.py b/main/xiaozhi-server/core/providers/tools/base/tool_executor.py index 7685e7c2d..820aa536d 100644 --- a/main/xiaozhi-server/core/providers/tools/base/tool_executor.py +++ b/main/xiaozhi-server/core/providers/tools/base/tool_executor.py @@ -1,27 +1,26 @@ -"""工具执行器基类定义""" +"""Tool executor base class definition""" from abc import ABC, abstractmethod from typing import Dict, Any from .tool_types import ToolDefinition from plugins_func.register import ActionResponse - class ToolExecutor(ABC): - """工具执行器抽象基类""" - + """Tool executor abstract base class""" + @abstractmethod async def execute( self, conn, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行工具调用""" + """Execute tool call""" pass - + @abstractmethod def get_tools(self) -> Dict[str, ToolDefinition]: - """获取该执行器管理的所有工具""" + """Get all tools managed by this executor""" pass - + @abstractmethod def has_tool(self, tool_name: str) -> bool: - """检查是否有指定工具""" + """Check if specified tool exists""" pass diff --git a/main/xiaozhi-server/core/providers/tools/base/tool_types.py b/main/xiaozhi-server/core/providers/tools/base/tool_types.py index 91466fad9..e6b0ae638 100644 --- a/main/xiaozhi-server/core/providers/tools/base/tool_types.py +++ b/main/xiaozhi-server/core/providers/tools/base/tool_types.py @@ -1,27 +1,25 @@ -"""工具系统的类型定义""" +"""Type definitions for tool system""" from enum import Enum - from dataclasses import dataclass from typing import Any, Dict, Optional from plugins_func.register import Action class ToolType(Enum): - """工具类型枚举""" - - SERVER_PLUGIN = "server_plugin" # 服务端插件 - SERVER_MCP = "server_mcp" # 服务端MCP - DEVICE_IOT = "device_iot" # 设备端IoT - DEVICE_MCP = "device_mcp" # 设备端MCP - MCP_ENDPOINT = "mcp_endpoint" # MCP接入点 + """Tool type enumeration""" + SERVER_PLUGIN = "server_plugin" # Server-side plugin + SERVER_MCP = "server_mcp" # Server-side MCP + DEVICE_IOT = "device_iot" # Device-side IoT + DEVICE_MCP = "device_mcp" # Device-side MCP + MCP_ENDPOINT = "mcp_endpoint" # MCP endpoint @dataclass class ToolDefinition: - """工具定义""" - - name: str # 工具名称 - description: Dict[str, Any] # 工具描述(OpenAI函数调用格式) - tool_type: ToolType # 工具类型 - parameters: Optional[Dict[str, Any]] = None # 额外参数 + """Tool definition""" + name: str # Tool name + # Tool description (OpenAI function call format) + description: Dict[str, Any] + tool_type: ToolType # Tool type + parameters: Optional[Dict[str, Any]] = None # Additional parameters diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/__init__.py b/main/xiaozhi-server/core/providers/tools/device_iot/__init__.py index 844c5c283..1bb8fc2e7 100644 --- a/main/xiaozhi-server/core/providers/tools/device_iot/__init__.py +++ b/main/xiaozhi-server/core/providers/tools/device_iot/__init__.py @@ -1,4 +1,4 @@ -"""设备端IoT工具模块""" +"""Device-side IoT tool module""" from .iot_descriptor import IotDescriptor from .iot_handler import handleIotDescriptors, handleIotStatus diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py b/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py index 81df02ad3..bff92a636 100644 --- a/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py +++ b/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py @@ -1,21 +1,20 @@ -"""IoT设备描述符定义""" +"""IoT device descriptor definition""" from config.logger import setup_logging TAG = __name__ logger = setup_logging() - class IotDescriptor: - """IoT设备描述符""" - + """IoT device descriptor""" + def __init__(self, name, description, properties, methods): self.name = name self.description = description self.properties = [] self.methods = [] - - # 根据描述创建属性 + + # Create properties based on description if properties is not None: for key, value in properties.items(): property_item = {} @@ -28,14 +27,14 @@ class IotDescriptor: else: property_item["value"] = "" self.properties.append(property_item) - - # 根据描述创建方法 + + # Create methods based on description if methods is not None: for key, value in methods.items(): method = {} method["description"] = value["description"] method["name"] = key - # 检查方法是否有参数 + # Check if method has parameters if "parameters" in value: method["parameters"] = {} for k, v in value["parameters"].items(): diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py b/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py index 7be9e1123..5731666af 100644 --- a/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py +++ b/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py @@ -1,4 +1,4 @@ -"""设备端IoT工具执行器""" +"""Device-side IoT tool executor""" import json import asyncio @@ -6,10 +6,9 @@ from typing import Dict, Any from ..base import ToolType, ToolDefinition, ToolExecutor from plugins_func.register import Action, ActionResponse - class DeviceIoTExecutor(ToolExecutor): - """设备端IoT工具执行器""" - + """Device-side IoT tool executor""" + def __init__(self, conn): self.conn = conn self.iot_tools: Dict[str, ToolDefinition] = {} @@ -17,65 +16,63 @@ class DeviceIoTExecutor(ToolExecutor): async def execute( self, conn, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行设备端IoT工具""" + """Execute device-side IoT tool""" if not self.has_tool(tool_name): return ActionResponse( - action=Action.NOTFOUND, response=f"IoT工具 {tool_name} 不存在" + action=Action.NOTFOUND, response=f"IoT tool {tool_name} does not exist" ) try: - # 解析工具名称,获取设备名和操作类型 + # Parse tool name to get device name and operation type if tool_name.startswith("get_"): - # 查询操作:get_devicename_property + # Query operation: get_devicename_property parts = tool_name.split("_", 2) if len(parts) >= 3: device_name = parts[1] property_name = parts[2] - value = await self._get_iot_status(device_name, property_name) + if value is not None: - # 处理响应模板 + # Process response template response_success = arguments.get( - "response_success", "查询成功:{value}" + "response_success", "Query successful: {value}" ) response = response_success.replace("{value}", str(value)) - return ActionResponse( action=Action.RESPONSE, response=response, ) else: response_failure = arguments.get( - "response_failure", f"无法获取{device_name}的状态" + "response_failure", f"Unable to get status of {device_name}" ) return ActionResponse( action=Action.ERROR, response=response_failure ) else: - # 控制操作:devicename_method + # Control operation: devicename_method parts = tool_name.split("_", 1) if len(parts) >= 2: device_name = parts[0] method_name = parts[1] - - # 提取控制参数(排除响应参数) + + # Extract control parameters (exclude response parameters) control_params = { k: v for k, v in arguments.items() if k not in ["response_success", "response_failure"] } - - # 发送IoT控制命令 + + # Send IoT control command await self._send_iot_command( device_name, method_name, control_params ) - - # 等待状态更新 + + # Wait for status update await asyncio.sleep(0.1) - - response_success = arguments.get("response_success", "操作成功") - - # 处理响应中的占位符 + response_success = arguments.get("response_success", "Operation successful") + + # Handle placeholders in response for param_name, param_value in control_params.items(): placeholder = "{" + param_name + "}" if placeholder in response_success: @@ -87,20 +84,20 @@ class DeviceIoTExecutor(ToolExecutor): "{value}", str(param_value) ) break - + return ActionResponse( action=Action.REQLLM, result=response_success, ) - return ActionResponse(action=Action.ERROR, response="无法解析IoT工具名称") + return ActionResponse(action=Action.ERROR, response="Unable to parse IoT tool name") except Exception as e: - response_failure = arguments.get("response_failure", "操作失败") + response_failure = arguments.get("response_failure", "Operation failed") return ActionResponse(action=Action.ERROR, response=response_failure) async def _get_iot_status(self, device_name: str, property_name: str): - """获取IoT设备状态""" + """Get IoT device status""" for key, value in self.conn.iot_descriptors.items(): if key.lower() == device_name.lower(): for property_item in value.properties: @@ -111,7 +108,7 @@ class DeviceIoTExecutor(ToolExecutor): async def _send_iot_command( self, device_name: str, method_name: str, parameters: Dict[str, Any] ): - """发送IoT控制命令""" + """Send IoT control command""" for key, value in self.conn.iot_descriptors.items(): if key.lower() == device_name.lower(): for method in value.methods: @@ -120,67 +117,65 @@ class DeviceIoTExecutor(ToolExecutor): "name": key, "method": method["name"], } - if parameters: command["parameters"] = parameters - + send_message = json.dumps( {"type": "iot", "commands": [command]} ) await self.conn.websocket.send(send_message) return - - raise Exception(f"未找到设备{device_name}的方法{method_name}") + + raise Exception(f"Method {method_name} not found for device {device_name}") def register_iot_tools(self, descriptors: list): - """注册IoT工具""" + """Register IoT tools""" for descriptor in descriptors: device_name = descriptor["name"] device_desc = descriptor["description"] - - # 注册查询工具 + + # Register query tools if "properties" in descriptor: for prop_name, prop_info in descriptor["properties"].items(): tool_name = f"get_{device_name.lower()}_{prop_name.lower()}" - tool_desc = { "type": "function", "function": { "name": tool_name, - "description": f"查询{device_desc}的{prop_info['description']}", + "description": f"Query {prop_info['description']} of {device_desc}", "parameters": { "type": "object", "properties": { "response_success": { "type": "string", - "description": f"查询成功时的友好回复,必须使用{{value}}作为占位符表示查询到的值", + "description": f"Friendly reply when query is successful, must use {{value}} as placeholder to represent the queried value", }, "response_failure": { "type": "string", - "description": f"查询失败时的友好回复", + "description": f"Friendly reply when query fails", }, }, "required": ["response_success", "response_failure"], }, }, } - + self.iot_tools[tool_name] = ToolDefinition( name=tool_name, description=tool_desc, tool_type=ToolType.DEVICE_IOT, ) - # 注册控制工具 + # Register control tools if "methods" in descriptor: for method_name, method_info in descriptor["methods"].items(): tool_name = f"{device_name.lower()}_{method_name.lower()}" - - # 构建参数 + + # Build parameters parameters = {} required_params = [] - - # 添加方法的原始参数 + + # Add original method parameters if "parameters" in method_info: parameters.update( { @@ -194,22 +189,22 @@ class DeviceIoTExecutor(ToolExecutor): } ) required_params.extend(method_info["parameters"].keys()) - - # 添加响应参数 + + # Add response parameters parameters.update( { "response_success": { "type": "string", - "description": "操作成功时的友好回复", + "description": "Friendly reply when operation is successful", }, "response_failure": { "type": "string", - "description": "操作失败时的友好回复", + "description": "Friendly reply when operation fails", }, } ) required_params.extend(["response_success", "response_failure"]) - + tool_desc = { "type": "function", "function": { @@ -222,7 +217,7 @@ class DeviceIoTExecutor(ToolExecutor): }, }, } - + self.iot_tools[tool_name] = ToolDefinition( name=tool_name, description=tool_desc, @@ -230,9 +225,9 @@ class DeviceIoTExecutor(ToolExecutor): ) def get_tools(self) -> Dict[str, ToolDefinition]: - """获取所有设备端IoT工具""" + """Get all device-side IoT tools""" return self.iot_tools.copy() def has_tool(self, tool_name: str) -> bool: - """检查是否有指定的设备端IoT工具""" - return tool_name in self.iot_tools + """Check if the specified device-side IoT tool exists""" + return tool_name in self.iot_tools \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py b/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py index 63992f273..39fb131b1 100644 --- a/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py +++ b/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py @@ -1,4 +1,4 @@ -"""IoT设备支持模块,提供IoT设备描述符和状态处理""" +"""IoT device support module, provides IoT device descriptor and status handling""" import asyncio from config.logger import setup_logging @@ -9,7 +9,7 @@ logger = setup_logging() async def handleIotDescriptors(conn, descriptors): - """处理物联网描述""" + """Handle IoT descriptors""" wait_max_time = 5 while ( not hasattr(conn, "func_handler") @@ -19,31 +19,30 @@ async def handleIotDescriptors(conn, descriptors): await asyncio.sleep(1) wait_max_time -= 1 if wait_max_time <= 0: - logger.bind(tag=TAG).debug("连接对象没有func_handler") + logger.bind(tag=TAG).debug("Connection object has no func_handler") return functions_changed = False - for descriptor in descriptors: - # 如果descriptor没有properties和methods,则直接跳过 + # If descriptor has no properties and methods, skip directly if "properties" not in descriptor and "methods" not in descriptor: continue - # 处理缺失properties的情况 + # Handle missing properties case if "properties" not in descriptor: descriptor["properties"] = {} - # 从methods中提取所有参数作为properties + # Extract all parameters from methods as properties if "methods" in descriptor: for method_name, method_info in descriptor["methods"].items(): if "parameters" in method_info: for param_name, param_info in method_info["parameters"].items(): - # 将参数信息转换为属性信息 + # Convert parameter info to property info descriptor["properties"][param_name] = { "description": param_info["description"], "type": param_info["type"], } - # 创建IOT设备描述符 + # Create IoT device descriptor iot_descriptor = IotDescriptor( descriptor["name"], descriptor["description"], @@ -53,16 +52,15 @@ async def handleIotDescriptors(conn, descriptors): conn.iot_descriptors[descriptor["name"]] = iot_descriptor functions_changed = True - # 如果注册了新函数,更新function描述列表 + # If new functions are registered, update function description list if functions_changed and hasattr(conn, "func_handler"): - # 注册IoT工具到统一工具处理器 + # Register IoT tools to unified tool handler await conn.func_handler.register_iot_tools(descriptors) - conn.func_handler.current_support_functions() async def handleIotStatus(conn, states): - """处理物联网状态""" + """Handle IoT status""" for state in states: for key, value in conn.iot_descriptors.items(): if key == state["name"]: @@ -71,13 +69,13 @@ async def handleIotStatus(conn, states): if property_item["name"] == k: if type(v) != type(property_item["value"]): logger.bind(tag=TAG).error( - f"属性{property_item['name']}的值类型不匹配" + f"Property {property_item['name']} value type mismatch" ) break else: property_item["value"] = v logger.bind(tag=TAG).info( - f"物联网状态更新: {key} , {property_item['name']} = {v}" + f"IoT status update: {key}, {property_item['name']} = {v}" ) - break + break break diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/__init__.py b/main/xiaozhi-server/core/providers/tools/device_mcp/__init__.py index 266d60c8a..3cb51fef6 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/__init__.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/__init__.py @@ -1,6 +1,7 @@ -"""设备端MCP工具模块""" +"""Device-side MCP tool module""" from .mcp_client import MCPClient + from .mcp_handler import ( send_mcp_message, handle_mcp_message, @@ -8,6 +9,7 @@ from .mcp_handler import ( send_mcp_tools_list_request, call_mcp_tool, ) + from .mcp_executor import DeviceMCPExecutor __all__ = [ diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py index 75aa22b55..9224de749 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py @@ -1,4 +1,4 @@ -"""设备端MCP客户端定义""" +"""Device-side MCP client definition""" import asyncio from concurrent.futures import Future @@ -8,10 +8,9 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() - class MCPClient: - """设备端MCP客户端,用于管理MCP状态和工具""" - + """Device-side MCP client for managing MCP state and tools""" + def __init__(self): self.tools = {} # sanitized_name -> tool_data self.name_mapping = {} @@ -28,7 +27,7 @@ class MCPClient: # Check if the cache is valid if self._cached_available_tools is not None: return self._cached_available_tools - + # If cache is not valid, regenerate the list result = [] for tool_name, tool_data in self.tools.items(): @@ -42,7 +41,7 @@ class MCPClient: }, } result.append({"type": "function", "function": function_def}) - + self._cached_available_tools = result # Store the generated list in cache return result @@ -59,9 +58,7 @@ class MCPClient: sanitized_name = sanitize_tool_name(tool_data["name"]) self.tools[sanitized_name] = tool_data self.name_mapping[sanitized_name] = tool_data["name"] - self._cached_available_tools = ( - None # Invalidate the cache when a tool is added - ) + self._cached_available_tools = None # Invalidate the cache when a tool is added async def get_next_id(self) -> int: async with self.lock: @@ -90,4 +87,4 @@ class MCPClient: async def cleanup_call_result(self, id: int): async with self.lock: if id in self.call_results: - self.call_results.pop(id) + self.call_results.pop(id) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py index 9f4be061f..1629d168f 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py @@ -1,42 +1,40 @@ -"""设备端MCP工具执行器""" +"""Device-side MCP tool executor""" from typing import Dict, Any from ..base import ToolType, ToolDefinition, ToolExecutor from plugins_func.register import Action, ActionResponse from .mcp_handler import call_mcp_tool - class DeviceMCPExecutor(ToolExecutor): - """设备端MCP工具执行器""" - + """Device-side MCP tool executor""" + def __init__(self, conn): self.conn = conn async def execute( self, conn, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行设备端MCP工具""" + """Execute device-side MCP tool""" if not hasattr(conn, "mcp_client") or not conn.mcp_client: return ActionResponse( action=Action.ERROR, - response="设备端MCP客户端未初始化", + response="Device-side MCP client not initialized", ) if not await conn.mcp_client.is_ready(): return ActionResponse( action=Action.ERROR, - response="设备端MCP客户端未准备就绪", + response="Device-side MCP client not ready", ) try: - # 转换参数为JSON字符串 + # Convert parameters to JSON string import json - args_str = json.dumps(arguments) if arguments else "{}" - - # 调用设备端MCP工具 + + # Call device-side MCP tool result = await call_mcp_tool(conn, conn.mcp_client, tool_name, args_str) - + resultJson = None if isinstance(result, str): try: @@ -44,7 +42,7 @@ class DeviceMCPExecutor(ToolExecutor): except Exception as e: pass - # 视觉大模型不经过二次LLM处理 + # Vision models do not go through secondary LLM processing if ( resultJson is not None and isinstance(resultJson, dict) @@ -63,17 +61,16 @@ class DeviceMCPExecutor(ToolExecutor): return ActionResponse(action=Action.ERROR, response=str(e)) def get_tools(self) -> Dict[str, ToolDefinition]: - """获取所有设备端MCP工具""" + """Get all device-side MCP tools""" if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client: return {} tools = {} mcp_tools = self.conn.mcp_client.get_available_tools() - + for tool in mcp_tools: func_def = tool.get("function", {}) tool_name = func_def.get("name", "") - if tool_name: tools[tool_name] = ToolDefinition( name=tool_name, description=tool, tool_type=ToolType.DEVICE_MCP @@ -82,8 +79,7 @@ class DeviceMCPExecutor(ToolExecutor): return tools def has_tool(self, tool_name: str) -> bool: - """检查是否有指定的设备端MCP工具""" + """Check if the specified device-side MCP tool exists""" if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client: return False - - return self.conn.mcp_client.has_tool(tool_name) + return self.conn.mcp_client.has_tool(tool_name) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py index c1b4d6c85..da4b311ed 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py @@ -1,4 +1,4 @@ -"""设备端MCP客户端支持模块""" +"""Device-side MCP client support module""" import json import asyncio @@ -12,111 +12,28 @@ TAG = __name__ logger = setup_logging() -class MCPClient: - """设备端MCP客户端,用于管理MCP状态和工具""" - - def __init__(self): - self.tools = {} # sanitized_name -> tool_data - self.name_mapping = {} - self.ready = False - self.call_results = {} # To store Futures for tool call responses - self.next_id = 1 - self.lock = asyncio.Lock() - self._cached_available_tools = None # Cache for get_available_tools - - def has_tool(self, name: str) -> bool: - return name in self.tools - - def get_available_tools(self) -> list: - # Check if the cache is valid - if self._cached_available_tools is not None: - return self._cached_available_tools - - # If cache is not valid, regenerate the list - result = [] - for tool_name, tool_data in self.tools.items(): - function_def = { - "name": tool_name, - "description": tool_data["description"], - "parameters": { - "type": tool_data["inputSchema"].get("type", "object"), - "properties": tool_data["inputSchema"].get("properties", {}), - "required": tool_data["inputSchema"].get("required", []), - }, - } - result.append({"type": "function", "function": function_def}) - - self._cached_available_tools = result # Store the generated list in cache - return result - - async def is_ready(self) -> bool: - async with self.lock: - return self.ready - - async def set_ready(self, status: bool): - async with self.lock: - self.ready = status - - async def add_tool(self, tool_data: dict): - async with self.lock: - sanitized_name = sanitize_tool_name(tool_data["name"]) - self.tools[sanitized_name] = tool_data - self.name_mapping[sanitized_name] = tool_data["name"] - self._cached_available_tools = ( - None # Invalidate the cache when a tool is added - ) - - async def get_next_id(self) -> int: - async with self.lock: - current_id = self.next_id - self.next_id += 1 - return current_id - - async def register_call_result_future(self, id: int, future: Future): - async with self.lock: - self.call_results[id] = future - - async def resolve_call_result(self, id: int, result: any): - async with self.lock: - if id in self.call_results: - future = self.call_results.pop(id) - if not future.done(): - future.set_result(result) - - async def reject_call_result(self, id: int, exception: Exception): - async with self.lock: - if id in self.call_results: - future = self.call_results.pop(id) - if not future.done(): - future.set_exception(exception) - - async def cleanup_call_result(self, id: int): - async with self.lock: - if id in self.call_results: - self.call_results.pop(id) - - async def send_mcp_message(conn, payload: dict): """Helper to send MCP messages, encapsulating common logic.""" if not conn.features.get("mcp"): - logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息") + logger.bind(tag=TAG).warning( + "Client does not support MCP, cannot send MCP message") return message = json.dumps({"type": "mcp", "payload": payload}) - try: await conn.websocket.send(message) - logger.bind(tag=TAG).info(f"成功发送MCP消息: {message}") + logger.bind(tag=TAG).info(f"Successfully sent MCP message: {message}") except Exception as e: - logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}") + logger.bind(tag=TAG).error(f"Failed to send MCP message: {e}") -async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): - """处理MCP消息,包括初始化、工具列表和工具调用响应等""" - logger.bind(tag=TAG).info(f"处理MCP消息: {str(payload)[:100]}") +async def handle_mcp_message(conn, mcp_client, payload: dict): + """Handle MCP messages, including initialization, tool list and tool call responses""" + logger.bind(tag=TAG).info(f"Handling MCP message: {str(payload)[:100]}") if not isinstance(payload, dict): - logger.bind(tag=TAG).error("MCP消息缺少payload字段或格式错误") + logger.bind(tag=TAG).error( + "MCP message missing payload field or format error") return # Handle result @@ -127,32 +44,32 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): # Check for tool call response first if msg_id in mcp_client.call_results: logger.bind(tag=TAG).debug( - f"收到工具调用响应,ID: {msg_id}, 结果: {result}" + f"Received tool call response, ID: {msg_id}, Result: {result}" ) await mcp_client.resolve_call_result(msg_id, result) return if msg_id == 1: # mcpInitializeID - logger.bind(tag=TAG).debug("收到MCP初始化响应") + logger.bind(tag=TAG).debug("Received MCP initialization response") server_info = result.get("serverInfo") if isinstance(server_info, dict): name = server_info.get("name") version = server_info.get("version") logger.bind(tag=TAG).info( - f"客户端MCP服务器信息: name={name}, version={version}" + f"Client MCP server info: name={name}, version={version}" ) return elif msg_id == 2: # mcpToolsListID - logger.bind(tag=TAG).debug("收到MCP工具列表响应") + logger.bind(tag=TAG).debug("Received MCP tools list response") if isinstance(result, dict) and "tools" in result: tools_data = result["tools"] if not isinstance(tools_data, list): - logger.bind(tag=TAG).error("工具列表格式错误") + logger.bind(tag=TAG).error("Tools list format error") return logger.bind(tag=TAG).info( - f"客户端设备支持的工具数量: {len(tools_data)}" + f"Client device supported tools count: {len(tools_data)}" ) for i, tool in enumerate(tools_data): @@ -161,12 +78,14 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): name = tool.get("name", "") description = tool.get("description", "") - input_schema = {"type": "object", "properties": {}, "required": []} + input_schema = {"type": "object", + "properties": {}, "required": []} if "inputSchema" in tool and isinstance(tool["inputSchema"], dict): schema = tool["inputSchema"] input_schema["type"] = schema.get("type", "object") - input_schema["properties"] = schema.get("properties", {}) + input_schema["properties"] = schema.get( + "properties", {}) input_schema["required"] = [ s for s in schema.get("required", []) if isinstance(s, str) ] @@ -176,14 +95,15 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): "description": description, "inputSchema": input_schema, } - await mcp_client.add_tool(new_tool) - logger.bind(tag=TAG).debug(f"客户端工具 #{i+1}: {name}") - # 替换所有工具描述中的工具名称 + await mcp_client.add_tool(new_tool) + logger.bind(tag=TAG).debug(f"Client tool #{i+1}: {name}") + + # Replace all tool names in tool descriptions for tool_data in mcp_client.tools.values(): if "description" in tool_data: description = tool_data["description"] - # 遍历所有工具名称进行替换 + # Iterate through all tool names for replacement for ( sanitized_name, original_name, @@ -195,13 +115,15 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): next_cursor = result.get("nextCursor", "") if next_cursor: - logger.bind(tag=TAG).info(f"有更多工具,nextCursor: {next_cursor}") + logger.bind(tag=TAG).info( + f"More tools available, nextCursor: {next_cursor}") await send_mcp_tools_list_continue_request(conn, next_cursor) else: await mcp_client.set_ready(True) - logger.bind(tag=TAG).info("所有工具已获取,MCP客户端准备就绪") + logger.bind(tag=TAG).info( + "All tools retrieved, MCP client ready") - # 刷新工具缓存,确保MCP工具被包含在函数列表中 + # Refresh tool cache to ensure MCP tools are included in function list if hasattr(conn, "func_handler") and conn.func_handler: conn.func_handler.tool_manager.refresh_tools() conn.func_handler.current_support_functions() @@ -210,26 +132,24 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): # Handle method calls (requests from the client) elif "method" in payload: method = payload["method"] - logger.bind(tag=TAG).info(f"收到MCP客户端请求: {method}") + logger.bind(tag=TAG).info(f"Received MCP client request: {method}") elif "error" in payload: error_data = payload["error"] - error_msg = error_data.get("message", "未知错误") - logger.bind(tag=TAG).error(f"收到MCP错误响应: {error_msg}") + error_msg = error_data.get("message", "Unknown error") + logger.bind(tag=TAG).error(f"Received MCP error response: {error_msg}") msg_id = int(payload.get("id", 0)) if msg_id in mcp_client.call_results: await mcp_client.reject_call_result( - msg_id, Exception(f"MCP错误: {error_msg}") + msg_id, Exception(f"MCP error: {error_msg}") ) async def send_mcp_initialize_message(conn): - """发送MCP初始化消息""" - + """Send MCP initialization message""" vision_url = get_vision_url(conn.config) - - # 密钥生成token + # Generate token using key auth = AuthToken(conn.config["server"]["auth_key"]) token = auth.generate_token(conn.headers.get("device-id")) @@ -255,66 +175,68 @@ async def send_mcp_initialize_message(conn): }, }, } - logger.bind(tag=TAG).info("发送MCP初始化消息") + + logger.bind(tag=TAG).info("Sending MCP initialization message") await send_mcp_message(conn, payload) async def send_mcp_tools_list_request(conn): - """发送MCP工具列表请求""" + """Send MCP tools list request""" payload = { "jsonrpc": "2.0", "id": 2, # mcpToolsListID "method": "tools/list", } - logger.bind(tag=TAG).debug("发送MCP工具列表请求") + + logger.bind(tag=TAG).debug("Sending MCP tools list request") await send_mcp_message(conn, payload) async def send_mcp_tools_list_continue_request(conn, cursor: str): - """发送带有cursor的MCP工具列表请求""" + """Send MCP tools list request with cursor""" payload = { "jsonrpc": "2.0", "id": 2, # mcpToolsListID (same ID for continuation) "method": "tools/list", "params": {"cursor": cursor}, } - logger.bind(tag=TAG).info(f"发送带cursor的MCP工具列表请求: {cursor}") + + logger.bind(tag=TAG).info( + f"Sending MCP tools list request with cursor: {cursor}") await send_mcp_message(conn, payload) async def call_mcp_tool( - conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30 + conn, mcp_client, tool_name: str, args: str = "{}", timeout: int = 30 ): - """ - 调用指定的工具,并等待响应 - """ + """Call the specified tool and wait for response""" if not await mcp_client.is_ready(): - raise RuntimeError("MCP客户端尚未准备就绪") + raise RuntimeError("MCP client is not ready yet") if not mcp_client.has_tool(tool_name): - raise ValueError(f"工具 {tool_name} 不存在") + raise ValueError(f"Tool {tool_name} does not exist") tool_call_id = await mcp_client.get_next_id() result_future = asyncio.Future() await mcp_client.register_call_result_future(tool_call_id, result_future) - # 处理参数 + # Handle parameters try: if isinstance(args, str): - # 确保字符串是有效的JSON + # Ensure string is valid JSON if not args.strip(): arguments = {} else: try: - # 尝试直接解析 + # Try to parse directly arguments = json.loads(args) except json.JSONDecodeError: - # 如果解析失败,尝试合并多个JSON对象 + # If parsing fails, try to merge multiple JSON objects try: - # 使用正则表达式匹配所有JSON对象 + # Use regex to match all JSON objects json_objects = re.findall(r"\{[^{}]*\}", args) if len(json_objects) > 1: - # 合并所有JSON对象 + # Merge all JSON objects merged_dict = {} for json_str in json_objects: try: @@ -326,29 +248,35 @@ async def call_mcp_tool( if merged_dict: arguments = merged_dict else: - raise ValueError(f"无法解析任何有效的JSON对象: {args}") + raise ValueError( + f"Cannot parse any valid JSON objects: {args}") else: - raise ValueError(f"参数JSON解析失败: {args}") + raise ValueError( + f"Parameter JSON parsing failed: {args}") except Exception as e: logger.bind(tag=TAG).error( - f"参数JSON解析失败: {str(e)}, 原始参数: {args}" + f"Parameter JSON parsing failed: {str(e)}, Original parameters: {args}" ) - raise ValueError(f"参数JSON解析失败: {str(e)}") + raise ValueError( + f"Parameter JSON parsing failed: {str(e)}") elif isinstance(args, dict): arguments = args else: - raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}") + raise ValueError( + f"Parameter type error, expected string or dictionary, actual type: {type(args)}") - # 确保参数是字典类型 + # Ensure parameters are dictionary type if not isinstance(arguments, dict): - raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}") + raise ValueError( + f"Parameters must be dictionary type, actual type: {type(arguments)}") except Exception as e: if not isinstance(e, ValueError): - raise ValueError(f"参数处理失败: {str(e)}") + raise ValueError(f"Parameter processing failed: {str(e)}") raise e actual_name = mcp_client.name_mapping.get(tool_name, tool_name) + payload = { "jsonrpc": "2.0", "id": tool_call_id, @@ -356,33 +284,36 @@ async def call_mcp_tool( "params": {"name": actual_name, "arguments": arguments}, } - logger.bind(tag=TAG).info(f"发送客户端mcp工具调用请求: {actual_name},参数: {args}") + logger.bind(tag=TAG).info( + f"Sending client MCP tool call request: {actual_name}, Parameters: {args}") await send_mcp_message(conn, payload) try: # Wait for response or timeout raw_result = await asyncio.wait_for(result_future, timeout=timeout) logger.bind(tag=TAG).info( - f"客户端mcp工具调用 {actual_name} 成功,原始结果: {raw_result}" + f"Client MCP tool call {actual_name} successful, Raw result: {raw_result}" ) if isinstance(raw_result, dict): if raw_result.get("isError") is True: error_msg = raw_result.get( - "error", "工具调用返回错误,但未提供具体错误信息" + "error", "Tool call returned error but did not provide specific error information" ) - raise RuntimeError(f"工具调用错误: {error_msg}") + raise RuntimeError(f"Tool call error: {error_msg}") content = raw_result.get("content") if isinstance(content, list) and len(content) > 0: if isinstance(content[0], dict) and "text" in content[0]: - # 直接返回文本内容,不进行JSON解析 + # Return text content directly without JSON parsing return content[0]["text"] - # 如果结果不是预期的格式,将其转换为字符串 + + # If result is not in expected format, convert to string return str(raw_result) + except asyncio.TimeoutError: await mcp_client.cleanup_call_result(tool_call_id) - raise TimeoutError("工具调用请求超时") + raise TimeoutError("Tool call request timeout") except Exception as e: await mcp_client.cleanup_call_result(tool_call_id) raise e diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/__init__.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/__init__.py index de2d9b1cf..b5bb8d9c0 100644 --- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/__init__.py +++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/__init__.py @@ -1,7 +1,9 @@ -"""MCP接入点工具模块""" +"""MCP endpoint tool module""" from .mcp_endpoint_executor import MCPEndpointExecutor + from .mcp_endpoint_client import MCPEndpointClient + from .mcp_endpoint_handler import ( connect_mcp_endpoint, send_mcp_endpoint_initialize, diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py index 4e9e5303f..e237170d4 100644 --- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py +++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py @@ -1,4 +1,4 @@ -"""MCP接入点客户端定义""" +"""MCP endpoint client definition""" import asyncio from concurrent.futures import Future @@ -8,10 +8,9 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() - class MCPEndpointClient: - """MCP接入点客户端,用于管理MCP接入点状态和工具""" - + """MCP endpoint client for managing MCP endpoint state and tools""" + def __init__(self, conn=None): self.conn = conn self.tools = {} # sanitized_name -> tool_data @@ -21,7 +20,7 @@ class MCPEndpointClient: self.next_id = 1 self.lock = asyncio.Lock() self._cached_available_tools = None # Cache for get_available_tools - self.websocket = None # WebSocket连接 + self.websocket = None # WebSocket connection def has_tool(self, name: str) -> bool: return name in self.tools @@ -30,7 +29,7 @@ class MCPEndpointClient: # Check if the cache is valid if self._cached_available_tools is not None: return self._cached_available_tools - + # If cache is not valid, regenerate the list result = [] for tool_name, tool_data in self.tools.items(): @@ -44,7 +43,7 @@ class MCPEndpointClient: }, } result.append({"type": "function", "function": function_def}) - + self._cached_available_tools = result # Store the generated list in cache return result @@ -61,9 +60,7 @@ class MCPEndpointClient: sanitized_name = sanitize_tool_name(tool_data["name"]) self.tools[sanitized_name] = tool_data self.name_mapping[sanitized_name] = tool_data["name"] - self._cached_available_tools = ( - None # Invalidate the cache when a tool is added - ) + self._cached_available_tools = None # Invalidate the cache when a tool is added async def get_next_id(self) -> int: async with self.lock: @@ -95,18 +92,18 @@ class MCPEndpointClient: self.call_results.pop(id) def set_websocket(self, websocket): - """设置WebSocket连接""" + """Set WebSocket connection""" self.websocket = websocket async def send_message(self, message: str): - """发送消息到MCP接入点""" + """Send message to MCP endpoint""" if self.websocket: await self.websocket.send(message) else: - raise RuntimeError("WebSocket连接未建立") + raise RuntimeError("WebSocket connection not established") async def close(self): - """关闭WebSocket连接""" + """Close WebSocket connection""" if self.websocket: await self.websocket.close() - self.websocket = None + self.websocket = None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py index f2c9bac15..d919a7f7a 100644 --- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py +++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py @@ -1,4 +1,4 @@ -"""MCP接入点工具执行器""" +"""MCP endpoint tool executor""" from typing import Dict, Any from ..base import ToolType, ToolDefinition, ToolExecutor @@ -7,7 +7,7 @@ from .mcp_endpoint_handler import call_mcp_endpoint_tool class MCPEndpointExecutor(ToolExecutor): - """MCP接入点工具执行器""" + """MCP endpoint tool executor""" def __init__(self, conn): self.conn = conn @@ -15,26 +15,25 @@ class MCPEndpointExecutor(ToolExecutor): async def execute( self, conn, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行MCP接入点工具""" + """Execute MCP endpoint tool""" if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client: return ActionResponse( action=Action.ERROR, - response="MCP接入点客户端未初始化", + response="MCP endpoint client not initialized", ) if not await conn.mcp_endpoint_client.is_ready(): return ActionResponse( action=Action.ERROR, - response="MCP接入点客户端未准备就绪", + response="MCP endpoint client not ready", ) try: - # 转换参数为JSON字符串 + # Convert parameters to JSON string import json - args_str = json.dumps(arguments) if arguments else "{}" - # 调用MCP接入点工具 + # Call MCP endpoint tool result = await call_mcp_endpoint_tool( conn.mcp_endpoint_client, tool_name, args_str ) @@ -46,7 +45,7 @@ class MCPEndpointExecutor(ToolExecutor): except Exception as e: pass - # 视觉大模型不经过二次LLM处理 + # Vision models do not go through secondary LLM processing if ( resultJson is not None and isinstance(resultJson, dict) @@ -65,7 +64,7 @@ class MCPEndpointExecutor(ToolExecutor): return ActionResponse(action=Action.ERROR, response=str(e)) def get_tools(self) -> Dict[str, ToolDefinition]: - """获取所有MCP接入点工具""" + """Get all MCP endpoint tools""" if ( not hasattr(self.conn, "mcp_endpoint_client") or not self.conn.mcp_endpoint_client @@ -78,7 +77,6 @@ class MCPEndpointExecutor(ToolExecutor): for tool in mcp_tools: func_def = tool.get("function", {}) tool_name = func_def.get("name", "") - if tool_name: tools[tool_name] = ToolDefinition( name=tool_name, description=tool, tool_type=ToolType.MCP_ENDPOINT @@ -87,11 +85,10 @@ class MCPEndpointExecutor(ToolExecutor): return tools def has_tool(self, tool_name: str) -> bool: - """检查是否有指定的MCP接入点工具""" + """Check if the specified MCP endpoint tool exists""" if ( not hasattr(self.conn, "mcp_endpoint_client") or not self.conn.mcp_endpoint_client ): return False - - return self.conn.mcp_endpoint_client.has_tool(tool_name) + return self.conn.mcp_endpoint_client.has_tool(tool_name) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py index c6afb07ba..ccb5bfb7c 100644 --- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py +++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py @@ -1,4 +1,4 @@ -"""MCP接入点处理器""" +"""MCP endpoint handler""" import json import asyncio @@ -12,92 +12,93 @@ logger = setup_logging() async def connect_mcp_endpoint(mcp_endpoint_url: str, conn=None) -> MCPEndpointClient: - """连接到MCP接入点""" + """Connect to MCP endpoint""" if not mcp_endpoint_url or "你的" in mcp_endpoint_url or mcp_endpoint_url == "null": return None try: websocket = await websockets.connect(mcp_endpoint_url) - mcp_client = MCPEndpointClient(conn) mcp_client.set_websocket(websocket) - # 启动消息监听器 + # Start message listener asyncio.create_task(_message_listener(mcp_client)) - # 发送初始化消息 + # Send initialization message await send_mcp_endpoint_initialize(mcp_client) - # 发送初始化完成通知 + # Send initialization complete notification await send_mcp_endpoint_notification(mcp_client, "notifications/initialized") - # 获取工具列表 + # Get tools list await send_mcp_endpoint_tools_list(mcp_client) - logger.bind(tag=TAG).info("MCP接入点连接成功") + logger.bind(tag=TAG).info("MCP endpoint connection successful") return mcp_client except Exception as e: - logger.bind(tag=TAG).error(f"连接MCP接入点失败: {e}") + logger.bind(tag=TAG).error(f"Failed to connect to MCP endpoint: {e}") return None async def _message_listener(mcp_client: MCPEndpointClient): - """监听MCP接入点消息""" + """Listen for MCP endpoint messages""" try: async for message in mcp_client.websocket: await handle_mcp_endpoint_message(mcp_client, message) except websockets.exceptions.ConnectionClosed: - logger.bind(tag=TAG).info("MCP接入点连接已关闭") + logger.bind(tag=TAG).info("MCP endpoint connection closed") except Exception as e: - logger.bind(tag=TAG).error(f"MCP接入点消息监听器错误: {e}") + logger.bind(tag=TAG).error(f"MCP endpoint message listener error: {e}") finally: await mcp_client.set_ready(False) async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: str): - """处理MCP接入点消息""" + """Handle MCP endpoint messages""" try: payload = json.loads(message) - logger.bind(tag=TAG).debug(f"收到MCP接入点消息: {payload}") + logger.bind(tag=TAG).debug(f"Received MCP endpoint message: {payload}") if not isinstance(payload, dict): - logger.bind(tag=TAG).error("MCP接入点消息格式错误") + logger.bind(tag=TAG).error("MCP endpoint message format error") return # Handle result if "result" in payload: result = payload["result"] - # 安全地获取消息ID,如果为None则使用0 + # Safely get message ID, use 0 if None msg_id_raw = payload.get("id") msg_id = int(msg_id_raw) if msg_id_raw is not None else 0 # Check for tool call response first if msg_id in mcp_client.call_results: logger.bind(tag=TAG).debug( - f"收到工具调用响应,ID: {msg_id}, 结果: {result}" + f"Received tool call response, ID: {msg_id}, Result: {result}" ) await mcp_client.resolve_call_result(msg_id, result) return if msg_id == 1: # mcpInitializeID - logger.bind(tag=TAG).debug("收到MCP接入点初始化响应") + logger.bind(tag=TAG).debug( + "Received MCP endpoint initialization response") if result is not None and isinstance(result, dict): server_info = result.get("serverInfo") if isinstance(server_info, dict): name = server_info.get("name") version = server_info.get("version") logger.bind(tag=TAG).info( - f"MCP接入点服务器信息: name={name}, version={version}" + f"MCP endpoint server info: name={name}, version={version}" ) else: logger.bind(tag=TAG).warning( - "MCP接入点初始化响应结果为空或格式错误" + "MCP endpoint initialization response result is empty or format error" ) return elif msg_id == 2: # mcpToolsListID - logger.bind(tag=TAG).debug("收到MCP接入点工具列表响应") + logger.bind(tag=TAG).debug( + "Received MCP endpoint tools list response") if ( result is not None and isinstance(result, dict) @@ -105,11 +106,11 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st ): tools_data = result["tools"] if not isinstance(tools_data, list): - logger.bind(tag=TAG).error("工具列表格式错误") + logger.bind(tag=TAG).error("Tools list format error") return logger.bind(tag=TAG).info( - f"MCP接入点支持的工具数量: {len(tools_data)}" + f"MCP endpoint supported tools count: {len(tools_data)}" ) for i, tool in enumerate(tools_data): @@ -129,7 +130,8 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st ): schema = tool["inputSchema"] input_schema["type"] = schema.get("type", "object") - input_schema["properties"] = schema.get("properties", {}) + input_schema["properties"] = schema.get( + "properties", {}) input_schema["required"] = [ s for s in schema.get("required", []) @@ -141,14 +143,16 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st "description": description, "inputSchema": input_schema, } - await mcp_client.add_tool(new_tool) - logger.bind(tag=TAG).debug(f"MCP接入点工具 #{i+1}: {name}") - # 替换所有工具描述中的工具名称 + await mcp_client.add_tool(new_tool) + logger.bind(tag=TAG).debug( + f"MCP endpoint tool #{i+1}: {name}") + + # Replace all tool names in tool descriptions for tool_data in mcp_client.tools.values(): if "description" in tool_data: description = tool_data["description"] - # 遍历所有工具名称进行替换 + # Iterate through all tool names for replacement for ( sanitized_name, original_name, @@ -159,11 +163,13 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st tool_data["description"] = description next_cursor = ( - result.get("nextCursor", "") if result is not None else "" + result.get( + "nextCursor", "") if result is not None else "" ) + if next_cursor: logger.bind(tag=TAG).info( - f"有更多工具,nextCursor: {next_cursor}" + f"More tools available, nextCursor: {next_cursor}" ) await send_mcp_endpoint_tools_list_continue( mcp_client, next_cursor @@ -171,10 +177,10 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st else: await mcp_client.set_ready(True) logger.bind(tag=TAG).info( - "所有MCP接入点工具已获取,客户端准备就绪" + "All MCP endpoint tools retrieved, client ready" ) - # 刷新工具缓存,确保MCP接入点工具被包含在函数列表中 + # Refresh tool cache to ensure MCP endpoint tools are included in function list if ( hasattr(mcp_client, "conn") and mcp_client.conn @@ -185,44 +191,46 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st mcp_client.conn.func_handler.current_support_functions() logger.bind(tag=TAG).info( - f"MCP接入点工具获取完成,共 {len(mcp_client.tools)} 个工具" + f"MCP endpoint tools retrieval completed, total {len(mcp_client.tools)} tools" ) else: logger.bind(tag=TAG).warning( - "MCP接入点工具列表响应结果为空或格式错误" + "MCP endpoint tools list response result is empty or format error" ) return # Handle method calls (requests from the endpoint) elif "method" in payload: method = payload["method"] - logger.bind(tag=TAG).info(f"收到MCP接入点请求: {method}") + logger.bind(tag=TAG).info( + f"Received MCP endpoint request: {method}") elif "error" in payload: error_data = payload["error"] - error_msg = error_data.get("message", "未知错误") - logger.bind(tag=TAG).error(f"收到MCP接入点错误响应: {error_msg}") + error_msg = error_data.get("message", "Unknown error") + logger.bind(tag=TAG).error( + f"Received MCP endpoint error response: {error_msg}") - # 安全地获取消息ID,如果为None则使用0 + # Safely get message ID, use 0 if None msg_id_raw = payload.get("id") msg_id = int(msg_id_raw) if msg_id_raw is not None else 0 if msg_id in mcp_client.call_results: await mcp_client.reject_call_result( - msg_id, Exception(f"MCP接入点错误: {error_msg}") + msg_id, Exception(f"MCP endpoint error: {error_msg}") ) except json.JSONDecodeError as e: - logger.bind(tag=TAG).error(f"MCP接入点消息JSON解析失败: {e}") + logger.bind(tag=TAG).error( + f"MCP endpoint message JSON parsing failed: {e}") except Exception as e: - logger.bind(tag=TAG).error(f"处理MCP接入点消息时出错: {e}") + logger.bind(tag=TAG).error(f"Error handling MCP endpoint message: {e}") import traceback - - logger.bind(tag=TAG).error(f"错误详情: {traceback.format_exc()}") + logger.bind(tag=TAG).error(f"Error details: {traceback.format_exc()}") async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient): - """发送MCP接入点初始化消息""" + """Send MCP endpoint initialization message""" payload = { "jsonrpc": "2.0", "id": 1, # mcpInitializeID @@ -239,47 +247,52 @@ async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient): }, }, } + message = json.dumps(payload) - logger.bind(tag=TAG).info("发送MCP接入点初始化消息") + logger.bind(tag=TAG).info("Sending MCP endpoint initialization message") await mcp_client.send_message(message) async def send_mcp_endpoint_notification(mcp_client: MCPEndpointClient, method: str): - """发送MCP接入点通知消息""" + """Send MCP endpoint notification message""" payload = { "jsonrpc": "2.0", "method": method, "params": {}, } + message = json.dumps(payload) - logger.bind(tag=TAG).debug(f"发送MCP接入点通知: {method}") + logger.bind(tag=TAG).debug(f"Sending MCP endpoint notification: {method}") await mcp_client.send_message(message) async def send_mcp_endpoint_tools_list(mcp_client: MCPEndpointClient): - """发送MCP接入点工具列表请求""" + """Send MCP endpoint tools list request""" payload = { "jsonrpc": "2.0", "id": 2, # mcpToolsListID "method": "tools/list", } + message = json.dumps(payload) - logger.bind(tag=TAG).debug("发送MCP接入点工具列表请求") + logger.bind(tag=TAG).debug("Sending MCP endpoint tools list request") await mcp_client.send_message(message) async def send_mcp_endpoint_tools_list_continue( mcp_client: MCPEndpointClient, cursor: str ): - """发送带有cursor的MCP接入点工具列表请求""" + """Send MCP endpoint tools list request with cursor""" payload = { "jsonrpc": "2.0", "id": 2, # mcpToolsListID (same ID for continuation) "method": "tools/list", "params": {"cursor": cursor}, } + message = json.dumps(payload) - logger.bind(tag=TAG).info(f"发送带cursor的MCP接入点工具列表请求: {cursor}") + logger.bind(tag=TAG).info( + f"Sending MCP endpoint tools list request with cursor: {cursor}") await mcp_client.send_message(message) @@ -287,35 +300,35 @@ async def call_mcp_endpoint_tool( mcp_client: MCPEndpointClient, tool_name: str, args: str = "{}", timeout: int = 30 ): """ - 调用指定的MCP接入点工具,并等待响应 + Call the specified MCP endpoint tool and wait for response """ if not await mcp_client.is_ready(): - raise RuntimeError("MCP接入点客户端尚未准备就绪") + raise RuntimeError("MCP endpoint client not ready yet") if not mcp_client.has_tool(tool_name): - raise ValueError(f"工具 {tool_name} 不存在") + raise ValueError(f"Tool {tool_name} does not exist") tool_call_id = await mcp_client.get_next_id() result_future = asyncio.Future() await mcp_client.register_call_result_future(tool_call_id, result_future) - # 处理参数 + # Handle parameters try: if isinstance(args, str): - # 确保字符串是有效的JSON + # Ensure string is valid JSON if not args.strip(): arguments = {} else: try: - # 尝试直接解析 + # Try to parse directly arguments = json.loads(args) except json.JSONDecodeError: - # 如果解析失败,尝试合并多个JSON对象 + # If parsing fails, try to merge multiple JSON objects try: - # 使用正则表达式匹配所有JSON对象 + # Use regex to match all JSON objects json_objects = re.findall(r"\{[^{}]*\}", args) if len(json_objects) > 1: - # 合并所有JSON对象 + # Merge all JSON objects merged_dict = {} for json_str in json_objects: try: @@ -327,29 +340,35 @@ async def call_mcp_endpoint_tool( if merged_dict: arguments = merged_dict else: - raise ValueError(f"无法解析任何有效的JSON对象: {args}") + raise ValueError( + f"Cannot parse any valid JSON objects: {args}") else: - raise ValueError(f"参数JSON解析失败: {args}") + raise ValueError( + f"Parameter JSON parsing failed: {args}") except Exception as e: logger.bind(tag=TAG).error( - f"参数JSON解析失败: {str(e)}, 原始参数: {args}" + f"Parameter JSON parsing failed: {str(e)}, Original parameters: {args}" ) - raise ValueError(f"参数JSON解析失败: {str(e)}") + raise ValueError( + f"Parameter JSON parsing failed: {str(e)}") elif isinstance(args, dict): arguments = args else: - raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}") + raise ValueError( + f"Parameter type error, expected string or dictionary, actual type: {type(args)}") - # 确保参数是字典类型 + # Ensure parameters are dictionary type if not isinstance(arguments, dict): - raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}") + raise ValueError( + f"Parameters must be dictionary type, actual type: {type(arguments)}") except Exception as e: if not isinstance(e, ValueError): - raise ValueError(f"参数处理失败: {str(e)}") + raise ValueError(f"Parameter processing failed: {str(e)}") raise e actual_name = mcp_client.name_mapping.get(tool_name, tool_name) + payload = { "jsonrpc": "2.0", "id": tool_call_id, @@ -358,33 +377,36 @@ async def call_mcp_endpoint_tool( } message = json.dumps(payload) - logger.bind(tag=TAG).info(f"发送MCP接入点工具调用请求: {actual_name},参数: {args}") + logger.bind(tag=TAG).info( + f"Sending MCP endpoint tool call request: {actual_name}, Parameters: {args}") await mcp_client.send_message(message) try: # Wait for response or timeout raw_result = await asyncio.wait_for(result_future, timeout=timeout) logger.bind(tag=TAG).info( - f"MCP接入点工具调用 {actual_name} 成功,原始结果: {raw_result}" + f"MCP endpoint tool call {actual_name} successful, Raw result: {raw_result}" ) if isinstance(raw_result, dict): if raw_result.get("isError") is True: error_msg = raw_result.get( - "error", "工具调用返回错误,但未提供具体错误信息" + "error", "Tool call returned error but did not provide specific error information" ) - raise RuntimeError(f"工具调用错误: {error_msg}") + raise RuntimeError(f"Tool call error: {error_msg}") content = raw_result.get("content") if isinstance(content, list) and len(content) > 0: if isinstance(content[0], dict) and "text" in content[0]: - # 直接返回文本内容,不进行JSON解析 + # Return text content directly without JSON parsing return content[0]["text"] - # 如果结果不是预期的格式,将其转换为字符串 + + # If result is not in expected format, convert to string return str(raw_result) + except asyncio.TimeoutError: await mcp_client.cleanup_call_result(tool_call_id) - raise TimeoutError("工具调用请求超时") + raise TimeoutError("Tool call request timeout") except Exception as e: await mcp_client.cleanup_call_result(tool_call_id) raise e diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/__init__.py b/main/xiaozhi-server/core/providers/tools/server_mcp/__init__.py index aecd80b8b..adc287192 100644 --- a/main/xiaozhi-server/core/providers/tools/server_mcp/__init__.py +++ b/main/xiaozhi-server/core/providers/tools/server_mcp/__init__.py @@ -1,4 +1,4 @@ -"""服务端MCP工具模块""" +"""Server-side MCP tool module""" from .mcp_manager import ServerMCPManager from .mcp_executor import ServerMCPExecutor diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py index 8b60ac1b4..0a7974f1f 100644 --- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py +++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py @@ -1,7 +1,6 @@ -"""服务端MCP客户端""" +"""Server-side MCP client""" from __future__ import annotations - from datetime import timedelta import asyncio import os @@ -9,7 +8,6 @@ import shutil import concurrent.futures from contextlib import AsyncExitStack from typing import Optional, List, Dict, Any - from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.client.sse import sse_client @@ -20,42 +18,40 @@ TAG = __name__ class ServerMCPClient: - """服务端MCP客户端,用于连接和管理MCP服务""" + """Server-side MCP client for connecting and managing MCP services""" def __init__(self, config: Dict[str, Any]): - """初始化服务端MCP客户端 + """Initialize server-side MCP client Args: - config: MCP服务配置字典 + config: MCP service configuration dictionary """ self.logger = setup_logging() self.config = config - self._worker_task: Optional[asyncio.Task] = None self._ready_evt = asyncio.Event() self._shutdown_evt = asyncio.Event() - self.session: Optional[ClientSession] = None - self.tools: List = [] # 原始工具对象 + self.tools: List = [] # Original tool objects self.tools_dict: Dict[str, Any] = {} self.name_mapping: Dict[str, str] = {} async def initialize(self): - """初始化MCP客户端连接""" + """Initialize MCP client connection""" if self._worker_task: return self._worker_task = asyncio.create_task( self._worker(), name="ServerMCPClientWorker" ) - await self._ready_evt.wait() + await self._ready_evt.wait() self.logger.bind(tag=TAG).info( - f"服务端MCP客户端已连接,可用工具: {[name for name in self.name_mapping.values()]}" + f"Server-side MCP client connected, available tools: {[name for name in self.name_mapping.values()]}" ) async def cleanup(self): - """清理MCP客户端资源""" + """Clean up MCP client resources""" if not self._worker_task: return @@ -63,26 +59,27 @@ class ServerMCPClient: try: await asyncio.wait_for(self._worker_task, timeout=20) except (asyncio.TimeoutError, Exception) as e: - self.logger.bind(tag=TAG).error(f"服务端MCP客户端关闭错误: {e}") + self.logger.bind(tag=TAG).error( + f"Server-side MCP client shutdown error: {e}") finally: self._worker_task = None def has_tool(self, name: str) -> bool: - """检查是否包含指定工具 + """Check if the specified tool is included Args: - name: 工具名称 + name: Tool name Returns: - bool: 是否包含该工具 + bool: Whether the tool is included """ return name in self.tools_dict def get_available_tools(self) -> List[Dict[str, Any]]: - """获取所有可用工具的定义 + """Get definitions of all available tools Returns: - List[Dict[str, Any]]: 工具定义列表 + List[Dict[str, Any]]: Tool definition list """ return [ { @@ -97,20 +94,20 @@ class ServerMCPClient: ] async def call_tool(self, name: str, args: dict) -> Any: - """调用指定工具 + """Call the specified tool Args: - name: 工具名称 - args: 工具参数 + name: Tool name + args: Tool parameters Returns: - Any: 工具执行结果 + Any: Tool execution result Raises: - RuntimeError: 客户端未初始化时抛出 + RuntimeError: Thrown when client is not initialized """ if not self.session: - raise RuntimeError("服务端MCP客户端未初始化") + raise RuntimeError("Server-side MCP client not initialized") real_name = self.name_mapping.get(name, name) loop = self._worker_task.get_loop() @@ -119,35 +116,36 @@ class ServerMCPClient: if loop is asyncio.get_running_loop(): return await coro - fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop) + fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe( + coro, loop) return await asyncio.wrap_future(fut) def is_connected(self) -> bool: - """检查MCP客户端是否连接正常 + """Check if MCP client is connected normally Returns: - bool: 如果客户端已连接并正常工作,返回True,否则返回False + bool: Returns True if client is connected and working normally, otherwise False """ - # 检查工作任务是否存在 + # Check if worker task exists if self._worker_task is None: return False - # 检查工作任务是否已经完成或取消 + # Check if worker task is completed or cancelled if self._worker_task.done(): return False - # 检查会话是否存在 + # Check if session exists if self.session is None: return False - # 所有检查都通过,连接正常 + # All checks passed, connection is normal return True async def _worker(self): - """MCP客户端工作协程""" + """MCP client worker coroutine""" async with AsyncExitStack() as stack: try: - # 建立 StdioClient + # Establish StdioClient if "command" in self.config: cmd = ( shutil.which("npx") @@ -165,7 +163,7 @@ class ServerMCPClient: ) read_stream, write_stream = stdio_r, stdio_w - # 建立SSEClient + # Establish SSEClient elif "url" in self.config: if "API_ACCESS_TOKEN" in self.config: headers = { @@ -173,13 +171,15 @@ class ServerMCPClient: } else: headers = {} + sse_r, sse_w = await stack.enter_async_context( sse_client(self.config["url"], headers=headers) ) read_stream, write_stream = sse_r, sse_w else: - raise ValueError("MCP客户端配置必须包含'command'或'url'") + raise ValueError( + "MCP client configuration must contain 'command' or 'url'") self.session = await stack.enter_async_context( ClientSession( @@ -188,10 +188,12 @@ class ServerMCPClient: read_timeout_seconds=timedelta(seconds=15), ) ) + await self.session.initialize() - # 获取工具 + # Get tools self.tools = (await self.session.list_tools()).tools + for t in self.tools: sanitized = sanitize_tool_name(t.name) self.tools_dict[sanitized] = t @@ -199,10 +201,11 @@ class ServerMCPClient: self._ready_evt.set() - # 挂起等待关闭 + # Suspend and wait for shutdown await self._shutdown_evt.wait() except Exception as e: - self.logger.bind(tag=TAG).error(f"服务端MCP客户端工作协程错误: {e}") + self.logger.bind(tag=TAG).error( + f"Server-side MCP client worker coroutine error: {e}") self._ready_evt.set() raise diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py index 9ae15d4bf..489aea378 100644 --- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py @@ -1,13 +1,15 @@ -"""服务端MCP工具执行器""" +"""Server-side MCP tool executor""" from typing import Dict, Any, Optional + from ..base import ToolType, ToolDefinition, ToolExecutor + from plugins_func.register import Action, ActionResponse + from .mcp_manager import ServerMCPManager - class ServerMCPExecutor(ToolExecutor): - """服务端MCP工具执行器""" + """Server-side MCP tool executor""" def __init__(self, conn): self.conn = conn @@ -15,7 +17,7 @@ class ServerMCPExecutor(ToolExecutor): self._initialized = False async def initialize(self): - """初始化MCP管理器""" + """Initialize MCP manager""" if not self._initialized: self.mcp_manager = ServerMCPManager(self.conn) await self.mcp_manager.initialize_servers() @@ -24,21 +26,20 @@ class ServerMCPExecutor(ToolExecutor): async def execute( self, conn, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行服务端MCP工具""" + """Execute server-side MCP tool""" if not self._initialized or not self.mcp_manager: return ActionResponse( action=Action.ERROR, - response="MCP管理器未初始化", + response="MCP manager not initialized", ) try: - # 移除mcp_前缀(如果有) + # Remove mcp_ prefix (if present) actual_tool_name = tool_name if tool_name.startswith("mcp_"): actual_tool_name = tool_name[4:] result = await self.mcp_manager.execute_tool(actual_tool_name, arguments) - return ActionResponse(action=Action.REQLLM, result=str(result)) except ValueError as e: @@ -53,7 +54,7 @@ class ServerMCPExecutor(ToolExecutor): ) def get_tools(self) -> Dict[str, ToolDefinition]: - """获取所有服务端MCP工具""" + """Get all server-side MCP tools""" if not self._initialized or not self.mcp_manager: return {} @@ -65,6 +66,7 @@ class ServerMCPExecutor(ToolExecutor): tool_name = func_def.get("name", "") if tool_name == "": continue + tools[tool_name] = ToolDefinition( name=tool_name, description=tool, tool_type=ToolType.SERVER_MCP ) @@ -72,11 +74,11 @@ class ServerMCPExecutor(ToolExecutor): return tools def has_tool(self, tool_name: str) -> bool: - """检查是否有指定的服务端MCP工具""" + """Check if the specified server-side MCP tool exists""" if not self._initialized or not self.mcp_manager: return False - # 移除mcp_前缀(如果有) + # Remove mcp_ prefix (if present) actual_tool_name = tool_name if tool_name.startswith("mcp_"): actual_tool_name = tool_name[4:] @@ -84,6 +86,6 @@ class ServerMCPExecutor(ToolExecutor): return self.mcp_manager.is_mcp_tool(actual_tool_name) async def cleanup(self): - """清理MCP连接""" + """Clean up MCP connections""" if self.mcp_manager: - await self.mcp_manager.cleanup_all() + await self.mcp_manager.cleanup_all() \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py index 52ab2b790..d1abe540a 100644 --- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py +++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py @@ -1,34 +1,43 @@ -"""服务端MCP管理器""" +"""Server-side MCP manager""" import asyncio + import os + import json + from typing import Dict, Any, List + from config.config_loader import get_project_dir + from config.logger import setup_logging + from .mcp_client import ServerMCPClient TAG = __name__ + logger = setup_logging() class ServerMCPManager: - """管理多个服务端MCP服务的集中管理器""" + """Centralized manager for managing multiple server-side MCP services""" def __init__(self, conn) -> None: - """初始化MCP管理器""" + """Initialize MCP manager""" self.conn = conn self.config_path = get_project_dir() + "data/.mcp_server_settings.json" + if not os.path.exists(self.config_path): self.config_path = "" logger.bind(tag=TAG).warning( - f"请检查mcp服务配置文件:data/.mcp_server_settings.json" + f"Please check the MCP service configuration file: data/.mcp_server_settings.json" ) + self.clients: Dict[str, ServerMCPClient] = {} self.tools = [] def load_config(self) -> Dict[str, Any]: - """加载MCP服务配置""" + """Load MCP service configuration""" if len(self.config_path) == 0: return {} @@ -43,8 +52,9 @@ class ServerMCPManager: return {} async def initialize_servers(self) -> None: - """初始化所有MCP服务""" + """Initialize all MCP services""" config = self.load_config() + for name, srv_config in config.items(): if not srv_config.get("command") and not srv_config.get("url"): logger.bind(tag=TAG).warning( @@ -53,11 +63,13 @@ class ServerMCPManager: continue try: - # 初始化服务端MCP客户端 - logger.bind(tag=TAG).info(f"初始化服务端MCP客户端: {name}") + # Initialize server-side MCP client + logger.bind(tag=TAG).info( + f"Initializing server-side MCP client: {name}") client = ServerMCPClient(srv_config) await client.initialize() self.clients[name] = client + client_tools = client.get_available_tools() self.tools.extend(client_tools) @@ -66,16 +78,16 @@ class ServerMCPManager: f"Failed to initialize MCP server {name}: {e}" ) - # 输出当前支持的服务端MCP工具列表 + # Output current supported server-side MCP tools list if hasattr(self.conn, "func_handler") and self.conn.func_handler: self.conn.func_handler.current_support_functions() def get_all_tools(self) -> List[Dict[str, Any]]: - """获取所有服务的工具function定义""" + """Get function definitions for all service tools""" return self.tools def is_mcp_tool(self, tool_name: str) -> bool: - """检查是否是MCP工具""" + """Check if it's an MCP tool""" for tool in self.tools: if ( tool.get("function") is not None @@ -85,15 +97,17 @@ class ServerMCPManager: return False async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any: - """执行工具调用,失败时会尝试重新连接""" - logger.bind(tag=TAG).info(f"执行服务端MCP工具 {tool_name},参数: {arguments}") + """Execute tool call, will attempt to reconnect on failure""" + logger.bind(tag=TAG).info( + f"Executing server-side MCP tool {tool_name}, parameters: {arguments}") - max_retries = 3 # 最大重试次数 - retry_interval = 2 # 重试间隔(秒) + max_retries = 3 # Maximum retry attempts + retry_interval = 2 # Retry interval (seconds) - # 找到对应的客户端 + # Find the corresponding client client_name = None target_client = None + for name, client in self.clients.items(): if client.has_tool(tool_name): client_name = name @@ -101,38 +115,40 @@ class ServerMCPManager: break if not target_client: - raise ValueError(f"工具 {tool_name} 在任意MCP服务中未找到") + raise ValueError(f"Tool {tool_name} not found in any MCP service") - # 带重试机制的工具调用 + # Tool call with retry mechanism for attempt in range(max_retries): try: return await target_client.call_tool(tool_name, arguments) except Exception as e: - # 最后一次尝试失败时直接抛出异常 + # Throw exception directly on last attempt failure if attempt == max_retries - 1: raise logger.bind(tag=TAG).warning( - f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}" + f"Failed to execute tool {tool_name} (attempt {attempt+1}/{max_retries}): {e}" ) - # 尝试重新连接 + # Attempt to reconnect logger.bind(tag=TAG).info( - f"重试前尝试重新连接 MCP 客户端 {client_name}" + f"Attempting to reconnect MCP client {client_name} before retry" ) + try: - # 关闭旧的连接 + # Close old connection await target_client.cleanup() - # 重新初始化客户端 + # Reinitialize client config = self.load_config() if client_name in config: client = ServerMCPClient(config[client_name]) await client.initialize() self.clients[client_name] = client target_client = client + logger.bind(tag=TAG).info( - f"成功重新连接 MCP 客户端: {client_name}" + f"Successfully reconnected MCP client: {client_name}" ) else: logger.bind(tag=TAG).error( @@ -143,16 +159,19 @@ class ServerMCPManager: f"Failed to reconnect MCP client {client_name}: {reconnect_error}" ) - # 等待一段时间再重试 + # Wait for a while before retrying await asyncio.sleep(retry_interval) async def cleanup_all(self) -> None: - """关闭所有 MCP客户端""" + """Close all MCP clients""" for name, client in list(self.clients.items()): try: if hasattr(client, "cleanup"): await asyncio.wait_for(client.cleanup(), timeout=20) - logger.bind(tag=TAG).info(f"服务端MCP客户端已关闭: {name}") + logger.bind(tag=TAG).info( + f"Server-side MCP client closed: {name}") except (asyncio.TimeoutError, Exception) as e: - logger.bind(tag=TAG).error(f"关闭服务端MCP客户端 {name} 时出错: {e}") + logger.bind(tag=TAG).error( + f"Error closing server-side MCP client {name}: {e}") + self.clients.clear() diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/__init__.py b/main/xiaozhi-server/core/providers/tools/server_plugins/__init__.py index 232b50d24..bdff66f2f 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/__init__.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/__init__.py @@ -1,5 +1,5 @@ -"""服务端插件工具模块""" +"""Server-side plugin tool module""" from .plugin_executor import ServerPluginExecutor -__all__ = ["ServerPluginExecutor"] +__all__ = ["ServerPluginExecutor"] \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index fe613b0c1..6af5ae7a0 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -1,12 +1,14 @@ -"""服务端插件工具执行器""" +"""Server-side plugin tool executor""" from typing import Dict, Any + from ..base import ToolType, ToolDefinition, ToolExecutor + from plugins_func.register import all_function_registry, Action, ActionResponse class ServerPluginExecutor(ToolExecutor): - """服务端插件工具执行器""" + """Server-side plugin tool executor""" def __init__(self, conn): self.conn = conn @@ -15,18 +17,19 @@ class ServerPluginExecutor(ToolExecutor): async def execute( self, conn, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行服务端插件工具""" + """Execute server-side plugin tool""" func_item = all_function_registry.get(tool_name) if not func_item: return ActionResponse( - action=Action.NOTFOUND, response=f"插件函数 {tool_name} 不存在" + action=Action.NOTFOUND, response=f"Plugin function {tool_name} does not exist" ) try: - # 根据工具类型决定如何调用 + # Decide how to call based on tool type if hasattr(func_item, "type"): func_type = func_item.type - if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (需要conn参数) + # SYSTEM_CTL, IOT_CTL (requires conn parameter) + if func_type.code in [4, 5]: result = func_item.func(conn, **arguments) elif func_type.code == 2: # WAIT result = func_item.func(**arguments) @@ -35,7 +38,7 @@ class ServerPluginExecutor(ToolExecutor): else: result = func_item.func(**arguments) else: - # 默认不传conn参数 + # Default: don't pass conn parameter result = func_item.func(**arguments) return result @@ -47,26 +50,27 @@ class ServerPluginExecutor(ToolExecutor): ) def get_tools(self) -> Dict[str, ToolDefinition]: - """获取所有注册的服务端插件工具""" + """Get all registered server-side plugin tools""" tools = {} - # 获取必要的函数 - necessary_functions = ["handle_exit_intent", "get_lunar"] + # Get necessary functions + necessary_functions = ["handle_exit_intent", "get_time", "get_lunar"] - # 获取配置中的函数 + # Get functions from config config_functions = self.config["Intent"][ self.config["selected_module"]["Intent"] ].get("functions", []) - # 转换为列表 + # Convert to list if not isinstance(config_functions, list): try: config_functions = list(config_functions) except TypeError: config_functions = [] - # 合并所有需要的函数 - all_required_functions = list(set(necessary_functions + config_functions)) + # Merge all required functions + all_required_functions = list( + set(necessary_functions + config_functions)) for func_name in all_required_functions: func_item = all_function_registry.get(func_name) @@ -80,5 +84,5 @@ class ServerPluginExecutor(ToolExecutor): return tools def has_tool(self, tool_name: str) -> bool: - """检查是否有指定的服务端插件工具""" - return tool_name in all_function_registry \ No newline at end of file + """Check if the specified server-side plugin tool exists""" + return tool_name in all_function_registry diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py b/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py index b81029aca..ee5bdbde7 100644 --- a/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py +++ b/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py @@ -1,39 +1,49 @@ -"""统一工具处理器""" +"""Unified tool handler""" import json + from typing import Dict, List, Any, Optional + from config.logger import setup_logging + from plugins_func.loadplugins import auto_import_modules from .base import ToolType + from plugins_func.register import Action, ActionResponse + from .unified_tool_manager import ToolManager + from .server_plugins import ServerPluginExecutor + from .server_mcp import ServerMCPExecutor + from .device_iot import DeviceIoTExecutor + from .device_mcp import DeviceMCPExecutor + from .mcp_endpoint import MCPEndpointExecutor class UnifiedToolHandler: - """统一工具处理器""" + """Unified tool handler""" def __init__(self, conn): self.conn = conn self.config = conn.config self.logger = setup_logging() - # 创建工具管理器 + # Create tool manager self.tool_manager = ToolManager(conn) - # 创建各类执行器 + # Create various executors self.server_plugin_executor = ServerPluginExecutor(conn) self.server_mcp_executor = ServerMCPExecutor(conn) self.device_iot_executor = DeviceIoTExecutor(conn) self.device_mcp_executor = DeviceMCPExecutor(conn) self.mcp_endpoint_executor = MCPEndpointExecutor(conn) - # 注册执行器 + # Register executors self.tool_manager.register_executor( ToolType.SERVER_PLUGIN, self.server_plugin_executor ) @@ -50,39 +60,40 @@ class UnifiedToolHandler: ToolType.MCP_ENDPOINT, self.mcp_endpoint_executor ) - # 初始化标志 + # Initialization flag self.finish_init = False async def _initialize(self): - """异步初始化""" + """Asynchronous initialization""" try: - # 自动导入插件模块 + # Auto import plugin modules auto_import_modules("plugins_func.functions") - # 初始化服务端MCP + # Initialize server-side MCP await self.server_mcp_executor.initialize() - # 初始化MCP接入点 + # Initialize MCP endpoint await self._initialize_mcp_endpoint() - # 初始化Home Assistant(如果需要) + # Initialize Home Assistant (if needed) self._initialize_home_assistant() self.finish_init = True - self.logger.info("统一工具处理器初始化完成") + self.logger.info("Unified tool handler initialization completed") - # 输出当前支持的所有工具列表 + # Output current supported tool list self.current_support_functions() except Exception as e: - self.logger.error(f"统一工具处理器初始化失败: {e}") + self.logger.error( + f"Unified tool handler initialization failed: {e}") async def _initialize_mcp_endpoint(self): - """初始化MCP接入点""" + """Initialize MCP endpoint""" try: from .mcp_endpoint import connect_mcp_endpoint - # 从配置中获取MCP接入点URL + # Get MCP endpoint URL from config mcp_endpoint_url = self.config.get("mcp_endpoint", "") if ( @@ -90,57 +101,58 @@ class UnifiedToolHandler: and "你的" not in mcp_endpoint_url and mcp_endpoint_url != "null" ): - self.logger.info(f"正在初始化MCP接入点: {mcp_endpoint_url}") + self.logger.info( + f"Initializing MCP endpoint: {mcp_endpoint_url}") mcp_endpoint_client = await connect_mcp_endpoint( mcp_endpoint_url, self.conn ) if mcp_endpoint_client: - # 将MCP接入点客户端保存到连接对象中 + # Save MCP endpoint client to connection object self.conn.mcp_endpoint_client = mcp_endpoint_client - self.logger.info("MCP接入点初始化成功") + self.logger.info("MCP endpoint initialization successful") else: - self.logger.warning("MCP接入点初始化失败") + self.logger.warning("MCP endpoint initialization failed") except Exception as e: - self.logger.error(f"初始化MCP接入点失败: {e}") + self.logger.error(f"MCP endpoint initialization failed: {e}") def _initialize_home_assistant(self): - """初始化Home Assistant提示词""" + """Initialize Home Assistant prompt""" try: from plugins_func.functions.hass_init import append_devices_to_prompt append_devices_to_prompt(self.conn) except ImportError: - pass # 忽略导入错误 + pass # Ignore import errors except Exception as e: - self.logger.error(f"初始化Home Assistant失败: {e}") + self.logger.error(f"Home Assistant initialization failed: {e}") def get_functions(self) -> List[Dict[str, Any]]: - """获取所有工具的函数描述""" + """Get function descriptions for all tools""" return self.tool_manager.get_function_descriptions() def current_support_functions(self) -> List[str]: - """获取当前支持的函数名称列表""" + """Get list of currently supported function names""" func_names = self.tool_manager.get_supported_tool_names() - self.logger.info(f"当前支持的函数列表: {func_names}") + self.logger.info(f"Current supported function list: {func_names}") return func_names def upload_functions_desc(self): - """刷新函数描述列表""" + """Refresh function description list""" self.tool_manager.refresh_tools() - self.logger.info("函数描述列表已刷新") + self.logger.info("Function description list refreshed") def has_tool(self, tool_name: str) -> bool: - """检查是否有指定工具""" + """Check if the specified tool exists""" return self.tool_manager.has_tool(tool_name) async def handle_llm_function_call( self, conn, function_call_data: Dict[str, Any] ) -> Optional[ActionResponse]: - """处理LLM函数调用""" + """Handle LLM function calls""" try: - # 处理多函数调用 + # Handle multiple function calls if "function_calls" in function_call_data: responses = [] for call in function_call_data["function_calls"]: @@ -150,52 +162,53 @@ class UnifiedToolHandler: responses.append(result) return self._combine_responses(responses) - # 处理单函数调用 + # Handle single function call function_name = function_call_data["name"] arguments = function_call_data.get("arguments", {}) - # 如果arguments是字符串,尝试解析为JSON + # If arguments is a string, try to parse as JSON if isinstance(arguments, str): try: arguments = json.loads(arguments) if arguments else {} except json.JSONDecodeError: - self.logger.error(f"无法解析函数参数: {arguments}") + self.logger.error( + f"Unable to parse function arguments: {arguments}") return ActionResponse( action=Action.ERROR, - response="无法解析函数参数", + response="Unable to parse function arguments", ) - self.logger.debug(f"调用函数: {function_name}, 参数: {arguments}") + self.logger.debug( + f"Calling function: {function_name}, arguments: {arguments}") - # 执行工具调用 + # Execute tool call result = await self.tool_manager.execute_tool(function_name, arguments) return result except Exception as e: - self.logger.error(f"处理function call错误: {e}") + self.logger.error(f"Error handling function call: {e}") return ActionResponse(action=Action.ERROR, response=str(e)) def _combine_responses(self, responses: List[ActionResponse]) -> ActionResponse: - """合并多个函数调用的响应""" + """Combine responses from multiple function calls""" if not responses: - return ActionResponse(action=Action.NONE, response="无响应") + return ActionResponse(action=Action.NONE, response="No response") - # 如果有任何错误,返回第一个错误 + # If there are any errors, return the first error for response in responses: if response.action == Action.ERROR: return response - # 合并所有成功的响应 + # Combine all successful responses contents = [] responses_text = [] - for response in responses: if response.content: contents.append(response.content) if response.response: responses_text.append(response.response) - # 确定最终的动作类型 + # Determine final action type final_action = Action.RESPONSE for response in responses: if response.action == Action.REQLLM: @@ -209,27 +222,28 @@ class UnifiedToolHandler: ) async def register_iot_tools(self, descriptors: List[Dict[str, Any]]): - """注册IoT设备工具""" + """Register IoT device tools""" self.device_iot_executor.register_iot_tools(descriptors) self.tool_manager.refresh_tools() - self.logger.info(f"注册了{len(descriptors)}个IoT设备的工具") + self.logger.info( + f"Registered tools for {len(descriptors)} IoT devices") def get_tool_statistics(self) -> Dict[str, int]: - """获取工具统计信息""" + """Get tool statistics""" return self.tool_manager.get_tool_statistics() async def cleanup(self): - """清理资源""" + """Clean up resources""" try: await self.server_mcp_executor.cleanup() - # 清理MCP接入点连接 + # Clean up MCP endpoint connection if ( hasattr(self.conn, "mcp_endpoint_client") and self.conn.mcp_endpoint_client ): await self.conn.mcp_endpoint_client.close() - self.logger.info("工具处理器清理完成") + self.logger.info("Tool handler cleanup completed") except Exception as e: - self.logger.error(f"工具处理器清理失败: {e}") + self.logger.error(f"Tool handler cleanup failed: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py index e2a918693..4978f1445 100644 --- a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py +++ b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py @@ -1,13 +1,16 @@ -"""统一工具管理器""" +"""Unified tool manager""" from typing import Dict, List, Optional, Any + from config.logger import setup_logging + from plugins_func.register import Action, ActionResponse + from .base import ToolType, ToolDefinition, ToolExecutor class ToolManager: - """统一工具管理器,管理所有类型的工具""" + """Unified tool manager, manages all types of tools""" def __init__(self, conn): self.conn = conn @@ -17,18 +20,18 @@ class ToolManager: self._cached_function_descriptions: Optional[List[Dict[str, Any]]] = None def register_executor(self, tool_type: ToolType, executor: ToolExecutor): - """注册工具执行器""" + """Register tool executor""" self.executors[tool_type] = executor self._invalidate_cache() - self.logger.info(f"注册工具执行器: {tool_type.value}") + self.logger.info(f"Registered tool executor: {tool_type.value}") def _invalidate_cache(self): - """使缓存失效""" + """Invalidate cache""" self._cached_tools = None self._cached_function_descriptions = None def get_all_tools(self) -> Dict[str, ToolDefinition]: - """获取所有工具定义""" + """Get all tool definitions""" if self._cached_tools is not None: return self._cached_tools @@ -38,21 +41,23 @@ class ToolManager: tools = executor.get_tools() for name, definition in tools.items(): if name in all_tools: - self.logger.warning(f"工具名称冲突: {name}") + self.logger.warning(f"Tool name conflict: {name}") all_tools[name] = definition except Exception as e: - self.logger.error(f"获取{tool_type.value}工具时出错: {e}") + self.logger.error( + f"Error getting {tool_type.value} tools: {e}") self._cached_tools = all_tools return all_tools def get_function_descriptions(self) -> List[Dict[str, Any]]: - """获取所有工具的函数描述(OpenAI格式)""" + """Get function descriptions for all tools (OpenAI format)""" if self._cached_function_descriptions is not None: return self._cached_function_descriptions descriptions = [] tools = self.get_all_tools() + for tool_definition in tools.values(): descriptions.append(tool_definition.description) @@ -60,12 +65,12 @@ class ToolManager: return descriptions def has_tool(self, tool_name: str) -> bool: - """检查是否存在指定工具""" + """Check if the specified tool exists""" tools = self.get_all_tools() return tool_name in tools def get_tool_type(self, tool_name: str) -> Optional[ToolType]: - """获取工具类型""" + """Get tool type""" tools = self.get_all_tools() tool_def = tools.get(tool_name) return tool_def.tool_type if tool_def else None @@ -73,52 +78,54 @@ class ToolManager: async def execute_tool( self, tool_name: str, arguments: Dict[str, Any] ) -> ActionResponse: - """执行工具调用""" + """Execute tool call""" try: - # 查找工具类型 + # Find tool type tool_type = self.get_tool_type(tool_name) if not tool_type: return ActionResponse( action=Action.NOTFOUND, - response=f"工具 {tool_name} 不存在", + response=f"Tool {tool_name} does not exist", ) - # 获取对应的执行器 + # Get corresponding executor executor = self.executors.get(tool_type) if not executor: return ActionResponse( action=Action.ERROR, - response=f"工具类型 {tool_type.value} 的执行器未注册", + response=f"Executor for tool type {tool_type.value} is not registered", ) - # 执行工具 - self.logger.info(f"执行工具: {tool_name},参数: {arguments}") + # Execute tool + self.logger.info( + f"Executing tool: {tool_name}, arguments: {arguments}") result = await executor.execute(self.conn, tool_name, arguments) - self.logger.debug(f"工具执行结果: {result}") + self.logger.debug(f"Tool execution result: {result}") return result except Exception as e: - self.logger.error(f"执行工具 {tool_name} 时出错: {e}") + self.logger.error(f"Error executing tool {tool_name}: {e}") return ActionResponse(action=Action.ERROR, response=str(e)) def get_supported_tool_names(self) -> List[str]: - """获取所有支持的工具名称""" + """Get all supported tool names""" tools = self.get_all_tools() return list(tools.keys()) def refresh_tools(self): - """刷新工具缓存""" + """Refresh tool cache""" self._invalidate_cache() - self.logger.info("工具缓存已刷新") + self.logger.info("Tool cache refreshed") def get_tool_statistics(self) -> Dict[str, int]: - """获取工具统计信息""" + """Get tool statistics""" stats = {} for tool_type, executor in self.executors.items(): try: tools = executor.get_tools() stats[tool_type.value] = len(tools) except Exception as e: - self.logger.error(f"获取{tool_type.value}工具统计时出错: {e}") + self.logger.error( + f"Error getting {tool_type.value} tool statistics: {e}") stats[tool_type.value] = 0 return stats diff --git a/main/xiaozhi-server/core/providers/tts/aliyun.py b/main/xiaozhi-server/core/providers/tts/aliyun.py index fe5b1896d..b8060089f 100644 --- a/main/xiaozhi-server/core/providers/tts/aliyun.py +++ b/main/xiaozhi-server/core/providers/tts/aliyun.py @@ -1,205 +1,354 @@ import uuid -import json -import hmac -import hashlib -import base64 -import requests -from datetime import datetime -from core.providers.tts.base import TTSProviderBase -from config.logger import setup_logging -import time -import uuid -from urllib import parse -TAG = __name__ -logger = setup_logging() +import json + +import hmac + +import hashlib + +import base64 + +import requests + +from datetime import datetime + +from core.providers.tts.base import TTSProviderBase + +import time + +import uuid + +from urllib import parse class AccessToken: + @staticmethod def _encode_text(text): + encoded_text = parse.quote_plus(text) + return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") @staticmethod def _encode_dict(dic): + keys = dic.keys() + dic_sorted = [(key, dic[key]) for key in sorted(keys)] + encoded_text = parse.urlencode(dic_sorted) + return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") @staticmethod def create_token(access_key_id, access_key_secret): + parameters = { + "AccessKeyId": access_key_id, + "Action": "CreateToken", + "Format": "JSON", + "RegionId": "cn-shanghai", + "SignatureMethod": "HMAC-SHA1", + "SignatureNonce": str(uuid.uuid1()), + "SignatureVersion": "1.0", + "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "Version": "2019-02-28", + } - # 构造规范化的请求字符串 + + # Construct normalized request string + query_string = AccessToken._encode_dict(parameters) - # print('规范化的请求字符串: %s' % query_string) - # 构造待签名字符串 + + # print('Normalized request string: %s' % query_string) + + # Construct string to be signed + string_to_sign = ( + "GET" + + "&" + + AccessToken._encode_text("/") + + "&" + + AccessToken._encode_text(query_string) + ) - # print('待签名的字符串: %s' % string_to_sign) - # 计算签名 + + # print('String to be signed: %s' % string_to_sign) + + # Calculate signature + secreted_string = hmac.new( + bytes(access_key_secret + "&", encoding="utf-8"), + bytes(string_to_sign, encoding="utf-8"), + hashlib.sha1, + ).digest() + signature = base64.b64encode(secreted_string) - # print('签名: %s' % signature) - # 进行URL编码 + + # print('Signature: %s' % signature) + + # URL encode + signature = AccessToken._encode_text(signature) - # print('URL编码后的签名: %s' % signature) - # 调用服务 + + # print('URL encoded signature: %s' % signature) + + # Call service + full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % ( + signature, + query_string, + ) + # print('url: %s' % full_url) - # 提交HTTP GET请求 + + # Submit HTTP GET request + response = requests.get(full_url) + if response.ok: + root_obj = response.json() + key = "Token" + if key in root_obj: + token = root_obj[key]["Id"] + expire_time = root_obj[key]["ExpireTime"] + return token, expire_time + # print(response.text) + return None, None class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) - # 新增空值判断逻辑 + # Add null value check logic + self.access_key_id = config.get("access_key_id") + self.access_key_secret = config.get("access_key_secret") self.appkey = config.get("appkey") + self.format = config.get("format", "wav") + self.audio_file_type = config.get("format", "wav") + sample_rate = config.get("sample_rate", "16000") + self.sample_rate = int(sample_rate) if sample_rate else 16000 if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice", "xiaoyun") volume = config.get("volume", "50") + self.volume = int(volume) if volume else 50 speech_rate = config.get("speech_rate", "0") + self.speech_rate = int(speech_rate) if speech_rate else 0 pitch_rate = config.get("pitch_rate", "0") + self.pitch_rate = int(pitch_rate) if pitch_rate else 0 self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com") + self.api_url = f"https://{self.host}/stream/v1/tts" + self.header = {"Content-Type": "application/json"} if self.access_key_id and self.access_key_secret: - # 使用密钥对生成临时token + + # Use key pair to generate temporary token + self._refresh_token() + else: - # 直接使用预生成的长期token + + # Directly use pre-generated long-term token + self.token = config.get("token") + self.expire_time = None def _refresh_token(self): - """刷新Token并记录过期时间""" + """Refresh Token and record expiration time""" + if self.access_key_id and self.access_key_secret: + self.token, expire_time_str = AccessToken.create_token( + self.access_key_id, self.access_key_secret + ) + if not expire_time_str: - raise ValueError("无法获取有效的Token过期时间") + + raise ValueError("Unable to get valid Token expiration time") try: - # 统一转换为字符串处理 + + # Uniformly convert to string processing + expire_str = str(expire_time_str).strip() if expire_str.isdigit(): + expire_time = datetime.fromtimestamp(int(expire_str)) + else: - expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") + + expire_time = datetime.strptime( + expire_str, "%Y-%m-%dT%H:%M:%SZ") + self.expire_time = expire_time.timestamp() - 60 + except Exception as e: - raise ValueError(f"无效的过期时间格式: {expire_str}") from e + + raise ValueError( + f"Invalid expiration time format: {expire_str}") from e else: + self.expire_time = None if not self.token: - raise ValueError("无法获取有效的访问Token") + + raise ValueError("Unable to get valid access Token") def _is_token_expired(self): - """检查Token是否过期""" + """Check if Token has expired""" + if not self.expire_time: - return False # 长期Token不过期 - # 新增调试日志 + + return False # Long-term Token does not expire + + # Add debug log + # current_time = time.time() + # remaining = self.expire_time - current_time - # print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | " - # f"过期时间 {datetime.fromtimestamp(self.expire_time)} | " - # f"剩余 {remaining:.2f}秒") + + # print(f"Token expiration check: current time {datetime.fromtimestamp(current_time)} | " + + # f"expiration time {datetime.fromtimestamp(self.expire_time)} | " + + # f"remaining {remaining:.2f}seconds") + return time.time() > self.expire_time async def text_to_speak(self, text, output_file): + if self._is_token_expired(): - logger.warning("Token已过期,正在自动刷新...") + + logger.warning("Token has expired, automatically refreshing...") + self._refresh_token() + request_json = { + "appkey": self.appkey, + "token": self.token, + "text": text, + "format": self.format, + "sample_rate": self.sample_rate, + "voice": self.voice, + "volume": self.volume, + "speech_rate": self.speech_rate, + "pitch_rate": self.pitch_rate, + } # print(self.api_url, json.dumps(request_json, ensure_ascii=False)) + try: + resp = requests.post( + self.api_url, json.dumps(request_json), headers=self.header + ) - if resp.status_code == 401: # Token过期特殊处理 + + if resp.status_code == 401: # Special handling for Token expiration + self._refresh_token() + resp = requests.post( + self.api_url, json.dumps(request_json), headers=self.header + ) - # 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的 + + # Check if the mime type of returned request data is audio/***, if so save to specified path; returned is binary format + if resp.headers["Content-Type"].startswith("audio/"): + if output_file: + with open(output_file, "wb") as f: + f.write(resp.content) + return output_file + else: + return resp.content + else: + raise Exception( + f"{__name__} status_code: {resp.status_code} response: {resp.content}" + ) + except Exception as e: - raise Exception(f"{__name__} error: {e}") \ No newline at end of file + + raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py index 55b93b790..529f15863 100644 --- a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py +++ b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py @@ -41,7 +41,7 @@ class AccessToken: "AccessKeyId": access_key_id, "Action": "CreateToken", "Format": "JSON", - "RegionId": "cn-shanghai", # 使用上海地域进行Token获取 + "RegionId": "cn-shanghai", # Use Shanghai region for Token acquisition "SignatureMethod": "HMAC-SHA1", "SignatureNonce": str(uuid.uuid1()), "SignatureVersion": "1.0", @@ -88,27 +88,28 @@ class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) - # 设置为流式接口类型 + # Set to streaming interface type self.interface_type = InterfaceType.DUAL_STREAM - # 基础配置 + # Basic configuration self.access_key_id = config.get("access_key_id") self.access_key_secret = config.get("access_key_secret") self.appkey = config.get("appkey") self.format = config.get("format", "pcm") self.audio_file_type = config.get("format", "pcm") - # 采样率配置 + # Sample rate configuration sample_rate = config.get("sample_rate", "16000") self.sample_rate = int(sample_rate) if sample_rate else 16000 - # 音色配置 - CosyVoice大模型音色 + # Voice configuration - CosyVoice large model voice if config.get("private_voice"): self.voice = config.get("private_voice") else: - self.voice = config.get("voice", "longxiaochun") # CosyVoice默认音色 + # CosyVoice default voice + self.voice = config.get("voice", "longxiaochun") - # 音频参数配置 + # Audio parameter configuration volume = config.get("volume", "50") self.volume = int(volume) if volume else 50 @@ -118,27 +119,27 @@ class TTSProvider(TTSProviderBase): pitch_rate = config.get("pitch_rate", "0") self.pitch_rate = int(pitch_rate) if pitch_rate else 0 - # WebSocket配置 + # WebSocket configuration self.host = config.get("host", "nls-gateway-cn-beijing.aliyuncs.com") - # 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议 + # If configured with internal network address (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol if "-internal." in self.host: self.ws_url = f"ws://{self.host}/ws/v1" else: - # 默认使用wss协议 + # Default to wss protocol self.ws_url = f"wss://{self.host}/ws/v1" self.ws = None self._monitor_task = None self.last_active_time = None - # 专属tts设置 + # Dedicated TTS settings self.message_id = "" - # 创建Opus编码器 + # Create Opus encoder self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( sample_rate=16000, channels=1, frame_size_ms=60 ) - # Token管理 + # Token management if self.access_key_id and self.access_key_secret: self._refresh_token() else: @@ -146,13 +147,13 @@ class TTSProvider(TTSProviderBase): self.expire_time = None def _refresh_token(self): - """刷新Token并记录过期时间""" + """Refresh Token and record expiration time""" if self.access_key_id and self.access_key_secret: self.token, expire_time_str = AccessToken.create_token( self.access_key_id, self.access_key_secret ) if not expire_time_str: - raise ValueError("无法获取有效的Token过期时间") + raise ValueError("Unable to get valid Token expiration time") expire_str = str(expire_time_str).strip() @@ -160,34 +161,38 @@ class TTSProvider(TTSProviderBase): if expire_str.isdigit(): expire_time = datetime.fromtimestamp(int(expire_str)) else: - expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") + expire_time = datetime.strptime( + expire_str, "%Y-%m-%dT%H:%M:%SZ") self.expire_time = expire_time.timestamp() - 60 except Exception as e: - raise ValueError(f"无效的过期时间格式: {expire_str}") from e + raise ValueError( + f"Invalid expiration time format: {expire_str}") from e else: self.expire_time = None if not self.token: - raise ValueError("无法获取有效的访问Token") + raise ValueError("Unable to get valid access Token") def _is_token_expired(self): - """检查Token是否过期""" + """Check if Token is expired""" if not self.expire_time: return False return time.time() > self.expire_time async def _ensure_connection(self): - """确保WebSocket连接可用""" + """Ensure WebSocket connection is available""" try: if self._is_token_expired(): - logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...") + logger.bind(tag=TAG).warning( + "Token has expired, automatically refreshing...") self._refresh_token() current_time = time.time() if self.ws and current_time - self.last_active_time < 10: - # 10秒内才可以复用链接进行连续对话 - logger.bind(tag=TAG).info(f"使用已有链接...") + # Can only reuse connection for continuous conversation within 10 seconds + logger.bind(tag=TAG).info(f"Using existing connection...") return self.ws - logger.bind(tag=TAG).info("开始建立新连接...") + logger.bind(tag=TAG).info( + "Starting to establish new connection...") self.ws = await websockets.connect( self.ws_url, @@ -196,106 +201,118 @@ class TTSProvider(TTSProviderBase): ping_timeout=10, close_timeout=10, ) - logger.bind(tag=TAG).info("WebSocket连接建立成功") + logger.bind(tag=TAG).info( + "WebSocket connection established successfully") self.last_active_time = time.time() return self.ws except Exception as e: - logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Failed to establish connection: {str(e)}") self.ws = None self.last_active_time = None raise def tts_text_priority_thread(self): - """流式文本处理线程""" + """Streaming text processing thread""" while not self.conn.stop_event.is_set(): try: message = self.tts_text_queue.get(timeout=1) logger.bind(tag=TAG).debug( - f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}" + f"Received TTS task|{message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}" ) if message.sentence_type == SentenceType.FIRST: self.conn.client_abort = False if self.conn.client_abort: - logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") + logger.bind(tag=TAG).info( + "Received interruption signal, terminating TTS text processing thread") continue if message.sentence_type == SentenceType.FIRST: - # 初始化参数 + # Initialize parameters try: if not getattr(self.conn, "sentence_id", None): self.conn.sentence_id = uuid.uuid4().hex logger.bind(tag=TAG).info( - f"自动生成新的 会话ID: {self.conn.sentence_id}" + f"Auto-generated new session ID: {self.conn.sentence_id}" ) - # aliyunStream独有的参数生成 + # AliyunStream-specific parameter generation self.message_id = str(uuid.uuid4().hex) - logger.bind(tag=TAG).info("开始启动TTS会话...") + logger.bind(tag=TAG).info("Starting TTS session...") future = asyncio.run_coroutine_threadsafe( self.start_session(self.conn.sentence_id), loop=self.conn.loop, ) future.result() self.before_stop_play_files.clear() - logger.bind(tag=TAG).info("TTS会话启动成功") + logger.bind(tag=TAG).info( + "TTS session started successfully") except Exception as e: - logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Failed to start TTS session: {str(e)}") continue elif ContentType.TEXT == message.content_type: if message.content_detail: try: logger.bind(tag=TAG).debug( - f"开始发送TTS文本: {message.content_detail}" + f"Starting to send TTS text: {message.content_detail}" ) future = asyncio.run_coroutine_threadsafe( - self.text_to_speak(message.content_detail, None), + self.text_to_speak( + message.content_detail, None), loop=self.conn.loop, ) future.result() - logger.bind(tag=TAG).debug("TTS文本发送成功") + logger.bind(tag=TAG).debug( + "TTS text sent successfully") except Exception as e: - logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Failed to send TTS text: {str(e)}") continue elif ContentType.FILE == message.content_type: logger.bind(tag=TAG).info( - f"添加音频文件到待播放列表: {message.content_file}" + f"Adding audio file to playback queue: {message.content_file}" ) if message.content_file and os.path.exists(message.content_file): - # 先处理文件音频数据 - file_audio = self._process_audio_file(message.content_file) + # Process file audio data first + file_audio = self._process_audio_file( + message.content_file) self.before_stop_play_files.append( (file_audio, message.content_detail) ) if message.sentence_type == SentenceType.LAST: try: - logger.bind(tag=TAG).info("开始结束TTS会话...") + logger.bind(tag=TAG).info( + "Starting to end TTS session...") future = asyncio.run_coroutine_threadsafe( self.finish_session(self.conn.sentence_id), loop=self.conn.loop, ) future.result() except Exception as e: - logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}") + logger.bind(tag=TAG).error( + f"Failed to end TTS session: {str(e)}") continue except queue.Empty: continue except Exception as e: logger.bind(tag=TAG).error( - f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}" ) async def text_to_speak(self, text, _): try: if self.ws is None: - logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本") + logger.bind(tag=TAG).warning( + f"WebSocket connection does not exist, terminating text sending") return filtered_text = MarkdownCleaner.clean_markdown(text) run_request = { @@ -313,7 +330,7 @@ class TTSProvider(TTSProviderBase): return except Exception as e: - logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}") + logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}") if self.ws: try: await self.ws.close() @@ -323,24 +340,25 @@ class TTSProvider(TTSProviderBase): raise async def start_session(self, session_id): - logger.bind(tag=TAG).info(f"开始会话~~{session_id}") + logger.bind(tag=TAG).info(f"Starting session~~{session_id}") try: - # 会话开始时检测上个会话的监听状态 + # Check previous session monitoring status when session starts if ( self._monitor_task is not None and isinstance(self._monitor_task, Task) and not self._monitor_task.done() ): logger.bind(tag=TAG).info( - "检测到未完成的上个会话,关闭监听任务和连接..." + "Detected incomplete previous session, closing monitoring task and connection..." ) await self.close() - # 建立新连接 + # Establish new connection await self._ensure_connection() - # 启动监听任务 - self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) + # Start monitoring task + self._monitor_task = asyncio.create_task( + self._start_monitor_tts_response()) start_request = { "header": { @@ -362,15 +380,15 @@ class TTSProvider(TTSProviderBase): } await self.ws.send(json.dumps(start_request)) self.last_active_time = time.time() - logger.bind(tag=TAG).info("会话启动请求已发送") + logger.bind(tag=TAG).info("Session start request sent") except Exception as e: - logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") + logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}") # 确保清理资源 await self.close() raise async def finish_session(self, session_id): - logger.bind(tag=TAG).info(f"关闭会话~~{session_id}") + logger.bind(tag=TAG).info(f"Closing session~~{session_id}") try: if self.ws: stop_request = { @@ -383,25 +401,25 @@ class TTSProvider(TTSProviderBase): } } await self.ws.send(json.dumps(stop_request)) - logger.bind(tag=TAG).info("会话结束请求已发送") + logger.bind(tag=TAG).info("Session end request sent") self.last_active_time = time.time() if self._monitor_task: try: await self._monitor_task except Exception as e: logger.bind(tag=TAG).error( - f"等待监听任务完成时发生错误: {str(e)}" + f"Error occurred while waiting for monitoring task to complete: {str(e)}" ) finally: self._monitor_task = None except Exception as e: - logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}") + logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}") # 确保清理资源 await self.close() raise async def close(self): - """资源清理""" + """Resource cleanup""" if self._monitor_task: try: self._monitor_task.cancel() @@ -409,7 +427,8 @@ class TTSProvider(TTSProviderBase): except asyncio.CancelledError: pass except Exception as e: - logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}") + logger.bind(tag=TAG).warning( + f"Error canceling monitoring task during close: {e}") self._monitor_task = None if self.ws: @@ -421,27 +440,29 @@ class TTSProvider(TTSProviderBase): self.last_active_time = None async def _start_monitor_tts_response(self): - """监听TTS响应""" + """Monitor TTS responses""" opus_datas_cache = [] is_first_sentence = True - first_sentence_segment_count = 0 # 添加计数器 + first_sentence_segment_count = 0 # Add counter try: - session_finished = False # 标记会话是否正常结束 + session_finished = False # Mark whether session ended normally while not self.conn.stop_event.is_set(): try: msg = await self.ws.recv() self.last_active_time = time.time() - # 检查客户端是否中止 + # Check if client aborted if self.conn.client_abort: - logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应") + logger.bind(tag=TAG).info( + "Received interruption signal, terminating TTS response monitoring") break - if isinstance(msg, str): # 文本控制消息 + if isinstance(msg, str): # Text control message try: data = json.loads(msg) header = data.get("header", {}) event_name = header.get("name") if event_name == "SynthesisStarted": - logger.bind(tag=TAG).debug("TTS合成已启动") + logger.bind(tag=TAG).debug( + "TTS synthesis started") self.tts_audio_queue.put( (SentenceType.FIRST, [], None) ) @@ -452,34 +473,38 @@ class TTSProvider(TTSProviderBase): not is_first_sentence or first_sentence_segment_count > 10 ): - # 发送缓存的数据 + # Send cached data if self.conn.tts_MessageText: logger.bind(tag=TAG).info( - f"句子语音生成成功: {self.conn.tts_MessageText}" + f"Sentence voice generation successful: {self.conn.tts_MessageText}" ) self.tts_audio_queue.put( - (SentenceType.MIDDLE, opus_datas_cache, self.conn.tts_MessageText) + (SentenceType.MIDDLE, opus_datas_cache, + self.conn.tts_MessageText) ) self.conn.tts_MessageText = None else: self.tts_audio_queue.put( - (SentenceType.MIDDLE, opus_datas_cache, None) + (SentenceType.MIDDLE, + opus_datas_cache, None) ) - # 第一句话结束后,将标志设置为False + # After first sentence ends, set flag to False is_first_sentence = False elif event_name == "SynthesisCompleted": - logger.bind(tag=TAG).debug(f"会话结束~~") + logger.bind(tag=TAG).debug(f"Session ended~~") self._process_before_stop_play_files() session_finished = True break except json.JSONDecodeError: - logger.bind(tag=TAG).warning("收到无效的JSON消息") - # 二进制消息(音频数据) + logger.bind(tag=TAG).warning( + "Received invalid JSON message") + # Binary message (audio data) elif isinstance(msg, (bytes, bytearray)): - logger.bind(tag=TAG).debug(f"推送数据到队列里面~~") - opus_datas = self.opus_encoder.encode_pcm_to_opus(msg, False) + logger.bind(tag=TAG).debug(f"Pushing data to queue~~") + opus_datas = self.opus_encoder.encode_pcm_to_opus( + msg, False) logger.bind(tag=TAG).debug( - f"推送数据到队列里面帧数~~{len(opus_datas)}" + f"Pushing data to queue frame count~~{len(opus_datas)}" ) if is_first_sentence: first_sentence_segment_count += 1 @@ -490,46 +515,46 @@ class TTSProvider(TTSProviderBase): else: opus_datas_cache.extend(opus_datas) else: - # 后续句子缓存 + # Cache subsequent sentences opus_datas_cache.extend(opus_datas) except websockets.ConnectionClosed: - logger.bind(tag=TAG).warning("WebSocket连接已关闭") + logger.bind(tag=TAG).warning("WebSocket connection closed") break except Exception as e: logger.bind(tag=TAG).error( - f"处理TTS响应时出错: {e}\n{traceback.format_exc()}" + f"Error processing TTS response: {e}\n{traceback.format_exc()}" ) break - # 仅在连接异常时才关闭 + # Only close on connection exception if not session_finished and self.ws: try: await self.ws.close() except: pass self.ws = None - # 监听任务退出时清理引用 + # Clean up references when monitoring task exits finally: self._monitor_task = None def to_tts(self, text: str) -> list: - """非流式TTS处理,用于测试及保存音频文件的场景""" + """Non-streaming TTS processing, used for testing and saving audio files scenarios""" try: - # 创建新的事件循环 + # Create new event loop loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - # 生成会话ID + # Generate session ID session_id = uuid.uuid4().hex - # 存储音频数据 + # Store audio data audio_data = [] async def _generate_audio(): - # 刷新Token(如果需要) + # Refresh Token (if needed) if self._is_token_expired(): self._refresh_token() - # 建立WebSocket连接 + # Establish WebSocket connection ws = await websockets.connect( self.ws_url, additional_headers={"X-NLS-Token": self.token}, @@ -538,7 +563,7 @@ class TTSProvider(TTSProviderBase): close_timeout=10, ) try: - # 发送StartSynthesis请求 + # Send StartSynthesis request start_message_id = str(uuid.uuid4().hex) start_request = { "header": { @@ -560,7 +585,7 @@ class TTSProvider(TTSProviderBase): } await ws.send(json.dumps(start_request)) - # 等待SynthesisStarted响应 + # Wait for SynthesisStarted response synthesis_started = False while not synthesis_started: msg = await ws.recv() @@ -569,7 +594,8 @@ class TTSProvider(TTSProviderBase): header = data.get("header", {}) if header.get("name") == "SynthesisStarted": synthesis_started = True - logger.bind(tag=TAG).debug("TTS合成已启动") + logger.bind(tag=TAG).debug( + "TTS synthesis started") elif header.get("name") == "TaskFailed": error_info = data.get("payload", {}).get( "error_info", {} @@ -579,10 +605,10 @@ class TTSProvider(TTSProviderBase): "error_message", "未知错误" ) raise Exception( - f"启动合成失败: {error_code} - {error_message}" + f"Failed to start synthesis: {error_code} - {error_message}" ) - # 发送文本合成请求 + # Send text synthesis request filtered_text = MarkdownCleaner.clean_markdown(text) run_message_id = str(uuid.uuid4().hex) run_request = { @@ -597,7 +623,7 @@ class TTSProvider(TTSProviderBase): } await ws.send(json.dumps(run_request)) - # 发送停止合成请求 + # Send stop synthesis request stop_message_id = str(uuid.uuid4().hex) stop_request = { "header": { @@ -610,12 +636,12 @@ class TTSProvider(TTSProviderBase): } await ws.send(json.dumps(stop_request)) - # 接收音频数据 + # Receive audio data synthesis_completed = False while not synthesis_completed: msg = await ws.recv() if isinstance(msg, (bytes, bytearray)): - # 编码为Opus并收集 + # Encode to Opus and collect opus_frames = self.opus_encoder.encode_pcm_to_opus( msg, False ) @@ -626,7 +652,8 @@ class TTSProvider(TTSProviderBase): event_name = header.get("name") if event_name == "SynthesisCompleted": synthesis_completed = True - logger.bind(tag=TAG).debug("TTS合成完成") + logger.bind(tag=TAG).debug( + "TTS synthesis completed") elif event_name == "TaskFailed": error_info = data.get("payload", {}).get( "error_info", {} @@ -636,7 +663,7 @@ class TTSProvider(TTSProviderBase): "error_message", "未知错误" ) raise Exception( - f"合成失败: {error_code} - {error_message}" + f"Synthesis failed: {error_code} - {error_message}" ) finally: try: @@ -649,5 +676,6 @@ class TTSProvider(TTSProviderBase): return audio_data except Exception as e: - logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}") - return [] \ No newline at end of file + logger.bind(tag=TAG).error( + f"Failed to generate audio data: {str(e)}") + return [] diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index c9b4041a8..b5f867729 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -20,13 +20,11 @@ from core.providers.tts.dto.dto import ( ContentType, InterfaceType, ) - import traceback TAG = __name__ logger = setup_logging() - class TTSProviderBase(ABC): def __init__(self, config, delete_audio_file): self.interface_type = InterfaceType.NON_STREAM @@ -39,7 +37,6 @@ class TTSProviderBase(ABC): self.tts_audio_queue = queue.Queue() self.tts_audio_first_sentence = True self.before_stop_play_files = [] - self.tts_text_buff = [] self.punctuations = ( "。", @@ -81,7 +78,7 @@ class TTSProviderBase(ABC): text = MarkdownCleaner.clean_markdown(text) max_repeat_time = 5 if self.delete_audio_file: - # 需要删除文件的直接转为音频数据 + # Files that need to be deleted are directly converted to audio data while max_repeat_time > 0: try: audio_bytes = asyncio.run(self.text_to_speak(text, None)) @@ -94,16 +91,17 @@ class TTSProviderBase(ABC): max_repeat_time -= 1 except Exception as e: logger.bind(tag=TAG).warning( - f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}" + f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}" ) max_repeat_time -= 1 + if max_repeat_time > 0: logger.bind(tag=TAG).info( - f"语音生成成功: {text},重试{5 - max_repeat_time}次" + f"Speech generation successful: {text}, retried {5 - max_repeat_time} times" ) else: logger.bind(tag=TAG).error( - f"语音生成失败: {text},请检查网络或服务是否正常" + f"Speech generation failed: {text}, please check network or service status" ) return None else: @@ -114,22 +112,21 @@ class TTSProviderBase(ABC): asyncio.run(self.text_to_speak(text, tmp_file)) except Exception as e: logger.bind(tag=TAG).warning( - f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}" + f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}" ) - # 未执行成功,删除文件 + # If execution unsuccessful, delete file if os.path.exists(tmp_file): os.remove(tmp_file) max_repeat_time -= 1 - + if max_repeat_time > 0: logger.bind(tag=TAG).info( - f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次" + f"Speech generation successful: {text}:{tmp_file}, retried {5 - max_repeat_time} times" ) else: logger.bind(tag=TAG).error( - f"语音生成失败: {text},请检查网络或服务是否正常" + f"Speech generation failed: {text}, please check network or service status" ) - return tmp_file except Exception as e: logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}") @@ -140,11 +137,11 @@ class TTSProviderBase(ABC): pass def audio_to_pcm_data(self, audio_file_path): - """音频文件转换为PCM编码""" + """Convert audio file to PCM encoding""" return audio_to_data(audio_file_path, is_opus=False) def audio_to_opus_data(self, audio_file_path): - """音频文件转换为Opus编码""" + """Convert audio file to Opus encoding""" return audio_to_data(audio_file_path, is_opus=True) def tts_one_sentence( @@ -155,14 +152,15 @@ class TTSProviderBase(ABC): content_file=None, sentence_id=None, ): - """发送一句话""" + """Send one sentence""" if not sentence_id: if conn.sentence_id: sentence_id = conn.sentence_id else: sentence_id = str(uuid.uuid4().hex) conn.sentence_id = sentence_id - # 对于单句的文本,进行分段处理 + + # For single sentence text, perform segmentation processing segments = re.split(r"([。!?!?;;\n])", content_detail) for seg in segments: self.tts_text_queue.put( @@ -178,36 +176,38 @@ class TTSProviderBase(ABC): async def open_audio_channels(self, conn): self.conn = conn self.tts_timeout = conn.config.get("tts_timeout", 10) - # tts 消化线程 + # TTS processing thread self.tts_priority_thread = threading.Thread( target=self.tts_text_priority_thread, daemon=True ) self.tts_priority_thread.start() - - # 音频播放 消化线程 + # Audio playback processing thread self.audio_play_priority_thread = threading.Thread( target=self._audio_play_priority_thread, daemon=True ) self.audio_play_priority_thread.start() + # Default is non-streaming processing mode + # Override in subclass for streaming processing mode - # 这里默认是非流式的处理方式 - # 流式处理方式请在子类中重写 def tts_text_priority_thread(self): while not self.conn.stop_event.is_set(): try: message = self.tts_text_queue.get(timeout=1) if message.sentence_type == SentenceType.FIRST: self.conn.client_abort = False + if self.conn.client_abort: - logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") + logger.bind(tag=TAG).info("Received interrupt signal, terminating TTS text processing thread") continue + if message.sentence_type == SentenceType.FIRST: - # 初始化参数 + # Initialize parameters self.tts_stop_request = False self.processed_chars = 0 self.tts_text_buff = [] self.is_first_sentence = True self.tts_audio_first_sentence = True + elif ContentType.TEXT == message.content_type: self.tts_text_buff.append(message.content_detail) segment_text = self._get_segment_text() @@ -225,6 +225,7 @@ class TTSProviderBase(ABC): self.tts_audio_queue.put( (message.sentence_type, audio_datas, segment_text) ) + elif ContentType.FILE == message.content_type: self._process_remaining_text() tts_file = message.content_file @@ -244,7 +245,7 @@ class TTSProviderBase(ABC): continue except Exception as e: logger.bind(tag=TAG).error( - f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" ) continue @@ -260,14 +261,18 @@ class TTSProviderBase(ABC): if self.conn.stop_event.is_set(): break continue + future = asyncio.run_coroutine_threadsafe( sendAudioMessage(self.conn, sentence_type, audio_datas, text), self.conn.loop, ) future.result() + if self.conn.max_output_size > 0 and text: add_device_output(self.conn.headers.get("device-id"), len(text)) + enqueue_tts_report(self.conn, text, audio_datas) + except Exception as e: logger.bind(tag=TAG).error( f"audio_play_priority priority_thread: {text} {e}" @@ -280,17 +285,17 @@ class TTSProviderBase(ABC): pass async def close(self): - """资源清理方法""" + """Resource cleanup method""" if hasattr(self, "ws") and self.ws: await self.ws.close() def _get_segment_text(self): - # 合并当前全部文本并处理未分割部分 + # Merge all current text and process unsegmented parts full_text = "".join(self.tts_text_buff) - current_text = full_text[self.processed_chars :] # 从未处理的位置开始 + current_text = full_text[self.processed_chars:] # Start from unprocessed position last_punct_pos = -1 - - # 根据是否是第一句话选择不同的标点符号集合 + + # Choose different punctuation sets based on whether it's the first sentence punctuations_to_use = ( self.first_sentence_punctuations if self.is_first_sentence @@ -309,27 +314,25 @@ class TTSProviderBase(ABC): segment_text = textUtils.get_string_no_punctuation_or_emoji( segment_text_raw ) - self.processed_chars += len(segment_text_raw) # 更新已处理字符位置 - - # 如果是第一句话,在找到第一个逗号后,将标志设置为False + self.processed_chars += len(segment_text_raw) # Update processed character position + # If it's the first sentence, set flag to False after finding first comma if self.is_first_sentence: self.is_first_sentence = False - return segment_text elif self.tts_stop_request and current_text: segment_text = current_text - self.is_first_sentence = True # 重置标志 + self.is_first_sentence = True # Reset flag return segment_text else: return None def _process_audio_file(self, tts_file): - """处理音频文件并转换为指定格式 - + """Process audio file and convert to specified format + Args: - tts_file: 音频文件路径 - content_detail: 内容详情 - + tts_file: Audio file path + content_detail: Content details + Returns: tuple: (sentence_type, audio_datas, content_detail) """ @@ -347,6 +350,7 @@ class TTSProviderBase(ABC): and tts_file.startswith(self.output_file) ): os.remove(tts_file) + return audio_datas def _process_before_stop_play_files(self): @@ -356,15 +360,17 @@ class TTSProviderBase(ABC): self.tts_audio_queue.put((SentenceType.LAST, [], None)) def _process_remaining_text(self): - """处理剩余的文本并生成语音 - + """Process remaining text and generate speech + Returns: - bool: 是否成功处理了文本 + bool: Whether text was successfully processed """ full_text = "".join(self.tts_text_buff) - remaining_text = full_text[self.processed_chars :] + remaining_text = full_text[self.processed_chars:] if remaining_text: - segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text) + segment_text = textUtils.get_string_no_punctuation_or_emoji( + remaining_text + ) if segment_text: if self.delete_audio_file: audio_datas = self.to_tts(segment_text) @@ -380,4 +386,4 @@ class TTSProviderBase(ABC): ) self.processed_chars += len(full_text) return True - return False \ No newline at end of file + return False diff --git a/main/xiaozhi-server/core/providers/tts/cozecn.py b/main/xiaozhi-server/core/providers/tts/cozecn.py index 6c5d05472..8e3f0110f 100644 --- a/main/xiaozhi-server/core/providers/tts/cozecn.py +++ b/main/xiaozhi-server/core/providers/tts/cozecn.py @@ -1,42 +1,76 @@ import requests + from core.providers.tts.base import TTSProviderBase class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.model = config.get("model") + self.access_token = config.get("access_token") + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice") + self.response_format = config.get("response_format", "wav") + self.audio_file_type = config.get("response_format", "wav") + self.host = "api.coze.cn" + self.api_url = f"https://{self.host}/v1/audio/speech" async def text_to_speak(self, text, output_file): + request_json = { + "model": self.model, + "input": text, + "voice_id": self.voice, + "response_format": self.response_format, + } + headers = { + "Authorization": f"Bearer {self.access_token}", + "Content-Type": "application/json", + } try: + response = requests.request( + "POST", self.api_url, json=request_json, headers=headers + ) + data = response.content + if output_file: + with open(output_file, "wb") as file_to_save: + file_to_save.write(data) + else: + return data + except Exception as e: + raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/custom.py b/main/xiaozhi-server/core/providers/tts/custom.py index b417825e8..9368c1679 100644 --- a/main/xiaozhi-server/core/providers/tts/custom.py +++ b/main/xiaozhi-server/core/providers/tts/custom.py @@ -1,54 +1,95 @@ import os + import json + import uuid + import requests + from config.logger import setup_logging + from datetime import datetime + from core.providers.tts.base import TTSProviderBase TAG = __name__ + logger = setup_logging() class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.url = config.get("url") + self.method = config.get("method", "GET") + self.headers = config.get("headers", {}) + self.format = config.get("format", "wav") + self.audio_file_type = config.get("format", "wav") + self.output_file = config.get("output_dir", "tmp/") + self.params = config.get("params") if isinstance(self.params, str): + try: + self.params = json.loads(self.params) + except json.JSONDecodeError: - raise ValueError("Custom TTS配置参数出错,无法将字符串解析为对象") + + raise ValueError("Custom TTS configuration parameter error, unable to parse string as object") + elif not isinstance(self.params, dict): - raise TypeError("Custom TTS配置参数出错, 请参考配置说明") + + raise TypeError("Custom TTS configuration parameter error, please refer to configuration instructions") def generate_filename(self): + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}") async def text_to_speak(self, text, output_file): + request_params = {} + for k, v in self.params.items(): + if isinstance(v, str) and "{prompt_text}" in v: + v = v.replace("{prompt_text}", text) + request_params[k] = v if self.method.upper() == "POST": + resp = requests.post(self.url, json=request_params, headers=self.headers) + else: + resp = requests.get(self.url, params=request_params, headers=self.headers) + if resp.status_code == 200: + if output_file: + with open(output_file, "wb") as file: + file.write(resp.content) + else: + return resp.content + else: - error_msg = f"Custom TTS请求失败: {resp.status_code} - {resp.text}" + + error_msg = f"Custom TTS request failed: {resp.status_code} - {resp.text}" + logger.bind(tag=TAG).error(error_msg) - raise Exception(error_msg) # 抛出异常,让调用方捕获 + + raise Exception(error_msg) # Throw exception for caller to catch \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/default.py b/main/xiaozhi-server/core/providers/tts/default.py index 7818d288b..5405df778 100644 --- a/main/xiaozhi-server/core/providers/tts/default.py +++ b/main/xiaozhi-server/core/providers/tts/default.py @@ -1,23 +1,34 @@ import os + from config.logger import setup_logging + from core.providers.tts.base import TTSProviderBase TAG = __name__ + logger = setup_logging() class DefaultTTS(TTSProviderBase): + def __init__(self, config, delete_audio_file=True): + super().__init__(config, delete_audio_file) + self.output_dir = config.get("output_dir", "output") + if not os.path.exists(self.output_dir): + os.makedirs(self.output_dir) def generate_filename(self): - """生成唯一的音频文件名""" + """Generate unique audio filename""" + import uuid return os.path.join(self.output_dir, f"{uuid.uuid4()}.wav") async def text_to_speak(self, text, output_file): - logger.bind(tag=TAG).error(f"无法实例化 TTS 服务,请检查配置") + + logger.bind(tag=TAG).error( + f"Unable to instantiate TTS service, please check configuration") diff --git a/main/xiaozhi-server/core/providers/tts/doubao.py b/main/xiaozhi-server/core/providers/tts/doubao.py index 2eed9bcfc..4df5aa087 100644 --- a/main/xiaozhi-server/core/providers/tts/doubao.py +++ b/main/xiaozhi-server/core/providers/tts/doubao.py @@ -1,86 +1,155 @@ import uuid + import json + import base64 + import requests + from core.utils.util import check_model_key + from core.providers.tts.base import TTSProviderBase + from config.logger import setup_logging TAG = __name__ + logger = setup_logging() - class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + if config.get("appid"): + self.appid = int(config.get("appid")) + else: + self.appid = "" + self.access_token = config.get("access_token") + self.cluster = config.get("cluster") if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice") - # 处理空字符串的情况 + # Handle empty string cases + speed_ratio = config.get("speed_ratio", "1.0") + volume_ratio = config.get("volume_ratio", "1.0") + pitch_ratio = config.get("pitch_ratio", "1.0") + self.audio_file_type = config.get("format", "wav") + self.speed_ratio = float(speed_ratio) if speed_ratio else 1.0 + self.volume_ratio = float(volume_ratio) if volume_ratio else 1.0 + self.pitch_ratio = float(pitch_ratio) if pitch_ratio else 1.0 self.api_url = config.get("api_url") + self.authorization = config.get("authorization") + self.header = {"Authorization": f"{self.authorization}{self.access_token}"} + model_key_msg = check_model_key("TTS", self.access_token) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) async def text_to_speak(self, text, output_file): + request_json = { + "app": { + "appid": f"{self.appid}", + "token": self.access_token, + "cluster": self.cluster, + }, + "user": {"uid": "1"}, + "audio": { + "voice_type": self.voice, + "encoding": self.audio_file_type, + "speed_ratio": self.speed_ratio, + "volume_ratio": self.volume_ratio, + "pitch_ratio": self.pitch_ratio, + }, + "request": { + "reqid": str(uuid.uuid4()), + "text": text, + "text_type": "plain", + "operation": "query", + "with_frontend": 1, + "frontend_type": "unitTson", + }, + } try: + resp = requests.post( + self.api_url, json.dumps(request_json), headers=self.header + ) + if "data" in resp.json(): + data = resp.json()["data"] + audio_bytes = base64.b64decode(data) + if output_file: + with open(output_file, "wb") as file_to_save: + file_to_save.write(audio_bytes) + else: + return audio_bytes + else: + raise Exception( + f"{__name__} status_code: {resp.status_code} response: {resp.content}" + ) + except Exception as e: - raise Exception(f"{__name__} error: {e}") + + raise Exception(f"{__name__} error: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/dto/dto.py b/main/xiaozhi-server/core/providers/tts/dto/dto.py index b23173409..e42e74734 100644 --- a/main/xiaozhi-server/core/providers/tts/dto/dto.py +++ b/main/xiaozhi-server/core/providers/tts/dto/dto.py @@ -3,41 +3,41 @@ from typing import Union, Optional class SentenceType(Enum): - # 说话阶段 - FIRST = "FIRST" # 首句话 - MIDDLE = "MIDDLE" # 说话中 - LAST = "LAST" # 最后一句 + # Speaking stage + FIRST = "FIRST" # First sentence + MIDDLE = "MIDDLE" # Speaking in progress + LAST = "LAST" # Last sentence class ContentType(Enum): - # 内容类型 - TEXT = "TEXT" # 文本内容 - FILE = "FILE" # 文件内容 - ACTION = "ACTION" # 动作内容 + # Content type + TEXT = "TEXT" # Text content + FILE = "FILE" # File content + ACTION = "ACTION" # Action content class InterfaceType(Enum): - # 接口类型 - DUAL_STREAM = "DUAL_STREAM" # 双流式 - SINGLE_STREAM = "SINGLE_STREAM" # 单流式 - NON_STREAM = "NON_STREAM" # 非流式 + # Interface type + DUAL_STREAM = "DUAL_STREAM" # Dual streaming + SINGLE_STREAM = "SINGLE_STREAM" # Single streaming + NON_STREAM = "NON_STREAM" # Non-streaming class TTSMessageDTO: def __init__( self, sentence_id: str, - # 说话阶段 + # Speaking stage sentence_type: SentenceType, - # 内容类型 + # Content type content_type: ContentType, - # 内容详情,一般是需要转换的文本或者音频的歌词 + # Content details, usually text to be converted or lyrics of audio content_detail: Optional[str] = None, - # 如果内容类型为文件,则需要传入文件路径 + # If content type is file, need to pass file path content_file: Optional[str] = None, ): self.sentence_id = sentence_id self.sentence_type = sentence_type self.content_type = content_type self.content_detail = content_detail - self.content_file = content_file + self.content_file = content_file \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py index ffa1c3aa7..9c978bf88 100644 --- a/main/xiaozhi-server/core/providers/tts/edge.py +++ b/main/xiaozhi-server/core/providers/tts/edge.py @@ -1,46 +1,81 @@ import os + import uuid + import edge_tts + from datetime import datetime + from core.providers.tts.base import TTSProviderBase - class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice") + self.audio_file_type = config.get("format", "mp3") def generate_filename(self, extension=".mp3"): + return os.path.join( + self.output_file, + f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", + ) async def text_to_speak(self, text, output_file): + try: + communicate = edge_tts.Communicate(text, voice=self.voice) + if output_file: - # 确保目录存在并创建空文件 + + # Ensure directory exists and create empty file + os.makedirs(os.path.dirname(output_file), exist_ok=True) + with open(output_file, "wb") as f: + pass - # 流式写入音频数据 - with open(output_file, "ab") as f: # 改为追加模式避免覆盖 + # Stream write audio data + + with open(output_file, "ab") as f: # Change to append mode to avoid overwrite + async for chunk in communicate.stream(): - if chunk["type"] == "audio": # 只处理音频数据块 + + if chunk["type"] == "audio": # Only process audio data chunks + f.write(chunk["data"]) + else: - # 返回音频二进制数据 + + # Return audio binary data + audio_bytes = b"" + async for chunk in communicate.stream(): + if chunk["type"] == "audio": + audio_bytes += chunk["data"] + return audio_bytes + except Exception as e: - error_msg = f"Edge TTS请求失败: {e}" - raise Exception(error_msg) # 抛出异常,让调用方捕获 \ No newline at end of file + + error_msg = f"Edge TTS request failed: {e}" + + raise Exception(error_msg) # Throw exception for caller to catch \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/elevenlabs.py b/main/xiaozhi-server/core/providers/tts/elevenlabs.py index 6decd3e3f..a11b262b2 100644 --- a/main/xiaozhi-server/core/providers/tts/elevenlabs.py +++ b/main/xiaozhi-server/core/providers/tts/elevenlabs.py @@ -9,43 +9,54 @@ logger = setup_logging() class TTSProvider(TTSProviderBase): + """ ElevenLabs TTS Provider Supports high-quality voice synthesis with multiple voices and languages """ + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) - self.api_key = config.get("api_key","sk_7bbbc42db83364614c2e07da3991c16a91256df9e7281f37") - if not self.api_key: + self.api_key = config.get( + "api_key", "sk_7bbbc42db83364614c2e07da3991c16a91256df9e7281f37") + if not self.api_key: raise ValueError("ElevenLabs API key is required") - self.voice_id = config.get("voice_id", "21m00Tcm4TlvDq8ikWAM") # Default to Rachel voice - self.model_id = config.get("model_id", "eleven_multilingual_v2") # Default multilingual model - + + # Default to Rachel voice + self.voice_id = config.get("voice_id", "21m00Tcm4TlvDq8ikWAM") + # Default multilingual model + self.model_id = config.get("model_id", "eleven_multilingual_v2") + # ElevenLabs API endpoint + self.api_url = f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}" - + # Voice settings + self.stability = float(config.get("stability", "0.75")) self.similarity_boost = float(config.get("similarity_boost", "0.75")) self.style = float(config.get("style", "0.0")) # For v2 models self.use_speaker_boost = config.get("use_speaker_boost", True) - + # Output format (ElevenLabs supports mp3, pcm, ulaw, mulaw) + self.output_format = config.get("output_format", "mp3_44100_128") self.audio_file_type = "mp3" if "mp3" in self.output_format else "wav" - + # Streaming settings - self.optimize_streaming_latency = int(config.get("optimize_streaming_latency", "0")) - + + self.optimize_streaming_latency = int( + config.get("optimize_streaming_latency", "0")) self.output_file = config.get("output_dir", "tmp/") - model_key_msg = check_model_key("ElevenLabs TTS", self.api_key) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) - + # Validate API key format if self.api_key and len(self.api_key) < 32: - logger.bind(tag=TAG).warning("ElevenLabs API key appears to be too short. Please check your API key.") + logger.bind(tag=TAG).warning( + "ElevenLabs API key appears to be too short. Please check your API key.") async def text_to_speak(self, text, output_file): """ @@ -56,80 +67,139 @@ class TTSProvider(TTSProviderBase): "Content-Type": "application/json", "xi-api-key": self.api_key } - + data = { "text": text, "model_id": self.model_id, "voice_settings": { "stability": self.stability, + "similarity_boost": self.similarity_boost, + "style": self.style, + "use_speaker_boost": self.use_speaker_boost + } + } - + # Add streaming optimization if specified + if self.optimize_streaming_latency > 0: + params = { + "optimize_streaming_latency": self.optimize_streaming_latency, + "output_format": self.output_format + } + else: + params = { + "output_format": self.output_format + } - + try: + response = requests.post( + self.api_url, + json=data, + headers=headers, + params=params, + timeout=30 + ) - + if response.status_code == 200: + if output_file: + with open(output_file, "wb") as audio_file: + audio_file.write(response.content) - logger.bind(tag=TAG).debug(f"ElevenLabs TTS saved to: {output_file}") + + logger.bind(tag=TAG).debug( + f"ElevenLabs TTS saved to: {output_file}") + else: + return response.content + else: - error_data = response.json() if response.headers.get('content-type') == 'application/json' else response.text + + error_data = response.json() if response.headers.get( + 'content-type') == 'application/json' else response.text + raise Exception( + f"ElevenLabs TTS request failed: {response.status_code} - {error_data}" + ) - + except requests.exceptions.Timeout: + raise Exception("ElevenLabs TTS request timed out") + except requests.exceptions.RequestException as e: + raise Exception(f"ElevenLabs TTS network error: {str(e)}") + except Exception as e: + logger.bind(tag=TAG).error(f"ElevenLabs TTS error: {str(e)}") + raise def get_available_voices(self): """ + Helper method to get available voices from ElevenLabs + """ + headers = { + "Accept": "application/json", + "xi-api-key": self.api_key + } - + try: + response = requests.get( + "https://api.elevenlabs.io/v1/voices", + headers=headers + ) - + if response.status_code == 200: + voices = response.json()["voices"] + return [(v["voice_id"], v["name"]) for v in voices] + else: - logger.bind(tag=TAG).error(f"Failed to fetch voices: {response.status_code}") + + logger.bind(tag=TAG).error( + f"Failed to fetch voices: {response.status_code}") + return [] + except Exception as e: + logger.bind(tag=TAG).error(f"Error fetching voices: {str(e)}") - return [] \ No newline at end of file + + return [] diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py index bbf191643..136b07789 100644 --- a/main/xiaozhi-server/core/providers/tts/fishspeech.py +++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py @@ -1,188 +1,319 @@ import base64 + import requests + import ormsgpack + from pathlib import Path + from pydantic import BaseModel, Field, conint, model_validator + from typing_extensions import Annotated + from typing import Literal + from core.utils.util import check_model_key, parse_string_to_list + from core.providers.tts.base import TTSProviderBase + from config.logger import setup_logging TAG = __name__ + logger = setup_logging() - class ServeReferenceAudio(BaseModel): + audio: bytes + text: str @model_validator(mode="before") + def decode_audio(cls, values): + audio = values.get("audio") + if ( + isinstance(audio, str) and len(audio) > 255 - ): # Check if audio is a string (Base64) + + ): # Check if audio is a string (Base64) + try: + values["audio"] = base64.b64decode(audio) + except Exception as e: + # If the audio is not a valid base64 string, we will just ignore it and let the server handle it + pass + return values def __repr__(self) -> str: + return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})" - class ServeTTSRequest(BaseModel): + text: str + chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200 + # Audio format + format: Literal["wav", "pcm", "mp3"] = "wav" + # References audios for in-context learning + references: list[ServeReferenceAudio] = [] + # Reference id + # For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/ + # Just pass 7f92f8afb8ec43bf81429cc1c9199cb1 + reference_id: str | None = None + seed: int | None = None + use_memory_cache: Literal["on", "off"] = "off" + # Normalize text for en & zh, this increase stability for numbers + normalize: bool = True + # not usually used below + streaming: bool = False + max_new_tokens: int = 1024 + top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7 + repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.2 + temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7 class Config: + # Allow arbitrary types for pytorch related types + arbitrary_types_allowed = True - def audio_to_bytes(file_path): + if not file_path or not Path(file_path).exists(): + return None + with open(file_path, "rb") as wav_file: + wav = wav_file.read() + return wav - def read_ref_text(ref_text): - path = Path(ref_text) - if path.exists() and path.is_file(): - with path.open("r", encoding="utf-8") as file: - return file.read() - return ref_text + path = Path(ref_text) + + if path.exists() and path.is_file(): + + with path.open("r", encoding="utf-8") as file: + + return file.read() + + return ref_text class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) self.reference_id = ( + None if not config.get("reference_id") else config.get("reference_id") - ) - self.reference_audio = parse_string_to_list( - config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio") - ) - self.reference_text = parse_string_to_list( - config.get('ref_text')if config.get('ref_text') else config.get("reference_text") - ) - self.format = config.get("response_format", "wav") - self.audio_file_type = config.get("response_format", "wav") - self.api_key = config.get("api_key", "YOUR_API_KEY") - model_key_msg = check_model_key("FishSpeech TTS", self.api_key) - if model_key_msg: - logger.bind(tag=TAG).error(model_key_msg) - return - self.normalize = str(config.get("normalize", True)).lower() in ( - "true", - "1", - "yes", + ) - # 处理空字符串的情况 + self.reference_audio = parse_string_to_list( + + config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio") + + ) + + self.reference_text = parse_string_to_list( + + config.get('ref_text')if config.get('ref_text') else config.get("reference_text") + + ) + + self.format = config.get("response_format", "wav") + + self.audio_file_type = config.get("response_format", "wav") + + self.api_key = config.get("api_key", "YOUR_API_KEY") + + model_key_msg = check_model_key("FishSpeech TTS", self.api_key) + + if model_key_msg: + + logger.bind(tag=TAG).error(model_key_msg) + + return + + self.normalize = str(config.get("normalize", True)).lower() in ( + + "true", + + "1", + + "yes", + + ) + + # Handle empty string cases + channels = config.get("channels", "1") + rate = config.get("rate", "44100") + max_new_tokens = config.get("max_new_tokens", "1024") + chunk_length = config.get("chunk_length", "200") self.channels = int(channels) if channels else 1 + self.rate = int(rate) if rate else 44100 + self.max_new_tokens = int(max_new_tokens) if max_new_tokens else 1024 + self.chunk_length = int(chunk_length) if chunk_length else 200 - # 处理空字符串的情况 + # Handle empty string cases + top_p = config.get("top_p", "0.7") + temperature = config.get("temperature", "0.7") + repetition_penalty = config.get("repetition_penalty", "1.2") self.top_p = float(top_p) if top_p else 0.7 + self.temperature = float(temperature) if temperature else 0.7 + self.repetition_penalty = ( + float(repetition_penalty) if repetition_penalty else 1.2 + ) self.streaming = str(config.get("streaming", False)).lower() in ( + "true", + "1", + "yes", + ) + self.use_memory_cache = config.get("use_memory_cache", "on") + self.seed = int(config.get("seed")) if config.get("seed") else None + self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts") async def text_to_speak(self, text, output_file): + # Prepare reference data + byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio] + ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text] data = { + "text": text, + "references": [ + ServeReferenceAudio(audio=audio if audio else b"", text=text) + for text, audio in zip(ref_texts, byte_audios) + ], + "reference_id": self.reference_id, + "normalize": self.normalize, + "format": self.format, + "max_new_tokens": self.max_new_tokens, + "chunk_length": self.chunk_length, + "top_p": self.top_p, + "repetition_penalty": self.repetition_penalty, + "temperature": self.temperature, + "streaming": self.streaming, + "use_memory_cache": self.use_memory_cache, + "seed": self.seed, + } pydantic_data = ServeTTSRequest(**data) response = requests.post( + self.api_url, + data=ormsgpack.packb( + pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC + ), + headers={ + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/msgpack", + }, + ) if response.status_code == 200: + audio_content = response.content if output_file: + with open(output_file, "wb") as audio_file: + audio_file.write(audio_content) + else: + return audio_content else: + error_msg = f"Request failed with status code {response.status_code}" + print(error_msg) + print(response.json()) - raise Exception(error_msg) + + raise Exception(error_msg) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py index 33586168f..80222fb2d 100644 --- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py +++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py @@ -1,103 +1,185 @@ import requests + from config.logger import setup_logging + from core.providers.tts.base import TTSProviderBase + from core.utils.util import parse_string_to_list TAG = __name__ + logger = setup_logging() class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.url = config.get("url") + self.text_lang = config.get("text_lang", "zh") - self.ref_audio_path = config.get('ref_audio') if config.get('ref_audio') else config.get("ref_audio_path") - self.prompt_text = config.get('ref_text') if config.get('ref_text') else config.get("prompt_text") + + self.ref_audio_path = config.get('ref_audio') if config.get( + 'ref_audio') else config.get("ref_audio_path") + + self.prompt_text = config.get('ref_text') if config.get( + 'ref_text') else config.get("prompt_text") + self.prompt_lang = config.get("prompt_lang", "zh") - # 处理空字符串的情况 + # Handle empty string cases + top_k = config.get("top_k", "5") + top_p = config.get("top_p", "1") + temperature = config.get("temperature", "1") + batch_threshold = config.get("batch_threshold", "0.75") + batch_size = config.get("batch_size", "1") + speed_factor = config.get("speed_factor", "1.0") + seed = config.get("seed", "-1") + repetition_penalty = config.get("repetition_penalty", "1.35") self.top_k = int(top_k) if top_k else 5 + self.top_p = float(top_p) if top_p else 1 + self.temperature = float(temperature) if temperature else 1 - self.batch_threshold = float(batch_threshold) if batch_threshold else 0.75 + + self.batch_threshold = float( + batch_threshold) if batch_threshold else 0.75 + self.batch_size = int(batch_size) if batch_size else 1 + self.speed_factor = float(speed_factor) if speed_factor else 1.0 + self.seed = int(seed) if seed else -1 + self.repetition_penalty = ( + float(repetition_penalty) if repetition_penalty else 1.35 + ) self.text_split_method = config.get("text_split_method", "cut0") self.split_bucket = str(config.get("split_bucket", True)).lower() in ( + "true", + "1", + "yes", + ) + self.return_fragment = str(config.get("return_fragment", False)).lower() in ( + "true", + "1", + "yes", + ) self.streaming_mode = str(config.get("streaming_mode", False)).lower() in ( + "true", + "1", + "yes", + ) self.parallel_infer = str(config.get("parallel_infer", True)).lower() in ( + "true", + "1", + "yes", + ) self.aux_ref_audio_paths = parse_string_to_list( + config.get("aux_ref_audio_paths") + ) + self.audio_file_type = config.get("format", "wav") async def text_to_speak(self, text, output_file): + request_json = { + "text": text, + "text_lang": self.text_lang, + "ref_audio_path": self.ref_audio_path, + "aux_ref_audio_paths": self.aux_ref_audio_paths, + "prompt_text": self.prompt_text, + "prompt_lang": self.prompt_lang, + "top_k": self.top_k, + "top_p": self.top_p, + "temperature": self.temperature, + "text_split_method": self.text_split_method, + "batch_size": self.batch_size, + "batch_threshold": self.batch_threshold, + "split_bucket": self.split_bucket, + "return_fragment": self.return_fragment, + "speed_factor": self.speed_factor, + "streaming_mode": self.streaming_mode, + "seed": self.seed, + "parallel_infer": self.parallel_infer, + "repetition_penalty": self.repetition_penalty, + } resp = requests.post(self.url, json=request_json) + if resp.status_code == 200: + if output_file: + with open(output_file, "wb") as file: + file.write(resp.content) + else: + return resp.content + else: - error_msg = f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}" + + error_msg = f"GPT_SoVITS_V2 TTS request failed: {resp.status_code} - {resp.text}" + logger.bind(tag=TAG).error(error_msg) + raise Exception(error_msg) diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py index a71e11e44..bdc895c9c 100644 --- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py +++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py @@ -1,64 +1,111 @@ import requests + from config.logger import setup_logging + from core.providers.tts.base import TTSProviderBase + from core.utils.util import parse_string_to_list TAG = __name__ + logger = setup_logging() - class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.url = config.get("url") + self.refer_wav_path = config.get('ref_audio')if config.get('ref_audio') else config.get("refer_wav_path") + self.prompt_text = config.get('ref_text')if config.get('ref_text') else config.get("prompt_text") + self.prompt_language = config.get("prompt_language") + self.text_language = config.get("text_language", "audo") - # 处理空字符串的情况 + # Handle empty string cases + top_k = config.get("top_k", "15") + top_p = config.get("top_p", "1.0") + temperature = config.get("temperature", "1.0") + sample_steps = config.get("sample_steps", "32") + speed = config.get("speed", "1.0") self.top_k = int(top_k) if top_k else 15 + self.top_p = float(top_p) if top_p else 1.0 + self.temperature = float(temperature) if temperature else 1.0 + self.sample_steps = int(sample_steps) if sample_steps else 32 + self.speed = float(speed) if speed else 1.0 self.cut_punc = config.get("cut_punc", "") + self.inp_refs = parse_string_to_list(config.get("inp_refs")) + self.if_sr = str(config.get("if_sr", False)).lower() in ("true", "1", "yes") + self.audio_file_type = config.get("format", "wav") async def text_to_speak(self, text, output_file): + request_params = { + "refer_wav_path": self.refer_wav_path, + "prompt_text": self.prompt_text, + "prompt_language": self.prompt_language, + "text": text, + "text_language": self.text_language, + "top_k": self.top_k, + "top_p": self.top_p, + "temperature": self.temperature, + "cut_punc": self.cut_punc, + "speed": self.speed, + "inp_refs": self.inp_refs, + "sample_steps": self.sample_steps, + "if_sr": self.if_sr, + } resp = requests.get(self.url, params=request_params) + if resp.status_code == 200: + if output_file: + with open(output_file, "wb") as file: + file.write(resp.content) + else: + return resp.content + else: - error_msg = f"GPT_SoVITS_V3 TTS请求失败: {resp.status_code} - {resp.text}" + + error_msg = f"GPT_SoVITS_V3 TTS request failed: {resp.status_code} - {resp.text}" + logger.bind(tag=TAG).error(error_msg) - raise Exception(error_msg) + + raise Exception(error_msg) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py index d4c89140e..907562b6f 100644 --- a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py +++ b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py @@ -10,10 +10,10 @@ from config.logger import setup_logging from core.utils import opus_encoder_utils from core.utils.util import check_model_key from core.providers.tts.base import TTSProviderBase +from core.handle.abortHandle import handleAbortMessage from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType from asyncio import Task - TAG = __name__ logger = setup_logging() @@ -21,744 +21,1299 @@ PROTOCOL_VERSION = 0b0001 DEFAULT_HEADER_SIZE = 0b0001 # Message Type: + FULL_CLIENT_REQUEST = 0b0001 AUDIO_ONLY_RESPONSE = 0b1011 FULL_SERVER_RESPONSE = 0b1001 ERROR_INFORMATION = 0b1111 # Message Type Specific Flags + MsgTypeFlagNoSeq = 0b0000 # Non-terminal packet with no sequence MsgTypeFlagPositiveSeq = 0b1 # Non-terminal packet with sequence > 0 MsgTypeFlagLastNoSeq = 0b10 # last packet with no sequence MsgTypeFlagNegativeSeq = 0b11 # Payload contains event number (int32) MsgTypeFlagWithEvent = 0b100 + # Message Serialization + NO_SERIALIZATION = 0b0000 JSON = 0b0001 + # Message Compression + COMPRESSION_NO = 0b0000 COMPRESSION_GZIP = 0b0001 - EVENT_NONE = 0 EVENT_Start_Connection = 1 - EVENT_FinishConnection = 2 +EVENT_ConnectionStarted = 50 # Successful connection +# Connection failed (possibly unable to pass permission authentication) +EVENT_ConnectionFailed = 51 +EVENT_ConnectionFinished = 52 # Connection ended -EVENT_ConnectionStarted = 50 # 成功建连 +# Uplink Session events -EVENT_ConnectionFailed = 51 # 建连失败(可能是无法通过权限认证) - -EVENT_ConnectionFinished = 52 # 连接结束 - -# 上行Session事件 EVENT_StartSession = 100 -EVENT_CancelSession = 101 EVENT_FinishSession = 102 -# 下行Session事件 -EVENT_SessionStarted = 150 -EVENT_SessionCanceled = 151 -EVENT_SessionFinished = 152 +# Downlink Session events + +EVENT_SessionStarted = 150 +EVENT_SessionFinished = 152 EVENT_SessionFailed = 153 -# 上行通用事件 +# Uplink general events + EVENT_TaskRequest = 200 -# 下行TTS事件 +# Downlink TTS events + EVENT_TTSSentenceStart = 350 - EVENT_TTSSentenceEnd = 351 - EVENT_TTSResponse = 352 class Header: + def __init__( + self, + protocol_version=PROTOCOL_VERSION, + header_size=DEFAULT_HEADER_SIZE, + message_type: int = 0, + message_type_specific_flags: int = 0, + serial_method: int = NO_SERIALIZATION, + compression_type: int = COMPRESSION_NO, + reserved_data=0, + ): + self.header_size = header_size + self.protocol_version = protocol_version + self.message_type = message_type + self.message_type_specific_flags = message_type_specific_flags + self.serial_method = serial_method + self.compression_type = compression_type + self.reserved_data = reserved_data def as_bytes(self) -> bytes: + return bytes( + [ + (self.protocol_version << 4) | self.header_size, + (self.message_type << 4) | self.message_type_specific_flags, + (self.serial_method << 4) | self.compression_type, + self.reserved_data, + ] + ) class Optional: + def __init__( + self, event: int = EVENT_NONE, sessionId: str = None, sequence: int = None + ): + self.event = event + self.sessionId = sessionId + self.errorCode: int = 0 + self.connectionId: str | None = None + self.response_meta_json: str | None = None + self.sequence = sequence - # 转成 byte 序列 + # Convert to byte sequence + def as_bytes(self) -> bytes: + option_bytes = bytearray() + if self.event != EVENT_NONE: + option_bytes.extend(self.event.to_bytes(4, "big", signed=True)) + if self.sessionId is not None: + session_id_bytes = str.encode(self.sessionId) + size = len(session_id_bytes).to_bytes(4, "big", signed=True) + option_bytes.extend(size) + option_bytes.extend(session_id_bytes) + if self.sequence is not None: + option_bytes.extend(self.sequence.to_bytes(4, "big", signed=True)) + return option_bytes class Response: + def __init__(self, header: Header, optional: Optional): + self.optional = optional + self.header = header + self.payload: bytes | None = None def __str__(self): + return super().__str__() class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.ws = None + self.interface_type = InterfaceType.DUAL_STREAM - self._monitor_task = None # 监听任务引用 + + self._monitor_task = None # Monitor task reference + self.appId = config.get("appid") + self.access_token = config.get("access_token") + self.cluster = config.get("cluster") + self.resource_id = config.get("resource_id") + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("speaker") - speech_rate = config.get("speech_rate", "0") - loudness_rate = config.get("loudness_rate", "0") - pitch = config.get("pitch", "0") - self.speech_rate = int(speech_rate) if speech_rate else 0 - self.loudness_rate = int(loudness_rate) if loudness_rate else 0 - self.pitch = int(pitch) if pitch else 0 + self.ws_url = config.get("ws_url") + self.authorization = config.get("authorization") - self.header = {"Authorization": f"{self.authorization}{self.access_token}"} + + self.header = { + "Authorization": f"{self.authorization}{self.access_token}"} + self.enable_two_way = True + self.tts_text = "" + self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( + sample_rate=16000, channels=1, frame_size_ms=60 + ) + model_key_msg = check_model_key("TTS", self.access_token) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) async def open_audio_channels(self, conn): + try: + await super().open_audio_channels(conn) + except Exception as e: - logger.bind(tag=TAG).error(f"Failed to open audio channels: {str(e)}") + + logger.bind(tag=TAG).error( + f"Failed to open audio channels: {str(e)}") + self.ws = None + raise async def _ensure_connection(self): - """建立新的WebSocket连接""" + """Establish new WebSocket connection""" + try: - if self.ws: - logger.bind(tag=TAG).info(f"使用已有链接...") - return self.ws - logger.bind(tag=TAG).info("开始建立新连接...") + + logger.bind(tag=TAG).info( + "Starting to establish new connection...") + ws_header = { + "X-Api-App-Key": self.appId, + "X-Api-Access-Key": self.access_token, + "X-Api-Resource-Id": self.resource_id, + "X-Api-Connect-Id": uuid.uuid4(), + } + self.ws = await websockets.connect( + self.ws_url, additional_headers=ws_header, max_size=1000000000 + ) - logger.bind(tag=TAG).info("WebSocket连接建立成功") + + logger.bind(tag=TAG).info( + "WebSocket connection established successfully") + return self.ws + except Exception as e: - logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}") + + logger.bind(tag=TAG).error( + f"Failed to establish connection: {str(e)}") + self.ws = None + raise def tts_text_priority_thread(self): - """火山引擎双流式TTS的文本处理线程""" + """Volcano Engine dual-stream TTS text processing thread""" + while not self.conn.stop_event.is_set(): + try: + message = self.tts_text_queue.get(timeout=1) + logger.bind(tag=TAG).debug( - f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}" + + f"Received TTS task | {message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}" + ) - if message.sentence_type == SentenceType.FIRST: - self.conn.client_abort = False - if self.conn.client_abort: - try: - logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") - asyncio.run_coroutine_threadsafe( - self.cancel_session(self.conn.sentence_id), - loop=self.conn.loop, - ) - continue - except Exception as e: - logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}") - continue + + logger.bind(tag=TAG).info( + "Received interruption signal, terminating TTS text processing thread") + + continue if message.sentence_type == SentenceType.FIRST: - # 初始化参数 - try: - if not getattr(self.conn, "sentence_id", None): - self.conn.sentence_id = uuid.uuid4().hex - logger.bind(tag=TAG).info(f"自动生成新的 会话ID: {self.conn.sentence_id}") - logger.bind(tag=TAG).info("开始启动TTS会话...") + # Initialize parameters + + try: + + if not getattr(self.conn, "sentence_id", None): + + self.conn.sentence_id = uuid.uuid4().hex + + logger.bind(tag=TAG).info( + f"Auto-generated new session ID: {self.conn.sentence_id}") + + logger.bind(tag=TAG).info("Starting TTS session...") + future = asyncio.run_coroutine_threadsafe( + self.start_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + future.result() + + self.tts_audio_first_sentence = True + self.before_stop_play_files.clear() - logger.bind(tag=TAG).info("TTS会话启动成功") + + logger.bind(tag=TAG).info( + "TTS session started successfully") + except Exception as e: - logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") + + logger.bind(tag=TAG).error( + f"Failed to start TTS session: {str(e)}") + continue elif ContentType.TEXT == message.content_type: + if message.content_detail: + try: + logger.bind(tag=TAG).debug( - f"开始发送TTS文本: {message.content_detail}" + + f"Starting to send TTS text: {message.content_detail}" + ) + future = asyncio.run_coroutine_threadsafe( - self.text_to_speak(message.content_detail, None), + + self.text_to_speak( + message.content_detail, None), + loop=self.conn.loop, + ) + future.result() - logger.bind(tag=TAG).debug("TTS文本发送成功") + + logger.bind(tag=TAG).debug( + "TTS text sent successfully") + except Exception as e: - logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}") + + logger.bind(tag=TAG).error( + f"Failed to send TTS text: {str(e)}") + continue elif ContentType.FILE == message.content_type: + logger.bind(tag=TAG).info( - f"添加音频文件到待播放列表: {message.content_file}" + + f"Adding audio file to playback queue: {message.content_file}" + + ) + + self.before_stop_play_files.append( + + (message.content_file, message.content_detail) + ) - if message.content_file and os.path.exists(message.content_file): - # 先处理文件音频数据 - file_audio = self._process_audio_file(message.content_file) - self.before_stop_play_files.append( - (file_audio, message.content_detail) - ) if message.sentence_type == SentenceType.LAST: + try: - logger.bind(tag=TAG).info("开始结束TTS会话...") + + logger.bind(tag=TAG).info( + "Starting to end TTS session...") + future = asyncio.run_coroutine_threadsafe( + self.finish_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + future.result() + except Exception as e: - logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}") + + logger.bind(tag=TAG).error( + f"Failed to end TTS session: {str(e)}") + continue except queue.Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( - f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + + f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" + ) + continue async def text_to_speak(self, text, _): - """发送文本到TTS服务""" + """Send text to TTS service""" + try: - # 建立新连接 + + # Establish new connection + if self.ws is None: - logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本") + + logger.bind(tag=TAG).warning( + f"WebSocket connection does not exist, terminating text sending") + return - # 过滤Markdown + # Filter Markdown + filtered_text = MarkdownCleaner.clean_markdown(text) - # 发送文本 + # Send text + await self.send_text(self.voice, filtered_text, self.conn.sentence_id) + return + except Exception as e: - logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}") + + logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}") + if self.ws: + try: + await self.ws.close() + except: + pass - self.ws = None + + self.ws = None + raise async def start_session(self, session_id): - logger.bind(tag=TAG).info(f"开始会话~~{session_id}") - try: - # 会话开始时检测上个会话的监听状态 - if ( - self._monitor_task is not None - and isinstance(self._monitor_task, Task) - and not self._monitor_task.done() - ): - logger.bind(tag=TAG).info("检测到未完成的上个会话,关闭监听任务和连接...") - await self.close() - # 建立新连接 + logger.bind(tag=TAG).info(f"Starting session ~~ {session_id}") + + try: + + task = self._monitor_task + + if ( + + task is not None + + and isinstance(task, Task) + + and not task.done() + + ): + + logger.bind(tag=TAG).info( + "Waiting for previous monitor task to end...") + + if self.ws is not None: + + logger.bind(tag=TAG).info( + "Forcing close of previous WebSocket connection to wake up monitor task...") + + try: + + await self.ws.close() + + except Exception as e: + + logger.bind(tag=TAG).warning( + f"Exception closing previous ws: {e}") + + self.ws = None + + try: + + await asyncio.wait_for(task, timeout=8) + + except Exception as e: + + logger.bind(tag=TAG).warning( + f"Exception waiting for monitor task: {e}") + + self._monitor_task = None + + # Establish new connection + await self._ensure_connection() - # 启动监听任务 - self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) + # Start monitor task + + self._monitor_task = asyncio.create_task( + self._start_monitor_tts_response()) header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + serial_method=JSON, + ).as_bytes() + optional = Optional( + event=EVENT_StartSession, sessionId=session_id + ).as_bytes() + payload = self.get_payload_bytes( + event=EVENT_StartSession, speaker=self.voice + ) + await self.send_event(self.ws, header, optional, payload) - logger.bind(tag=TAG).info("会话启动请求已发送") + + logger.bind(tag=TAG).info("Session start request sent") + except Exception as e: - logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") - # 确保清理资源 - await self.close() + + logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}") + + # Ensure resource cleanup + + if hasattr(self, "_monitor_task"): + + try: + + self._monitor_task.cancel() + + await self._monitor_task + + except: + + pass + + self._monitor_task = None + + if self.ws: + + try: + + await self.ws.close() + + except: + + pass + + self.ws = None + raise async def finish_session(self, session_id): - logger.bind(tag=TAG).info(f"关闭会话~~{session_id}") - try: - if self.ws: - header = Header( - message_type=FULL_CLIENT_REQUEST, - message_type_specific_flags=MsgTypeFlagWithEvent, - serial_method=JSON, - ).as_bytes() - optional = Optional( - event=EVENT_FinishSession, sessionId=session_id - ).as_bytes() - payload = str.encode("{}") - await self.send_event(self.ws, header, optional, payload) - logger.bind(tag=TAG).info("会话结束请求已发送") - # 等待监听任务完成 - if self._monitor_task: + logger.bind(tag=TAG).info(f"Closing session ~~ {session_id}") + + try: + + if self.ws: + + header = Header( + + message_type=FULL_CLIENT_REQUEST, + + message_type_specific_flags=MsgTypeFlagWithEvent, + + serial_method=JSON, + + ).as_bytes() + + optional = Optional( + + event=EVENT_FinishSession, sessionId=session_id + + ).as_bytes() + + payload = str.encode("{}") + + await self.send_event(self.ws, header, optional, payload) + + logger.bind(tag=TAG).info("Session end request sent") + + # Wait for monitor task to complete + + if hasattr(self, "_monitor_task"): + try: + await self._monitor_task + except Exception as e: + logger.bind(tag=TAG).error( - f"等待监听任务完成时发生错误: {str(e)}" + + f"Error occurred while waiting for monitor task completion: {str(e)}" + ) + finally: + self._monitor_task = None - except Exception as e: - logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}") - # 确保清理资源 - await self.close() - raise + # Close connection + + await self.close() - async def cancel_session(self,session_id): - logger.bind(tag=TAG).info(f"取消会话,释放服务端资源~~{session_id}") - try: - if self.ws: - header = Header( - message_type=FULL_CLIENT_REQUEST, - message_type_specific_flags=MsgTypeFlagWithEvent, - serial_method=JSON, - ).as_bytes() - optional = Optional( - event=EVENT_CancelSession, sessionId=session_id - ).as_bytes() - payload = str.encode("{}") - await self.send_event(self.ws, header, optional, payload) - logger.bind(tag=TAG).info("会话取消请求已发送") except Exception as e: - logger.bind(tag=TAG).error(f"取消会话失败: {str(e)}") - # 确保清理资源 - await self.close() + + logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}") + + # Ensure resource cleanup + + if hasattr(self, "_monitor_task"): + + try: + + self._monitor_task.cancel() + + await self._monitor_task + + except: + + pass + + self._monitor_task = None + + if self.ws: + + try: + + await self.ws.close() + + except: + + pass + + self.ws = None + raise async def close(self): - """资源清理方法""" - # 取消监听任务 - if self._monitor_task: - try: - self._monitor_task.cancel() - await self._monitor_task - except asyncio.CancelledError: - pass - except Exception as e: - logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}") - self._monitor_task = None + """Resource cleanup method""" if self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None async def _start_monitor_tts_response(self): - """监听TTS响应""" + """Monitor TTS responses""" + opus_datas_cache = [] + is_first_sentence = True - first_sentence_segment_count = 0 # 添加计数器 + + first_sentence_segment_count = 0 # Add counter + try: - session_finished = False # 标记会话是否正常结束 + while not self.conn.stop_event.is_set(): + try: - # 确保 `recv()` 运行在同一个 event loop + + # Ensure `recv()` runs on the same event loop + msg = await self.ws.recv() + res = self.parser_response(msg) + self.print_response(res, "send_text res:") - if res.optional.event == EVENT_SessionCanceled: - logger.bind(tag=TAG).debug(f"释放服务端资源成功~~") - session_finished = True + # Check if client aborted + + if self.conn.client_abort: + + logger.bind(tag=TAG).info( + "Received interruption signal, terminating TTS response monitoring") + break - elif res.optional.event == EVENT_TTSSentenceStart: + + if res.optional.event == EVENT_TTSSentenceStart: + json_data = json.loads(res.payload.decode("utf-8")) + self.tts_text = json_data.get("text", "") - logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}") - self.tts_audio_queue.put( - (SentenceType.FIRST, [], self.tts_text) - ) - opus_datas_cache = [] - first_sentence_segment_count = 0 # 重置计数器 - elif ( - res.optional.event == EVENT_TTSResponse - and res.header.message_type == AUDIO_ONLY_RESPONSE - ): - logger.bind(tag=TAG).debug(f"推送数据到队列里面~~") - opus_datas = self.wav_to_opus_data_audio_raw(res.payload) + logger.bind(tag=TAG).debug( - f"推送数据到队列里面帧数~~{len(opus_datas)}" + f"Sentence voice generation started: {self.tts_text}") + + self.tts_audio_queue.put( + + (SentenceType.FIRST, [], self.tts_text) + ) + + opus_datas_cache = [] + + first_sentence_segment_count = 0 # Reset counter + + elif ( + + res.optional.event == EVENT_TTSResponse + + and res.header.message_type == AUDIO_ONLY_RESPONSE + + ): + + logger.bind(tag=TAG).debug(f"Pushing data to queue ~~") + + opus_datas = self.wav_to_opus_data_audio_raw( + res.payload) + + logger.bind(tag=TAG).debug( + + f"Pushing data to queue frame count ~~ {len(opus_datas)}" + + ) + if is_first_sentence: + first_sentence_segment_count += 1 + if first_sentence_segment_count <= 6: + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus_datas, None) + ) + else: - opus_datas_cache.extend(opus_datas) + + opus_datas_cache = opus_datas_cache + opus_datas + else: - # 后续句子缓存 - opus_datas_cache.extend(opus_datas) + + # Cache subsequent sentences + + opus_datas_cache = opus_datas_cache + opus_datas + elif res.optional.event == EVENT_TTSSentenceEnd: - logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}") + + logger.bind(tag=TAG).info( + f"Sentence voice generation successful: {self.tts_text}") + if not is_first_sentence or first_sentence_segment_count > 10: - # 发送缓存的数据 + + # Send cached data + self.tts_audio_queue.put( + (SentenceType.MIDDLE, opus_datas_cache, None) + ) - # 第一句话结束后,将标志设置为False + + # After first sentence ends, set flag to False + is_first_sentence = False + elif res.optional.event == EVENT_SessionFinished: - logger.bind(tag=TAG).debug(f"会话结束~~") + + logger.bind(tag=TAG).debug(f"Session ended ~~") + self._process_before_stop_play_files() - session_finished = True + break + except websockets.ConnectionClosed: - logger.bind(tag=TAG).warning("WebSocket连接已关闭") + + logger.bind(tag=TAG).warning("WebSocket connection closed") + break + except Exception as e: + logger.bind(tag=TAG).error( + f"Error in _start_monitor_tts_response: {e}" + ) + traceback.print_exc() + break - # 仅在连接异常时才关闭 - if not session_finished and self.ws: - try: - await self.ws.close() - except: - pass - self.ws = None - # 监听任务退出时清理引用 + finally: + + # Ensure resource cleanup + + if self.ws: + + try: + + await self.ws.close() + + except: + + pass + + self.ws = None + + # Clear reference when monitor task exits + self._monitor_task = None async def send_event( + self, + ws: websockets.WebSocketClientProtocol, + header: bytes, + optional: bytes | None = None, + payload: bytes = None, + ): + try: + full_client_request = bytearray(header) + if optional is not None: + full_client_request.extend(optional) + if payload is not None: + payload_size = len(payload).to_bytes(4, "big", signed=True) + full_client_request.extend(payload_size) + full_client_request.extend(payload) + await ws.send(full_client_request) + except websockets.ConnectionClosed: + logger.bind(tag=TAG).error(f"ConnectionClosed") + raise async def send_text(self, speaker: str, text: str, session_id): + header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + serial_method=JSON, + ).as_bytes() - optional = Optional(event=EVENT_TaskRequest, sessionId=session_id).as_bytes() + + optional = Optional(event=EVENT_TaskRequest, + sessionId=session_id).as_bytes() + payload = self.get_payload_bytes( + event=EVENT_TaskRequest, text=text, speaker=speaker + ) + return await self.send_event(self.ws, header, optional, payload) - # 读取 res 数组某段 字符串内容 + # Read res array segment string content + def read_res_content(self, res: bytes, offset: int): - content_size = int.from_bytes(res[offset : offset + 4], "big", signed=True) + + content_size = int.from_bytes( + res[offset: offset + 4], "big", signed=True) + offset += 4 - content = str(res[offset : offset + content_size]) + + content = str(res[offset: offset + content_size]) + offset += content_size + return content, offset - # 读取 payload + # Read payload + def read_res_payload(self, res: bytes, offset: int): - payload_size = int.from_bytes(res[offset : offset + 4], "big", signed=True) + + payload_size = int.from_bytes( + res[offset: offset + 4], "big", signed=True) + offset += 4 - payload = res[offset : offset + payload_size] + + payload = res[offset: offset + payload_size] + offset += payload_size + return payload, offset def parser_response(self, res) -> Response: + if isinstance(res, str): + raise RuntimeError(res) + response = Response(Header(), Optional()) - # 解析结果 + + # Parse result + # header + header = response.header + num = 0b00001111 + header.protocol_version = res[0] >> 4 & num + header.header_size = res[0] & 0x0F + header.message_type = (res[1] >> 4) & num + header.message_type_specific_flags = res[1] & 0x0F + header.serialization_method = res[2] >> num + header.message_compression = res[2] & 0x0F + header.reserved = res[3] - # + offset = 4 + optional = response.optional + if header.message_type == FULL_SERVER_RESPONSE or AUDIO_ONLY_RESPONSE: + # read event + if header.message_type_specific_flags == MsgTypeFlagWithEvent: - optional.event = int.from_bytes(res[offset:8], "big", signed=True) + + optional.event = int.from_bytes( + res[offset:8], "big", signed=True) + offset += 4 + if optional.event == EVENT_NONE: + return response + # read connectionId + elif optional.event == EVENT_ConnectionStarted: - optional.connectionId, offset = self.read_res_content(res, offset) + + optional.connectionId, offset = self.read_res_content( + res, offset) + elif optional.event == EVENT_ConnectionFailed: + optional.response_meta_json, offset = self.read_res_content( + res, offset + ) + elif ( + optional.event == EVENT_SessionStarted + or optional.event == EVENT_SessionFailed + or optional.event == EVENT_SessionFinished + ): - optional.sessionId, offset = self.read_res_content(res, offset) + + optional.sessionId, offset = self.read_res_content( + res, offset) + optional.response_meta_json, offset = self.read_res_content( + res, offset + ) + else: - optional.sessionId, offset = self.read_res_content(res, offset) - response.payload, offset = self.read_res_payload(res, offset) + + optional.sessionId, offset = self.read_res_content( + res, offset) + + response.payload, offset = self.read_res_payload(res, offset) elif header.message_type == ERROR_INFORMATION: + optional.errorCode = int.from_bytes( - res[offset : offset + 4], "big", signed=True + + res[offset: offset + 4], "big", signed=True + ) + offset += 4 + response.payload, offset = self.read_res_payload(res, offset) + return response async def start_connection(self): + header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + ).as_bytes() + optional = Optional(event=EVENT_Start_Connection).as_bytes() + payload = str.encode("{}") + return await self.send_event(self.ws, header, optional, payload) def print_response(self, res, tag_msg: str): - logger.bind(tag=TAG).debug(f"===>{tag_msg} header:{res.header.__dict__}") - logger.bind(tag=TAG).debug(f"===>{tag_msg} optional:{res.optional.__dict__}") + + logger.bind(tag=TAG).debug( + f"===> {tag_msg} header:{res.header.__dict__}") + + logger.bind(tag=TAG).debug( + f"===> {tag_msg} optional:{res.optional.__dict__}") def get_payload_bytes( + self, + uid="1234", + event=EVENT_NONE, + text="", + speaker="", + audio_format="pcm", + audio_sample_rate=16000, + ): + return str.encode( + json.dumps( + { + "user": {"uid": uid}, + "event": event, + "namespace": "BidirectionalTTS", + "req_params": { + "text": text, + "speaker": speaker, + "audio_params": { + "format": audio_format, + "sample_rate": audio_sample_rate, - "speech_rate": self.speech_rate, - "loudness_rate": self.loudness_rate + }, + }, - "additions": { - "post_process": { - "pitch": self.pitch - } - } + } + ) + ) def wav_to_opus_data_audio_raw(self, raw_data_var, is_end=False): + opus_datas = self.opus_encoder.encode_pcm_to_opus(raw_data_var, is_end) + return opus_datas def to_tts(self, text: str) -> list: - """非流式生成音频数据,用于生成音频及测试场景 + """Non-streaming audio data generation for audio generation and testing scenarios Args: - text: 要转换的文本 + + text: Text to convert Returns: - list: 音频数据列表 + + list: Audio data list + """ + try: - # 创建事件循环 + + # Create event loop + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) - # 生成会话ID + # Generate session ID + session_id = uuid.uuid4().__str__().replace("-", "") - # 存储音频数据 + # Store audio data + audio_data = [] async def _generate_audio(): - # 创建新的WebSocket连接 + + # Create new WebSocket connection + ws_header = { + "X-Api-App-Key": self.appId, + "X-Api-Access-Key": self.access_token, + "X-Api-Resource-Id": self.resource_id, + "X-Api-Connect-Id": uuid.uuid4(), + } + ws = await websockets.connect( + self.ws_url, additional_headers=ws_header, max_size=1000000000 + ) try: - # 启动会话 + + # Start session + header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + serial_method=JSON, + ).as_bytes() + optional = Optional( + event=EVENT_StartSession, sessionId=session_id + ).as_bytes() + payload = self.get_payload_bytes( + event=EVENT_StartSession, speaker=self.voice + ) + await self.send_event(ws, header, optional, payload) - # 发送文本 + # Send text + header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + serial_method=JSON, + ).as_bytes() + optional = Optional( + event=EVENT_TaskRequest, sessionId=session_id + ).as_bytes() + payload = self.get_payload_bytes( + event=EVENT_TaskRequest, text=text, speaker=self.voice + ) + await self.send_event(ws, header, optional, payload) - # 发送结束会话请求 + # Send session end request + header = Header( + message_type=FULL_CLIENT_REQUEST, + message_type_specific_flags=MsgTypeFlagWithEvent, + serial_method=JSON, + ).as_bytes() + optional = Optional( + event=EVENT_FinishSession, sessionId=session_id + ).as_bytes() + payload = str.encode("{}") + await self.send_event(ws, header, optional, payload) - # 接收音频数据 + # Receive audio data + while True: + msg = await ws.recv() + res = self.parser_response(msg) if ( + res.optional.event == EVENT_TTSResponse + and res.header.message_type == AUDIO_ONLY_RESPONSE + ): - opus_datas = self.wav_to_opus_data_audio_raw(res.payload) + + opus_datas = self.wav_to_opus_data_audio_raw( + res.payload) + audio_data.extend(opus_datas) + elif res.optional.event == EVENT_SessionFinished: + break finally: - # 清理资源 + + # Cleanup resources + try: + await ws.close() + except: + pass - # 运行异步任务 + # Run async task + loop.run_until_complete(_generate_audio()) + loop.close() return audio_data except Exception as e: - logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}") - return [] \ No newline at end of file + + logger.bind(tag=TAG).error( + f"Failed to generate audio data: {str(e)}") + + return [] diff --git a/main/xiaozhi-server/core/providers/tts/index_stream.py b/main/xiaozhi-server/core/providers/tts/index_stream.py index c05614a3c..865b5b98f 100644 --- a/main/xiaozhi-server/core/providers/tts/index_stream.py +++ b/main/xiaozhi-server/core/providers/tts/index_stream.py @@ -29,27 +29,28 @@ class TTSProvider(TTSProviderBase): self.before_stop_play_files = [] self.segment_count = 0 - # 创建Opus编码器 需注意接口返回的采样率为24000 + # Create Opus encoder Note: interface returns sample rate of 24000 self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( sample_rate=24000, channels=1, frame_size_ms=60 ) - # 文本缓冲区和PCM缓冲区 + # Text buffer and PCM buffer self.text_buffer = "" self.pcm_buffer = bytearray() def tts_text_priority_thread(self): - """流式文本处理线程""" + """Streaming text processing thread""" while not self.conn.stop_event.is_set(): try: message = self.tts_text_queue.get(timeout=1) if message.sentence_type == SentenceType.FIRST: - # 初始化参数 + # Initialize parameters self.tts_stop_request = False self.processed_chars = 0 self.tts_text_buff = [] self.segment_count = 0 self.before_stop_play_files.clear() + elif ContentType.TEXT == message.content_type: self.tts_text_buff.append(message.content_detail) segment_text = self._get_segment_text() @@ -58,35 +59,39 @@ class TTSProvider(TTSProviderBase): elif ContentType.FILE == message.content_type: logger.bind(tag=TAG).info( - f"添加音频文件到待播放列表: {message.content_file}" + f"Adding audio file to playback queue: {message.content_file}" ) + if message.content_file and os.path.exists(message.content_file): - # 先处理文件音频数据 - file_audio = self._process_audio_file(message.content_file) + # Process file audio data first + file_audio = self._process_audio_file( + message.content_file) self.before_stop_play_files.append( (file_audio, message.content_detail) ) if message.sentence_type == SentenceType.LAST: - # 处理剩余的文本 + # Process remaining text self._process_remaining_text(True) except queue.Empty: continue except Exception as e: logger.bind(tag=TAG).error( - f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" ) def _process_remaining_text(self, is_last=False): - """处理剩余的文本并生成语音 + """Process remaining text and generate speech + Returns: - bool: 是否成功处理了文本 + bool: Whether text was successfully processed """ full_text = "".join(self.tts_text_buff) - remaining_text = full_text[self.processed_chars :] + remaining_text = full_text[self.processed_chars:] if remaining_text: - segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text) + segment_text = textUtils.get_string_no_punctuation_or_emoji( + remaining_text) if segment_text: self.to_tts_single_stream(segment_text, is_last) self.processed_chars += len(full_text) @@ -103,27 +108,27 @@ class TTSProvider(TTSProviderBase): asyncio.run(self.text_to_speak(text, is_last)) except Exception as e: logger.bind(tag=TAG).warning( - f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}" + f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}" ) - max_repeat_time -= 1 - if max_repeat_time > 0: - logger.bind(tag=TAG).info( - f"语音生成成功: {text},重试{5 - max_repeat_time}次" - ) - else: - logger.bind(tag=TAG).error( - f"语音生成失败: {text},请检查网络或服务是否正常" - ) + max_repeat_time -= 1 + if max_repeat_time > 0: + logger.bind(tag=TAG).info( + f"Speech generation successful: {text}, retried {5 - max_repeat_time} times" + ) + else: + logger.bind(tag=TAG).error( + f"Speech generation failed: {text}, please check network or service status" + ) + except Exception as e: logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}") finally: return None async def text_to_speak(self, text, is_last): - """流式处理TTS音频,每句只推送一次音频列表""" + """Stream process TTS audio, push audio list only once per sentence""" payload = {"text": text, "character": self.voice} - frame_bytes = int( self.opus_encoder.sample_rate * self.opus_encoder.channels # 1 @@ -131,25 +136,25 @@ class TTSProvider(TTSProviderBase): / 1000 * 2 ) # 16-bit = 2 bytes + try: async with aiohttp.ClientSession() as session: async with session.post(self.api_url, json=payload, timeout=10) as resp: - if resp.status != 200: logger.bind(tag=TAG).error( - f"TTS请求失败: {resp.status}, {await resp.text()}" + f"TTS request failed: {resp.status}, {await resp.text()}" ) self.tts_audio_queue.put((SentenceType.LAST, [], None)) return self.pcm_buffer.clear() opus_datas_cache = [] - self.tts_audio_queue.put((SentenceType.FIRST, [], text)) - # 处理音频流数据 + # Process audio stream data async for chunk in resp.content.iter_any(): - data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk + data = chunk[0] if isinstance( + chunk, (list, tuple)) else chunk if not data: continue @@ -161,8 +166,9 @@ class TTSProvider(TTSProviderBase): opus = self.opus_encoder.encode_pcm_to_opus( frame, end_of_stream=False ) + if opus: - if self.segment_count < 10: # 前10个片段直接发送 + if self.segment_count < 10: # Send first 10 segments directly self.tts_audio_queue.put( (SentenceType.MIDDLE, opus, None) ) @@ -170,72 +176,74 @@ class TTSProvider(TTSProviderBase): else: opus_datas_cache.extend(opus) - # flush 剩余不足一帧的数据 + # Flush remaining data that doesn't fill a complete frame if self.pcm_buffer: opus = self.opus_encoder.encode_pcm_to_opus( bytes(self.pcm_buffer), end_of_stream=True ) + if opus: - if self.segment_count < 10: # 前10个片段直接发送 - # 直接发送 + if self.segment_count < 10: # Send first 10 segments directly + # Send directly self.tts_audio_queue.put( (SentenceType.MIDDLE, opus, None) ) self.segment_count += 1 else: - # 后续片段缓存 + # Cache subsequent segments opus_datas_cache.extend(opus) + self.pcm_buffer.clear() - # 如果不是前10个片段,发送缓存的数据 + # If not in first 10 segments, send cached data if self.segment_count >= 10 and opus_datas_cache: self.tts_audio_queue.put( (SentenceType.MIDDLE, opus_datas_cache, None) ) - # 如果是最后一段,输出音频获取完毕 + # If this is the last segment, audio acquisition complete if is_last: self._process_before_stop_play_files() except Exception as e: - logger.bind(tag=TAG).error(f"TTS请求异常: {e}") + logger.bind(tag=TAG).error(f"TTS request exception: {e}") self.tts_audio_queue.put((SentenceType.LAST, [], None)) async def close(self): - """资源清理""" + """Resource cleanup""" await super().close() if hasattr(self, "opus_encoder"): self.opus_encoder.close() def to_tts(self, text: str) -> list: - """非流式TTS处理,用于测试及保存音频文件的场景 + """Non-streaming TTS processing for testing and saving audio files Args: - text: 要转换的文本 + text: Text to convert Returns: - list: 返回opus编码后的音频数据列表 + list: Returns opus-encoded audio data list """ start_time = time.time() text = MarkdownCleaner.clean_markdown(text) - payload = {"text": text, "character": self.character} try: with requests.post(self.api_url, json=payload, timeout=5) as response: if response.status_code != 200: logger.bind(tag=TAG).error( - f"TTS请求失败: {response.status_code}, {response.text}" + f"TTS request failed: {response.status_code}, {response.text}" ) return [] - logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒") + logger.info( + f"TTS request successful: {text}, time cost: {time.time() - start_time} seconds") - # 使用opus编码器处理PCM数据 + # Use opus encoder to process PCM data opus_datas = [] pcm_data = response.content - # 计算每帧的字节数 + # Calculate bytes per frame frame_bytes = int( self.opus_encoder.sample_rate * self.opus_encoder.channels @@ -244,21 +252,22 @@ class TTSProvider(TTSProviderBase): * 2 ) - # 分帧处理PCM数据 + # Process PCM data frame by frame for i in range(0, len(pcm_data), frame_bytes): - frame = pcm_data[i : i + frame_bytes] + frame = pcm_data[i: i + frame_bytes] if len(frame) < frame_bytes: - # 最后一帧可能不足,用0填充 + # Last frame might be insufficient, pad with zeros frame = frame + b"\x00" * (frame_bytes - len(frame)) opus = self.opus_encoder.encode_pcm_to_opus( frame, end_of_stream=(i + frame_bytes >= len(pcm_data)) ) + if opus: opus_datas.extend(opus) return opus_datas except Exception as e: - logger.bind(tag=TAG).error(f"TTS请求异常: {e}") - return [] \ No newline at end of file + logger.bind(tag=TAG).error(f"TTS request exception: {e}") + return [] diff --git a/main/xiaozhi-server/core/providers/tts/linkerai.py b/main/xiaozhi-server/core/providers/tts/linkerai.py index 94da16213..47975abb8 100644 --- a/main/xiaozhi-server/core/providers/tts/linkerai.py +++ b/main/xiaozhi-server/core/providers/tts/linkerai.py @@ -14,7 +14,6 @@ from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType TAG = __name__ logger = setup_logging() - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) @@ -24,68 +23,69 @@ class TTSProvider(TTSProviderBase): self.api_url = config.get("api_url") self.audio_format = "pcm" self.before_stop_play_files = [] - self.segment_count = 0 # 添加片段计数器 - - # 创建Opus编码器 + self.segment_count = 0 # Add segment counter + + # Create Opus encoder self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( sample_rate=16000, channels=1, frame_size_ms=60 ) - - # 添加文本缓冲区 + + # Add text buffer self.text_buffer = "" - - # PCM缓冲区 + # PCM buffer self.pcm_buffer = bytearray() - + ################################################################################### - # linkerai单流式TTS重写父类的方法--开始 + # linkerai single-stream TTS override parent class methods - Start ################################################################################### - + def tts_text_priority_thread(self): - """流式文本处理线程""" + """Streaming text processing thread""" while not self.conn.stop_event.is_set(): try: message = self.tts_text_queue.get(timeout=1) if message.sentence_type == SentenceType.FIRST: - # 初始化参数 + # Initialize parameters self.tts_stop_request = False self.processed_chars = 0 self.tts_text_buff = [] self.segment_count = 0 self.before_stop_play_files.clear() + elif ContentType.TEXT == message.content_type: self.tts_text_buff.append(message.content_detail) segment_text = self._get_segment_text() if segment_text: self.to_tts_single_stream(segment_text) - + elif ContentType.FILE == message.content_type: logger.bind(tag=TAG).info( - f"添加音频文件到待播放列表: {message.content_file}" + f"Adding audio file to playback queue: {message.content_file}" ) + if message.content_file and os.path.exists(message.content_file): - # 先处理文件音频数据 + # Process file audio data first file_audio = self._process_audio_file(message.content_file) self.before_stop_play_files.append( (file_audio, message.content_detail) ) - + if message.sentence_type == SentenceType.LAST: - # 处理剩余的文本 + # Process remaining text self._process_remaining_text(True) - + except queue.Empty: continue except Exception as e: logger.bind(tag=TAG).error( - f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" + f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}" ) - + def _process_remaining_text(self, is_last=False): - """处理剩余的文本并生成语音 - + """Process remaining text and generate speech + Returns: - bool: 是否成功处理了文本 + bool: Whether text was successfully processed """ full_text = "".join(self.tts_text_buff) remaining_text = full_text[self.processed_chars :] @@ -98,7 +98,7 @@ class TTSProvider(TTSProviderBase): self._process_before_stop_play_files() else: self._process_before_stop_play_files() - + def to_tts_single_stream(self, text, is_last=False): try: max_repeat_time = 5 @@ -107,37 +107,38 @@ class TTSProvider(TTSProviderBase): asyncio.run(self.text_to_speak(text, is_last)) except Exception as e: logger.bind(tag=TAG).warning( - f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}" + f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}" ) + max_repeat_time -= 1 - - if max_repeat_time > 0: - logger.bind(tag=TAG).info( - f"语音生成成功: {text},重试{5 - max_repeat_time}次" - ) - else: - logger.bind(tag=TAG).error( - f"语音生成失败: {text},请检查网络或服务是否正常" - ) + if max_repeat_time > 0: + logger.bind(tag=TAG).info( + f"Speech generation successful: {text}, retried {5 - max_repeat_time} times" + ) + else: + logger.bind(tag=TAG).error( + f"Speech generation failed: {text}, please check network or service status" + ) + except Exception as e: logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}") finally: return None - + ################################################################################### - # linkerai单流式TTS重写父类的方法--结束 + # linkerai single-stream TTS override parent class methods - End ################################################################################### - + async def text_to_speak(self, text, is_last): - """流式处理TTS音频,每句只推送一次音频列表""" + """Stream process TTS audio, push audio list only once per sentence""" await self._tts_request(text, is_last) - + async def close(self): - """资源清理""" + """Resource cleanup""" await super().close() if hasattr(self, "opus_encoder"): self.opus_encoder.close() - + async def _tts_request(self, text: str, is_last: bool) -> None: params = { "tts_text": text, @@ -146,14 +147,15 @@ class TTSProvider(TTSProviderBase): "stream": "true", "target_sr": 16000, "audio_format": "pcm", - "instruct_text": "请生成一段自然流畅的语音", + "instruct_text": "Please generate natural and fluent speech", } + headers = { "Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json", } - - # 一帧 PCM 所需字节数:60 ms × 16 kHz × 1 ch × 2 B = 1 920 + + # PCM bytes per frame: 60 ms × 16 kHz × 1 ch × 2 B = 1920 frame_bytes = int( self.opus_encoder.sample_rate * self.opus_encoder.channels # 1 @@ -161,94 +163,93 @@ class TTSProvider(TTSProviderBase): / 1000 * 2 ) # 16-bit = 2 bytes - + try: async with aiohttp.ClientSession() as session: async with session.get( self.api_url, params=params, headers=headers, timeout=10 ) as resp: - if resp.status != 200: logger.bind(tag=TAG).error( - f"TTS请求失败: {resp.status}, {await resp.text()}" + f"TTS request failed: {resp.status}, {await resp.text()}" ) self.tts_audio_queue.put((SentenceType.LAST, [], None)) return - + self.pcm_buffer.clear() opus_datas_cache = [] - self.tts_audio_queue.put((SentenceType.FIRST, [], text)) - - # 兼容 iter_chunked / iter_chunks / iter_any + + # Compatible with iter_chunked / iter_chunks / iter_any async for chunk in resp.content.iter_any(): data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk if not data: continue - - # 拼到 buffer + + # Append to buffer self.pcm_buffer.extend(data) - - # 够一帧就编码 + + # Encode when enough for one frame while len(self.pcm_buffer) >= frame_bytes: frame = bytes(self.pcm_buffer[:frame_bytes]) del self.pcm_buffer[:frame_bytes] - opus = self.opus_encoder.encode_pcm_to_opus( frame, end_of_stream=False ) + if opus: - if self.segment_count < 10: # 前10个片段直接发送 + if self.segment_count < 10: # Send first 10 segments directly self.tts_audio_queue.put( (SentenceType.MIDDLE, opus, None) ) self.segment_count += 1 else: opus_datas_cache.extend(opus) - - # flush 剩余不足一帧的数据 + + # Flush remaining data that doesn't fill a complete frame if self.pcm_buffer: opus = self.opus_encoder.encode_pcm_to_opus( bytes(self.pcm_buffer), end_of_stream=True ) + if opus: - if self.segment_count < 10: # 前10个片段直接发送 - # 直接发送 + if self.segment_count < 10: # Send first 10 segments directly + # Send directly self.tts_audio_queue.put( (SentenceType.MIDDLE, opus, None) ) self.segment_count += 1 else: - # 后续片段缓存 + # Cache subsequent segments opus_datas_cache.extend(opus) + self.pcm_buffer.clear() - - # 如果不是前10个片段,发送缓存的数据 + + # If not in first 10 segments, send cached data if self.segment_count >= 10 and opus_datas_cache: self.tts_audio_queue.put( (SentenceType.MIDDLE, opus_datas_cache, None) ) - - # 如果是最后一段,输出音频获取完毕 + + # If this is the last segment, audio acquisition complete if is_last: self._process_before_stop_play_files() - + except Exception as e: - logger.bind(tag=TAG).error(f"TTS请求异常: {e}") + logger.bind(tag=TAG).error(f"TTS request exception: {e}") self.tts_audio_queue.put((SentenceType.LAST, [], None)) - + def to_tts(self, text: str) -> list: - """非流式TTS处理,用于测试及保存音频文件的场景 - + """Non-streaming TTS processing for testing and saving audio files + Args: - text: 要转换的文本 - + text: Text to convert + Returns: - list: 返回opus编码后的音频数据列表 + list: Returns opus-encoded audio data list """ start_time = time.time() text = MarkdownCleaner.clean_markdown(text) - params = { "tts_text": text, "spk_id": self.voice, @@ -256,30 +257,31 @@ class TTSProvider(TTSProviderBase): "stream": False, "target_sr": 16000, "audio_format": self.audio_format, - "instruct_text": "请生成一段自然流畅的语音", + "instruct_text": "Please generate natural and fluent speech", } + headers = { "Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json", } - + try: with requests.get( self.api_url, params=params, headers=headers, timeout=5 ) as response: if response.status_code != 200: logger.bind(tag=TAG).error( - f"TTS请求失败: {response.status_code}, {response.text}" + f"TTS request failed: {response.status_code}, {response.text}" ) return [] - - logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒") - - # 使用opus编码器处理PCM数据 + + logger.info(f"TTS request successful: {text}, time cost: {time.time() - start_time} seconds") + + # Use opus encoder to process PCM data opus_datas = [] pcm_data = response.content - - # 计算每帧的字节数 + + # Calculate bytes per frame frame_bytes = int( self.opus_encoder.sample_rate * self.opus_encoder.channels @@ -287,22 +289,23 @@ class TTSProvider(TTSProviderBase): / 1000 * 2 ) - - # 分帧处理PCM数据 + + # Process PCM data frame by frame for i in range(0, len(pcm_data), frame_bytes): frame = pcm_data[i : i + frame_bytes] if len(frame) < frame_bytes: - # 最后一帧可能不足,用0填充 + # Last frame might be insufficient, pad with zeros frame = frame + b"\x00" * (frame_bytes - len(frame)) - + opus = self.opus_encoder.encode_pcm_to_opus( frame, end_of_stream=(i + frame_bytes >= len(pcm_data)) ) + if opus: opus_datas.extend(opus) - + return opus_datas - + except Exception as e: - logger.bind(tag=TAG).error(f"TTS请求异常: {e}") - return [] \ No newline at end of file + logger.bind(tag=TAG).error(f"TTS request exception: {e}") + return [] diff --git a/main/xiaozhi-server/core/providers/tts/minimax.py b/main/xiaozhi-server/core/providers/tts/minimax.py index 75e25e2ee..1c9e08e52 100644 --- a/main/xiaozhi-server/core/providers/tts/minimax.py +++ b/main/xiaozhi-server/core/providers/tts/minimax.py @@ -6,18 +6,18 @@ from datetime import datetime from core.providers.tts.base import TTSProviderBase from core.utils.util import parse_string_to_list - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) self.group_id = config.get("group_id") self.api_key = config.get("api_key") self.model = config.get("model") + if config.get("private_voice"): self.voice = config.get("private_voice") else: self.voice = config.get("voice_id") - + default_voice_setting = { "voice_id": "female-shaonv", "speed": 1, @@ -25,6 +25,7 @@ class TTSProvider(TTSProviderBase): "pitch": 0, "emotion": "happy", } + default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} defult_audio_setting = { "sample_rate": 32000, @@ -32,20 +33,23 @@ class TTSProvider(TTSProviderBase): "format": "mp3", "channel": 1, } + self.voice_setting = { **default_voice_setting, **config.get("voice_setting", {}), } + self.pronunciation_dict = { **default_pronunciation_dict, **config.get("pronunciation_dict", {}), } + self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})} self.timber_weights = parse_string_to_list(config.get("timber_weights")) - + if self.voice: self.voice_setting["voice_id"] = self.voice - + self.host = "api.minimax.chat" self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}" self.header = { @@ -53,13 +57,13 @@ class TTSProvider(TTSProviderBase): "Authorization": f"Bearer {self.api_key}", } self.audio_file_type = defult_audio_setting.get("format", "mp3") - + def generate_filename(self, extension=".mp3"): return os.path.join( self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}", ) - + async def text_to_speak(self, text, output_file): request_json = { "model": self.model, @@ -69,19 +73,21 @@ class TTSProvider(TTSProviderBase): "pronunciation_dict": self.pronunciation_dict, "audio_setting": self.audio_setting, } - + if type(self.timber_weights) is list and len(self.timber_weights) > 0: request_json["timber_weights"] = self.timber_weights request_json["voice_setting"]["voice_id"] = "" - + try: resp = requests.post( self.api_url, json.dumps(request_json), headers=self.header ) - # 检查返回请求数据的status_code是否为0 + + # Check if response data status_code is 0 if resp.json()["base_resp"]["status_code"] == 0: data = resp.json()["data"]["audio"] audio_bytes = bytes.fromhex(data) + if output_file: with open(output_file, "wb") as file_to_save: file_to_save.write(audio_bytes) @@ -91,5 +97,6 @@ class TTSProvider(TTSProviderBase): raise Exception( f"{__name__} status_code: {resp.status_code} response: {resp.content}" ) + except Exception as e: raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py b/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py index 605b3efd4..569782bc1 100644 --- a/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py +++ b/main/xiaozhi-server/core/providers/tts/minimax_httpstream.py @@ -7,18 +7,18 @@ from typing import Iterator, Optional, Union from core.providers.tts.base import TTSProviderBase from core.utils.util import parse_string_to_list - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) self.group_id = config.get("group_id") self.api_key = config.get("api_key") self.model = config.get("model") + if config.get("private_voice"): self.voice = config.get("private_voice") else: self.voice = config.get("voice_id") - + default_voice_setting = { "voice_id": "female-shaonv", "speed": 1, @@ -26,6 +26,7 @@ class TTSProvider(TTSProviderBase): "pitch": 0, "emotion": "happy", } + default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} defult_audio_setting = { "sample_rate": 32000, @@ -33,20 +34,23 @@ class TTSProvider(TTSProviderBase): "format": "mp3", "channel": 1, } + self.voice_setting = { **default_voice_setting, **config.get("voice_setting", {}), } + self.pronunciation_dict = { **default_pronunciation_dict, **config.get("pronunciation_dict", {}), } + self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})} self.timber_weights = parse_string_to_list(config.get("timber_weights")) - + if self.voice: self.voice_setting["voice_id"] = self.voice - + self.host = "api.minimax.chat" self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}" self.header = { @@ -54,15 +58,15 @@ class TTSProvider(TTSProviderBase): "Authorization": f"Bearer {self.api_key}", } self.audio_file_type = defult_audio_setting.get("format", "mp3") - + def generate_filename(self, extension=".mp3"): return os.path.join( self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}", ) - + async def text_to_speak(self, text, output_file): - """非流式语音合成(保留原有实现)""" + """Non-streaming speech synthesis (preserves original implementation)""" request_json = { "model": self.model, "text": text, @@ -71,18 +75,20 @@ class TTSProvider(TTSProviderBase): "pronunciation_dict": self.pronunciation_dict, "audio_setting": self.audio_setting, } - + if type(self.timber_weights) is list and len(self.timber_weights) > 0: request_json["timber_weights"] = self.timber_weights request_json["voice_setting"]["voice_id"] = "" - + try: resp = requests.post( self.api_url, json.dumps(request_json), headers=self.header ) + if resp.json()["base_resp"]["status_code"] == 0: data = resp.json()["data"]["audio"] audio_bytes = bytes.fromhex(data) + if output_file: with open(output_file, "wb") as file_to_save: file_to_save.write(audio_bytes) @@ -92,19 +98,21 @@ class TTSProvider(TTSProviderBase): raise Exception( f"{__name__} status_code: {resp.status_code} response: {resp.content}" ) + except Exception as e: raise Exception(f"{__name__} error: {e}") - + def text_to_speak_stream( - self, - text: str, + self, + text: str, chunk_callback: Optional[callable] = None ) -> Iterator[bytes]: """ - 流式语音合成方法 - :param text: 要合成的文本 - :param chunk_callback: 可选的回调函数,用于处理每个音频块 - :return: 生成器,每次产生一个音频数据块(bytes) + Streaming speech synthesis method + + :param text: Text to synthesize + :param chunk_callback: Optional callback function to process each audio chunk + :return: Generator that yields an audio data chunk (bytes) each time """ request_json = { "model": self.model, @@ -114,11 +122,11 @@ class TTSProvider(TTSProviderBase): "pronunciation_dict": self.pronunciation_dict, "audio_setting": self.audio_setting, } - + if isinstance(self.timber_weights, list) and len(self.timber_weights) > 0: request_json["timber_weights"] = self.timber_weights request_json["voice_setting"]["voice_id"] = "" - + try: with requests.post( self.api_url, @@ -126,67 +134,67 @@ class TTSProvider(TTSProviderBase): headers=self.header, stream=True ) as response: - - # 检查HTTP状态码 + # Check HTTP status code if response.status_code != 200: raise Exception( f"HTTP error: {response.status_code}, response: {response.text}" ) - # 处理流式响应 + # Process streaming response for line in response.iter_lines(): - if line: # 过滤空行 - # 检查是否为数据行 (SSE格式) + if line: # Filter empty lines + # Check if it's a data line (SSE format) if line.startswith(b'data:'): try: - data = json.loads(line[5:].strip()) # 去掉"data:"前缀 + data = json.loads(line[5:].strip()) # Remove "data:" prefix - # 检查API状态码 + # Check API status code if data.get("base_resp", {}).get("status_code", -1) != 0: raise Exception( f"API error: {data.get('base_resp', {}).get('status_msg')}" ) - # 跳过非音频数据块 + # Skip non-audio data chunks if "extra_info" in data: continue - - # 提取音频数据 + + # Extract audio data audio_hex = data.get("data", {}).get("audio") if audio_hex: audio_chunk = bytes.fromhex(audio_hex) if chunk_callback: chunk_callback(audio_chunk) yield audio_chunk - + except json.JSONDecodeError: - # 忽略JSON解析错误(可能是心跳包等) + # Ignore JSON parsing errors (might be heartbeat packets, etc.) continue except Exception as e: raise e - + except Exception as e: raise Exception(f"{__name__} stream error: {e}") - + def save_stream_to_file( - self, - text: str, + self, + text: str, output_file: Optional[str] = None, progress_callback: Optional[callable] = None ) -> str: """ - 流式合成并保存到文件 - :param text: 要合成的文本 - :param output_file: 输出文件路径,如果为None则自动生成 - :param progress_callback: 可选的回调函数,接收已写入的字节数 - :return: 保存的文件路径 + Stream synthesis and save to file + + :param text: Text to synthesize + :param output_file: Output file path, auto-generated if None + :param progress_callback: Optional callback function that receives bytes written + :return: Saved file path """ if not output_file: output_file = self.generate_filename(extension=f".{self.audio_file_type}") os.makedirs(os.path.dirname(output_file), exist_ok=True) - total_bytes = 0 + try: with open(output_file, "wb") as audio_file: for audio_chunk in self.text_to_speak_stream(text): @@ -195,18 +203,21 @@ class TTSProvider(TTSProviderBase): total_bytes += len(audio_chunk) if progress_callback: progress_callback(total_bytes) + return output_file + except Exception as e: - # 清理可能创建的不完整文件 + # Clean up potentially created incomplete file if os.path.exists(output_file): os.remove(output_file) raise e - + def stream_to_audio_player(self, text: str, player_command: list = None): """ - 流式合成并直接播放音频 - :param text: 要合成的文本 - :param player_command: 音频播放器命令,默认使用mpv + Stream synthesis and play audio directly + + :param text: Text to synthesize + :param player_command: Audio player command, defaults to mpv """ if player_command is None: player_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"] @@ -223,8 +234,9 @@ class TTSProvider(TTSProviderBase): for audio_chunk in self.text_to_speak_stream(text): player_process.stdin.write(audio_chunk) player_process.stdin.flush() - + player_process.stdin.close() player_process.wait() + except Exception as e: - raise Exception(f"Audio player error: {e}") \ No newline at end of file + raise Exception(f"Audio player error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py b/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py index bda6b47fa..7a9707559 100644 --- a/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py +++ b/main/xiaozhi-server/core/providers/tts/minimax_webSocket.py @@ -15,8 +15,8 @@ class TTSProvider(TTSProviderBase): self.group_id = config.get("group_id") self.api_key = config.get("api_key") self.model = config.get("model") - - # 初始化语音设置 + + # Initialize voice settings default_voice_setting = { "voice_id": "female-shaonv", "speed": 1, @@ -24,52 +24,59 @@ class TTSProvider(TTSProviderBase): "pitch": 0, "emotion": "happy", } - default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]} + + default_pronunciation_dict = { + "tone": ["处理/(chu3)(li3)", "危险/dangerous"]} default_audio_setting = { "sample_rate": 32000, "bitrate": 128000, "format": "mp3", "channel": 1, } - - # 合并配置 + + # Merge configurations self.voice_setting = { **default_voice_setting, **config.get("voice_setting", {}), } + self.pronunciation_dict = { **default_pronunciation_dict, **config.get("pronunciation_dict", {}), } + self.audio_setting = { - **default_audio_setting, + **default_audio_setting, **config.get("audio_setting", {}) } - self.timber_weights = parse_string_to_list(config.get("timber_weights")) - - # 设置语音ID + + self.timber_weights = parse_string_to_list( + config.get("timber_weights")) + + # Set voice ID if config.get("private_voice"): self.voice_setting["voice_id"] = config.get("private_voice") elif config.get("voice_id"): self.voice_setting["voice_id"] = config.get("voice_id") - - # WebSocket配置 + + # WebSocket configuration self.ws_url = "wss://api.minimaxi.com/ws/v1/t2a_v2" self.headers = { "Authorization": f"Bearer {self.api_key}", "GroupId": self.group_id } + self.audio_file_type = self.audio_setting.get("format", "mp3") def generate_filename(self, extension=".mp3"): - """生成唯一的音频文件名""" + """Generate unique audio filename""" return os.path.join( self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}", ) async def _establish_connection(self): - """建立WebSocket连接""" + """Establish WebSocket connection""" ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE @@ -80,17 +87,19 @@ class TTSProvider(TTSProviderBase): additional_headers=self.headers, ssl=ssl_context ) + connected = json.loads(await ws.recv()) if connected.get("event") == "connected_success": - print("连接成功") + print("Connection successful") return ws return None + except Exception as e: - print(f"连接失败: {e}") + print(f"Connection failed: {e}") return None async def _start_task(self, websocket): - """发送任务开始请求""" + """Send task start request""" start_msg = { "event": "task_start", "model": self.model, @@ -98,7 +107,7 @@ class TTSProvider(TTSProviderBase): "pronunciation_dict": self.pronunciation_dict, "audio_setting": self.audio_setting } - + if self.timber_weights and len(self.timber_weights) > 0: start_msg["timber_weights"] = self.timber_weights start_msg["voice_setting"]["voice_id"] = "" @@ -108,7 +117,7 @@ class TTSProvider(TTSProviderBase): return response.get("event") == "task_started" async def _continue_task(self, websocket, text): - """发送继续请求并收集音频数据""" + """Send continue request and collect audio data""" await websocket.send(json.dumps({ "event": "task_continue", "text": text @@ -121,36 +130,37 @@ class TTSProvider(TTSProviderBase): audio_chunks.append(response["data"]["audio"]) if response.get("is_final"): break + return "".join(audio_chunks) async def _close_connection(self, websocket): - """关闭连接""" + """Close connection""" if websocket: await websocket.send(json.dumps({"event": "task_finish"})) await websocket.close() - print("连接已关闭") + print("Connection closed") async def text_to_speak(self, text, output_file=None): - """主方法:文本转语音""" + """Main method: text to speech""" ws = await self._establish_connection() if not ws: - raise Exception("无法建立WebSocket连接") + raise Exception("Unable to establish WebSocket connection") try: if not await self._start_task(ws): - raise Exception("任务启动失败") + raise Exception("Task start failed") hex_audio = await self._continue_task(ws, text) audio_bytes = bytes.fromhex(hex_audio) - # 保存到文件或返回二进制数据 + # Save to file or return binary data if output_file: with open(output_file, "wb") as f: f.write(audio_bytes) - print(f"音频已保存为{output_file}") + print(f"Audio saved as {output_file}") return output_file else: - # 返回音频二进制数据(不播放) + # Return audio binary data (no playback) return audio_bytes finally: @@ -158,23 +168,22 @@ class TTSProvider(TTSProviderBase): async def main(): - """测试用主函数""" - # 示例配置 + """Test main function""" + # Example configuration config = { - "group_id": "YOUR_GROUP_ID", # 替换为实际的group_id - "api_key": "YOUR_API_KEY", # 替换为实际的api_key - "model": "your-model", # 替换为实际的模型名称 + "group_id": "YOUR_GROUP_ID", # Replace with actual group_id + "api_key": "YOUR_API_KEY", # Replace with actual api_key + "model": "your-model", # Replace with actual model name "voice_id": "male-qn-qingse", "voice_setting": { "speed": 1.2, "emotion": "happy" } } - + tts = TTSProvider(config, delete_audio_file=True) output_file = tts.generate_filename() - await tts.text_to_speak("这是一个测试文本,用于验证流式语音合成功能", output_file) - + await tts.text_to_speak("This is a test text to verify streaming speech synthesis functionality", output_file) if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file + asyncio.run(main()) diff --git a/main/xiaozhi-server/core/providers/tts/openai.py b/main/xiaozhi-server/core/providers/tts/openai.py index 20bf9a96a..571d02c19 100644 --- a/main/xiaozhi-server/core/providers/tts/openai.py +++ b/main/xiaozhi-server/core/providers/tts/openai.py @@ -11,7 +11,8 @@ class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) self.api_key = config.get("api_key") - self.api_url = config.get("api_url", "https://api.openai.com/v1/audio/speech") + self.api_url = config.get( + "api_url", "https://api.openai.com/v1/audio/speech") self.model = config.get("model", "tts-1") if config.get("private_voice"): self.voice = config.get("private_voice") @@ -20,11 +21,11 @@ class TTSProvider(TTSProviderBase): self.response_format = config.get("format", "wav") self.audio_file_type = config.get("format", "wav") - # 处理空字符串的情况 + # Handle empty string case speed = config.get("speed", "1.0") self.speed = float(speed) if speed else 1.0 - self.output_file = config.get("output_dir", "tmp/") + model_key_msg = check_model_key("TTS", self.api_key) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) @@ -34,6 +35,7 @@ class TTSProvider(TTSProviderBase): "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", } + data = { "model": self.model, "input": text, @@ -41,7 +43,9 @@ class TTSProvider(TTSProviderBase): "response_format": "wav", "speed": self.speed, } + response = requests.post(self.api_url, json=data, headers=headers) + if response.status_code == 200: if output_file: with open(output_file, "wb") as audio_file: @@ -50,5 +54,5 @@ class TTSProvider(TTSProviderBase): return response.content else: raise Exception( - f"OpenAI TTS请求失败: {response.status_code} - {response.text}" + f"OpenAI TTS request failed: {response.status_code} - {response.text}" ) diff --git a/main/xiaozhi-server/core/providers/tts/paddle_speech.py b/main/xiaozhi-server/core/providers/tts/paddle_speech.py index 891678e07..37a7d3bb6 100644 --- a/main/xiaozhi-server/core/providers/tts/paddle_speech.py +++ b/main/xiaozhi-server/core/providers/tts/paddle_speech.py @@ -12,7 +12,6 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) @@ -23,28 +22,28 @@ class TTSProvider(TTSProviderBase): self.speed = config.get("speed", 1.0) self.volume = config.get("volume", 1.0) self.save_path = config.get("save_path", "./streaming_tts.wav") - + async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1, - bits_per_sample: int = 16) -> bytes: + bits_per_sample: int = 16) -> bytes: """ - 将 PCM 数据转换为 WAV 文件并返回字节数据 - :param pcm_data: PCM 数据(原始字节流) - :param sample_rate: 音频采样率,默认为24000 - :param num_channels: 声道数,默认为单声道 - :param bits_per_sample: 每个样本的位数,默认为16 - :return: WAV 格式的字节数据 + Convert PCM data to WAV file and return byte data + :param pcm_data: PCM data (raw byte stream) + :param sample_rate: Audio sample rate, default 24000 + :param num_channels: Number of channels, default mono + :param bits_per_sample: Bits per sample, default 16 + :return: WAV format byte data """ - byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16位PCM + byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16-bit PCM wav_io = io.BytesIO() - + with wave.open(wav_io, "wb") as wav_file: wav_file.setnchannels(num_channels) wav_file.setsampwidth(bits_per_sample // 8) wav_file.setframerate(sample_rate) wav_file.writeframes(byte_data.tobytes()) - + return wav_io.getvalue() - + async def text_to_speak(self, text, output_file): if self.protocol == "websocket": return await self.text_streaming(text, output_file) @@ -52,7 +51,7 @@ class TTSProvider(TTSProviderBase): return await self.text(text, output_file) else: raise ValueError("Unsupported protocol. Please use 'websocket' or 'http'.") - + async def text(self, text, output_file): request_json = { "text": text, @@ -62,7 +61,7 @@ class TTSProvider(TTSProviderBase): "sample_rate": self.sample_rate, "save_path": self.save_path } - + try: async with aiohttp.ClientSession() as session: async with session.post(self.url, json=request_json) as resp: @@ -71,6 +70,7 @@ class TTSProvider(TTSProviderBase): if resp_json.get("success"): data = resp_json["result"] audio_bytes = base64.b64decode(data["audio"]) + if output_file: with open(output_file, "wb") as file_to_save: file_to_save.write(audio_bytes) @@ -82,71 +82,78 @@ class TTSProvider(TTSProviderBase): else: raise Exception( f"HTTP Error: {resp.status} - {await resp.text()} while processing text: {text}") + except Exception as e: raise Exception(f"Error during TTS HTTP request: {e} while processing text: {text}") - + async def text_streaming(self, text, output_file): try: - # 使用 websockets 异步连接到 WebSocket 服务器 + # Use websockets to asynchronously connect to WebSocket server async with websockets.connect(self.url) as ws: - # 发送开始请求 + # Send start request start_request = { "task": "tts", "signal": "start" } + await ws.send(json.dumps(start_request)) - - # 接收开始响应并提取 session_id + + # Receive start response and extract session_id start_response = await ws.recv() - start_response = json.loads(start_response) # 解析 JSON 响应 + start_response = json.loads(start_response) # Parse JSON response + if start_response.get("status") != 0: - raise Exception(f"连接失败: {start_response.get('signal')}") - + raise Exception(f"Connection failed: {start_response.get('signal')}") + session_id = start_response.get("session") - - # 发送待合成的文本数据 + + # Send text data to be synthesized data_request = { "text": text, "spk_id": self.spk_id, } + await ws.send(json.dumps(data_request)) - + audio_chunks = b"" - timeout_seconds = 60 # 设置超时 + timeout_seconds = 60 # Set timeout + try: while True: response = await asyncio.wait_for(ws.recv(), timeout=timeout_seconds) - response = json.loads(response) # 解析 JSON 响应 + response = json.loads(response) # Parse JSON response + status = response.get("status") - - if status == 2: # 最后一个数据包 + if status == 2: # Last data packet break else: - # 拼接音频数据(base64 编码的 PCM 数据) + # Concatenate audio data (base64 encoded PCM data) audio_chunks += base64.b64decode(response.get("audio")) + except asyncio.TimeoutError: - raise Exception(f"WebSocket 超时:等待音频数据超过 {timeout_seconds} 秒") - - # 将拼接后的 PCM 数据转换为 WAV 格式 + raise Exception(f"WebSocket timeout: waiting for audio data exceeded {timeout_seconds} seconds") + + # Convert concatenated PCM data to WAV format wav_data = await self.pcm_to_wav(audio_chunks) - - # 结束请求 + + # End request end_request = { "task": "tts", "signal": "end", - "session": session_id # 会话 ID 必须与开始请求中的一致 + "session": session_id # Session ID must match the start request } + await ws.send(json.dumps(end_request)) - - # 接收结束响应避免服务抛出异常 + + # Receive end response to avoid service throwing exception await ws.recv() - - # 返回或保存音频数据 + + # Return or save audio data if output_file: with open(output_file, "wb") as file_to_save: file_to_save.write(wav_data) else: return wav_data - + except Exception as e: - raise Exception(f"Error during TTS WebSocket request: {e} while processing text: {text}") \ No newline at end of file + raise Exception(f"Error during TTS WebSocket request: {e} while processing text: {text}") diff --git a/main/xiaozhi-server/core/providers/tts/siliconflow.py b/main/xiaozhi-server/core/providers/tts/siliconflow.py index b85cebf43..342a195ff 100644 --- a/main/xiaozhi-server/core/providers/tts/siliconflow.py +++ b/main/xiaozhi-server/core/providers/tts/siliconflow.py @@ -1,25 +1,25 @@ import requests from core.providers.tts.base import TTSProviderBase - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) self.model = config.get("model") self.access_token = config.get("access_token") + if config.get("private_voice"): self.voice = config.get("private_voice") else: self.voice = config.get("voice") + self.response_format = config.get("response_format", "mp3") self.audio_file_type = config.get("response_format", "mp3") self.sample_rate = config.get("sample_rate") self.speed = float(config.get("speed", 1.0)) self.gain = config.get("gain") - self.host = "api.siliconflow.cn" self.api_url = f"https://{self.host}/v1/audio/speech" - + async def text_to_speak(self, text, output_file): request_json = { "model": self.model, @@ -27,19 +27,24 @@ class TTSProvider(TTSProviderBase): "voice": self.voice, "response_format": self.response_format, } + headers = { "Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json", } + try: response = requests.request( "POST", self.api_url, json=request_json, headers=headers ) + data = response.content + if output_file: with open(output_file, "wb") as file_to_save: file_to_save.write(data) else: return data + except Exception as e: raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/tencent.py b/main/xiaozhi-server/core/providers/tts/tencent.py index a24936324..27dba96a4 100644 --- a/main/xiaozhi-server/core/providers/tts/tencent.py +++ b/main/xiaozhi-server/core/providers/tts/tencent.py @@ -8,57 +8,59 @@ import requests from datetime import datetime, timezone from core.providers.tts.base import TTSProviderBase - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) self.appid = config.get("appid") self.secret_id = config.get("secret_id") self.secret_key = config.get("secret_key") + if config.get("private_voice"): self.voice = config.get("private_voice") else: self.voice = int(config.get("voice")) - self.api_url = "https://tts.tencentcloudapi.com" # 正确的API端点 + + self.api_url = "https://tts.tencentcloudapi.com" # Correct API endpoint self.region = config.get("region") self.output_file = config.get("output_dir") self.audio_file_type = config.get("format", "wav") - + def _get_auth_headers(self, request_body): - """生成鉴权请求头""" - # 获取当前UTC时间戳 + """Generate authentication request headers""" + # Get current UTC timestamp timestamp = int(time.time()) - - # 使用UTC时间计算日期 + + # Calculate date using UTC time utc_date = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime( "%Y-%m-%d" ) - - # 服务名称必须是 "tts" + + # Service name must be "tts" service = "tts" - - # 拼接凭证范围 + + # Construct credential scope credential_scope = f"{utc_date}/{service}/tc3_request" - - # 使用TC3-HMAC-SHA256签名方法 + + # Use TC3-HMAC-SHA256 signature method algorithm = "TC3-HMAC-SHA256" - - # 构建规范请求字符串 + + # Build canonical request string http_request_method = "POST" canonical_uri = "/" canonical_querystring = "" - - # 请求头必须包含host和content-type,且按字典序排列 + + # Request headers must include host and content-type, sorted in dictionary order canonical_headers = ( f"content-type:application/json\n" f"host:tts.tencentcloudapi.com\n" ) + signed_headers = "content-type;host" - - # 请求体哈希值 + + # Request body hash value payload = json.dumps(request_body) payload_hash = hashlib.sha256(payload.encode("utf-8")).hexdigest() - - # 构建规范请求字符串 + + # Build canonical request string canonical_request = ( f"{http_request_method}\n" f"{canonical_uri}\n" @@ -67,41 +69,41 @@ class TTSProvider(TTSProviderBase): f"{signed_headers}\n" f"{payload_hash}" ) - - # 计算规范请求的哈希值 + + # Calculate hash value of canonical request hashed_canonical_request = hashlib.sha256( canonical_request.encode("utf-8") ).hexdigest() - - # 构建待签名字符串 + + # Build string to sign string_to_sign = ( f"{algorithm}\n" f"{timestamp}\n" f"{credential_scope}\n" f"{hashed_canonical_request}" ) - - # 计算签名密钥 + + # Calculate signature key secret_date = self._hmac_sha256( f"TC3{self.secret_key}".encode("utf-8"), utc_date ) secret_service = self._hmac_sha256(secret_date, service) secret_signing = self._hmac_sha256(secret_service, "tc3_request") - - # 计算签名 + + # Calculate signature signature = hmac.new( secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256 ).hexdigest() - - # 构建授权头 + + # Build authorization header authorization = ( f"{algorithm} " f"Credential={self.secret_id}/{credential_scope}, " f"SignedHeaders={signed_headers}, " f"Signature={signature}" ) - - # 构建请求头 + + # Build request headers headers = { "Content-Type": "application/json", "Host": "tts.tencentcloudapi.com", @@ -112,45 +114,46 @@ class TTSProvider(TTSProviderBase): "X-TC-Region": self.region, "X-TC-Language": "zh-CN", } - + return headers - + def _hmac_sha256(self, key, msg): - """HMAC-SHA256加密""" + """HMAC-SHA256 encryption""" if isinstance(msg, str): msg = msg.encode("utf-8") return hmac.new(key, msg, hashlib.sha256).digest() - + async def text_to_speak(self, text, output_file): - # 构建请求体 + # Build request body request_json = { - "Text": text, # 合成语音的源文本 - "SessionId": str(uuid.uuid4()), # 会话ID,随机生成 - "VoiceType": int(self.voice), # 音色 + "Text": text, # Source text for speech synthesis + "SessionId": str(uuid.uuid4()), # Session ID, randomly generated + "VoiceType": int(self.voice), # Voice type } - + try: - # 获取请求头(每次请求都重新生成,以确保时间戳和签名是最新的) + # Get request headers (regenerate for each request to ensure timestamp and signature are up-to-date) headers = self._get_auth_headers(request_json) - - # 发送请求 + + # Send request resp = requests.post( self.api_url, json.dumps(request_json), headers=headers ) - - # 检查响应 + + # Check response if resp.status_code == 200: response_data = resp.json() - - # 检查是否成功 + + # Check if successful if response_data.get("Response", {}).get("Error") is not None: error_info = response_data["Response"]["Error"] raise Exception( - f"API返回错误: {error_info['Code']}: {error_info['Message']}" + f"API returned error: {error_info['Code']}: {error_info['Message']}" ) - - # 解码Base64音频数据 + + # Decode Base64 audio data audio_bytes = base64.b64decode(response_data["Response"].get("Audio")) + if audio_bytes: if output_file: with open(output_file, "wb") as f: @@ -158,10 +161,11 @@ class TTSProvider(TTSProviderBase): else: return audio_bytes else: - raise Exception(f"{__name__}: 没有返回音频数据: {response_data}") + raise Exception(f"{__name__}: No audio data returned: {response_data}") else: raise Exception( f"{__name__} status_code: {resp.status_code} response: {resp.content}" ) + except Exception as e: raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/ttson.py b/main/xiaozhi-server/core/providers/tts/ttson.py index 91deeed96..5c9c4d365 100644 --- a/main/xiaozhi-server/core/providers/tts/ttson.py +++ b/main/xiaozhi-server/core/providers/tts/ttson.py @@ -10,7 +10,6 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() - class TTSProvider(TTSProviderBase): def __init__(self, config, delete_audio_file): super().__init__(config, delete_audio_file) @@ -18,10 +17,12 @@ class TTSProvider(TTSProviderBase): "url", "https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=", ) + if config.get("private_voice"): self.voice = int(config.get("private_voice")) else: self.voice = int(config.get("voice_id", 1695)) + self.token = config.get("token") self.to_lang = config.get("to_lang") self.volume_change_dB = int(config.get("volume_change_dB", 0)) @@ -33,35 +34,37 @@ class TTSProvider(TTSProviderBase): self.audio_file_type = config.get("format", "mp3") self.emotion = int(config.get("emotion", 1)) self.header = {"Content-Type": "application/json"} - + def generate_filename(self, extension=".mp3"): return os.path.join( self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}", ) - + async def text_to_speak(self, text, output_file): url = f"{self.url}{self.token}" result = "firefly" - payload = json.dumps( - { - "to_lang": self.to_lang, - "text": text, - "emotion": self.emotion, - "format": self.format, - "volume_change_dB": self.volume_change_dB, - "voice_id": self.voice, - "pitch_factor": self.pitch_factor, - "speed_factor": self.speed_factor, - "token": self.token, - } - ) - + + payload = json.dumps({ + "to_lang": self.to_lang, + "text": text, + "emotion": self.emotion, + "format": self.format, + "volume_change_dB": self.volume_change_dB, + "voice_id": self.voice, + "pitch_factor": self.pitch_factor, + "speed_factor": self.speed_factor, + "token": self.token, + }) + resp = requests.request("POST", url, data=payload) + if resp.status_code != 200: - logger.bind(tag=TAG).error(f"TTSON 请求失败: {resp.text}") - raise Exception(f"{__name__}: TTS请求失败") + logger.bind(tag=TAG).error(f"TTSON request failed: {resp.text}") + raise Exception(f"{__name__}: TTS request failed") + resp_json = resp.json() + try: result = ( resp_json["url"] @@ -72,17 +75,19 @@ class TTSProvider(TTSProviderBase): + "&voice_audio_path=" + resp_json["voice_path"] ) - + audio_content = requests.get(result) + if output_file: with open(output_file, "wb") as f: f.write(audio_content.content) else: return audio_content.content + voice_path = resp_json.get("voice_path") des_path = output_file shutil.move(voice_path, des_path) - + except Exception as e: print("error:", e) - raise Exception(f"{__name__}: TTS请求失败") + raise Exception(f"{__name__}: TTS request failed") diff --git a/main/xiaozhi-server/core/providers/vad/base.py b/main/xiaozhi-server/core/providers/vad/base.py index 1d8d4c8dd..23c6749e0 100644 --- a/main/xiaozhi-server/core/providers/vad/base.py +++ b/main/xiaozhi-server/core/providers/vad/base.py @@ -3,7 +3,8 @@ from typing import Optional class VADProviderBase(ABC): + @abstractmethod def is_vad(self, conn, data) -> bool: - """检测音频数据中的语音活动""" + """Detect voice activity in audio data""" pass diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py index 2d4fbbead..9988b8266 100644 --- a/main/xiaozhi-server/core/providers/vad/silero.py +++ b/main/xiaozhi-server/core/providers/vad/silero.py @@ -20,69 +20,70 @@ class VADProvider(VADProviderBase): ) self.decoder = opuslib_next.Decoder(16000, 1) - - # 处理空字符串的情况 + # Handle empty string case threshold = config.get("threshold", "0.5") threshold_low = config.get("threshold_low", "0.2") min_silence_duration_ms = config.get("min_silence_duration_ms", "1000") - self.vad_threshold = float(threshold) if threshold else 0.5 self.vad_threshold_low = float(threshold_low) if threshold_low else 0.2 - self.silence_threshold_ms = ( int(min_silence_duration_ms) if min_silence_duration_ms else 1000 ) - # 至少要多少帧才算有语音 + # At least how many frames needed to be considered as having voice self.frame_window_threshold = 3 def is_vad(self, conn, opus_packet): try: pcm_frame = self.decoder.decode(opus_packet, 960) - conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区 + conn.client_audio_buffer.extend( + pcm_frame) # Add new data to buffer - # 处理缓冲区中的完整帧(每次处理512采样点) + # Process complete frames in buffer (process 512 samples each time) client_have_voice = False while len(conn.client_audio_buffer) >= 512 * 2: - # 提取前512个采样点(1024字节) + # Extract first 512 samples (1024 bytes) chunk = conn.client_audio_buffer[: 512 * 2] - conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :] + conn.client_audio_buffer = conn.client_audio_buffer[512 * 2:] - # 转换为模型需要的张量格式 + # Convert to tensor format required by model audio_int16 = np.frombuffer(chunk, dtype=np.int16) audio_float32 = audio_int16.astype(np.float32) / 32768.0 audio_tensor = torch.from_numpy(audio_float32) - # 检测语音活动 + # Detect voice activity with torch.no_grad(): speech_prob = self.model(audio_tensor, 16000).item() - # 双阈值判断 + # Dual threshold judgment if speech_prob >= self.vad_threshold: is_voice = True elif speech_prob <= self.vad_threshold_low: is_voice = False else: is_voice = conn.last_is_voice + # If sound doesn't drop below minimum value, continue previous state, judge as having sound - # 声音没低于最低值则延续前一个状态,判断为有声音 conn.last_is_voice = is_voice - # 更新滑动窗口 + # Update sliding window conn.client_voice_window.append(is_voice) - client_have_voice = (conn.client_voice_window.count(True) >= self.frame_window_threshold) + client_have_voice = (conn.client_voice_window.count( + True) >= self.frame_window_threshold) - # 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话 - if conn.client_have_voice and not client_have_voice: - stop_duration = time.time() * 1000 - conn.last_activity_time - if stop_duration >= self.silence_threshold_ms: - conn.client_voice_stop = True - if client_have_voice: - conn.client_have_voice = True - conn.last_activity_time = time.time() * 1000 + # If previously had voice, but this time no voice, and time difference since last voice exceeds silence threshold, consider sentence finished + if conn.client_have_voice and not client_have_voice: + stop_duration = time.time() * 1000 - conn.last_activity_time + if stop_duration >= self.silence_threshold_ms: + conn.client_voice_stop = True + + if client_have_voice: + conn.client_have_voice = True + conn.last_activity_time = time.time() * 1000 return client_have_voice + except opuslib_next.OpusError as e: - logger.bind(tag=TAG).info(f"解码错误: {e}") + logger.bind(tag=TAG).info(f"Decode error: {e}") except Exception as e: - logger.bind(tag=TAG).error(f"Error processing audio packet: {e}") \ No newline at end of file + logger.bind(tag=TAG).error(f"Error processing audio packet: {e}") diff --git a/main/xiaozhi-server/core/providers/vllm/openai.py b/main/xiaozhi-server/core/providers/vllm/openai.py index 35bc1d7a3..e556a72fe 100644 --- a/main/xiaozhi-server/core/providers/vllm/openai.py +++ b/main/xiaozhi-server/core/providers/vllm/openai.py @@ -37,10 +37,10 @@ class VLLMProvider(VLLMProviderBase): model_key_msg = check_model_key("VLLM", self.api_key) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) - self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url) + self.client = openai.OpenAI( + api_key=self.api_key, base_url=self.base_url) def response(self, question, base64_image): - question = question + "(请使用中文回复)" try: messages = [ { @@ -65,4 +65,4 @@ class VLLMProvider(VLLMProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") - raise \ No newline at end of file + raise diff --git a/main/xiaozhi-server/core/utils/asr.py b/main/xiaozhi-server/core/utils/asr.py index 983114d32..22b103418 100644 --- a/main/xiaozhi-server/core/utils/asr.py +++ b/main/xiaozhi-server/core/utils/asr.py @@ -13,12 +13,14 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() + def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase: - """工厂方法创建ASR实例""" + """Factory method to create ASR instance""" if os.path.exists(os.path.join('core', 'providers', 'asr', f'{class_name}.py')): lib_name = f'core.providers.asr.{class_name}' if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].ASRProvider(*args, **kwargs) - raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确") \ No newline at end of file + raise ValueError( + f"Unsupported ASR type: {class_name}, please check if the type in this configuration is set correctly") diff --git a/main/xiaozhi-server/core/utils/auth.py b/main/xiaozhi-server/core/utils/auth.py index fd36cbeb0..c5189a3aa 100644 --- a/main/xiaozhi-server/core/utils/auth.py +++ b/main/xiaozhi-server/core/utils/auth.py @@ -12,17 +12,17 @@ import base64 class AuthToken: def __init__(self, secret_key: str): - self.secret_key = secret_key.encode() # 转换为字节 - # 从密钥派生固定长度的加密密钥 (32字节 for AES-256) + self.secret_key = secret_key.encode() # Convert to bytes + # Derive fixed-length encryption key from secret key (32 bytes for AES-256) self.encryption_key = self._derive_key(32) def _derive_key(self, length: int) -> bytes: - """派生固定长度的密钥""" + """Derive fixed-length key""" from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC - # 使用固定盐值(实际生产环境应使用随机盐) - salt = b"fixed_salt_placeholder" # 生产环境应改为随机生成 + # Use fixed salt (production environment should use random salt) + salt = b"fixed_salt_placeholder" # Production should change to randomly generated kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=length, @@ -33,94 +33,83 @@ class AuthToken: return kdf.derive(self.secret_key) def _encrypt_payload(self, payload: dict) -> str: - """使用AES-GCM加密整个payload""" - # 将payload转换为JSON字符串 + """Encrypt entire payload using AES-GCM""" + # Convert payload to JSON string payload_json = json.dumps(payload) - - # 生成随机IV + # Generate random IV iv = os.urandom(12) - # 创建加密器 + # Create encryptor cipher = Cipher( algorithms.AES(self.encryption_key), modes.GCM(iv), backend=default_backend(), ) encryptor = cipher.encryptor() - - # 加密并生成标签 - ciphertext = encryptor.update(payload_json.encode()) + encryptor.finalize() + # Encrypt and generate tag + ciphertext = encryptor.update( + payload_json.encode()) + encryptor.finalize() tag = encryptor.tag - - # 组合 IV + 密文 + 标签 + # Combine IV + ciphertext + tag encrypted_data = iv + ciphertext + tag return base64.urlsafe_b64encode(encrypted_data).decode() def _decrypt_payload(self, encrypted_data: str) -> dict: - """解密AES-GCM加密的payload""" - # 解码Base64 + """Decrypt AES-GCM encrypted payload""" + # Decode Base64 data = base64.urlsafe_b64decode(encrypted_data.encode()) - # 拆分组件 + # Split components iv = data[:12] tag = data[-16:] ciphertext = data[12:-16] - - # 创建解密器 + # Create decryptor cipher = Cipher( algorithms.AES(self.encryption_key), modes.GCM(iv, tag), backend=default_backend(), ) decryptor = cipher.decryptor() - - # 解密 + # Decrypt plaintext = decryptor.update(ciphertext) + decryptor.finalize() return json.loads(plaintext.decode()) def generate_token(self, device_id: str) -> str: """ - 生成JWT token - :param device_id: 设备ID - :return: JWT token字符串 + Generate JWT token + :param device_id: Device ID + :return: JWT token string """ - # 设置过期时间为1小时后 + # Set expiration time to 1 hour later expire_time = datetime.now(timezone.utc) + timedelta(hours=1) - - # 创建原始payload + # Create original payload payload = {"device_id": device_id, "exp": expire_time.timestamp()} - - # 加密整个payload + # Encrypt entire payload encrypted_payload = self._encrypt_payload(payload) - - # 创建外层payload,包含加密数据 + # Create outer payload containing encrypted data outer_payload = {"data": encrypted_payload} - - # 使用JWT进行编码 + # Use JWT for encoding token = jwt.encode(outer_payload, self.secret_key, algorithm="HS256") return token def verify_token(self, token: str) -> Tuple[bool, Optional[str]]: """ - 验证token - :param token: JWT token字符串 - :return: (是否有效, 设备ID) + Verify token + :param token: JWT token string + :return: (is valid, device ID) """ try: - # 先验证外层JWT(签名和过期时间) - outer_payload = jwt.decode(token, self.secret_key, algorithms=["HS256"]) - - # 解密内层payload + # First verify outer JWT (signature and expiration time) + outer_payload = jwt.decode( + token, self.secret_key, algorithms=["HS256"]) + # Decrypt inner payload inner_payload = self._decrypt_payload(outer_payload["data"]) - - # 再次检查过期时间(双重验证) + # Check expiration time again (double verification) if inner_payload["exp"] < time.time(): return False, None - return True, inner_payload["device_id"] - except jwt.InvalidTokenError: return False, None except json.JSONDecodeError: return False, None - except Exception as e: # 捕获其他可能的错误 + except Exception as e: # Catch other possible errors print(f"Token verification failed: {str(e)}") return False, None diff --git a/main/xiaozhi-server/core/utils/cache/config.py b/main/xiaozhi-server/core/utils/cache/config.py index 194daf97d..195679380 100644 --- a/main/xiaozhi-server/core/utils/cache/config.py +++ b/main/xiaozhi-server/core/utils/cache/config.py @@ -1,5 +1,5 @@ """ -缓存配置管理 +Cache configuration management """ from enum import Enum @@ -7,10 +7,8 @@ from typing import Dict, Any, Optional from dataclasses import dataclass from .strategies import CacheStrategy - class CacheType(Enum): - """缓存类型枚举""" - + """Cache type enumeration""" LOCATION = "location" WEATHER = "weather" LUNAR = "lunar" @@ -19,40 +17,39 @@ class CacheType(Enum): CONFIG = "config" DEVICE_PROMPT = "device_prompt" - @dataclass class CacheConfig: - """缓存配置类""" - + """Cache configuration class""" strategy: CacheStrategy = CacheStrategy.TTL - ttl: Optional[float] = 300 # 默认5分钟 - max_size: Optional[int] = 1000 # 默认最大1000条 - cleanup_interval: float = 60 # 清理间隔(秒) - + ttl: Optional[float] = 300 # Default 5 minutes + max_size: Optional[int] = 1000 # Default maximum 1000 entries + cleanup_interval: float = 60 # Cleanup interval (seconds) + @classmethod def for_type(cls, cache_type: CacheType) -> "CacheConfig": - """根据缓存类型返回预设配置""" + """Return preset configuration based on cache type""" configs = { CacheType.LOCATION: cls( - strategy=CacheStrategy.TTL, ttl=None, max_size=1000 # 手动失效 + strategy=CacheStrategy.TTL, ttl=None, max_size=1000 # Manual expiration ), CacheType.IP_INFO: cls( - strategy=CacheStrategy.TTL, ttl=86400, max_size=1000 # 24小时 + strategy=CacheStrategy.TTL, ttl=86400, max_size=1000 # 24 hours ), CacheType.WEATHER: cls( - strategy=CacheStrategy.TTL, ttl=28800, max_size=1000 # 8小时 + strategy=CacheStrategy.TTL, ttl=28800, max_size=1000 # 8 hours ), CacheType.LUNAR: cls( - strategy=CacheStrategy.TTL, ttl=2592000, max_size=365 # 30天过期 + strategy=CacheStrategy.TTL, ttl=2592000, max_size=365 # 30 days expiration ), CacheType.INTENT: cls( - strategy=CacheStrategy.TTL_LRU, ttl=600, max_size=1000 # 10分钟 + strategy=CacheStrategy.TTL_LRU, ttl=600, max_size=1000 # 10 minutes ), CacheType.CONFIG: cls( - strategy=CacheStrategy.FIXED_SIZE, ttl=None, max_size=20 # 手动失效 + strategy=CacheStrategy.FIXED_SIZE, ttl=None, max_size=20 # Manual expiration ), CacheType.DEVICE_PROMPT: cls( - strategy=CacheStrategy.TTL, ttl=None, max_size=1000 # 手动失效 + strategy=CacheStrategy.TTL, ttl=None, max_size=1000 # Manual expiration ), } - return configs.get(cache_type, cls()) \ No newline at end of file + + return configs.get(cache_type, cls()) diff --git a/main/xiaozhi-server/core/utils/cache/manager.py b/main/xiaozhi-server/core/utils/cache/manager.py index 57f84c590..a4aee87e4 100644 --- a/main/xiaozhi-server/core/utils/cache/manager.py +++ b/main/xiaozhi-server/core/utils/cache/manager.py @@ -1,5 +1,5 @@ """ -全局缓存管理器 +Global cache manager """ import time @@ -9,10 +9,9 @@ from collections import OrderedDict from .strategies import CacheStrategy, CacheEntry from .config import CacheConfig, CacheType - class GlobalCacheManager: - """全局缓存管理器""" - + """Global cache manager""" + def __init__(self): self._logger = None self._caches: Dict[str, Dict[str, CacheEntry]] = {} @@ -21,26 +20,25 @@ class GlobalCacheManager: self._global_lock = threading.RLock() self._last_cleanup = time.time() self._stats = {"hits": 0, "misses": 0, "evictions": 0, "cleanups": 0} - + @property def logger(self): - """延迟初始化 logger 以避免循环导入""" + """Lazy initialize logger to avoid circular imports""" if self._logger is None: from config.logger import setup_logging - self._logger = setup_logging() return self._logger - + def _get_cache_name(self, cache_type: CacheType, namespace: str = "") -> str: - """生成缓存名称""" + """Generate cache name""" if namespace: return f"{cache_type.value}:{namespace}" return cache_type.value - + def _get_or_create_cache( self, cache_name: str, config: CacheConfig ) -> Dict[str, CacheEntry]: - """获取或创建缓存空间""" + """Get or create cache space""" with self._global_lock: if cache_name not in self._caches: self._caches[cache_name] = ( @@ -48,10 +46,12 @@ class GlobalCacheManager: if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU] else {} ) + self._configs[cache_name] = config self._locks[cache_name] = threading.RLock() + return self._caches[cache_name] - + def set( self, cache_type: CacheType, @@ -60,157 +60,155 @@ class GlobalCacheManager: ttl: Optional[float] = None, namespace: str = "", ) -> None: - """设置缓存值""" + """Set cache value""" cache_name = self._get_cache_name(cache_type, namespace) config = self._configs.get(cache_name) or CacheConfig.for_type(cache_type) cache = self._get_or_create_cache(cache_name, config) - - # 使用配置的TTL或传入的TTL + + # Use configured TTL or passed TTL effective_ttl = ttl if ttl is not None else config.ttl - + with self._locks[cache_name]: - # 创建缓存条目 + # Create cache entry entry = CacheEntry(value=value, timestamp=time.time(), ttl=effective_ttl) - - # 处理不同策略 + + # Handle different strategies if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]: - # LRU策略:如果已存在则移动到末尾 + # LRU strategy: if exists, move to end if key in cache: del cache[key] cache[key] = entry - - # 检查大小限制 + + # Check size limit if config.max_size and len(cache) > config.max_size: - # 移除最旧的条目 + # Remove oldest entry oldest_key = next(iter(cache)) del cache[oldest_key] self._stats["evictions"] += 1 - else: cache[key] = entry - - # 检查大小限制 + + # Check size limit if config.max_size and len(cache) > config.max_size: - # 简单策略:随机移除一个条目 + # Simple strategy: randomly remove an entry victim_key = next(iter(cache)) del cache[victim_key] self._stats["evictions"] += 1 - - # 定期清理过期条目 + + # Periodic cleanup of expired entries self._maybe_cleanup(cache_name) - + def get( self, cache_type: CacheType, key: str, namespace: str = "" ) -> Optional[Any]: - """获取缓存值""" + """Get cache value""" cache_name = self._get_cache_name(cache_type, namespace) - + if cache_name not in self._caches: self._stats["misses"] += 1 return None - + cache = self._caches[cache_name] config = self._configs[cache_name] - + with self._locks[cache_name]: if key not in cache: self._stats["misses"] += 1 return None - + entry = cache[key] - - # 检查过期 + + # Check expiration if entry.is_expired(): del cache[key] self._stats["misses"] += 1 return None - - # 更新访问信息 + + # Update access information entry.touch() - - # LRU策略:移动到末尾 + + # LRU strategy: move to end if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]: del cache[key] cache[key] = entry - + self._stats["hits"] += 1 return entry.value - + def delete(self, cache_type: CacheType, key: str, namespace: str = "") -> bool: - """删除缓存条目""" + """Delete cache entry""" cache_name = self._get_cache_name(cache_type, namespace) - + if cache_name not in self._caches: return False - + cache = self._caches[cache_name] - + with self._locks[cache_name]: if key in cache: del cache[key] return True return False - + def clear(self, cache_type: CacheType, namespace: str = "") -> None: - """清空指定缓存""" + """Clear specified cache""" cache_name = self._get_cache_name(cache_type, namespace) - + if cache_name not in self._caches: return - + with self._locks[cache_name]: self._caches[cache_name].clear() - + def invalidate_pattern( self, cache_type: CacheType, pattern: str, namespace: str = "" ) -> int: - """按模式失效缓存条目""" + """Invalidate cache entries by pattern""" cache_name = self._get_cache_name(cache_type, namespace) - + if cache_name not in self._caches: return 0 - + cache = self._caches[cache_name] deleted_count = 0 - + with self._locks[cache_name]: keys_to_delete = [key for key in cache.keys() if pattern in key] for key in keys_to_delete: del cache[key] deleted_count += 1 - + return deleted_count - + def _cleanup_expired(self, cache_name: str) -> int: - """清理过期条目""" + """Clean up expired entries""" if cache_name not in self._caches: return 0 - + cache = self._caches[cache_name] deleted_count = 0 - + with self._locks[cache_name]: expired_keys = [key for key, entry in cache.items() if entry.is_expired()] for key in expired_keys: del cache[key] deleted_count += 1 - + return deleted_count - + def _maybe_cleanup(self, cache_name: str): - """定期清理检查""" + """Periodic cleanup check""" config = self._configs.get(cache_name) if not config: return - + now = time.time() if now - self._last_cleanup > config.cleanup_interval: self._last_cleanup = now deleted = self._cleanup_expired(cache_name) if deleted > 0: self._stats["cleanups"] += 1 - self.logger.debug(f"清理缓存 {cache_name}: 删除 {deleted} 个过期条目") + self.logger.debug(f"Cleaned cache {cache_name}: deleted {deleted} expired entries") - -# 创建全局缓存管理器实例 -cache_manager = GlobalCacheManager() \ No newline at end of file +# Create global cache manager instance +cache_manager = GlobalCacheManager() diff --git a/main/xiaozhi-server/core/utils/cache/strategies.py b/main/xiaozhi-server/core/utils/cache/strategies.py index 396b9540c..a45293b9c 100644 --- a/main/xiaozhi-server/core/utils/cache/strategies.py +++ b/main/xiaozhi-server/core/utils/cache/strategies.py @@ -1,5 +1,5 @@ """ -缓存策略和数据结构定义 +Cache strategy and data structure definitions """ import time @@ -9,21 +9,19 @@ from dataclasses import dataclass class CacheStrategy(Enum): - """缓存策略枚举""" - - TTL = "ttl" # 基于时间过期 - LRU = "lru" # 最近最少使用 - FIXED_SIZE = "fixed_size" # 固定大小 - TTL_LRU = "ttl_lru" # TTL + LRU混合策略 + """Cache strategy enumeration""" + TTL = "ttl" # Time-based expiration + LRU = "lru" # Least Recently Used + FIXED_SIZE = "fixed_size" # Fixed size + TTL_LRU = "ttl_lru" # TTL + LRU hybrid strategy @dataclass class CacheEntry: - """缓存条目数据结构""" - + """Cache entry data structure""" value: Any timestamp: float - ttl: Optional[float] = None # 生存时间(秒) + ttl: Optional[float] = None # Time to live (seconds) access_count: int = 0 last_access: float = None @@ -32,12 +30,12 @@ class CacheEntry: self.last_access = self.timestamp def is_expired(self) -> bool: - """检查是否过期""" + """Check if expired""" if self.ttl is None: return False return time.time() - self.timestamp > self.ttl def touch(self): - """更新访问时间和计数""" + """Update access time and count""" self.last_access = time.time() - self.access_count += 1 \ No newline at end of file + self.access_count += 1 diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py index 6adadfdcb..f489aa632 100644 --- a/main/xiaozhi-server/core/utils/dialogue.py +++ b/main/xiaozhi-server/core/utils/dialogue.py @@ -23,7 +23,7 @@ class Message: class Dialogue: def __init__(self): self.dialogue: List[Message] = [] - # 获取当前时间 + # Get current time self.current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") def put(self, message: Message): @@ -46,14 +46,16 @@ class Dialogue: dialogue.append({"role": m.role, "content": m.content}) def get_llm_dialogue(self) -> List[Dict[str, str]]: - # 直接调用get_llm_dialogue_with_memory,传入None作为memory_str - # 这样确保说话人功能在所有调用路径下都生效 + # Directly call get_llm_dialogue_with_memory, passing None as memory_str + # This ensures speaker functionality takes effect in all call paths return self.get_llm_dialogue_with_memory(None, None) def update_system_message(self, new_content: str): - """更新或添加系统消息""" - # 查找第一个系统消息 - system_msg = next((msg for msg in self.dialogue if msg.role == "system"), None) + """Update or add system message""" + # Find the first system message + system_msg = next( + (msg for msg in self.dialogue if msg.role == "system"), None) + if system_msg: system_msg.content = new_content else: @@ -62,57 +64,60 @@ class Dialogue: def get_llm_dialogue_with_memory( self, memory_str: str = None, voiceprint_config: dict = None ) -> List[Dict[str, str]]: - # 构建对话 + # Build dialogue dialogue = [] - # 添加系统提示和记忆 + # Add system prompt and memory system_message = next( (msg for msg in self.dialogue if msg.role == "system"), None ) if system_message: - # 基础系统提示 + # Base system prompt enhanced_system_prompt = system_message.content - # 替换时间占位符 + + # Replace time placeholder enhanced_system_prompt = enhanced_system_prompt.replace( "{{current_time}}", datetime.now().strftime("%H:%M") ) - # 添加说话人个性化描述 + # Add speaker personalization description try: speakers = voiceprint_config.get("speakers", []) if speakers: - enhanced_system_prompt += "\n\n" + enhanced_system_prompt += "\n\n" for speaker_str in speakers: try: parts = speaker_str.split(",", 2) if len(parts) >= 2: name = parts[1].strip() - # 如果描述为空,则为"" + # If description is empty, then "" description = ( parts[2].strip() if len(parts) >= 3 else "" ) - enhanced_system_prompt += f"\n- {name}:{description}" + enhanced_system_prompt += f"\n- {name}: {description}" except: pass - enhanced_system_prompt += "\n\n" + enhanced_system_prompt += "\n\n" except: - # 配置读取失败时忽略错误,不影响其他功能 + # Ignore errors when configuration reading fails, don't affect other functionality pass - # 使用正则表达式匹配 标签,不管中间有什么内容 + # Use regular expression to match tags, regardless of content inside if memory_str is not None: enhanced_system_prompt = re.sub( r".*?", - f"\n{memory_str}\n", + f"\n{memory_str}\n", enhanced_system_prompt, flags=re.DOTALL, ) - dialogue.append({"role": "system", "content": enhanced_system_prompt}) - # 添加用户和助手的对话 + dialogue.append( + {"role": "system", "content": enhanced_system_prompt}) + + # Add user and assistant dialogue for m in self.dialogue: - if m.role != "system": # 跳过原始的系统消息 + if m.role != "system": # Skip original system message self.getMessages(m, dialogue) - return dialogue \ No newline at end of file + return dialogue diff --git a/main/xiaozhi-server/core/utils/intent.py b/main/xiaozhi-server/core/utils/intent.py index 747ecf38a..cc6ae53b3 100644 --- a/main/xiaozhi-server/core/utils/intent.py +++ b/main/xiaozhi-server/core/utils/intent.py @@ -7,11 +7,12 @@ logger = setup_logging() def create_instance(class_name, *args, **kwargs): - # 创建intent实例 + # Create intent instance if os.path.exists(os.path.join('core', 'providers', 'intent', class_name, f'{class_name}.py')): lib_name = f'core.providers.intent.{class_name}.{class_name}' if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].IntentProvider(*args, **kwargs) - raise ValueError(f"不支持的intent类型: {class_name},请检查该配置的type是否设置正确") \ No newline at end of file + raise ValueError( + f"Unsupported intent type: {class_name}, please check if the type in this configuration is set correctly") diff --git a/main/xiaozhi-server/core/utils/llm.py b/main/xiaozhi-server/core/utils/llm.py index 4c6ae27bf..90c921af2 100644 --- a/main/xiaozhi-server/core/utils/llm.py +++ b/main/xiaozhi-server/core/utils/llm.py @@ -1,23 +1,23 @@ +import importlib +from config.logger import setup_logging import os import sys - -# 添加项目根目录到Python路径 +# Add project root directory to Python path current_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.abspath(os.path.join(current_dir, "..", "..")) sys.path.insert(0, project_root) -from config.logger import setup_logging -import importlib logger = setup_logging() def create_instance(class_name, *args, **kwargs): - # 创建LLM实例 + # Create LLM instance if os.path.exists(os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')): lib_name = f'core.providers.llm.{class_name}.{class_name}' if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].LLMProvider(*args, **kwargs) - raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确") + raise ValueError( + f"Unsupported LLM type: {class_name}, please check if the type in this configuration is set correctly") diff --git a/main/xiaozhi-server/core/utils/memory.py b/main/xiaozhi-server/core/utils/memory.py index ff43b220c..db28cf06e 100644 --- a/main/xiaozhi-server/core/utils/memory.py +++ b/main/xiaozhi-server/core/utils/memory.py @@ -8,11 +8,12 @@ logger = setup_logging() def create_instance(class_name, *args, **kwargs): if os.path.exists( - os.path.join("core", "providers", "memory", class_name, f"{class_name}.py") + os.path.join("core", "providers", "memory", + class_name, f"{class_name}.py") ): lib_name = f"core.providers.memory.{class_name}.{class_name}" if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f"{lib_name}") return sys.modules[lib_name].MemoryProvider(*args, **kwargs) - raise ValueError(f"不支持的记忆服务类型: {class_name}") + raise ValueError(f"Unsupported memory service type: {class_name}") diff --git a/main/xiaozhi-server/core/utils/modules_initialize.py b/main/xiaozhi-server/core/utils/modules_initialize.py index bf27df92e..e60207091 100644 --- a/main/xiaozhi-server/core/utils/modules_initialize.py +++ b/main/xiaozhi-server/core/utils/modules_initialize.py @@ -1,10 +1,12 @@ from typing import Dict, Any + from config.logger import setup_logging + from core.utils import tts, llm, intent, memory, vad, asr TAG = __name__ -logger = setup_logging() +logger = setup_logging() def initialize_modules( logger, @@ -17,23 +19,23 @@ def initialize_modules( init_intent=False, ) -> Dict[str, Any]: """ - 初始化所有模块组件 + Initialize all module components Args: - config: 配置字典 + config: Configuration dictionary Returns: - Dict[str, Any]: 包含所有初始化后的模块的字典 + Dict[str, Any]: Dictionary containing all initialized modules """ modules = {} - # 初始化TTS模块 + # Initialize TTS module if init_tts: select_tts_module = config["selected_module"]["TTS"] modules["tts"] = initialize_tts(config) - logger.bind(tag=TAG).info(f"初始化组件: tts成功 {select_tts_module}") + logger.bind(tag=TAG).info(f"Initialize component: tts successful {select_tts_module}") - # 初始化LLM模块 + # Initialize LLM module if init_llm: select_llm_module = config["selected_module"]["LLM"] llm_type = ( @@ -41,13 +43,14 @@ def initialize_modules( if "type" not in config["LLM"][select_llm_module] else config["LLM"][select_llm_module]["type"] ) + modules["llm"] = llm.create_instance( llm_type, config["LLM"][select_llm_module], ) - logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}") + logger.bind(tag=TAG).info(f"Initialize component: llm successful {select_llm_module}") - # 初始化Intent模块 + # Initialize Intent module if init_intent: select_intent_module = config["selected_module"]["Intent"] intent_type = ( @@ -55,13 +58,14 @@ def initialize_modules( if "type" not in config["Intent"][select_intent_module] else config["Intent"][select_intent_module]["type"] ) + modules["intent"] = intent.create_instance( intent_type, config["Intent"][select_intent_module], ) - logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}") + logger.bind(tag=TAG).info(f"Initialize component: intent successful {select_intent_module}") - # 初始化Memory模块 + # Initialize Memory module if init_memory: select_memory_module = config["selected_module"]["Memory"] memory_type = ( @@ -69,14 +73,15 @@ def initialize_modules( if "type" not in config["Memory"][select_memory_module] else config["Memory"][select_memory_module]["type"] ) + modules["memory"] = memory.create_instance( memory_type, config["Memory"][select_memory_module], config.get("summaryMemory", None), ) - logger.bind(tag=TAG).info(f"初始化组件: memory成功 {select_memory_module}") + logger.bind(tag=TAG).info(f"Initialize component: memory successful {select_memory_module}") - # 初始化VAD模块 + # Initialize VAD module if init_vad: select_vad_module = config["selected_module"]["VAD"] vad_type = ( @@ -84,19 +89,20 @@ def initialize_modules( if "type" not in config["VAD"][select_vad_module] else config["VAD"][select_vad_module]["type"] ) + modules["vad"] = vad.create_instance( vad_type, config["VAD"][select_vad_module], ) - logger.bind(tag=TAG).info(f"初始化组件: vad成功 {select_vad_module}") + logger.bind(tag=TAG).info(f"Initialize component: vad successful {select_vad_module}") - # 初始化ASR模块 + # Initialize ASR module if init_asr: select_asr_module = config["selected_module"]["ASR"] modules["asr"] = initialize_asr(config) - logger.bind(tag=TAG).info(f"初始化组件: asr成功 {select_asr_module}") - return modules + logger.bind(tag=TAG).info(f"Initialize component: asr successful {select_asr_module}") + return modules def initialize_tts(config): select_tts_module = config["selected_module"]["TTS"] @@ -105,13 +111,14 @@ def initialize_tts(config): if "type" not in config["TTS"][select_tts_module] else config["TTS"][select_tts_module]["type"] ) + new_tts = tts.create_instance( tts_type, config["TTS"][select_tts_module], str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"), ) - return new_tts + return new_tts def initialize_asr(config): select_asr_module = config["selected_module"]["ASR"] @@ -120,31 +127,32 @@ def initialize_asr(config): if "type" not in config["ASR"][select_asr_module] else config["ASR"][select_asr_module]["type"] ) + new_asr = asr.create_instance( asr_type, config["ASR"][select_asr_module], str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"), ) - logger.bind(tag=TAG).info("ASR模块初始化完成") + + logger.bind(tag=TAG).info("ASR module initialization completed") return new_asr - def initialize_voiceprint(asr_instance, config): - """初始化声纹识别功能""" + """Initialize voiceprint recognition functionality""" voiceprint_config = config.get("voiceprint") if not voiceprint_config: - return False - - # 应用配置 - if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"): - logger.bind(tag=TAG).warning("声纹识别配置不完整") return False - + + # Apply configuration + if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"): + logger.bind(tag=TAG).warning("Voiceprint recognition configuration incomplete") + return False + try: asr_instance.init_voiceprint(voiceprint_config) - logger.bind(tag=TAG).info("ASR模块声纹识别功能已动态启用") - logger.bind(tag=TAG).info(f"配置说话人数量: {len(voiceprint_config['speakers'])}") + logger.bind(tag=TAG).info("ASR module voiceprint recognition functionality dynamically enabled") + logger.bind(tag=TAG).info(f"Configured speaker count: {len(voiceprint_config['speakers'])}") return True except Exception as e: - logger.bind(tag=TAG).error(f"动态初始化声纹识别功能失败: {str(e)}") + logger.bind(tag=TAG).error(f"Failed to dynamically initialize voiceprint recognition functionality: {str(e)}") return False diff --git a/main/xiaozhi-server/core/utils/opus_encoder_utils.py b/main/xiaozhi-server/core/utils/opus_encoder_utils.py index 23d26c398..735c25f8a 100644 --- a/main/xiaozhi-server/core/utils/opus_encoder_utils.py +++ b/main/xiaozhi-server/core/utils/opus_encoder_utils.py @@ -1,11 +1,10 @@ """ -Opus编码工具类 -将PCM音频数据编码为Opus格式 +Opus encoding utility class +Encode PCM audio data to Opus format """ import logging import traceback - import numpy as np from typing import List, Optional from opuslib_next import Encoder @@ -13,89 +12,91 @@ from opuslib_next import constants class OpusEncoderUtils: - """PCM到Opus的编码器""" + """PCM to Opus encoder""" def __init__(self, sample_rate: int, channels: int, frame_size_ms: int): """ - 初始化Opus编码器 + Initialize Opus encoder Args: - sample_rate: 采样率 (Hz) - channels: 通道数 (1=单声道, 2=立体声) - frame_size_ms: 帧大小 (毫秒) + sample_rate: Sample rate (Hz) + channels: Number of channels (1=mono, 2=stereo) + frame_size_ms: Frame size (milliseconds) """ self.sample_rate = sample_rate self.channels = channels self.frame_size_ms = frame_size_ms - # 计算每帧样本数 = 采样率 * 帧大小(毫秒) / 1000 + + # Calculate samples per frame = sample rate * frame size(ms) / 1000 self.frame_size = (sample_rate * frame_size_ms) // 1000 - # 总帧大小 = 每帧样本数 * 通道数 + + # Total frame size = samples per frame * channels self.total_frame_size = self.frame_size * channels - # 比特率和复杂度设置 + # Bitrate and complexity settings self.bitrate = 24000 # bps - self.complexity = 10 # 最高质量 + self.complexity = 10 # Highest quality - # 缓冲区初始化为空 + # Initialize buffer as empty self.buffer = np.array([], dtype=np.int16) try: - # 创建Opus编码器 + # Create Opus encoder self.encoder = Encoder( - sample_rate, channels, constants.APPLICATION_AUDIO # 音频优化模式 + sample_rate, channels, constants.APPLICATION_AUDIO # Audio optimization mode ) self.encoder.bitrate = self.bitrate self.encoder.complexity = self.complexity - self.encoder.signal = constants.SIGNAL_VOICE # 语音信号优化 + self.encoder.signal = constants.SIGNAL_VOICE # Voice signal optimization + except Exception as e: - logging.error(f"初始化Opus编码器失败: {e}") - raise RuntimeError("初始化失败") from e + logging.error(f"Failed to initialize Opus encoder: {e}") + raise RuntimeError("Initialization failed") from e def reset_state(self): - """重置编码器状态""" + """Reset encoder state""" self.encoder.reset_state() self.buffer = np.array([], dtype=np.int16) def encode_pcm_to_opus(self, pcm_data: bytes, end_of_stream: bool) -> List[bytes]: """ - 将PCM数据编码为Opus格式 + Encode PCM data to Opus format Args: - pcm_data: PCM字节数据 - end_of_stream: 是否为流的结束 + pcm_data: PCM byte data + end_of_stream: Whether this is the end of stream Returns: - Opus数据包列表 + List of Opus data packets """ - # 将字节数据转换为short数组 + # Convert byte data to short array new_samples = self._convert_bytes_to_shorts(pcm_data) - # 校验PCM数据 + # Validate PCM data self._validate_pcm_data(new_samples) - # 将新数据追加到缓冲区 + # Append new data to buffer self.buffer = np.append(self.buffer, new_samples) opus_packets = [] offset = 0 - # 处理所有完整帧 + # Process all complete frames while offset <= len(self.buffer) - self.total_frame_size: - frame = self.buffer[offset : offset + self.total_frame_size] + frame = self.buffer[offset: offset + self.total_frame_size] output = self._encode(frame) if output: opus_packets.append(output) offset += self.total_frame_size - # 保留未处理的样本 + # Keep unprocessed samples self.buffer = self.buffer[offset:] - # 流结束时处理剩余数据 + # Process remaining data at end of stream if end_of_stream and len(self.buffer) > 0: - # 创建最后一帧并用0填充 + # Create last frame and pad with zeros last_frame = np.zeros(self.total_frame_size, dtype=np.int16) last_frame[: len(self.buffer)] = self.buffer - output = self._encode(last_frame) if output: opus_packets.append(output) @@ -104,33 +105,35 @@ class OpusEncoderUtils: return opus_packets def _encode(self, frame: np.ndarray) -> Optional[bytes]: - """编码一帧音频数据""" + """Encode one frame of audio data""" try: - # 将numpy数组转换为bytes + # Convert numpy array to bytes frame_bytes = frame.tobytes() - # opuslib要求输入字节数必须是channels*2的倍数 + # opuslib requires input byte count to be multiple of channels*2 encoded = self.encoder.encode(frame_bytes, self.frame_size) return encoded except Exception as e: - logging.error(f"Opus编码失败: {e}") + logging.error(f"Opus encoding failed: {e}") traceback.print_exc() return None def _convert_bytes_to_shorts(self, bytes_data: bytes) -> np.ndarray: - """将字节数组转换为short数组 (16位PCM)""" - # 假设输入是小端字节序的16位PCM + """Convert byte array to short array (16-bit PCM)""" + # Assume input is little-endian 16-bit PCM return np.frombuffer(bytes_data, dtype=np.int16) def _validate_pcm_data(self, pcm_shorts: np.ndarray) -> None: - """验证PCM数据是否有效""" - # 16位PCM数据范围是 -32768 到 32767 + """Validate PCM data validity""" + # 16-bit PCM data range is -32768 to 32767 if np.any((pcm_shorts < -32768) | (pcm_shorts > 32767)): - invalid_samples = pcm_shorts[(pcm_shorts < -32768) | (pcm_shorts > 32767)] - logging.warning(f"发现无效PCM样本: {invalid_samples[:5]}...") - # 在实际应用中可以选择裁剪而不是抛出异常 + invalid_samples = pcm_shorts[( + pcm_shorts < -32768) | (pcm_shorts > 32767)] + logging.warning( + f"Found invalid PCM samples: {invalid_samples[:5]}...") + # In practice, you can choose to clip instead of throwing exception # np.clip(pcm_shorts, -32768, 32767, out=pcm_shorts) def close(self): - """关闭编码器并释放资源""" - # opuslib没有明确的关闭方法,Python的垃圾回收会处理 + """Close encoder and release resources""" + # opuslib doesn't have explicit close method, Python's garbage collection will handle it pass diff --git a/main/xiaozhi-server/core/utils/output_counter.py b/main/xiaozhi-server/core/utils/output_counter.py index 1e7ae8df6..3482014ed 100644 --- a/main/xiaozhi-server/core/utils/output_counter.py +++ b/main/xiaozhi-server/core/utils/output_counter.py @@ -1,23 +1,24 @@ import datetime from typing import Dict, Tuple -# 全局字典,用于存储每个设备的每日输出字数 +# Global dictionary to store daily output word count for each device _device_daily_output: Dict[Tuple[str, datetime.date], int] = {} -# 记录最后一次检查的日期 + +# Record the last check date _last_check_date: datetime.date = None def reset_device_output(): """ - 重置所有设备的每日输出字数 - 每天0点调用此函数 + Reset daily output word count for all devices + Call this function at 0:00 every day """ _device_daily_output.clear() def get_device_output(device_id: str) -> int: """ - 获取设备当日的输出字数 + Get device's output word count for today """ current_date = datetime.datetime.now().date() return _device_daily_output.get((device_id, current_date), 0) @@ -25,26 +26,28 @@ def get_device_output(device_id: str) -> int: def add_device_output(device_id: str, char_count: int): """ - 增加设备的输出字数 + Add to device's output word count """ current_date = datetime.datetime.now().date() global _last_check_date - # 如果是第一次调用或者日期发生变化,清空计数器 + # If first call or date changed, clear counter if _last_check_date is None or _last_check_date != current_date: _device_daily_output.clear() _last_check_date = current_date current_count = _device_daily_output.get((device_id, current_date), 0) - _device_daily_output[(device_id, current_date)] = current_count + char_count + _device_daily_output[(device_id, current_date) + ] = current_count + char_count def check_device_output_limit(device_id: str, max_output_size: int) -> bool: """ - 检查设备是否超过输出限制 - :return: True 如果超过限制,False 如果未超过 + Check if device exceeds output limit + :return: True if exceeds limit, False if not """ if not device_id: return False + current_output = get_device_output(device_id) return current_output >= max_output_size diff --git a/main/xiaozhi-server/core/utils/p3.py b/main/xiaozhi-server/core/utils/p3.py index c75b968e0..ddcba7f0a 100644 --- a/main/xiaozhi-server/core/utils/p3.py +++ b/main/xiaozhi-server/core/utils/p3.py @@ -2,25 +2,25 @@ import struct def decode_opus_from_file(input_file): """ - 从p3文件中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。 + Decode Opus data from p3 file and return a list of Opus data packets and total duration. """ opus_datas = [] total_frames = 0 - sample_rate = 16000 # 文件采样率 - frame_duration_ms = 60 # 帧时长 + sample_rate = 16000 # File sample rate + frame_duration_ms = 60 # Frame duration frame_size = int(sample_rate * frame_duration_ms / 1000) with open(input_file, 'rb') as f: while True: - # 读取头部(4字节):[1字节类型,1字节保留,2字节长度] + # Read header (4 bytes): [1 byte type, 1 byte reserved, 2 bytes length] header = f.read(4) if not header: break - # 解包头部信息 + # Unpack header information _, _, data_len = struct.unpack('>BBH', header) - # 根据头部指定的长度读取 Opus 数据 + # Read Opus data according to header specified length opus_data = f.read(data_len) if len(opus_data) != data_len: raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the file.") @@ -28,32 +28,39 @@ def decode_opus_from_file(input_file): opus_datas.append(opus_data) total_frames += 1 - # 计算总时长 + # Calculate total duration total_duration = (total_frames * frame_duration_ms) / 1000.0 + return opus_datas, total_duration def decode_opus_from_bytes(input_bytes): """ - 从p3二进制数据中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。 + Decode Opus data from p3 binary data and return a list of Opus data packets and total duration. """ import io + opus_datas = [] total_frames = 0 - sample_rate = 16000 # 文件采样率 - frame_duration_ms = 60 # 帧时长 + sample_rate = 16000 # File sample rate + frame_duration_ms = 60 # Frame duration frame_size = int(sample_rate * frame_duration_ms / 1000) f = io.BytesIO(input_bytes) + while True: header = f.read(4) if not header: break + _, _, data_len = struct.unpack('>BBH', header) + opus_data = f.read(data_len) if len(opus_data) != data_len: raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the bytes.") + opus_datas.append(opus_data) total_frames += 1 total_duration = (total_frames * frame_duration_ms) / 1000.0 - return opus_datas, total_duration \ No newline at end of file + + return opus_datas, total_duration diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py index a81fd9aac..3c1eaad99 100644 --- a/main/xiaozhi-server/core/utils/prompt_manager.py +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -1,6 +1,6 @@ """ -系统提示词管理器模块 -负责管理和更新系统提示词,包括快速初始化和异步增强功能 +System prompt manager module +Responsible for managing and updating system prompts, including quick initialization and async enhancement features """ import os @@ -12,13 +12,13 @@ from jinja2 import Template TAG = __name__ WEEKDAY_MAP = { - "Monday": "星期一", - "Tuesday": "星期二", - "Wednesday": "星期三", - "Thursday": "星期四", - "Friday": "星期五", - "Saturday": "星期六", - "Sunday": "星期日", + "Monday": "Monday", + "Tuesday": "Tuesday", + "Wednesday": "Wednesday", + "Thursday": "Thursday", + "Friday": "Friday", + "Saturday": "Saturday", + "Sunday": "Sunday", } EMOJI_List = [ @@ -47,7 +47,7 @@ EMOJI_List = [ class PromptManager: - """系统提示词管理器,负责管理和更新系统提示词""" + """System prompt manager, responsible for managing and updating system prompts""" def __init__(self, config: Dict[str, Any], logger=None): self.config = config @@ -55,7 +55,7 @@ class PromptManager: self.base_prompt_template = None self.last_update_time = 0 - # 导入全局缓存管理器 + # Import global cache manager from core.utils.cache.manager import cache_manager, CacheType self.cache_manager = cache_manager @@ -64,59 +64,71 @@ class PromptManager: self._load_base_template() def _load_base_template(self): - """加载基础提示词模板""" + """Load base prompt template""" try: template_path = "agent-base-prompt.txt" cache_key = f"prompt_template:{template_path}" - # 先从缓存获取 - cached_template = self.cache_manager.get(self.CacheType.CONFIG, cache_key) + # Get from cache first + cached_template = self.cache_manager.get( + self.CacheType.CONFIG, cache_key) if cached_template is not None: self.base_prompt_template = cached_template - self.logger.bind(tag=TAG).debug("从缓存加载基础提示词模板") + self.logger.bind(tag=TAG).debug( + "Load base prompt template from cache") return - # 缓存未命中,从文件读取 + # Cache miss, read from file if os.path.exists(template_path): with open(template_path, "r", encoding="utf-8") as f: template_content = f.read() - # 存入缓存(CONFIG类型默认不自动过期,需要手动失效) + # Store in cache (CONFIG type doesn't auto-expire by default, needs manual invalidation) self.cache_manager.set( self.CacheType.CONFIG, cache_key, template_content ) + self.base_prompt_template = template_content - self.logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存") + self.logger.bind(tag=TAG).debug( + "Successfully loaded base prompt template and cached") else: - self.logger.bind(tag=TAG).warning("未找到agent-base-prompt.txt文件") + self.logger.bind(tag=TAG).warning( + "agent-base-prompt.txt file not found") + except Exception as e: - self.logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}") + self.logger.bind(tag=TAG).error( + f"Failed to load prompt template: {e}") def get_quick_prompt(self, user_prompt: str, device_id: str = None) -> str: - """快速获取系统提示词(使用用户配置)""" + """Quick get system prompt (using user configuration)""" device_cache_key = f"device_prompt:{device_id}" cached_device_prompt = self.cache_manager.get( self.CacheType.DEVICE_PROMPT, device_cache_key ) + if cached_device_prompt is not None: - self.logger.bind(tag=TAG).debug(f"使用设备 {device_id} 的缓存提示词") + self.logger.bind(tag=TAG).debug( + f"Using cached prompt for device {device_id}") return cached_device_prompt else: self.logger.bind(tag=TAG).debug( - f"设备 {device_id} 无缓存提示词,使用传入的提示词" + f"No cached prompt for device {device_id}, using passed prompt" ) - # 使用传入的提示词并缓存(如果有设备ID) + # Use passed prompt and cache (if device ID exists) if device_id: device_cache_key = f"device_prompt:{device_id}" - self.cache_manager.set(self.CacheType.CONFIG, device_cache_key, user_prompt) - self.logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存") + self.cache_manager.set(self.CacheType.CONFIG, + device_cache_key, user_prompt) + self.logger.bind(tag=TAG).debug( + f"Prompt for device {device_id} has been cached") - self.logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...") + self.logger.bind(tag=TAG).info( + f"Using quick prompt: {user_prompt[:50]}...") return user_prompt def _get_current_time_info(self) -> tuple: - """获取当前时间信息""" + """Get current time information""" from datetime import datetime now = datetime.now() @@ -132,94 +144,109 @@ class PromptManager: return today_date, today_weekday, lunar_date def _get_location_info(self, client_ip: str) -> str: - """获取位置信息""" + """Get location information""" try: - # 先从缓存获取 - cached_location = self.cache_manager.get(self.CacheType.LOCATION, client_ip) + # Get from cache first + cached_location = self.cache_manager.get( + self.CacheType.LOCATION, client_ip) if cached_location is not None: return cached_location - # 缓存未命中,调用API获取 + # Cache miss, call API to get from core.utils.util import get_ip_info ip_info = get_ip_info(client_ip, self.logger) - city = ip_info.get("city", "未知位置") + city = ip_info.get("city", "Unknown location") location = f"{city}" - # 存入缓存 - self.cache_manager.set(self.CacheType.LOCATION, client_ip, location) + # Store in cache + self.cache_manager.set( + self.CacheType.LOCATION, client_ip, location) + return location + except Exception as e: - self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}") - return "未知位置" + self.logger.bind(tag=TAG).error( + f"Failed to get location information: {e}") + return "Unknown location" def _get_weather_info(self, conn, location: str) -> str: - """获取天气信息""" + """Get weather information""" try: - # 先从缓存获取 - cached_weather = self.cache_manager.get(self.CacheType.WEATHER, location) + # Get from cache first + cached_weather = self.cache_manager.get( + self.CacheType.WEATHER, location) if cached_weather is not None: return cached_weather - # 缓存未命中,调用get_weather函数获取 + # Cache miss, call get_weather function to get from plugins_func.functions.get_weather import get_weather from plugins_func.register import ActionResponse - # 调用get_weather函数 + # Call get_weather function result = get_weather(conn, location=location, lang="zh_CN") if isinstance(result, ActionResponse): weather_report = result.result - self.cache_manager.set(self.CacheType.WEATHER, location, weather_report) + self.cache_manager.set( + self.CacheType.WEATHER, location, weather_report) return weather_report - return "天气信息获取失败" + + return "Failed to get weather information" except Exception as e: - self.logger.bind(tag=TAG).error(f"获取天气信息失败: {e}") - return "天气信息获取失败" + self.logger.bind(tag=TAG).error( + f"Failed to get weather information: {e}") + return "Failed to get weather information" def update_context_info(self, conn, client_ip: str): - """同步更新上下文信息""" + """Synchronously update context information""" try: - # 获取位置信息(使用全局缓存) + # Get location information (using global cache) local_address = self._get_location_info(client_ip) - # 获取天气信息(使用全局缓存) + + # Get weather information (using global cache) self._get_weather_info(conn, local_address) - self.logger.bind(tag=TAG).info(f"上下文信息更新完成") + + self.logger.bind(tag=TAG).info( + f"Context information update completed") except Exception as e: - self.logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}") + self.logger.bind(tag=TAG).error( + f"Failed to update context information: {e}") def build_enhanced_prompt( self, user_prompt: str, device_id: str, client_ip: str = None ) -> str: - """构建增强的系统提示词""" + """Build enhanced system prompt""" if not self.base_prompt_template: return user_prompt try: - # 获取最新的时间信息(不缓存) + # Get latest time information (not cached) today_date, today_weekday, lunar_date = ( self._get_current_time_info() ) - # 获取缓存的上下文信息 + # Get cached context information local_address = "" weather_info = "" if client_ip: - # 获取位置信息(从全局缓存) + # Get location information (from global cache) local_address = ( - self.cache_manager.get(self.CacheType.LOCATION, client_ip) or "" + self.cache_manager.get( + self.CacheType.LOCATION, client_ip) or "" ) - # 获取天气信息(从全局缓存) + # Get weather information (from global cache) if local_address: weather_info = ( - self.cache_manager.get(self.CacheType.WEATHER, local_address) + self.cache_manager.get( + self.CacheType.WEATHER, local_address) or "" ) - # 替换模板变量 + # Replace template variables template = Template(self.base_prompt_template) enhanced_prompt = template.render( base_prompt=user_prompt, @@ -231,15 +258,19 @@ class PromptManager: weather_info=weather_info, emojiList=EMOJI_List, ) + device_cache_key = f"device_prompt:{device_id}" self.cache_manager.set( self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt ) + self.logger.bind(tag=TAG).info( - f"构建增强提示词成功,长度: {len(enhanced_prompt)}" + f"Built enhanced prompt successfully, length: {len(enhanced_prompt)}" ) + return enhanced_prompt except Exception as e: - self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}") - return user_prompt \ No newline at end of file + self.logger.bind(tag=TAG).error( + f"Failed to build enhanced prompt: {e}") + return user_prompt diff --git a/main/xiaozhi-server/core/utils/textUtils.py b/main/xiaozhi-server/core/utils/textUtils.py index ae4e16228..bad7e6b9b 100644 --- a/main/xiaozhi-server/core/utils/textUtils.py +++ b/main/xiaozhi-server/core/utils/textUtils.py @@ -1,6 +1,7 @@ import json TAG = __name__ + EMOJI_MAP = { "😂": "laughing", "😭": "crying", @@ -24,6 +25,7 @@ EMOJI_MAP = { "😘": "kissy", "😏": "confident", } + EMOJI_RANGES = [ (0x1F600, 0x1F64F), (0x1F300, 0x1F5FF), @@ -36,56 +38,62 @@ EMOJI_RANGES = [ def get_string_no_punctuation_or_emoji(s): - """去除字符串首尾的空格、标点符号和表情符号""" + """Remove spaces, punctuation marks and emojis from the beginning and end of string""" chars = list(s) - # 处理开头的字符 + # Handle characters at the beginning start = 0 while start < len(chars) and is_punctuation_or_emoji(chars[start]): start += 1 - # 处理结尾的字符 + + # Handle characters at the end end = len(chars) - 1 while end >= start and is_punctuation_or_emoji(chars[end]): end -= 1 - return "".join(chars[start : end + 1]) + + return "".join(chars[start: end + 1]) def is_punctuation_or_emoji(char): - """检查字符是否为空格、指定标点或表情符号""" - # 定义需要去除的中英文标点(包括全角/半角) + """Check if character is space, specified punctuation or emoji""" + # Define Chinese and English punctuation to be removed (including full-width/half-width) punctuation_set = { ",", - ",", # 中文逗号 + 英文逗号 + ",", # Chinese comma + English comma "。", - ".", # 中文句号 + 英文句号 + ".", # Chinese period + English period "!", - "!", # 中文感叹号 + 英文感叹号 - "“", - "”", - '"', # 中文双引号 + 英文引号 + "!", # Chinese exclamation + English exclamation + """, + """, + '"', # Chinese quotes + English quotes ":", - ":", # 中文冒号 + 英文冒号 + ":", # Chinese colon + English colon "-", - "-", # 英文连字符 + 中文全角横线 - "、", # 中文顿号 + "-", # English hyphen + Chinese full-width dash + "、", # Chinese enumeration comma "[", - "]", # 方括号 + "]", # Square brackets "【", - "】", # 中文方括号 + "】", # Chinese square brackets } + if char.isspace() or char in punctuation_set: return True + return is_emoji(char) async def get_emotion(conn, text): - """获取文本内的情绪消息""" + """Get emotion message within text""" emoji = "🙂" emotion = "happy" + for char in text: if char in EMOJI_MAP: emoji = char emotion = EMOJI_MAP[char] break + try: await conn.websocket.send( json.dumps( @@ -98,16 +106,17 @@ async def get_emotion(conn, text): ) ) except Exception as e: - conn.logger.bind(tag=TAG).warning(f"发送情绪表情失败,错误:{e}") - return + conn.logger.bind(tag=TAG).warning( + f"Failed to send emotion emoji, error: {e}") + return def is_emoji(char): - """检查字符是否为emoji表情""" + """Check if character is emoji""" code_point = ord(char) return any(start <= code_point <= end for start, end in EMOJI_RANGES) def check_emoji(text): - """去除文本中的所有emoji表情""" - return ''.join(char for char in text if not is_emoji(char) and char != "\n") \ No newline at end of file + """Remove all emojis from text""" + return ''.join(char for char in text if not is_emoji(char) and char != "\n") diff --git a/main/xiaozhi-server/core/utils/tts.py b/main/xiaozhi-server/core/utils/tts.py index eb3836672..7523b9fcf 100644 --- a/main/xiaozhi-server/core/utils/tts.py +++ b/main/xiaozhi-server/core/utils/tts.py @@ -8,29 +8,30 @@ logger = setup_logging() def create_instance(class_name, *args, **kwargs): - # 创建TTS实例 + # Create TTS instance if os.path.exists(os.path.join('core', 'providers', 'tts', f'{class_name}.py')): lib_name = f'core.providers.tts.{class_name}' if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].TTSProvider(*args, **kwargs) - raise ValueError(f"不支持的TTS类型: {class_name},请检查该配置的type是否设置正确") + raise ValueError( + f"Unsupported TTS type: {class_name}, please check if the type configuration is correct") class MarkdownCleaner: """ - 封装 Markdown 清理逻辑:直接用 MarkdownCleaner.clean_markdown(text) 即可 + Encapsulate Markdown cleaning logic: directly use MarkdownCleaner.clean_markdown(text) """ - # 公式字符 + # Formula characters NORMAL_FORMULA_CHARS = re.compile(r'[a-zA-Z\\^_{}\+\-\(\)\[\]=]') @staticmethod def _replace_inline_dollar(m: re.Match) -> str: """ - 只要捕获到完整的 "$...$": - - 如果内部有典型公式字符 => 去掉两侧 $ - - 否则 (纯数字/货币等) => 保留 "$...$" + When capturing complete "$...$": + - If there are typical formula characters inside => remove $ on both sides + - Otherwise (pure numbers/currency etc) => keep "$...$" """ content = m.group(1) if MarkdownCleaner.NORMAL_FORMULA_CHARS.search(content): @@ -41,17 +42,19 @@ class MarkdownCleaner: @staticmethod def _replace_table_block(match: re.Match) -> str: """ - 当匹配到一个整段表格块时,回调该函数。 + When matching an entire table block, this function is called back. """ block_text = match.group('table_block') lines = block_text.strip('\n').split('\n') - parsed_table = [] + for line in lines: line_stripped = line.strip() if re.match(r'^\|\s*[-:]+\s*(\|\s*[-:]+\s*)+\|?$', line_stripped): continue - columns = [col.strip() for col in line_stripped.split('|') if col.strip() != ''] + + columns = [col.strip() + for col in line_stripped.split('|') if col.strip() != ''] if columns: parsed_table.append(columns) @@ -60,53 +63,54 @@ class MarkdownCleaner: headers = parsed_table[0] data_rows = parsed_table[1:] if len(parsed_table) > 1 else [] - lines_for_tts = [] + if len(parsed_table) == 1: - # 只有一行 + # Only one row only_line_str = ", ".join(parsed_table[0]) - lines_for_tts.append(f"单行表格:{only_line_str}") + lines_for_tts.append(f"Single row table: {only_line_str}") else: - lines_for_tts.append(f"表头是:{', '.join(headers)}") + lines_for_tts.append(f"Headers are: {', '.join(headers)}") for i, row in enumerate(data_rows, start=1): row_str_list = [] for col_index, cell_val in enumerate(row): if col_index < len(headers): - row_str_list.append(f"{headers[col_index]} = {cell_val}") + row_str_list.append( + f"{headers[col_index]} = {cell_val}") else: row_str_list.append(cell_val) - lines_for_tts.append(f"第 {i} 行:{', '.join(row_str_list)}") + lines_for_tts.append(f"Row {i}: {', '.join(row_str_list)}") return "\n".join(lines_for_tts) + "\n" - # 预编译所有正则表达式(按执行频率排序) - # 这里要把 replace_xxx 的静态方法放在最前定义,以便在列表里能正确引用它们。 + # Pre-compile all regular expressions (ordered by execution frequency) + # Here we need to put replace_xxx static methods at the front to reference them correctly in the list. REGEXES = [ - (re.compile(r'```.*?```', re.DOTALL), ''), # 代码块 - (re.compile(r'^#+\s*', re.MULTILINE), ''), # 标题 - (re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # 粗体 - (re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\1'), r'\2'), # 斜体 - (re.compile(r'!\[.*?\]\(.*?\)'), ''), # 图片 - (re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # 链接 - (re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # 引用 + (re.compile(r'``````', re.DOTALL), ''), # Code blocks + (re.compile(r'^#+\s*', re.MULTILINE), ''), # Headers + (re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # Bold + (re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\1'), r'\2'), # Italic + (re.compile(r'!\[.*?\]\(.*?\)'), ''), # Images + (re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # Links + (re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # Quotes ( - re.compile(r'(?P(?:^[^\n]*\|[^\n]*\n)+)', re.MULTILINE), + re.compile( + r'(?P(?:^[^\n]*\|[^\n]*\n)+)', re.MULTILINE), _replace_table_block ), - (re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # 列表 - (re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # 块级公式 + (re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # Lists + (re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # Block formulas ( - re.compile(r'(? str: """ - 主入口方法:依序执行所有正则,移除或替换 Markdown 元素 + Main entry method: execute all regex in sequence, remove or replace Markdown elements """ for regex, replacement in MarkdownCleaner.REGEXES: text = regex.sub(replacement, text) - return text.strip() \ No newline at end of file + return text.strip() diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 2c407c3ab..118e72d25 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -13,6 +13,7 @@ from pydub import AudioSegment import copy TAG = __name__ + emoji_map = { "neutral": "😶", "happy": "🙂", @@ -53,7 +54,6 @@ def get_local_ip(): def is_private_ip(ip_addr): """ Check if an IP address is a private IP address (compatible with IPv4 and IPv6). - @param {string} ip_addr - The IP address to check. @return {bool} True if the IP address is private, False otherwise. """ @@ -89,30 +89,31 @@ def is_private_ip(ip_addr): return True # Link-local unicast addresses (FE80::/10) else: return False # Not a private IPv6 address - except (ValueError, IndexError): return False # IP address format error or insufficient segments def get_ip_info(ip_addr, logger): try: - # 导入全局缓存管理器 + # Import global cache manager from core.utils.cache.manager import cache_manager, CacheType - # 先从缓存获取 + # Get from cache first cached_ip_info = cache_manager.get(CacheType.IP_INFO, ip_addr) if cached_ip_info is not None: return cached_ip_info - # 缓存未命中,调用API + # Cache miss, call API if is_private_ip(ip_addr): ip_addr = "" + url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}" resp = requests.get(url).json() ip_info = {"city": resp.get("city")} - # 存入缓存 + # Store in cache cache_manager.set(CacheType.IP_INFO, ip_addr, ip_info) + return ip_info except Exception as e: logger.bind(tag=TAG).error(f"Error getting client ip info: {e}") @@ -120,51 +121,51 @@ def get_ip_info(ip_addr, logger): def write_json_file(file_path, data): - """将数据写入 JSON 文件""" + """Write data to JSON file""" with open(file_path, "w", encoding="utf-8") as file: json.dump(data, file, ensure_ascii=False, indent=4) def remove_punctuation_and_length(text): - # 全角符号和半角符号的Unicode范围 + # Unicode ranges for full-width and half-width symbols full_width_punctuations = ( "!"#$%&'()*+,-。/:;<=>?@[\]^_`{|}~" ) - half_width_punctuations = r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~' - space = " " # 半角空格 - full_width_space = " " # 全角空格 - # 去除全角和半角符号以及空格 + half_width_punctuations = r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~' + space = " " # Half-width space + full_width_space = " " # Full-width space + + # Remove full-width and half-width symbols and spaces result = "".join( - [ - char - for char in text - if char not in full_width_punctuations - and char not in half_width_punctuations - and char not in space - and char not in full_width_space - ] + char + for char in text + if char not in full_width_punctuations + and char not in half_width_punctuations + and char not in space + and char not in full_width_space ) if result == "Yeah": return 0, "" + return len(result), result def check_model_key(modelType, modelKey): if "你" in modelKey: - return f"配置错误: {modelType} 的 API key 未设置,当前值为: {modelKey}" + return f"Configuration error: {modelType} API key not set, current value: {modelKey}" return None def parse_string_to_list(value, separator=";"): """ - 将输入值转换为列表 + Convert input value to list Args: - value: 输入值,可以是 None、字符串或列表 - separator: 分隔符,默认为分号 + value: Input value, can be None, string, or list + separator: Separator, default is semicolon Returns: - list: 处理后的列表 + list: Processed list """ if value is None or value == "": return [] @@ -178,100 +179,107 @@ def parse_string_to_list(value, separator=";"): def check_ffmpeg_installed(): ffmpeg_installed = False try: - # 执行ffmpeg -version命令,并捕获输出 + # Execute ffmpeg -version command and capture output result = subprocess.run( ["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, - check=True, # 如果返回码非零则抛出异常 + check=True, # Throw exception if return code is non-zero ) - # 检查输出中是否包含版本信息(可选) + + # Check if output contains version information (optional) output = result.stdout + result.stderr if "ffmpeg version" in output.lower(): ffmpeg_installed = True - return False + return True except (subprocess.CalledProcessError, FileNotFoundError): - # 命令执行失败或未找到 + # Command execution failed or not found ffmpeg_installed = False + if not ffmpeg_installed: - error_msg = "您的电脑还没正确安装ffmpeg\n" - error_msg += "\n建议您:\n" - error_msg += "1、按照项目的安装文档,正确进入conda环境\n" - error_msg += "2、查阅安装文档,如何在conda环境中安装ffmpeg\n" + error_msg = "ffmpeg is not properly installed on your computer\n" + error_msg += "\nWe recommend that you:\n" + error_msg += "1. Follow the project installation documentation and properly enter the conda environment\n" + error_msg += "2. Refer to the installation documentation on how to install ffmpeg in the conda environment\n" raise ValueError(error_msg) def extract_json_from_string(input_string): - """提取字符串中的 JSON 部分""" + """Extract JSON part from string""" pattern = r"(\{.*\})" - match = re.search(pattern, input_string, re.DOTALL) # 添加 re.DOTALL + match = re.search(pattern, input_string, re.DOTALL) # Add re.DOTALL if match: - return match.group(1) # 返回提取的 JSON 字符串 + return match.group(1) # Return extracted JSON string return None def audio_to_data(audio_file_path, is_opus=True): - # 获取文件后缀名 + # Get file extension file_type = os.path.splitext(audio_file_path)[1] if file_type: file_type = file_type.lstrip(".") - # 读取音频文件,-nostdin 参数:不要从标准输入读取数据,否则FFmpeg会阻塞 + + # Read audio file, -nostdin parameter: don't read data from stdin, otherwise FFmpeg will block audio = AudioSegment.from_file( audio_file_path, format=file_type, parameters=["-nostdin"] ) - # 转换为单声道/16kHz采样率/16位小端编码(确保与编码器匹配) + # Convert to mono/16kHz sample rate/16-bit little endian encoding (ensure match with encoder) audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2) - # 音频时长(秒) + # Audio duration (seconds) duration = len(audio) / 1000.0 - # 获取原始PCM数据(16位小端) + # Get raw PCM data (16-bit little endian) raw_data = audio.raw_data + return pcm_to_data(raw_data, is_opus), duration def audio_bytes_to_data(audio_bytes, file_type, is_opus=True): """ - 直接用音频二进制数据转为opus/pcm数据,支持wav、mp3、p3 + Convert audio binary data directly to opus/pcm data, supports wav, mp3, p3 """ if file_type == "p3": - # 直接用p3解码 + # Decode directly with p3 return p3.decode_opus_from_bytes(audio_bytes) else: - # 其他格式用pydub + # Use pydub for other formats audio = AudioSegment.from_file( BytesIO(audio_bytes), format=file_type, parameters=["-nostdin"] ) + audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2) duration = len(audio) / 1000.0 raw_data = audio.raw_data + return pcm_to_data(raw_data, is_opus), duration def pcm_to_data(raw_data, is_opus=True): - # 初始化Opus编码器 + # Initialize Opus encoder encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO) - # 编码参数 + # Encoding parameters frame_duration = 60 # 60ms per frame frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame datas = [] - # 按帧处理所有音频数据(包括最后一帧可能补零) - for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample - # 获取当前帧的二进制数据 - chunk = raw_data[i : i + frame_size * 2] - # 如果最后一帧不足,补零 + # Process all audio data by frames (including last frame which may be padded with zeros) + for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample + # Get binary data for current frame + chunk = raw_data[i: i + frame_size * 2] + + # If last frame is insufficient, pad with zeros if len(chunk) < frame_size * 2: chunk += b"\x00" * (frame_size * 2 - len(chunk)) if is_opus: - # 转换为numpy数组处理 + # Convert to numpy array for processing np_frame = np.frombuffer(chunk, dtype=np.int16) - # 编码Opus数据 + # Encode Opus data frame_data = encoder.encode(np_frame.tobytes(), frame_size) else: frame_data = chunk if isinstance(chunk, bytes) else bytes(chunk) @@ -283,28 +291,28 @@ def pcm_to_data(raw_data, is_opus=True): def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1): """ - 将opus帧列表解码为wav字节流 + Decode opus frame list to wav byte stream """ decoder = opuslib_next.Decoder(sample_rate, channels) pcm_datas = [] - frame_duration = 60 # ms frame_size = int(sample_rate * frame_duration / 1000) # 960 for opus_frame in opus_datas: - # 解码为PCM(返回bytes,2字节/采样点) + # Decode to PCM (returns bytes, 2 bytes/sample) pcm = decoder.decode(opus_frame, frame_size) pcm_datas.append(pcm) pcm_bytes = b"".join(pcm_datas) - # 写入wav字节流 + # Write to wav byte stream wav_buffer = BytesIO() with wave.open(wav_buffer, "wb") as wf: wf.setnchannels(channels) wf.setsampwidth(2) # 16bit wf.setframerate(sample_rate) wf.writeframes(pcm_bytes) + return wav_buffer.getvalue() @@ -314,20 +322,25 @@ def check_vad_update(before_config, new_config): or new_config["selected_module"].get("VAD") is None ): return False + update_vad = False current_vad_module = before_config["selected_module"]["VAD"] new_vad_module = new_config["selected_module"]["VAD"] + current_vad_type = ( current_vad_module if "type" not in before_config["VAD"][current_vad_module] else before_config["VAD"][current_vad_module]["type"] ) + new_vad_type = ( new_vad_module if "type" not in new_config["VAD"][new_vad_module] else new_config["VAD"][new_vad_module]["type"] ) + update_vad = current_vad_type != new_vad_type + return update_vad @@ -337,30 +350,35 @@ def check_asr_update(before_config, new_config): or new_config["selected_module"].get("ASR") is None ): return False + update_asr = False current_asr_module = before_config["selected_module"]["ASR"] new_asr_module = new_config["selected_module"]["ASR"] + current_asr_type = ( current_asr_module if "type" not in before_config["ASR"][current_asr_module] else before_config["ASR"][current_asr_module]["type"] ) + new_asr_type = ( new_asr_module if "type" not in new_config["ASR"][new_asr_module] else new_config["ASR"][new_asr_module]["type"] ) + update_asr = current_asr_type != new_asr_type + return update_asr def filter_sensitive_info(config: dict) -> dict: """ - 过滤配置中的敏感信息 + Filter sensitive information from configuration Args: - config: 原始配置字典 + config: Original configuration dictionary Returns: - 过滤后的配置字典 + Filtered configuration dictionary """ sensitive_keys = [ "api_key", @@ -380,7 +398,8 @@ def filter_sensitive_info(config: dict) -> dict: elif isinstance(v, dict): filtered[k] = _filter_dict(v) elif isinstance(v, list): - filtered[k] = [_filter_dict(i) if isinstance(i, dict) else i for i in v] + filtered[k] = [_filter_dict(i) if isinstance( + i, dict) else i for i in v] else: filtered[k] = v return filtered @@ -389,34 +408,32 @@ def filter_sensitive_info(config: dict) -> dict: def get_vision_url(config: dict) -> str: - """获取 vision URL - + """Get vision URL Args: - config: 配置字典 - + config: Configuration dictionary Returns: str: vision URL """ server_config = config["server"] vision_explain = server_config.get("vision_explain", "") + if "你的" in vision_explain: local_ip = get_local_ip() port = int(server_config.get("http_port", 8003)) vision_explain = f"http://{local_ip}:{port}/mcp/vision/explain" + return vision_explain def is_valid_image_file(file_data: bytes) -> bool: """ - 检查文件数据是否为有效的图片格式 - + Check if file data is a valid image format Args: - file_data: 文件的二进制数据 - + file_data: Binary data of the file Returns: - bool: 如果是有效的图片格式返回True,否则返回False + bool: True if valid image format, False otherwise """ - # 常见图片格式的魔数(文件头) + # Magic numbers (file headers) for common image formats image_signatures = { b"\xff\xd8\xff": "JPEG", b"\x89PNG\r\n\x1a\n": "PNG", @@ -428,7 +445,7 @@ def is_valid_image_file(file_data: bytes) -> bool: b"RIFF": "WEBP", } - # 检查文件头是否匹配任何已知的图片格式 + # Check if file header matches any known image format for signature in image_signatures: if file_data.startswith(signature): return True @@ -438,30 +455,28 @@ def is_valid_image_file(file_data: bytes) -> bool: def sanitize_tool_name(name: str) -> str: """Sanitize tool names for OpenAI compatibility.""" - # 支持中文、英文字母、数字、下划线和连字符 + # Support Chinese, English letters, numbers, underscores and hyphens return re.sub(r"[^a-zA-Z0-9_\-\u4e00-\u9fff]", "_", name) def validate_mcp_endpoint(mcp_endpoint: str) -> bool: """ - 校验MCP接入点格式 - + Validate MCP endpoint format Args: - mcp_endpoint: MCP接入点字符串 - + mcp_endpoint: MCP endpoint string Returns: - bool: 是否有效 + bool: Whether valid """ - # 1. 检查是否以ws开头 + # 1. Check if starts with ws if not mcp_endpoint.startswith("ws"): return False - # 2. 检查是否包含key、call字样 + # 2. Check if contains key, call keywords if "key" in mcp_endpoint.lower() or "call" in mcp_endpoint.lower(): return False - # 3. 检查是否包含/mcp/字样 + # 3. Check if contains /mcp/ pattern if "/mcp/" not in mcp_endpoint: return False - return True \ No newline at end of file + return True diff --git a/main/xiaozhi-server/core/utils/vad.py b/main/xiaozhi-server/core/utils/vad.py index b1dd1faf8..c31b002a2 100644 --- a/main/xiaozhi-server/core/utils/vad.py +++ b/main/xiaozhi-server/core/utils/vad.py @@ -7,13 +7,12 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() - def create_instance(class_name: str, *args, **kwargs) -> VADProviderBase: - """工厂方法创建VAD实例""" + """Factory method to create VAD instance""" if os.path.exists(os.path.join("core", "providers", "vad", f"{class_name}.py")): lib_name = f"core.providers.vad.{class_name}" if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f"{lib_name}") return sys.modules[lib_name].VADProvider(*args, **kwargs) - - raise ValueError(f"不支持的VAD类型: {class_name},请检查该配置的type是否设置正确") + + raise ValueError(f"Unsupported VAD type: {class_name}, please check if the type configuration is correct") diff --git a/main/xiaozhi-server/core/utils/vllm.py b/main/xiaozhi-server/core/utils/vllm.py index 465580f76..145256949 100644 --- a/main/xiaozhi-server/core/utils/vllm.py +++ b/main/xiaozhi-server/core/utils/vllm.py @@ -1,7 +1,7 @@ import os import sys -# 添加项目根目录到Python路径 +# Add project root directory to Python path current_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.abspath(os.path.join(current_dir, "..", "..")) sys.path.insert(0, project_root) @@ -11,13 +11,12 @@ import importlib logger = setup_logging() - def create_instance(class_name, *args, **kwargs): - # 创建LLM实例 + # Create LLM instance if os.path.exists(os.path.join("core", "providers", "vllm", f"{class_name}.py")): lib_name = f"core.providers.vllm.{class_name}" if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f"{lib_name}") return sys.modules[lib_name].VLLMProvider(*args, **kwargs) - - raise ValueError(f"不支持的VLLM类型: {class_name},请检查该配置的type是否设置正确") + + raise ValueError(f"Unsupported VLLM type: {class_name}, please check if the type configuration is correct") diff --git a/main/xiaozhi-server/core/utils/voiceprint_provider.py b/main/xiaozhi-server/core/utils/voiceprint_provider.py index fb830defc..1ef041996 100644 --- a/main/xiaozhi-server/core/utils/voiceprint_provider.py +++ b/main/xiaozhi-server/core/utils/voiceprint_provider.py @@ -9,40 +9,39 @@ from config.logger import setup_logging TAG = __name__ logger = setup_logging() - class VoiceprintProvider: - """声纹识别服务提供者""" + """Voiceprint recognition service provider""" def __init__(self, config: dict): self.original_url = config.get("url", "") self.speakers = config.get("speakers", []) self.speaker_map = self._parse_speakers() - # 解析API地址和密钥 + # Parse API address and key self.api_url = None self.api_key = None self.speaker_ids = [] if not self.original_url: - logger.bind(tag=TAG).warning("声纹识别URL未配置,声纹识别将被禁用") + logger.bind(tag=TAG).warning("Voiceprint recognition URL not configured, voiceprint recognition will be disabled") self.enabled = False else: - # 解析URL和key + # Parse URL and key parsed_url = urlparse(self.original_url) base_url = f"{parsed_url.scheme}://{parsed_url.netloc}" - # 从查询参数中提取key + # Extract key from query parameters query_params = parse_qs(parsed_url.query) self.api_key = query_params.get('key', [''])[0] if not self.api_key: - logger.bind(tag=TAG).error("URL中未找到key参数,声纹识别将被禁用") + logger.bind(tag=TAG).error("Key parameter not found in URL, voiceprint recognition will be disabled") self.enabled = False else: - # 构造identify接口地址 + # Construct identify interface address self.api_url = f"{base_url}/voiceprint/identify" - # 提取speaker_ids + # Extract speaker_ids for speaker_str in self.speakers: try: parts = speaker_str.split(",", 2) @@ -52,16 +51,16 @@ class VoiceprintProvider: except Exception: continue - # 检查是否有有效的说话人配置 + # Check if there are valid speaker configurations if not self.speaker_ids: - logger.bind(tag=TAG).warning("未配置有效的说话人,声纹识别将被禁用") + logger.bind(tag=TAG).warning("No valid speakers configured, voiceprint recognition will be disabled") self.enabled = False else: self.enabled = True - logger.bind(tag=TAG).info(f"声纹识别已配置: API={self.api_url}, 说话人={len(self.speaker_ids)}个") + logger.bind(tag=TAG).info(f"Voiceprint recognition configured: API={self.api_url}, speakers={len(self.speaker_ids)} total") def _parse_speakers(self) -> Dict[str, Dict[str, str]]: - """解析说话人配置""" + """Parse speaker configuration""" speaker_map = {} for speaker_str in self.speakers: try: @@ -73,62 +72,61 @@ class VoiceprintProvider: "description": description } except Exception as e: - logger.bind(tag=TAG).warning(f"解析说话人配置失败: {speaker_str}, 错误: {e}") + logger.bind(tag=TAG).warning(f"Failed to parse speaker configuration: {speaker_str}, error: {e}") return speaker_map async def identify_speaker(self, audio_data: bytes, session_id: str) -> Optional[str]: - """识别说话人""" + """Identify speaker""" if not self.enabled or not self.api_url or not self.api_key: - logger.bind(tag=TAG).debug("声纹识别功能已禁用或未配置,跳过识别") + logger.bind(tag=TAG).debug("Voiceprint recognition feature disabled or not configured, skipping recognition") return None - + try: api_start_time = time.monotonic() - # 准备请求头 + # Prepare request headers headers = { 'Authorization': f'Bearer {self.api_key}', 'Accept': 'application/json' } - # 准备multipart/form-data数据 + # Prepare multipart/form-data data data = aiohttp.FormData() data.add_field('speaker_ids', ','.join(self.speaker_ids)) data.add_field('file', audio_data, filename='audio.wav', content_type='audio/wav') timeout = aiohttp.ClientTimeout(total=10) - # 网络请求 + # Network request async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(self.api_url, headers=headers, data=data) as response: - if response.status == 200: result = await response.json() speaker_id = result.get("speaker_id") score = result.get("score", 0) + total_elapsed_time = time.monotonic() - api_start_time + logger.bind(tag=TAG).info(f"Voiceprint recognition time: {total_elapsed_time:.3f}s") - logger.bind(tag=TAG).info(f"声纹识别耗时: {total_elapsed_time:.3f}s") - - # 置信度检查 + # Confidence check if score < 0.5: - logger.bind(tag=TAG).warning(f"声纹识别置信度较低: {score:.3f}") + logger.bind(tag=TAG).warning(f"Low voiceprint recognition confidence: {score:.3f}") if speaker_id and speaker_id in self.speaker_map: result_name = self.speaker_map[speaker_id]["name"] return result_name else: - logger.bind(tag=TAG).warning(f"未识别的说话人ID: {speaker_id}") - return "未知说话人" + logger.bind(tag=TAG).warning(f"Unrecognized speaker ID: {speaker_id}") + return "Unknown speaker" else: - logger.bind(tag=TAG).error(f"声纹识别API错误: HTTP {response.status}") + logger.bind(tag=TAG).error(f"Voiceprint recognition API error: HTTP {response.status}") return None - + except asyncio.TimeoutError: elapsed = time.monotonic() - api_start_time - logger.bind(tag=TAG).error(f"声纹识别超时: {elapsed:.3f}s") + logger.bind(tag=TAG).error(f"Voiceprint recognition timeout: {elapsed:.3f}s") return None except Exception as e: elapsed = time.monotonic() - api_start_time - logger.bind(tag=TAG).error(f"声纹识别失败: {e}") - return None \ No newline at end of file + logger.bind(tag=TAG).error(f"Voiceprint recognition failed: {e}") + return None diff --git a/main/xiaozhi-server/core/utils/wakeup_word.py b/main/xiaozhi-server/core/utils/wakeup_word.py index ab58f290b..0d1e82508 100644 --- a/main/xiaozhi-server/core/utils/wakeup_word.py +++ b/main/xiaozhi-server/core/utils/wakeup_word.py @@ -17,11 +17,12 @@ class FileLock: self.start_time = time.time() while True: try: - portalocker.lock(self.file, portalocker.LOCK_EX | portalocker.LOCK_NB) + portalocker.lock( + self.file, portalocker.LOCK_EX | portalocker.LOCK_NB) return self.file except portalocker.LockException: if time.time() - self.start_time > self.timeout: - raise TimeoutError("获取文件锁超时") + raise TimeoutError("File lock acquisition timeout") time.sleep(0.1) def __exit__(self, exc_type, exc_val, exc_tb): @@ -33,21 +34,22 @@ class WakeupWordsConfig: self.config_file = "data/.wakeup_words.yaml" self.assets_dir = "config/assets/wakeup_words" self._ensure_directories() + self._config_cache = None self._last_load_time = 0 - self._cache_ttl = 1 # 缓存有效期(秒) - self._lock_timeout = 5 # 文件锁超时时间(秒) + self._cache_ttl = 1 # Cache TTL (seconds) + self._lock_timeout = 5 # File lock timeout (seconds) def _ensure_directories(self): - """确保必要的目录存在""" + """Ensure necessary directories exist""" os.makedirs(os.path.dirname(self.config_file), exist_ok=True) os.makedirs(self.assets_dir, exist_ok=True) def _load_config(self) -> Dict: - """加载配置文件,使用缓存机制""" + """Load configuration file with caching mechanism""" current_time = time.time() - # 如果缓存有效,直接返回缓存 + # If cache is valid, return cache directly if ( self._config_cache is not None and current_time - self._last_load_time < self._cache_ttl @@ -60,40 +62,45 @@ class WakeupWordsConfig: f.seek(0) content = f.read() config = yaml.safe_load(content) if content else {} + self._config_cache = config self._last_load_time = current_time return config + except (TimeoutError, IOError) as e: - print(f"加载配置文件失败: {e}") + print(f"Failed to load configuration file: {e}") return {} except Exception as e: - print(f"加载配置文件时发生未知错误: {e}") + print( + f"Unknown error occurred while loading configuration file: {e}") return {} def _save_config(self, config: Dict): - """保存配置到文件,使用文件锁保护""" + """Save configuration to file with file lock protection""" try: with open(self.config_file, "w") as f: with FileLock(f, timeout=self._lock_timeout): yaml.dump(config, f, allow_unicode=True) self._config_cache = config self._last_load_time = time.time() + except (TimeoutError, IOError) as e: - print(f"保存配置文件失败: {e}") + print(f"Failed to save configuration file: {e}") raise except Exception as e: - print(f"保存配置文件时发生未知错误: {e}") + print( + f"Unknown error occurred while saving configuration file: {e}") raise def get_wakeup_response(self, voice: str) -> Dict: + """Get wakeup word response configuration""" voice = hashlib.md5(voice.encode()).hexdigest() - """获取唤醒词回复配置""" config = self._load_config() if not config or voice not in config: return None - # 检查文件大小 + # Check file size file_path = config[voice]["file_path"] if not os.path.exists(file_path) or os.stat(file_path).st_size < (15 * 1024): return None @@ -101,40 +108,45 @@ class WakeupWordsConfig: return config[voice] def update_wakeup_response(self, voice: str, file_path: str, text: str): - """更新唤醒词回复配置""" + """Update wakeup word response configuration""" try: - # 过滤表情符号 - filtered_text = re.sub(r'[\U0001F600-\U0001F64F\U0001F900-\U0001F9FF]', '', text) - + # Filter emoji symbols + filtered_text = re.sub( + r'[\U0001F600-\U0001F64F\U0001F900-\U0001F9FF]', '', text) + config = self._load_config() voice_hash = hashlib.md5(voice.encode()).hexdigest() + config[voice_hash] = { "voice": voice, "file_path": file_path, "time": time.time(), "text": filtered_text, } + self._save_config(config) + except Exception as e: - print(f"更新唤醒词回复配置失败: {e}") + print(f"Failed to update wakeup word response configuration: {e}") raise def generate_file_path(self, voice: str) -> str: - """生成音频文件路径,使用voice的哈希值作为文件名""" + """Generate audio file path using voice hash as filename""" try: - # 生成voice的哈希值 + # Generate hash of voice voice_hash = hashlib.md5(voice.encode()).hexdigest() file_path = os.path.join(self.assets_dir, f"{voice_hash}.wav") - # 如果文件已存在,先删除 + # If file already exists, delete it first if os.path.exists(file_path): try: os.remove(file_path) except Exception as e: - print(f"删除已存在的音频文件失败: {e}") + print(f"Failed to delete existing audio file: {e}") raise return file_path + except Exception as e: - print(f"生成音频文件路径失败: {e}") + print(f"Failed to generate audio file path: {e}") raise diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index bebce3a42..d32b4e223 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -14,6 +14,7 @@ class WebSocketServer: self.config = config self.logger = setup_logging() self.config_lock = asyncio.Lock() + modules = initialize_modules( self.logger, self.config, @@ -24,6 +25,7 @@ class WebSocketServer: "Memory" in self.config["selected_module"], "Intent" in self.config["selected_module"], ) + self._vad = modules["vad"] if "vad" in modules else None self._asr = modules["asr"] if "asr" in modules else None self._llm = modules["llm"] if "llm" in modules else None @@ -43,8 +45,8 @@ class WebSocketServer: await asyncio.Future() async def _handle_connection(self, websocket): - """处理新连接,每次创建独立的ConnectionHandler""" - # 创建ConnectionHandler时传入当前server实例 + """Handle new connection, create independent ConnectionHandler each time""" + # Pass current server instance when creating ConnectionHandler handler = ConnectionHandler( self.config, self._vad, @@ -52,63 +54,54 @@ class WebSocketServer: self._llm, self._memory, self._intent, - self, # 传入server实例 + self, # Pass 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}") finally: - # 确保从活动连接集合中移除 self.active_connections.discard(handler) - # 强制关闭连接(如果还没有关闭的话) - try: - # 安全地检查WebSocket状态并关闭 - if hasattr(websocket, "closed") and not websocket.closed: - await websocket.close() - elif hasattr(websocket, "state") and websocket.state.name != "CLOSED": - await websocket.close() - else: - # 如果没有closed属性,直接尝试关闭 - await websocket.close() - except Exception as close_error: - self.logger.bind(tag=TAG).error( - f"服务器端强制关闭连接时出错: {close_error}" - ) async def _http_response(self, websocket, request_headers): - # 检查是否为 WebSocket 升级请求 + # Check if it's a WebSocket upgrade request if request_headers.headers.get("connection", "").lower() == "upgrade": - # 如果是 WebSocket 请求,返回 None 允许握手继续 + # If it's a WebSocket request, return None to allow handshake to continue return None else: - # 如果是普通 HTTP 请求,返回 "server is running" + # If it's a regular 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 update was successful """ try: async with self.config_lock: - # 重新获取配置 + # Get configuration again 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"Successfully got new configuration") + + # Check if VAD and ASR types need updating 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 updating: {update_vad} {update_asr}" ) - # 更新配置 + + # Update configuration self.config = new_config - # 重新初始化组件 + + # Reinitialize components modules = initialize_modules( self.logger, new_config, @@ -120,7 +113,7 @@ class WebSocketServer: "Intent" in new_config["selected_module"], ) - # 更新组件实例 + # Update component instances if "vad" in modules: self._vad = modules["vad"] if "asr" in modules: @@ -131,8 +124,12 @@ 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"Configuration update task completed") return True + except Exception as e: - self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}") - return False \ No newline at end of file + self.logger.bind(tag=TAG).error( + f"Failed to update server configuration: {str(e)}") + return False diff --git a/main/xiaozhi-server/performance_tester.py b/main/xiaozhi-server/performance_tester.py index a5fc52219..b07feb42a 100644 --- a/main/xiaozhi-server/performance_tester.py +++ b/main/xiaozhi-server/performance_tester.py @@ -4,16 +4,14 @@ import os import statistics import time from typing import Dict - import aiohttp from tabulate import tabulate - from config.settings import load_config from core.utils.asr import create_instance as create_stt_instance from core.utils.llm import create_instance as create_llm_instance from core.utils.tts import create_instance as create_tts_instance -# 设置全局日志级别为WARNING,抑制INFO级别日志 +# Set global log level to WARNING, suppress INFO level logs logging.basicConfig(level=logging.WARNING) @@ -23,9 +21,9 @@ class AsyncPerformanceTester: self.test_sentences = self.config.get("module_test", {}).get( "test_sentences", [ - "你好,请介绍一下你自己", + "Hello, please introduce yourself", "What's the weather like today?", - "请用100字概括量子计算的基本原理和应用前景", + "Please summarize the basic principles and application prospects of quantum computing in 100 words", ], ) @@ -33,7 +31,7 @@ class AsyncPerformanceTester: self.wav_root = r"config/assets" for file_name in os.listdir(self.wav_root): file_path = os.path.join(self.wav_root, file_name) - # 检查文件大小是否大于300KB + # Check if file size is larger than 300KB if os.path.getsize(file_path) > 300 * 1024: # 300KB = 300 * 1024 bytes with open(file_path, "rb") as f: self.test_wav_list.append(f.read()) @@ -41,57 +39,60 @@ class AsyncPerformanceTester: self.results = {"llm": {}, "tts": {}, "stt": {}, "combinations": []} async def _check_ollama_service(self, base_url: str, model_name: str) -> bool: - """异步检查Ollama服务状态""" + """Asynchronously check Ollama service status""" async with aiohttp.ClientSession() as session: try: - # 检查服务是否可用 + # Check if service is available async with session.get(f"{base_url}/api/version") as response: if response.status != 200: - print(f"🚫 Ollama服务未启动或无法访问: {base_url}") + print( + f"🚫 Ollama service not started or inaccessible: {base_url}") return False - # 检查模型是否存在 + # Check if model exists async with session.get(f"{base_url}/api/tags") as response: if response.status == 200: data = await response.json() models = data.get("models", []) if not any(model["name"] == model_name for model in models): print( - f"🚫 Ollama模型 {model_name} 未找到,请先使用 ollama pull {model_name} 下载" + f"🚫 Ollama model {model_name} not found, please use ollama pull {model_name} to download first" ) return False else: - print(f"🚫 无法获取Ollama模型列表") + print(f"🚫 Unable to get Ollama model list") return False + return True except Exception as e: - print(f"🚫 无法连接到Ollama服务: {str(e)}") + print(f"🚫 Unable to connect to Ollama service: {str(e)}") return False async def _test_tts(self, tts_name: str, config: Dict) -> Dict: - """异步测试单个TTS性能""" + """Asynchronously test single TTS performance""" try: - logging.getLogger("core.providers.tts.base").setLevel(logging.WARNING) - + logging.getLogger("core.providers.tts.base").setLevel( + logging.WARNING) token_fields = ["access_token", "api_key", "token"] if any( field in config and any(x in config[field] for x in ["你的", "placeholder"]) for field in token_fields ): - print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过") + print( + f"⏭️ TTS {tts_name} access_token/api_key not configured, skipped") return {"name": tts_name, "type": "tts", "errors": 1} module_type = config.get("type", tts_name) - tts = create_tts_instance(module_type, config, delete_audio_file=True) - - print(f"🎵 测试 TTS: {tts_name}") + tts = create_tts_instance( + module_type, config, delete_audio_file=True) + print(f"🎵 Testing TTS: {tts_name}") tmp_file = tts.generate_filename() - await tts.text_to_speak("连接测试", tmp_file) + await tts.text_to_speak("Connection test", tmp_file) if not tmp_file or not os.path.exists(tmp_file): - print(f"❌ {tts_name} 连接失败") + print(f"❌ {tts_name} connection failed") return {"name": tts_name, "type": "tts", "errors": 1} total_time = 0 @@ -118,34 +119,36 @@ class AsyncPerformanceTester: } except Exception as e: - print(f"⚠️ {tts_name} 测试失败: {str(e)}") + print(f"⚠️ {tts_name} test failed: {str(e)}") return {"name": tts_name, "type": "tts", "errors": 1} async def _test_stt(self, stt_name: str, config: Dict) -> Dict: - """异步测试单个STT性能""" + """Asynchronously test single STT performance""" try: - logging.getLogger("core.providers.asr.base").setLevel(logging.WARNING) + logging.getLogger("core.providers.asr.base").setLevel( + logging.WARNING) token_fields = ["access_token", "api_key", "token"] if any( field in config and any(x in config[field] for x in ["你的", "placeholder"]) for field in token_fields ): - print(f"⏭️ STT {stt_name} 未配置access_token/api_key,已跳过") + print( + f"⏭️ STT {stt_name} access_token/api_key not configured, skipped") return {"name": stt_name, "type": "stt", "errors": 1} module_type = config.get("type", stt_name) - stt = create_stt_instance(module_type, config, delete_audio_file=True) + stt = create_stt_instance( + module_type, config, delete_audio_file=True) stt.audio_format = "pcm" - print(f"🎵 测试 STT: {stt_name}") - + print(f"🎵 Testing STT: {stt_name}") text, _ = await stt.speech_to_text( [self.test_wav_list[0]], "1", stt.audio_format ) if text is None: - print(f"❌ {stt_name} 连接失败") + print(f"❌ {stt_name} connection failed") return {"name": stt_name, "type": "stt", "errors": 1} total_time = 0 @@ -171,18 +174,18 @@ class AsyncPerformanceTester: } except Exception as e: - print(f"⚠️ {stt_name} 测试失败: {str(e)}") + print(f"⚠️ {stt_name} test failed: {str(e)}") return {"name": stt_name, "type": "stt", "errors": 1} async def _test_llm(self, llm_name: str, config: Dict) -> Dict: - """异步测试单个LLM性能""" + """Asynchronously test single LLM performance""" try: - # 对于Ollama,跳过api_key检查并进行特殊处理 + # For Ollama, skip api_key check and perform special handling if llm_name == "Ollama": base_url = config.get("base_url", "http://localhost:11434") model_name = config.get("model_name") if not model_name: - print(f"🚫 Ollama未配置model_name") + print(f"🚫 Ollama model_name not configured") return {"name": llm_name, "type": "llm", "errors": 1} if not await self._check_ollama_service(base_url, model_name): @@ -191,44 +194,48 @@ class AsyncPerformanceTester: if "api_key" in config and any( x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"] ): - print(f"🚫 跳过未配置的LLM: {llm_name}") + print(f"🚫 Skipping unconfigured LLM: {llm_name}") return {"name": llm_name, "type": "llm", "errors": 1} - # 获取实际类型(兼容旧配置) + # Get actual type (compatible with old configuration) module_type = config.get("type", llm_name) llm = create_llm_instance(module_type, config) - # 统一使用UTF-8编码 + # Uniformly use UTF-8 encoding test_sentences = [ s.encode("utf-8").decode("utf-8") for s in self.test_sentences ] - # 创建所有句子的测试任务 + # Create test tasks for all sentences sentence_tasks = [] for sentence in test_sentences: sentence_tasks.append( self._test_single_sentence(llm_name, llm, sentence) ) - # 并发执行所有句子测试 + # Execute all sentence tests concurrently sentence_results = await asyncio.gather(*sentence_tasks) - # 处理结果 + # Process results valid_results = [r for r in sentence_results if r is not None] if not valid_results: - print(f"⚠️ {llm_name} 无有效数据,可能配置错误") + print( + f"⚠️ {llm_name} no valid data, configuration may be incorrect") return {"name": llm_name, "type": "llm", "errors": 1} first_token_times = [r["first_token_time"] for r in valid_results] response_times = [r["response_time"] for r in valid_results] - # 过滤异常数据 + # Filter abnormal data mean = statistics.mean(response_times) - stdev = statistics.stdev(response_times) if len(response_times) > 1 else 0 - filtered_times = [t for t in response_times if t <= mean + 3 * stdev] + stdev = statistics.stdev(response_times) if len( + response_times) > 1 else 0 + filtered_times = [ + t for t in response_times if t <= mean + 3 * stdev] if len(filtered_times) < len(test_sentences) * 0.5: - print(f"⚠️ {llm_name} 有效数据不足,可能网络不稳定") + print( + f"⚠️ {llm_name} insufficient valid data, network may be unstable") return {"name": llm_name, "type": "llm", "errors": 1} return { @@ -242,18 +249,20 @@ class AsyncPerformanceTester: else 0 ), "std_response": ( - statistics.stdev(response_times) if len(response_times) > 1 else 0 + statistics.stdev(response_times) if len( + response_times) > 1 else 0 ), "errors": 0, } + except Exception as e: - print(f"LLM {llm_name} 测试失败: {str(e)}") + print(f"LLM {llm_name} test failed: {str(e)}") return {"name": llm_name, "type": "llm", "errors": 1} async def _test_single_sentence(self, llm_name: str, llm, sentence: str) -> Dict: - """测试单个句子的性能""" + """Test performance of a single sentence""" try: - print(f"📝 {llm_name} 开始测试: {sentence[:20]}...") + print(f"📝 {llm_name} starting test: {sentence[:20]}...") sentence_start = time.time() first_token_received = False first_token_time = None @@ -266,7 +275,8 @@ class AsyncPerformanceTester: if not first_token_received and chunk.strip() != "": first_token_time = time.time() - sentence_start first_token_received = True - print(f"✓ {llm_name} 首个Token: {first_token_time:.3f}s") + print( + f"✓ {llm_name} first token: {first_token_time:.3f}s") yield chunk response_chunks = [] @@ -274,11 +284,11 @@ class AsyncPerformanceTester: response_chunks.append(chunk) response_time = time.time() - sentence_start - print(f"✓ {llm_name} 完成响应: {response_time:.3f}s") + print(f"✓ {llm_name} response completed: {response_time:.3f}s") if first_token_time is None: first_token_time = ( - response_time # 如果没有检测到first token,使用总响应时间 + response_time # If no first token detected, use total response time ) return { @@ -287,23 +297,27 @@ class AsyncPerformanceTester: "first_token_time": first_token_time, "response_time": response_time, } + except Exception as e: - print(f"⚠️ {llm_name} 句子测试失败: {str(e)}") + print(f"⚠️ {llm_name} sentence test failed: {str(e)}") return None def _generate_combinations(self): - """生成最佳组合建议""" + """Generate best combination recommendations""" valid_llms = [ k for k, v in self.results["llm"].items() if v["errors"] == 0 and v["avg_first_token"] >= 0.05 ] - valid_tts = [k for k, v in self.results["tts"].items() if v["errors"] == 0] - valid_stt = [k for k, v in self.results["stt"].items() if v["errors"] == 0] + valid_tts = [k for k, v in self.results["tts"].items() + if v["errors"] == 0] + valid_stt = [k for k, v in self.results["stt"].items() + if v["errors"] == 0] - # 找出基准值 + # Find benchmark values min_first_token = ( - min([self.results["llm"][llm]["avg_first_token"] for llm in valid_llms]) + min([self.results["llm"][llm]["avg_first_token"] + for llm in valid_llms]) if valid_llms else 1 ) @@ -321,24 +335,27 @@ class AsyncPerformanceTester: for llm in valid_llms: for tts in valid_tts: for stt in valid_stt: - # 计算相对性能分数(越小越好) + # Calculate relative performance score (smaller is better) llm_score = ( - self.results["llm"][llm]["avg_first_token"] / min_first_token + self.results["llm"][llm]["avg_first_token"] / + min_first_token ) - tts_score = self.results["tts"][tts]["avg_time"] / min_tts_time - stt_score = self.results["stt"][stt]["avg_time"] / min_stt_time + tts_score = self.results["tts"][tts]["avg_time"] / \ + min_tts_time + stt_score = self.results["stt"][stt]["avg_time"] / \ + min_stt_time - # 计算稳定性分数(标准差/平均值,越小越稳定) + # Calculate stability score (standard deviation/average, smaller is more stable) llm_stability = ( self.results["llm"][llm]["std_first_token"] / self.results["llm"][llm]["avg_first_token"] ) - # 综合得分(考虑性能和稳定性) - # LLM得分: 性能权重(70%) + 稳定性权重(30%) + # Comprehensive score (considering performance and stability) + # LLM score: performance weight(70%) + stability weight(30%) llm_final_score = llm_score * 0.7 + llm_stability * 0.3 - # 总分 = LLM得分(70%) + TTS得分(30%) + STT得分(30%) + # Total score = LLM score(70%) + TTS score(30%) + STT score(30%) total_score = ( llm_final_score * 0.7 + tts_score * 0.3 + stt_score * 0.3 ) @@ -360,88 +377,92 @@ class AsyncPerformanceTester: } ) - # 分数越小越好 + # Smaller score is better self.results["combinations"].sort(key=lambda x: x["score"]) def _print_results(self): - """打印测试结果""" + """Print test results""" llm_table = [] for name, data in self.results["llm"].items(): if data["errors"] == 0: stability = data["std_first_token"] / data["avg_first_token"] llm_table.append( [ - name, # 不需要固定宽度,让tabulate自己处理对齐 - f"{data['avg_first_token']:.3f}秒", - f"{data['avg_response']:.3f}秒", + name, # No need for fixed width, let tabulate handle alignment + f"{data['avg_first_token']:.3f}s", + f"{data['avg_response']:.3f}s", f"{stability:.3f}", ] ) if llm_table: - print("\nLLM 性能排行:\n") + print("\nLLM Performance Rankings:\n") print( tabulate( llm_table, - headers=["模型名称", "首字耗时", "总耗时", "稳定性"], + headers=["Model Name", "First Token Time", + "Total Time", "Stability"], tablefmt="github", colalign=("left", "right", "right", "right"), disable_numparse=True, ) ) else: - print("\n⚠️ 没有可用的LLM模块进行测试。") + print("\n⚠️ No available LLM modules for testing.") tts_table = [] for name, data in self.results["tts"].items(): if data["errors"] == 0: - tts_table.append([name, f"{data['avg_time']:.3f}秒"]) # 不需要固定宽度 + # No need for fixed width + tts_table.append([name, f"{data['avg_time']:.3f}s"]) if tts_table: - print("\nTTS 性能排行:\n") + print("\nTTS Performance Rankings:\n") print( tabulate( tts_table, - headers=["模型名称", "合成耗时"], + headers=["Model Name", "Synthesis Time"], tablefmt="github", colalign=("left", "right"), disable_numparse=True, ) ) else: - print("\n⚠️ 没有可用的TTS模块进行测试。") + print("\n⚠️ No available TTS modules for testing.") stt_table = [] for name, data in self.results["stt"].items(): if data["errors"] == 0: - stt_table.append([name, f"{data['avg_time']:.3f}秒"]) # 不需要固定宽度 + # No need for fixed width + stt_table.append([name, f"{data['avg_time']:.3f}s"]) if stt_table: - print("\nSTT 性能排行:\n") + print("\nSTT Performance Rankings:\n") print( tabulate( stt_table, - headers=["模型名称", "合成耗时"], + headers=["Model Name", "Recognition Time"], tablefmt="github", colalign=("left", "right"), disable_numparse=True, ) ) else: - print("\n⚠️ 没有可用的STT模块进行测试。") + print("\n⚠️ No available STT modules for testing.") if self.results["combinations"]: - print("\n推荐配置组合 (得分越小越好):\n") + print("\nRecommended Configuration Combinations (smaller score is better):\n") combo_table = [] - for combo in self.results["combinations"][:]: + for combo in self.results["combinations"][:5]: combo_table.append( [ - f"{combo['llm']} + {combo['tts']} + {combo['stt']}", # 不需要固定宽度 + # No need for fixed width + f"{combo['llm']} + {combo['tts']} + {combo['stt']}", f"{combo['score']:.3f}", - f"{combo['details']['llm_first_token']:.3f}秒", + f"{combo['details']['llm_first_token']:.3f}s", f"{combo['details']['llm_stability']:.3f}", - f"{combo['details']['tts_time']:.3f}秒", - f"{combo['details']['stt_time']:.3f}秒", + f"{combo['details']['tts_time']:.3f}s", + f"{combo['details']['stt_time']:.3f}s", ] ) @@ -449,23 +470,24 @@ class AsyncPerformanceTester: tabulate( combo_table, headers=[ - "组合方案", - "综合得分", - "LLM首字耗时", - "稳定性", - "TTS合成耗时", - "STT合成耗时", + "Combination Plan", + "Comprehensive Score", + "LLM First Token Time", + "Stability", + "TTS Synthesis Time", + "STT Recognition Time", ], tablefmt="github", - colalign=("left", "right", "right", "right", "right", "right"), + colalign=("left", "right", "right", + "right", "right", "right"), disable_numparse=True, ) ) else: - print("\n⚠️ 没有可用的模块组合建议。") + print("\n⚠️ No available module combination recommendations.") def _process_results(self, all_results): - """处理测试结果""" + """Process test results""" for result in all_results: if result["errors"] == 0: if result["type"] == "llm": @@ -478,51 +500,52 @@ class AsyncPerformanceTester: pass async def run(self): - """执行全量异步测试""" - print("🔍 开始筛选可用模块...") + """Execute full asynchronous testing""" + print("🔍 Starting to filter available modules...") - # 创建所有测试任务 + # Create all test tasks all_tasks = [] - # LLM测试任务 + # LLM test tasks if self.config.get("LLM") is not None: for llm_name, config in self.config.get("LLM", {}).items(): - # 检查配置有效性 + # Check configuration validity if llm_name == "CozeLLM": if any(x in config.get("bot_id", "") for x in ["你的"]) or any( x in config.get("user_id", "") for x in ["你的"] ): - print(f"⏭️ LLM {llm_name} 未配置bot_id/user_id,已跳过") + print( + f"⏭️ LLM {llm_name} bot_id/user_id not configured, skipped") continue elif "api_key" in config and any( x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"] ): - print(f"⏭️ LLM {llm_name} 未配置api_key,已跳过") + print(f"⏭️ LLM {llm_name} api_key not configured, skipped") continue - # 对于Ollama,先检查服务状态 + # For Ollama, check service status first if llm_name == "Ollama": base_url = config.get("base_url", "http://localhost:11434") model_name = config.get("model_name") if not model_name: - print(f"🚫 Ollama未配置model_name") + print(f"🚫 Ollama model_name not configured") continue if not await self._check_ollama_service(base_url, model_name): continue - print(f"📋 添加LLM测试任务: {llm_name}") + print(f"📋 Adding LLM test task: {llm_name}") module_type = config.get("type", llm_name) llm = create_llm_instance(module_type, config) - # 为每个句子创建独立任务 + # Create independent tasks for each sentence for sentence in self.test_sentences: sentence = sentence.encode("utf-8").decode("utf-8") all_tasks.append( self._test_single_sentence(llm_name, llm, sentence) ) - # TTS测试任务 + # TTS test tasks if self.config.get("TTS") is not None: for tts_name, config in self.config.get("TTS", {}).items(): token_fields = ["access_token", "api_key", "token"] @@ -531,12 +554,14 @@ class AsyncPerformanceTester: and any(x in config[field] for x in ["你的", "placeholder"]) for field in token_fields ): - print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过") + print( + f"⏭️ TTS {tts_name} access_token/api_key not configured, skipped") continue - print(f"🎵 添加TTS测试任务: {tts_name}") + + print(f"🎵 Adding TTS test task: {tts_name}") all_tasks.append(self._test_tts(tts_name, config)) - # STT测试任务 + # STT test tasks if len(self.test_wav_list) >= 1: if self.config.get("ASR") is not None: for stt_name, config in self.config.get("ASR", {}).items(): @@ -546,28 +571,32 @@ class AsyncPerformanceTester: and any(x in config[field] for x in ["你的", "placeholder"]) for field in token_fields ): - print(f"⏭️ ASR {stt_name} 未配置access_token/api_key,已跳过") + print( + f"⏭️ ASR {stt_name} access_token/api_key not configured, skipped") continue - print(f"🎵 添加ASR测试任务: {stt_name}") + + print(f"🎵 Adding ASR test task: {stt_name}") all_tasks.append(self._test_stt(stt_name, config)) else: - print(f"\n⚠️ {self.wav_root} 路径下没有音频文件,已跳过STT测试任务") + print( + f"\n⚠️ No audio files found in {self.wav_root} path, STT test tasks skipped") print( - f"\n✅ 找到 {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} 个可用LLM模块" + f"\n✅ Found {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} available LLM modules" ) print( - f"✅ 找到 {len([t for t in all_tasks if '_test_tts' in str(t)])} 个可用TTS模块" + f"✅ Found {len([t for t in all_tasks if '_test_tts' in str(t)])} available TTS modules" ) print( - f"✅ 找到 {len([t for t in all_tasks if '_test_stt' in str(t)])} 个可用STT模块" + f"✅ Found {len([t for t in all_tasks if '_test_stt' in str(t)])} available STT modules" ) - print("\n⏳ 开始并发测试所有模块...\n") - # 并发执行所有测试任务 + print("\n⏳ Starting concurrent testing of all modules...\n") + + # Execute all test tasks concurrently all_results = await asyncio.gather(*all_tasks, return_exceptions=True) - # 处理LLM结果 + # Process LLM results llm_results = {} for result in [ r @@ -583,12 +612,14 @@ class AsyncPerformanceTester: "response_times": [], "errors": 0, } + llm_results[llm_name]["first_token_times"].append( result["first_token_time"] ) - llm_results[llm_name]["response_times"].append(result["response_time"]) + llm_results[llm_name]["response_times"].append( + result["response_time"]) - # 计算LLM平均值和标准差 + # Calculate LLM averages and standard deviations for llm_name, data in llm_results.items(): if len(data["first_token_times"]) >= len(self.test_sentences) * 0.5: self.results["llm"][llm_name] = { @@ -611,7 +642,7 @@ class AsyncPerformanceTester: "errors": 0, } - # 处理TTS结果 + # Process TTS results for result in [ r for r in all_results @@ -620,7 +651,7 @@ class AsyncPerformanceTester: if result["errors"] == 0: self.results["tts"][result["name"]] = result - # 处理STT结果 + # Process STT results for result in [ r for r in all_results @@ -629,8 +660,8 @@ class AsyncPerformanceTester: if result["errors"] == 0: self.results["stt"][result["name"]] = result - # 生成组合建议并打印结果 - print("\n📊 生成测试报告...") + # Generate combination recommendations and print results + print("\n📊 Generating test report...") self._generate_combinations() self._print_results() @@ -639,6 +670,5 @@ async def main(): tester = AsyncPerformanceTester() await tester.run() - if __name__ == "__main__": asyncio.run(main()) diff --git a/main/xiaozhi-server/performance_tester_vllm.py b/main/xiaozhi-server/performance_tester_vllm.py index 4dafddcc1..d49843ae5 100644 --- a/main/xiaozhi-server/performance_tester_vllm.py +++ b/main/xiaozhi-server/performance_tester_vllm.py @@ -8,7 +8,7 @@ from tabulate import tabulate from config.settings import load_config from core.utils.vllm import create_instance -# 设置全局日志级别为WARNING,抑制INFO级别日志 +# Set global log level to WARNING, suppress INFO level logs logging.basicConfig(level=logging.WARNING) @@ -20,55 +20,60 @@ class AsyncVisionPerformanceTester: "../../docs/images/demo2.png", ] self.test_questions = [ - "这张图片里有什么?", - "请详细描述这张图片的内容", + "What's in this image?", + "Please describe the content of this image in detail", ] - # 加载测试图片 + # Load test images self.results = {"vllm": {}} async def _test_vllm(self, vllm_name: str, config: Dict) -> Dict: - """异步测试单个视觉大模型性能""" + """Asynchronously test single vision large model performance""" try: - # 检查API密钥配置 + # Check API key configuration if "api_key" in config and any( x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"] ): - print(f"⏭️ VLLM {vllm_name} 未配置api_key,已跳过") + print(f"⏭️ VLLM {vllm_name} api_key not configured, skipped") return {"name": vllm_name, "type": "vllm", "errors": 1} - # 获取实际类型(兼容旧配置) + # Get actual type (compatible with old configuration) module_type = config.get("type", vllm_name) vllm = create_instance(module_type, config) - print(f"🖼️ 测试 VLLM: {vllm_name}") + print(f"🖼️ Testing VLLM: {vllm_name}") - # 创建所有测试任务 + # Create all test tasks test_tasks = [] for question in self.test_questions: for image in self.test_images: test_tasks.append( - self._test_single_vision(vllm_name, vllm, question, image) + self._test_single_vision( + vllm_name, vllm, question, image) ) - # 并发执行所有测试 + # Execute all tests concurrently test_results = await asyncio.gather(*test_tasks) - # 处理结果 + # Process results valid_results = [r for r in test_results if r is not None] if not valid_results: - print(f"⚠️ {vllm_name} 无有效数据,可能配置错误") + print( + f"⚠️ {vllm_name} no valid data, configuration may be incorrect") return {"name": vllm_name, "type": "vllm", "errors": 1} response_times = [r["response_time"] for r in valid_results] - # 过滤异常数据 + # Filter abnormal data mean = statistics.mean(response_times) - stdev = statistics.stdev(response_times) if len(response_times) > 1 else 0 - filtered_times = [t for t in response_times if t <= mean + 3 * stdev] + stdev = statistics.stdev(response_times) if len( + response_times) > 1 else 0 + filtered_times = [ + t for t in response_times if t <= mean + 3 * stdev] if len(filtered_times) < len(test_tasks) * 0.5: - print(f"⚠️ {vllm_name} 有效数据不足,可能网络不稳定") + print( + f"⚠️ {vllm_name} insufficient valid data, network may be unstable") return {"name": vllm_name, "type": "vllm", "errors": 1} return { @@ -76,44 +81,47 @@ class AsyncVisionPerformanceTester: "type": "vllm", "avg_response": sum(response_times) / len(response_times), "std_response": ( - statistics.stdev(response_times) if len(response_times) > 1 else 0 + statistics.stdev(response_times) if len( + response_times) > 1 else 0 ), "errors": 0, } except Exception as e: - print(f"⚠️ VLLM {vllm_name} 测试失败: {str(e)}") + print(f"⚠️ VLLM {vllm_name} test failed: {str(e)}") return {"name": vllm_name, "type": "vllm", "errors": 1} async def _test_single_vision( self, vllm_name: str, vllm, question: str, image: str ) -> Dict: - """测试单个视觉问题的性能""" + """Test performance of a single vision question""" try: - print(f"📝 {vllm_name} 开始测试: {question[:20]}...") + print(f"📝 {vllm_name} starting test: {question[:20]}...") start_time = time.time() - # 读取图片并转换为base64 + # Read image and convert to base64 with open(image, "rb") as image_file: image_data = image_file.read() image_base64 = base64.b64encode(image_data).decode("utf-8") - # 直接获取响应 + # Get response directly response = vllm.response(question, image_base64) response_time = time.time() - start_time - print(f"✓ {vllm_name} 完成响应: {response_time:.3f}s") + + print(f"✓ {vllm_name} response completed: {response_time:.3f}s") return { "name": vllm_name, "type": "vllm", "response_time": response_time, } + except Exception as e: - print(f"⚠️ {vllm_name} 测试失败: {str(e)}") + print(f"⚠️ {vllm_name} test failed: {str(e)}") return None def _print_results(self): - """打印测试结果""" + """Print test results""" vllm_table = [] for name, data in self.results["vllm"].items(): if data["errors"] == 0: @@ -121,62 +129,65 @@ class AsyncVisionPerformanceTester: vllm_table.append( [ name, - f"{data['avg_response']:.3f}秒", + f"{data['avg_response']:.3f}s", f"{stability:.3f}", ] ) if vllm_table: - print("\n视觉大模型性能排行:\n") + print("\nVision Large Model Performance Rankings:\n") print( tabulate( vllm_table, - headers=["模型名称", "响应耗时", "稳定性"], + headers=["Model Name", "Response Time", "Stability"], tablefmt="github", colalign=("left", "right", "right"), disable_numparse=True, ) ) else: - print("\n⚠️ 没有可用的视觉大模型进行测试。") + print("\n⚠️ No available vision large models for testing.") async def run(self): - """执行全量异步测试""" - print("🔍 开始筛选可用视觉大模型...") + """Execute full asynchronous testing""" + print("🔍 Starting to filter available vision large models...") if not self.test_images: - print(f"\n⚠️ {self.image_root} 路径下没有图片文件,无法进行测试") + print(f"\n⚠️ No image files found in path, testing cannot proceed") return - # 创建所有测试任务 + # Create all test tasks all_tasks = [] - # VLLM测试任务 + # VLLM test tasks if self.config.get("VLLM") is not None: for vllm_name, config in self.config.get("VLLM", {}).items(): if "api_key" in config and any( x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"] ): - print(f"⏭️ VLLM {vllm_name} 未配置api_key,已跳过") + print( + f"⏭️ VLLM {vllm_name} api_key not configured, skipped") continue - print(f"🖼️ 添加VLLM测试任务: {vllm_name}") + + print(f"🖼️ Adding VLLM test task: {vllm_name}") all_tasks.append(self._test_vllm(vllm_name, config)) - print(f"\n✅ 找到 {len(all_tasks)} 个可用视觉大模型") - print(f"✅ 使用 {len(self.test_images)} 张测试图片") - print(f"✅ 使用 {len(self.test_questions)} 个测试问题") - print("\n⏳ 开始并发测试所有模型...\n") + print(f"\n✅ Found {len(all_tasks)} available vision large models") + print(f"✅ Using {len(self.test_images)} test images") + print(f"✅ Using {len(self.test_questions)} test questions") - # 并发执行所有测试任务 + print("\n⏳ Starting concurrent testing of all models...\n") + + # Execute all test tasks concurrently all_results = await asyncio.gather(*all_tasks, return_exceptions=True) - # 处理结果 + # Process results for result in all_results: if isinstance(result, dict) and result["errors"] == 0: self.results["vllm"][result["name"]] = result - # 打印结果 - print("\n📊 生成测试报告...") + # Print results + print("\n📊 Generating test report...") self._print_results() @@ -184,6 +195,5 @@ async def main(): tester = AsyncVisionPerformanceTester() await tester.run() - if __name__ == "__main__": asyncio.run(main()) diff --git a/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py b/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py index e5ca0d1f8..ceaad5afd 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py +++ b/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py @@ -13,25 +13,25 @@ GET_NEWS_FROM_CHINANEWS_FUNCTION_DESC = { "function": { "name": "get_news_from_chinanews", "description": ( - "获取最新新闻,随机选择一条新闻进行播报。" - "用户可以指定新闻类型,如社会新闻、科技新闻、国际新闻等。" - "如果没有指定,默认播报社会新闻。" - "用户可以要求获取详细内容,此时会获取新闻的详细内容。" + "Get latest news, randomly select one news item for broadcast. " + "Users can specify news type, such as social news, tech news, international news, etc. " + "If not specified, defaults to social news. " + "Users can request detailed content, which will fetch detailed news content." ), "parameters": { "type": "object", "properties": { "category": { "type": "string", - "description": "新闻类别,例如社会、科技、国际。可选参数,如果不提供则使用默认类别", + "description": "News category, e.g., society, tech, international. Optional parameter, uses default category if not provided", }, "detail": { "type": "boolean", - "description": "是否获取详细内容,默认为false。如果为true,则获取上一条新闻的详细内容", + "description": "Whether to get detailed content, defaults to false. If true, gets detailed content of the previous news item", }, "lang": { "type": "string", - "description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN", + "description": "Language code for user response, e.g., zh_CN/zh_HK/en_US/ja_JP etc., defaults to zh_CN", }, }, "required": ["lang"], @@ -39,34 +39,30 @@ GET_NEWS_FROM_CHINANEWS_FUNCTION_DESC = { }, } - def fetch_news_from_rss(rss_url): - """从RSS源获取新闻列表""" + """Fetch news list from RSS source""" try: response = requests.get(rss_url) response.raise_for_status() - - # 解析XML + # Parse XML root = ET.fromstring(response.content) - - # 查找所有item元素(新闻条目) + # Find all item elements (news entries) news_items = [] for item in root.findall(".//item"): title = ( - item.find("title").text if item.find("title") is not None else "无标题" + item.find("title").text if item.find("title") is not None else "No title" ) link = item.find("link").text if item.find("link") is not None else "#" description = ( item.find("description").text if item.find("description") is not None - else "无描述" + else "No description" ) pubDate = ( item.find("pubDate").text if item.find("pubDate") is not None - else "未知时间" + else "Unknown time" ) - news_items.append( { "title": title, @@ -75,22 +71,18 @@ def fetch_news_from_rss(rss_url): "pubDate": pubDate, } ) - return news_items except Exception as e: - logger.bind(tag=TAG).error(f"获取RSS新闻失败: {e}") + logger.bind(tag=TAG).error(f"Failed to fetch RSS news: {e}") return [] - def fetch_news_detail(url): - """获取新闻详情页内容并总结""" + """Fetch news detail page content and summarize""" try: response = requests.get(url) response.raise_for_status() - soup = BeautifulSoup(response.content, "html.parser") - - # 尝试提取正文内容 (这里的选择器需要根据实际网站结构调整) + # Try to extract body content (selectors need adjustment based on actual website structure) content_div = soup.select_one( ".content_desc, .content, article, .article-content" ) @@ -101,44 +93,40 @@ def fetch_news_detail(url): ) return content else: - # 如果找不到特定的内容区域,尝试获取所有段落 + # If specific content area not found, try to get all paragraphs paragraphs = soup.find_all("p") content = "\n".join( [p.get_text().strip() for p in paragraphs if p.get_text().strip()] ) - return content[:2000] # 限制长度 + return content[:2000] # Limit length except Exception as e: - logger.bind(tag=TAG).error(f"获取新闻详情失败: {e}") - return "无法获取详细内容" - + logger.bind(tag=TAG).error(f"Failed to fetch news details: {e}") + return "Unable to get detailed content" def map_category(category_text): - """将用户输入的中文类别映射到配置文件中的类别键""" + """Map user input Chinese category to category keys in config file""" if not category_text: return None - - # 类别映射字典,目前支持社会、国际、财经新闻,如需更多类型,参见配置文件 + # Category mapping dictionary, currently supports society, international, finance news + # For more types, see config file category_map = { - # 社会新闻 - "社会": "society_rss_url", - "社会新闻": "society_rss_url", - # 国际新闻 - "国际": "world_rss_url", - "国际新闻": "world_rss_url", - # 财经新闻 - "财经": "finance_rss_url", - "财经新闻": "finance_rss_url", - "金融": "finance_rss_url", - "经济": "finance_rss_url", + # Social news + "society": "society_rss_url", + "social news": "society_rss_url", + # International news + "international": "world_rss_url", + "international news": "world_rss_url", + # Finance news + "finance": "finance_rss_url", + "financial news": "finance_rss_url", + "financial": "finance_rss_url", + "economy": "finance_rss_url", } - - # 转换为小写并去除空格 + # Convert to lowercase and remove spaces normalized_category = category_text.lower().strip() - - # 返回映射结果,如果没有匹配项则返回原始输入 + # Return mapping result, if no match found return original input return category_map.get(normalized_category, category_text) - @register_function( "get_news_from_chinanews", GET_NEWS_FROM_CHINANEWS_FUNCTION_DESC, @@ -147,9 +135,9 @@ def map_category(category_text): def get_news_from_chinanews( conn, category: str = None, detail: bool = False, lang: str = "zh_CN" ): - """获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容""" + """Get news and randomly select one for broadcast, or get detailed content of previous news""" try: - # 如果detail为True,获取上一条新闻的详细内容 + # If detail is True, get detailed content of previous news if detail: if ( not hasattr(conn, "last_news_link") @@ -158,94 +146,88 @@ def get_news_from_chinanews( ): return ActionResponse( Action.REQLLM, - "抱歉,没有找到最近查询的新闻,请先获取一条新闻。", + "Sorry, no recent news query found, please get a news item first.", None, ) - + link = conn.last_news_link.get("link") - title = conn.last_news_link.get("title", "未知标题") - + title = conn.last_news_link.get("title", "Unknown title") if link == "#": return ActionResponse( - Action.REQLLM, "抱歉,该新闻没有可用的链接获取详细内容。", None + Action.REQLLM, "Sorry, this news has no available link to get detailed content.", None ) - - logger.bind(tag=TAG).debug(f"获取新闻详情: {title}, URL={link}") - - # 获取新闻详情 + + logger.bind(tag=TAG).debug(f"Getting news details: {title}, URL={link}") + # Get news details detail_content = fetch_news_detail(link) - - if not detail_content or detail_content == "无法获取详细内容": + if not detail_content or detail_content == "Unable to get detailed content": return ActionResponse( Action.REQLLM, - f"抱歉,无法获取《{title}》的详细内容,可能是链接已失效或网站结构发生变化。", + f"Sorry, unable to get detailed content for 《{title}》, link may be invalid or website structure has changed.", None, ) - - # 构建详情报告 + + # Build detail report detail_report = ( - f"根据下列数据,用{lang}回应用户的新闻详情查询请求:\n\n" - f"新闻标题: {title}\n" - f"详细内容: {detail_content}\n\n" - f"(请对上述新闻内容进行总结,提取关键信息,以自然、流畅的方式向用户播报," - f"不要提及这是总结,就像是在讲述一个完整的新闻故事)" + f"Based on the following data, respond to user's news detail query in {lang}:\n\n" + f"News title: {title}\n" + f"Detailed content: {detail_content}\n\n" + f"(Please summarize the above news content, extract key information, and broadcast to user in a natural, fluent manner, " + f"don't mention this is a summary, tell it like a complete news story)" ) - + return ActionResponse(Action.REQLLM, detail_report, None) - - # 否则,获取新闻列表并随机选择一条 - # 从配置中获取RSS URL + + # Otherwise, get news list and randomly select one + # Get RSS URL from config rss_config = conn.config["plugins"]["get_news_from_chinanews"] default_rss_url = rss_config.get( "default_rss_url", "https://www.chinanews.com.cn/rss/society.xml" ) - - # 将用户输入的类别映射到配置中的类别键 + + # Map user input category to category key in config mapped_category = map_category(category) - - # 如果提供了类别,尝试从配置中获取对应的URL + # If category is provided, try to get corresponding URL from config rss_url = default_rss_url if mapped_category and mapped_category in rss_config: rss_url = rss_config[mapped_category] - + logger.bind(tag=TAG).info( - f"获取新闻: 原始类别={category}, 映射类别={mapped_category}, URL={rss_url}" + f"Getting news: original category={category}, mapped category={mapped_category}, URL={rss_url}" ) - - # 获取新闻列表 + + # Get news list news_items = fetch_news_from_rss(rss_url) - if not news_items: return ActionResponse( - Action.REQLLM, "抱歉,未能获取到新闻信息,请稍后再试。", None + Action.REQLLM, "Sorry, failed to get news information, please try again later.", None ) - - # 随机选择一条新闻 + + # Randomly select one news item selected_news = random.choice(news_items) - - # 保存当前新闻链接到连接对象,以便后续查询详情 + # Save current news link to connection object for later detail queries if not hasattr(conn, "last_news_link"): conn.last_news_link = {} conn.last_news_link = { "link": selected_news.get("link", "#"), - "title": selected_news.get("title", "未知标题"), + "title": selected_news.get("title", "Unknown title"), } - - # 构建新闻报告 + + # Build news report news_report = ( - f"根据下列数据,用{lang}回应用户的新闻查询请求:\n\n" - f"新闻标题: {selected_news['title']}\n" - f"发布时间: {selected_news['pubDate']}\n" - f"新闻内容: {selected_news['description']}\n" - f"(请以自然、流畅的方式向用户播报这条新闻,可以适当总结内容," - f"直接读出新闻即可,不需要额外多余的内容。" - f"如果用户询问更多详情,告知用户可以说'请详细介绍这条新闻'获取更多内容)" + f"Based on the following data, respond to user's news query in {lang}:\n\n" + f"News title: {selected_news['title']}\n" + f"Publish time: {selected_news['pubDate']}\n" + f"News content: {selected_news['description']}\n" + f"(Please broadcast this news to user in a natural, fluent manner, can appropriately summarize content, " + f"just read the news directly, no need for extra content. " + f"If user asks for more details, tell them they can say 'please introduce this news in detail' to get more content)" ) - + return ActionResponse(Action.REQLLM, news_report, None) - + except Exception as e: - logger.bind(tag=TAG).error(f"获取新闻出错: {e}") + logger.bind(tag=TAG).error(f"Error getting news: {e}") return ActionResponse( - Action.REQLLM, "抱歉,获取新闻时发生错误,请稍后再试。", None + Action.REQLLM, "Sorry, an error occurred while getting news, please try again later.", None ) diff --git a/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py b/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py index 546411060..909880e38 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py +++ b/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py @@ -10,77 +10,80 @@ logger = setup_logging() CHANNEL_MAP = { "V2EX": "v2ex-share", - "知乎": "zhihu", - "微博": "weibo", - "联合早报": "zaobao", - "酷安": "coolapk", + "Zhihu": "zhihu", + "Weibo": "weibo", + "Lianhe Zaobao": "zaobao", + "Coolapk": "coolapk", "MKTNews": "mktnews-flash", - "华尔街见闻": "wallstreetcn-quick", - "36氪": "36kr-quick", - "抖音": "douyin", - "虎扑": "hupu", - "百度贴吧": "tieba", - "今日头条": "toutiao", - "IT之家": "ithome", - "澎湃新闻": "thepaper", - "卫星通讯社": "sputniknewscn", - "参考消息": "cankaoxiaoxi", - "远景论坛": "pcbeta-windows11", - "财联社": "cls-depth", - "雪球": "xueqiu-hotstock", - "格隆汇": "gelonghui", - "法布财经": "fastbull-express", + "Wall Street Journal": "wallstreetcn-quick", + "36Kr": "36kr-quick", + "Douyin": "douyin", + "Hupu": "hupu", + "Baidu Tieba": "tieba", + "Toutiao": "toutiao", + "IT Home": "ithome", + "Pengpai News": "thepaper", + "Sputnik News": "sputniknewscn", + "Reference News": "cankaoxiaoxi", + "Pcbeta": "pcbeta-windows11", + "CLS": "cls-depth", + "Xueqiu": "xueqiu-hotstock", + "Gelonghui": "gelonghui", + "Fastbull": "fastbull-express", "Solidot": "solidot", "Hacker News": "hackernews", "Product Hunt": "producthunt", "Github": "github-trending-today", - "哔哩哔哩": "bilibili-hot-search", - "快手": "kuaishou", - "靠谱新闻": "kaopu", - "金十数据": "jin10", - "百度热搜": "baidu", - "牛客": "nowcoder", - "少数派": "sspai", - "稀土掘金": "juejin", - "凤凰网": "ifeng", - "虫部落": "chongbuluo-latest", + "Bilibili": "bilibili-hot-search", + "Kuaishou": "kuaishou", + "Kaopu News": "kaopu", + "Jin10": "jin10", + "Baidu Hot Search": "baidu", + "Nowcoder": "nowcoder", + "Sspai": "sspai", + "Juejin": "juejin", + "Ifeng": "ifeng", + "Chongbuluo": "chongbuluo-latest", } - -# 默认新闻来源字典,当配置中没有指定时使用 -DEFAULT_NEWS_SOURCES = "澎湃新闻;百度热搜;财联社" +# Default news sources dictionary, used when not specified in config +DEFAULT_NEWS_SOURCES = "Pengpai News;Baidu Hot Search;CLS" def get_news_sources_from_config(conn): - """从配置中获取新闻源字符串""" + """Get news sources string from config""" try: - # 尝试从插件配置中获取新闻源 + # Try to get news sources from plugin config if ( conn.config.get("plugins") and conn.config["plugins"].get("get_news_from_newsnow") and conn.config["plugins"]["get_news_from_newsnow"].get("news_sources") ): - # 获取配置的新闻源字符串 + # Get configured news sources string news_sources_config = conn.config["plugins"]["get_news_from_newsnow"][ "news_sources" ] if isinstance(news_sources_config, str) and news_sources_config.strip(): - logger.bind(tag=TAG).debug(f"使用配置的新闻源: {news_sources_config}") + logger.bind(tag=TAG).debug( + f"Using configured news sources: {news_sources_config}") return news_sources_config else: - logger.bind(tag=TAG).warning("新闻源配置为空或格式错误,使用默认配置") + logger.bind(tag=TAG).warning( + "News sources config is empty or invalid format, using default config") else: - logger.bind(tag=TAG).debug("未找到新闻源配置,使用默认配置") + logger.bind(tag=TAG).debug( + "News sources config not found, using default config") return DEFAULT_NEWS_SOURCES except Exception as e: - logger.bind(tag=TAG).error(f"获取新闻源配置失败: {e},使用默认配置") + logger.bind(tag=TAG).error( + f"Failed to get news sources config: {e}, using default config") return DEFAULT_NEWS_SOURCES -# 从CHANNEL_MAP获取所有可用的新闻源名称 +# Get all available news source names from CHANNEL_MAP available_sources = list(CHANNEL_MAP.keys()) example_sources_str = "、".join(available_sources) @@ -89,25 +92,25 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = { "function": { "name": "get_news_from_newsnow", "description": ( - "获取最新新闻,随机选择一条新闻进行播报。" - f"用户可以选择不同的新闻源,标准的名称是:{example_sources_str}" - "例如用户要求百度新闻,其实就是百度热搜。如果没有指定,默认从澎湃新闻获取。" - "用户可以要求获取详细内容,此时会获取新闻的详细内容。" + "Get latest news, randomly select one news item for broadcast. " + f"Users can choose different news sources, standard names are: {example_sources_str}" + "For example, if user requests Baidu news, it's actually Baidu Hot Search. If not specified, defaults to Pengpai News. " + "Users can request detailed content, which will fetch detailed news content." ), "parameters": { "type": "object", "properties": { "source": { "type": "string", - "description": f"新闻源的标准中文名称,例如{example_sources_str}等。可选参数,如果不提供则使用默认新闻源", + "description": f"Standard Chinese name of news source, e.g., {example_sources_str} etc. Optional parameter, uses default news source if not provided", }, "detail": { "type": "boolean", - "description": "是否获取详细内容,默认为false。如果为true,则获取上一条新闻的详细内容", + "description": "Whether to get detailed content, defaults to false. If true, gets detailed content of the previous news item", }, "lang": { "type": "string", - "description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN", + "description": "Language code for user response, e.g., zh_CN/zh_HK/en_US/ja_JP etc., defaults to zh_CN", }, }, "required": ["lang"], @@ -117,7 +120,7 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = { def fetch_news_from_api(conn, source="thepaper"): - """从API获取新闻列表""" + """Fetch news list from API""" try: api_url = f"https://newsnow.busiyi.world/api/s?id={source}" if conn.config["plugins"].get("get_news_from_newsnow") and conn.config[ @@ -127,42 +130,44 @@ def fetch_news_from_api(conn, source="thepaper"): response = requests.get(api_url, timeout=10) response.raise_for_status() - data = response.json() if "items" in data: return data["items"] else: - logger.bind(tag=TAG).error(f"获取新闻API响应格式错误: {data}") + logger.bind(tag=TAG).error( + f"News API response format error: {data}") return [] except Exception as e: - logger.bind(tag=TAG).error(f"获取新闻API失败: {e}") + logger.bind(tag=TAG).error(f"News API failed: {e}") return [] def fetch_news_detail(url): - """获取新闻详情页内容并使用MarkItDown清理HTML""" + """Fetch news detail page content and clean HTML using MarkItDown""" try: response = requests.get(url, timeout=10) response.raise_for_status() - # 使用MarkItDown清理HTML内容 + # Use MarkItDown to clean HTML content md = MarkItDown(enable_plugins=False) result = md.convert(response) - # 获取清理后的文本内容 + # Get cleaned text content clean_text = result.text_content - # 如果清理后的内容为空,返回提示信息 + # If cleaned content is empty, return prompt message if not clean_text or len(clean_text.strip()) == 0: - logger.bind(tag=TAG).warning(f"清理后的新闻内容为空: {url}") - return "无法解析新闻详情内容,可能是网站结构特殊或内容受限。" + logger.bind(tag=TAG).warning( + f"Cleaned news content is empty: {url}") + return "Unable to parse news detail content, website structure may be special or content restricted." return clean_text + except Exception as e: - logger.bind(tag=TAG).error(f"获取新闻详情失败: {e}") - return "无法获取详细内容" + logger.bind(tag=TAG).error(f"Failed to fetch news details: {e}") + return "Unable to get detailed content" @register_function( @@ -171,14 +176,14 @@ def fetch_news_detail(url): ToolType.SYSTEM_CTL, ) def get_news_from_newsnow( - conn, source: str = "澎湃新闻", detail: bool = False, lang: str = "zh_CN" + conn, source: str = "Pengpai News", detail: bool = False, lang: str = "zh_CN" ): - """获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容""" + """Get news and randomly select one for broadcast, or get detailed content of previous news""" try: - # 获取当前配置的新闻源 + # Get currently configured news sources news_sources = get_news_sources_from_config(conn) - # 如果detail为True,获取上一条新闻的详细内容 + # If detail is True, get detailed content of previous news detail = str(detail).lower() == "true" if detail: if ( @@ -188,101 +193,99 @@ def get_news_from_newsnow( ): return ActionResponse( Action.REQLLM, - "抱歉,没有找到最近查询的新闻,请先获取一条新闻。", + "Sorry, no recent news query found, please get a news item first.", None, ) url = conn.last_newsnow_link.get("url") - title = conn.last_newsnow_link.get("title", "未知标题") + title = conn.last_newsnow_link.get("title", "Unknown title") source_id = conn.last_newsnow_link.get("source_id", "thepaper") - source_name = CHANNEL_MAP.get(source_id, "未知来源") + source_name = CHANNEL_MAP.get(source_id, "Unknown source") if not url or url == "#": return ActionResponse( - Action.REQLLM, "抱歉,该新闻没有可用的链接获取详细内容。", None + Action.REQLLM, "Sorry, this news has no available link to get detailed content.", None ) logger.bind(tag=TAG).debug( - f"获取新闻详情: {title}, 来源: {source_name}, URL={url}" + f"Getting news details: {title}, source: {source_name}, URL={url}" ) - # 获取新闻详情 + # Get news details detail_content = fetch_news_detail(url) - - if not detail_content or detail_content == "无法获取详细内容": + if not detail_content or detail_content == "Unable to get detailed content": return ActionResponse( Action.REQLLM, - f"抱歉,无法获取《{title}》的详细内容,可能是链接已失效或网站结构发生变化。", + f"Sorry, unable to get detailed content for 《{title}》, link may be invalid or website structure has changed.", None, ) - # 构建详情报告 + # Build detail report detail_report = ( - f"根据下列数据,用{lang}回应用户的新闻详情查询请求:\n\n" - f"新闻标题: {title}\n" - # f"新闻来源: {source_name}\n" - f"详细内容: {detail_content}\n\n" - f"(请对上述新闻内容进行总结,提取关键信息,以自然、流畅的方式向用户播报," - f"不要提及这是总结,就像是在讲述一个完整的新闻故事)" + f"Based on the following data, respond to user's news detail query in {lang}:\n\n" + f"News title: {title}\n" + f"Detailed content: {detail_content}\n\n" + f"(Please summarize the above news content, extract key information, and broadcast to user in a natural, fluent manner, " + f"don't mention this is a summary, tell it like a complete news story)" ) return ActionResponse(Action.REQLLM, detail_report, None) - # 否则,获取新闻列表并随机选择一条 - # 将中文名称转换为英文ID + # Otherwise, get news list and randomly select one + # Convert Chinese name to English ID english_source_id = None - - # 检查输入的中文名称是否在配置的新闻源中 + # Check if input Chinese name is in configured news sources news_sources_list = [ name.strip() for name in news_sources.split(";") if name.strip() ] + if source in news_sources_list: - # 如果输入的中文名称在配置的新闻源中,在 CHANNEL_MAP 中查找对应的英文ID + # If input Chinese name is in configured news sources, look up corresponding English ID in CHANNEL_MAP english_source_id = CHANNEL_MAP.get(source) - # 如果找不到对应的英文ID,使用默认源 + # If corresponding English ID not found, use default source if not english_source_id: - logger.bind(tag=TAG).warning(f"无效的新闻源: {source},使用默认源澎湃新闻") + logger.bind(tag=TAG).warning( + f"Invalid news source: {source}, using default source Pengpai News") english_source_id = "thepaper" - source = "澎湃新闻" + source = "Pengpai News" - logger.bind(tag=TAG).info(f"获取新闻: 新闻源={source}({english_source_id})") + logger.bind(tag=TAG).info( + f"Getting news: news source={source}({english_source_id})") - # 获取新闻列表 + # Get news list news_items = fetch_news_from_api(conn, english_source_id) - if not news_items: return ActionResponse( Action.REQLLM, - f"抱歉,未能从{source}获取到新闻信息,请稍后再试或尝试其他新闻源。", + f"Sorry, failed to get news information from {source}, please try again later or try other news sources.", None, ) - # 随机选择一条新闻 + # Randomly select one news item selected_news = random.choice(news_items) - # 保存当前新闻链接到连接对象,以便后续查询详情 + # Save current news link to connection object for later detail queries if not hasattr(conn, "last_newsnow_link"): conn.last_newsnow_link = {} conn.last_newsnow_link = { "url": selected_news.get("url", "#"), - "title": selected_news.get("title", "未知标题"), + "title": selected_news.get("title", "Unknown title"), "source_id": english_source_id, } - # 构建新闻报告 + # Build news report news_report = ( - f"根据下列数据,用{lang}回应用户的新闻查询请求:\n\n" - f"新闻标题: {selected_news['title']}\n" - # f"新闻来源: {source}\n" - f"(请以自然、流畅的方式向用户播报这条新闻标题," - f"提示用户可以要求获取详细内容,此时会获取新闻的详细内容。)" + f"Based on the following data, respond to user's news query in {lang}:\n\n" + f"News title: {selected_news['title']}\n" + f"(Please broadcast this news title to user in a natural, fluent manner, " + f"remind user they can request detailed content, which will fetch detailed news content.)" ) return ActionResponse(Action.REQLLM, news_report, None) except Exception as e: - logger.bind(tag=TAG).error(f"获取新闻出错: {e}") + logger.bind(tag=TAG).error(f"Error getting news: {e}") return ActionResponse( - Action.REQLLM, "抱歉,获取新闻时发生错误,请稍后再试。", None + Action.REQLLM, "Sorry, an error occurred while getting news, please try again later.", None ) diff --git a/main/xiaozhi-server/plugins_func/functions/get_time.py b/main/xiaozhi-server/plugins_func/functions/get_time.py index 4409977e3..6297873d0 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_time.py +++ b/main/xiaozhi-server/plugins_func/functions/get_time.py @@ -39,7 +39,7 @@ def get_lunar(date=None, query=None): """ from core.utils.cache.manager import cache_manager, CacheType - # 如果提供了日期参数,则使用指定日期;否则使用当前日期 + # If date parameter is provided, use specified date; otherwise use current date if date: try: now = datetime.strptime(date, "%Y-%m-%d") @@ -58,24 +58,29 @@ def get_lunar(date=None, query=None): if query is None: query = "default query for heavenly stems/earthly branches year and lunar date" - # 尝试从缓存获取农历信息 + # Try to get lunar information from cache lunar_cache_key = f"lunar_info_{current_date}" cached_lunar_info = cache_manager.get(CacheType.LUNAR, lunar_cache_key) + if cached_lunar_info: return ActionResponse(Action.REQLLM, cached_lunar_info, None) response_text = f"Please respond to the user's query based on the following information, providing details related to {query}:\n" lunar = cnlunar.Lunar(now, godType="8char") + response_text += ( "Lunar Calendar Information:\n" - "%s Year %s %s\n" % (lunar.lunarYearCn, lunar.lunarMonthCn[:-1], lunar.lunarDayCn) - + "Heavenly Stems & Earthly Branches: %s Year %s Month %s Day\n" % (lunar.year8Char, lunar.month8Char, lunar.day8Char) + "%s Year %s %s\n" % ( + lunar.lunarYearCn, lunar.lunarMonthCn[:-1], lunar.lunarDayCn) + + "Heavenly Stems & Earthly Branches: %s Year %s Month %s Day\n" % ( + lunar.year8Char, lunar.month8Char, lunar.day8Char) + "Chinese Zodiac: %s\n" % (lunar.chineseYearZodiac) + "Eight Characters (Ba Zi): %s\n" % ( " ".join( - [lunar.year8Char, lunar.month8Char, lunar.day8Char, lunar.twohour8Char] + [lunar.year8Char, lunar.month8Char, + lunar.day8Char, lunar.twohour8Char] ) ) + "Today's Festivals: %s\n" @@ -83,15 +88,16 @@ def get_lunar(date=None, query=None): ",".join( filter( None, - ( + [ lunar.get_legalHolidays(), lunar.get_otherHolidays(), lunar.get_otherLunarHolidays(), - ), + ], ) ) ) - + "Today's Solar Term: %s\n" % (lunar.todaySolarTerms if lunar.todaySolarTerms else "None") + + "Today's Solar Term: %s\n" % ( + lunar.todaySolarTerms if lunar.todaySolarTerms else "None") + "Next Solar Term: %s %s Year %s Month %s Day\n" % ( lunar.nextSolarTerm, @@ -126,4 +132,4 @@ def get_lunar(date=None, query=None): # Cache lunar information cache_manager.set(CacheType.LUNAR, lunar_cache_key, response_text) - return ActionResponse(Action.REQLLM, response_text, None) \ No newline at end of file + return ActionResponse(Action.REQLLM, response_text, None) diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py index 8b191b272..c4269e962 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_weather.py +++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py @@ -12,20 +12,20 @@ GET_WEATHER_FUNCTION_DESC = { "function": { "name": "get_weather", "description": ( - "获取某个地点的天气,用户应提供一个位置,比如用户说杭州天气,参数为:杭州。" - "如果用户说的是省份,默认用省会城市。如果用户说的不是省份或城市而是一个地名,默认用该地所在省份的省会城市。" - "如果用户没有指明地点,说“天气怎么样”,”今天天气如何“,location参数为空" + "Get weather for a location, user should provide a location, e.g., if user says 'Hangzhou weather', parameter is: Hangzhou. " + "If user mentions a province, defaults to provincial capital. If user mentions a place name that's not a province or city, defaults to the provincial capital of that place's province. " + "If user doesn't specify location, saying 'how's the weather', 'how's today's weather', location parameter is empty" ), "parameters": { "type": "object", "properties": { "location": { "type": "string", - "description": "地点名,例如杭州。可选参数,如果不提供则不传", + "description": "Location name, e.g., Hangzhou. Optional parameter, don't pass if not provided", }, "lang": { "type": "string", - "description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN", + "description": "Language code for user response, e.g., zh_CN/zh_HK/en_US/ja_JP etc., defaults to zh_CN", }, }, "required": ["lang"], @@ -40,70 +40,70 @@ HEADERS = { ) } -# 天气代码 https://dev.qweather.com/docs/resource/icons/#weather-icons +# Weather codes https://dev.qweather.com/docs/resource/icons/#weather-icons WEATHER_CODE_MAP = { - "100": "晴", - "101": "多云", - "102": "少云", - "103": "晴间多云", - "104": "阴", - "150": "晴", - "151": "多云", - "152": "少云", - "153": "晴间多云", - "300": "阵雨", - "301": "强阵雨", - "302": "雷阵雨", - "303": "强雷阵雨", - "304": "雷阵雨伴有冰雹", - "305": "小雨", - "306": "中雨", - "307": "大雨", - "308": "极端降雨", - "309": "毛毛雨/细雨", - "310": "暴雨", - "311": "大暴雨", - "312": "特大暴雨", - "313": "冻雨", - "314": "小到中雨", - "315": "中到大雨", - "316": "大到暴雨", - "317": "暴雨到大暴雨", - "318": "大暴雨到特大暴雨", - "350": "阵雨", - "351": "强阵雨", - "399": "雨", - "400": "小雪", - "401": "中雪", - "402": "大雪", - "403": "暴雪", - "404": "雨夹雪", - "405": "雨雪天气", - "406": "阵雨夹雪", - "407": "阵雪", - "408": "小到中雪", - "409": "中到大雪", - "410": "大到暴雪", - "456": "阵雨夹雪", - "457": "阵雪", - "499": "雪", - "500": "薄雾", - "501": "雾", - "502": "霾", - "503": "扬沙", - "504": "浮尘", - "507": "沙尘暴", - "508": "强沙尘暴", - "509": "浓雾", - "510": "强浓雾", - "511": "中度霾", - "512": "重度霾", - "513": "严重霾", - "514": "大雾", - "515": "特强浓雾", - "900": "热", - "901": "冷", - "999": "未知", + "100": "Sunny", + "101": "Cloudy", + "102": "Few clouds", + "103": "Partly cloudy", + "104": "Overcast", + "150": "Clear", + "151": "Cloudy", + "152": "Few clouds", + "153": "Partly cloudy", + "300": "Shower", + "301": "Heavy shower", + "302": "Thundershower", + "303": "Heavy thundershower", + "304": "Thundershower with hail", + "305": "Light rain", + "306": "Moderate rain", + "307": "Heavy rain", + "308": "Extreme rain", + "309": "Drizzle", + "310": "Storm", + "311": "Heavy storm", + "312": "Severe storm", + "313": "Freezing rain", + "314": "Light to moderate rain", + "315": "Moderate to heavy rain", + "316": "Heavy rain to storm", + "317": "Storm to heavy storm", + "318": "Heavy to severe storm", + "350": "Shower", + "351": "Heavy shower", + "399": "Rain", + "400": "Light snow", + "401": "Moderate snow", + "402": "Heavy snow", + "403": "Snowstorm", + "404": "Sleet", + "405": "Rain and snow", + "406": "Shower snow", + "407": "Snow shower", + "408": "Light to moderate snow", + "409": "Moderate to heavy snow", + "410": "Heavy snow to snowstorm", + "456": "Shower snow", + "457": "Snow shower", + "499": "Snow", + "500": "Mist", + "501": "Fog", + "502": "Haze", + "503": "Sand", + "504": "Dust", + "507": "Duststorm", + "508": "Sandstorm", + "509": "Dense fog", + "510": "Heavy fog", + "511": "Moderate haze", + "512": "Heavy haze", + "513": "Severe haze", + "514": "Heavy fog", + "515": "Extra heavy fog", + "900": "Hot", + "901": "Cold", + "999": "Unknown", } @@ -120,10 +120,11 @@ def fetch_weather_page(url): def parse_weather_info(soup): city_name = soup.select_one("h1.c-submenu__location").get_text(strip=True) - - current_abstract = soup.select_one(".c-city-weather-current .current-abstract") + current_abstract = soup.select_one( + ".c-city-weather-current .current-abstract") current_abstract = ( - current_abstract.get_text(strip=True) if current_abstract else "未知" + current_abstract.get_text( + strip=True) if current_abstract else "Unknown" ) current_basic = {} @@ -136,14 +137,18 @@ def parse_weather_info(soup): current_basic[key] = value temps_list = [] - for row in soup.select(".city-forecast-tabs__row")[:7]: # 取前7天的数据 + # Get first 7 days of data + for row in soup.select(".city-forecast-tabs__row")[:7]: date = row.select_one(".date-bg .date").get_text(strip=True) weather_code = ( - row.select_one(".date-bg .icon")["src"].split("/")[-1].split(".")[0] + row.select_one( + ".date-bg .icon")["src"].split("/")[-1].split(".")[0] ) - weather = WEATHER_CODE_MAP.get(weather_code, "未知") - temps = [span.get_text(strip=True) for span in row.select(".tmp-cont .temp")] - high_temp, low_temp = (temps[0], temps[-1]) if len(temps) >= 2 else (None, None) + weather = WEATHER_CODE_MAP.get(weather_code, "Unknown") + temps = [span.get_text(strip=True) + for span in row.select(".tmp-cont .temp")] + high_temp, low_temp = ( + temps[0], temps[-1]) if len(temps) >= 2 else (None, None) temps_list.append((date, weather, high_temp, low_temp)) return city_name, current_abstract, current_basic, temps_list @@ -162,16 +167,16 @@ def get_weather(conn, location: str = None, lang: str = "zh_CN"): default_location = conn.config["plugins"]["get_weather"]["default_location"] client_ip = conn.client_ip - # 优先使用用户提供的location参数 + # Prioritize user-provided location parameter if not location: - # 通过客户端IP解析城市 + # Parse city through client IP if client_ip: - # 先从缓存获取IP对应的城市信息 + # First get IP corresponding city info from cache cached_ip_info = cache_manager.get(CacheType.IP_INFO, client_ip) if cached_ip_info: location = cached_ip_info.get("city") else: - # 缓存未命中,调用API获取 + # Cache miss, call API to get ip_info = get_ip_info(client_ip, logger) if ip_info: cache_manager.set(CacheType.IP_INFO, client_ip, ip_info) @@ -180,43 +185,49 @@ def get_weather(conn, location: str = None, lang: str = "zh_CN"): if not location: location = default_location else: - # 若无IP,使用默认位置 + # If no IP, use default location location = default_location - # 尝试从缓存获取完整天气报告 + + # Try to get complete weather report from cache weather_cache_key = f"full_weather_{location}_{lang}" - cached_weather_report = cache_manager.get(CacheType.WEATHER, weather_cache_key) + cached_weather_report = cache_manager.get( + CacheType.WEATHER, weather_cache_key) + if cached_weather_report: return ActionResponse(Action.REQLLM, cached_weather_report, None) - # 缓存未命中,获取实时天气数据 + # Cache miss, get real-time weather data city_info = fetch_city_info(location, api_key, api_host) if not city_info: return ActionResponse( - Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None + Action.REQLLM, f"Related city not found: {location}, please confirm if location is correct", None ) + soup = fetch_weather_page(city_info["fxLink"]) if not soup: - return ActionResponse(Action.REQLLM, None, "请求失败") - city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup) + return ActionResponse(Action.REQLLM, None, "Request failed") - weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_abstract}\n" + city_name, current_abstract, current_basic, temps_list = parse_weather_info( + soup) - # 添加有效的当前天气参数 + weather_report = f"Your queried location is: {city_name}\n\nCurrent weather: {current_abstract}\n" + + # Add valid current weather parameters if current_basic: - weather_report += "详细参数:\n" + weather_report += "Detailed parameters:\n" for key, value in current_basic.items(): - if value != "0": # 过滤无效值 - weather_report += f" · {key}: {value}\n" + if value != "0": # Filter invalid values + weather_report += f" · {key}: {value}\n" - # 添加7天预报 - weather_report += "\n未来7天预报:\n" + # Add 7-day forecast + weather_report += "\n7-day forecast:\n" for date, weather, high, low in temps_list: - weather_report += f"{date}: {weather},气温 {low}~{high}\n" + weather_report += f"{date}: {weather}, temperature {low}~{high}\n" - # 提示语 - weather_report += "\n(如需某一天的具体天气,请告诉我日期)" + # Reminder text + weather_report += "\n(For specific weather on a certain day, please tell me the date)" - # 缓存完整的天气报告 + # Cache complete weather report cache_manager.set(CacheType.WEATHER, weather_cache_key, weather_report) - return ActionResponse(Action.REQLLM, weather_report, None) \ No newline at end of file + return ActionResponse(Action.REQLLM, weather_report, None) diff --git a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py index affa8af2f..3f29b23aa 100644 --- a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py +++ b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py @@ -8,13 +8,13 @@ handle_exit_intent_function_desc = { "type": "function", "function": { "name": "handle_exit_intent", - "description": "当用户想结束对话或需要退出系统时调用", + "description": "Called when user wants to end conversation or needs to exit system", "parameters": { "type": "object", "properties": { "say_goodbye": { "type": "string", - "description": "和用户友好结束对话的告别语", + "description": "Friendly farewell message to end conversation with user", } }, "required": ["say_goodbye"], @@ -27,17 +27,20 @@ handle_exit_intent_function_desc = { "handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL ) def handle_exit_intent(conn, say_goodbye: str | None = None): - # 处理退出意图 + # Handle exit intent try: if say_goodbye is None: - say_goodbye = "再见,祝您生活愉快!" + say_goodbye = "Goodbye, have a wonderful day!" + conn.close_after_chat = True - logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}") + logger.bind(tag=TAG).info(f"Exit intent handled: {say_goodbye}") + return ActionResponse( - action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye + action=Action.RESPONSE, result="Exit intent handled", response=say_goodbye ) + except Exception as e: - logger.bind(tag=TAG).error(f"处理退出意图错误: {e}") + logger.bind(tag=TAG).error(f"Error handling exit intent: {e}") return ActionResponse( - action=Action.NONE, result="退出意图处理失败", response="" + action=Action.NONE, result="Exit intent handling failed", response="" ) diff --git a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py index 13b3febbd..ed188aa1d 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py @@ -11,14 +11,14 @@ hass_get_state_function_desc = { "type": "function", "function": { "name": "hass_get_state", - "description": "获取homeassistant里设备的状态,包括查询灯光亮度、颜色、色温,媒体播放器的音量,设备的暂停、继续操作", + "description": "Get device status in homeassistant, including querying light brightness, color, color temperature, media player volume, device pause/resume operations", "parameters": { "type": "object", "properties": { "entity_id": { "type": "string", - "description": "需要操作的设备id,homeassistant里的entity_id", - } + "description": "Device ID to operate, entity_id in homeassistant", + }, }, "required": ["entity_id"], }, @@ -29,20 +29,13 @@ hass_get_state_function_desc = { @register_function("hass_get_state", hass_get_state_function_desc, ToolType.SYSTEM_CTL) def hass_get_state(conn, entity_id=""): try: - future = asyncio.run_coroutine_threadsafe( handle_hass_get_state(conn, entity_id), conn.loop ) - # 添加10秒超时 - ha_response = future.result(timeout=10) + ha_response = future.result() return ActionResponse(Action.REQLLM, ha_response, None) - except asyncio.TimeoutError: - logger.bind(tag=TAG).error("获取Home Assistant状态超时") - return ActionResponse(Action.ERROR, "请求超时", None) except Exception as e: - error_msg = f"执行Home Assistant操作失败" - logger.bind(tag=TAG).error(error_msg) - return ActionResponse(Action.ERROR, error_msg, None) + logger.bind(tag=TAG).error(f"Error processing get state intent: {e}") async def handle_hass_get_state(conn, entity_id): @@ -50,51 +43,57 @@ async def handle_hass_get_state(conn, entity_id): api_key = ha_config.get("api_key") base_url = ha_config.get("base_url") url = f"{base_url}/api/states/{entity_id}" - headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} + headers = {"Authorization": f"Bearer {api_key}", + "Content-Type": "application/json"} + response = requests.get(url, headers=headers) if response.status_code == 200: - responsetext = "设备状态:" + response.json()["state"] + " " - logger.bind(tag=TAG).info(f"api返回内容: {response.json()}") + responsetext = "Device status: " + response.json()["state"] + " " + logger.bind(tag=TAG).info(f"API return content: {response.json()}") if "media_title" in response.json()["attributes"]: responsetext = ( responsetext - + "正在播放的是:" + + "Currently playing: " + str(response.json()["attributes"]["media_title"]) + " " ) + if "volume_level" in response.json()["attributes"]: responsetext = ( responsetext - + "音量是:" + + "Volume is: " + str(response.json()["attributes"]["volume_level"]) + " " ) + if "color_temp_kelvin" in response.json()["attributes"]: responsetext = ( responsetext - + "色温是:" + + "Color temperature is: " + str(response.json()["attributes"]["color_temp_kelvin"]) + " " ) + if "rgb_color" in response.json()["attributes"]: responsetext = ( responsetext - + "rgb颜色是:" + + "RGB color is: " + str(response.json()["attributes"]["rgb_color"]) + " " ) + if "brightness" in response.json()["attributes"]: responsetext = ( responsetext - + "亮度是:" + + "Brightness is: " + str(response.json()["attributes"]["brightness"]) + " " ) - logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}") + + logger.bind(tag=TAG).info(f"Query return content: {responsetext}") return responsetext # return response.json()['attributes'] # response.attributes - else: - return f"切换失败,错误码: {response.status_code}" \ No newline at end of file + return f"Switch failed, error code: {response.status_code}" diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py index 11cbb7a0c..923d8daea 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_init.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py @@ -18,10 +18,11 @@ def append_devices_to_prompt(conn): ) if "hass_get_state" in funcs or "hass_set_state" in funcs: - prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" - deviceStr = conn.config["plugins"].get(config_source, {}).get("devices", "") + prompt = "\nBelow is my smart device list (location, device name, entity_id), can be controlled through homeassistant\n" + deviceStr = conn.config["plugins"].get( + config_source, {}).get("devices", "") conn.prompt += prompt + deviceStr + "\n" - # 更新提示词 + # Update prompt conn.dialogue.update_system_message(conn.prompt) @@ -30,21 +31,22 @@ def initialize_hass_handler(conn): if not conn.load_function_plugin: return ha_config - # 确定配置来源 + # Determine config source config_source = ( "home_assistant" if conn.config["plugins"].get("home_assistant") else "hass_get_state" ) + if not conn.config["plugins"].get(config_source): return ha_config - # 统一获取配置 + # Unified config retrieval plugin_config = conn.config["plugins"][config_source] ha_config["base_url"] = plugin_config.get("base_url") ha_config["api_key"] = plugin_config.get("api_key") - # 统一检查API密钥 + # Unified API key check model_key_msg = check_model_key("home_assistant", ha_config.get("api_key")) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) diff --git a/main/xiaozhi-server/plugins_func/functions/hass_play_music.py b/main/xiaozhi-server/plugins_func/functions/hass_play_music.py index fa6527b62..10aef95e2 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_play_music.py @@ -11,17 +11,17 @@ hass_play_music_function_desc = { "type": "function", "function": { "name": "hass_play_music", - "description": "用户想听音乐、有声书的时候使用,在房间的媒体播放器(media_player)里播放对应音频", + "description": "Used when user wants to listen to music or audiobooks, plays corresponding audio in the room's media player (media_player)", "parameters": { "type": "object", "properties": { "media_content_id": { "type": "string", - "description": "可以是音乐或有声书的专辑名称、歌曲名、演唱者,如果未指定就填random", + "description": "Can be album name, song name, or artist name for music or audiobooks. Fill 'random' if not specified", }, "entity_id": { "type": "string", - "description": "需要操作的音箱的设备id,homeassistant里的entity_id,media_player开头", + "description": "Device ID of the speaker to operate, entity_id in homeassistant, starts with media_player", }, }, "required": ["media_content_id", "entity_id"], @@ -35,16 +35,17 @@ hass_play_music_function_desc = { ) def hass_play_music(conn, entity_id="", media_content_id="random"): try: - # 执行音乐播放命令 + # Execute music playback command future = asyncio.run_coroutine_threadsafe( - handle_hass_play_music(conn, entity_id, media_content_id), conn.loop + handle_hass_play_music( + conn, entity_id, media_content_id), conn.loop ) ha_response = future.result() return ActionResponse( - action=Action.RESPONSE, result="退出意图已处理", response=ha_response + action=Action.RESPONSE, result="Exit intent processed", response=ha_response ) except Exception as e: - logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}") + logger.bind(tag=TAG).error(f"Error processing music intent: {e}") async def handle_hass_play_music(conn, entity_id, media_content_id): @@ -52,10 +53,11 @@ async def handle_hass_play_music(conn, entity_id, media_content_id): api_key = ha_config.get("api_key") base_url = ha_config.get("base_url") url = f"{base_url}/api/services/music_assistant/play_media" - headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} + headers = {"Authorization": f"Bearer {api_key}", + "Content-Type": "application/json"} data = {"entity_id": entity_id, "media_id": media_content_id} response = requests.post(url, headers=headers, json=data) if response.status_code == 200: - return f"正在播放{media_content_id}的音乐" + return f"Now playing {media_content_id} music" else: - return f"音乐播放失败,错误码: {response.status_code}" + return f"Music playback failed, error code: {response.status_code}" diff --git a/main/xiaozhi-server/plugins_func/functions/hass_set_state.py b/main/xiaozhi-server/plugins_func/functions/hass_set_state.py index 704148ee6..1ce6e871d 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_set_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_set_state.py @@ -11,7 +11,7 @@ hass_set_state_function_desc = { "type": "function", "function": { "name": "hass_set_state", - "description": "设置homeassistant里设备的状态,包括开、关,调整灯光亮度、颜色、色温,调整播放器的音量,设备的暂停、继续、静音操作", + "description": "Set device status in homeassistant, including on/off, adjusting light brightness, color, color temperature, adjusting player volume, device pause/resume/mute operations", "parameters": { "type": "object", "properties": { @@ -20,27 +20,27 @@ hass_set_state_function_desc = { "properties": { "type": { "type": "string", - "description": "需要操作的动作,打开设备:turn_on,关闭设备:turn_off,增加亮度:brightness_up,降低亮度:brightness_down,设置亮度:brightness_value,增加音量:volume_up,降低音量:volume_down,设置音量:volume_set,设置色温:set_kelvin,设置颜色:set_color,设备暂停:pause,设备继续:continue,静音/取消静音:volume_mute", + "description": "Action to perform, turn on device: turn_on, turn off device: turn_off, increase brightness: brightness_up, decrease brightness: brightness_down, set brightness: brightness_value, increase volume: volume_up, decrease volume: volume_down, set volume: volume_set, set color temperature: set_kelvin, set color: set_color, device pause: pause, device resume: continue, mute/unmute: volume_mute", }, "input": { "type": "integer", - "description": "只有在设置音量,设置亮度时候才需要,有效值为1-100,对应音量和亮度的1%-100%", + "description": "Only needed when setting volume or brightness, valid values 1-100, corresponding to 1%-100% volume and brightness", }, "is_muted": { "type": "string", - "description": "只有在设置静音操作时才需要,设置静音的时候该值为true,取消静音时该值为false", + "description": "Only needed for mute operations, set to true when muting, false when unmuting", }, "rgb_color": { "type": "array", "items": {"type": "integer"}, - "description": "只有在设置颜色时需要,这里填目标颜色的rgb值", + "description": "Only needed when setting color, fill target color RGB values here", }, }, "required": ["type"], }, "entity_id": { "type": "string", - "description": "需要操作的设备id,homeassistant里的entity_id", + "description": "Device ID to operate, entity_id in homeassistant", }, }, "required": ["state", "entity_id"], @@ -48,7 +48,6 @@ hass_set_state_function_desc = { }, } - @register_function("hass_set_state", hass_set_state_function_desc, ToolType.SYSTEM_CTL) def hass_set_state(conn, entity_id="", state={}): try: @@ -58,85 +57,99 @@ def hass_set_state(conn, entity_id="", state={}): ha_response = future.result() return ActionResponse(Action.REQLLM, ha_response, None) except Exception as e: - logger.bind(tag=TAG).error(f"处理设置属性意图错误: {e}") - + logger.bind(tag=TAG).error(f"Error processing set attribute intent: {e}") async def handle_hass_set_state(conn, entity_id, state): ha_config = initialize_hass_handler(conn) api_key = ha_config.get("api_key") base_url = ha_config.get("base_url") + """ state = { "type":"brightness_up","input":"80","is_muted":"true"} """ + domains = entity_id.split(".") if len(domains) > 1: domain = domains[0] else: - return "执行失败,错误的设备id" + return "Execution failed, invalid device id" + action = "" arg = "" value = "" + if state["type"] == "turn_on": - description = "设备已打开" + description = "Device turned on" if domain == "cover": action = "open_cover" elif domain == "vacuum": action = "start" else: action = "turn_on" + elif state["type"] == "turn_off": - description = "设备已关闭" + description = "Device turned off" if domain == "cover": action = "close_cover" elif domain == "vacuum": action = "stop" else: action = "turn_off" + elif state["type"] == "brightness_up": - description = "灯光已调亮" + description = "Light brightness increased" action = "turn_on" arg = "brightness_step_pct" value = 10 + elif state["type"] == "brightness_down": - description = "灯光已调暗" + description = "Light brightness decreased" action = "turn_on" arg = "brightness_step_pct" value = -10 + elif state["type"] == "brightness_value": - description = f"亮度已调整到{state['input']}" + description = f"Brightness adjusted to {state['input']}" action = "turn_on" arg = "brightness_pct" value = state["input"] + elif state["type"] == "set_color": - description = f"颜色已调整到{state['rgb_color']}" + description = f"Color adjusted to {state['rgb_color']}" action = "turn_on" arg = "rgb_color" value = state["rgb_color"] + elif state["type"] == "set_kelvin": - description = f"色温已调整到{state['input']}K" + description = f"Color temperature adjusted to {state['input']}K" action = "turn_on" arg = "kelvin" value = state["input"] + elif state["type"] == "volume_up": - description = "音量已调大" + description = "Volume increased" action = state["type"] + elif state["type"] == "volume_down": - description = "音量已调小" + description = "Volume decreased" action = state["type"] + elif state["type"] == "volume_set": - description = f"音量已调整到{state['input']}" + description = f"Volume adjusted to {state['input']}" action = state["type"] arg = "volume_level" value = state["input"] if state["input"] >= 1: value = state["input"] / 100 + elif state["type"] == "volume_mute": - description = f"设备已静音" + description = f"Device muted" action = state["type"] arg = "is_volume_muted" value = state["is_muted"] + elif state["type"] == "pause": - description = f"设备已暂停" + description = f"Device paused" action = state["type"] if domain == "media_player": action = "media_pause" @@ -144,28 +157,33 @@ async def handle_hass_set_state(conn, entity_id, state): action = "stop_cover" if domain == "vacuum": action = "pause" + elif state["type"] == "continue": - description = f"设备已继续" + description = f"Device resumed" if domain == "media_player": action = "media_play" if domain == "vacuum": action = "start" + else: - return f"{domain} {state.type}功能尚未支持" - + return f"{domain} {state.type} function not yet supported" + if arg == "": data = { "entity_id": entity_id, } else: data = {"entity_id": entity_id, arg: value} + url = f"{base_url}/api/services/{domain}/{action}" headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} response = requests.post(url, headers=headers, json=data) + logger.bind(tag=TAG).info( - f"设置状态:{description},url:{url},return_code:{response.status_code}" + f"Set status: {description}, url: {url}, return_code: {response.status_code}" ) + if response.status_code == 200: return description else: - return f"设置失败,错误码: {response.status_code}" + return f"Setting failed, error code: {response.status_code}" \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 0edf3c0de..0ff9865e5 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -1,10 +1,13 @@ +from config.logger import setup_logging import os import re import time import random +import asyncio import difflib import traceback from pathlib import Path +from core.utils import p3 from core.handle.sendAudioHandle import send_stt_message from plugins_func.register import register_function, ToolType, ActionResponse, Action from core.utils.dialogue import Message @@ -18,13 +21,13 @@ play_music_function_desc = { "type": "function", "function": { "name": "play_music", - "description": "唱歌、听歌、播放音乐的方法。", + "description": "Method for singing, listening to songs, and playing music.", "parameters": { "type": "object", "properties": { "song_name": { "type": "string", - "description": "歌曲名称,如果用户没有指定具体歌名则为'random', 明确指定的时返回音乐的名字 示例: ```用户:播放两只老虎\n参数:两只老虎``` ```用户:播放音乐 \n参数:random ```", + "description": "Song name. If user doesn't specify a specific song name, it should be 'random'. When explicitly specified, return the music name. Example: ```User: play Two Tigers\nParameter: Two Tigers``` ```User: play music\nParameter: random```", } }, "required": ["song_name"], @@ -37,44 +40,45 @@ play_music_function_desc = { def play_music(conn, song_name: str): try: music_intent = ( - f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐" + f"Play music {song_name}" if song_name != "random" else "Play random music" ) - # 检查事件循环状态 + # Check event loop status if not conn.loop.is_running(): - conn.logger.bind(tag=TAG).error("事件循环未运行,无法提交任务") + conn.logger.bind(tag=TAG).error( + "Event loop is not running, cannot submit task") return ActionResponse( - action=Action.RESPONSE, result="系统繁忙", response="请稍后再试" + action=Action.RESPONSE, result="System busy", response="Please try again later" ) - # 提交异步任务 - task = conn.loop.create_task( - handle_music_command(conn, music_intent) # 封装异步逻辑 + # Submit async task + future = asyncio.run_coroutine_threadsafe( + handle_music_command(conn, music_intent), conn.loop ) - # 非阻塞回调处理 + # Non-blocking callback handling def handle_done(f): try: - f.result() # 可在此处理成功逻辑 - conn.logger.bind(tag=TAG).info("播放完成") + f.result() # Can handle success logic here + conn.logger.bind(tag=TAG).info("Playback completed") except Exception as e: - conn.logger.bind(tag=TAG).error(f"播放失败: {e}") + conn.logger.bind(tag=TAG).error(f"Playback failed: {e}") - task.add_done_callback(handle_done) + future.add_done_callback(handle_done) return ActionResponse( - action=Action.NONE, result="指令已接收", response="正在为您播放音乐" + action=Action.NONE, result="Command received", response="Playing music for you" ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}") + conn.logger.bind(tag=TAG).error(f"Error processing music intent: {e}") return ActionResponse( - action=Action.RESPONSE, result=str(e), response="播放音乐时出错了" + action=Action.RESPONSE, result=str(e), response="Error occurred while playing music" ) def _extract_song_name(text): - """从用户输入中提取歌名""" - for keyword in ["播放音乐"]: + """Extract song name from user input""" + for keyword in ["Play music"]: if keyword in text: parts = text.split(keyword) if len(parts) > 1: @@ -83,13 +87,14 @@ def _extract_song_name(text): def _find_best_match(potential_song, music_files): - """查找最匹配的歌曲""" + """Find the best matching song""" best_match = None highest_ratio = 0 for music_file in music_files: song_name = os.path.splitext(music_file)[0] - ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio() + ratio = difflib.SequenceMatcher( + None, potential_song, song_name).ratio() if ratio > highest_ratio and ratio > 0.4: highest_ratio = ratio best_match = music_file @@ -101,13 +106,13 @@ def get_music_files(music_dir, music_ext): music_files = [] music_file_names = [] for file in music_dir.rglob("*"): - # 判断是否是文件 + # Check if it's a file if file.is_file(): - # 获取文件扩展名 + # Get file extension ext = file.suffix.lower() - # 判断扩展名是否在列表中 + # Check if extension is in the list if ext in music_ext: - # 添加相对路径 + # Add relative path music_files.append(str(file.relative_to(music_dir))) music_file_names.append( os.path.splitext(str(file.relative_to(music_dir)))[0] @@ -121,7 +126,8 @@ def initialize_music_handler(conn): if "play_music" in conn.config["plugins"]: MUSIC_CACHE["music_config"] = conn.config["plugins"]["play_music"] MUSIC_CACHE["music_dir"] = os.path.abspath( - MUSIC_CACHE["music_config"].get("music_dir", "./music") # 默认路径修改 + MUSIC_CACHE["music_config"].get( + "music_dir", "./music") # Default path modified ) MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get( "music_ext", (".mp3", ".wav", ".p3") @@ -133,7 +139,7 @@ def initialize_music_handler(conn): MUSIC_CACHE["music_dir"] = os.path.abspath("./music") MUSIC_CACHE["music_ext"] = (".mp3", ".wav", ".p3") MUSIC_CACHE["refresh_time"] = 60 - # 获取音乐文件列表 + # Get music file list MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files( MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"] ) @@ -145,84 +151,88 @@ async def handle_music_command(conn, text): initialize_music_handler(conn) global MUSIC_CACHE - """处理音乐播放指令""" + """Handle music playback commands""" clean_text = re.sub(r"[^\w\s]", "", text).strip() - conn.logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") + conn.logger.bind(tag=TAG).debug( + f"Check if it's a music command: {clean_text}") - # 尝试匹配具体歌名 + # Try to match specific song name if os.path.exists(MUSIC_CACHE["music_dir"]): if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]: - # 刷新音乐文件列表 + # Refresh music file list MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = ( - get_music_files(MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"]) + get_music_files( + MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"]) ) MUSIC_CACHE["scan_time"] = time.time() potential_song = _extract_song_name(clean_text) if potential_song: - best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"]) + best_match = _find_best_match( + potential_song, MUSIC_CACHE["music_files"]) if best_match: - conn.logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}") + conn.logger.bind(tag=TAG).info( + f"Found best matching song: {best_match}") await play_local_music(conn, specific_file=best_match) return True - # 检查是否是通用播放音乐命令 + # Check if it's a general play music command await play_local_music(conn) return True def _get_random_play_prompt(song_name): - """生成随机播放引导语""" - # 移除文件扩展名 + """Generate random play prompt""" + # Remove file extension clean_name = os.path.splitext(song_name)[0] prompts = [ - f"Now playing for you, '{clean_name}'", - f"Please enjoy the song, '{clean_name}'", - f"About to play for you, '{clean_name}'", - f"Now bringing you, '{clean_name}'", - f"Let's listen together to, '{clean_name}'", - f"Next, please enjoy, '{clean_name}'", - f"At this moment, presenting to you, '{clean_name}'", + f"Now playing for you, {clean_name}", + f"Please enjoy the song, {clean_name}", + f"About to play for you, {clean_name}", + f"Bringing you, {clean_name}", + f"Let's listen to, {clean_name}", + f"Next, please enjoy, {clean_name}", + f"Presenting to you, {clean_name}", ] - # 直接使用random.choice,不设置seed + # Use random.choice directly, don't set seed return random.choice(prompts) async def play_local_music(conn, specific_file=None): global MUSIC_CACHE - """播放本地音乐文件""" + """Play local music files""" try: if not os.path.exists(MUSIC_CACHE["music_dir"]): conn.logger.bind(tag=TAG).error( - f"音乐目录不存在: " + MUSIC_CACHE["music_dir"] + f"Music directory does not exist: " + MUSIC_CACHE["music_dir"] ) return - # 确保路径正确性 + # Ensure path correctness if specific_file: selected_music = specific_file music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file) else: if not MUSIC_CACHE["music_files"]: - conn.logger.bind(tag=TAG).error("未找到MP3音乐文件") + conn.logger.bind(tag=TAG).error("No MP3 music files found") return selected_music = random.choice(MUSIC_CACHE["music_files"]) music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music) if not os.path.exists(music_path): - conn.logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") + conn.logger.bind(tag=TAG).error( + f"Selected music file does not exist: {music_path}") return text = _get_random_play_prompt(selected_music) await send_stt_message(conn, text) conn.dialogue.put(Message(role="assistant", content=text)) - if conn.intent_type == "intent_llm": - conn.tts.tts_text_queue.put( - TTSMessageDTO( - sentence_id=conn.sentence_id, - sentence_type=SentenceType.FIRST, - content_type=ContentType.ACTION, - ) + conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=conn.sentence_id, + sentence_type=SentenceType.FIRST, + content_type=ContentType.ACTION, ) + ) conn.tts.tts_text_queue.put( TTSMessageDTO( sentence_id=conn.sentence_id, @@ -239,15 +249,15 @@ async def play_local_music(conn, specific_file=None): content_file=music_path, ) ) - if conn.intent_type == "intent_llm": - conn.tts.tts_text_queue.put( - TTSMessageDTO( - sentence_id=conn.sentence_id, - sentence_type=SentenceType.LAST, - content_type=ContentType.ACTION, - ) + conn.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=conn.sentence_id, + sentence_type=SentenceType.LAST, + content_type=ContentType.ACTION, ) + ) except Exception as e: - conn.logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") - conn.logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") \ No newline at end of file + conn.logger.bind(tag=TAG).error(f"Failed to play music: {str(e)}") + conn.logger.bind(tag=TAG).error( + f"Detailed error: {traceback.format_exc()}") diff --git a/main/xiaozhi-server/plugins_func/loadplugins.py b/main/xiaozhi-server/plugins_func/loadplugins.py index 9b20355e5..1aff87fdc 100644 --- a/main/xiaozhi-server/plugins_func/loadplugins.py +++ b/main/xiaozhi-server/plugins_func/loadplugins.py @@ -2,24 +2,27 @@ import importlib import pkgutil from config.logger import setup_logging + TAG = __name__ + logger = setup_logging() + def auto_import_modules(package_name): """ - 自动导入指定包内的所有模块。 + Automatically import all modules within the specified package. Args: - package_name (str): 包的名称,如 'functions'。 + package_name (str): Package name, e.g., 'functions'. """ - # 获取包的路径 + # Get package path package = importlib.import_module(package_name) package_path = package.__path__ - # 遍历包内的所有模块 + # Iterate through all modules in the package for _, module_name, _ in pkgutil.iter_modules(package_path): - # 导入模块 + # Import module full_module_name = f"{package_name}.{module_name}" importlib.import_module(full_module_name) - #logger.bind(tag=TAG).info(f"模块 '{full_module_name}' 已加载") \ No newline at end of file + # logger.bind(tag=TAG).info(f"Module '{full_module_name}' loaded") diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py index 5c2b0781a..c9820dcc2 100644 --- a/main/xiaozhi-server/plugins_func/register.py +++ b/main/xiaozhi-server/plugins_func/register.py @@ -7,15 +7,16 @@ logger = setup_logging() class ToolType(Enum): - NONE = (1, "调用完工具后,不做其他操作") - WAIT = (2, "调用工具,等待函数返回") - CHANGE_SYS_PROMPT = (3, "修改系统提示词,切换角色性格或职责") + NONE = (1, "No other operations after calling tool") + WAIT = (2, "Call tool and wait for function return") + CHANGE_SYS_PROMPT = ( + 3, "Modify system prompt, switch role personality or responsibility") SYSTEM_CTL = ( 4, - "系统控制,影响正常的对话流程,如退出、播放音乐等,需要传递conn参数", + "System control, affects normal conversation flow, such as exit, play music, etc., requires conn parameter", ) - IOT_CTL = (5, "IOT设备控制,需要传递conn参数") - MCP_CLIENT = (6, "MCP客户端") + IOT_CTL = (5, "IOT device control, requires conn parameter") + MCP_CLIENT = (6, "MCP client") def __init__(self, code, message): self.code = code @@ -23,11 +24,11 @@ class ToolType(Enum): class Action(Enum): - ERROR = (-1, "错误") - NOTFOUND = (0, "没有找到函数") - NONE = (1, "啥也不干") - RESPONSE = (2, "直接回复") - REQLLM = (3, "调用函数后再请求llm生成回复") + ERROR = (-1, "Error") + NOTFOUND = (0, "Function not found") + NONE = (1, "Do nothing") + RESPONSE = (2, "Direct response") + REQLLM = (3, "Request LLM to generate response after calling function") def __init__(self, code, message): self.code = code @@ -36,9 +37,9 @@ class Action(Enum): class ActionResponse: def __init__(self, action: Action, result=None, response=None): - self.action = action # 动作类型 - self.result = result # 动作产生的结果 - self.response = response # 直接回复的内容 + self.action = action # Action type + self.result = result # Result produced by action + self.response = response # Direct response content class FunctionItem: @@ -50,51 +51,52 @@ class FunctionItem: class DeviceTypeRegistry: - """设备类型注册表,用于管理IOT设备类型及其函数""" + """Device type registry for managing IOT device types and their functions""" def __init__(self): self.type_functions = {} # type_signature -> {func_name: FunctionItem} def generate_device_type_id(self, descriptor): - """通过设备能力描述生成类型ID""" + """Generate type ID through device capability description""" properties = sorted(descriptor["properties"].keys()) methods = sorted(descriptor["methods"].keys()) - # 使用属性和方法的组合作为设备类型的唯一标识 + # Use combination of properties and methods as unique identifier for device type type_signature = ( f"{descriptor['name']}:{','.join(properties)}:{','.join(methods)}" ) return type_signature def get_device_functions(self, type_id): - """获取设备类型对应的所有函数""" + """Get all functions corresponding to device type""" return self.type_functions.get(type_id, {}) def register_device_type(self, type_id, functions): - """注册设备类型及其函数""" + """Register device type and its functions""" if type_id not in self.type_functions: self.type_functions[type_id] = functions -# 初始化函数注册字典 +# Initialize function registry dictionary all_function_registry = {} def register_function(name, desc, type=None): - """注册函数到函数注册字典的装饰器""" + """Decorator for registering functions to function registry dictionary""" def decorator(func): all_function_registry[name] = FunctionItem(name, desc, func, type) - logger.bind(tag=TAG).debug(f"函数 '{name}' 已加载,可以注册使用") + logger.bind(tag=TAG).debug( + f"Function '{name}' loaded, ready for registration") return func return decorator def register_device_function(name, desc, type=None): - """注册设备级别的函数到函数注册字典的装饰器""" + """Decorator for registering device-level functions to function registry dictionary""" def decorator(func): - logger.bind(tag=TAG).debug(f"设备函数 '{name}' 已加载") + logger.bind(tag=TAG).debug(f"Device function '{name}' loaded") return func return decorator @@ -106,28 +108,31 @@ class FunctionRegistry: self.logger = setup_logging() def register_function(self, name, func_item=None): - # 如果提供了func_item,直接注册 + # If func_item is provided, register directly if func_item: self.function_registry[name] = func_item - self.logger.bind(tag=TAG).debug(f"函数 '{name}' 直接注册成功") + self.logger.bind(tag=TAG).debug( + f"Function '{name}' registered directly") return func_item - # 否则从all_function_registry中查找 + # Otherwise search from all_function_registry func = all_function_registry.get(name) if not func: - self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到") + self.logger.bind(tag=TAG).error(f"Function '{name}' not found") return None self.function_registry[name] = func - self.logger.bind(tag=TAG).debug(f"函数 '{name}' 注册成功") + self.logger.bind(tag=TAG).debug( + f"Function '{name}' registered successfully") return func def unregister_function(self, name): - # 注销函数,检测是否存在 + # Unregister function, check if exists if name not in self.function_registry: - self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到") + self.logger.bind(tag=TAG).error(f"Function '{name}' not found") return False self.function_registry.pop(name, None) - self.logger.bind(tag=TAG).info(f"函数 '{name}' 注销成功") + self.logger.bind(tag=TAG).info( + f"Function '{name}' unregistered successfully") return True def get_function(self, name):