mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #4 from Craftech360-projects/translated-to-english
tranlated to english server and mqtt folders
This commit is contained in:
commit
a68b8ffa18
143 changed files with 7811 additions and 5873 deletions
|
|
@ -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协议
|
- **Multi-protocol Support**: Simultaneous support for MQTT, UDP, and WebSocket protocols
|
||||||
- **音频数据传输**: 专为音频数据流优化的传输机制
|
- **Audio Data Transmission**: Transmission mechanism optimized for audio data streams
|
||||||
- **加密通信**: 使用AES-128-CTR加密UDP数据传输
|
- **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服务器**: 处理设备控制消息
|
- **MQTT Server**: Handles device control messages
|
||||||
- **UDP服务器**: 处理高效的音频数据传输
|
- **UDP Server**: Handles efficient audio data transmission
|
||||||
- **WebSocket客户端**: 连接到聊天服务器
|
- **WebSocket Client**: Connects to chat servers
|
||||||
- **桥接层**: 在不同协议间转换和路由消息
|
- **Bridge Layer**: Converts and routes messages between different protocols
|
||||||
|
|
||||||
## 项目结构
|
## Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
├── app.js # 主应用入口
|
├── app.js # Main application entry point
|
||||||
├── mqtt-protocol.js # MQTT协议实现
|
├── mqtt-protocol.js # MQTT protocol implementation
|
||||||
├── ecosystem.config.js # PM2配置文件
|
├── ecosystem.config.js # PM2 configuration file
|
||||||
├── package.json # 项目依赖
|
├── package.json # Project dependencies
|
||||||
├── .env # 环境变量配置
|
├── .env # Environment variable configuration
|
||||||
├── utils/
|
├── utils/
|
||||||
│ ├── config-manager.js # 配置管理工具
|
│ ├── config-manager.js # Configuration management tool
|
||||||
│ ├── mqtt_config_v2.js # MQTT配置验证工具
|
│ ├── mqtt_config_v2.js # MQTT configuration validation tool
|
||||||
│ └── weixinAlert.js # 微信告警工具
|
│ └── weixinAlert.js # WeChat alert tool
|
||||||
└── config/ # 配置文件目录
|
└── config/ # Configuration file directory
|
||||||
```
|
```
|
||||||
|
|
||||||
## 依赖项
|
## Dependencies
|
||||||
|
|
||||||
- **debug**: 调试日志输出
|
- **debug**: Debug log output
|
||||||
- **dotenv**: 环境变量管理
|
- **dotenv**: Environment variable management
|
||||||
- **ws**: WebSocket客户端
|
- **ws**: WebSocket client
|
||||||
- **events**: Node.js 事件模块
|
- **events**: Node.js event module
|
||||||
|
|
||||||
## 安装要求
|
## Installation Requirements
|
||||||
|
|
||||||
- Node.js 14.x 或更高版本
|
- Node.js 14.x or higher
|
||||||
- npm 或 yarn 包管理器
|
- npm or yarn package manager
|
||||||
- PM2 (用于生产环境部署)
|
- PM2 (for production environment deployment)
|
||||||
|
|
||||||
## 安装步骤
|
## Installation Steps
|
||||||
|
|
||||||
|
1. Clone repository
|
||||||
|
|
||||||
1. 克隆仓库
|
|
||||||
```bash
|
```bash
|
||||||
git clone <仓库地址>
|
git clone <repository-url>
|
||||||
cd mqtt-websocket-bridge
|
cd mqtt-websocket-bridge
|
||||||
```
|
```
|
||||||
|
|
||||||
2. 安装依赖
|
2. Install dependencies
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
```
|
```
|
||||||
|
|
||||||
3. 创建配置文件
|
3. Create configuration file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
mkdir -p config
|
mkdir -p config
|
||||||
cp config/mqtt.json.example config/mqtt.json
|
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
|
```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服务器端口
|
MQTT_PORT=1883 # MQTT server port
|
||||||
UDP_PORT=8884 # UDP服务器端口
|
UDP_PORT=8884 # UDP server port
|
||||||
PUBLIC_IP=your-ip # 服务器公网IP
|
PUBLIC_IP=your-ip # Server public IP
|
||||||
```
|
```
|
||||||
|
|
||||||
## 运行服务
|
## Running the Service
|
||||||
|
|
||||||
### 开发环境
|
### Development Environment
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 直接运行
|
# Run directly
|
||||||
node app.js
|
node app.js
|
||||||
|
|
||||||
# 调试模式运行
|
# Run in debug mode
|
||||||
DEBUG=mqtt-server node app.js
|
DEBUG=mqtt-server node app.js
|
||||||
```
|
```
|
||||||
|
|
||||||
### 生产环境 (使用PM2)
|
### Production Environment (Using PM2)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 安装PM2
|
# Install PM2
|
||||||
npm install -g pm2
|
npm install -g pm2
|
||||||
|
|
||||||
# 启动服务
|
# Start service
|
||||||
pm2 start ecosystem.config.js
|
pm2 start ecosystem.config.js
|
||||||
|
|
||||||
# 查看日志
|
# View logs
|
||||||
pm2 logs xz-mqtt
|
pm2 logs xz-mqtt
|
||||||
|
|
||||||
# 监控服务
|
# Monitor service
|
||||||
pm2 monit
|
pm2 monit
|
||||||
```
|
```
|
||||||
|
|
||||||
服务将在以下端口启动:
|
The service will start on the following ports:
|
||||||
- MQTT 服务器: 端口 1883 (可通过环境变量修改)
|
|
||||||
- UDP 服务器: 端口 8884 (可通过环境变量修改)
|
|
||||||
|
|
||||||
## 协议说明
|
- MQTT Server: Port 1883 (can be modified via environment variables)
|
||||||
|
- UDP Server: Port 8884 (can be modified via environment variables)
|
||||||
|
|
||||||
### 设备连接流程
|
## Protocol Description
|
||||||
|
|
||||||
1. 设备通过MQTT协议连接到服务器
|
### Device Connection Flow
|
||||||
2. 设备发送 `hello` 消息,包含音频参数和特性
|
|
||||||
3. 服务器创建WebSocket连接到聊天服务器
|
|
||||||
4. 服务器返回UDP连接参数给设备
|
|
||||||
5. 设备通过UDP发送音频数据
|
|
||||||
6. 服务器将音频数据转发到WebSocket
|
|
||||||
7. WebSocket返回的控制消息通过MQTT发送给设备
|
|
||||||
|
|
||||||
### 消息格式
|
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
|
```json
|
||||||
{
|
{
|
||||||
"type": "hello",
|
"type": "hello",
|
||||||
|
|
@ -153,7 +158,8 @@ pm2 monit
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Hello 响应 (服务器 -> 设备)
|
#### Hello Response (Server -> Device)
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"type": "hello",
|
"type": "hello",
|
||||||
|
|
@ -171,45 +177,45 @@ pm2 monit
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 安全说明
|
## Security Description
|
||||||
|
|
||||||
- UDP通信使用AES-128-CTR加密
|
- UDP communication uses AES-128-CTR encryption
|
||||||
- 每个会话使用唯一的加密密钥
|
- Each session uses a unique encryption key
|
||||||
- 使用序列号防止重放攻击
|
- Uses sequence numbers to prevent replay attacks
|
||||||
- 设备通过MAC地址进行身份验证
|
- Device authentication via MAC address
|
||||||
- 支持设备分组和UUID验证
|
- Supports device grouping and UUID verification
|
||||||
|
|
||||||
## 性能优化
|
## Performance Optimization
|
||||||
|
|
||||||
- 使用预分配的缓冲区减少内存分配
|
- Uses pre-allocated buffers to reduce memory allocation
|
||||||
- UDP协议用于高效传输音频数据
|
- 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地址格式是否正确
|
- Check if device MAC address format is correct
|
||||||
- 确保UDP端口在防火墙中开放
|
- 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功能
|
1. Modify `mqtt-protocol.js` to support new MQTT functionality
|
||||||
2. 在 `MQTTConnection` 类中添加新的消息处理方法
|
2. Add new message handling methods in `MQTTConnection` class
|
||||||
3. 更新配置管理器以支持新的配置选项
|
3. Update configuration manager to support new configuration options
|
||||||
4. 在 `WebSocketBridge` 类中添加新的WebSocket处理逻辑
|
4. Add new WebSocket handling logic in `WebSocketBridge` class
|
||||||
|
|
||||||
### 调试技巧
|
### Debugging Tips
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 启用所有调试输出
|
# Enable all debug output
|
||||||
DEBUG=* node app.js
|
DEBUG=* node app.js
|
||||||
|
|
||||||
# 只启用MQTT服务器调试
|
# Enable only MQTT server debugging
|
||||||
DEBUG=mqtt-server node app.js
|
DEBUG=mqtt-server node app.js
|
||||||
```
|
```
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,81 +1,78 @@
|
||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
/**
|
|
||||||
* MQTT签名密钥生成器
|
|
||||||
* 用于生成MQTT_SIGNATURE_KEY环境变量
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MQTT signature key generator
|
||||||
|
* Used to generate MQTT_SIGNATURE_KEY environment variable
|
||||||
|
*/
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
|
||||||
function generateSecureKey(length = 32) {
|
function generateSecureKey(length = 32) {
|
||||||
// 生成随机字节
|
// Generate random bytes
|
||||||
const randomBytes = crypto.randomBytes(length);
|
const randomBytes = crypto.randomBytes(length);
|
||||||
|
// Convert to base64 string
|
||||||
// 转换为base64字符串
|
|
||||||
const base64Key = randomBytes.toString('base64');
|
const base64Key = randomBytes.toString('base64');
|
||||||
|
|
||||||
return base64Key;
|
return base64Key;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateHexKey(length = 32) {
|
function generateHexKey(length = 32) {
|
||||||
// 生成随机字节
|
// Generate random bytes
|
||||||
const randomBytes = crypto.randomBytes(length);
|
const randomBytes = crypto.randomBytes(length);
|
||||||
|
// Convert to hexadecimal string
|
||||||
// 转换为十六进制字符串
|
|
||||||
const hexKey = randomBytes.toString('hex');
|
const hexKey = randomBytes.toString('hex');
|
||||||
|
|
||||||
return hexKey;
|
return hexKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateUUIDKey() {
|
function generateUUIDKey() {
|
||||||
// 使用UUID v4作为密钥
|
// Use UUID v4 as key
|
||||||
const uuid = crypto.randomUUID();
|
const uuid = crypto.randomUUID();
|
||||||
return uuid;
|
return uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('='.repeat(60));
|
console.log('='.repeat(60));
|
||||||
console.log('MQTT签名密钥生成器');
|
console.log('MQTT Signature Key Generator');
|
||||||
console.log('='.repeat(60));
|
console.log('='.repeat(60));
|
||||||
|
|
||||||
console.log('\n1. Base64格式密钥 (推荐):');
|
console.log('\n1. Base64 format key (recommended):');
|
||||||
const base64Key = generateSecureKey();
|
const base64Key = generateSecureKey();
|
||||||
console.log(` ${base64Key}`);
|
console.log(` ${base64Key}`);
|
||||||
|
|
||||||
console.log('\n2. 十六进制格式密钥:');
|
console.log('\n2. Hexadecimal format key:');
|
||||||
const hexKey = generateHexKey();
|
const hexKey = generateHexKey();
|
||||||
console.log(` ${hexKey}`);
|
console.log(` ${hexKey}`);
|
||||||
|
|
||||||
console.log('\n3. UUID格式密钥:');
|
console.log('\n3. UUID format key:');
|
||||||
const uuidKey = generateUUIDKey();
|
const uuidKey = generateUUIDKey();
|
||||||
console.log(` ${uuidKey}`);
|
console.log(` ${uuidKey}`);
|
||||||
|
|
||||||
console.log('\n='.repeat(60));
|
console.log('\n='.repeat(60));
|
||||||
console.log('使用方法:');
|
console.log('Usage:');
|
||||||
console.log('='.repeat(60));
|
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(`$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(`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(`export MQTT_SIGNATURE_KEY="${base64Key}"`);
|
||||||
|
|
||||||
console.log('\n在.env文件中设置:');
|
console.log('\nSet in .env file:');
|
||||||
console.log(`MQTT_SIGNATURE_KEY=${base64Key}`);
|
console.log(`MQTT_SIGNATURE_KEY=${base64Key}`);
|
||||||
|
|
||||||
console.log('\n='.repeat(60));
|
console.log('\n='.repeat(60));
|
||||||
console.log('注意事项:');
|
console.log('Notes:');
|
||||||
console.log('='.repeat(60));
|
console.log('='.repeat(60));
|
||||||
console.log('1. 请妥善保管生成的密钥,不要泄露给他人');
|
console.log('1. Please keep the generated key secure and do not leak it to others');
|
||||||
console.log('2. 在生产环境中,建议使用更长的密钥 (64字节)');
|
console.log('2. In production environment, longer keys are recommended (64 bytes)');
|
||||||
console.log('3. 密钥设置后需要重启MQTT服务器才能生效');
|
console.log('3. MQTT server needs to be restarted after setting the key');
|
||||||
console.log('4. 客户端连接时需要使用相同的密钥生成密码签名');
|
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]) {
|
if (process.argv[2]) {
|
||||||
const customLength = parseInt(process.argv[2]);
|
const customLength = parseInt(process.argv[2]);
|
||||||
if (customLength > 0) {
|
if (customLength > 0) {
|
||||||
console.log(`\n自定义长度密钥 (${customLength}字节):`);
|
console.log(`\nCustom length key (${customLength} bytes):`);
|
||||||
console.log(` ${generateSecureKey(customLength)}`);
|
console.log(` ${generateSecureKey(customLength)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1,499 +1,513 @@
|
||||||
const debug = require('debug')('mqtt-server');
|
const debug = require("debug")("mqtt-server");
|
||||||
const EventEmitter = require('events');
|
const EventEmitter = require("events");
|
||||||
|
|
||||||
// MQTT 固定头部的类型
|
// MQTT fixed header types
|
||||||
const PacketType = {
|
const PacketType = {
|
||||||
CONNECT: 1,
|
CONNECT: 1,
|
||||||
CONNACK: 2,
|
CONNACK: 2,
|
||||||
PUBLISH: 3,
|
PUBLISH: 3,
|
||||||
SUBSCRIBE: 8,
|
SUBSCRIBE: 8,
|
||||||
SUBACK: 9,
|
SUBACK: 9,
|
||||||
PINGREQ: 12,
|
PINGREQ: 12,
|
||||||
PINGRESP: 13,
|
PINGRESP: 13,
|
||||||
DISCONNECT: 14 // 添加 DISCONNECT
|
DISCONNECT: 14, // Added DISCONNECT
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MQTT协议处理类
|
* MQTT protocol handler class
|
||||||
* 负责MQTT协议的解析和封装,以及心跳维持
|
* Responsible for MQTT protocol parsing and encapsulation, as well as heartbeat maintenance
|
||||||
*/
|
*/
|
||||||
class MQTTProtocol extends EventEmitter {
|
class MQTTProtocol extends EventEmitter {
|
||||||
constructor(socket) {
|
constructor(socket) {
|
||||||
super();
|
super();
|
||||||
this.socket = socket;
|
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.buffer = Buffer.alloc(0);
|
||||||
this.isConnected = false;
|
this.emit("protocolError", err);
|
||||||
this.keepAliveInterval = 0;
|
return;
|
||||||
this.lastActivity = Date.now();
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.setupSocketHandlers();
|
/**
|
||||||
|
* 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
pos += 1;
|
||||||
* 设置Socket事件处理
|
// Connection flags
|
||||||
*/
|
const connectFlags = message[pos];
|
||||||
setupSocketHandlers() {
|
const hasUsername = (connectFlags & 0x80) !== 0;
|
||||||
this.socket.on('data', (data) => {
|
const hasPassword = (connectFlags & 0x40) !== 0;
|
||||||
this.lastActivity = Date.now();
|
const cleanSession = (connectFlags & 0x02) !== 0;
|
||||||
this.buffer = Buffer.concat([this.buffer, data]);
|
pos += 1;
|
||||||
this.processBuffer();
|
|
||||||
});
|
|
||||||
|
|
||||||
this.socket.on('close', () => {
|
// Keep alive time
|
||||||
this.emit('close');
|
const keepAlive = message.readUInt16BE(pos);
|
||||||
});
|
pos += 2;
|
||||||
|
|
||||||
this.socket.on('error', (err) => {
|
// Parse clientId
|
||||||
this.emit('error', err);
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Parse password (if exists)
|
||||||
* 处理缓冲区中的所有完整消息
|
let password = "";
|
||||||
*/
|
if (hasPassword) {
|
||||||
processBuffer() {
|
const passwordLength = message.readUInt16BE(pos);
|
||||||
// 持续处理缓冲区中的数据,直到没有完整的消息可以处理
|
pos += 2;
|
||||||
while (this.buffer.length > 0) {
|
password = message.toString("utf8", pos, pos + passwordLength);
|
||||||
// 至少需要2个字节才能开始解析(1字节固定头部 + 至少1字节的剩余长度)
|
pos += passwordLength;
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Set heartbeat interval (1.5 times client-specified keepAlive value, in seconds)
|
||||||
* 解析MQTT报文中的Remaining Length字段
|
this.keepAliveInterval = keepAlive * 1000 * 1.5;
|
||||||
* @param {Buffer} buffer - 消息缓冲区
|
|
||||||
* @returns {{value: number, bytesRead: number}} 包含解析的值和读取的字节数
|
|
||||||
*/
|
|
||||||
decodeRemainingLength(buffer) {
|
|
||||||
let multiplier = 1;
|
|
||||||
let value = 0;
|
|
||||||
let bytesRead = 0;
|
|
||||||
let digit;
|
|
||||||
|
|
||||||
do {
|
// Send CONNACK
|
||||||
if (bytesRead >= 4 || bytesRead >= buffer.length - 1) {
|
this.sendConnack(0, false);
|
||||||
throw new Error('Malformed Remaining Length');
|
|
||||||
}
|
|
||||||
|
|
||||||
digit = buffer[bytesRead + 1];
|
// Mark as connected
|
||||||
bytesRead++;
|
this.isConnected = true;
|
||||||
|
|
||||||
value += (digit & 127) * multiplier;
|
// Emit connection event
|
||||||
multiplier *= 128;
|
this.emit("connect", {
|
||||||
|
clientId,
|
||||||
|
protocol,
|
||||||
|
protocolLevel,
|
||||||
|
keepAlive,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
cleanSession,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
} while ((digit & 128) !== 0);
|
/**
|
||||||
|
* 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
|
||||||
|
|
||||||
return { value, bytesRead };
|
// 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Parse payload
|
||||||
* 编码MQTT报文中的Remaining Length字段
|
const payload = message.slice(payloadStart).toString("utf8");
|
||||||
* @param {number} length - 要编码的长度值
|
|
||||||
* @returns {{bytes: Buffer, bytesLength: number}} 包含编码后的字节和字节长度
|
|
||||||
*/
|
|
||||||
encodeRemainingLength(length) {
|
|
||||||
let digit;
|
|
||||||
const bytes = Buffer.alloc(4); // 最多4个字节
|
|
||||||
let bytesLength = 0;
|
|
||||||
|
|
||||||
do {
|
// Emit publish event
|
||||||
digit = length % 128;
|
this.emit("publish", {
|
||||||
length = Math.floor(length / 128);
|
topic,
|
||||||
// 如果还有更多字节,设置最高位
|
payload,
|
||||||
if (length > 0) {
|
qos,
|
||||||
digit |= 0x80;
|
dup,
|
||||||
}
|
retain,
|
||||||
bytes[bytesLength++] = digit;
|
packetId,
|
||||||
} while (length > 0 && bytesLength < 4);
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return { bytes, bytesLength };
|
/**
|
||||||
|
* 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Encode variable length
|
||||||
* 解析CONNECT消息
|
const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } =
|
||||||
* @param {Buffer} message - 完整的CONNECT消息
|
this.encodeRemainingLength(remainingLength);
|
||||||
*/
|
|
||||||
parseConnect(message) {
|
|
||||||
// 解析剩余长度
|
|
||||||
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
|
|
||||||
|
|
||||||
// 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节)
|
// Allocate buffer: fixed header(1 byte) + variable length field + remaining length value
|
||||||
const headerLength = 1 + bytesRead;
|
const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength);
|
||||||
|
|
||||||
// 从可变头部开始位置读取协议名长度
|
// Write fixed header
|
||||||
const protocolLength = message.readUInt16BE(headerLength);
|
let firstByte = PacketType.PUBLISH << 4;
|
||||||
const protocol = message.toString('utf8', headerLength + 2, headerLength + 2 + protocolLength);
|
if (dup) firstByte |= 0x08;
|
||||||
|
if (qos > 0) firstByte |= qos << 1;
|
||||||
|
if (retain) firstByte |= 0x01;
|
||||||
|
packet[0] = firstByte;
|
||||||
|
|
||||||
// 更新位置指针,跳过协议名
|
// Write variable length field
|
||||||
let pos = headerLength + 2 + protocolLength;
|
remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize);
|
||||||
|
|
||||||
// 协议级别,4为MQTT 3.1.1
|
// Write topic length and topic
|
||||||
const protocolLevel = message[pos];
|
const variableHeaderStart = 1 + remainingLengthSize;
|
||||||
|
packet.writeUInt16BE(topicLength, variableHeaderStart);
|
||||||
|
packet.write(topic, variableHeaderStart + 2);
|
||||||
|
|
||||||
// 检查协议版本
|
// If QoS > 0, write packet ID
|
||||||
if (protocolLevel !== 4) { // 4 表示 MQTT 3.1.1
|
let payloadStart = variableHeaderStart + 2 + topicLength;
|
||||||
debug('不支持的协议版本:', protocolLevel);
|
if (qos > 0 && packetId) {
|
||||||
// 发送 CONNACK,使用不支持的协议版本的返回码 (0x01)
|
packet.writeUInt16BE(packetId, payloadStart);
|
||||||
this.sendConnack(1, false);
|
payloadStart += 2;
|
||||||
// 关闭连接
|
|
||||||
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;
|
|
||||||
|
|
||||||
// 解析 username(如果存在)
|
|
||||||
let username = '';
|
|
||||||
if (hasUsername) {
|
|
||||||
const usernameLength = message.readUInt16BE(pos);
|
|
||||||
pos += 2;
|
|
||||||
username = message.toString('utf8', pos, pos + usernameLength);
|
|
||||||
pos += usernameLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 解析 password(如果存在)
|
|
||||||
let password = '';
|
|
||||||
if (hasPassword) {
|
|
||||||
const passwordLength = message.readUInt16BE(pos);
|
|
||||||
pos += 2;
|
|
||||||
password = message.toString('utf8', pos, pos + passwordLength);
|
|
||||||
pos += passwordLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 设置心跳间隔(客户端指定的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 payload
|
||||||
* 解析PUBLISH消息
|
packet.write(payload, payloadStart);
|
||||||
* @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标志
|
|
||||||
|
|
||||||
// 使用通用方法解析剩余长度
|
this.socket.write(packet);
|
||||||
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
|
this.lastActivity = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
// 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节)
|
/**
|
||||||
const headerLength = 1 + bytesRead;
|
* Send SUBACK message
|
||||||
|
* @param {number} packetId - Packet ID
|
||||||
|
* @param {number} returnCode - Return code
|
||||||
|
*/
|
||||||
|
sendSuback(packetId, returnCode = 0) {
|
||||||
|
if (!this.isConnected || !this.socket.writable) return;
|
||||||
|
|
||||||
// 解析主题
|
const packet = Buffer.from([
|
||||||
const topicLength = message.readUInt16BE(headerLength);
|
PacketType.SUBACK << 4,
|
||||||
const topic = message.toString('utf8', headerLength + 2, headerLength + 2 + topicLength);
|
3, // Remaining length
|
||||||
|
packetId >> 8, // Packet ID MSB
|
||||||
|
packetId & 0xff, // Packet ID LSB
|
||||||
|
returnCode, // Return code
|
||||||
|
]);
|
||||||
|
|
||||||
// 对于QoS > 0,包含消息ID
|
this.socket.write(packet);
|
||||||
let packetId = null;
|
this.lastActivity = Date.now();
|
||||||
let payloadStart = headerLength + 2 + topicLength;
|
}
|
||||||
|
|
||||||
if (qos > 0) {
|
/**
|
||||||
packetId = message.readUInt16BE(payloadStart);
|
* Send PINGRESP message
|
||||||
payloadStart += 2;
|
*/
|
||||||
}
|
sendPingResp() {
|
||||||
|
if (!this.isConnected || !this.socket.writable) return;
|
||||||
|
|
||||||
// 解析有效载荷
|
const packet = Buffer.from([
|
||||||
const payload = message.slice(payloadStart).toString('utf8');
|
PacketType.PINGRESP << 4, // Fixed header
|
||||||
|
0, // Remaining length
|
||||||
|
]);
|
||||||
|
|
||||||
// 发出发布事件
|
this.socket.write(packet);
|
||||||
this.emit('publish', {
|
this.lastActivity = Date.now();
|
||||||
topic,
|
}
|
||||||
payload,
|
|
||||||
qos,
|
/**
|
||||||
dup,
|
* Get last activity time
|
||||||
retain,
|
*/
|
||||||
packetId
|
getLastActivity() {
|
||||||
});
|
return this.lastActivity;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析SUBSCRIBE消息
|
* Get heartbeat interval
|
||||||
* @param {Buffer} message - 完整的SUBSCRIBE消息
|
*/
|
||||||
*/
|
getKeepAliveInterval() {
|
||||||
parseSubscribe(message) {
|
return this.keepAliveInterval;
|
||||||
const packetId = message.readUInt16BE(2);
|
}
|
||||||
const topicLength = message.readUInt16BE(4);
|
|
||||||
const topic = message.toString('utf8', 6, 6 + topicLength);
|
/**
|
||||||
const qos = message[6 + topicLength]; // QoS值
|
* Clear buffer
|
||||||
|
*/
|
||||||
// 发出订阅事件
|
clearBuffer() {
|
||||||
this.emit('subscribe', {
|
this.buffer = Buffer.alloc(0);
|
||||||
packetId,
|
}
|
||||||
topic,
|
|
||||||
qos
|
/**
|
||||||
});
|
* Close connection
|
||||||
}
|
*/
|
||||||
|
close() {
|
||||||
/**
|
if (this.socket.writable) {
|
||||||
* 解析PINGREQ消息
|
this.socket.end();
|
||||||
* @param {Buffer} message - 完整的PINGREQ消息
|
|
||||||
*/
|
|
||||||
parsePingReq(message) {
|
|
||||||
debug('收到心跳请求');
|
|
||||||
|
|
||||||
// 发送 PINGRESP
|
|
||||||
this.sendPingResp();
|
|
||||||
|
|
||||||
debug('已发送心跳响应');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 解析DISCONNECT消息
|
|
||||||
* @param {Buffer} message - 完整的DISCONNECT消息
|
|
||||||
*/
|
|
||||||
parseDisconnect(message) {
|
|
||||||
// 标记为未连接
|
|
||||||
this.isConnected = false;
|
|
||||||
|
|
||||||
// 发出断开连接事件
|
|
||||||
this.emit('disconnect');
|
|
||||||
|
|
||||||
// 关闭 socket
|
|
||||||
this.socket.end();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送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();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送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();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送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();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取上次活动时间
|
|
||||||
*/
|
|
||||||
getLastActivity() {
|
|
||||||
return this.lastActivity;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取心跳间隔
|
|
||||||
*/
|
|
||||||
getKeepAliveInterval() {
|
|
||||||
return this.keepAliveInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清空缓冲区
|
|
||||||
*/
|
|
||||||
clearBuffer() {
|
|
||||||
this.buffer = Buffer.alloc(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 关闭连接
|
|
||||||
*/
|
|
||||||
close() {
|
|
||||||
if (this.socket.writable) {
|
|
||||||
this.socket.end();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 导出 PacketType 和 MQTTProtocol 类
|
// Export PacketType and MQTTProtocol class
|
||||||
module.exports = {
|
module.exports = {
|
||||||
PacketType,
|
PacketType,
|
||||||
MQTTProtocol
|
MQTTProtocol,
|
||||||
};
|
};
|
||||||
|
|
@ -3,74 +3,73 @@ const path = require('path');
|
||||||
const EventEmitter = require('events');
|
const EventEmitter = require('events');
|
||||||
|
|
||||||
class ConfigManager extends EventEmitter {
|
class ConfigManager extends EventEmitter {
|
||||||
constructor(fileName) {
|
constructor(fileName) {
|
||||||
super();
|
super();
|
||||||
this.config = {}; // 移除默认的 apiKeys 配置
|
this.config = {}; // Remove default apiKeys configuration
|
||||||
this.configPath = path.join(__dirname, "..", "config", fileName);
|
this.configPath = path.join(__dirname, "..", "config", fileName);
|
||||||
this.loadConfig();
|
this.loadConfig();
|
||||||
this.watchConfig();
|
this.watchConfig();
|
||||||
// 添加防抖计时器变量
|
// Add debounce timer variable
|
||||||
this.watchDebounceTimer = null;
|
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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
createEmptyConfig() {
|
loadConfig() {
|
||||||
try {
|
try {
|
||||||
const dir = path.dirname(this.configPath);
|
const data = fs.readFileSync(this.configPath, 'utf8');
|
||||||
if (!fs.existsSync(dir)) {
|
const newConfig = JSON.parse(data);
|
||||||
fs.mkdirSync(dir, { recursive: true });
|
// Check if configuration has changed
|
||||||
}
|
if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) {
|
||||||
const defaultConfig = {}; // 空配置对象
|
console.log('Configuration updated', this.configPath);
|
||||||
fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2));
|
this.config = newConfig;
|
||||||
console.log('已创建空配置文件', this.configPath);
|
// Emit configuration update event
|
||||||
} catch (error) {
|
this.emit('configChanged', this.config);
|
||||||
console.error('创建空配置文件出错:', error, this.configPath);
|
}
|
||||||
}
|
} catch (error) {
|
||||||
}
|
console.error('Error loading configuration:', error, this.configPath);
|
||||||
|
if (error.code === 'ENOENT') {
|
||||||
watchConfig() {
|
this.createEmptyConfig();
|
||||||
fs.watch(path.dirname(this.configPath), (eventType, filename) => {
|
}
|
||||||
if (filename === path.basename(this.configPath) && eventType === 'change') {
|
|
||||||
// 清除之前的计时器
|
|
||||||
if (this.watchDebounceTimer) {
|
|
||||||
clearTimeout(this.watchDebounceTimer);
|
|
||||||
}
|
}
|
||||||
// 设置新的计时器,300ms 后执行
|
}
|
||||||
this.watchDebounceTimer = setTimeout(() => {
|
|
||||||
this.loadConfig();
|
|
||||||
}, 300);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取配置的方法
|
createEmptyConfig() {
|
||||||
getConfig() {
|
try {
|
||||||
return this.config;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 获取特定配置项的方法
|
watchConfig() {
|
||||||
get(key) {
|
fs.watch(path.dirname(this.configPath), (eventType, filename) => {
|
||||||
return this.config[key];
|
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 = {
|
module.exports = {
|
||||||
|
|
|
||||||
|
|
@ -1,103 +1,116 @@
|
||||||
require('dotenv').config();
|
require("dotenv").config();
|
||||||
const crypto = require('crypto');
|
const crypto = require("crypto");
|
||||||
|
|
||||||
|
|
||||||
function generatePasswordSignature(content, secretKey) {
|
function generatePasswordSignature(content, secretKey) {
|
||||||
// Create an HMAC object using SHA256 and the secretKey
|
// Create an HMAC object using SHA256 and the secretKey
|
||||||
const hmac = crypto.createHmac('sha256', secretKey);
|
const hmac = crypto.createHmac("sha256", secretKey);
|
||||||
|
// Update the HMAC object with the clientId
|
||||||
// Update the HMAC object with the clientId
|
hmac.update(content);
|
||||||
hmac.update(content);
|
// Generate the HMAC digest in binary format
|
||||||
|
const binarySignature = hmac.digest();
|
||||||
// Generate the HMAC digest in binary format
|
// Encode the binary signature to Base64
|
||||||
const binarySignature = hmac.digest();
|
const base64Signature = binarySignature.toString("base64");
|
||||||
|
return base64Signature;
|
||||||
// Encode the binary signature to Base64
|
|
||||||
const base64Signature = binarySignature.toString('base64');
|
|
||||||
|
|
||||||
return base64Signature;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateMqttCredentials(clientId, username, password) {
|
function validateMqttCredentials(clientId, username, password) {
|
||||||
// 验证密码签名
|
// Validate password signature
|
||||||
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
|
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
|
||||||
if (signatureKey) {
|
if (signatureKey) {
|
||||||
const expectedSignature = generatePasswordSignature(clientId + '|' + username, signatureKey);
|
const expectedSignature = generatePasswordSignature(
|
||||||
if (password !== expectedSignature) {
|
clientId + "|" + username,
|
||||||
throw new Error('密码签名验证失败');
|
signatureKey
|
||||||
}
|
);
|
||||||
} else {
|
if (password !== expectedSignature) {
|
||||||
console.warn('缺少MQTT_SIGNATURE_KEY环境变量,跳过密码签名验证');
|
throw new Error("Password signature validation failed");
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
console.warn(
|
||||||
|
"Missing MQTT_SIGNATURE_KEY environment variable, skipping password signature validation"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// 验证clientId
|
// Validate clientId
|
||||||
if (!clientId || typeof clientId !== 'string') {
|
if (!clientId || typeof clientId !== "string") {
|
||||||
throw new Error('clientId必须是非空字符串');
|
throw new Error("clientId must be a non-empty string");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证clientId格式(必须包含@@@分隔符)
|
// Validate clientId format (must contain @@@ separator)
|
||||||
const clientIdParts = clientId.split('@@@');
|
const clientIdParts = clientId.split("@@@");
|
||||||
// 新版本 MQTT 参数
|
// New version MQTT parameters
|
||||||
if (clientIdParts.length !== 3) {
|
if (clientIdParts.length !== 3) {
|
||||||
throw new Error('clientId格式错误,必须包含@@@分隔符');
|
throw new Error("clientId format error, must contain @@@ separator");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证username
|
// Validate username
|
||||||
if (!username || typeof username !== 'string') {
|
if (!username || typeof username !== "string") {
|
||||||
throw new Error('username必须是非空字符串');
|
throw new Error("username must be a non-empty string");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 尝试解码username(应该是base64编码的JSON)
|
// Try to decode username (should be base64 encoded JSON)
|
||||||
let userData;
|
let userData;
|
||||||
try {
|
try {
|
||||||
const decodedUsername = Buffer.from(username, 'base64').toString();
|
const decodedUsername = Buffer.from(username, "base64").toString();
|
||||||
userData = JSON.parse(decodedUsername);
|
userData = JSON.parse(decodedUsername);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error('username不是有效的base64编码JSON');
|
throw new Error("username is not valid base64 encoded JSON");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析clientId中的信息
|
// Parse information from clientId
|
||||||
const [groupId, macAddress, uuid] = clientIdParts;
|
const [groupId, macAddress, uuid] = clientIdParts;
|
||||||
|
// If validation succeeds, return parsed useful information
|
||||||
// 如果验证成功,返回解析后的有用信息
|
return {
|
||||||
return {
|
groupId,
|
||||||
groupId,
|
macAddress: macAddress.replace(/_/g, ":"),
|
||||||
macAddress: macAddress.replace(/_/g, ':'),
|
uuid,
|
||||||
uuid,
|
userData,
|
||||||
userData
|
};
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateMqttConfig(groupId, macAddress, uuid, userData) {
|
function generateMqttConfig(groupId, macAddress, uuid, userData) {
|
||||||
const endpoint = process.env.MQTT_ENDPOINT;
|
const endpoint = process.env.MQTT_ENDPOINT;
|
||||||
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
|
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
|
||||||
if (!signatureKey) {
|
if (!signatureKey) {
|
||||||
console.warn('No signature key, skip generating MQTT config');
|
console.warn("No signature key, skip generating MQTT config");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const deviceIdNoColon = macAddress.replace(/:/g, '_');
|
|
||||||
const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`;
|
const deviceIdNoColon = macAddress.replace(/:/g, "_");
|
||||||
const username = Buffer.from(JSON.stringify(userData)).toString('base64');
|
const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`;
|
||||||
const password = generatePasswordSignature(clientId + '|' + username, signatureKey);
|
const username = Buffer.from(JSON.stringify(userData)).toString("base64");
|
||||||
return {
|
const password = generatePasswordSignature(
|
||||||
endpoint,
|
clientId + "|" + username,
|
||||||
port: 8883,
|
signatureKey
|
||||||
client_id: clientId,
|
);
|
||||||
username,
|
|
||||||
password,
|
return {
|
||||||
publish_topic: 'device-server',
|
endpoint,
|
||||||
subscribe_topic: 'null' // 旧版本固件不返回此字段会出错
|
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 = {
|
module.exports = {
|
||||||
generateMqttConfig,
|
generateMqttConfig,
|
||||||
validateMqttCredentials
|
validateMqttCredentials,
|
||||||
}
|
};
|
||||||
|
|
||||||
if (require.main === module) {
|
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' });
|
const config = generateMqttConfig(
|
||||||
console.log('config', config);
|
"GID_test",
|
||||||
const credentials = validateMqttCredentials(config.client_id, config.username, config.password);
|
"11:22:33:44:55:66",
|
||||||
console.log('credentials', credentials);
|
"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);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
```bash
|
||||||
node quick-test.js
|
node quick-test.js
|
||||||
```
|
```
|
||||||
|
|
||||||
这个脚本会:
|
This script will:
|
||||||
- ✅ 检查配置文件
|
|
||||||
- ✅ 测试MQTT服务器连接(端口1883)
|
|
||||||
- ✅ 测试WebSocket后端服务连接
|
|
||||||
- ✅ 显示测试结果和建议
|
|
||||||
|
|
||||||
### 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
|
```bash
|
||||||
node test-mqtt.js
|
node test-mqtt.js
|
||||||
```
|
```
|
||||||
|
|
||||||
这个脚本会:
|
This script will:
|
||||||
- 🔗 连接到MQTT服务器
|
|
||||||
- 🔐 使用配置的MAC地址进行认证
|
|
||||||
- 📝 订阅回复主题
|
|
||||||
- 📤 发送hello消息测试WebSocket转发
|
|
||||||
- 📥 等待并显示服务器响应
|
|
||||||
- 🧪 发送其他测试消息
|
|
||||||
|
|
||||||
## 手动测试步骤
|
- 🔗 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
|
```bash
|
||||||
node app.js
|
node app.js
|
||||||
```
|
```
|
||||||
|
|
||||||
应该看到类似输出:
|
You should see similar output:
|
||||||
|
|
||||||
```
|
```
|
||||||
MQTT 服务器启动在端口 1883
|
MQTT server started on port 1883
|
||||||
UDP 服务器启动在端口 1883
|
UDP server started on port 1883
|
||||||
连接数: 0, 活跃数: 0
|
Connections: 0, Active: 0
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 检查配置文件
|
### 2. Check Configuration File
|
||||||
|
|
||||||
确认 `config/mqtt.json` 配置正确:
|
Confirm that `config/mqtt.json` is configured correctly:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"production": {
|
"production": {
|
||||||
"chat_servers": [
|
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"]
|
||||||
"ws://192.168.68.66:8000/xiaozhi/v1/"
|
},
|
||||||
]
|
"development": {
|
||||||
},
|
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
|
||||||
"development": {
|
"mac_addresss": ["d8:43:ae:3e:4b:5a"]
|
||||||
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
|
},
|
||||||
"mac_addresss": ["d8:43:ae:3e:4b:5a"]
|
"debug": false
|
||||||
},
|
|
||||||
"debug": false
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 使用MQTT客户端工具测试
|
### 3. Test Using MQTT Client Tools
|
||||||
|
|
||||||
#### 使用mosquitto客户端:
|
#### Using mosquitto client:
|
||||||
|
|
||||||
|
**Connection test:**
|
||||||
|
|
||||||
**连接测试:**
|
|
||||||
```bash
|
```bash
|
||||||
mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello"
|
mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello"
|
||||||
```
|
```
|
||||||
|
|
||||||
**订阅测试:**
|
**Subscription test:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
mosquitto_sub -h localhost -p 1883 -t "devices/p2p/d8_43_ae_3e_4b_5a"
|
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. **连接设置:**
|
1. **Connection settings:**
|
||||||
- 服务器:localhost
|
|
||||||
- 端口:1883
|
- Server: localhost
|
||||||
- 客户端ID:`GID_test@@@d8_43_ae_3e_4b_5a`
|
- Port: 1883
|
||||||
- 用户名:test_user
|
- Client ID: `GID_test@@@d8_43_ae_3e_4b_5a`
|
||||||
- 密码:test_password
|
- Username: test_user
|
||||||
|
- Password: test_password
|
||||||
|
|
||||||
|
2. **Publish test message:**
|
||||||
|
|
||||||
|
- Topic: `test/topic`
|
||||||
|
- Message:
|
||||||
|
|
||||||
2. **发布测试消息:**
|
|
||||||
- 主题:`test/topic`
|
|
||||||
- 消息:
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"type": "hello",
|
"type": "hello",
|
||||||
"version": 3,
|
"version": 3,
|
||||||
"transport": "mqtt",
|
"transport": "mqtt",
|
||||||
"audio_params": {
|
"audio_params": {
|
||||||
"sample_rate": 16000,
|
"sample_rate": 16000,
|
||||||
"channels": 1,
|
"channels": 1,
|
||||||
"format": "opus"
|
"format": "opus"
|
||||||
},
|
},
|
||||||
"features": ["tts", "asr"]
|
"features": ["tts", "asr"]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
3. **订阅回复主题:**
|
3. **Subscribe to reply topic:**
|
||||||
- 主题:`devices/p2p/d8_43_ae_3e_4b_5a`
|
- Topic: `devices/p2p/d8_43_ae_3e_4b_5a`
|
||||||
|
|
||||||
## 测试结果判断
|
## Test Result Assessment
|
||||||
|
|
||||||
### ✅ 成功指标
|
### ✅ Success Indicators
|
||||||
|
|
||||||
|
1. **MQTT connection successful:**
|
||||||
|
|
||||||
1. **MQTT连接成功:**
|
|
||||||
```
|
```
|
||||||
✓ 成功连接到MQTT服务器 localhost:1883
|
✓ Successfully connected to MQTT server localhost:1883
|
||||||
✓ MQTT连接成功
|
✓ MQTT connection successful
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **WebSocket转发成功:**
|
2. **WebSocket forwarding successful:**
|
||||||
|
|
||||||
```
|
```
|
||||||
✓ WebSocket服务器连接成功
|
✓ WebSocket server connection successful
|
||||||
✓ 收到PUBLISH消息
|
✓ Received PUBLISH message
|
||||||
```
|
```
|
||||||
|
|
||||||
3. **服务器日志正常:**
|
3. **Server logs normal:**
|
||||||
```
|
```
|
||||||
客户端连接: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... }
|
Client connected: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... }
|
||||||
收到发布消息: { topic: 'test/topic', payload: '...', qos: 0 }
|
Received publish message: { topic: 'test/topic', payload: '...', qos: 0 }
|
||||||
```
|
```
|
||||||
|
|
||||||
### ❌ 常见问题
|
### ❌ Common Issues
|
||||||
|
|
||||||
1. **MQTT服务器连接失败:**
|
1. **MQTT server connection failed:**
|
||||||
```
|
|
||||||
✗ 连接错误: connect ECONNREFUSED 127.0.0.1:1883
|
|
||||||
```
|
|
||||||
**解决方案:** 确保运行 `node app.js` 启动MQTT网关
|
|
||||||
|
|
||||||
2. **WebSocket连接失败:**
|
|
||||||
```
|
```
|
||||||
✗ WebSocket服务器连接失败: connect ECONNREFUSED
|
✗ Connection error: connect ECONNREFUSED 127.0.0.1:1883
|
||||||
```
|
```
|
||||||
**解决方案:** 检查WebSocket后端服务是否运行,网络是否可达
|
|
||||||
|
|
||||||
3. **认证失败:**
|
**Solution:** Ensure running `node app.js` to start MQTT gateway
|
||||||
```
|
|
||||||
无效的 clientId: xxx
|
2. **WebSocket connection failed:**
|
||||||
```
|
|
||||||
**解决方案:** 检查客户端ID格式是否为 `GID_test@@@mac_address`
|
|
||||||
|
|
||||||
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
|
```json
|
||||||
{
|
{
|
||||||
"debug": true
|
"debug": true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
或设置环境变量:
|
Or set environment variable:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
DEBUG=mqtt-server node app.js
|
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 Client connected: { clientId: '...', username: '...', ... }
|
||||||
mqtt-server 收到发布消息: { topic: '...', payload: '...', qos: 0 }
|
mqtt-server Received publish message: { topic: '...', payload: '...', qos: 0 }
|
||||||
mqtt-server 发送消息到 devices/p2p/...: {...}
|
mqtt-server Sending message to devices/p2p/...: {...}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 网络连通性测试
|
### 3. Network Connectivity Test
|
||||||
|
|
||||||
|
**Test WebSocket server:**
|
||||||
|
|
||||||
**测试WebSocket服务器:**
|
|
||||||
```bash
|
```bash
|
||||||
curl -I http://192.168.68.66:8000/xiaozhi/v1/
|
curl -I http://192.168.68.66:8000/xiaozhi/v1/
|
||||||
```
|
```
|
||||||
|
|
||||||
**测试MQTT端口:**
|
**Test MQTT port:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
telnet localhost 1883
|
telnet localhost 1883
|
||||||
```
|
```
|
||||||
|
|
||||||
## 性能测试
|
## Performance Testing
|
||||||
|
|
||||||
### 并发连接测试
|
### Concurrent Connection Test
|
||||||
|
|
||||||
可以修改测试脚本创建多个并发连接:
|
You can modify the test script to create multiple concurrent connections:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 创建多个测试客户端
|
// Create multiple test clients
|
||||||
const clients = [];
|
const clients = [];
|
||||||
for (let i = 0; i < 10; i++) {
|
for (let i = 0; i < 10; i++) {
|
||||||
const client = new MQTTTestClient();
|
const client = new MQTTTestClient();
|
||||||
clients.push(client);
|
clients.push(client);
|
||||||
// 连接和测试...
|
// Connect and test...
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 消息吞吐量测试
|
### Message Throughput Test
|
||||||
|
|
||||||
发送大量消息测试转发性能:
|
Send large number of messages to test forwarding performance:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 发送100条消息
|
// Send 100 messages
|
||||||
for (let i = 0; i < 100; i++) {
|
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`)
|
- [ ] Is MQTT gateway service running (`node app.js`)
|
||||||
- [ ] 端口1883是否被占用
|
- [ ] Is port 1883 occupied
|
||||||
- [ ] 配置文件格式是否正确
|
- [ ] Is configuration file format correct
|
||||||
- [ ] WebSocket后端服务是否运行
|
- [ ] Is WebSocket backend service running
|
||||||
- [ ] 网络连接是否正常
|
- [ ] Is network connection normal
|
||||||
- [ ] MAC地址是否在配置的白名单中
|
- [ ] Is MAC address in configured whitelist
|
||||||
- [ ] 客户端ID格式是否正确
|
- [ ] Is client ID format correct
|
||||||
- [ ] 防火墙是否阻止连接
|
- [ ] Is firewall blocking connections
|
||||||
|
|
||||||
## 总结
|
## Summary
|
||||||
|
|
||||||
通过以上测试方法,你可以全面验证MQTT网关的转发功能是否配置成功。建议先运行快速测试,如果有问题再进行详细的手动测试和调试。
|
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.
|
||||||
|
|
|
||||||
|
|
@ -13,12 +13,11 @@ from core.utils.util import check_ffmpeg_installed
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
async def wait_for_exit() -> None:
|
async def wait_for_exit() -> None:
|
||||||
"""
|
"""
|
||||||
阻塞直到收到 Ctrl‑C / SIGTERM。
|
Block until receiving Ctrl-C / SIGTERM.
|
||||||
- Unix: 使用 add_signal_handler
|
- Unix: Use add_signal_handler
|
||||||
- Windows: 依赖 KeyboardInterrupt
|
- Windows: Rely on KeyboardInterrupt
|
||||||
"""
|
"""
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
stop_event = asyncio.Event()
|
stop_event = asyncio.Event()
|
||||||
|
|
@ -28,114 +27,116 @@ async def wait_for_exit() -> None:
|
||||||
loop.add_signal_handler(sig, stop_event.set)
|
loop.add_signal_handler(sig, stop_event.set)
|
||||||
await stop_event.wait()
|
await stop_event.wait()
|
||||||
else:
|
else:
|
||||||
# Windows:await一个永远pending的fut,
|
# Windows: await a forever pending future,
|
||||||
# 让 KeyboardInterrupt 冒泡到 asyncio.run,以此消除遗留普通线程导致进程退出阻塞的问题
|
# let KeyboardInterrupt bubble up to asyncio.run, to eliminate process exit blocking caused by legacy normal threads
|
||||||
try:
|
try:
|
||||||
await asyncio.Future()
|
await asyncio.Future()
|
||||||
except KeyboardInterrupt: # Ctrl‑C
|
except KeyboardInterrupt: # Ctrl-C
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
async def monitor_stdin():
|
async def monitor_stdin():
|
||||||
"""监控标准输入,消费回车键"""
|
"""Monitor standard input, consume enter key presses"""
|
||||||
while True:
|
while True:
|
||||||
await ainput() # 异步等待输入,消费回车
|
await ainput() # Asynchronously wait for input, consume enter
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
check_ffmpeg_installed()
|
check_ffmpeg_installed()
|
||||||
config = load_config()
|
config = load_config()
|
||||||
|
|
||||||
# 默认使用manager-api的secret作为auth_key
|
# Default to using manager-api's secret as auth_key
|
||||||
# 如果secret为空,则生成随机密钥
|
# If secret is empty, generate random key
|
||||||
# auth_key用于jwt认证,比如视觉分析接口的jwt认证
|
# auth_key is used for jwt authentication, such as jwt authentication for vision analysis interface
|
||||||
auth_key = config.get("manager-api", {}).get("secret", "")
|
auth_key = config.get("manager-api", {}).get("secret", "")
|
||||||
if not auth_key or len(auth_key) == 0 or "你" in auth_key:
|
if not auth_key or len(auth_key) == 0 or "你" in auth_key:
|
||||||
auth_key = str(uuid.uuid4().hex)
|
auth_key = str(uuid.uuid4().hex)
|
||||||
config["server"]["auth_key"] = auth_key
|
config["server"]["auth_key"] = auth_key
|
||||||
logger.bind(tag=TAG).info(f"Generated 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())
|
stdin_task = asyncio.create_task(monitor_stdin())
|
||||||
|
|
||||||
# 启动 WebSocket 服务器
|
# Start WebSocket server
|
||||||
ws_server = WebSocketServer(config)
|
ws_server = WebSocketServer(config)
|
||||||
ws_task = asyncio.create_task(ws_server.start())
|
ws_task = asyncio.create_task(ws_server.start())
|
||||||
# 启动 Simple http 服务器
|
|
||||||
|
# Start Simple http server
|
||||||
ota_server = SimpleHttpServer(config)
|
ota_server = SimpleHttpServer(config)
|
||||||
ota_task = asyncio.create_task(ota_server.start())
|
ota_task = asyncio.create_task(ota_server.start())
|
||||||
|
|
||||||
read_config_from_api = config.get("read_config_from_api", False)
|
read_config_from_api = config.get("read_config_from_api", False)
|
||||||
port = int(config["server"].get("http_port", 8003))
|
port = int(config["server"].get("http_port", 8003))
|
||||||
|
|
||||||
if not read_config_from_api:
|
if not read_config_from_api:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
"OTA接口是\t\thttp://{}:{}/xiaozhi/ota/",
|
"OTA interface is\t\thttp://{}:{}/xiaozhi/ota/",
|
||||||
get_local_ip(),
|
get_local_ip(),
|
||||||
port,
|
port,
|
||||||
)
|
)
|
||||||
|
|
||||||
mcp_endpoint = config.get("mcp_endpoint", None)
|
mcp_endpoint = config.get("mcp_endpoint", None)
|
||||||
if mcp_endpoint is not None and "你" not in mcp_endpoint:
|
if mcp_endpoint is not None and "你" not in mcp_endpoint:
|
||||||
# 校验MCP接入点格式
|
# Validate MCP endpoint format
|
||||||
if validate_mcp_endpoint(mcp_endpoint):
|
if validate_mcp_endpoint(mcp_endpoint):
|
||||||
logger.bind(tag=TAG).info("mcp接入点是\t{}", mcp_endpoint)
|
logger.bind(tag=TAG).info("MCP endpoint is\t{}", mcp_endpoint)
|
||||||
# 将mcp计入点地址转成调用点
|
# Convert mcp endpoint address to call endpoint
|
||||||
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
|
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
|
||||||
config["mcp_endpoint"] = mcp_endpoint
|
config["mcp_endpoint"] = mcp_endpoint
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error("mcp接入点不符合规范")
|
logger.bind(tag=TAG).error("MCP endpoint does not conform to specifications")
|
||||||
config["mcp_endpoint"] = "你的接入点 websocket地址"
|
config["mcp_endpoint"] = "Your endpoint websocket address"
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
"视觉分析接口是\thttp://{}:{}/mcp/vision/explain",
|
"Vision analysis interface is\thttp://{}:{}/mcp/vision/explain",
|
||||||
get_local_ip(),
|
get_local_ip(),
|
||||||
port,
|
port,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 获取WebSocket配置,使用安全的默认值
|
# Get WebSocket configuration, use safe default values
|
||||||
websocket_port = 8000
|
websocket_port = 8000
|
||||||
server_config = config.get("server", {})
|
server_config = config.get("server", {})
|
||||||
if isinstance(server_config, dict):
|
if isinstance(server_config, dict):
|
||||||
websocket_port = int(server_config.get("port", 8000))
|
websocket_port = int(server_config.get("port", 8000))
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
"Websocket地址是\tws://{}:{}/xiaozhi/v1/",
|
"Websocket address is\tws://{}:{}/xiaozhi/v1/",
|
||||||
get_local_ip(),
|
get_local_ip(),
|
||||||
websocket_port,
|
websocket_port,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
"=======上面的地址是websocket协议地址,请勿用浏览器访问======="
|
"=======The above address is websocket protocol address, please do not access with browser======="
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
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(
|
logger.bind(tag=TAG).info(
|
||||||
"=============================================================\n"
|
"=============================================================\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await wait_for_exit() # 阻塞直到收到退出信号
|
await wait_for_exit() # Block until receiving exit signal
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
print("任务被取消,清理资源中...")
|
print("Task was cancelled, cleaning up resources...")
|
||||||
finally:
|
finally:
|
||||||
# 取消所有任务(关键修复点)
|
# Cancel all tasks (critical fix point)
|
||||||
stdin_task.cancel()
|
stdin_task.cancel()
|
||||||
ws_task.cancel()
|
ws_task.cancel()
|
||||||
if ota_task:
|
if ota_task:
|
||||||
ota_task.cancel()
|
ota_task.cancel()
|
||||||
|
|
||||||
# 等待任务终止(必须加超时)
|
# Wait for task termination (must add timeout)
|
||||||
await asyncio.wait(
|
await asyncio.wait(
|
||||||
[stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
|
[stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
|
||||||
timeout=3.0,
|
timeout=3.0,
|
||||||
return_when=asyncio.ALL_COMPLETED,
|
return_when=asyncio.ALL_COMPLETED,
|
||||||
)
|
)
|
||||||
print("服务器已关闭,程序退出。")
|
|
||||||
|
|
||||||
|
print("Server has been closed, program exiting.")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
try:
|
try:
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("手动中断,程序终止。")
|
print("Manual interruption, program terminated.")
|
||||||
|
|
|
||||||
|
|
@ -19,9 +19,9 @@ import opuslib
|
||||||
|
|
||||||
# --- Configuration ---
|
# --- 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
|
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
|
MQTT_BROKER_PORT = 1883
|
||||||
# DEVICE_MAC is now dynamically generated for uniqueness
|
# DEVICE_MAC is now dynamically generated for uniqueness
|
||||||
PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback
|
PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback
|
||||||
|
|
|
||||||
|
|
@ -3,23 +3,20 @@ import yaml
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from config.manage_api_client import init_service, get_server_config, get_agent_models
|
from config.manage_api_client import init_service, get_server_config, get_agent_models
|
||||||
|
|
||||||
|
|
||||||
def get_project_dir():
|
def get_project_dir():
|
||||||
"""获取项目根目录"""
|
"""Get project root directory"""
|
||||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
|
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
|
||||||
|
|
||||||
|
|
||||||
def read_config(config_path):
|
def read_config(config_path):
|
||||||
with open(config_path, "r", encoding="utf-8") as file:
|
with open(config_path, "r", encoding="utf-8") as file:
|
||||||
config = yaml.safe_load(file)
|
config = yaml.safe_load(file)
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
def load_config():
|
def load_config():
|
||||||
"""加载配置文件"""
|
"""Load configuration file"""
|
||||||
from core.utils.cache.manager import cache_manager, CacheType
|
from core.utils.cache.manager import cache_manager, CacheType
|
||||||
|
|
||||||
# 检查缓存
|
# Check cache
|
||||||
cached_config = cache_manager.get(CacheType.CONFIG, "main_config")
|
cached_config = cache_manager.get(CacheType.CONFIG, "main_config")
|
||||||
if cached_config is not None:
|
if cached_config is not None:
|
||||||
return cached_config
|
return cached_config
|
||||||
|
|
@ -27,29 +24,30 @@ def load_config():
|
||||||
default_config_path = get_project_dir() + "config.yaml"
|
default_config_path = get_project_dir() + "config.yaml"
|
||||||
custom_config_path = get_project_dir() + "data/.config.yaml"
|
custom_config_path = get_project_dir() + "data/.config.yaml"
|
||||||
|
|
||||||
# 加载默认配置
|
# Load default configuration
|
||||||
default_config = read_config(default_config_path)
|
default_config = read_config(default_config_path)
|
||||||
custom_config = read_config(custom_config_path)
|
custom_config = read_config(custom_config_path)
|
||||||
|
|
||||||
if custom_config.get("manager-api", {}).get("url"):
|
if custom_config.get("manager-api", {}).get("url"):
|
||||||
config = get_config_from_api(custom_config)
|
config = get_config_from_api(custom_config)
|
||||||
else:
|
else:
|
||||||
# 合并配置
|
# Merge configurations
|
||||||
config = merge_configs(default_config, custom_config)
|
config = merge_configs(default_config, custom_config)
|
||||||
# 初始化目录
|
|
||||||
|
# Initialize directories
|
||||||
ensure_directories(config)
|
ensure_directories(config)
|
||||||
|
|
||||||
# 缓存配置
|
# Cache configuration
|
||||||
cache_manager.set(CacheType.CONFIG, "main_config", config)
|
cache_manager.set(CacheType.CONFIG, "main_config", config)
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
def get_config_from_api(config):
|
def get_config_from_api(config):
|
||||||
"""从Java API获取配置"""
|
"""Get configuration from Java API"""
|
||||||
# 初始化API客户端
|
# Initialize API client
|
||||||
init_service(config)
|
init_service(config)
|
||||||
|
|
||||||
# 获取服务器配置
|
# Get server configuration
|
||||||
config_data = get_server_config()
|
config_data = get_server_config()
|
||||||
if config_data is None:
|
if config_data is None:
|
||||||
raise Exception("Failed to fetch server config from API")
|
raise Exception("Failed to fetch server config from API")
|
||||||
|
|
@ -59,7 +57,8 @@ def get_config_from_api(config):
|
||||||
"url": config["manager-api"].get("url", ""),
|
"url": config["manager-api"].get("url", ""),
|
||||||
"secret": config["manager-api"].get("secret", ""),
|
"secret": config["manager-api"].get("secret", ""),
|
||||||
}
|
}
|
||||||
# server的配置以本地为准
|
|
||||||
|
# Use local server configuration as priority
|
||||||
if config.get("server"):
|
if config.get("server"):
|
||||||
config_data["server"] = {
|
config_data["server"] = {
|
||||||
"ip": config["server"].get("ip", ""),
|
"ip": config["server"].get("ip", ""),
|
||||||
|
|
@ -68,23 +67,23 @@ def get_config_from_api(config):
|
||||||
"vision_explain": config["server"].get("vision_explain", ""),
|
"vision_explain": config["server"].get("vision_explain", ""),
|
||||||
"auth_key": config["server"].get("auth_key", ""),
|
"auth_key": config["server"].get("auth_key", ""),
|
||||||
}
|
}
|
||||||
|
|
||||||
return config_data
|
return config_data
|
||||||
|
|
||||||
|
|
||||||
def get_private_config_from_api(config, device_id, client_id):
|
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"])
|
return get_agent_models(device_id, client_id, config["selected_module"])
|
||||||
|
|
||||||
|
|
||||||
def ensure_directories(config):
|
def ensure_directories(config):
|
||||||
"""确保所有配置路径存在"""
|
"""Ensure all configuration paths exist"""
|
||||||
dirs_to_create = set()
|
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")
|
log_dir = config.get("log", {}).get("log_dir", "tmp")
|
||||||
dirs_to_create.add(os.path.join(project_dir, log_dir))
|
dirs_to_create.add(os.path.join(project_dir, log_dir))
|
||||||
|
|
||||||
# ASR/TTS模块输出目录
|
# ASR/TTS module output directories
|
||||||
for module in ["ASR", "TTS"]:
|
for module in ["ASR", "TTS"]:
|
||||||
if config.get(module) is None:
|
if config.get(module) is None:
|
||||||
continue
|
continue
|
||||||
|
|
@ -93,40 +92,40 @@ def ensure_directories(config):
|
||||||
if output_dir:
|
if output_dir:
|
||||||
dirs_to_create.add(output_dir)
|
dirs_to_create.add(output_dir)
|
||||||
|
|
||||||
# 根据selected_module创建模型目录
|
# Create model directories based on selected_module
|
||||||
selected_modules = config.get("selected_module", {})
|
selected_modules = config.get("selected_module", {})
|
||||||
for module_type in ["ASR", "LLM", "TTS"]:
|
for module_type in ["ASR", "LLM", "TTS"]:
|
||||||
selected_provider = selected_modules.get(module_type)
|
selected_provider = selected_modules.get(module_type)
|
||||||
if not selected_provider:
|
if not selected_provider:
|
||||||
continue
|
continue
|
||||||
if config.get(module) is None:
|
if config.get(module_type) is None:
|
||||||
continue
|
continue
|
||||||
if config.get(selected_provider) is None:
|
if config.get(selected_provider) is None:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
provider_config = config.get(module_type, {}).get(selected_provider, {})
|
provider_config = config.get(module_type, {}).get(selected_provider, {})
|
||||||
output_dir = provider_config.get("output_dir")
|
output_dir = provider_config.get("output_dir")
|
||||||
if output_dir:
|
if output_dir:
|
||||||
full_model_dir = os.path.join(project_dir, output_dir)
|
full_model_dir = os.path.join(project_dir, output_dir)
|
||||||
dirs_to_create.add(full_model_dir)
|
dirs_to_create.add(full_model_dir)
|
||||||
|
|
||||||
# 统一创建目录(保留原data目录创建)
|
# Create directories uniformly (keep original data directory creation)
|
||||||
for dir_path in dirs_to_create:
|
for dir_path in dirs_to_create:
|
||||||
try:
|
try:
|
||||||
os.makedirs(dir_path, exist_ok=True)
|
os.makedirs(dir_path, exist_ok=True)
|
||||||
except PermissionError:
|
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):
|
def merge_configs(default_config, custom_config):
|
||||||
"""
|
"""
|
||||||
递归合并配置,custom_config优先级更高
|
Recursively merge configurations, custom_config has higher priority
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
default_config: 默认配置
|
default_config: Default configuration
|
||||||
custom_config: 用户自定义配置
|
custom_config: User custom configuration
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
合并后的配置
|
Merged configuration
|
||||||
"""
|
"""
|
||||||
if not isinstance(default_config, Mapping) or not isinstance(
|
if not isinstance(default_config, Mapping) or not isinstance(
|
||||||
custom_config, Mapping
|
custom_config, Mapping
|
||||||
|
|
@ -134,7 +133,6 @@ def merge_configs(default_config, custom_config):
|
||||||
return custom_config
|
return custom_config
|
||||||
|
|
||||||
merged = dict(default_config)
|
merged = dict(default_config)
|
||||||
|
|
||||||
for key, value in custom_config.items():
|
for key, value in custom_config.items():
|
||||||
if (
|
if (
|
||||||
key in merged
|
key in merged
|
||||||
|
|
|
||||||
|
|
@ -8,22 +8,23 @@ from datetime import datetime
|
||||||
SERVER_VERSION = "0.7.4"
|
SERVER_VERSION = "0.7.4"
|
||||||
_logger_initialized = False
|
_logger_initialized = False
|
||||||
|
|
||||||
|
|
||||||
def get_module_abbreviation(module_name, module_dict):
|
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, "")
|
module_value = module_dict.get(module_name, "")
|
||||||
if not module_value:
|
if not module_value:
|
||||||
return "00"
|
return "00"
|
||||||
|
|
||||||
if "_" in module_value:
|
if "_" in module_value:
|
||||||
parts = module_value.split("_")
|
parts = module_value.split("_")
|
||||||
return parts[-1][:2] if parts[-1] else "00"
|
return parts[-1][:2] if parts[-1] else "00"
|
||||||
|
|
||||||
return module_value[:2]
|
return module_value[:2]
|
||||||
|
|
||||||
|
|
||||||
def build_module_string(selected_module):
|
def build_module_string(selected_module):
|
||||||
"""构建模块字符串"""
|
"""Build module string"""
|
||||||
return (
|
return (
|
||||||
get_module_abbreviation("VAD", selected_module)
|
get_module_abbreviation("VAD", selected_module)
|
||||||
+ get_module_abbreviation("ASR", selected_module)
|
+ get_module_abbreviation("ASR", selected_module)
|
||||||
|
|
@ -34,40 +35,50 @@ def build_module_string(selected_module):
|
||||||
+ get_module_abbreviation("VLLM", selected_module)
|
+ get_module_abbreviation("VLLM", selected_module)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def formatter(record):
|
def formatter(record):
|
||||||
"""为没有 tag 的日志添加默认值,并处理动态模块字符串"""
|
"""Add default values for logs without tag, and handle dynamic module string"""
|
||||||
record["extra"].setdefault("tag", record["name"])
|
record["extra"].setdefault("tag", record["name"])
|
||||||
# 如果没有设置 selected_module,使用默认值
|
# If selected_module is not set, use default value
|
||||||
record["extra"].setdefault("selected_module", "00000000000000")
|
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"]
|
record["selected_module"] = record["extra"]["selected_module"]
|
||||||
return record["message"]
|
return record["message"]
|
||||||
|
|
||||||
|
def update_module_string(selected_module_str):
|
||||||
|
"""Update module string"""
|
||||||
|
logger.configure(
|
||||||
|
extra={
|
||||||
|
"selected_module": selected_module_str,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
def setup_logging():
|
def setup_logging():
|
||||||
check_config_file()
|
check_config_file()
|
||||||
"""从配置文件中读取日志配置,并设置日志输出格式和级别"""
|
"""Read log configuration from config file and set log output format and level"""
|
||||||
config = load_config()
|
config = load_config()
|
||||||
log_config = config["log"]
|
log_config = config["log"]
|
||||||
|
|
||||||
global _logger_initialized
|
global _logger_initialized
|
||||||
|
|
||||||
# 第一次初始化时配置日志
|
# Configure logging on first initialization
|
||||||
if not _logger_initialized:
|
if not _logger_initialized:
|
||||||
# 使用默认的模块字符串进行初始化
|
# Initialize with default module string
|
||||||
logger.configure(
|
logger.configure(
|
||||||
extra={
|
extra={
|
||||||
"selected_module": log_config.get("selected_module", "00000000000000"),
|
"selected_module": log_config.get("selected_module", "00000000000000"),
|
||||||
})
|
}
|
||||||
|
)
|
||||||
|
|
||||||
log_format = log_config.get(
|
log_format = log_config.get(
|
||||||
"log_format",
|
"log_format",
|
||||||
"<green>{time:YYMMDD HH:mm:ss}</green>[{version}_{extra[selected_module]}][<light-blue>{extra[tag]}</light-blue>]-<level>{level}</level>-<light-green>{message}</light-green>",
|
"{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][{extra[tag]}]-{level}-{message}",
|
||||||
)
|
)
|
||||||
|
|
||||||
log_format_file = log_config.get(
|
log_format_file = log_config.get(
|
||||||
"log_format_file",
|
"log_format_file",
|
||||||
"{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}",
|
"{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}",
|
||||||
)
|
)
|
||||||
|
|
||||||
log_format = log_format.replace("{version}", SERVER_VERSION)
|
log_format = log_format.replace("{version}", SERVER_VERSION)
|
||||||
log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
|
log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
|
||||||
|
|
||||||
|
|
@ -79,35 +90,35 @@ def setup_logging():
|
||||||
os.makedirs(log_dir, exist_ok=True)
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
os.makedirs(data_dir, exist_ok=True)
|
os.makedirs(data_dir, exist_ok=True)
|
||||||
|
|
||||||
# 配置日志输出
|
# Configure log output
|
||||||
logger.remove()
|
logger.remove()
|
||||||
|
|
||||||
# 输出到控制台
|
# Output to console
|
||||||
logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
|
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)
|
log_file_path = os.path.join(log_dir, log_file)
|
||||||
|
|
||||||
# 添加日志处理器
|
# Add log handler
|
||||||
logger.add(
|
logger.add(
|
||||||
log_file_path,
|
log_file_path,
|
||||||
format=log_format_file,
|
format=log_format_file,
|
||||||
level=log_level,
|
level=log_level,
|
||||||
filter=formatter,
|
filter=formatter,
|
||||||
rotation="10 MB", # 每个文件最大10MB
|
rotation="10 MB", # Each file maximum 10MB
|
||||||
retention="30 days", # 保留30天
|
retention="30 days", # Keep for 30 days
|
||||||
compression=None,
|
compression=None,
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
enqueue=True, # 异步安全
|
enqueue=True, # Async safe
|
||||||
backtrace=True,
|
backtrace=True,
|
||||||
diagnose=True,
|
diagnose=True,
|
||||||
)
|
)
|
||||||
_logger_initialized = True # 标记为已初始化
|
|
||||||
|
_logger_initialized = True # Mark as initialized
|
||||||
|
|
||||||
return logger
|
return logger
|
||||||
|
|
||||||
|
|
||||||
def create_connection_logger(selected_module_str):
|
def create_connection_logger(selected_module_str):
|
||||||
"""为连接创建独立的日志器,绑定特定的模块字符串"""
|
"""Create independent logger for connection, bind specific module string"""
|
||||||
return logger.bind(selected_module=selected_module_str)
|
return logger.bind(selected_module=selected_module_str)
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,8 @@ class DeviceNotFoundException(Exception):
|
||||||
class DeviceBindException(Exception):
|
class DeviceBindException(Exception):
|
||||||
def __init__(self, bind_code):
|
def __init__(self, bind_code):
|
||||||
self.bind_code = bind_code
|
self.bind_code = bind_code
|
||||||
super().__init__(f"设备绑定异常,绑定码: {bind_code}")
|
super().__init__(
|
||||||
|
f"Device binding exception, binding code: {bind_code}")
|
||||||
|
|
||||||
|
|
||||||
class ManageApiClient:
|
class ManageApiClient:
|
||||||
|
|
@ -24,7 +25,7 @@ class ManageApiClient:
|
||||||
_secret = None
|
_secret = None
|
||||||
|
|
||||||
def __new__(cls, config):
|
def __new__(cls, config):
|
||||||
"""单例模式确保全局唯一实例,并支持传入配置参数"""
|
"""Singleton pattern to ensure a globally unique instance, supporting configuration parameters"""
|
||||||
if cls._instance is None:
|
if cls._instance is None:
|
||||||
cls._instance = super().__new__(cls)
|
cls._instance = super().__new__(cls)
|
||||||
cls._init_client(config)
|
cls._init_client(config)
|
||||||
|
|
@ -32,23 +33,25 @@ class ManageApiClient:
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _init_client(cls, config):
|
def _init_client(cls, config):
|
||||||
"""初始化持久化连接池"""
|
"""Initialize persistent connection pool"""
|
||||||
cls.config = config.get("manager-api")
|
cls.config = config.get("manager-api")
|
||||||
|
|
||||||
if not cls.config:
|
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"):
|
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"):
|
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._secret = cls.config.get("secret")
|
||||||
cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数
|
cls.max_retries = cls.config.get(
|
||||||
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒)
|
"max_retries", 6) # Maximum retry count
|
||||||
# NOTE(goody): 2025/4/16 http相关资源统一管理,后续可以增加线程池或者超时
|
# Initial retry delay (seconds)
|
||||||
# 后续也可以统一配置apiToken之类的走通用的Auth
|
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(
|
cls._client = httpx.Client(
|
||||||
base_url=cls.config.get("url"),
|
base_url=cls.config.get("url"),
|
||||||
headers={
|
headers={
|
||||||
|
|
@ -56,39 +59,42 @@ class ManageApiClient:
|
||||||
"Accept": "application/json",
|
"Accept": "application/json",
|
||||||
"Authorization": "Bearer " + cls._secret,
|
"Authorization": "Bearer " + cls._secret,
|
||||||
},
|
},
|
||||||
timeout=cls.config.get("timeout", 30), # 默认超时时间30秒
|
# Default timeout 30 seconds
|
||||||
|
timeout=cls.config.get("timeout", 30),
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _request(cls, method: str, endpoint: str, **kwargs) -> Dict:
|
def _request(cls, method: str, endpoint: str, **kwargs) -> Dict:
|
||||||
"""发送单次HTTP请求并处理响应"""
|
"""Send a single HTTP request and handle response"""
|
||||||
endpoint = endpoint.lstrip("/")
|
endpoint = endpoint.lstrip("/")
|
||||||
response = cls._client.request(method, endpoint, **kwargs)
|
response = cls._client.request(method, endpoint, **kwargs)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
result = response.json()
|
result = response.json()
|
||||||
|
|
||||||
# 处理API返回的业务错误
|
# Handle business errors returned by API
|
||||||
if result.get("code") == 10041:
|
if result.get("code") == 10041:
|
||||||
raise DeviceNotFoundException(result.get("msg"))
|
raise DeviceNotFoundException(result.get("msg"))
|
||||||
elif result.get("code") == 10042:
|
elif result.get("code") == 10042:
|
||||||
raise DeviceBindException(result.get("msg"))
|
raise DeviceBindException(result.get("msg"))
|
||||||
elif result.get("code") != 0:
|
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
|
return result.get("data") if result.get("code") == 0 else None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _should_retry(cls, exception: Exception) -> bool:
|
def _should_retry(cls, exception: Exception) -> bool:
|
||||||
"""判断异常是否应该重试"""
|
"""Determine if exception should be retried"""
|
||||||
# 网络连接相关错误
|
# Network connection related errors
|
||||||
if isinstance(
|
if isinstance(
|
||||||
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError)
|
exception, (httpx.ConnectError,
|
||||||
|
httpx.TimeoutException, httpx.NetworkError)
|
||||||
):
|
):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# HTTP状态码错误
|
# HTTP status code errors
|
||||||
if isinstance(exception, httpx.HTTPStatusError):
|
if isinstance(exception, httpx.HTTPStatusError):
|
||||||
status_code = exception.response.status_code
|
status_code = exception.response.status_code
|
||||||
return status_code in [408, 429, 500, 502, 503, 504]
|
return status_code in [408, 429, 500, 502, 503, 504]
|
||||||
|
|
@ -97,43 +103,43 @@ class ManageApiClient:
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
|
def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
|
||||||
"""带重试机制的请求执行器"""
|
"""Request executor with retry mechanism"""
|
||||||
retry_count = 0
|
retry_count = 0
|
||||||
|
|
||||||
while retry_count <= cls.max_retries:
|
while retry_count <= cls.max_retries:
|
||||||
try:
|
try:
|
||||||
# 执行请求
|
# Execute request
|
||||||
return cls._request(method, endpoint, **kwargs)
|
return cls._request(method, endpoint, **kwargs)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 判断是否应该重试
|
# Determine if should retry
|
||||||
if retry_count < cls.max_retries and cls._should_retry(e):
|
if retry_count < cls.max_retries and cls._should_retry(e):
|
||||||
retry_count += 1
|
retry_count += 1
|
||||||
print(
|
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)
|
time.sleep(cls.retry_delay)
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
# 不重试,直接抛出异常
|
# Don't retry, throw exception directly
|
||||||
raise
|
raise
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def safe_close(cls):
|
def safe_close(cls):
|
||||||
"""安全关闭连接池"""
|
"""Safely close connection pool"""
|
||||||
if cls._client:
|
if cls._client:
|
||||||
cls._client.close()
|
cls._client.close()
|
||||||
cls._instance = None
|
cls._instance = None
|
||||||
|
|
||||||
|
|
||||||
def get_server_config() -> Optional[Dict]:
|
def get_server_config() -> Optional[Dict]:
|
||||||
"""获取服务器基础配置"""
|
"""Get server basic configuration"""
|
||||||
return ManageApiClient._instance._execute_request("POST", "/config/server-base")
|
return ManageApiClient._instance._execute_request("POST", "/config/server-base")
|
||||||
|
|
||||||
|
|
||||||
def get_agent_models(
|
def get_agent_models(
|
||||||
mac_address: str, client_id: str, selected_module: Dict
|
mac_address: str, client_id: str, selected_module: Dict
|
||||||
) -> Optional[Dict]:
|
) -> Optional[Dict]:
|
||||||
"""获取代理模型配置"""
|
"""Get agent model configuration"""
|
||||||
return ManageApiClient._instance._execute_request(
|
return ManageApiClient._instance._execute_request(
|
||||||
"POST",
|
"POST",
|
||||||
"/config/agent-models",
|
"/config/agent-models",
|
||||||
|
|
@ -155,14 +161,14 @@ def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[Dict]:
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"存储短期记忆到服务器失败: {e}")
|
print(f"Failed to save short-term memory to server: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def report(
|
def report(
|
||||||
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
|
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
|
||||||
) -> Optional[Dict]:
|
) -> Optional[Dict]:
|
||||||
"""带熔断的业务方法示例"""
|
"""Business method example with circuit breaker"""
|
||||||
if not content or not ManageApiClient._instance:
|
if not content or not ManageApiClient._instance:
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
|
|
@ -181,7 +187,7 @@ def report(
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"TTS上报失败: {e}")
|
print(f"TTS reporting failed: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,33 +1,34 @@
|
||||||
import os
|
import os
|
||||||
from config.config_loader import read_config, get_project_dir, load_config
|
from config.config_loader import read_config, get_project_dir, load_config
|
||||||
|
|
||||||
|
|
||||||
default_config_file = "config.yaml"
|
default_config_file = "config.yaml"
|
||||||
config_file_valid = False
|
config_file_valid = False
|
||||||
|
|
||||||
|
|
||||||
def check_config_file():
|
def check_config_file():
|
||||||
global config_file_valid
|
global config_file_valid
|
||||||
if config_file_valid:
|
if config_file_valid:
|
||||||
return
|
return
|
||||||
|
|
||||||
"""
|
"""
|
||||||
简化的配置检查,仅提示用户配置文件的使用情况
|
Simplified configuration check, only prompt user about config file usage
|
||||||
"""
|
"""
|
||||||
custom_config_file = get_project_dir() + "data/." + default_config_file
|
custom_config_file = get_project_dir() + "data/." + default_config_file
|
||||||
|
|
||||||
if not os.path.exists(custom_config_file):
|
if not os.path.exists(custom_config_file):
|
||||||
raise FileNotFoundError(
|
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()
|
config = load_config()
|
||||||
if config.get("read_config_from_api", False):
|
if config.get("read_config_from_api", False):
|
||||||
print("从API读取配置")
|
print("Reading configuration from API")
|
||||||
old_config_origin = read_config(custom_config_file)
|
old_config_origin = read_config(custom_config_file)
|
||||||
if old_config_origin.get("selected_module") is not None:
|
if old_config_origin.get("selected_module") is not None:
|
||||||
error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n"
|
error_msg = "Your configuration file seems to contain both smart control panel configuration and local configuration:\n"
|
||||||
error_msg += "\n建议您:\n"
|
error_msg += "\nRecommendations:\n"
|
||||||
error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\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、按教程配置好接口地址和密钥\n"
|
error_msg += "2. Configure the API address and secret key according to tutorial\n"
|
||||||
raise ValueError(error_msg)
|
raise ValueError(error_msg)
|
||||||
|
|
||||||
config_file_valid = True
|
config_file_valid = True
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ class BaseHandler:
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
|
|
||||||
def _add_cors_headers(self, response):
|
def _add_cors_headers(self, response):
|
||||||
"""添加CORS头信息"""
|
"""Add CORS header information"""
|
||||||
response.headers["Access-Control-Allow-Headers"] = (
|
response.headers["Access-Control-Allow-Headers"] = (
|
||||||
"client-id, content-type, device-id"
|
"client-id, content-type, device-id"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -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 json
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
@ -150,17 +23,18 @@ class OTAHandler(BaseHandler):
|
||||||
def __init__(self, config: dict):
|
def __init__(self, config: dict):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
# Load MQTT signature key from environment or 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:
|
def _get_websocket_url(self, local_ip: str, port: int) -> str:
|
||||||
"""获取websocket地址
|
"""Get websocket address
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
local_ip: 本地IP地址
|
local_ip: Local IP address
|
||||||
port: 端口号
|
port: Port number
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: websocket地址
|
str: websocket address
|
||||||
"""
|
"""
|
||||||
server_config = self.config["server"]
|
server_config = self.config["server"]
|
||||||
websocket_config = server_config.get("websocket", "")
|
websocket_config = server_config.get("websocket", "")
|
||||||
|
|
@ -171,14 +45,14 @@ class OTAHandler(BaseHandler):
|
||||||
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
|
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
|
||||||
|
|
||||||
def _generate_mqtt_credentials(self, device_id: str, client_ip: str) -> dict:
|
def _generate_mqtt_credentials(self, device_id: str, client_ip: str) -> dict:
|
||||||
"""生成MQTT凭据
|
"""Generate MQTT credentials
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
device_id: 设备ID (MAC地址格式)
|
device_id: Device ID (MAC address format)
|
||||||
client_ip: 客户端IP地址
|
client_ip: Client IP address
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict: MQTT凭据信息
|
dict: MQTT credential information
|
||||||
"""
|
"""
|
||||||
# Convert MAC address format (remove colons, use underscores)
|
# Convert MAC address format (remove colons, use underscores)
|
||||||
mac_address = device_id.replace(":", "_")
|
mac_address = device_id.replace(":", "_")
|
||||||
|
|
@ -197,7 +71,8 @@ class OTAHandler(BaseHandler):
|
||||||
# Generate password signature
|
# Generate password signature
|
||||||
content = f"{client_id}|{username}"
|
content = f"{client_id}|{username}"
|
||||||
password = base64.b64encode(
|
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()
|
).decode()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
@ -207,25 +82,29 @@ class OTAHandler(BaseHandler):
|
||||||
}
|
}
|
||||||
|
|
||||||
async def handle_post(self, request):
|
async def handle_post(self, request):
|
||||||
"""处理 OTA POST 请求"""
|
"""Handle OTA POST request"""
|
||||||
try:
|
try:
|
||||||
data = await request.text()
|
data = await request.text()
|
||||||
self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}")
|
self.logger.bind(tag=TAG).debug(
|
||||||
self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}")
|
f"OTA request method: {request.method}")
|
||||||
self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}")
|
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", "")
|
device_id = request.headers.get("device-id", "")
|
||||||
if 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:
|
else:
|
||||||
raise Exception("OTA请求设备ID为空")
|
raise Exception("OTA request device ID is empty")
|
||||||
|
|
||||||
data_json = json.loads(data)
|
data_json = json.loads(data)
|
||||||
|
|
||||||
# Get client IP address
|
# Get client IP address
|
||||||
client_ip = request.remote
|
client_ip = request.remote
|
||||||
if request.headers.get('X-Forwarded-For'):
|
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'):
|
elif request.headers.get('X-Real-IP'):
|
||||||
client_ip = request.headers.get('X-Real-IP')
|
client_ip = request.headers.get('X-Real-IP')
|
||||||
|
|
||||||
|
|
@ -243,7 +122,8 @@ class OTAHandler(BaseHandler):
|
||||||
# Generate MQTT credentials if MQTT is enabled
|
# Generate MQTT credentials if MQTT is enabled
|
||||||
mqtt_credentials = None
|
mqtt_credentials = None
|
||||||
if mqtt_enabled:
|
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 = {
|
return_json = {
|
||||||
"server_time": {
|
"server_time": {
|
||||||
|
|
@ -296,7 +176,7 @@ class OTAHandler(BaseHandler):
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
)
|
)
|
||||||
except Exception as e:
|
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."}
|
return_json = {"success": False, "message": "request error."}
|
||||||
response = web.Response(
|
response = web.Response(
|
||||||
text=json.dumps(return_json, separators=(",", ":")),
|
text=json.dumps(return_json, separators=(",", ":")),
|
||||||
|
|
@ -307,7 +187,7 @@ class OTAHandler(BaseHandler):
|
||||||
return response
|
return response
|
||||||
|
|
||||||
async def handle_get(self, request):
|
async def handle_get(self, request):
|
||||||
"""处理 OTA GET 请求"""
|
"""Handle OTA GET request"""
|
||||||
try:
|
try:
|
||||||
server_config = self.config["server"]
|
server_config = self.config["server"]
|
||||||
local_ip = get_local_ip()
|
local_ip = get_local_ip()
|
||||||
|
|
@ -322,20 +202,22 @@ class OTAHandler(BaseHandler):
|
||||||
mqtt_port = mqtt_config.get("port", 1883)
|
mqtt_port = mqtt_config.get("port", 1883)
|
||||||
udp_port = mqtt_config.get("udp_port", 8884)
|
udp_port = mqtt_config.get("udp_port", 8884)
|
||||||
|
|
||||||
message = f"""OTA接口运行正常
|
message = f"""OTA interface running normally
|
||||||
服务器配置信息:
|
Server configuration information:
|
||||||
- WebSocket地址: {websocket_url}
|
- WebSocket address: {websocket_url}
|
||||||
- HTTP端口: {http_port}
|
- HTTP port: {http_port}
|
||||||
- WebSocket端口: {port}
|
- WebSocket port: {port}
|
||||||
- MQTT网关: {'启用' if mqtt_enabled else '禁用'}
|
- MQTT gateway: {'Enabled' if mqtt_enabled else 'Disabled'}
|
||||||
- MQTT代理: {mqtt_broker}:{mqtt_port}
|
- MQTT broker: {mqtt_broker}:{mqtt_port}
|
||||||
- UDP端口: {udp_port}
|
- UDP port: {udp_port}
|
||||||
- 服务器IP: {local_ip}"""
|
- Server IP: {local_ip}"""
|
||||||
|
|
||||||
response = web.Response(text=message, content_type="text/plain; charset=utf-8")
|
response = web.Response(
|
||||||
|
text=message, content_type="text/plain; charset=utf-8")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}")
|
self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}")
|
||||||
response = web.Response(text="OTA接口异常", content_type="text/plain")
|
response = web.Response(
|
||||||
|
text="OTA interface exception", content_type="text/plain")
|
||||||
finally:
|
finally:
|
||||||
self._add_cors_headers(response)
|
self._add_cors_headers(response)
|
||||||
return response
|
return response
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ from plugins_func.register import Action
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
# 设置最大文件大小为5MB
|
# Set maximum file size to 5MB
|
||||||
MAX_FILE_SIZE = 5 * 1024 * 1024
|
MAX_FILE_SIZE = 5 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -20,81 +20,83 @@ class VisionHandler:
|
||||||
def __init__(self, config: dict):
|
def __init__(self, config: dict):
|
||||||
self.config = config
|
self.config = config
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
# 初始化认证工具
|
# Initialize authentication tool
|
||||||
self.auth = AuthToken(config["server"]["auth_key"])
|
self.auth = AuthToken(config["server"]["auth_key"])
|
||||||
|
|
||||||
def _create_error_response(self, message: str) -> dict:
|
def _create_error_response(self, message: str) -> dict:
|
||||||
"""创建统一的错误响应格式"""
|
"""Create unified error response format"""
|
||||||
return {"success": False, "message": message}
|
return {"success": False, "message": message}
|
||||||
|
|
||||||
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
|
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
|
||||||
"""验证认证token"""
|
"""Verify authentication token"""
|
||||||
auth_header = request.headers.get("Authorization", "")
|
auth_header = request.headers.get("Authorization", "")
|
||||||
if not auth_header.startswith("Bearer "):
|
if not auth_header.startswith("Bearer "):
|
||||||
return False, None
|
return False, None
|
||||||
|
|
||||||
token = auth_header[7:] # 移除"Bearer "前缀
|
token = auth_header[7:] # Remove "Bearer " prefix
|
||||||
return self.auth.verify_token(token)
|
return self.auth.verify_token(token)
|
||||||
|
|
||||||
async def handle_post(self, request):
|
async def handle_post(self, request):
|
||||||
"""处理 MCP Vision POST 请求"""
|
"""Handle MCP Vision POST request"""
|
||||||
response = None # 初始化response变量
|
response = None # Initialize response variable
|
||||||
try:
|
try:
|
||||||
# 验证token
|
# Verify token
|
||||||
is_valid, token_device_id = self._verify_auth_token(request)
|
is_valid, token_device_id = self._verify_auth_token(request)
|
||||||
if not is_valid:
|
if not is_valid:
|
||||||
response = web.Response(
|
response = web.Response(
|
||||||
text=json.dumps(
|
text=json.dumps(
|
||||||
self._create_error_response("无效的认证token或token已过期")
|
self._create_error_response(
|
||||||
|
"Invalid authentication token or token expired")
|
||||||
),
|
),
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
status=401,
|
status=401,
|
||||||
)
|
)
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# 获取请求头信息
|
# Get request header information
|
||||||
device_id = request.headers.get("Device-Id", "")
|
device_id = request.headers.get("Device-Id", "")
|
||||||
client_id = request.headers.get("Client-Id", "")
|
client_id = request.headers.get("Client-Id", "")
|
||||||
if device_id != token_device_id:
|
if device_id != token_device_id:
|
||||||
raise ValueError("设备ID与token不匹配")
|
raise ValueError("Device ID does not match token")
|
||||||
# 解析multipart/form-data请求
|
# Parse multipart/form-data request
|
||||||
reader = await request.multipart()
|
reader = await request.multipart()
|
||||||
|
|
||||||
# 读取question字段
|
# Read question field
|
||||||
question_field = await reader.next()
|
question_field = await reader.next()
|
||||||
if question_field is None:
|
if question_field is None:
|
||||||
raise ValueError("缺少问题字段")
|
raise ValueError("Missing question field")
|
||||||
question = await question_field.text()
|
question = await question_field.text()
|
||||||
self.logger.bind(tag=TAG).debug(f"Question: {question}")
|
self.logger.bind(tag=TAG).debug(f"Question: {question}")
|
||||||
|
|
||||||
# 读取图片文件
|
# Read image file
|
||||||
image_field = await reader.next()
|
image_field = await reader.next()
|
||||||
if image_field is None:
|
if image_field is None:
|
||||||
raise ValueError("缺少图片文件")
|
raise ValueError("Missing image file")
|
||||||
|
|
||||||
# 读取图片数据
|
# Read image data
|
||||||
image_data = await image_field.read()
|
image_data = await image_field.read()
|
||||||
if not image_data:
|
if not image_data:
|
||||||
raise ValueError("图片数据为空")
|
raise ValueError("Image data is empty")
|
||||||
|
|
||||||
# 检查文件大小
|
# Check file size
|
||||||
if len(image_data) > MAX_FILE_SIZE:
|
if len(image_data) > MAX_FILE_SIZE:
|
||||||
raise ValueError(
|
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):
|
if not is_valid_image_file(image_data):
|
||||||
raise ValueError(
|
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")
|
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)
|
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:
|
if read_config_from_api:
|
||||||
current_config = get_private_config_from_api(
|
current_config = get_private_config_from_api(
|
||||||
current_config,
|
current_config,
|
||||||
|
|
@ -104,7 +106,8 @@ class VisionHandler:
|
||||||
|
|
||||||
select_vllm_module = current_config["selected_module"].get("VLLM")
|
select_vllm_module = current_config["selected_module"].get("VLLM")
|
||||||
if not select_vllm_module:
|
if not select_vllm_module:
|
||||||
raise ValueError("您还未设置默认的视觉分析模块")
|
raise ValueError(
|
||||||
|
"You have not set a default vision analysis module yet")
|
||||||
|
|
||||||
vllm_type = (
|
vllm_type = (
|
||||||
select_vllm_module
|
select_vllm_module
|
||||||
|
|
@ -113,7 +116,8 @@ class VisionHandler:
|
||||||
)
|
)
|
||||||
|
|
||||||
if not vllm_type:
|
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 = create_instance(
|
||||||
vllm_type, current_config["VLLM"][select_vllm_module]
|
vllm_type, current_config["VLLM"][select_vllm_module]
|
||||||
|
|
@ -132,15 +136,18 @@ class VisionHandler:
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
)
|
)
|
||||||
except ValueError as e:
|
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))
|
return_json = self._create_error_response(str(e))
|
||||||
response = web.Response(
|
response = web.Response(
|
||||||
text=json.dumps(return_json, separators=(",", ":")),
|
text=json.dumps(return_json, separators=(",", ":")),
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
|
self.logger.bind(tag=TAG).error(
|
||||||
return_json = self._create_error_response("处理请求时发生错误")
|
f"MCP Vision POST request exception: {e}")
|
||||||
|
return_json = self._create_error_response(
|
||||||
|
"Error occurred while processing request")
|
||||||
response = web.Response(
|
response = web.Response(
|
||||||
text=json.dumps(return_json, separators=(",", ":")),
|
text=json.dumps(return_json, separators=(",", ":")),
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
|
|
@ -151,20 +158,21 @@ class VisionHandler:
|
||||||
return response
|
return response
|
||||||
|
|
||||||
async def handle_get(self, request):
|
async def handle_get(self, request):
|
||||||
"""处理 MCP Vision GET 请求"""
|
"""Handle MCP Vision GET request"""
|
||||||
try:
|
try:
|
||||||
vision_explain = get_vision_url(self.config)
|
vision_explain = get_vision_url(self.config)
|
||||||
if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
|
if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
|
||||||
message = (
|
message = (
|
||||||
f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}"
|
f"MCP Vision interface running normally, vision explanation interface address is: {vision_explain}"
|
||||||
)
|
)
|
||||||
else:
|
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")
|
response = web.Response(text=message, content_type="text/plain")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}")
|
self.logger.bind(tag=TAG).error(
|
||||||
return_json = self._create_error_response("服务器内部错误")
|
f"MCP Vision GET request exception: {e}")
|
||||||
|
return_json = self._create_error_response("Internal server error")
|
||||||
response = web.Response(
|
response = web.Response(
|
||||||
text=json.dumps(return_json, separators=(",", ":")),
|
text=json.dumps(return_json, separators=(",", ":")),
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
|
|
@ -174,7 +182,7 @@ class VisionHandler:
|
||||||
return response
|
return response
|
||||||
|
|
||||||
def _add_cors_headers(self, response):
|
def _add_cors_headers(self, response):
|
||||||
"""添加CORS头信息"""
|
"""Add CORS header information"""
|
||||||
response.headers["Access-Control-Allow-Headers"] = (
|
response.headers["Access-Control-Allow-Headers"] = (
|
||||||
"client-id, content-type, device-id"
|
"client-id, content-type, device-id"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,41 +1,41 @@
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class AuthenticationError(Exception):
|
class AuthenticationError(Exception):
|
||||||
"""认证异常"""
|
"""Authentication exception"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class AuthMiddleware:
|
class AuthMiddleware:
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.config = config
|
self.config = config
|
||||||
self.auth_config = config["server"].get("auth", {})
|
self.auth_config = config["server"].get("auth", {})
|
||||||
# 构建token查找表
|
|
||||||
|
# Build token lookup table
|
||||||
self.tokens = {
|
self.tokens = {
|
||||||
item["token"]: item["name"]
|
item["token"]: item["name"]
|
||||||
for item in self.auth_config.get("tokens", [])
|
for item in self.auth_config.get("tokens", [])
|
||||||
}
|
}
|
||||||
# 设备白名单
|
|
||||||
|
# Device whitelist
|
||||||
self.allowed_devices = set(
|
self.allowed_devices = set(
|
||||||
self.auth_config.get("allowed_devices", [])
|
self.auth_config.get("allowed_devices", [])
|
||||||
)
|
)
|
||||||
|
|
||||||
async def authenticate(self, headers):
|
async def authenticate(self, headers):
|
||||||
"""验证连接请求"""
|
"""Verify connection request"""
|
||||||
# 检查是否启用认证
|
# Check if authentication is enabled
|
||||||
if not self.auth_config.get("enabled", False):
|
if not self.auth_config.get("enabled", False):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# 检查设备是否在白名单中
|
# Check if device is in whitelist
|
||||||
device_id = headers.get("device-id", "")
|
device_id = headers.get("device-id", "")
|
||||||
|
|
||||||
if self.allowed_devices and device_id in self.allowed_devices:
|
if self.allowed_devices and device_id in self.allowed_devices:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# 验证Authorization header
|
# Verify Authorization header
|
||||||
auth_header = headers.get("authorization", "")
|
auth_header = headers.get("authorization", "")
|
||||||
if not auth_header.startswith("Bearer "):
|
if not auth_header.startswith("Bearer "):
|
||||||
logger.bind(tag=TAG).error("Missing or invalid Authorization header")
|
logger.bind(tag=TAG).error("Missing or invalid Authorization header")
|
||||||
|
|
@ -50,5 +50,5 @@ class AuthMiddleware:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def get_token_name(self, token):
|
def get_token_name(self, token):
|
||||||
"""获取token对应的设备名称"""
|
"""Get device name corresponding to token"""
|
||||||
return self.tokens.get(token)
|
return self.tokens.get(token)
|
||||||
|
|
@ -65,12 +65,13 @@ class ConnectionHandler:
|
||||||
self.config = copy.deepcopy(config)
|
self.config = copy.deepcopy(config)
|
||||||
self.session_id = str(uuid.uuid4())
|
self.session_id = str(uuid.uuid4())
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
self.server = server # 保存server实例的引用
|
self.server = server # Save a reference to the server instance
|
||||||
|
|
||||||
self.auth = AuthMiddleware(config)
|
self.auth = AuthMiddleware(config)
|
||||||
self.need_bind = False
|
self.need_bind = False
|
||||||
self.bind_code = None
|
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.websocket = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
|
|
@ -82,24 +83,24 @@ class ConnectionHandler:
|
||||||
self.chat_history_conf = 0
|
self.chat_history_conf = 0
|
||||||
self.audio_format = "opus"
|
self.audio_format = "opus"
|
||||||
|
|
||||||
# 客户端状态相关
|
# Client state related
|
||||||
self.client_abort = False
|
self.client_abort = False
|
||||||
self.client_is_speaking = False
|
self.client_is_speaking = False
|
||||||
self.client_listen_mode = "auto"
|
self.client_listen_mode = "auto"
|
||||||
|
|
||||||
# 线程任务相关
|
# Thread task related
|
||||||
self.loop = asyncio.get_event_loop()
|
self.loop = asyncio.get_event_loop()
|
||||||
self.stop_event = threading.Event()
|
self.stop_event = threading.Event()
|
||||||
self.executor = ThreadPoolExecutor(max_workers=5)
|
self.executor = ThreadPoolExecutor(max_workers=5)
|
||||||
|
|
||||||
# 添加上报线程池
|
# Add reporting thread pool
|
||||||
self.report_queue = queue.Queue()
|
self.report_queue = queue.Queue()
|
||||||
self.report_thread = None
|
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_asr_enable = self.read_config_from_api
|
||||||
self.report_tts_enable = self.read_config_from_api
|
self.report_tts_enable = self.read_config_from_api
|
||||||
|
|
||||||
# 依赖的组件
|
# Dependent components
|
||||||
self.vad = None
|
self.vad = None
|
||||||
self.asr = None
|
self.asr = None
|
||||||
self.tts = None
|
self.tts = None
|
||||||
|
|
@ -109,33 +110,34 @@ class ConnectionHandler:
|
||||||
self.memory = _memory
|
self.memory = _memory
|
||||||
self.intent = _intent
|
self.intent = _intent
|
||||||
|
|
||||||
# 为每个连接单独管理声纹识别
|
# Manage voiceprint recognition separately for each connection
|
||||||
self.voiceprint_provider = None
|
self.voiceprint_provider = None
|
||||||
|
|
||||||
# vad相关变量
|
# VAD related variables
|
||||||
self.client_audio_buffer = bytearray()
|
self.client_audio_buffer = bytearray()
|
||||||
self.client_have_voice = False
|
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_stop = False
|
||||||
self.client_voice_window = deque(maxlen=5)
|
self.client_voice_window = deque(maxlen=5)
|
||||||
self.last_is_voice = False
|
self.last_is_voice = False
|
||||||
|
|
||||||
# asr相关变量
|
# ASR related variables
|
||||||
# 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
|
# Since a public local ASR might be used in actual deployment, variables cannot be exposed to the public ASR.
|
||||||
# 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量
|
# Therefore, variables related to ASR need to be defined here as private variables of the connection.
|
||||||
self.asr_audio = []
|
self.asr_audio = []
|
||||||
self.asr_audio_queue = queue.Queue()
|
self.asr_audio_queue = queue.Queue()
|
||||||
|
|
||||||
# llm相关变量
|
# LLM related variables
|
||||||
self.llm_finish_task = True
|
self.llm_finish_task = True
|
||||||
self.dialogue = Dialogue()
|
self.dialogue = Dialogue()
|
||||||
|
|
||||||
# tts相关变量
|
# TTS related variables
|
||||||
self.sentence_id = None
|
self.sentence_id = None
|
||||||
# 处理TTS响应没有文本返回
|
# Handle cases where TTS response has no text
|
||||||
self.tts_MessageText = ""
|
self.tts_MessageText = ""
|
||||||
|
|
||||||
# iot相关变量
|
# IoT related variables
|
||||||
self.iot_descriptors = {}
|
self.iot_descriptors = {}
|
||||||
self.func_handler = None
|
self.func_handler = None
|
||||||
|
|
||||||
|
|
@ -145,35 +147,36 @@ class ConnectionHandler:
|
||||||
if len(cmd) > self.max_cmd_length:
|
if len(cmd) > self.max_cmd_length:
|
||||||
self.max_cmd_length = len(cmd)
|
self.max_cmd_length = len(cmd)
|
||||||
|
|
||||||
# 是否在聊天结束后关闭连接
|
# Whether to close the connection after the chat ends
|
||||||
self.close_after_chat = False
|
self.close_after_chat = False
|
||||||
self.load_function_plugin = False
|
self.load_function_plugin = False
|
||||||
self.intent_type = "nointent"
|
self.intent_type = "nointent"
|
||||||
|
|
||||||
self.timeout_seconds = (
|
self.timeout_seconds = (
|
||||||
int(self.config.get("close_connection_no_voice_time", 120)) + 60
|
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
|
self.timeout_task = None
|
||||||
|
|
||||||
# {"mcp":true} 表示启用MCP功能
|
# {"mcp":true} indicates that the MCP function is enabled
|
||||||
self.features = None
|
self.features = None
|
||||||
|
|
||||||
# 初始化提示词管理器
|
# Initialize prompt manager
|
||||||
self.prompt_manager = PromptManager(config, self.logger)
|
self.prompt_manager = PromptManager(config, self.logger)
|
||||||
|
|
||||||
async def handle_connection(self, ws):
|
async def handle_connection(self, ws):
|
||||||
try:
|
try:
|
||||||
# 获取并验证headers
|
# Get and validate headers
|
||||||
self.headers = dict(ws.request.headers)
|
self.headers = dict(ws.request.headers)
|
||||||
|
|
||||||
if self.headers.get("device-id", None) is None:
|
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
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
# 从 WebSocket 请求中获取路径
|
# Get the path from the WebSocket request
|
||||||
request_path = ws.request.path
|
request_path = ws.request.path
|
||||||
if not request_path:
|
if not request_path:
|
||||||
self.logger.bind(tag=TAG).error("无法获取请求路径")
|
self.logger.bind(tag=TAG).error(
|
||||||
|
"Unable to get request path")
|
||||||
return
|
return
|
||||||
parsed_url = urlparse(request_path)
|
parsed_url = urlparse(request_path)
|
||||||
query_params = parse_qs(parsed_url.query)
|
query_params = parse_qs(parsed_url.query)
|
||||||
|
|
@ -181,7 +184,7 @@ class ConnectionHandler:
|
||||||
self.headers["device-id"] = query_params["device-id"][0]
|
self.headers["device-id"] = query_params["device-id"][0]
|
||||||
self.headers["client-id"] = query_params["client-id"][0]
|
self.headers["client-id"] = query_params["client-id"][0]
|
||||||
else:
|
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)
|
await self.close(ws)
|
||||||
return
|
return
|
||||||
real_ip = self.headers.get("x-real-ip") or self.headers.get(
|
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}"
|
f"{self.client_ip} conn - Headers: {self.headers}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 进行认证
|
# Perform authentication
|
||||||
await self.auth.authenticate(self.headers)
|
await self.auth.authenticate(self.headers)
|
||||||
|
|
||||||
# 认证通过,继续处理
|
# Authentication passed, continue processing
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
self.device_id = self.headers.get("device-id", None)
|
self.device_id = self.headers.get("device-id", None)
|
||||||
|
|
||||||
# 初始化活动时间戳
|
# Initialize activity timestamp
|
||||||
self.last_activity_time = time.time() * 1000
|
self.last_activity_time = time.time() * 1000
|
||||||
|
|
||||||
# 启动超时检查任务
|
# Start timeout check task
|
||||||
self.timeout_task = asyncio.create_task(self._check_timeout())
|
self.timeout_task = asyncio.create_task(self._check_timeout())
|
||||||
|
|
||||||
self.welcome_msg = self.config["xiaozhi"]
|
self.welcome_msg = self.config["xiaozhi"]
|
||||||
self.welcome_msg["session_id"] = self.session_id
|
self.welcome_msg["session_id"] = self.session_id
|
||||||
|
|
||||||
# 获取差异化配置
|
# Get differential configuration
|
||||||
self._initialize_private_config()
|
self._initialize_private_config()
|
||||||
# 异步初始化
|
# Asynchronous initialization
|
||||||
self.executor.submit(self._initialize_components)
|
self.executor.submit(self._initialize_components)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async for message in self.websocket:
|
async for message in self.websocket:
|
||||||
await self._route_message(message)
|
await self._route_message(message)
|
||||||
except websockets.exceptions.ConnectionClosed:
|
except websockets.exceptions.ConnectionClosed:
|
||||||
self.logger.bind(tag=TAG).info("客户端断开连接")
|
self.logger.bind(tag=TAG).info("Client disconnected")
|
||||||
|
|
||||||
except AuthenticationError as e:
|
except AuthenticationError as e:
|
||||||
self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
|
self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
stack_trace = traceback.format_exc()
|
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
|
return
|
||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
await self._save_and_close(ws)
|
await self._save_and_close(ws)
|
||||||
except Exception as final_error:
|
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:
|
try:
|
||||||
await self.close(ws)
|
await self.close(ws)
|
||||||
except Exception as close_error:
|
except Exception as close_error:
|
||||||
self.logger.bind(tag=TAG).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):
|
async def _save_and_close(self, ws):
|
||||||
"""保存记忆并关闭连接"""
|
"""Save memory and close the connection"""
|
||||||
try:
|
try:
|
||||||
if self.memory:
|
if self.memory:
|
||||||
# 使用线程池异步保存记忆
|
# Use a thread pool to save memory asynchronously
|
||||||
def save_memory_task():
|
def save_memory_task():
|
||||||
try:
|
try:
|
||||||
# 创建新事件循环(避免与主循环冲突)
|
# Create a new event loop (to avoid conflicts with the main loop)
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
loop.run_until_complete(
|
loop.run_until_complete(
|
||||||
self.memory.save_memory(self.dialogue.dialogue)
|
self.memory.save_memory(self.dialogue.dialogue)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
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:
|
finally:
|
||||||
try:
|
try:
|
||||||
loop.close()
|
loop.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 启动线程保存记忆,不等待完成
|
# Start a thread to save memory, do not wait for completion
|
||||||
threading.Thread(target=save_memory_task, daemon=True).start()
|
threading.Thread(target=save_memory_task, daemon=True).start()
|
||||||
except Exception as e:
|
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:
|
finally:
|
||||||
# 立即关闭连接,不等待记忆保存完成
|
# Close the connection immediately, do not wait for memory saving to complete
|
||||||
try:
|
try:
|
||||||
await self.close(ws)
|
await self.close(ws)
|
||||||
except Exception as close_error:
|
except Exception as close_error:
|
||||||
self.logger.bind(tag=TAG).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):
|
async def _route_message(self, message):
|
||||||
"""消息路由"""
|
"""Message routing"""
|
||||||
if isinstance(message, str):
|
if isinstance(message, str):
|
||||||
await handleTextMessage(self, message)
|
await handleTextMessage(self, message)
|
||||||
elif isinstance(message, bytes):
|
elif isinstance(message, bytes):
|
||||||
|
|
@ -288,28 +294,29 @@ class ConnectionHandler:
|
||||||
self.asr_audio_queue.put(message)
|
self.asr_audio_queue.put(message)
|
||||||
|
|
||||||
async def handle_restart(self, message):
|
async def handle_restart(self, message):
|
||||||
"""处理服务器重启请求"""
|
"""Handle server restart request"""
|
||||||
try:
|
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(
|
await self.websocket.send(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
"type": "server",
|
"type": "server",
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"message": "服务器重启中...",
|
"message": "Server restarting...",
|
||||||
"content": {"action": "restart"},
|
"content": {"action": "restart"},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 异步执行重启操作
|
# Asynchronously execute the restart operation
|
||||||
def restart_server():
|
def restart_server():
|
||||||
"""实际执行重启的方法"""
|
"""The actual method to execute the restart"""
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
self.logger.bind(tag=TAG).info("执行服务器重启...")
|
self.logger.bind(tag=TAG).info("Executing server restart...")
|
||||||
subprocess.Popen(
|
subprocess.Popen(
|
||||||
[sys.executable, "app.py"],
|
[sys.executable, "app.py"],
|
||||||
stdin=sys.stdin,
|
stdin=sys.stdin,
|
||||||
|
|
@ -319,11 +326,11 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
os._exit(0)
|
os._exit(0)
|
||||||
|
|
||||||
# 使用线程执行重启避免阻塞事件循环
|
# Use a thread to execute the restart to avoid blocking the event loop
|
||||||
threading.Thread(target=restart_server, daemon=True).start()
|
threading.Thread(target=restart_server, daemon=True).start()
|
||||||
|
|
||||||
except Exception as e:
|
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(
|
await self.websocket.send(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
|
|
@ -342,60 +349,62 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
self.logger = create_connection_logger(self.selected_module_str)
|
self.logger = create_connection_logger(self.selected_module_str)
|
||||||
|
|
||||||
"""初始化组件"""
|
"""Initialize components"""
|
||||||
if self.config.get("prompt") is not None:
|
if self.config.get("prompt") is not None:
|
||||||
user_prompt = self.config["prompt"]
|
user_prompt = self.config["prompt"]
|
||||||
# 使用快速提示词进行初始化
|
# Use a quick prompt for initialization
|
||||||
prompt = self.prompt_manager.get_quick_prompt(user_prompt)
|
prompt = self.prompt_manager.get_quick_prompt(user_prompt)
|
||||||
self.change_system_prompt(prompt)
|
self.change_system_prompt(prompt)
|
||||||
self.logger.bind(tag=TAG).info(
|
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:
|
if self.vad is None:
|
||||||
self.vad = self._vad
|
self.vad = self._vad
|
||||||
if self.asr is None:
|
if self.asr is None:
|
||||||
self.asr = self._initialize_asr()
|
self.asr = self._initialize_asr()
|
||||||
|
|
||||||
# 初始化声纹识别
|
# Initialize voiceprint recognition
|
||||||
self._initialize_voiceprint()
|
self._initialize_voiceprint()
|
||||||
|
|
||||||
# 打开语音识别通道
|
# Open speech recognition channel
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self.asr.open_audio_channels(self), self.loop
|
self.asr.open_audio_channels(self), self.loop
|
||||||
)
|
)
|
||||||
if self.tts is None:
|
if self.tts is None:
|
||||||
self.tts = self._initialize_tts()
|
self.tts = self._initialize_tts()
|
||||||
# 打开语音合成通道
|
# Open speech synthesis channel
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self.tts.open_audio_channels(self), self.loop
|
self.tts.open_audio_channels(self), self.loop
|
||||||
)
|
)
|
||||||
|
|
||||||
"""加载记忆"""
|
"""Load memory"""
|
||||||
self._initialize_memory()
|
self._initialize_memory()
|
||||||
"""加载意图识别"""
|
"""Load intent recognition"""
|
||||||
self._initialize_intent()
|
self._initialize_intent()
|
||||||
"""初始化上报线程"""
|
"""Initialize reporting thread"""
|
||||||
self._init_report_threads()
|
self._init_report_threads()
|
||||||
"""更新系统提示词"""
|
"""Update system prompt"""
|
||||||
self._init_prompt_enhancement()
|
self._init_prompt_enhancement()
|
||||||
|
|
||||||
except Exception as e:
|
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):
|
def _init_prompt_enhancement(self):
|
||||||
# 更新上下文信息
|
# Update context information
|
||||||
self.prompt_manager.update_context_info(self, self.client_ip)
|
self.prompt_manager.update_context_info(self, self.client_ip)
|
||||||
enhanced_prompt = self.prompt_manager.build_enhanced_prompt(
|
enhanced_prompt = self.prompt_manager.build_enhanced_prompt(
|
||||||
self.config["prompt"], self.device_id, self.client_ip
|
self.config["prompt"], self.device_id, self.client_ip
|
||||||
)
|
)
|
||||||
if enhanced_prompt:
|
if enhanced_prompt:
|
||||||
self.change_system_prompt(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):
|
def _init_report_threads(self):
|
||||||
"""初始化ASR和TTS上报线程"""
|
"""Initialize ASR and TTS reporting threads"""
|
||||||
if not self.read_config_from_api or self.need_bind:
|
if not self.read_config_from_api or self.need_bind:
|
||||||
return
|
return
|
||||||
if self.chat_history_conf == 0:
|
if self.chat_history_conf == 0:
|
||||||
|
|
@ -405,10 +414,10 @@ class ConnectionHandler:
|
||||||
target=self._report_worker, daemon=True
|
target=self._report_worker, daemon=True
|
||||||
)
|
)
|
||||||
self.report_thread.start()
|
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):
|
def _initialize_tts(self):
|
||||||
"""初始化TTS"""
|
"""Initialize TTS"""
|
||||||
tts = None
|
tts = None
|
||||||
if not self.need_bind:
|
if not self.need_bind:
|
||||||
tts = initialize_tts(self.config)
|
tts = initialize_tts(self.config)
|
||||||
|
|
@ -419,35 +428,39 @@ class ConnectionHandler:
|
||||||
return tts
|
return tts
|
||||||
|
|
||||||
def _initialize_asr(self):
|
def _initialize_asr(self):
|
||||||
"""初始化ASR"""
|
"""Initialize ASR"""
|
||||||
if self._asr.interface_type == InterfaceType.LOCAL:
|
if self._asr.interface_type == InterfaceType.LOCAL:
|
||||||
# 如果公共ASR是本地服务,则直接返回
|
# If the public ASR is a local service, return directly
|
||||||
# 因为本地一个实例ASR,可以被多个连接共享
|
# Because one local ASR instance can be shared by multiple connections
|
||||||
asr = self._asr
|
asr = self._asr
|
||||||
else:
|
else:
|
||||||
# 如果公共ASR是远程服务,则初始化一个新实例
|
# If the public ASR is a remote service, initialize a new instance
|
||||||
# 因为远程ASR,涉及到websocket连接和接收线程,需要每个连接一个实例
|
# Because a remote ASR involves a WebSocket connection and a receiving thread, each connection needs its own instance
|
||||||
asr = initialize_asr(self.config)
|
asr = initialize_asr(self.config)
|
||||||
|
|
||||||
return asr
|
return asr
|
||||||
|
|
||||||
def _initialize_voiceprint(self):
|
def _initialize_voiceprint(self):
|
||||||
"""为当前连接初始化声纹识别"""
|
"""Initialize voiceprint recognition for the current connection"""
|
||||||
try:
|
try:
|
||||||
voiceprint_config = self.config.get("voiceprint", {})
|
voiceprint_config = self.config.get("voiceprint", {})
|
||||||
if voiceprint_config:
|
if voiceprint_config:
|
||||||
self.voiceprint_provider = VoiceprintProvider(voiceprint_config)
|
self.voiceprint_provider = VoiceprintProvider(
|
||||||
self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
|
voiceprint_config)
|
||||||
|
self.logger.bind(tag=TAG).info(
|
||||||
|
"Voiceprint recognition function dynamically enabled on connection")
|
||||||
else:
|
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:
|
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):
|
def _initialize_private_config(self):
|
||||||
"""如果是从配置文件获取,则进行二次实例化"""
|
"""If getting from the configuration file, perform a second instantiation"""
|
||||||
if not self.read_config_from_api:
|
if not self.read_config_from_api:
|
||||||
return
|
return
|
||||||
"""从接口获取差异化的配置进行二次实例化,非全量重新实例化"""
|
"""Get differential configuration from the interface for a second instantiation, not a full re-instantiation"""
|
||||||
try:
|
try:
|
||||||
begin_time = time.time()
|
begin_time = time.time()
|
||||||
private_config = get_private_config_from_api(
|
private_config = get_private_config_from_api(
|
||||||
|
|
@ -455,9 +468,10 @@ class ConnectionHandler:
|
||||||
self.headers.get("device-id"),
|
self.headers.get("device-id"),
|
||||||
self.headers.get("client-id", 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(
|
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:
|
except DeviceNotFoundException as e:
|
||||||
self.need_bind = True
|
self.need_bind = True
|
||||||
|
|
@ -468,7 +482,8 @@ class ConnectionHandler:
|
||||||
private_config = {}
|
private_config = {}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.need_bind = True
|
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 = {}
|
private_config = {}
|
||||||
|
|
||||||
init_llm, init_tts, init_memory, init_intent = (
|
init_llm, init_tts, init_memory, init_intent = (
|
||||||
|
|
@ -517,9 +532,10 @@ class ConnectionHandler:
|
||||||
if private_config.get("Intent", None) is not None:
|
if private_config.get("Intent", None) is not None:
|
||||||
init_intent = True
|
init_intent = True
|
||||||
self.config["Intent"] = private_config["Intent"]
|
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
|
self.config["selected_module"]["Intent"] = model_intent
|
||||||
# 加载插件配置
|
# Load plugin configuration
|
||||||
if model_intent != "Intent_nointent":
|
if model_intent != "Intent_nointent":
|
||||||
plugin_from_server = private_config.get("plugins", {})
|
plugin_from_server = private_config.get("plugins", {})
|
||||||
for plugin, config_str in plugin_from_server.items():
|
for plugin, config_str in plugin_from_server.items():
|
||||||
|
|
@ -527,16 +543,17 @@ class ConnectionHandler:
|
||||||
self.config["plugins"] = plugin_from_server
|
self.config["plugins"] = plugin_from_server
|
||||||
self.config["Intent"][self.config["selected_module"]["Intent"]][
|
self.config["Intent"][self.config["selected_module"]["Intent"]][
|
||||||
"functions"
|
"functions"
|
||||||
] = plugin_from_server.keys()
|
] = list(plugin_from_server.keys())
|
||||||
if private_config.get("prompt", None) is not None:
|
if private_config.get("prompt", None) is not None:
|
||||||
self.config["prompt"] = private_config["prompt"]
|
self.config["prompt"] = private_config["prompt"]
|
||||||
# 获取声纹信息
|
# Get voiceprint information
|
||||||
if private_config.get("voiceprint", None) is not None:
|
if private_config.get("voiceprint", None) is not None:
|
||||||
self.config["voiceprint"] = private_config["voiceprint"]
|
self.config["voiceprint"] = private_config["voiceprint"]
|
||||||
if private_config.get("summaryMemory", None) is not None:
|
if private_config.get("summaryMemory", None) is not None:
|
||||||
self.config["summaryMemory"] = private_config["summaryMemory"]
|
self.config["summaryMemory"] = private_config["summaryMemory"]
|
||||||
if private_config.get("device_max_output_size", None) is not None:
|
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:
|
if private_config.get("chat_history_conf", None) is not None:
|
||||||
self.chat_history_conf = int(private_config["chat_history_conf"])
|
self.chat_history_conf = int(private_config["chat_history_conf"])
|
||||||
if private_config.get("mcp_endpoint", None) is not None:
|
if private_config.get("mcp_endpoint", None) is not None:
|
||||||
|
|
@ -553,7 +570,8 @@ class ConnectionHandler:
|
||||||
init_intent,
|
init_intent,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
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 = {}
|
modules = {}
|
||||||
if modules.get("tts", None) is not None:
|
if modules.get("tts", None) is not None:
|
||||||
self.tts = modules["tts"]
|
self.tts = modules["tts"]
|
||||||
|
|
@ -571,7 +589,7 @@ class ConnectionHandler:
|
||||||
def _initialize_memory(self):
|
def _initialize_memory(self):
|
||||||
if self.memory is None:
|
if self.memory is None:
|
||||||
return
|
return
|
||||||
"""初始化记忆模块"""
|
"""Initialize memory module"""
|
||||||
self.memory.init_memory(
|
self.memory.init_memory(
|
||||||
role_id=self.device_id,
|
role_id=self.device_id,
|
||||||
llm=self.llm,
|
llm=self.llm,
|
||||||
|
|
@ -579,36 +597,38 @@ class ConnectionHandler:
|
||||||
save_to_file=not self.read_config_from_api,
|
save_to_file=not self.read_config_from_api,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 获取记忆总结配置
|
# Get memory summary configuration
|
||||||
memory_config = self.config["Memory"]
|
memory_config = self.config["Memory"]
|
||||||
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
|
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
|
||||||
"type"
|
"type"
|
||||||
]
|
]
|
||||||
# 如果使用 nomen,直接返回
|
# If using nomem, return directly
|
||||||
if memory_type == "nomem":
|
if memory_type == "nomem":
|
||||||
return
|
return
|
||||||
# 使用 mem_local_short 模式
|
# Use mem_local_short mode
|
||||||
elif memory_type == "mem_local_short":
|
elif memory_type == "mem_local_short":
|
||||||
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
|
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
|
||||||
"llm"
|
"llm"
|
||||||
]
|
]
|
||||||
if memory_llm_name and memory_llm_name in self.config["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
|
from core.utils import llm as llm_utils
|
||||||
|
|
||||||
memory_llm_config = self.config["LLM"][memory_llm_name]
|
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 = llm_utils.create_instance(
|
||||||
memory_llm_type, memory_llm_config
|
memory_llm_type, memory_llm_config
|
||||||
)
|
)
|
||||||
self.logger.bind(tag=TAG).info(
|
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)
|
self.memory.set_llm(memory_llm)
|
||||||
else:
|
else:
|
||||||
# 否则使用主LLM
|
# Otherwise use main LLM
|
||||||
self.memory.set_llm(self.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):
|
def _initialize_intent(self):
|
||||||
if self.intent is None:
|
if self.intent is None:
|
||||||
|
|
@ -618,60 +638,63 @@ class ConnectionHandler:
|
||||||
]["type"]
|
]["type"]
|
||||||
if self.intent_type == "function_call" or self.intent_type == "intent_llm":
|
if self.intent_type == "function_call" or self.intent_type == "intent_llm":
|
||||||
self.load_function_plugin = True
|
self.load_function_plugin = True
|
||||||
"""初始化意图识别模块"""
|
"""Initialize intent recognition module"""
|
||||||
# 获取意图识别配置
|
# Get intent recognition configuration
|
||||||
intent_config = self.config["Intent"]
|
intent_config = self.config["Intent"]
|
||||||
intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
|
intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
|
||||||
"type"
|
"type"
|
||||||
]
|
]
|
||||||
|
|
||||||
# 如果使用 nointent,直接返回
|
# If using nointent, return directly
|
||||||
if intent_type == "nointent":
|
if intent_type == "nointent":
|
||||||
return
|
return
|
||||||
# 使用 intent_llm 模式
|
# Use intent_llm mode
|
||||||
elif intent_type == "intent_llm":
|
elif intent_type == "intent_llm":
|
||||||
intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
|
intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
|
||||||
"llm"
|
"llm"
|
||||||
]
|
]
|
||||||
|
|
||||||
if intent_llm_name and intent_llm_name in self.config["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
|
from core.utils import llm as llm_utils
|
||||||
|
|
||||||
intent_llm_config = self.config["LLM"][intent_llm_name]
|
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 = llm_utils.create_instance(
|
||||||
intent_llm_type, intent_llm_config
|
intent_llm_type, intent_llm_config
|
||||||
)
|
)
|
||||||
self.logger.bind(tag=TAG).info(
|
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)
|
self.intent.set_llm(intent_llm)
|
||||||
else:
|
else:
|
||||||
# 否则使用主LLM
|
# Otherwise use main LLM
|
||||||
self.intent.set_llm(self.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)
|
self.func_handler = UnifiedToolHandler(self)
|
||||||
|
|
||||||
# 异步初始化工具处理器
|
# Asynchronously initialize tool handler
|
||||||
if hasattr(self, "loop") and self.loop:
|
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):
|
def change_system_prompt(self, prompt):
|
||||||
self.prompt = prompt
|
self.prompt = prompt
|
||||||
# 更新系统prompt至上下文
|
# Update system prompt in the context
|
||||||
self.dialogue.update_system_message(self.prompt)
|
self.dialogue.update_system_message(self.prompt)
|
||||||
|
|
||||||
def chat(self, query, tool_call=False, depth=0):
|
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
|
self.llm_finish_task = False
|
||||||
|
|
||||||
if not tool_call:
|
if not tool_call:
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
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:
|
if depth == 0:
|
||||||
self.sentence_id = str(uuid.uuid4().hex)
|
self.sentence_id = str(uuid.uuid4().hex)
|
||||||
self.tts.tts_text_queue.put(
|
self.tts.tts_text_queue.put(
|
||||||
|
|
@ -689,7 +712,7 @@ class ConnectionHandler:
|
||||||
response_message = []
|
response_message = []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 使用带记忆的对话
|
# Use dialogue with memory
|
||||||
memory_str = None
|
memory_str = None
|
||||||
if self.memory is not None:
|
if self.memory is not None:
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
|
|
@ -698,7 +721,7 @@ class ConnectionHandler:
|
||||||
memory_str = future.result()
|
memory_str = future.result()
|
||||||
|
|
||||||
if self.intent_type == "function_call" and functions is not None:
|
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(
|
llm_responses = self.llm.response_with_functions(
|
||||||
self.session_id,
|
self.session_id,
|
||||||
self.dialogue.get_llm_dialogue_with_memory(
|
self.dialogue.get_llm_dialogue_with_memory(
|
||||||
|
|
@ -714,10 +737,11 @@ class ConnectionHandler:
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
# 处理流式响应
|
# Handle streaming response
|
||||||
tool_call_flag = False
|
tool_call_flag = False
|
||||||
function_name = None
|
function_name = None
|
||||||
function_id = None
|
function_id = None
|
||||||
|
|
@ -751,7 +775,7 @@ class ConnectionHandler:
|
||||||
else:
|
else:
|
||||||
content = response
|
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():
|
if emotion_flag and content is not None and content.strip():
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
textUtils.get_emotion(self, content),
|
textUtils.get_emotion(self, content),
|
||||||
|
|
@ -770,7 +794,7 @@ class ConnectionHandler:
|
||||||
content_detail=content,
|
content_detail=content,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
# 处理function call
|
# Handle function call
|
||||||
if tool_call_flag:
|
if tool_call_flag:
|
||||||
bHasError = False
|
bHasError = False
|
||||||
if function_id is None:
|
if function_id is None:
|
||||||
|
|
@ -794,11 +818,12 @@ class ConnectionHandler:
|
||||||
f"function call error: {content_arguments}"
|
f"function call error: {content_arguments}"
|
||||||
)
|
)
|
||||||
if not bHasError:
|
if not bHasError:
|
||||||
# 如需要大模型先处理一轮,添加相关处理后的日志情况
|
# If the LLM needs to process a turn first, add relevant processed log information
|
||||||
if len(response_message) > 0:
|
if len(response_message) > 0:
|
||||||
text_buff = "".join(response_message)
|
text_buff = "".join(response_message)
|
||||||
self.tts_MessageText = text_buff
|
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()
|
response_message.clear()
|
||||||
self.logger.bind(tag=TAG).debug(
|
self.logger.bind(tag=TAG).debug(
|
||||||
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
|
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
|
||||||
|
|
@ -809,16 +834,17 @@ class ConnectionHandler:
|
||||||
"arguments": function_arguments,
|
"arguments": function_arguments,
|
||||||
}
|
}
|
||||||
|
|
||||||
# 使用统一工具处理器处理所有工具调用
|
# Use unified tool handler to process all tool calls
|
||||||
result = asyncio.run_coroutine_threadsafe(
|
result = asyncio.run_coroutine_threadsafe(
|
||||||
self.func_handler.handle_llm_function_call(
|
self.func_handler.handle_llm_function_call(
|
||||||
self, function_call_data
|
self, function_call_data
|
||||||
),
|
),
|
||||||
self.loop,
|
self.loop,
|
||||||
).result()
|
).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:
|
if len(response_message) > 0:
|
||||||
text_buff = "".join(response_message)
|
text_buff = "".join(response_message)
|
||||||
self.tts_MessageText = text_buff
|
self.tts_MessageText = text_buff
|
||||||
|
|
@ -832,7 +858,7 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.llm_finish_task = True
|
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(
|
self.logger.bind(tag=TAG).debug(
|
||||||
lambda: json.dumps(
|
lambda: json.dumps(
|
||||||
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
|
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
|
||||||
|
|
@ -842,11 +868,12 @@ class ConnectionHandler:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _handle_function_result(self, result, function_call_data, depth):
|
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
|
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))
|
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
|
text = result.result
|
||||||
if text is not None and len(text) > 0:
|
if text is not None and len(text) > 0:
|
||||||
function_id = function_call_data["id"]
|
function_id = function_call_data["id"]
|
||||||
|
|
@ -881,53 +908,57 @@ class ConnectionHandler:
|
||||||
self.chat(text, tool_call=True, depth=depth + 1)
|
self.chat(text, tool_call=True, depth=depth + 1)
|
||||||
elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
|
elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
|
||||||
text = result.response if result.response else result.result
|
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))
|
self.dialogue.put(Message(role="assistant", content=text))
|
||||||
else:
|
else:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _report_worker(self):
|
def _report_worker(self):
|
||||||
"""聊天记录上报工作线程"""
|
"""Chat history reporting worker thread"""
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
# 从队列获取数据,设置超时以便定期检查停止事件
|
# Get data from the queue, set a timeout to periodically check the stop event
|
||||||
item = self.report_queue.get(timeout=1)
|
item = self.report_queue.get(timeout=1)
|
||||||
if item is None: # 检测毒丸对象
|
if item is None: # Detect the poison pill object
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
# 检查线程池状态
|
# Check the thread pool status
|
||||||
if self.executor is None:
|
if self.executor is None:
|
||||||
continue
|
continue
|
||||||
# 提交任务到线程池
|
# Submit the task to the thread pool
|
||||||
self.executor.submit(self._process_report, *item)
|
self.executor.submit(self._process_report, *item)
|
||||||
except Exception as e:
|
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:
|
except queue.Empty:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
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):
|
def _process_report(self, type, text, audio_data, report_time):
|
||||||
"""处理上报任务"""
|
"""Process the reporting task"""
|
||||||
try:
|
try:
|
||||||
# 执行上报(传入二进制数据)
|
# Execute the report (pass binary data)
|
||||||
report(self, type, text, audio_data, report_time)
|
report(self, type, text, audio_data, report_time)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
|
self.logger.bind(tag=TAG).error(
|
||||||
|
f"Report processing exception: {e}")
|
||||||
finally:
|
finally:
|
||||||
# 标记任务完成
|
# Mark the task as done
|
||||||
self.report_queue.task_done()
|
self.report_queue.task_done()
|
||||||
|
|
||||||
def clearSpeakStatus(self):
|
def clearSpeakStatus(self):
|
||||||
self.client_is_speaking = False
|
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):
|
async def close(self, ws=None):
|
||||||
"""资源清理方法"""
|
"""Resource cleanup method"""
|
||||||
try:
|
try:
|
||||||
# 取消超时任务
|
# Cancel the timeout task
|
||||||
if self.timeout_task and not self.timeout_task.done():
|
if self.timeout_task and not self.timeout_task.done():
|
||||||
self.timeout_task.cancel()
|
self.timeout_task.cancel()
|
||||||
try:
|
try:
|
||||||
|
|
@ -936,36 +967,36 @@ class ConnectionHandler:
|
||||||
pass
|
pass
|
||||||
self.timeout_task = None
|
self.timeout_task = None
|
||||||
|
|
||||||
# 清理工具处理器资源
|
# Clean up tool handler resources
|
||||||
if hasattr(self, "func_handler") and self.func_handler:
|
if hasattr(self, "func_handler") and self.func_handler:
|
||||||
try:
|
try:
|
||||||
await self.func_handler.cleanup()
|
await self.func_handler.cleanup()
|
||||||
except Exception as cleanup_error:
|
except Exception as cleanup_error:
|
||||||
self.logger.bind(tag=TAG).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:
|
if self.stop_event:
|
||||||
self.stop_event.set()
|
self.stop_event.set()
|
||||||
|
|
||||||
# 清空任务队列
|
# Clear task queues
|
||||||
self.clear_queues()
|
self.clear_queues()
|
||||||
|
|
||||||
# 关闭WebSocket连接
|
# Close the WebSocket connection
|
||||||
try:
|
try:
|
||||||
if ws:
|
if ws:
|
||||||
# 安全地检查WebSocket状态并关闭
|
# Safely check WebSocket state and close
|
||||||
try:
|
try:
|
||||||
if hasattr(ws, "closed") and not ws.closed:
|
if hasattr(ws, "closed") and not ws.closed:
|
||||||
await ws.close()
|
await ws.close()
|
||||||
elif hasattr(ws, "state") and ws.state.name != "CLOSED":
|
elif hasattr(ws, "state") and ws.state.name != "CLOSED":
|
||||||
await ws.close()
|
await ws.close()
|
||||||
else:
|
else:
|
||||||
# 如果没有closed属性,直接尝试关闭
|
# If no closed attribute, try to close directly
|
||||||
await ws.close()
|
await ws.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
# 如果关闭失败,忽略错误
|
# If closing fails, ignore the error
|
||||||
pass
|
pass
|
||||||
elif self.websocket:
|
elif self.websocket:
|
||||||
try:
|
try:
|
||||||
|
|
@ -980,43 +1011,45 @@ class ConnectionHandler:
|
||||||
):
|
):
|
||||||
await self.websocket.close()
|
await self.websocket.close()
|
||||||
else:
|
else:
|
||||||
# 如果没有closed属性,直接尝试关闭
|
# If no closed attribute, try to close directly
|
||||||
await self.websocket.close()
|
await self.websocket.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
# 如果关闭失败,忽略错误
|
# If closing fails, ignore the error
|
||||||
pass
|
pass
|
||||||
except Exception as ws_error:
|
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:
|
if self.tts:
|
||||||
await self.tts.close()
|
await self.tts.close()
|
||||||
|
|
||||||
# 最后关闭线程池(避免阻塞)
|
# Finally close thread pool (avoid blocking)
|
||||||
if self.executor:
|
if self.executor:
|
||||||
try:
|
try:
|
||||||
self.executor.shutdown(wait=False)
|
self.executor.shutdown(wait=False)
|
||||||
except Exception as executor_error:
|
except Exception as executor_error:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(
|
||||||
f"关闭线程池时出错: {executor_error}"
|
f"Error shutting down thread pool: {executor_error}"
|
||||||
)
|
)
|
||||||
self.executor = None
|
self.executor = None
|
||||||
|
|
||||||
self.logger.bind(tag=TAG).info("连接资源已释放")
|
self.logger.bind(tag=TAG).info("Connection resources released")
|
||||||
except Exception as e:
|
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:
|
finally:
|
||||||
# 确保停止事件被设置
|
# Ensure the stop event is set
|
||||||
if self.stop_event:
|
if self.stop_event:
|
||||||
self.stop_event.set()
|
self.stop_event.set()
|
||||||
|
|
||||||
def clear_queues(self):
|
def clear_queues(self):
|
||||||
"""清空所有任务队列"""
|
"""Clear all task queues"""
|
||||||
if self.tts:
|
if self.tts:
|
||||||
self.logger.bind(tag=TAG).debug(
|
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 [
|
for q in [
|
||||||
self.tts.tts_text_queue,
|
self.tts.tts_text_queue,
|
||||||
self.tts.tts_audio_queue,
|
self.tts.tts_audio_queue,
|
||||||
|
|
@ -1031,7 +1064,7 @@ class ConnectionHandler:
|
||||||
break
|
break
|
||||||
|
|
||||||
self.logger.bind(tag=TAG).debug(
|
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):
|
def reset_vad_states(self):
|
||||||
|
|
@ -1052,10 +1085,10 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
|
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
|
||||||
|
|
||||||
async def _check_timeout(self):
|
async def _check_timeout(self):
|
||||||
"""检查连接超时"""
|
"""Check for connection timeout"""
|
||||||
try:
|
try:
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
# 检查是否超时(只有在时间戳已初始化的情况下)
|
# Check for timeout (only if the timestamp has been initialized)
|
||||||
if self.last_activity_time > 0.0:
|
if self.last_activity_time > 0.0:
|
||||||
current_time = time.time() * 1000
|
current_time = time.time() * 1000
|
||||||
if (
|
if (
|
||||||
|
|
@ -1063,20 +1096,21 @@ class ConnectionHandler:
|
||||||
> self.timeout_seconds * 1000
|
> self.timeout_seconds * 1000
|
||||||
):
|
):
|
||||||
if not self.stop_event.is_set():
|
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()
|
self.stop_event.set()
|
||||||
# 使用 try-except 包装关闭操作,确保不会因为异常而阻塞
|
# Use try-except to wrap the close operation, ensuring no blocking due to exceptions
|
||||||
try:
|
try:
|
||||||
await self.close(self.websocket)
|
await self.close(self.websocket)
|
||||||
except Exception as close_error:
|
except Exception as close_error:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(
|
||||||
f"超时关闭连接时出错: {close_error}"
|
f"Error closing connection on timeout: {close_error}"
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
# 每10秒检查一次,避免过于频繁
|
# Check every 10 seconds to avoid being too frequent
|
||||||
await asyncio.sleep(10)
|
await asyncio.sleep(10)
|
||||||
except Exception as e:
|
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:
|
finally:
|
||||||
self.logger.bind(tag=TAG).info("超时检查任务已退出")
|
self.logger.bind(tag=TAG).info("Timeout check task has exited")
|
||||||
|
|
|
||||||
|
|
@ -5,10 +5,10 @@ TAG = __name__
|
||||||
|
|
||||||
async def handleAbortMessage(conn):
|
async def handleAbortMessage(conn):
|
||||||
conn.logger.bind(tag=TAG).info("Abort message received")
|
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.client_abort = True
|
||||||
conn.clear_queues()
|
conn.clear_queues()
|
||||||
# 打断客户端说话状态
|
# Interrupt client speaking state
|
||||||
await conn.websocket.send(
|
await conn.websocket.send(
|
||||||
json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id})
|
json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id})
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -21,24 +21,24 @@ WAKEUP_CONFIG = {
|
||||||
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
|
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
|
||||||
}
|
}
|
||||||
|
|
||||||
# 创建全局的唤醒词配置管理器
|
# Create global wakeup words configuration manager
|
||||||
wakeup_words_config = WakeupWordsConfig()
|
wakeup_words_config = WakeupWordsConfig()
|
||||||
|
|
||||||
# 用于防止并发调用wakeupWordsResponse的锁
|
# Lock to prevent concurrent calls to wakeupWordsResponse
|
||||||
_wakeup_response_lock = asyncio.Lock()
|
_wakeup_response_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
async def handleHelloMessage(conn, msg_json):
|
async def handleHelloMessage(conn, msg_json):
|
||||||
"""处理hello消息"""
|
"""Handle hello message"""
|
||||||
audio_params = msg_json.get("audio_params")
|
audio_params = msg_json.get("audio_params")
|
||||||
if audio_params:
|
if audio_params:
|
||||||
format = audio_params.get("format")
|
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.audio_format = format
|
||||||
conn.welcome_msg["audio_params"] = audio_params
|
conn.welcome_msg["audio_params"] = audio_params
|
||||||
features = msg_json.get("features")
|
features = msg_json.get("features")
|
||||||
if features:
|
if features:
|
||||||
conn.logger.bind(tag=TAG).info(f"客户端特性: {features}")
|
conn.logger.bind(tag=TAG).info(f"Client features: {features}")
|
||||||
conn.features = features
|
conn.features = features
|
||||||
|
|
||||||
# Handle both list and dictionary formats for features
|
# Handle both list and dictionary formats for features
|
||||||
|
|
@ -49,11 +49,11 @@ async def handleHelloMessage(conn, msg_json):
|
||||||
has_mcp = features.get("mcp", False)
|
has_mcp = features.get("mcp", False)
|
||||||
|
|
||||||
if has_mcp:
|
if has_mcp:
|
||||||
conn.logger.bind(tag=TAG).info("客户端支持MCP")
|
conn.logger.bind(tag=TAG).info("Client supports MCP")
|
||||||
conn.mcp_client = MCPClient()
|
conn.mcp_client = MCPClient()
|
||||||
# 发送初始化
|
# Send initialization
|
||||||
asyncio.create_task(send_mcp_initialize_message(conn))
|
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))
|
asyncio.create_task(send_mcp_tools_list_request(conn))
|
||||||
|
|
||||||
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
||||||
|
|
@ -74,12 +74,12 @@ async def checkWakeupWords(conn, text):
|
||||||
conn.just_woken_up = True
|
conn.just_woken_up = True
|
||||||
await send_stt_message(conn, text)
|
await send_stt_message(conn, text)
|
||||||
|
|
||||||
# 获取当前音色
|
# Get current voice
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
voice = getattr(conn.tts, "voice", "default")
|
||||||
if not voice:
|
if not voice:
|
||||||
voice = "default"
|
voice = "default"
|
||||||
|
|
||||||
# 获取唤醒词回复配置
|
# Get wakeup words reply configuration
|
||||||
response = wakeup_words_config.get_wakeup_response(voice)
|
response = wakeup_words_config.get_wakeup_response(voice)
|
||||||
if not response or not response.get("file_path"):
|
if not response or not response.get("file_path"):
|
||||||
response = {
|
response = {
|
||||||
|
|
@ -89,18 +89,19 @@ async def checkWakeupWords(conn, text):
|
||||||
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
|
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
|
||||||
}
|
}
|
||||||
|
|
||||||
# 播放唤醒词回复
|
# Play wakeup words reply
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
opus_packets, _ = audio_to_data(response.get("file_path"))
|
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.FIRST, opus_packets, response.get("text"))
|
||||||
await sendAudioMessage(conn, SentenceType.LAST, [], None)
|
await sendAudioMessage(conn, SentenceType.LAST, [], None)
|
||||||
|
|
||||||
# 补充对话
|
# Add to dialogue
|
||||||
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
|
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 time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
|
||||||
if not _wakeup_response_lock.locked():
|
if not _wakeup_response_lock.locked():
|
||||||
asyncio.create_task(wakeupWordsResponse(conn))
|
asyncio.create_task(wakeupWordsResponse(conn))
|
||||||
|
|
@ -112,38 +113,38 @@ async def wakeupWordsResponse(conn):
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 尝试获取锁,如果获取不到就返回
|
# Try to acquire lock, return if cannot acquire
|
||||||
if not await _wakeup_response_lock.acquire():
|
if not await _wakeup_response_lock.acquire():
|
||||||
return
|
return
|
||||||
|
|
||||||
# 生成唤醒词回复
|
# Generate wakeup words reply
|
||||||
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
|
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
|
||||||
question = (
|
question = (
|
||||||
"此刻用户正在和你说```"
|
"The user is currently saying ```"
|
||||||
+ wakeup_word
|
+ 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)
|
result = conn.llm.response_no_stream(conn.config["prompt"], question)
|
||||||
if not result or len(result) == 0:
|
if not result or len(result) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
# 生成TTS音频
|
# Generate TTS audio
|
||||||
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
|
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
|
||||||
if not tts_result:
|
if not tts_result:
|
||||||
return
|
return
|
||||||
|
|
||||||
# 获取当前音色
|
# Get current voice
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
voice = getattr(conn.tts, "voice", "default")
|
||||||
|
|
||||||
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
|
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
|
||||||
file_path = wakeup_words_config.generate_file_path(voice)
|
file_path = wakeup_words_config.generate_file_path(voice)
|
||||||
with open(file_path, "wb") as f:
|
with open(file_path, "wb") as f:
|
||||||
f.write(wav_bytes)
|
f.write(wav_bytes)
|
||||||
# 更新配置
|
# Update configuration
|
||||||
wakeup_words_config.update_wakeup_response(voice, file_path, result)
|
wakeup_words_config.update_wakeup_response(voice, file_path, result)
|
||||||
finally:
|
finally:
|
||||||
# 确保在任何情况下都释放锁
|
# Ensure lock is released in any case
|
||||||
if _wakeup_response_lock.locked():
|
if _wakeup_response_lock.locked():
|
||||||
_wakeup_response_lock.release()
|
_wakeup_response_lock.release()
|
||||||
|
|
|
||||||
|
|
@ -13,44 +13,47 @@ TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handle_user_intent(conn, text):
|
async def handle_user_intent(conn, text):
|
||||||
# 预处理输入文本,处理可能的JSON格式
|
# Preprocess input text, handle possible JSON format
|
||||||
try:
|
try:
|
||||||
if text.strip().startswith('{') and text.strip().endswith('}'):
|
if text.strip().startswith('{') and text.strip().endswith('}'):
|
||||||
parsed_data = json.loads(text)
|
parsed_data = json.loads(text)
|
||||||
if isinstance(parsed_data, dict) and "content" in parsed_data:
|
if isinstance(parsed_data, dict) and "content" in parsed_data:
|
||||||
text = parsed_data["content"] # 提取content用于意图分析
|
# Extract content for intent analysis
|
||||||
conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息
|
text = parsed_data["content"]
|
||||||
|
conn.current_speaker = parsed_data.get(
|
||||||
|
"speaker") # Preserve speaker information
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 检查是否有明确的退出命令
|
# Check if there is an explicit exit command
|
||||||
filtered_text = remove_punctuation_and_length(text)[1]
|
filtered_text = remove_punctuation_and_length(text)[1]
|
||||||
if await check_direct_exit(conn, filtered_text):
|
if await check_direct_exit(conn, filtered_text):
|
||||||
return True
|
return True
|
||||||
# 检查是否是唤醒词
|
# Check if it's a wake-up word
|
||||||
if await checkWakeupWords(conn, filtered_text):
|
if await checkWakeupWords(conn, filtered_text):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
if conn.intent_type == "function_call":
|
if conn.intent_type == "function_call":
|
||||||
# 使用支持function calling的聊天方法,不再进行意图分析
|
# Use chat method that supports function calling, no longer perform intent analysis
|
||||||
return False
|
return False
|
||||||
# 使用LLM进行意图分析
|
# Use LLM for intent analysis
|
||||||
intent_result = await analyze_intent_with_llm(conn, text)
|
intent_result = await analyze_intent_with_llm(conn, text)
|
||||||
if not intent_result:
|
if not intent_result:
|
||||||
return False
|
return False
|
||||||
# 会话开始时生成sentence_id
|
# Generate sentence_id at the beginning of the conversation
|
||||||
conn.sentence_id = str(uuid.uuid4().hex)
|
conn.sentence_id = str(uuid.uuid4().hex)
|
||||||
# 处理各种意图
|
# Handle various intents
|
||||||
return await process_intent_result(conn, intent_result, text)
|
return await process_intent_result(conn, intent_result, text)
|
||||||
|
|
||||||
|
|
||||||
async def check_direct_exit(conn, text):
|
async def check_direct_exit(conn, text):
|
||||||
"""检查是否有明确的退出命令"""
|
"""Check if there is an explicit exit command"""
|
||||||
_, text = remove_punctuation_and_length(text)
|
_, text = remove_punctuation_and_length(text)
|
||||||
cmd_exit = conn.cmd_exit
|
cmd_exit = conn.cmd_exit
|
||||||
for cmd in cmd_exit:
|
for cmd in cmd_exit:
|
||||||
if text == cmd:
|
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 send_stt_message(conn, text)
|
||||||
await conn.close()
|
await conn.close()
|
||||||
return True
|
return True
|
||||||
|
|
@ -58,33 +61,34 @@ async def check_direct_exit(conn, text):
|
||||||
|
|
||||||
|
|
||||||
async def analyze_intent_with_llm(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:
|
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
|
return None
|
||||||
|
|
||||||
# 对话历史记录
|
# Conversation history records
|
||||||
dialogue = conn.dialogue
|
dialogue = conn.dialogue
|
||||||
try:
|
try:
|
||||||
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
|
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
|
||||||
return intent_result
|
return intent_result
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def process_intent_result(conn, intent_result, original_text):
|
async def process_intent_result(conn, intent_result, original_text):
|
||||||
"""处理意图识别结果"""
|
"""Process intent recognition results"""
|
||||||
try:
|
try:
|
||||||
# 尝试将结果解析为JSON
|
# Try to parse the result as JSON
|
||||||
intent_data = json.loads(intent_result)
|
intent_data = json.loads(intent_result)
|
||||||
|
|
||||||
# 检查是否有function_call
|
# Check if there is a function_call
|
||||||
if "function_call" in intent_data:
|
if "function_call" in intent_data:
|
||||||
# 直接从意图识别获取了function_call
|
# Directly obtained function_call from intent recognition
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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"]
|
function_name = intent_data["function_call"]["name"]
|
||||||
if function_name == "continue_chat":
|
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"]
|
function_args = intent_data["function_call"]["arguments"]
|
||||||
if function_args is None:
|
if function_args is None:
|
||||||
function_args = {}
|
function_args = {}
|
||||||
# 确保参数是字符串格式的JSON
|
# Ensure parameters are in string format JSON
|
||||||
if isinstance(function_args, dict):
|
if isinstance(function_args, dict):
|
||||||
function_args = json.dumps(function_args)
|
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)
|
await send_stt_message(conn, original_text)
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
|
|
||||||
# 使用executor执行函数调用和结果处理
|
# Use executor to execute function calls and result processing
|
||||||
def process_function_call():
|
def process_function_call():
|
||||||
conn.dialogue.put(Message(role="user", content=original_text))
|
conn.dialogue.put(Message(role="user", content=original_text))
|
||||||
|
|
||||||
# 使用统一工具处理器处理所有工具调用
|
# Use unified tool handler to process all tool calls
|
||||||
try:
|
try:
|
||||||
result = asyncio.run_coroutine_threadsafe(
|
result = asyncio.run_coroutine_threadsafe(
|
||||||
conn.func_handler.handle_llm_function_call(
|
conn.func_handler.handle_llm_function_call(
|
||||||
|
|
@ -121,20 +125,21 @@ async def process_intent_result(conn, intent_result, original_text):
|
||||||
conn.loop,
|
conn.loop,
|
||||||
).result()
|
).result()
|
||||||
except Exception as e:
|
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(
|
result = ActionResponse(
|
||||||
action=Action.ERROR, result=str(e), response=str(e)
|
action=Action.ERROR, result=str(e), response=str(e)
|
||||||
)
|
)
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
if result.action == Action.RESPONSE: # 直接回复前端
|
if result.action == Action.RESPONSE: # Directly reply to frontend
|
||||||
text = result.response
|
text = result.response
|
||||||
if text is not None:
|
if text is not None:
|
||||||
speak_txt(conn, text)
|
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
|
text = result.result
|
||||||
conn.dialogue.put(Message(role="tool", content=text))
|
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:
|
if llm_result is None:
|
||||||
llm_result = text
|
llm_result = text
|
||||||
speak_txt(conn, llm_result)
|
speak_txt(conn, llm_result)
|
||||||
|
|
@ -147,19 +152,19 @@ async def process_intent_result(conn, intent_result, original_text):
|
||||||
speak_txt(conn, text)
|
speak_txt(conn, text)
|
||||||
elif function_name != "play_music":
|
elif function_name != "play_music":
|
||||||
# For backward compatibility with original code
|
# For backward compatibility with original code
|
||||||
# 获取当前最新的文本索引
|
# Get the current latest text index
|
||||||
text = result.response
|
text = result.response
|
||||||
if text is None:
|
if text is None:
|
||||||
text = result.result
|
text = result.result
|
||||||
if text is not None:
|
if text is not None:
|
||||||
speak_txt(conn, text)
|
speak_txt(conn, text)
|
||||||
|
|
||||||
# 将函数执行放在线程池中
|
# Put function execution in thread pool
|
||||||
conn.executor.submit(process_function_call)
|
conn.executor.submit(process_function_call)
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
except json.JSONDecodeError as e:
|
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
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,53 +12,55 @@ TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handleAudioMessage(conn, audio):
|
async def handleAudioMessage(conn, audio):
|
||||||
# 当前片段是否有人说话
|
# Whether the current segment has someone speaking
|
||||||
have_voice = conn.vad.is_vad(conn, audio)
|
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:
|
if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
|
||||||
have_voice = False
|
have_voice = False
|
||||||
# 设置一个短暂延迟后恢复VAD检测
|
# Set a brief delay before resuming VAD detection
|
||||||
conn.asr_audio.clear()
|
conn.asr_audio.clear()
|
||||||
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
|
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
|
return
|
||||||
|
|
||||||
if have_voice:
|
if have_voice:
|
||||||
if conn.client_is_speaking:
|
if conn.client_is_speaking:
|
||||||
await handleAbortMessage(conn)
|
await handleAbortMessage(conn)
|
||||||
# 设备长时间空闲检测,用于say goodbye
|
# Device long-term idle detection, used for say goodbye
|
||||||
await no_voice_close_connect(conn, have_voice)
|
await no_voice_close_connect(conn, have_voice)
|
||||||
# 接收音频
|
# Receive audio
|
||||||
await conn.asr.receive_audio(conn, audio, have_voice)
|
await conn.asr.receive_audio(conn, audio, have_voice)
|
||||||
|
|
||||||
|
|
||||||
async def resume_vad_detection(conn):
|
async def resume_vad_detection(conn):
|
||||||
# 等待2秒后恢复VAD检测
|
# Wait 2 seconds before resuming VAD detection
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
conn.just_woken_up = False
|
conn.just_woken_up = False
|
||||||
|
|
||||||
|
|
||||||
async def startToChat(conn, text):
|
async def startToChat(conn, text):
|
||||||
# 检查输入是否是JSON格式(包含说话人信息)
|
# Check if input is in JSON format (containing speaker information)
|
||||||
speaker_name = None
|
speaker_name = None
|
||||||
actual_text = text
|
actual_text = text
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 尝试解析JSON格式的输入
|
# Try to parse JSON format input
|
||||||
if text.strip().startswith('{') and text.strip().endswith('}'):
|
if text.strip().startswith('{') and text.strip().endswith('}'):
|
||||||
data = json.loads(text)
|
data = json.loads(text)
|
||||||
if 'speaker' in data and 'content' in data:
|
if 'speaker' in data and 'content' in data:
|
||||||
speaker_name = data['speaker']
|
speaker_name = data['speaker']
|
||||||
actual_text = data['content']
|
actual_text = data['content']
|
||||||
conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}")
|
conn.logger.bind(tag=TAG).info(
|
||||||
|
f"Parsed speaker information: {speaker_name}")
|
||||||
|
|
||||||
# 直接使用JSON格式的文本,不解析
|
# Use JSON format text directly, do not parse
|
||||||
actual_text = text
|
actual_text = text
|
||||||
except (json.JSONDecodeError, KeyError):
|
except (json.JSONDecodeError, KeyError):
|
||||||
# 如果解析失败,继续使用原始文本
|
# If parsing fails, continue using original text
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 保存说话人信息到连接对象
|
# Save speaker information to connection object
|
||||||
if speaker_name:
|
if speaker_name:
|
||||||
conn.current_speaker = speaker_name
|
conn.current_speaker = speaker_name
|
||||||
else:
|
else:
|
||||||
|
|
@ -68,7 +70,7 @@ async def startToChat(conn, text):
|
||||||
await check_bind_device(conn)
|
await check_bind_device(conn)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 如果当日的输出字数大于限定的字数
|
# If the daily output word count exceeds the limit
|
||||||
if conn.max_output_size > 0:
|
if conn.max_output_size > 0:
|
||||||
if check_device_output_limit(
|
if check_device_output_limit(
|
||||||
conn.headers.get("device-id"), conn.max_output_size
|
conn.headers.get("device-id"), conn.max_output_size
|
||||||
|
|
@ -78,14 +80,14 @@ async def startToChat(conn, text):
|
||||||
if conn.client_is_speaking:
|
if conn.client_is_speaking:
|
||||||
await handleAbortMessage(conn)
|
await handleAbortMessage(conn)
|
||||||
|
|
||||||
# 首先进行意图分析,使用实际文本内容
|
# First perform intent analysis, using actual text content
|
||||||
intent_handled = await handle_user_intent(conn, actual_text)
|
intent_handled = await handle_user_intent(conn, actual_text)
|
||||||
|
|
||||||
if intent_handled:
|
if intent_handled:
|
||||||
# 如果意图已被处理,不再进行聊天
|
# If intent has been handled, no longer proceed with chat
|
||||||
return
|
return
|
||||||
|
|
||||||
# 意图未被处理,继续常规聊天流程,使用实际文本内容
|
# Intent not handled, continue with regular chat flow, using actual text content
|
||||||
await send_stt_message(conn, actual_text)
|
await send_stt_message(conn, actual_text)
|
||||||
conn.executor.submit(conn.chat, 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:
|
if have_voice:
|
||||||
conn.last_activity_time = time.time() * 1000
|
conn.last_activity_time = time.time() * 1000
|
||||||
return
|
return
|
||||||
# 只有在已经初始化过时间戳的情况下才进行超时检查
|
# Only perform timeout check when timestamp has been initialized
|
||||||
if conn.last_activity_time > 0.0:
|
if conn.last_activity_time > 0.0:
|
||||||
no_voice_time = time.time() * 1000 - conn.last_activity_time
|
no_voice_time = time.time() * 1000 - conn.last_activity_time
|
||||||
close_connection_no_voice_time = int(
|
close_connection_no_voice_time = int(
|
||||||
|
|
@ -108,17 +110,18 @@ async def no_voice_close_connect(conn, have_voice):
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
end_prompt = conn.config.get("end_prompt", {})
|
end_prompt = conn.config.get("end_prompt", {})
|
||||||
if end_prompt and end_prompt.get("enable", True) is False:
|
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()
|
await conn.close()
|
||||||
return
|
return
|
||||||
prompt = end_prompt.get("prompt")
|
prompt = end_prompt.get("prompt")
|
||||||
if not 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)
|
await startToChat(conn, prompt)
|
||||||
|
|
||||||
|
|
||||||
async def max_out_size(conn):
|
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)
|
await send_stt_message(conn, text)
|
||||||
file_path = "config/assets/max_output_size.wav"
|
file_path = "config/assets/max_output_size.wav"
|
||||||
opus_packets, _ = audio_to_data(file_path)
|
opus_packets, _ = audio_to_data(file_path)
|
||||||
|
|
@ -128,34 +131,37 @@ async def max_out_size(conn):
|
||||||
|
|
||||||
async def check_bind_device(conn):
|
async def check_bind_device(conn):
|
||||||
if conn.bind_code:
|
if conn.bind_code:
|
||||||
# 确保bind_code是6位数字
|
# Ensure bind_code is a 6-digit number
|
||||||
if len(conn.bind_code) != 6:
|
if len(conn.bind_code) != 6:
|
||||||
conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}")
|
conn.logger.bind(tag=TAG).error(
|
||||||
text = "绑定码格式错误,请检查配置。"
|
f"Invalid binding code format: {conn.bind_code}")
|
||||||
|
text = "Binding code format error, please check configuration."
|
||||||
await send_stt_message(conn, text)
|
await send_stt_message(conn, text)
|
||||||
return
|
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)
|
await send_stt_message(conn, text)
|
||||||
|
|
||||||
# 播放提示音
|
# Play notification sound
|
||||||
music_path = "config/assets/bind_code.wav"
|
music_path = "config/assets/bind_code.wav"
|
||||||
opus_packets, _ = audio_to_data(music_path)
|
opus_packets, _ = audio_to_data(music_path)
|
||||||
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
|
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
|
||||||
|
|
||||||
# 逐个播放数字
|
# Play digits one by one
|
||||||
for i in range(6): # 确保只播放6位数字
|
for i in range(6): # Ensure only 6 digits are played
|
||||||
try:
|
try:
|
||||||
digit = conn.bind_code[i]
|
digit = conn.bind_code[i]
|
||||||
num_path = f"config/assets/bind_code/{digit}.wav"
|
num_path = f"config/assets/bind_code/{digit}.wav"
|
||||||
num_packets, _ = audio_to_data(num_path)
|
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:
|
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
|
continue
|
||||||
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
|
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
else:
|
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)
|
await send_stt_message(conn, text)
|
||||||
music_path = "config/assets/bind_not_found.wav"
|
music_path = "config/assets/bind_not_found.wav"
|
||||||
opus_packets, _ = audio_to_data(music_path)
|
opus_packets, _ = audio_to_data(music_path)
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,12 @@
|
||||||
"""
|
"""
|
||||||
TTS上报功能已集成到ConnectionHandler类中。
|
TTS reporting functionality has been integrated into the ConnectionHandler class.
|
||||||
|
|
||||||
上报功能包括:
|
Reporting functionality includes:
|
||||||
1. 每个连接对象拥有自己的上报队列和处理线程
|
1. Each connection object has its own reporting queue and processing thread
|
||||||
2. 上报线程的生命周期与连接对象绑定
|
2. The reporting thread's lifecycle is bound to the connection object
|
||||||
3. 使用ConnectionHandler.enqueue_tts_report方法进行上报
|
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
|
import time
|
||||||
|
|
@ -19,21 +19,21 @@ TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
def report(conn, type, text, opus_data, report_time):
|
def report(conn, type, text, opus_data, report_time):
|
||||||
"""执行聊天记录上报操作
|
"""Execute chat history reporting operation
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
conn: 连接对象
|
conn: Connection object
|
||||||
type: 上报类型,1为用户,2为智能体
|
type: Report type, 1 for user, 2 for agent
|
||||||
text: 合成文本
|
text: Synthesized text
|
||||||
opus_data: opus音频数据
|
opus_data: Opus audio data
|
||||||
report_time: 上报时间
|
report_time: Report time
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if opus_data:
|
if opus_data:
|
||||||
audio_data = opus_to_wav(conn, opus_data)
|
audio_data = opus_to_wav(conn, opus_data)
|
||||||
else:
|
else:
|
||||||
audio_data = None
|
audio_data = None
|
||||||
# 执行上报
|
# Execute reporting
|
||||||
manage_report(
|
manage_report(
|
||||||
mac_address=conn.device_id,
|
mac_address=conn.device_id,
|
||||||
session_id=conn.session_id,
|
session_id=conn.session_id,
|
||||||
|
|
@ -43,20 +43,20 @@ def report(conn, type, text, opus_data, report_time):
|
||||||
report_time=report_time,
|
report_time=report_time,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
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):
|
def opus_to_wav(conn, opus_data):
|
||||||
"""将Opus数据转换为WAV格式的字节流
|
"""Convert Opus data to WAV format byte stream
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
output_dir: 输出目录(保留参数以保持接口兼容)
|
output_dir: Output directory (parameter retained for interface compatibility)
|
||||||
opus_data: opus音频数据
|
opus_data: Opus audio data
|
||||||
|
|
||||||
Returns:
|
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 = []
|
pcm_data = []
|
||||||
|
|
||||||
for opus_packet in opus_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_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
||||||
pcm_data.append(pcm_frame)
|
pcm_data.append(pcm_frame)
|
||||||
except opuslib_next.OpusError as e:
|
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:
|
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)
|
pcm_data_bytes = b"".join(pcm_data)
|
||||||
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
|
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
|
||||||
|
|
||||||
# WAV文件头
|
# WAV file header
|
||||||
wav_header = bytearray()
|
wav_header = bytearray()
|
||||||
wav_header.extend(b"RIFF") # ChunkID
|
wav_header.extend(b"RIFF") # ChunkID
|
||||||
wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize
|
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(b"data") # Subchunk2ID
|
||||||
wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size
|
wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size
|
||||||
|
|
||||||
# 返回完整的WAV数据
|
# Return complete WAV data
|
||||||
return bytes(wav_header) + pcm_data_bytes
|
return bytes(wav_header) + pcm_data_bytes
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -98,27 +98,27 @@ def enqueue_tts_report(conn, text, opus_data):
|
||||||
return
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
"""将TTS数据加入上报队列
|
"""Add TTS data to reporting queue
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
conn: 连接对象
|
conn: Connection object
|
||||||
text: 合成文本
|
text: Synthesized text
|
||||||
opus_data: opus音频数据
|
opus_data: Opus audio data
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
|
# Use connection object's queue, pass text and binary data instead of file path
|
||||||
if conn.chat_history_conf == 2:
|
if conn.chat_history_conf == 2:
|
||||||
conn.report_queue.put((2, text, opus_data, int(time.time())))
|
conn.report_queue.put((2, text, opus_data, int(time.time())))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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:
|
else:
|
||||||
conn.report_queue.put((2, text, None, int(time.time())))
|
conn.report_queue.put((2, text, None, int(time.time())))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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:
|
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):
|
def enqueue_asr_report(conn, text, opus_data):
|
||||||
|
|
@ -126,24 +126,24 @@ def enqueue_asr_report(conn, text, opus_data):
|
||||||
return
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
"""将ASR数据加入上报队列
|
"""Add ASR data to reporting queue
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
conn: 连接对象
|
conn: Connection object
|
||||||
text: 合成文本
|
text: Synthesized text
|
||||||
opus_data: opus音频数据
|
opus_data: Opus audio data
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
|
# Use connection object's queue, pass text and binary data instead of file path
|
||||||
if conn.chat_history_conf == 2:
|
if conn.chat_history_conf == 2:
|
||||||
conn.report_queue.put((1, text, opus_data, int(time.time())))
|
conn.report_queue.put((1, text, opus_data, int(time.time())))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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:
|
else:
|
||||||
conn.report_queue.put((1, text, None, int(time.time())))
|
conn.report_queue.put((1, text, None, int(time.time())))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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:
|
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}")
|
||||||
|
|
@ -8,12 +8,13 @@ TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def sendAudioMessage(conn, sentenceType, audios, text):
|
async def sendAudioMessage(conn, sentenceType, audios, text):
|
||||||
# 发送句子开始消息
|
# Send sentence start message
|
||||||
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
|
conn.logger.bind(tag=TAG).info(
|
||||||
|
f"Send audio message: {sentenceType}, {text}")
|
||||||
|
|
||||||
pre_buffer = False
|
pre_buffer = False
|
||||||
if conn.tts.tts_audio_first_sentence:
|
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
|
conn.tts.tts_audio_first_sentence = False
|
||||||
pre_buffer = True
|
pre_buffer = True
|
||||||
|
|
||||||
|
|
@ -21,7 +22,7 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
|
||||||
|
|
||||||
await sendAudio(conn, audios, pre_buffer)
|
await sendAudio(conn, audios, pre_buffer)
|
||||||
|
|
||||||
# 发送结束消息(如果是最后一个文本)
|
# Send end message (if it's the last text)
|
||||||
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
||||||
await send_tts_message(conn, "stop", None)
|
await send_tts_message(conn, "stop", None)
|
||||||
conn.client_is_speaking = False
|
conn.client_is_speaking = False
|
||||||
|
|
@ -29,16 +30,17 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
||||||
|
|
||||||
# 播放音频
|
# Play audio
|
||||||
async def sendAudio(conn, audios, pre_buffer=True):
|
async def sendAudio(conn, audios, pre_buffer=True):
|
||||||
if audios is None or len(audios) == 0:
|
if audios is None or len(audios) == 0:
|
||||||
return
|
return
|
||||||
# 流控参数优化
|
# Flow control parameter optimization
|
||||||
frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码
|
# Frame duration (milliseconds), matching Opus encoding
|
||||||
|
frame_duration = 60
|
||||||
start_time = time.perf_counter()
|
start_time = time.perf_counter()
|
||||||
play_position = 0
|
play_position = 0
|
||||||
|
|
||||||
# 仅当第一句话时执行预缓冲
|
# Execute pre-buffering only for the first sentence
|
||||||
if pre_buffer:
|
if pre_buffer:
|
||||||
pre_buffer_frames = min(3, len(audios))
|
pre_buffer_frames = min(3, len(audios))
|
||||||
for i in range(pre_buffer_frames):
|
for i in range(pre_buffer_frames):
|
||||||
|
|
@ -47,15 +49,15 @@ async def sendAudio(conn, audios, pre_buffer=True):
|
||||||
else:
|
else:
|
||||||
remaining_audios = audios
|
remaining_audios = audios
|
||||||
|
|
||||||
# 播放剩余音频帧
|
# Play remaining audio frames
|
||||||
for opus_packet in remaining_audios:
|
for opus_packet in remaining_audios:
|
||||||
if conn.client_abort:
|
if conn.client_abort:
|
||||||
break
|
break
|
||||||
|
|
||||||
# 重置没有声音的状态
|
# Reset no-voice state
|
||||||
conn.last_activity_time = time.time() * 1000
|
conn.last_activity_time = time.time() * 1000
|
||||||
|
|
||||||
# 计算预期发送时间
|
# Calculate expected send time
|
||||||
expected_time = start_time + (play_position / 1000)
|
expected_time = start_time + (play_position / 1000)
|
||||||
current_time = time.perf_counter()
|
current_time = time.perf_counter()
|
||||||
delay = expected_time - current_time
|
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):
|
async def send_tts_message(conn, state, text=None):
|
||||||
"""发送 TTS 状态消息"""
|
"""Send TTS status message"""
|
||||||
message = {"type": "tts", "state": state, "session_id": conn.session_id}
|
message = {"type": "tts", "state": state, "session_id": conn.session_id}
|
||||||
if text is not None:
|
if text is not None:
|
||||||
message["text"] = textUtils.check_emoji(text)
|
message["text"] = textUtils.check_emoji(text)
|
||||||
|
|
||||||
# TTS播放结束
|
# TTS playback ended
|
||||||
if state == "stop":
|
if state == "stop":
|
||||||
# 播放提示音
|
# Play notification sound
|
||||||
tts_notify = conn.config.get("enable_stop_tts_notify", False)
|
tts_notify = conn.config.get("enable_stop_tts_notify", False)
|
||||||
if tts_notify:
|
if tts_notify:
|
||||||
stop_tts_notify_voice = conn.config.get(
|
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)
|
audios, _ = conn.tts.audio_to_opus_data(stop_tts_notify_voice)
|
||||||
await sendAudio(conn, audios)
|
await sendAudio(conn, audios)
|
||||||
# 清除服务端讲话状态
|
# Clear server speaking status
|
||||||
conn.clearSpeakStatus()
|
conn.clearSpeakStatus()
|
||||||
|
|
||||||
# 发送消息到客户端
|
# Send message to client
|
||||||
await conn.websocket.send(json.dumps(message))
|
await conn.websocket.send(json.dumps(message))
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -96,26 +98,27 @@ async def send_stt_message(conn, text):
|
||||||
await send_tts_message(conn, "start")
|
await send_tts_message(conn, "start")
|
||||||
return
|
return
|
||||||
|
|
||||||
"""发送 STT 状态消息"""
|
"""Send STT status message"""
|
||||||
|
|
||||||
# 解析JSON格式,提取实际的用户说话内容
|
# Parse JSON format, extract actual user speech content
|
||||||
display_text = text
|
display_text = text
|
||||||
try:
|
try:
|
||||||
# 尝试解析JSON格式
|
# Try to parse JSON format
|
||||||
if text.strip().startswith('{') and text.strip().endswith('}'):
|
if text.strip().startswith('{') and text.strip().endswith('}'):
|
||||||
parsed_data = json.loads(text)
|
parsed_data = json.loads(text)
|
||||||
if isinstance(parsed_data, dict) and "content" in parsed_data:
|
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"]
|
display_text = parsed_data["content"]
|
||||||
# 保存说话人信息到conn对象
|
# Save speaker information to conn object
|
||||||
if "speaker" in parsed_data:
|
if "speaker" in parsed_data:
|
||||||
conn.current_speaker = parsed_data["speaker"]
|
conn.current_speaker = parsed_data["speaker"]
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
# 如果不是JSON格式,直接使用原始文本
|
# If it's not JSON format, use original text directly
|
||||||
display_text = text
|
display_text = text
|
||||||
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
|
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
|
||||||
await conn.websocket.send(
|
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
|
conn.client_is_speaking = True
|
||||||
await send_tts_message(conn, "start")
|
await send_tts_message(conn, "start")
|
||||||
|
|
@ -14,25 +14,28 @@ TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handleTextMessage(conn, message):
|
async def handleTextMessage(conn, message):
|
||||||
"""处理文本消息"""
|
"""Handle text messages"""
|
||||||
try:
|
try:
|
||||||
msg_json = json.loads(message)
|
msg_json = json.loads(message)
|
||||||
if isinstance(msg_json, int):
|
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)
|
await conn.websocket.send(message)
|
||||||
return
|
return
|
||||||
if msg_json["type"] == "hello":
|
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)
|
await handleHelloMessage(conn, msg_json)
|
||||||
elif msg_json["type"] == "abort":
|
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)
|
await handleAbortMessage(conn)
|
||||||
elif msg_json["type"] == "listen":
|
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:
|
if "mode" in msg_json:
|
||||||
conn.client_listen_mode = msg_json["mode"]
|
conn.client_listen_mode = msg_json["mode"]
|
||||||
conn.logger.bind(tag=TAG).debug(
|
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":
|
if msg_json["state"] == "start":
|
||||||
conn.client_have_voice = True
|
conn.client_have_voice = True
|
||||||
|
|
@ -47,77 +50,81 @@ async def handleTextMessage(conn, message):
|
||||||
conn.asr_audio.clear()
|
conn.asr_audio.clear()
|
||||||
if "text" in msg_json:
|
if "text" in msg_json:
|
||||||
conn.last_activity_time = time.time() * 1000
|
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(
|
filtered_len, filtered_text = remove_punctuation_and_length(
|
||||||
original_text
|
original_text
|
||||||
)
|
)
|
||||||
|
|
||||||
# 识别是否是唤醒词
|
# Identify if it's a wake-up word
|
||||||
is_wakeup_words = filtered_text in conn.config.get("wakeup_words")
|
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)
|
enable_greeting = conn.config.get("enable_greeting", True)
|
||||||
|
|
||||||
if is_wakeup_words and not enable_greeting:
|
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_stt_message(conn, original_text)
|
||||||
await send_tts_message(conn, "stop", None)
|
await send_tts_message(conn, "stop", None)
|
||||||
conn.client_is_speaking = False
|
conn.client_is_speaking = False
|
||||||
elif is_wakeup_words:
|
elif is_wakeup_words:
|
||||||
conn.just_woken_up = True
|
conn.just_woken_up = True
|
||||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
# Report plain text data (reuse ASR reporting function, but provide no audio data)
|
||||||
enqueue_asr_report(conn, "嘿,你好呀", [])
|
enqueue_asr_report(conn, "Hey, hello there", [])
|
||||||
await startToChat(conn, "嘿,你好呀")
|
await startToChat(conn, "Hey, hello there")
|
||||||
else:
|
else:
|
||||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
# Report plain text data (reuse ASR reporting function, but provide no audio data)
|
||||||
enqueue_asr_report(conn, original_text, [])
|
enqueue_asr_report(conn, original_text, [])
|
||||||
# 否则需要LLM对文字内容进行答复
|
# Otherwise, need LLM to respond to text content
|
||||||
await startToChat(conn, original_text)
|
await startToChat(conn, original_text)
|
||||||
elif msg_json["type"] == "iot":
|
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:
|
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:
|
if "states" in msg_json:
|
||||||
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
|
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
|
||||||
elif msg_json["type"] == "mcp":
|
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:
|
if "payload" in msg_json:
|
||||||
asyncio.create_task(
|
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":
|
elif msg_json["type"] == "server":
|
||||||
# 记录日志时过滤敏感信息
|
# Filter sensitive information when logging
|
||||||
conn.logger.bind(tag=TAG).info(
|
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:
|
if not conn.read_config_from_api:
|
||||||
return
|
return
|
||||||
# 获取post请求的secret
|
# Get secret from post request
|
||||||
post_secret = msg_json.get("content", {}).get("secret", "")
|
post_secret = msg_json.get("content", {}).get("secret", "")
|
||||||
secret = conn.config["manager-api"].get("secret", "")
|
secret = conn.config["manager-api"].get("secret", "")
|
||||||
# 如果secret不匹配,则返回
|
# If secret doesn't match, return
|
||||||
if post_secret != secret:
|
if post_secret != secret:
|
||||||
await conn.websocket.send(
|
await conn.websocket.send(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
"type": "server",
|
"type": "server",
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": "服务器密钥验证失败",
|
"message": "Server secret verification failed",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
# 动态更新配置
|
# Dynamically update configuration
|
||||||
if msg_json["action"] == "update_config":
|
if msg_json["action"] == "update_config":
|
||||||
try:
|
try:
|
||||||
# 更新WebSocketServer的配置
|
# Update WebSocketServer configuration
|
||||||
if not conn.server:
|
if not conn.server:
|
||||||
await conn.websocket.send(
|
await conn.websocket.send(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
"type": "server",
|
"type": "server",
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": "无法获取服务器实例",
|
"message": "Cannot get server instance",
|
||||||
"content": {"action": "update_config"},
|
"content": {"action": "update_config"},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
@ -130,40 +137,42 @@ async def handleTextMessage(conn, message):
|
||||||
{
|
{
|
||||||
"type": "server",
|
"type": "server",
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": "更新服务器配置失败",
|
"message": "Failed to update server configuration",
|
||||||
"content": {"action": "update_config"},
|
"content": {"action": "update_config"},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 发送成功响应
|
# Send success response
|
||||||
await conn.websocket.send(
|
await conn.websocket.send(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
"type": "server",
|
"type": "server",
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"message": "配置更新成功",
|
"message": "Configuration updated successfully",
|
||||||
"content": {"action": "update_config"},
|
"content": {"action": "update_config"},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
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(
|
await conn.websocket.send(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
"type": "server",
|
"type": "server",
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": f"更新配置失败: {str(e)}",
|
"message": f"Failed to update configuration: {str(e)}",
|
||||||
"content": {"action": "update_config"},
|
"content": {"action": "update_config"},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
# 重启服务器
|
# Restart server
|
||||||
elif msg_json["action"] == "restart":
|
elif msg_json["action"] == "restart":
|
||||||
await conn.handle_restart(msg_json)
|
await conn.handle_restart(msg_json)
|
||||||
else:
|
else:
|
||||||
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
|
conn.logger.bind(tag=TAG).error(
|
||||||
|
f"Received unknown type message: {message}")
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
await conn.websocket.send(message)
|
await conn.websocket.send(message)
|
||||||
|
|
@ -15,19 +15,18 @@ class SimpleHttpServer:
|
||||||
self.vision_handler = VisionHandler(config)
|
self.vision_handler = VisionHandler(config)
|
||||||
|
|
||||||
def _get_websocket_url(self, local_ip: str, port: int) -> str:
|
def _get_websocket_url(self, local_ip: str, port: int) -> str:
|
||||||
"""获取websocket地址
|
"""Get websocket address
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
local_ip: 本地IP地址
|
local_ip: Local IP address
|
||||||
port: 端口号
|
port: Port number
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: websocket地址
|
str: websocket address
|
||||||
"""
|
"""
|
||||||
server_config = self.config["server"]
|
server_config = self.config["server"]
|
||||||
websocket_config = server_config.get("websocket")
|
websocket_config = server_config.get("websocket")
|
||||||
|
if websocket_config and "you" not in websocket_config:
|
||||||
if websocket_config and "你" not in websocket_config:
|
|
||||||
return websocket_config
|
return websocket_config
|
||||||
else:
|
else:
|
||||||
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
|
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
|
||||||
|
|
@ -39,43 +38,52 @@ class SimpleHttpServer:
|
||||||
|
|
||||||
if port:
|
if port:
|
||||||
try:
|
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()
|
app = web.Application()
|
||||||
|
|
||||||
read_config_from_api = server_config.get("read_config_from_api", False)
|
read_config_from_api = server_config.get(
|
||||||
self.logger.bind(tag=TAG).info(f"read_config_from_api: {read_config_from_api}")
|
"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:
|
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")
|
self.logger.bind(tag=TAG).info("Adding OTA routes")
|
||||||
app.add_routes(
|
app.add_routes([
|
||||||
[
|
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
|
||||||
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
|
web.post("/xiaozhi/ota/",
|
||||||
web.post("/xiaozhi/ota/", self.ota_handler.handle_post),
|
self.ota_handler.handle_post),
|
||||||
web.options("/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),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
# 运行服务
|
# 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")
|
self.logger.bind(tag=TAG).info("Setting up HTTP server runner")
|
||||||
runner = web.AppRunner(app)
|
runner = web.AppRunner(app)
|
||||||
await runner.setup()
|
await runner.setup()
|
||||||
site = web.TCPSite(runner, host, port)
|
site = web.TCPSite(runner, host, port)
|
||||||
await site.start()
|
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:
|
while True:
|
||||||
await asyncio.sleep(3600) # 每隔 1 小时检查一次
|
await asyncio.sleep(3600) # Check every hour
|
||||||
|
|
||||||
except Exception as e:
|
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
|
raise
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,16 @@
|
||||||
import http.client
|
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import time
|
||||||
from typing import Optional, Tuple, List
|
|
||||||
import os
|
|
||||||
import uuid
|
import uuid
|
||||||
import hmac
|
import hmac
|
||||||
import hashlib
|
|
||||||
import base64
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import asyncio
|
||||||
import requests
|
import requests
|
||||||
|
import websockets
|
||||||
|
import opuslib_next
|
||||||
|
import random
|
||||||
|
from typing import Optional, Tuple, List
|
||||||
from urllib import parse
|
from urllib import parse
|
||||||
import time
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
|
|
@ -18,7 +19,6 @@ from core.providers.asr.dto.dto import InterfaceType
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class AccessToken:
|
class AccessToken:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _encode_text(text):
|
def _encode_text(text):
|
||||||
|
|
@ -45,204 +45,301 @@ class AccessToken:
|
||||||
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
"Version": "2019-02-28",
|
"Version": "2019-02-28",
|
||||||
}
|
}
|
||||||
# 构造规范化的请求字符串
|
|
||||||
query_string = AccessToken._encode_dict(parameters)
|
query_string = AccessToken._encode_dict(parameters)
|
||||||
# print('规范化的请求字符串: %s' % query_string)
|
|
||||||
# 构造待签名字符串
|
|
||||||
string_to_sign = (
|
string_to_sign = (
|
||||||
"GET"
|
"GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string)
|
||||||
+ "&"
|
|
||||||
+ AccessToken._encode_text("/")
|
|
||||||
+ "&"
|
|
||||||
+ AccessToken._encode_text(query_string)
|
|
||||||
)
|
)
|
||||||
# print('待签名的字符串: %s' % string_to_sign)
|
|
||||||
# 计算签名
|
|
||||||
secreted_string = hmac.new(
|
secreted_string = hmac.new(
|
||||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
bytes(access_key_secret + "&", encoding="utf-8"),
|
||||||
bytes(string_to_sign, encoding="utf-8"),
|
bytes(string_to_sign, encoding="utf-8"),
|
||||||
hashlib.sha1,
|
hashlib.sha1,
|
||||||
).digest()
|
).digest()
|
||||||
signature = base64.b64encode(secreted_string)
|
signature = base64.b64encode(secreted_string)
|
||||||
# print('签名: %s' % signature)
|
|
||||||
# 进行URL编码
|
|
||||||
signature = AccessToken._encode_text(signature)
|
signature = AccessToken._encode_text(signature)
|
||||||
# print('URL编码后的签名: %s' % 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,
|
|
||||||
)
|
|
||||||
# print('url: %s' % full_url)
|
|
||||||
# 提交HTTP GET请求
|
|
||||||
response = requests.get(full_url)
|
response = requests.get(full_url)
|
||||||
|
|
||||||
if response.ok:
|
if response.ok:
|
||||||
root_obj = response.json()
|
root_obj = response.json()
|
||||||
key = "Token"
|
if "Token" in root_obj:
|
||||||
if key in root_obj:
|
return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"]
|
||||||
token = root_obj[key]["Id"]
|
|
||||||
expire_time = root_obj[key]["ExpireTime"]
|
|
||||||
return token, expire_time
|
|
||||||
# print(response.text)
|
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
|
|
||||||
class ASRProvider(ASRProviderBase):
|
class ASRProvider(ASRProviderBase):
|
||||||
def __init__(self, config: dict, delete_audio_file: bool):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.interface_type = InterfaceType.NON_STREAM
|
self.interface_type = InterfaceType.STREAM
|
||||||
"""阿里云ASR初始化"""
|
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_id = config.get("access_key_id")
|
||||||
self.access_key_secret = config.get("access_key_secret")
|
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")
|
||||||
|
|
||||||
self.app_key = config.get("appkey")
|
# If configured as internal address (containing -internal.aliyuncs.com), use ws protocol, default is wss protocol
|
||||||
self.host = "nls-gateway-cn-shanghai.aliyuncs.com"
|
if "-internal." in self.host:
|
||||||
self.base_url = f"https://{self.host}/stream/v1/asr"
|
self.ws_url = f"ws://{self.host}/ws/v1"
|
||||||
self.sample_rate = 16000
|
else:
|
||||||
self.format = "wav"
|
# 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.output_dir = config.get("output_dir", "./audio_output")
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
|
self.expire_time = None
|
||||||
|
|
||||||
|
# Token management
|
||||||
if self.access_key_id and self.access_key_secret:
|
if self.access_key_id and self.access_key_secret:
|
||||||
# 使用密钥对生成临时token
|
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
else:
|
elif not self.token:
|
||||||
# 直接使用预生成的长期token
|
raise ValueError("Must provide access_key_id+access_key_secret or directly provide token")
|
||||||
self.token = config.get("token")
|
|
||||||
self.expire_time = None
|
|
||||||
|
|
||||||
# 确保输出目录存在
|
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
|
||||||
|
|
||||||
def _refresh_token(self):
|
def _refresh_token(self):
|
||||||
"""刷新Token并记录过期时间"""
|
"""Refresh 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)
|
||||||
self.token, expire_time_str = AccessToken.create_token(
|
if not self.token:
|
||||||
self.access_key_id, self.access_key_secret
|
raise ValueError("Unable to get valid access Token")
|
||||||
)
|
|
||||||
if not expire_time_str:
|
|
||||||
raise ValueError("无法获取有效的Token过期时间")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 统一转换为字符串处理
|
expire_str = str(expire_time_str).strip()
|
||||||
expire_str = str(expire_time_str).strip()
|
if expire_str.isdigit():
|
||||||
|
expire_time = datetime.fromtimestamp(int(expire_str))
|
||||||
if expire_str.isdigit():
|
else:
|
||||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
|
||||||
else:
|
self.expire_time = expire_time.timestamp() - 60
|
||||||
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
|
except:
|
||||||
self.expire_time = expire_time.timestamp() - 60
|
|
||||||
except Exception as e:
|
|
||||||
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
|
|
||||||
|
|
||||||
else:
|
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
if not self.token:
|
|
||||||
raise ValueError("无法获取有效的访问Token")
|
|
||||||
|
|
||||||
def _is_token_expired(self):
|
def _is_token_expired(self):
|
||||||
"""检查Token是否过期"""
|
"""Check if Token has expired"""
|
||||||
if not self.expire_time:
|
return self.expire_time and time.time() > 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:
|
async def open_audio_channels(self, conn):
|
||||||
"""构造请求URL,包含参数"""
|
await super().open_audio_channels(conn)
|
||||||
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]:
|
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||||
"""发送请求到阿里云ASR服务"""
|
# Initialize audio cache
|
||||||
try:
|
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
||||||
# 设置HTTP头
|
conn.asr_audio_for_voiceprint = []
|
||||||
headers = {
|
|
||||||
"X-NLS-Token": self.token,
|
|
||||||
"Content-type": "application/octet-stream",
|
|
||||||
"Content-Length": str(len(pcm_data)),
|
|
||||||
}
|
|
||||||
|
|
||||||
# 创建连接并发送请求
|
# Store audio data
|
||||||
conn = http.client.HTTPSConnection(self.host)
|
if audio:
|
||||||
request_url = self._construct_request_url()
|
conn.asr_audio_for_voiceprint.append(audio)
|
||||||
|
conn.asr_audio.append(audio)
|
||||||
|
conn.asr_audio = conn.asr_audio[-10:]
|
||||||
|
|
||||||
loop = asyncio.get_event_loop()
|
# Only establish connection when there is voice and no connection exists
|
||||||
await loop.run_in_executor(
|
if audio_have_voice and not self.is_processing:
|
||||||
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()
|
|
||||||
|
|
||||||
# 解析响应
|
|
||||||
try:
|
try:
|
||||||
body_json = json.loads(body)
|
await self._start_recognition(conn)
|
||||||
status = body_json.get("status")
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
|
||||||
|
await self._cleanup(conn)
|
||||||
|
return
|
||||||
|
|
||||||
if status == 20000000:
|
if self.asr_ws and self.is_processing and self.server_ready:
|
||||||
result = body_json.get("result", "")
|
try:
|
||||||
logger.bind(tag=TAG).debug(f"ASR结果: {result}")
|
pcm_frame = self.decoder.decode(audio, 960)
|
||||||
return result
|
await self.asr_ws.send(pcm_frame)
|
||||||
else:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}")
|
logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
|
||||||
return None
|
await self._cleanup(conn)
|
||||||
|
|
||||||
except ValueError:
|
async def _start_recognition(self, conn):
|
||||||
logger.bind(tag=TAG).error("响应不是JSON格式")
|
"""Start recognition session"""
|
||||||
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]]:
|
|
||||||
"""将语音数据转换为文本"""
|
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
logger.warning("Token已过期,正在自动刷新...")
|
|
||||||
self._refresh_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:
|
try:
|
||||||
# 解码Opus为PCM
|
while self.asr_ws and not conn.stop_event.is_set():
|
||||||
if audio_format == "pcm":
|
try:
|
||||||
pcm_data = opus_data
|
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
|
||||||
else:
|
result = json.loads(response)
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
header = result.get("header", {})
|
||||||
if self.delete_audio_file:
|
payload = result.get("payload", {})
|
||||||
pass
|
message_name = header.get("name", "")
|
||||||
else:
|
status = header.get("status", 0)
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
# 发送请求并获取文本
|
if status != 20000000:
|
||||||
text = await self._send_request(combined_pcm_data)
|
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
|
||||||
|
|
||||||
if text:
|
# Receiving TranscriptionStarted means server is ready to receive audio data
|
||||||
return text, file_path
|
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
|
||||||
|
|
||||||
return "", file_path
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
|
||||||
return "", file_path
|
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()
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,9 @@ class AccessToken:
|
||||||
}
|
}
|
||||||
query_string = AccessToken._encode_dict(parameters)
|
query_string = AccessToken._encode_dict(parameters)
|
||||||
string_to_sign = (
|
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(
|
secreted_string = hmac.new(
|
||||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
bytes(access_key_secret + "&", encoding="utf-8"),
|
||||||
|
|
@ -57,7 +59,8 @@ class AccessToken:
|
||||||
).digest()
|
).digest()
|
||||||
signature = base64.b64encode(secreted_string)
|
signature = base64.b64encode(secreted_string)
|
||||||
signature = AccessToken._encode_text(signature)
|
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)
|
response = requests.get(full_url)
|
||||||
if response.ok:
|
if response.ok:
|
||||||
root_obj = response.json()
|
root_obj = response.json()
|
||||||
|
|
@ -76,19 +79,19 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.asr_ws = None
|
self.asr_ws = None
|
||||||
self.forward_task = None
|
self.forward_task = None
|
||||||
self.is_processing = False
|
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_id = config.get("access_key_id")
|
||||||
self.access_key_secret = config.get("access_key_secret")
|
self.access_key_secret = config.get("access_key_secret")
|
||||||
self.appkey = config.get("appkey")
|
self.appkey = config.get("appkey")
|
||||||
self.token = config.get("token")
|
self.token = config.get("token")
|
||||||
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
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:
|
if "-internal." in self.host:
|
||||||
self.ws_url = f"ws://{self.host}/ws/v1"
|
self.ws_url = f"ws://{self.host}/ws/v1"
|
||||||
else:
|
else:
|
||||||
# 默认使用wss协议
|
# Default to wss protocol
|
||||||
self.ws_url = f"wss://{self.host}/ws/v1"
|
self.ws_url = f"wss://{self.host}/ws/v1"
|
||||||
|
|
||||||
self.max_sentence_silence = config.get("max_sentence_silence")
|
self.max_sentence_silence = config.get("max_sentence_silence")
|
||||||
|
|
@ -96,53 +99,57 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
# Token管理
|
# Token management
|
||||||
if self.access_key_id and self.access_key_secret:
|
if self.access_key_id and self.access_key_secret:
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
elif not self.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):
|
def _refresh_token(self):
|
||||||
"""刷新Token"""
|
"""Refresh Token"""
|
||||||
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
|
self.token, expire_time_str = AccessToken.create_token(
|
||||||
|
self.access_key_id, self.access_key_secret)
|
||||||
if not self.token:
|
if not self.token:
|
||||||
raise ValueError("无法获取有效的访问Token")
|
raise ValueError("Unable to obtain valid access Token")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
expire_str = str(expire_time_str).strip()
|
expire_str = str(expire_time_str).strip()
|
||||||
if expire_str.isdigit():
|
if expire_str.isdigit():
|
||||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
expire_time = datetime.fromtimestamp(int(expire_str))
|
||||||
else:
|
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
|
self.expire_time = expire_time.timestamp() - 60
|
||||||
except:
|
except:
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
def _is_token_expired(self):
|
def _is_token_expired(self):
|
||||||
"""检查Token是否过期"""
|
"""Check if Token is expired"""
|
||||||
return self.expire_time and time.time() > self.expire_time
|
return self.expire_time and time.time() > self.expire_time
|
||||||
|
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
await super().open_audio_channels(conn)
|
await super().open_audio_channels(conn)
|
||||||
|
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||||
# 初始化音频缓存
|
# Initialize audio cache
|
||||||
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
||||||
conn.asr_audio_for_voiceprint = []
|
conn.asr_audio_for_voiceprint = []
|
||||||
|
|
||||||
# 存储音频数据
|
# Store audio data
|
||||||
if audio:
|
if audio:
|
||||||
conn.asr_audio_for_voiceprint.append(audio)
|
conn.asr_audio_for_voiceprint.append(audio)
|
||||||
|
|
||||||
conn.asr_audio.append(audio)
|
conn.asr_audio.append(audio)
|
||||||
conn.asr_audio = conn.asr_audio[-10:]
|
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:
|
if audio_have_voice and not self.is_processing:
|
||||||
try:
|
try:
|
||||||
await self._start_recognition(conn)
|
await self._start_recognition(conn)
|
||||||
except Exception as e:
|
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)
|
await self._cleanup(conn)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -151,15 +158,15 @@ class ASRProvider(ASRProviderBase):
|
||||||
pcm_frame = self.decoder.decode(audio, 960)
|
pcm_frame = self.decoder.decode(audio, 960)
|
||||||
await self.asr_ws.send(pcm_frame)
|
await self.asr_ws.send(pcm_frame)
|
||||||
except Exception as e:
|
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)
|
await self._cleanup(conn)
|
||||||
|
|
||||||
async def _start_recognition(self, conn):
|
async def _start_recognition(self, conn):
|
||||||
"""开始识别会话"""
|
"""Start recognition session"""
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
|
|
||||||
# 建立连接
|
# Establish connection
|
||||||
headers = {"X-NLS-Token": self.token}
|
headers = {"X-NLS-Token": self.token}
|
||||||
self.asr_ws = await websockets.connect(
|
self.asr_ws = await websockets.connect(
|
||||||
self.ws_url,
|
self.ws_url,
|
||||||
|
|
@ -171,10 +178,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
)
|
)
|
||||||
|
|
||||||
self.is_processing = True
|
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))
|
self.forward_task = asyncio.create_task(self._forward_results(conn))
|
||||||
|
|
||||||
# 发送开始请求
|
# Send start request
|
||||||
start_request = {
|
start_request = {
|
||||||
"header": {
|
"header": {
|
||||||
"namespace": "SpeechTranscriber",
|
"namespace": "SpeechTranscriber",
|
||||||
|
|
@ -196,10 +203,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
|
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):
|
async def _forward_results(self, conn):
|
||||||
"""转发识别结果"""
|
"""Forward recognition results"""
|
||||||
try:
|
try:
|
||||||
while self.asr_ws and not conn.stop_event.is_set():
|
while self.asr_ws and not conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
|
|
@ -212,51 +220,59 @@ class ASRProvider(ASRProviderBase):
|
||||||
status = header.get("status", 0)
|
status = header.get("status", 0)
|
||||||
|
|
||||||
if status != 20000000:
|
if status != 20000000:
|
||||||
if status in [40000004, 40010004]: # 连接超时或客户端断开
|
# Connection timeout or client disconnect
|
||||||
logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}")
|
if status in [40000004, 40010004]:
|
||||||
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"Connection issue, status code: {status}")
|
||||||
break
|
break
|
||||||
elif status in [40270002, 40270003]: # 音频问题
|
elif status in [40270002, 40270003]: # Audio issues
|
||||||
logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}")
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"Audio processing issue, status code: {status}")
|
||||||
continue
|
continue
|
||||||
else:
|
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
|
continue
|
||||||
|
|
||||||
# 收到TranscriptionStarted表示服务器准备好接收音频数据
|
# TranscriptionStarted indicates server is ready to receive audio data
|
||||||
if message_name == "TranscriptionStarted":
|
if message_name == "TranscriptionStarted":
|
||||||
self.server_ready = True
|
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:
|
if conn.asr_audio:
|
||||||
for cached_audio in conn.asr_audio[-10:]:
|
for cached_audio in conn.asr_audio[-10:]:
|
||||||
try:
|
try:
|
||||||
pcm_frame = self.decoder.decode(cached_audio, 960)
|
pcm_frame = self.decoder.decode(
|
||||||
|
cached_audio, 960)
|
||||||
await self.asr_ws.send(pcm_frame)
|
await self.asr_ws.send(pcm_frame)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"Failed to send cached audio: {e}")
|
||||||
break
|
break
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if message_name == "TranscriptionResultChanged":
|
if message_name == "TranscriptionResultChanged":
|
||||||
# 中间结果
|
# Intermediate result
|
||||||
text = payload.get("result", "")
|
text = payload.get("result", "")
|
||||||
if text:
|
if text:
|
||||||
self.text = text
|
self.text = text
|
||||||
elif message_name == "SentenceEnd":
|
elif message_name == "SentenceEnd":
|
||||||
# 最终结果
|
# Final result
|
||||||
text = payload.get("result", "")
|
text = payload.get("result", "")
|
||||||
if text:
|
if text:
|
||||||
self.text = text
|
self.text = text
|
||||||
conn.reset_vad_states()
|
conn.reset_vad_states()
|
||||||
# 传递缓存的音频数据
|
# Pass cached audio data
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
audio_data = getattr(
|
||||||
|
conn, 'asr_audio_for_voiceprint', [])
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
# 清空缓存
|
# Clear cache
|
||||||
conn.asr_audio_for_voiceprint = []
|
conn.asr_audio_for_voiceprint = []
|
||||||
break
|
break
|
||||||
elif message_name == "TranscriptionCompleted":
|
elif message_name == "TranscriptionCompleted":
|
||||||
# 识别完成
|
# Recognition completed
|
||||||
self.is_processing = False
|
self.is_processing = False
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
@ -265,26 +281,28 @@ class ASRProvider(ASRProviderBase):
|
||||||
except websockets.exceptions.ConnectionClosed:
|
except websockets.exceptions.ConnectionClosed:
|
||||||
break
|
break
|
||||||
except Exception as e:
|
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
|
break
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
|
||||||
finally:
|
finally:
|
||||||
await self._cleanup(conn)
|
await self._cleanup(conn)
|
||||||
|
|
||||||
async def _cleanup(self, conn):
|
async def _cleanup(self, conn):
|
||||||
"""清理资源"""
|
"""Clean up resources"""
|
||||||
logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
|
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'):
|
if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
|
||||||
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
|
should_stop = self.is_processing or self.server_ready
|
||||||
|
|
||||||
# 发送停止识别请求
|
# Send stop recognition request
|
||||||
if self.asr_ws and should_stop:
|
if self.asr_ws and should_stop:
|
||||||
try:
|
try:
|
||||||
stop_msg = {
|
stop_msg = {
|
||||||
|
|
@ -297,47 +315,50 @@ class ASRProvider(ASRProviderBase):
|
||||||
"appkey": self.appkey
|
"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 self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
logger.bind(tag=TAG).info("ASR终止请求已发送")
|
logger.bind(tag=TAG).info("ASR termination request sent")
|
||||||
except Exception as e:
|
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.is_processing = False
|
||||||
self.server_ready = 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():
|
if self.forward_task and not self.forward_task.done():
|
||||||
self.forward_task.cancel()
|
self.forward_task.cancel()
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(self.forward_task, timeout=1.0)
|
await asyncio.wait_for(self.forward_task, timeout=1.0)
|
||||||
except Exception as e:
|
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:
|
finally:
|
||||||
self.forward_task = None
|
self.forward_task = None
|
||||||
|
|
||||||
# 关闭连接
|
# Close connection
|
||||||
if self.asr_ws:
|
if self.asr_ws:
|
||||||
try:
|
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)
|
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:
|
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:
|
finally:
|
||||||
self.asr_ws = None
|
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):
|
async def speech_to_text(self, opus_data, session_id, audio_format):
|
||||||
"""获取识别结果"""
|
"""Get recognition result"""
|
||||||
result = self.text
|
result = self.text
|
||||||
self.text = ""
|
self.text = ""
|
||||||
return result, None
|
return result, None
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""关闭资源"""
|
"""Close resources"""
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
|
|
@ -9,7 +9,6 @@ from core.providers.asr.dto.dto import InterfaceType
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ASRProvider(ASRProviderBase):
|
class ASRProvider(ASRProviderBase):
|
||||||
def __init__(self, config: dict, delete_audio_file: bool = True):
|
def __init__(self, config: dict, delete_audio_file: bool = True):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
@ -17,48 +16,48 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.app_id = config.get("app_id")
|
self.app_id = config.get("app_id")
|
||||||
self.api_key = config.get("api_key")
|
self.api_key = config.get("api_key")
|
||||||
self.secret_key = config.get("secret_key")
|
self.secret_key = config.get("secret_key")
|
||||||
|
|
||||||
dev_pid = config.get("dev_pid", "1537")
|
dev_pid = config.get("dev_pid", "1537")
|
||||||
self.dev_pid = int(dev_pid) if dev_pid else 1537
|
self.dev_pid = int(dev_pid) if dev_pid else 1537
|
||||||
|
|
||||||
self.output_dir = config.get("output_dir")
|
self.output_dir = config.get("output_dir")
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key)
|
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)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""Convert speech data to text"""
|
||||||
if not opus_data:
|
if not opus_data:
|
||||||
logger.bind(tag=TAG).warning("音频数据为空!")
|
logger.bind(tag=TAG).warning("Audio data is empty!")
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# 检查配置是否已设置
|
# Check if configuration is set
|
||||||
if not self.app_id or not self.api_key or not self.secret_key:
|
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
|
return None, file_path
|
||||||
|
|
||||||
# 将Opus音频数据解码为PCM
|
# Decode Opus audio data to PCM
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
else:
|
else:
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
# Determine whether to save as WAV file
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
self.save_audio_to_file(pcm_data, session_id)
|
self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
# 识别本地文件
|
|
||||||
|
# Recognize local file
|
||||||
result = self.client.asr(
|
result = self.client.asr(
|
||||||
combined_pcm_data,
|
combined_pcm_data,
|
||||||
"pcm",
|
"pcm",
|
||||||
|
|
@ -70,16 +69,17 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
if result and result["err_no"] == 0:
|
if result and result["err_no"] == 0:
|
||||||
logger.bind(tag=TAG).debug(
|
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]
|
result = result["result"][0]
|
||||||
return result, file_path
|
return result, file_path
|
||||||
else:
|
else:
|
||||||
raise Exception(
|
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
|
|
||||||
|
return None, file_path
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return None, file_path
|
||||||
|
|
|
||||||
|
|
@ -26,14 +26,14 @@ class ASRProviderBase(ABC):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 打开音频通道
|
# Open audio channels
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
conn.asr_priority_thread = threading.Thread(
|
conn.asr_priority_thread = threading.Thread(
|
||||||
target=self.asr_text_priority_thread, args=(conn,), daemon=True
|
target=self.asr_text_priority_thread, args=(conn,), daemon=True
|
||||||
)
|
)
|
||||||
conn.asr_priority_thread.start()
|
conn.asr_priority_thread.start()
|
||||||
|
|
||||||
# 有序处理ASR音频
|
# Process ASR audio in order
|
||||||
def asr_text_priority_thread(self, conn):
|
def asr_text_priority_thread(self, conn):
|
||||||
while not conn.stop_event.is_set():
|
while not conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
|
|
@ -47,11 +47,11 @@ class ASRProviderBase(ABC):
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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
|
continue
|
||||||
|
|
||||||
# 接收音频
|
# Receive audio
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||||
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
|
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
|
||||||
have_voice = audio_have_voice
|
have_voice = audio_have_voice
|
||||||
|
|
@ -71,13 +71,13 @@ class ASRProviderBase(ABC):
|
||||||
if len(asr_audio_task) > 15:
|
if len(asr_audio_task) > 15:
|
||||||
await self.handle_voice_stop(conn, asr_audio_task)
|
await self.handle_voice_stop(conn, asr_audio_task)
|
||||||
|
|
||||||
# 处理语音停止
|
# Handle voice stop
|
||||||
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
||||||
"""并行处理ASR和声纹识别"""
|
"""Parallel processing of ASR and voiceprint recognition"""
|
||||||
try:
|
try:
|
||||||
total_start_time = time.monotonic()
|
total_start_time = time.monotonic()
|
||||||
|
|
||||||
# 准备音频数据
|
# Prepare audio data
|
||||||
if conn.audio_format == "pcm":
|
if conn.audio_format == "pcm":
|
||||||
pcm_data = asr_audio_task
|
pcm_data = asr_audio_task
|
||||||
else:
|
else:
|
||||||
|
|
@ -85,14 +85,14 @@ class ASRProviderBase(ABC):
|
||||||
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 预先准备WAV数据
|
# Pre-prepare WAV data
|
||||||
wav_data = None
|
wav_data = None
|
||||||
# 使用连接的声纹识别提供者
|
# Use connection's voiceprint provider
|
||||||
if conn.voiceprint_provider and combined_pcm_data:
|
if conn.voiceprint_provider and combined_pcm_data:
|
||||||
wav_data = self._pcm_to_wav(combined_pcm_data)
|
wav_data = self._pcm_to_wav(combined_pcm_data)
|
||||||
|
|
||||||
|
# Define ASR task
|
||||||
|
|
||||||
# 定义ASR任务
|
|
||||||
def run_asr():
|
def run_asr():
|
||||||
start_time = time.monotonic()
|
start_time = time.monotonic()
|
||||||
try:
|
try:
|
||||||
|
|
@ -100,19 +100,21 @@ class ASRProviderBase(ABC):
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
try:
|
try:
|
||||||
result = loop.run_until_complete(
|
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()
|
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
|
return result
|
||||||
finally:
|
finally:
|
||||||
loop.close()
|
loop.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
end_time = time.monotonic()
|
end_time = time.monotonic()
|
||||||
logger.bind(tag=TAG).error(f"ASR失败: {e}")
|
logger.bind(tag=TAG).error(f"ASR failed: {e}")
|
||||||
return ("", None)
|
return ("", None)
|
||||||
|
|
||||||
# 定义声纹识别任务
|
# Define voiceprint recognition task
|
||||||
def run_voiceprint():
|
def run_voiceprint():
|
||||||
if not wav_data:
|
if not wav_data:
|
||||||
return None
|
return None
|
||||||
|
|
@ -120,18 +122,20 @@ class ASRProviderBase(ABC):
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
try:
|
try:
|
||||||
# 使用连接的声纹识别提供者
|
# Use connection's voiceprint provider
|
||||||
result = loop.run_until_complete(
|
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
|
return result
|
||||||
finally:
|
finally:
|
||||||
loop.close()
|
loop.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"声纹识别失败: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
|
f"Voiceprint recognition failed: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 使用线程池执行器并行运行
|
# Run in parallel using thread pool executor
|
||||||
parallel_start_time = time.monotonic()
|
parallel_start_time = time.monotonic()
|
||||||
|
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
|
||||||
|
|
@ -140,49 +144,53 @@ class ASRProviderBase(ABC):
|
||||||
if conn.voiceprint_provider and wav_data:
|
if conn.voiceprint_provider and wav_data:
|
||||||
voiceprint_future = thread_executor.submit(run_voiceprint)
|
voiceprint_future = thread_executor.submit(run_voiceprint)
|
||||||
|
|
||||||
# 等待两个线程都完成
|
# Wait for both threads to complete
|
||||||
asr_result = asr_future.result(timeout=15)
|
asr_result = asr_future.result(timeout=15)
|
||||||
voiceprint_result = voiceprint_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:
|
else:
|
||||||
asr_result = asr_future.result(timeout=15)
|
asr_result = asr_future.result(timeout=15)
|
||||||
results = {"asr": asr_result, "voiceprint": None}
|
results = {"asr": asr_result, "voiceprint": None}
|
||||||
|
|
||||||
|
# Process results
|
||||||
# 处理结果
|
|
||||||
raw_text, file_path = results.get("asr", ("", None))
|
raw_text, file_path = results.get("asr", ("", None))
|
||||||
speaker_name = results.get("voiceprint", None)
|
speaker_name = results.get("voiceprint", None)
|
||||||
|
|
||||||
# 记录识别结果
|
# Log recognition results
|
||||||
if raw_text:
|
if raw_text:
|
||||||
logger.bind(tag=TAG).info(f"识别文本: {raw_text}")
|
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
|
||||||
if speaker_name:
|
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
|
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)
|
text_len, _ = remove_punctuation_and_length(raw_text)
|
||||||
self.stop_ws_connection()
|
self.stop_ws_connection()
|
||||||
|
|
||||||
if text_len > 0:
|
if text_len > 0:
|
||||||
# 构建包含说话人信息的JSON字符串
|
# Build JSON string with speaker information
|
||||||
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
|
enhanced_text = self._build_enhanced_text(
|
||||||
|
raw_text, speaker_name)
|
||||||
|
|
||||||
# 使用自定义模块进行上报
|
# Use custom module for reporting
|
||||||
await startToChat(conn, enhanced_text)
|
await startToChat(conn, enhanced_text)
|
||||||
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
|
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
|
||||||
|
|
||||||
except Exception as e:
|
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
|
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:
|
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
||||||
"""构建包含说话人信息的文本"""
|
"""Build text with speaker information"""
|
||||||
if speaker_name and speaker_name.strip():
|
if speaker_name and speaker_name.strip():
|
||||||
return json.dumps({
|
return json.dumps({
|
||||||
"speaker": speaker_name,
|
"speaker": speaker_name,
|
||||||
|
|
@ -192,22 +200,23 @@ class ASRProviderBase(ABC):
|
||||||
return text
|
return text
|
||||||
|
|
||||||
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
|
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
|
||||||
"""将PCM数据转换为WAV格式"""
|
"""Convert PCM data to WAV format"""
|
||||||
if len(pcm_data) == 0:
|
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""
|
return b""
|
||||||
|
|
||||||
# 确保数据长度是偶数(16位音频)
|
# Ensure data length is even (16-bit audio)
|
||||||
if len(pcm_data) % 2 != 0:
|
if len(pcm_data) % 2 != 0:
|
||||||
pcm_data = pcm_data[:-1]
|
pcm_data = pcm_data[:-1]
|
||||||
|
|
||||||
# 创建WAV文件头
|
# Create WAV file header
|
||||||
wav_buffer = io.BytesIO()
|
wav_buffer = io.BytesIO()
|
||||||
try:
|
try:
|
||||||
with wave.open(wav_buffer, 'wb') as wav_file:
|
with wave.open(wav_buffer, 'wb') as wav_file:
|
||||||
wav_file.setnchannels(1) # 单声道
|
wav_file.setnchannels(1) # Mono
|
||||||
wav_file.setsampwidth(2) # 16位
|
wav_file.setsampwidth(2) # 16-bit
|
||||||
wav_file.setframerate(16000) # 16kHz采样率
|
wav_file.setframerate(16000) # 16kHz sample rate
|
||||||
wav_file.writeframes(pcm_data)
|
wav_file.writeframes(pcm_data)
|
||||||
|
|
||||||
wav_buffer.seek(0)
|
wav_buffer.seek(0)
|
||||||
|
|
@ -215,14 +224,14 @@ class ASRProviderBase(ABC):
|
||||||
|
|
||||||
return wav_data
|
return wav_data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"WAV转换失败: {e}")
|
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
|
||||||
return b""
|
return b""
|
||||||
|
|
||||||
def stop_ws_connection(self):
|
def stop_ws_connection(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
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]
|
module_name = __name__.split(".")[-1]
|
||||||
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
|
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
|
||||||
file_path = os.path.join(self.output_dir, file_name)
|
file_path = os.path.join(self.output_dir, file_name)
|
||||||
|
|
@ -239,16 +248,16 @@ class ASRProviderBase(ABC):
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""Convert speech data to text"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
|
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
|
||||||
"""将Opus音频数据解码为PCM数据"""
|
"""Decode Opus audio data to PCM data"""
|
||||||
try:
|
try:
|
||||||
decoder = opuslib_next.Decoder(16000, 1)
|
decoder = opuslib_next.Decoder(16000, 1)
|
||||||
pcm_data = []
|
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):
|
for i, opus_packet in enumerate(opus_data):
|
||||||
try:
|
try:
|
||||||
|
|
@ -260,12 +269,15 @@ class ASRProviderBase(ABC):
|
||||||
pcm_data.append(pcm_frame)
|
pcm_data.append(pcm_frame)
|
||||||
|
|
||||||
except opuslib_next.OpusError as e:
|
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:
|
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
|
return pcm_data
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
|
f"Error occurred during audio decoding: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
@ -9,20 +9,16 @@ from typing import Optional, Tuple, List
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
CLIENT_FULL_REQUEST = 0b0001
|
CLIENT_FULL_REQUEST = 0b0001
|
||||||
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
|
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
|
||||||
|
|
||||||
NO_SEQUENCE = 0b0000
|
NO_SEQUENCE = 0b0000
|
||||||
NEG_SEQUENCE = 0b0010
|
NEG_SEQUENCE = 0b0010
|
||||||
|
|
||||||
SERVER_FULL_RESPONSE = 0b1001
|
SERVER_FULL_RESPONSE = 0b1001
|
||||||
SERVER_ACK = 0b1011
|
SERVER_ACK = 0b1011
|
||||||
SERVER_ERROR_RESPONSE = 0b1111
|
SERVER_ERROR_RESPONSE = 0b1111
|
||||||
|
|
||||||
NO_SERIALIZATION = 0b0000
|
NO_SERIALIZATION = 0b0000
|
||||||
JSON = 0b0001
|
JSON = 0b0001
|
||||||
THRIFT = 0b0011
|
THRIFT = 0b0011
|
||||||
|
|
@ -37,9 +33,9 @@ def parse_response(res):
|
||||||
protocol_version(4 bits), header_size(4 bits),
|
protocol_version(4 bits), header_size(4 bits),
|
||||||
message_type(4 bits), message_type_specific_flags(4 bits)
|
message_type(4 bits), message_type_specific_flags(4 bits)
|
||||||
serialization_method(4 bits) message_compression(4 bits)
|
serialization_method(4 bits) message_compression(4 bits)
|
||||||
reserved (8bits) 保留字段
|
reserved (8bits) reserved field
|
||||||
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
|
header_extensions extension header (size equals 8 * 4 * (header_size - 1))
|
||||||
payload 类似与http 请求体
|
payload similar to http request body
|
||||||
"""
|
"""
|
||||||
protocol_version = res[0] >> 4
|
protocol_version = res[0] >> 4
|
||||||
header_size = res[0] & 0x0F
|
header_size = res[0] & 0x0F
|
||||||
|
|
@ -48,11 +44,13 @@ def parse_response(res):
|
||||||
serialization_method = res[2] >> 4
|
serialization_method = res[2] >> 4
|
||||||
message_compression = res[2] & 0x0F
|
message_compression = res[2] & 0x0F
|
||||||
reserved = res[3]
|
reserved = res[3]
|
||||||
header_extensions = res[4 : header_size * 4]
|
header_extensions = res[4: header_size * 4]
|
||||||
payload = res[header_size * 4 :]
|
payload = res[header_size * 4:]
|
||||||
|
|
||||||
result = {}
|
result = {}
|
||||||
payload_msg = None
|
payload_msg = None
|
||||||
payload_size = 0
|
payload_size = 0
|
||||||
|
|
||||||
if message_type == SERVER_FULL_RESPONSE:
|
if message_type == SERVER_FULL_RESPONSE:
|
||||||
payload_size = int.from_bytes(payload[:4], "big", signed=True)
|
payload_size = int.from_bytes(payload[:4], "big", signed=True)
|
||||||
payload_msg = payload[4:]
|
payload_msg = payload[4:]
|
||||||
|
|
@ -67,16 +65,21 @@ def parse_response(res):
|
||||||
result["code"] = code
|
result["code"] = code
|
||||||
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
||||||
payload_msg = payload[8:]
|
payload_msg = payload[8:]
|
||||||
|
|
||||||
if payload_msg is None:
|
if payload_msg is None:
|
||||||
return result
|
return result
|
||||||
|
|
||||||
if message_compression == GZIP:
|
if message_compression == GZIP:
|
||||||
payload_msg = gzip.decompress(payload_msg)
|
payload_msg = gzip.decompress(payload_msg)
|
||||||
|
|
||||||
if serialization_method == JSON:
|
if serialization_method == JSON:
|
||||||
payload_msg = json.loads(str(payload_msg, "utf-8"))
|
payload_msg = json.loads(str(payload_msg, "utf-8"))
|
||||||
elif serialization_method != NO_SERIALIZATION:
|
elif serialization_method != NO_SERIALIZATION:
|
||||||
payload_msg = str(payload_msg, "utf-8")
|
payload_msg = str(payload_msg, "utf-8")
|
||||||
|
|
||||||
result["payload_msg"] = payload_msg
|
result["payload_msg"] = payload_msg
|
||||||
result["payload_size"] = payload_size
|
result["payload_size"] = payload_size
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.correct_table_name = config.get("correct_table_name", "")
|
self.correct_table_name = config.get("correct_table_name", "")
|
||||||
self.output_dir = config.get("output_dir")
|
self.output_dir = config.get("output_dir")
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
self.host = "openspeech.bytedance.com"
|
self.host = "openspeech.bytedance.com"
|
||||||
self.ws_url = f"wss://{self.host}/api/v2/asr"
|
self.ws_url = f"wss://{self.host}/api/v2/asr"
|
||||||
self.success_code = 1000
|
self.success_code = 1000
|
||||||
self.seg_duration = 15000
|
self.seg_duration = 15000
|
||||||
|
|
||||||
# 确保输出目录存在
|
# Ensure output directory exists
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
"""Generate protocol header."""
|
"""Generate protocol header."""
|
||||||
header = bytearray()
|
header = bytearray()
|
||||||
header_size = 1
|
header_size = 1
|
||||||
|
|
||||||
header.append((0b0001 << 4) | header_size) # Protocol version
|
header.append((0b0001 << 4) | header_size) # Protocol version
|
||||||
header.append((message_type << 4) | message_type_specific_flags)
|
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
|
header.append(0x00) # reserved
|
||||||
|
|
||||||
return header
|
return header
|
||||||
|
|
||||||
def _construct_request(self, reqid) -> dict:
|
def _construct_request(self, reqid) -> dict:
|
||||||
|
|
@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
) -> Optional[str]:
|
) -> Optional[str]:
|
||||||
"""Send request to Volcano ASR service."""
|
"""Send request to Volcano ASR service."""
|
||||||
try:
|
try:
|
||||||
auth_header = {"Authorization": "Bearer; {}".format(self.access_token)}
|
auth_header = {
|
||||||
|
"Authorization": "Bearer; {}".format(self.access_token)}
|
||||||
async with websockets.connect(
|
async with websockets.connect(
|
||||||
self.ws_url, additional_headers=auth_header
|
self.ws_url, additional_headers=auth_header
|
||||||
) as websocket:
|
) as websocket:
|
||||||
|
|
@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
request_params = self._construct_request(str(uuid.uuid4()))
|
request_params = self._construct_request(str(uuid.uuid4()))
|
||||||
payload_bytes = str.encode(json.dumps(request_params))
|
payload_bytes = str.encode(json.dumps(request_params))
|
||||||
payload_bytes = gzip.compress(payload_bytes)
|
payload_bytes = gzip.compress(payload_bytes)
|
||||||
|
|
||||||
full_client_request = self._generate_header()
|
full_client_request = self._generate_header()
|
||||||
full_client_request.extend(
|
full_client_request.extend(
|
||||||
(len(payload_bytes)).to_bytes(4, "big")
|
(len(payload_bytes)).to_bytes(4, "big")
|
||||||
|
|
@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
await websocket.send(full_client_request)
|
await websocket.send(full_client_request)
|
||||||
res = await websocket.recv()
|
res = await websocket.recv()
|
||||||
result = parse_response(res)
|
result = parse_response(res)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
"payload_msg" in result
|
"payload_msg" in result
|
||||||
and result["payload_msg"]["code"] != self.success_code
|
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}")
|
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||||
return None
|
return None
|
||||||
|
|
@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase):
|
||||||
audio_only_request = self._generate_header(
|
audio_only_request = self._generate_header(
|
||||||
message_type=CLIENT_AUDIO_ONLY_REQUEST
|
message_type=CLIENT_AUDIO_ONLY_REQUEST
|
||||||
)
|
)
|
||||||
|
|
||||||
payload_bytes = gzip.compress(chunk)
|
payload_bytes = gzip.compress(chunk)
|
||||||
audio_only_request.extend(
|
audio_only_request.extend(
|
||||||
(len(payload_bytes)).to_bytes(4, "big")
|
(len(payload_bytes)).to_bytes(4, "big")
|
||||||
) # payload size(4 bytes)
|
) # payload size(4 bytes)
|
||||||
audio_only_request.extend(payload_bytes) # payload
|
audio_only_request.extend(payload_bytes) # payload
|
||||||
|
|
||||||
# Send audio data
|
# Send audio data
|
||||||
await websocket.send(audio_only_request)
|
await websocket.send(audio_only_request)
|
||||||
|
|
||||||
# Receive response
|
# Receive response
|
||||||
response = await websocket.recv()
|
response = await websocket.recv()
|
||||||
result = parse_response(response)
|
result = parse_response(response)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
"payload_msg" in result
|
"payload_msg" in result
|
||||||
and result["payload_msg"]["code"] == self.success_code
|
and result["payload_msg"]["code"] == self.success_code
|
||||||
):
|
):
|
||||||
if len(result["payload_msg"]["result"]) > 0:
|
if len(result["payload_msg"]["result"]) > 0:
|
||||||
return result["payload_msg"]["result"][0]["text"]
|
return result["payload_msg"]["result"][0]["text"]
|
||||||
return None
|
return None
|
||||||
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
|
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
|
||||||
# 无有效语音,返回空字符串
|
# No valid voice, return empty string
|
||||||
return ""
|
return ""
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
data_len = len(data)
|
data_len = len(data)
|
||||||
offset = 0
|
offset = 0
|
||||||
while offset + chunk_size < data_len:
|
while offset + chunk_size < data_len:
|
||||||
yield data[offset : offset + chunk_size], False
|
yield data[offset: offset + chunk_size], False
|
||||||
offset += chunk_size
|
offset += chunk_size
|
||||||
else:
|
else:
|
||||||
yield data[offset:data_len], True
|
yield data[offset:data_len], True
|
||||||
|
|
@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase):
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""Convert speech data to text"""
|
||||||
|
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# 合并所有opus数据包
|
# Merge all opus data packets
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
else:
|
else:
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
# Determine whether to save as WAV file
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
# 直接使用PCM数据
|
# Use PCM data directly
|
||||||
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
|
# Calculate segment size (mono, 16bit, 16kHz sample rate)
|
||||||
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
|
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
|
||||||
segment_size = int(size_per_sec * self.seg_duration / 1000)
|
segment_size = int(size_per_sec * self.seg_duration / 1000)
|
||||||
|
|
||||||
# 语音识别
|
# Speech recognition
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
text = await self._send_request(combined_pcm_data, segment_size)
|
text = await self._send_request(combined_pcm_data, segment_size)
|
||||||
|
|
||||||
if text:
|
if text:
|
||||||
logger.bind(tag=TAG).debug(
|
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 text, file_path
|
||||||
|
|
||||||
return "", file_path
|
return "", file_path
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return "", file_path
|
||||||
|
|
|
||||||
|
|
@ -9,20 +9,16 @@ from typing import Optional, Tuple, List
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
CLIENT_FULL_REQUEST = 0b0001
|
CLIENT_FULL_REQUEST = 0b0001
|
||||||
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
|
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
|
||||||
|
|
||||||
NO_SEQUENCE = 0b0000
|
NO_SEQUENCE = 0b0000
|
||||||
NEG_SEQUENCE = 0b0010
|
NEG_SEQUENCE = 0b0010
|
||||||
|
|
||||||
SERVER_FULL_RESPONSE = 0b1001
|
SERVER_FULL_RESPONSE = 0b1001
|
||||||
SERVER_ACK = 0b1011
|
SERVER_ACK = 0b1011
|
||||||
SERVER_ERROR_RESPONSE = 0b1111
|
SERVER_ERROR_RESPONSE = 0b1111
|
||||||
|
|
||||||
NO_SERIALIZATION = 0b0000
|
NO_SERIALIZATION = 0b0000
|
||||||
JSON = 0b0001
|
JSON = 0b0001
|
||||||
THRIFT = 0b0011
|
THRIFT = 0b0011
|
||||||
|
|
@ -37,9 +33,9 @@ def parse_response(res):
|
||||||
protocol_version(4 bits), header_size(4 bits),
|
protocol_version(4 bits), header_size(4 bits),
|
||||||
message_type(4 bits), message_type_specific_flags(4 bits)
|
message_type(4 bits), message_type_specific_flags(4 bits)
|
||||||
serialization_method(4 bits) message_compression(4 bits)
|
serialization_method(4 bits) message_compression(4 bits)
|
||||||
reserved (8bits) 保留字段
|
reserved (8bits) reserved field
|
||||||
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
|
header_extensions extension header (size equals 8 * 4 * (header_size - 1))
|
||||||
payload 类似与http 请求体
|
payload similar to http request body
|
||||||
"""
|
"""
|
||||||
protocol_version = res[0] >> 4
|
protocol_version = res[0] >> 4
|
||||||
header_size = res[0] & 0x0F
|
header_size = res[0] & 0x0F
|
||||||
|
|
@ -48,11 +44,13 @@ def parse_response(res):
|
||||||
serialization_method = res[2] >> 4
|
serialization_method = res[2] >> 4
|
||||||
message_compression = res[2] & 0x0F
|
message_compression = res[2] & 0x0F
|
||||||
reserved = res[3]
|
reserved = res[3]
|
||||||
header_extensions = res[4 : header_size * 4]
|
header_extensions = res[4: header_size * 4]
|
||||||
payload = res[header_size * 4 :]
|
payload = res[header_size * 4:]
|
||||||
|
|
||||||
result = {}
|
result = {}
|
||||||
payload_msg = None
|
payload_msg = None
|
||||||
payload_size = 0
|
payload_size = 0
|
||||||
|
|
||||||
if message_type == SERVER_FULL_RESPONSE:
|
if message_type == SERVER_FULL_RESPONSE:
|
||||||
payload_size = int.from_bytes(payload[:4], "big", signed=True)
|
payload_size = int.from_bytes(payload[:4], "big", signed=True)
|
||||||
payload_msg = payload[4:]
|
payload_msg = payload[4:]
|
||||||
|
|
@ -67,16 +65,21 @@ def parse_response(res):
|
||||||
result["code"] = code
|
result["code"] = code
|
||||||
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
||||||
payload_msg = payload[8:]
|
payload_msg = payload[8:]
|
||||||
|
|
||||||
if payload_msg is None:
|
if payload_msg is None:
|
||||||
return result
|
return result
|
||||||
|
|
||||||
if message_compression == GZIP:
|
if message_compression == GZIP:
|
||||||
payload_msg = gzip.decompress(payload_msg)
|
payload_msg = gzip.decompress(payload_msg)
|
||||||
|
|
||||||
if serialization_method == JSON:
|
if serialization_method == JSON:
|
||||||
payload_msg = json.loads(str(payload_msg, "utf-8"))
|
payload_msg = json.loads(str(payload_msg, "utf-8"))
|
||||||
elif serialization_method != NO_SERIALIZATION:
|
elif serialization_method != NO_SERIALIZATION:
|
||||||
payload_msg = str(payload_msg, "utf-8")
|
payload_msg = str(payload_msg, "utf-8")
|
||||||
|
|
||||||
result["payload_msg"] = payload_msg
|
result["payload_msg"] = payload_msg
|
||||||
result["payload_size"] = payload_size
|
result["payload_size"] = payload_size
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.correct_table_name = config.get("correct_table_name", "")
|
self.correct_table_name = config.get("correct_table_name", "")
|
||||||
self.output_dir = config.get("output_dir")
|
self.output_dir = config.get("output_dir")
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
self.host = "openspeech.bytedance.com"
|
self.host = "openspeech.bytedance.com"
|
||||||
self.ws_url = f"wss://{self.host}/api/v2/asr"
|
self.ws_url = f"wss://{self.host}/api/v2/asr"
|
||||||
self.success_code = 1000
|
self.success_code = 1000
|
||||||
self.seg_duration = 15000
|
self.seg_duration = 15000
|
||||||
|
|
||||||
# 确保输出目录存在
|
# Ensure output directory exists
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
"""Generate protocol header."""
|
"""Generate protocol header."""
|
||||||
header = bytearray()
|
header = bytearray()
|
||||||
header_size = 1
|
header_size = 1
|
||||||
|
|
||||||
header.append((0b0001 << 4) | header_size) # Protocol version
|
header.append((0b0001 << 4) | header_size) # Protocol version
|
||||||
header.append((message_type << 4) | message_type_specific_flags)
|
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
|
header.append(0x00) # reserved
|
||||||
|
|
||||||
return header
|
return header
|
||||||
|
|
||||||
def _construct_request(self, reqid) -> dict:
|
def _construct_request(self, reqid) -> dict:
|
||||||
|
|
@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
) -> Optional[str]:
|
) -> Optional[str]:
|
||||||
"""Send request to Volcano ASR service."""
|
"""Send request to Volcano ASR service."""
|
||||||
try:
|
try:
|
||||||
auth_header = {"Authorization": "Bearer; {}".format(self.access_token)}
|
auth_header = {
|
||||||
|
"Authorization": "Bearer; {}".format(self.access_token)}
|
||||||
async with websockets.connect(
|
async with websockets.connect(
|
||||||
self.ws_url, additional_headers=auth_header
|
self.ws_url, additional_headers=auth_header
|
||||||
) as websocket:
|
) as websocket:
|
||||||
|
|
@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
request_params = self._construct_request(str(uuid.uuid4()))
|
request_params = self._construct_request(str(uuid.uuid4()))
|
||||||
payload_bytes = str.encode(json.dumps(request_params))
|
payload_bytes = str.encode(json.dumps(request_params))
|
||||||
payload_bytes = gzip.compress(payload_bytes)
|
payload_bytes = gzip.compress(payload_bytes)
|
||||||
|
|
||||||
full_client_request = self._generate_header()
|
full_client_request = self._generate_header()
|
||||||
full_client_request.extend(
|
full_client_request.extend(
|
||||||
(len(payload_bytes)).to_bytes(4, "big")
|
(len(payload_bytes)).to_bytes(4, "big")
|
||||||
|
|
@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
await websocket.send(full_client_request)
|
await websocket.send(full_client_request)
|
||||||
res = await websocket.recv()
|
res = await websocket.recv()
|
||||||
result = parse_response(res)
|
result = parse_response(res)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
"payload_msg" in result
|
"payload_msg" in result
|
||||||
and result["payload_msg"]["code"] != self.success_code
|
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}")
|
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||||
return None
|
return None
|
||||||
|
|
@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase):
|
||||||
audio_only_request = self._generate_header(
|
audio_only_request = self._generate_header(
|
||||||
message_type=CLIENT_AUDIO_ONLY_REQUEST
|
message_type=CLIENT_AUDIO_ONLY_REQUEST
|
||||||
)
|
)
|
||||||
|
|
||||||
payload_bytes = gzip.compress(chunk)
|
payload_bytes = gzip.compress(chunk)
|
||||||
audio_only_request.extend(
|
audio_only_request.extend(
|
||||||
(len(payload_bytes)).to_bytes(4, "big")
|
(len(payload_bytes)).to_bytes(4, "big")
|
||||||
) # payload size(4 bytes)
|
) # payload size(4 bytes)
|
||||||
audio_only_request.extend(payload_bytes) # payload
|
audio_only_request.extend(payload_bytes) # payload
|
||||||
|
|
||||||
# Send audio data
|
# Send audio data
|
||||||
await websocket.send(audio_only_request)
|
await websocket.send(audio_only_request)
|
||||||
|
|
||||||
# Receive response
|
# Receive response
|
||||||
response = await websocket.recv()
|
response = await websocket.recv()
|
||||||
result = parse_response(response)
|
result = parse_response(response)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
"payload_msg" in result
|
"payload_msg" in result
|
||||||
and result["payload_msg"]["code"] == self.success_code
|
and result["payload_msg"]["code"] == self.success_code
|
||||||
):
|
):
|
||||||
if len(result["payload_msg"]["result"]) > 0:
|
if len(result["payload_msg"]["result"]) > 0:
|
||||||
return result["payload_msg"]["result"][0]["text"]
|
return result["payload_msg"]["result"][0]["text"]
|
||||||
return None
|
return None
|
||||||
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
|
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
|
||||||
# 无有效语音,返回空字符串
|
# No valid voice, return empty string
|
||||||
return ""
|
return ""
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
data_len = len(data)
|
data_len = len(data)
|
||||||
offset = 0
|
offset = 0
|
||||||
while offset + chunk_size < data_len:
|
while offset + chunk_size < data_len:
|
||||||
yield data[offset : offset + chunk_size], False
|
yield data[offset: offset + chunk_size], False
|
||||||
offset += chunk_size
|
offset += chunk_size
|
||||||
else:
|
else:
|
||||||
yield data[offset:data_len], True
|
yield data[offset:data_len], True
|
||||||
|
|
@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase):
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""Convert speech data to text"""
|
||||||
|
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# 合并所有opus数据包
|
# Merge all opus data packets
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
else:
|
else:
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
# Determine whether to save as WAV file
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
# 直接使用PCM数据
|
# Use PCM data directly
|
||||||
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
|
# Calculate segment size (mono, 16bit, 16kHz sample rate)
|
||||||
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
|
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
|
||||||
segment_size = int(size_per_sec * self.seg_duration / 1000)
|
segment_size = int(size_per_sec * self.seg_duration / 1000)
|
||||||
|
|
||||||
# 语音识别
|
# Speech recognition
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
text = await self._send_request(combined_pcm_data, segment_size)
|
text = await self._send_request(combined_pcm_data, segment_size)
|
||||||
|
|
||||||
if text:
|
if text:
|
||||||
logger.bind(tag=TAG).debug(
|
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 text, file_path
|
||||||
|
|
||||||
return "", file_path
|
return "", file_path
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return "", file_path
|
||||||
|
|
@ -3,7 +3,7 @@ from typing import Union, Optional
|
||||||
|
|
||||||
|
|
||||||
class InterfaceType(Enum):
|
class InterfaceType(Enum):
|
||||||
# 接口类型
|
# Interface type
|
||||||
STREAM = "STREAM" # 流式接口
|
STREAM = "STREAM" # Streaming interface
|
||||||
NON_STREAM = "NON_STREAM" # 非流式接口
|
NON_STREAM = "NON_STREAM" # Non-streaming interface
|
||||||
LOCAL = "LOCAL" # 本地服务
|
LOCAL = "LOCAL" # Local service
|
||||||
|
|
|
||||||
|
|
@ -15,10 +15,11 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
MAX_RETRIES = 2
|
MAX_RETRIES = 2
|
||||||
RETRY_DELAY = 1 # 重试延迟(秒)
|
RETRY_DELAY = 1 # Retry delay (seconds)
|
||||||
|
|
||||||
|
# Capture standard output
|
||||||
|
|
||||||
|
|
||||||
# 捕获标准输出
|
|
||||||
class CaptureOutput:
|
class CaptureOutput:
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
self._output = io.StringIO()
|
self._output = io.StringIO()
|
||||||
|
|
@ -30,7 +31,7 @@ class CaptureOutput:
|
||||||
self.output = self._output.getvalue()
|
self.output = self._output.getvalue()
|
||||||
self._output.close()
|
self._output.close()
|
||||||
|
|
||||||
# 将捕获到的内容通过 logger 输出
|
# Output captured content through logger
|
||||||
if self.output:
|
if self.output:
|
||||||
logger.bind(tag=TAG).info(self.output.strip())
|
logger.bind(tag=TAG).info(self.output.strip())
|
||||||
|
|
||||||
|
|
@ -39,58 +40,60 @@ class ASRProvider(ASRProviderBase):
|
||||||
def __init__(self, config: dict, delete_audio_file: bool):
|
def __init__(self, config: dict, delete_audio_file: bool):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
# 内存检测,要求大于2G
|
# Memory detection, require more than 2G
|
||||||
min_mem_bytes = 2 * 1024 * 1024 * 1024
|
min_mem_bytes = 2 * 1024 * 1024 * 1024
|
||||||
total_mem = psutil.virtual_memory().total
|
total_mem = psutil.virtual_memory().total
|
||||||
if total_mem < min_mem_bytes:
|
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.interface_type = InterfaceType.LOCAL
|
||||||
self.model_dir = config.get("model_dir")
|
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
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
# 确保输出目录存在
|
# Ensure output directory exists
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
with CaptureOutput():
|
with CaptureOutput():
|
||||||
self.model = AutoModel(
|
self.model = AutoModel(
|
||||||
model=self.model_dir,
|
model=self.model_dir,
|
||||||
vad_kwargs={"max_single_segment_time": 30000},
|
vad_kwargs={"max_single_segment_time": 30000},
|
||||||
disable_update=True,
|
disable_update=True,
|
||||||
hub="hf",
|
hub="hf",
|
||||||
# device="cuda:0", # 启用GPU加速
|
# device="cuda:0", # Enable GPU acceleration
|
||||||
)
|
)
|
||||||
|
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""语音转文本主处理逻辑"""
|
"""Speech to text main processing logic"""
|
||||||
file_path = None
|
file_path = None
|
||||||
retry_count = 0
|
retry_count = 0
|
||||||
|
|
||||||
while retry_count < MAX_RETRIES:
|
while retry_count < MAX_RETRIES:
|
||||||
try:
|
try:
|
||||||
# 合并所有opus数据包
|
# Merge all opus data packets
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
else:
|
else:
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 检查磁盘空间
|
# Check disk space
|
||||||
if not self.delete_audio_file:
|
if not self.delete_audio_file:
|
||||||
free_space = shutil.disk_usage(self.output_dir).free
|
free_space = shutil.disk_usage(self.output_dir).free
|
||||||
if free_space < len(combined_pcm_data) * 2: # 预留2倍空间
|
if free_space < len(combined_pcm_data) * 2: # Reserve 2x space
|
||||||
raise OSError("磁盘空间不足")
|
raise OSError("Insufficient disk space")
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
# Determine whether to save as WAV file
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
# 语音识别
|
# Speech recognition
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
result = self.model.generate(
|
result = self.model.generate(
|
||||||
input=combined_pcm_data,
|
input=combined_pcm_data,
|
||||||
|
|
@ -99,9 +102,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
use_itn=True,
|
use_itn=True,
|
||||||
batch_size_s=60,
|
batch_size_s=60,
|
||||||
)
|
)
|
||||||
|
|
||||||
text = rich_transcription_postprocess(result[0]["text"])
|
text = rich_transcription_postprocess(result[0]["text"])
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug(
|
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 text, file_path
|
||||||
|
|
@ -110,25 +115,28 @@ class ASRProvider(ASRProviderBase):
|
||||||
retry_count += 1
|
retry_count += 1
|
||||||
if retry_count >= MAX_RETRIES:
|
if retry_count >= MAX_RETRIES:
|
||||||
logger.bind(tag=TAG).error(
|
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
|
return "", file_path
|
||||||
|
|
||||||
logger.bind(tag=TAG).warning(
|
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)
|
time.sleep(RETRY_DELAY)
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return "", file_path
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
# 文件清理逻辑
|
# File cleanup logic
|
||||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||||
try:
|
try:
|
||||||
os.remove(file_path)
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"文件删除失败: {file_path} | 错误: {e}"
|
f"File deletion failed: {file_path} | Error: {e}"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,11 @@ import re
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ASRProvider(ASRProviderBase):
|
class ASRProvider(ASRProviderBase):
|
||||||
def __init__(self, config: dict, delete_audio_file: bool):
|
def __init__(self, config: dict, delete_audio_file: bool):
|
||||||
"""
|
"""
|
||||||
Initialize the ASRProvider with server configuration.
|
Initialize the ASRProvider with server configuration.
|
||||||
|
|
||||||
:param config: Dictionary containing 'host', 'port', and 'is_ssl'.
|
:param config: Dictionary containing 'host', 'port', and 'is_ssl'.
|
||||||
:param delete_audio_file: Boolean to indicate whether to delete audio files after processing.
|
:param delete_audio_file: Boolean to indicate whether to delete audio files after processing.
|
||||||
"""
|
"""
|
||||||
|
|
@ -36,6 +36,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
if self.is_ssl
|
if self.is_ssl
|
||||||
else f"ws://{self.host}:{self.port}"
|
else f"ws://{self.host}:{self.port}"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.ssl_context = ssl.SSLContext() if self.is_ssl else None
|
self.ssl_context = ssl.SSLContext() if self.is_ssl else None
|
||||||
if self.ssl_context:
|
if self.ssl_context:
|
||||||
self.ssl_context.check_hostname = False
|
self.ssl_context.check_hostname = False
|
||||||
|
|
@ -52,11 +53,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
response = await asyncio.wait_for(ws.recv(), timeout=5)
|
response = await asyncio.wait_for(ws.recv(), timeout=5)
|
||||||
response_data = json.loads(response)
|
response_data = json.loads(response)
|
||||||
logger.bind(tag=TAG).debug(f"Received response: {response_data}")
|
logger.bind(tag=TAG).debug(f"Received response: {response_data}")
|
||||||
|
|
||||||
if response_data.get("is_final", True):
|
if response_data.get("is_final", True):
|
||||||
text += response_data.get("text", "")
|
text += response_data.get("text", "")
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
text += response_data.get("text", "")
|
text += response_data.get("text", "")
|
||||||
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
"Timeout while waiting for response from WebSocket."
|
"Timeout while waiting for response from WebSocket."
|
||||||
|
|
@ -65,28 +68,27 @@ class ASRProvider(ASRProviderBase):
|
||||||
except websockets.exceptions.ConnectionClosed as e:
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
|
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
|
||||||
break
|
break
|
||||||
|
|
||||||
return text
|
return text
|
||||||
|
|
||||||
async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple:
|
async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple:
|
||||||
"""
|
"""
|
||||||
Internal method to handle WebSocket communication.
|
Internal method to handle WebSocket communication.
|
||||||
Reuses the persistent WebSocket connection if available.
|
Reuses the persistent WebSocket connection if available.
|
||||||
|
|
||||||
:param pcm_data: PCM audio data to send.
|
:param pcm_data: PCM audio data to send.
|
||||||
:param session_id: Unique session identifier.
|
:param session_id: Unique session identifier.
|
||||||
:return: Tuple containing recognized text and optional timestamp.
|
:return: Tuple containing recognized text and optional timestamp.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Send initial configuration message
|
# Send initial configuration message
|
||||||
config_message = json.dumps(
|
config_message = json.dumps({
|
||||||
{
|
"mode": "offline",
|
||||||
"mode": "offline",
|
"chunk_size": [5, 10, 5],
|
||||||
"chunk_size": [5, 10, 5],
|
"chunk_interval": 10,
|
||||||
"chunk_interval": 10,
|
"wav_name": session_id,
|
||||||
"wav_name": session_id,
|
"is_speaking": True,
|
||||||
"is_speaking": True,
|
"itn": False,
|
||||||
"itn": False,
|
})
|
||||||
}
|
|
||||||
)
|
|
||||||
await ws.send(config_message)
|
await ws.send(config_message)
|
||||||
logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}")
|
logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}")
|
||||||
|
|
||||||
|
|
@ -104,6 +106,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""
|
"""
|
||||||
Convert speech data to text using FunASR.
|
Convert speech data to text using FunASR.
|
||||||
|
|
||||||
:param opus_data: List of Opus-encoded audio data chunks.
|
:param opus_data: List of Opus-encoded audio data chunks.
|
||||||
:param session_id: Unique session identifier.
|
:param session_id: Unique session identifier.
|
||||||
:return: Tuple containing recognized text and optional timestamp.
|
:return: Tuple containing recognized text and optional timestamp.
|
||||||
|
|
@ -115,11 +118,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
# Determine whether to save as WAV file
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
|
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
|
||||||
async with websockets.connect(
|
async with websockets.connect(
|
||||||
self.uri,
|
self.uri,
|
||||||
|
|
@ -151,9 +155,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# Get the result from the receive task
|
# Get the result from the receive task
|
||||||
result = receive_task.result()
|
result = receive_task.result()
|
||||||
|
|
||||||
match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result)
|
match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result)
|
||||||
if match:
|
if match:
|
||||||
result = match.group(4).strip()
|
result = match.group(4).strip()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
result,
|
result,
|
||||||
file_path,
|
file_path,
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,6 @@ class ASRProvider(ASRProviderBase):
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""Convert speech data to text using Groq Whisper API"""
|
"""Convert speech data to text using Groq Whisper API"""
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -115,7 +114,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
if self.delete_audio_file and os.path.exists(audio_file_path):
|
if self.delete_audio_file and os.path.exists(audio_file_path):
|
||||||
try:
|
try:
|
||||||
os.remove(audio_file_path)
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(
|
logger.bind(tag=TAG).warning(
|
||||||
f"Failed to delete audio file {audio_file_path}: {e}"
|
f"Failed to delete audio file {audio_file_path}: {e}"
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import requests
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ASRProvider(ASRProviderBase):
|
class ASRProvider(ASRProviderBase):
|
||||||
def __init__(self, config: dict, delete_audio_file: bool):
|
def __init__(self, config: dict, delete_audio_file: bool):
|
||||||
self.interface_type = InterfaceType.NON_STREAM
|
self.interface_type = InterfaceType.NON_STREAM
|
||||||
|
|
@ -32,7 +33,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug(
|
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}")
|
logger.bind(tag=TAG).info(f"file path: {file_path}")
|
||||||
|
|
@ -40,13 +41,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
}
|
}
|
||||||
|
|
||||||
# 使用data参数传递模型名称
|
# Use data parameter to pass model name
|
||||||
data = {
|
data = {
|
||||||
"model": self.model
|
"model": self.model
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Use with statement to ensure file is closed
|
||||||
with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭
|
with open(file_path, "rb") as audio_file:
|
||||||
files = {
|
files = {
|
||||||
"file": audio_file
|
"file": audio_file
|
||||||
}
|
}
|
||||||
|
|
@ -59,24 +60,26 @@ class ASRProvider(ASRProviderBase):
|
||||||
headers=headers
|
headers=headers
|
||||||
)
|
)
|
||||||
logger.bind(tag=TAG).debug(
|
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:
|
if response.status_code == 200:
|
||||||
text = response.json().get("text", "")
|
text = response.json().get("text", "")
|
||||||
return text, file_path
|
return text, file_path
|
||||||
else:
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}")
|
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}")
|
||||||
return "", None
|
return "", None
|
||||||
finally:
|
finally:
|
||||||
# 文件清理逻辑
|
# File cleanup logic
|
||||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||||
try:
|
try:
|
||||||
os.remove(file_path)
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
|
f"File deletion failed: {file_path} | Error: {e}")
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
# 捕获标准输出
|
# Capture standard output
|
||||||
class CaptureOutput:
|
class CaptureOutput:
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
self._output = io.StringIO()
|
self._output = io.StringIO()
|
||||||
|
|
@ -29,7 +29,7 @@ class CaptureOutput:
|
||||||
self.output = self._output.getvalue()
|
self.output = self._output.getvalue()
|
||||||
self._output.close()
|
self._output.close()
|
||||||
|
|
||||||
# 将捕获到的内容通过 logger 输出
|
# Output captured content through logger
|
||||||
if self.output:
|
if self.output:
|
||||||
logger.bind(tag=TAG).info(self.output.strip())
|
logger.bind(tag=TAG).info(self.output.strip())
|
||||||
|
|
||||||
|
|
@ -40,23 +40,25 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.interface_type = InterfaceType.LOCAL
|
self.interface_type = InterfaceType.LOCAL
|
||||||
self.model_dir = config.get("model_dir")
|
self.model_dir = config.get("model_dir")
|
||||||
self.output_dir = config.get("output_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
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
# 确保输出目录存在
|
# Ensure output directory exists
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
# 初始化模型文件路径
|
# Initialize model file paths
|
||||||
model_files = {
|
model_files = {
|
||||||
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
|
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
|
||||||
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
||||||
}
|
}
|
||||||
|
|
||||||
# 下载并检查模型文件
|
# Download and check model files
|
||||||
try:
|
try:
|
||||||
for file_name, file_path in model_files.items():
|
for file_name, file_path in model_files.items():
|
||||||
if not os.path.isfile(file_path):
|
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_file_download(
|
||||||
model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue",
|
model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue",
|
||||||
file_path=file_name,
|
file_path=file_name,
|
||||||
|
|
@ -64,13 +66,15 @@ class ASRProvider(ASRProviderBase):
|
||||||
)
|
)
|
||||||
|
|
||||||
if not os.path.isfile(file_path):
|
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.model_path = model_files["model.int8.onnx"]
|
||||||
self.tokens_path = model_files["tokens.txt"]
|
self.tokens_path = model_files["tokens.txt"]
|
||||||
|
|
||||||
except Exception as e:
|
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
|
raise
|
||||||
|
|
||||||
with CaptureOutput():
|
with CaptureOutput():
|
||||||
|
|
@ -123,10 +127,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""语音转文本主处理逻辑"""
|
"""Main processing logic for speech to text"""
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# 保存音频文件
|
# Save audio file
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
|
|
@ -134,10 +138,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
logger.bind(tag=TAG).debug(
|
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()
|
start_time = time.time()
|
||||||
s = self.model.create_stream()
|
s = self.model.create_stream()
|
||||||
samples, sample_rate = self.read_wave(file_path)
|
samples, sample_rate = self.read_wave(file_path)
|
||||||
|
|
@ -145,19 +149,22 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.model.decode_stream(s)
|
self.model.decode_stream(s)
|
||||||
text = s.result.text
|
text = s.result.text
|
||||||
logger.bind(tag=TAG).debug(
|
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 text, file_path
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return "", file_path
|
||||||
finally:
|
finally:
|
||||||
# 文件清理逻辑
|
# File cleanup logic
|
||||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||||
try:
|
try:
|
||||||
os.remove(file_path)
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
|
f"File deletion failed: {file_path} | Error: {e}")
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@ logger = setup_logging()
|
||||||
class ASRProvider(ASRProviderBase):
|
class ASRProvider(ASRProviderBase):
|
||||||
API_URL = "https://asr.tencentcloudapi.com"
|
API_URL = "https://asr.tencentcloudapi.com"
|
||||||
API_VERSION = "2019-06-14"
|
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):
|
def __init__(self, config: dict, delete_audio_file: bool = True):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
@ -28,103 +28,106 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.output_dir = config.get("output_dir")
|
self.output_dir = config.get("output_dir")
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
# 确保输出目录存在
|
# Ensure output directory exists
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""Convert speech data to text"""
|
||||||
if not opus_data:
|
if not opus_data:
|
||||||
logger.bind(tag=TAG).warning("音频数据为空!")
|
logger.bind(tag=TAG).warning("Audio data is empty!")
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# 检查配置是否已设置
|
# Check if configuration is set
|
||||||
if not self.secret_id or not self.secret_key:
|
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
|
return None, file_path
|
||||||
|
|
||||||
# 将Opus音频数据解码为PCM
|
# Decode Opus audio data to PCM
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
else:
|
else:
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
# Decide whether to save as WAV file
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
self.save_audio_to_file(pcm_data, session_id)
|
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")
|
base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8")
|
||||||
|
|
||||||
# 构建请求体
|
# Build request body
|
||||||
request_body = self._build_request_body(base64_audio)
|
request_body = self._build_request_body(base64_audio)
|
||||||
|
|
||||||
# 获取认证头
|
# Get authentication headers
|
||||||
timestamp, authorization = self._get_auth_headers(request_body)
|
timestamp, authorization = self._get_auth_headers(request_body)
|
||||||
|
|
||||||
# 发送请求
|
# Send request
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
result = self._send_request(request_body, timestamp, authorization)
|
result = self._send_request(request_body, timestamp, authorization)
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
logger.bind(tag=TAG).debug(
|
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:
|
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
|
return None, file_path
|
||||||
|
|
||||||
def _build_request_body(self, base64_audio: str) -> str:
|
def _build_request_body(self, base64_audio: str) -> str:
|
||||||
"""构建请求体"""
|
"""Build request body"""
|
||||||
request_map = {
|
request_map = {
|
||||||
"ProjectId": 0,
|
"ProjectId": 0,
|
||||||
"SubServiceType": 2, # 一句话识别
|
"SubServiceType": 2, # One-sentence recognition
|
||||||
"EngSerViceType": "16k_zh", # 中文普通话通用
|
"EngSerViceType": "16k_zh", # Chinese Mandarin general
|
||||||
"SourceType": 1, # 音频数据来源为语音文件
|
"SourceType": 1, # Audio data source is speech file
|
||||||
"VoiceFormat": self.FORMAT, # 音频格式
|
"VoiceFormat": self.FORMAT, # Audio format
|
||||||
"Data": base64_audio, # Base64编码的音频数据
|
"Data": base64_audio, # Base64 encoded audio data
|
||||||
"DataLen": len(base64_audio), # 数据长度
|
"DataLen": len(base64_audio), # Data length
|
||||||
}
|
}
|
||||||
|
|
||||||
return json.dumps(request_map)
|
return json.dumps(request_map)
|
||||||
|
|
||||||
def _get_auth_headers(self, request_body: str) -> Tuple[str, str]:
|
def _get_auth_headers(self, request_body: str) -> Tuple[str, str]:
|
||||||
"""获取认证头"""
|
"""Get authentication headers"""
|
||||||
try:
|
try:
|
||||||
# 获取当前UTC时间戳
|
# Get current UTC timestamp
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
timestamp = str(int(now.timestamp()))
|
timestamp = str(int(now.timestamp()))
|
||||||
date = now.strftime("%Y-%m-%d")
|
date = now.strftime("%Y-%m-%d")
|
||||||
|
|
||||||
# 服务名称必须是 "asr"
|
# Service name must be "asr"
|
||||||
service = "asr"
|
service = "asr"
|
||||||
|
|
||||||
# 拼接凭证范围
|
# Concatenate credential scope
|
||||||
credential_scope = f"{date}/{service}/tc3_request"
|
credential_scope = f"{date}/{service}/tc3_request"
|
||||||
|
|
||||||
# 使用TC3-HMAC-SHA256签名方法
|
# Use TC3-HMAC-SHA256 signature method
|
||||||
algorithm = "TC3-HMAC-SHA256"
|
algorithm = "TC3-HMAC-SHA256"
|
||||||
|
|
||||||
# 构建规范请求字符串
|
# Build canonical request string
|
||||||
http_request_method = "POST"
|
http_request_method = "POST"
|
||||||
canonical_uri = "/"
|
canonical_uri = "/"
|
||||||
canonical_query_string = ""
|
canonical_query_string = ""
|
||||||
|
|
||||||
# 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写
|
# Note: Headers need to be sorted in ASCII order, and both key and value are converted to lowercase
|
||||||
# 必须包含content-type和host头部
|
# Must include content-type and host headers
|
||||||
content_type = "application/json; charset=utf-8"
|
content_type = "application/json; charset=utf-8"
|
||||||
host = "asr.tencentcloudapi.com"
|
host = "asr.tencentcloudapi.com"
|
||||||
action = "SentenceRecognition" # 接口名称
|
action = "SentenceRecognition" # Interface name
|
||||||
|
|
||||||
# 构建规范头部信息,注意顺序和格式
|
# Build canonical headers, note order and format
|
||||||
canonical_headers = (
|
canonical_headers = (
|
||||||
f"content-type:{content_type.lower()}\n"
|
f"content-type:{content_type.lower()}\n"
|
||||||
+ f"host:{host.lower()}\n"
|
+ f"host:{host.lower()}\n"
|
||||||
|
|
@ -133,10 +136,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
signed_headers = "content-type;host;x-tc-action"
|
signed_headers = "content-type;host;x-tc-action"
|
||||||
|
|
||||||
# 请求体哈希值
|
# Request body hash value
|
||||||
payload_hash = self._sha256_hex(request_body)
|
payload_hash = self._sha256_hex(request_body)
|
||||||
|
|
||||||
# 构建规范请求字符串
|
# Build canonical request string
|
||||||
canonical_request = (
|
canonical_request = (
|
||||||
f"{http_request_method}\n"
|
f"{http_request_method}\n"
|
||||||
+ f"{canonical_uri}\n"
|
+ f"{canonical_uri}\n"
|
||||||
|
|
@ -146,10 +149,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
+ f"{payload_hash}"
|
+ f"{payload_hash}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 计算规范请求的哈希值
|
# Calculate hash value of canonical request
|
||||||
hashed_canonical_request = self._sha256_hex(canonical_request)
|
hashed_canonical_request = self._sha256_hex(canonical_request)
|
||||||
|
|
||||||
# 构建待签名字符串
|
# Build string to be signed
|
||||||
string_to_sign = (
|
string_to_sign = (
|
||||||
f"{algorithm}\n"
|
f"{algorithm}\n"
|
||||||
+ f"{timestamp}\n"
|
+ f"{timestamp}\n"
|
||||||
|
|
@ -157,17 +160,17 @@ class ASRProvider(ASRProviderBase):
|
||||||
+ f"{hashed_canonical_request}"
|
+ f"{hashed_canonical_request}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 计算签名密钥
|
# Calculate signature key
|
||||||
secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date)
|
secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date)
|
||||||
secret_service = self._hmac_sha256(secret_date, service)
|
secret_service = self._hmac_sha256(secret_date, service)
|
||||||
secret_signing = self._hmac_sha256(secret_service, "tc3_request")
|
secret_signing = self._hmac_sha256(secret_service, "tc3_request")
|
||||||
|
|
||||||
# 计算签名
|
# Calculate signature
|
||||||
signature = self._bytes_to_hex(
|
signature = self._bytes_to_hex(
|
||||||
self._hmac_sha256(secret_signing, string_to_sign)
|
self._hmac_sha256(secret_signing, string_to_sign)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 构建授权头
|
# Build authorization header
|
||||||
authorization = (
|
authorization = (
|
||||||
f"{algorithm} "
|
f"{algorithm} "
|
||||||
+ f"Credential={self.secret_id}/{credential_scope}, "
|
+ f"Credential={self.secret_id}/{credential_scope}, "
|
||||||
|
|
@ -178,13 +181,15 @@ class ASRProvider(ASRProviderBase):
|
||||||
return timestamp, authorization
|
return timestamp, authorization
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(
|
||||||
raise RuntimeError(f"生成认证头失败: {e}")
|
f"Failed to generate authentication headers: {e}", exc_info=True)
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Failed to generate authentication headers: {e}")
|
||||||
|
|
||||||
def _send_request(
|
def _send_request(
|
||||||
self, request_body: str, timestamp: str, authorization: str
|
self, request_body: str, timestamp: str, authorization: str
|
||||||
) -> Optional[str]:
|
) -> Optional[str]:
|
||||||
"""发送请求到腾讯云API"""
|
"""Send request to Tencent Cloud API"""
|
||||||
headers = {
|
headers = {
|
||||||
"Content-Type": "application/json; charset=utf-8",
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
"Host": "asr.tencentcloudapi.com",
|
"Host": "asr.tencentcloudapi.com",
|
||||||
|
|
@ -196,43 +201,47 @@ class ASRProvider(ASRProviderBase):
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
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:
|
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()
|
response_json = response.json()
|
||||||
|
|
||||||
# 检查是否有错误
|
# Check for errors
|
||||||
if "Response" in response_json and "Error" in response_json["Response"]:
|
if "Response" in response_json and "Error" in response_json["Response"]:
|
||||||
error = response_json["Response"]["Error"]
|
error = response_json["Response"]["Error"]
|
||||||
error_code = error["Code"]
|
error_code = error["Code"]
|
||||||
error_message = error["Message"]
|
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"]:
|
if "Response" in response_json and "Result" in response_json["Response"]:
|
||||||
return response_json["Response"]["Result"]
|
return response_json["Response"]["Result"]
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).warning(f"响应中没有识别结果: {response_json}")
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"No recognition result in response: {response_json}")
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
def _sha256_hex(self, data: str) -> str:
|
def _sha256_hex(self, data: str) -> str:
|
||||||
"""计算字符串的SHA256哈希值"""
|
"""Calculate SHA256 hash value of string"""
|
||||||
digest = hashlib.sha256(data.encode("utf-8")).digest()
|
digest = hashlib.sha256(data.encode("utf-8")).digest()
|
||||||
return self._bytes_to_hex(digest)
|
return self._bytes_to_hex(digest)
|
||||||
|
|
||||||
def _hmac_sha256(self, key, data: str) -> bytes:
|
def _hmac_sha256(self, key, data: str) -> bytes:
|
||||||
"""计算HMAC-SHA256"""
|
"""Calculate HMAC-SHA256"""
|
||||||
if isinstance(key, str):
|
if isinstance(key, str):
|
||||||
key = key.encode("utf-8")
|
key = key.encode("utf-8")
|
||||||
|
|
||||||
return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest()
|
return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest()
|
||||||
|
|
||||||
def _bytes_to_hex(self, bytes_data: bytes) -> str:
|
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)
|
return "".join(f"{b:02x}" for b in bytes_data)
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
|
||||||
from typing import List, Dict
|
from typing import List, Dict
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -12,22 +13,23 @@ class IntentProviderBase(ABC):
|
||||||
|
|
||||||
def set_llm(self, llm):
|
def set_llm(self, llm):
|
||||||
self.llm = llm
|
self.llm = llm
|
||||||
# 获取模型名称和类型信息
|
# Get model name and type information
|
||||||
model_name = getattr(llm, "model_name", str(llm.__class__.__name__))
|
model_name = getattr(llm, "model_name", str(llm.__class__.__name__))
|
||||||
# 记录更详细的日志
|
# Log more detailed information
|
||||||
logger.bind(tag=TAG).info(f"意图识别设置LLM: {model_name}")
|
logger.bind(tag=TAG).info(
|
||||||
|
f"Intent recognition setting LLM: {model_name}")
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
||||||
"""
|
"""
|
||||||
检测用户最后一句话的意图
|
Detect the intent of the user's last sentence
|
||||||
Args:
|
Args:
|
||||||
dialogue_history: 对话历史记录列表,每条记录包含role和content
|
dialogue_history: List of dialogue history records, each record contains role and content
|
||||||
Returns:
|
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
|
pass
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from ..base import IntentProviderBase
|
||||||
from typing import List, Dict
|
from typing import List, Dict
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -9,12 +10,12 @@ logger = setup_logging()
|
||||||
class IntentProvider(IntentProviderBase):
|
class IntentProvider(IntentProviderBase):
|
||||||
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
||||||
"""
|
"""
|
||||||
默认的意图识别实现,始终返回继续聊天
|
Default intent recognition implementation, always returns continue chat
|
||||||
Args:
|
Args:
|
||||||
dialogue_history: 对话历史记录列表
|
dialogue_history: List of dialogue history records
|
||||||
text: 本次对话记录
|
text: Current conversation record
|
||||||
Returns:
|
Returns:
|
||||||
固定返回"继续聊天"
|
Fixed return "continue chat"
|
||||||
"""
|
"""
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
"Using functionCallProvider, always returning continue chat"
|
"Using functionCallProvider, always returning continue chat"
|
||||||
|
|
|
||||||
|
|
@ -16,35 +16,34 @@ class IntentProvider(IntentProviderBase):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
self.llm = None
|
self.llm = None
|
||||||
self.promot = ""
|
self.promot = ""
|
||||||
# 导入全局缓存管理器
|
# Add cache management
|
||||||
from core.utils.cache.manager import cache_manager, CacheType
|
self.intent_cache = {} # Cache for intent recognition results
|
||||||
|
self.cache_expiry = 600 # Cache validity period of 10 minutes
|
||||||
self.cache_manager = cache_manager
|
self.cache_max_size = 100 # Maximum of 100 intents to cache
|
||||||
self.CacheType = CacheType
|
self.history_count = 4 # Default to using the last 4 conversation records
|
||||||
self.history_count = 4 # 默认使用最近4条对话记录
|
|
||||||
|
|
||||||
def get_intent_system_prompt(self, functions_list: str) -> str:
|
def get_intent_system_prompt(self, functions_list: str) -> str:
|
||||||
"""
|
"""
|
||||||
根据配置的意图选项和可用函数动态生成系统提示词
|
Dynamically generate a system prompt based on configured intent options and available functions.
|
||||||
Args:
|
Args:
|
||||||
functions: 可用的函数列表,JSON格式字符串
|
functions: A list of available functions in JSON format string.
|
||||||
Returns:
|
Returns:
|
||||||
格式化后的系统提示词
|
A formatted system prompt.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# 构建函数说明部分
|
# Build the function description part
|
||||||
functions_desc = "可用的函数列表:\n"
|
functions_desc = "Available functions list:\n"
|
||||||
for func in functions_list:
|
for func in functions_list:
|
||||||
func_info = func.get("function", {})
|
func_info = func.get("function", {})
|
||||||
name = func_info.get("name", "")
|
name = func_info.get("name", "")
|
||||||
desc = func_info.get("description", "")
|
desc = func_info.get("description", "")
|
||||||
params = func_info.get("parameters", {})
|
params = func_info.get("parameters", {})
|
||||||
|
|
||||||
functions_desc += f"\n函数名: {name}\n"
|
functions_desc += f"\nFunction Name: {name}\n"
|
||||||
functions_desc += f"描述: {desc}\n"
|
functions_desc += f"Description: {desc}\n"
|
||||||
|
|
||||||
if params:
|
if params:
|
||||||
functions_desc += "参数:\n"
|
functions_desc += "Parameters:\n"
|
||||||
for param_name, param_info in params.get("properties", {}).items():
|
for param_name, param_info in params.get("properties", {}).items():
|
||||||
param_desc = param_info.get("description", "")
|
param_desc = param_info.get("description", "")
|
||||||
param_type = param_info.get("type", "")
|
param_type = param_info.get("type", "")
|
||||||
|
|
@ -53,60 +52,81 @@ class IntentProvider(IntentProviderBase):
|
||||||
functions_desc += "---\n"
|
functions_desc += "---\n"
|
||||||
|
|
||||||
prompt = (
|
prompt = (
|
||||||
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\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"
|
||||||
"- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\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"
|
||||||
"- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\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"
|
f"{functions_desc}\n"
|
||||||
"处理步骤:\n"
|
"Processing Steps:\n"
|
||||||
"1. 分析用户输入,确定用户意图\n"
|
"1. Analyze user input to determine user intent.\n"
|
||||||
"2. 从可用函数列表中选择最匹配的函数\n"
|
"2. Select the best matching function from the list of available functions.\n"
|
||||||
"3. 如果找到匹配的函数,生成对应的function_call 格式\n"
|
"3. If a matching function is found, generate the corresponding function_call format.\n"
|
||||||
'4. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n'
|
'4. If no matching function is found, return {"function_call": {"name": "continue_chat"}}\n\n'
|
||||||
"返回格式要求:\n"
|
"Return Format Requirements:\n"
|
||||||
"1. 必须返回纯JSON格式\n"
|
"1. Must return in pure JSON format.\n"
|
||||||
"2. 必须包含function_call字段\n"
|
"2. Must include the function_call field.\n"
|
||||||
"3. function_call必须包含name字段\n"
|
"3. function_call must include the name field.\n"
|
||||||
"4. 如果函数需要参数,必须包含arguments字段\n\n"
|
"4. If the function requires parameters, it must include the arguments field.\n\n"
|
||||||
"示例:\n"
|
"Examples:\n"
|
||||||
"```\n"
|
"```\n"
|
||||||
"用户: 现在几点了?\n"
|
"User: What time is it?\n"
|
||||||
'返回: {"function_call": {"name": "get_time"}}\n'
|
'Return: {"function_call": {"name": "get_time"}}\n'
|
||||||
"```\n"
|
"```\n"
|
||||||
"```\n"
|
"```\n"
|
||||||
"用户: 当前电池电量是多少?\n"
|
"User: What is the current battery level?\n"
|
||||||
'返回: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "当前电池电量为{value}%", "response_failure": "无法获取Battery的当前电量百分比"}}}\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"
|
"```\n"
|
||||||
"用户: 当前屏幕亮度是多少?\n"
|
"User: What is the current screen brightness?\n"
|
||||||
'返回: {"function_call": {"name": "self_screen_get_brightness"}}\n'
|
'Return: {"function_call": {"name": "self_screen_get_brightness"}}\n'
|
||||||
"```\n"
|
"```\n"
|
||||||
"```\n"
|
"```\n"
|
||||||
"用户: 设置屏幕亮度为50%\n"
|
"User: Set screen brightness to 50%.\n"
|
||||||
'返回: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
|
'Return: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
|
||||||
"```\n"
|
"```\n"
|
||||||
"```\n"
|
"```\n"
|
||||||
"用户: 我想结束对话\n"
|
"User: I want to end the conversation.\n"
|
||||||
'返回: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
|
'Return: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
|
||||||
"```\n"
|
"```\n"
|
||||||
"```\n"
|
"```\n"
|
||||||
"用户: 你好啊\n"
|
"User: Hello.\n"
|
||||||
'返回: {"function_call": {"name": "continue_chat"}}\n'
|
'Return: {"function_call": {"name": "continue_chat"}}\n'
|
||||||
"```\n\n"
|
"```\n\n"
|
||||||
"注意:\n"
|
"Note:\n"
|
||||||
"1. 只返回JSON格式,不要包含任何其他文字\n"
|
"1. Only return in JSON format, do not include any other text.\n"
|
||||||
'2. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
|
'2. If no matching function is found, return {"function_call": {"name": "continue_chat"}}.\n'
|
||||||
"3. 确保返回的JSON格式正确,包含所有必要的字段\n"
|
"3. Ensure the returned JSON format is correct and includes all necessary fields.\n"
|
||||||
"特殊说明:\n"
|
"Special Instructions:\n"
|
||||||
"- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n"
|
"- When a single user input contains multiple commands (e.g., 'turn on the light and increase the volume').\n"
|
||||||
"- 请返回多个function_call组成的JSON数组\n"
|
"- Please return a JSON array of multiple function_calls.\n"
|
||||||
"- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}"
|
"- Example: {'function_calls': [{'name':'light_on'}, {'name':'volume_up'}]}"
|
||||||
)
|
)
|
||||||
return prompt
|
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):
|
def replyResult(self, text: str, original_text: str):
|
||||||
llm_result = self.llm.response_no_stream(
|
llm_result = self.llm.response_no_stream(
|
||||||
system_prompt=text,
|
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,
|
+ original_text,
|
||||||
)
|
)
|
||||||
return llm_result
|
return llm_result
|
||||||
|
|
@ -117,24 +137,31 @@ class IntentProvider(IntentProviderBase):
|
||||||
if conn.func_handler is None:
|
if conn.func_handler is None:
|
||||||
return '{"function_call": {"name": "continue_chat"}}'
|
return '{"function_call": {"name": "continue_chat"}}'
|
||||||
|
|
||||||
# 记录整体开始时间
|
# Record the overall start time
|
||||||
total_start_time = time.time()
|
total_start_time = time.time()
|
||||||
|
|
||||||
# 打印使用的模型信息
|
# Print the model information being used
|
||||||
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
model_info = getattr(self.llm, "model_name",
|
||||||
logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}")
|
str(self.llm.__class__.__name__))
|
||||||
|
logger.bind(tag=TAG).debug(
|
||||||
|
f"Using intent recognition model: {model_info}")
|
||||||
|
|
||||||
# 计算缓存键
|
# Calculate the cache key
|
||||||
cache_key = hashlib.md5((conn.device_id + text).encode()).hexdigest()
|
cache_key = hashlib.md5(text.encode()).hexdigest()
|
||||||
|
|
||||||
# 检查缓存
|
# Check the cache
|
||||||
cached_intent = self.cache_manager.get(self.CacheType.INTENT, cache_key)
|
if cache_key in self.intent_cache:
|
||||||
if cached_intent is not None:
|
cache_entry = self.intent_cache[cache_key]
|
||||||
cache_time = time.time() - total_start_time
|
# Check if the cache has expired
|
||||||
logger.bind(tag=TAG).debug(
|
if time.time() - cache_entry["timestamp"] <= self.cache_expiry:
|
||||||
f"使用缓存的意图: {cache_key} -> {cached_intent}, 耗时: {cache_time:.4f}秒"
|
cache_time = time.time() - total_start_time
|
||||||
)
|
logger.bind(tag=TAG).debug(
|
||||||
return cached_intent
|
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 == "":
|
if self.promot == "":
|
||||||
functions = conn.func_handler.get_functions()
|
functions = conn.func_handler.get_functions()
|
||||||
|
|
@ -157,17 +184,17 @@ class IntentProvider(IntentProviderBase):
|
||||||
else:
|
else:
|
||||||
devices = []
|
devices = []
|
||||||
if len(devices) > 0:
|
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:
|
for device in devices:
|
||||||
hass_prompt += device + "\n"
|
hass_prompt += device + "\n"
|
||||||
prompt_music += hass_prompt
|
prompt_music += hass_prompt
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
||||||
|
|
||||||
# 构建用户对话历史的提示
|
# Build the user dialogue history prompt
|
||||||
msgStr = ""
|
msgStr = ""
|
||||||
|
|
||||||
# 获取最近的对话历史
|
# Get the recent dialogue history
|
||||||
start_idx = max(0, len(dialogue_history) - self.history_count)
|
start_idx = max(0, len(dialogue_history) - self.history_count)
|
||||||
for i in range(start_idx, len(dialogue_history)):
|
for i in range(start_idx, len(dialogue_history)):
|
||||||
msgStr += f"{dialogue_history[i].role}: {dialogue_history[i].content}\n"
|
msgStr += f"{dialogue_history[i].role}: {dialogue_history[i].content}\n"
|
||||||
|
|
@ -175,57 +202,59 @@ class IntentProvider(IntentProviderBase):
|
||||||
msgStr += f"User: {text}\n"
|
msgStr += f"User: {text}\n"
|
||||||
user_prompt = f"current dialogue:\n{msgStr}"
|
user_prompt = f"current dialogue:\n{msgStr}"
|
||||||
|
|
||||||
# 记录预处理完成时间
|
# Record the preprocessing completion time
|
||||||
preprocess_time = time.time() - total_start_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()
|
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(
|
intent = self.llm.response_no_stream(
|
||||||
system_prompt=prompt_music, user_prompt=user_prompt
|
system_prompt=prompt_music, user_prompt=user_prompt
|
||||||
)
|
)
|
||||||
|
|
||||||
# 记录LLM调用完成时间
|
# Record the LLM call completion time
|
||||||
llm_time = time.time() - llm_start_time
|
llm_time = time.time() - llm_start_time
|
||||||
logger.bind(tag=TAG).debug(
|
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()
|
postprocess_start_time = time.time()
|
||||||
|
|
||||||
# 清理和解析响应
|
# Clean and parse the response
|
||||||
intent = intent.strip()
|
intent = intent.strip()
|
||||||
# 尝试提取JSON部分
|
# Try to extract the JSON part
|
||||||
match = re.search(r"\{.*\}", intent, re.DOTALL)
|
match = re.search(r"\{.*\}", intent, re.DOTALL)
|
||||||
if match:
|
if match:
|
||||||
intent = match.group(0)
|
intent = match.group(0)
|
||||||
|
|
||||||
# 记录总处理时间
|
# Record the total processing time
|
||||||
total_time = time.time() - total_start_time
|
total_time = time.time() - total_start_time
|
||||||
logger.bind(tag=TAG).debug(
|
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:
|
try:
|
||||||
intent_data = json.loads(intent)
|
intent_data = json.loads(intent)
|
||||||
# 如果包含function_call,则格式化为适合处理的格式
|
# If it contains function_call, format it for processing
|
||||||
if "function_call" in intent_data:
|
if "function_call" in intent_data:
|
||||||
function_data = intent_data["function_call"]
|
function_data = intent_data["function_call"]
|
||||||
function_name = function_data.get("name")
|
function_name = function_data.get("name")
|
||||||
function_args = function_data.get("arguments", {})
|
function_args = function_data.get("arguments", {})
|
||||||
|
|
||||||
# 记录识别到的function call
|
# Record the recognized function call
|
||||||
logger.bind(tag=TAG).info(
|
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":
|
if function_name == "continue_chat":
|
||||||
# 保留非工具相关的消息
|
# Keep non-tool related messages
|
||||||
clean_history = [
|
clean_history = [
|
||||||
msg
|
msg
|
||||||
for msg in conn.dialogue.dialogue
|
for msg in conn.dialogue.dialogue
|
||||||
|
|
@ -233,30 +262,38 @@ class IntentProvider(IntentProviderBase):
|
||||||
]
|
]
|
||||||
conn.dialogue.dialogue = clean_history
|
conn.dialogue.dialogue = clean_history
|
||||||
|
|
||||||
# 添加到缓存
|
# Add to cache
|
||||||
self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
|
self.intent_cache[cache_key] = {
|
||||||
|
"intent": intent,
|
||||||
|
"timestamp": time.time(),
|
||||||
|
}
|
||||||
|
|
||||||
# 后处理时间
|
# Post-processing time
|
||||||
postprocess_time = time.time() - postprocess_start_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
|
return intent
|
||||||
else:
|
else:
|
||||||
# 添加到缓存
|
# Add to cache
|
||||||
self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
|
self.intent_cache[cache_key] = {
|
||||||
|
"intent": intent,
|
||||||
|
"timestamp": time.time(),
|
||||||
|
}
|
||||||
|
|
||||||
# 后处理时间
|
# Post-processing time
|
||||||
postprocess_time = time.time() - postprocess_start_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
|
return intent
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
# 后处理时间
|
# Post-processing time
|
||||||
postprocess_time = time.time() - postprocess_start_time
|
postprocess_time = time.time() - postprocess_start_time
|
||||||
logger.bind(tag=TAG).error(
|
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"
|
||||||
)
|
)
|
||||||
# 如果解析失败,默认返回继续聊天意图
|
# If parsing fails, default to returning a continue chat intent
|
||||||
return '{"intent": "继续聊天"}'
|
return '{"intent": "Continue Chat"}'
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from ..base import IntentProviderBase
|
||||||
from typing import List, Dict
|
from typing import List, Dict
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -9,12 +10,12 @@ logger = setup_logging()
|
||||||
class IntentProvider(IntentProviderBase):
|
class IntentProvider(IntentProviderBase):
|
||||||
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
||||||
"""
|
"""
|
||||||
默认的意图识别实现,始终返回继续聊天
|
Default intent recognition implementation, always returns continue chat
|
||||||
Args:
|
Args:
|
||||||
dialogue_history: 对话历史记录列表
|
dialogue_history: List of dialogue history records
|
||||||
text: 本次对话记录
|
text: Current conversation record
|
||||||
Returns:
|
Returns:
|
||||||
固定返回"继续聊天"
|
Fixed return "continue chat"
|
||||||
"""
|
"""
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
"Using NoIntentProvider, always returning continue chat"
|
"Using NoIntentProvider, always returning continue chat"
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ from dashscope import Application
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -19,14 +20,14 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
def response(self, session_id, dialogue):
|
def response(self, session_id, dialogue):
|
||||||
try:
|
try:
|
||||||
# 处理dialogue
|
# Process dialogue
|
||||||
if self.is_No_prompt:
|
if self.is_No_prompt:
|
||||||
dialogue.pop(0)
|
dialogue.pop(0)
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"【阿里百练API服务】处理后的dialogue: {dialogue}"
|
f"[Alibaba Bailian API Service] Processed dialogue: {dialogue}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 构造调用参数
|
# Construct call parameters
|
||||||
call_params = {
|
call_params = {
|
||||||
"api_key": self.api_key,
|
"api_key": self.api_key,
|
||||||
"app_id": self.app_id,
|
"app_id": self.app_id,
|
||||||
|
|
@ -34,12 +35,12 @@ class LLMProvider(LLMProviderBase):
|
||||||
"messages": dialogue,
|
"messages": dialogue,
|
||||||
}
|
}
|
||||||
if self.memory_id != False:
|
if self.memory_id != False:
|
||||||
# 百练memory需要prompt参数
|
# Bailian memory requires prompt parameter
|
||||||
prompt = dialogue[-1].get("content")
|
prompt = dialogue[-1].get("content")
|
||||||
call_params["memory_id"] = self.memory_id
|
call_params["memory_id"] = self.memory_id
|
||||||
call_params["prompt"] = prompt
|
call_params["prompt"] = prompt
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"【阿里百练API服务】处理后的prompt: {prompt}"
|
f"[Alibaba Bailian API Service] Processed prompt: {prompt}"
|
||||||
)
|
)
|
||||||
|
|
||||||
responses = Application.call(**call_params)
|
responses = Application.call(**call_params)
|
||||||
|
|
@ -47,20 +48,21 @@ class LLMProvider(LLMProviderBase):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"code={responses.status_code}, "
|
f"code={responses.status_code}, "
|
||||||
f"message={responses.message}, "
|
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:
|
else:
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"【阿里百练API服务】构造参数: {call_params}"
|
f"[Alibaba Bailian API Service] Constructed parameters: {call_params}"
|
||||||
)
|
)
|
||||||
yield responses.output.text
|
yield responses.output.text
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
yield "【LLM服务响应异常】"
|
f"[Alibaba Bailian API Service] Response exception: {e}")
|
||||||
|
yield "[LLM Service Response Exception]"
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
logger.bind(tag=TAG).error(
|
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"
|
||||||
)
|
)
|
||||||
|
|
@ -1,9 +1,11 @@
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class LLMProviderBase(ABC):
|
class LLMProviderBase(ABC):
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def response(self, session_id, dialogue):
|
def response(self, session_id, dialogue):
|
||||||
|
|
@ -12,7 +14,7 @@ class LLMProviderBase(ABC):
|
||||||
|
|
||||||
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
|
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
|
||||||
try:
|
try:
|
||||||
# 构造对话格式
|
# Construct dialogue format
|
||||||
dialogue = [
|
dialogue = [
|
||||||
{"role": "system", "content": system_prompt},
|
{"role": "system", "content": system_prompt},
|
||||||
{"role": "user", "content": user_prompt}
|
{"role": "user", "content": user_prompt}
|
||||||
|
|
@ -23,17 +25,18 @@ class LLMProviderBase(ABC):
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
return "【LLM服务响应异常】"
|
f"Error in Ollama response generation: {e}")
|
||||||
|
return "[LLM Service Response Exception]"
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
"""
|
"""
|
||||||
Default implementation for function calling (streaming)
|
Default implementation for function calling (streaming)
|
||||||
This should be overridden by providers that support function calls
|
This should be overridden by providers that support function calls
|
||||||
|
|
||||||
|
|
||||||
Returns: generator that yields either text tokens or a special function call token
|
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 providers that don't support functions, just return regular response
|
||||||
for token in self.response(session_id, dialogue):
|
for token in self.response(session_id, dialogue):
|
||||||
yield token, None
|
yield token, None
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from config.logger import setup_logging
|
||||||
import json
|
import json
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
|
|
||||||
|
|
||||||
# official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
|
# official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
|
||||||
from cozepy import COZE_CN_BASE_URL
|
from cozepy import COZE_CN_BASE_URL
|
||||||
from cozepy import (
|
from cozepy import (
|
||||||
|
|
@ -13,34 +14,41 @@ from cozepy import (
|
||||||
from core.providers.llm.system_prompt import get_system_prompt_for_function
|
from core.providers.llm.system_prompt import get_system_prompt_for_function
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.personal_access_token = config.get("personal_access_token")
|
self.personal_access_token = config.get("personal_access_token")
|
||||||
self.bot_id = str(config.get("bot_id"))
|
self.bot_id = str(config.get("bot_id"))
|
||||||
self.user_id = str(config.get("user_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)
|
model_key_msg = check_model_key("CozeLLM", self.personal_access_token)
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
coze_api_token = self.personal_access_token
|
coze_api_token = self.personal_access_token
|
||||||
coze_api_base = COZE_CN_BASE_URL
|
coze_api_base = COZE_CN_BASE_URL
|
||||||
|
|
||||||
|
|
||||||
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
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)
|
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
|
||||||
conversation_id = self.session_conversation_map.get(session_id)
|
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:
|
if not conversation_id:
|
||||||
conversation = coze.conversations.create(messages=[])
|
conversation = coze.conversations.create(messages=[])
|
||||||
conversation_id = conversation.id
|
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(
|
for event in coze.chat.stream(
|
||||||
bot_id=self.bot_id,
|
bot_id=self.bot_id,
|
||||||
|
|
@ -54,15 +62,17 @@ class LLMProvider(LLMProviderBase):
|
||||||
print(event.message.content, end="", flush=True)
|
print(event.message.content, end="", flush=True)
|
||||||
yield event.message.content
|
yield event.message.content
|
||||||
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
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"]
|
last_msg = dialogue[-1]["content"]
|
||||||
function_str = json.dumps(functions, ensure_ascii=False)
|
function_str = json.dumps(functions, ensure_ascii=False)
|
||||||
modify_msg = get_system_prompt_for_function(function_str) + last_msg
|
modify_msg = get_system_prompt_for_function(function_str) + last_msg
|
||||||
dialogue[-1]["content"] = modify_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":
|
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
|
||||||
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
|
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
|
||||||
while len(dialogue) > 1:
|
while len(dialogue) > 1:
|
||||||
|
|
@ -71,5 +81,6 @@ class LLMProvider(LLMProviderBase):
|
||||||
break
|
break
|
||||||
dialogue.pop()
|
dialogue.pop()
|
||||||
|
|
||||||
|
|
||||||
for token in self.response(session_id, dialogue):
|
for token in self.response(session_id, dialogue):
|
||||||
yield token, None
|
yield token, None
|
||||||
|
|
@ -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.providers.llm.system_prompt import get_system_prompt_for_function
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.api_key = config["api_key"]
|
self.api_key = config["api_key"]
|
||||||
self.mode = config.get("mode", "chat-messages")
|
self.mode = config.get("mode", "chat-messages")
|
||||||
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip("/")
|
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)
|
model_key_msg = check_model_key("DifyLLM", self.api_key)
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
try:
|
||||||
# 取最后一条用户消息
|
# Get the last user message
|
||||||
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
||||||
conversation_id = self.session_conversation_map.get(session_id)
|
conversation_id = self.session_conversation_map.get(session_id)
|
||||||
|
|
||||||
# 发起流式请求
|
|
||||||
|
# Initiate streaming request
|
||||||
if self.mode == "chat-messages":
|
if self.mode == "chat-messages":
|
||||||
request_json = {
|
request_json = {
|
||||||
"query": last_msg["content"],
|
"query": last_msg["content"],
|
||||||
|
|
@ -47,6 +51,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
"user": session_id,
|
"user": session_id,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
with requests.post(
|
with requests.post(
|
||||||
f"{self.base_url}/{self.mode}",
|
f"{self.base_url}/{self.mode}",
|
||||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||||
|
|
@ -57,13 +62,13 @@ class LLMProvider(LLMProviderBase):
|
||||||
for line in r.iter_lines():
|
for line in r.iter_lines():
|
||||||
if line.startswith(b"data: "):
|
if line.startswith(b"data: "):
|
||||||
event = json.loads(line[6:])
|
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:
|
if not conversation_id:
|
||||||
conversation_id = event.get("conversation_id")
|
conversation_id = event.get("conversation_id")
|
||||||
self.session_conversation_map[session_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(
|
if event.get("event") != "message_replace" and event.get(
|
||||||
"answer"
|
"answer"
|
||||||
):
|
):
|
||||||
|
|
@ -76,30 +81,33 @@ class LLMProvider(LLMProviderBase):
|
||||||
if event["data"]["status"] == "succeeded":
|
if event["data"]["status"] == "succeeded":
|
||||||
yield event["data"]["outputs"]["answer"]
|
yield event["data"]["outputs"]["answer"]
|
||||||
else:
|
else:
|
||||||
yield "【服务响应异常】"
|
yield "[Service Response Exception]"
|
||||||
elif self.mode == "completion-messages":
|
elif self.mode == "completion-messages":
|
||||||
for line in r.iter_lines():
|
for line in r.iter_lines():
|
||||||
if line.startswith(b"data: "):
|
if line.startswith(b"data: "):
|
||||||
event = json.loads(line[6:])
|
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(
|
if event.get("event") != "message_replace" and event.get(
|
||||||
"answer"
|
"answer"
|
||||||
):
|
):
|
||||||
yield event["answer"]
|
yield event["answer"]
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {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):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
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"]
|
last_msg = dialogue[-1]["content"]
|
||||||
function_str = json.dumps(functions, ensure_ascii=False)
|
function_str = json.dumps(functions, ensure_ascii=False)
|
||||||
modify_msg = get_system_prompt_for_function(function_str) + last_msg
|
modify_msg = get_system_prompt_for_function(function_str) + last_msg
|
||||||
dialogue[-1]["content"] = modify_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":
|
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
|
||||||
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
|
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
|
||||||
while len(dialogue) > 1:
|
while len(dialogue) > 1:
|
||||||
|
|
@ -108,5 +116,6 @@ class LLMProvider(LLMProviderBase):
|
||||||
break
|
break
|
||||||
dialogue.pop()
|
dialogue.pop()
|
||||||
|
|
||||||
|
|
||||||
for token in self.response(session_id, dialogue):
|
for token in self.response(session_id, dialogue):
|
||||||
yield token, None
|
yield token, None
|
||||||
|
|
@ -4,10 +4,12 @@ import requests
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.api_key = config["api_key"]
|
self.api_key = config["api_key"]
|
||||||
|
|
@ -18,12 +20,14 @@ class LLMProvider(LLMProviderBase):
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
try:
|
||||||
# 取最后一条用户消息
|
# Get the last user message
|
||||||
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
||||||
|
|
||||||
# 发起流式请求
|
|
||||||
|
# Initiate streaming request
|
||||||
with requests.post(
|
with requests.post(
|
||||||
f"{self.base_url}/chat/completions",
|
f"{self.base_url}/chat/completions",
|
||||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||||
|
|
@ -43,6 +47,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
if line[6:].decode("utf-8") == "[DONE]":
|
if line[6:].decode("utf-8") == "[DONE]":
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
||||||
data = json.loads(line[6:])
|
data = json.loads(line[6:])
|
||||||
if "choices" in data and len(data["choices"]) > 0:
|
if "choices" in data and len(data["choices"]) > 0:
|
||||||
delta = data["choices"][0].get("delta", {})
|
delta = data["choices"][0].get("delta", {})
|
||||||
|
|
@ -58,16 +63,19 @@ class LLMProvider(LLMProviderBase):
|
||||||
continue
|
continue
|
||||||
yield content
|
yield content
|
||||||
|
|
||||||
|
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {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):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
logger.bind(tag=TAG).error(
|
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"
|
||||||
)
|
)
|
||||||
|
|
@ -1,24 +1,26 @@
|
||||||
import os, json, uuid
|
import os
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from google import generativeai as genai
|
from google import generativeai as genai
|
||||||
from google.generativeai import types, GenerationConfig
|
from google.generativeai import types, GenerationConfig
|
||||||
|
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from google.generativeai.types import GenerateContentResponse
|
from google.generativeai.types import GenerateContentResponse
|
||||||
from requests import RequestException
|
from requests import RequestException
|
||||||
|
|
||||||
|
|
||||||
log = setup_logging()
|
log = setup_logging()
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
def test_proxy(proxy_url: str, test_url: str) -> bool:
|
def test_proxy(proxy_url: str, test_url: str) -> bool:
|
||||||
try:
|
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
|
return 200 <= resp.status_code < 400
|
||||||
except RequestException:
|
except RequestException:
|
||||||
return False
|
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):
|
def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
|
||||||
"""
|
"""
|
||||||
分别测试 HTTP 和 HTTPS 代理是否可用,并设置环境变量。
|
Test whether HTTP and HTTPS proxies are available separately, and set environment variables.
|
||||||
如果 HTTPS 代理不可用但 HTTP 可用,会将 HTTPS_PROXY 也指向 HTTP。
|
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_http_url = "http://www.google.com"
|
||||||
test_https_url = "https://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)
|
ok_http = test_proxy(http_proxy, test_http_url)
|
||||||
if ok_http:
|
if ok_http:
|
||||||
os.environ["HTTP_PROXY"] = http_proxy
|
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:
|
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:
|
if https_proxy:
|
||||||
ok_https = test_proxy(https_proxy, test_https_url)
|
ok_https = test_proxy(https_proxy, test_https_url)
|
||||||
if ok_https:
|
if ok_https:
|
||||||
os.environ["HTTPS_PROXY"] = https_proxy
|
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:
|
else:
|
||||||
log.bind(tag=TAG).warning(
|
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 ok_http and not ok_https:
|
||||||
if test_proxy(http_proxy, test_https_url):
|
if test_proxy(http_proxy, test_https_url):
|
||||||
os.environ["HTTPS_PROXY"] = http_proxy
|
os.environ["HTTPS_PROXY"] = http_proxy
|
||||||
ok_https = True
|
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:
|
if not ok_http and not ok_https:
|
||||||
log.bind(tag=TAG).error(
|
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):
|
class LLMProvider(LLMProviderBase):
|
||||||
|
|
@ -79,11 +86,11 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
if http_proxy or https_proxy:
|
if http_proxy or https_proxy:
|
||||||
log.bind(tag=TAG).info(
|
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)
|
setup_proxy_env(http_proxy, https_proxy)
|
||||||
log.bind(tag=TAG).info(
|
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)
|
genai.configure(api_key=self.api_key)
|
||||||
self.model = genai.GenerativeModel(self.model_name)
|
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):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
yield from self._generate(dialogue, None)
|
yield from self._generate(dialogue, None)
|
||||||
|
|
||||||
|
|
@ -122,7 +130,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
def _generate(self, dialogue, tools):
|
def _generate(self, dialogue, tools):
|
||||||
role_map = {"assistant": "model", "user": "user"}
|
role_map = {"assistant": "model", "user": "user"}
|
||||||
contents: list = []
|
contents: list = []
|
||||||
# 拼接对话
|
# Concatenate dialogue
|
||||||
for m in dialogue:
|
for m in dialogue:
|
||||||
r = m["role"]
|
r = m["role"]
|
||||||
|
|
||||||
|
|
@ -170,7 +178,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
cand = chunk.candidates[0]
|
cand = chunk.candidates[0]
|
||||||
for part in cand.content.parts:
|
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):
|
if getattr(part, "function_call", None):
|
||||||
fc = part.function_call
|
fc = part.function_call
|
||||||
yield None, [
|
yield None, [
|
||||||
|
|
@ -186,15 +194,16 @@ class LLMProvider(LLMProviderBase):
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
return
|
return
|
||||||
# b) 普通文本
|
# b) Plain text
|
||||||
if getattr(part, "text", None):
|
if getattr(part, "text", None):
|
||||||
yield part.text if tools is None else (part.text, None)
|
yield part.text if tools is None else (part.text, None)
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
if tools is not None:
|
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
|
@staticmethod
|
||||||
def _safe_finish_stream(stream: GenerateContentResponse):
|
def _safe_finish_stream(stream: GenerateContentResponse):
|
||||||
if hasattr(stream, "resolve"):
|
if hasattr(stream, "resolve"):
|
||||||
|
|
@ -202,5 +211,5 @@ class LLMProvider(LLMProviderBase):
|
||||||
elif hasattr(stream, "close"):
|
elif hasattr(stream, "close"):
|
||||||
stream.close() # Gemini SDK version < 0.5.0
|
stream.close() # Gemini SDK version < 0.5.0
|
||||||
else:
|
else:
|
||||||
for _ in stream: # 兜底耗尽
|
for _ in stream: # Fallback to exhaust
|
||||||
pass
|
pass
|
||||||
|
|
@ -9,43 +9,46 @@ logger = setup_logging()
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
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.api_key = config.get("api_key")
|
||||||
self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url
|
# Default to use base_url
|
||||||
self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API 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):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
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
|
input_text = None
|
||||||
if isinstance(dialogue, list): # 确保 dialogue 是一个列表
|
if isinstance(dialogue, list): # Ensure dialogue is a list
|
||||||
# 逆序遍历,找到最后一个 role 为 'user' 的消息
|
# Iterate in reverse order to find the last message with role 'user'
|
||||||
for message in reversed(dialogue):
|
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", "")
|
input_text = message.get("content", "")
|
||||||
break # 找到后立即退出循环
|
break # Exit loop immediately after finding
|
||||||
|
|
||||||
# 构造请求数据
|
# Construct request data
|
||||||
payload = {
|
payload = {
|
||||||
"text": input_text,
|
"text": input_text,
|
||||||
"agent_id": self.agent_id,
|
"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 = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
}
|
}
|
||||||
|
|
||||||
# 发起 POST 请求
|
# Send POST request
|
||||||
response = requests.post(self.api_url, json=payload, headers=headers)
|
response = requests.post(
|
||||||
|
self.api_url, json=payload, headers=headers)
|
||||||
|
|
||||||
# 检查请求是否成功
|
# Check if request was successful
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
# 解析返回数据
|
# Parse returned data
|
||||||
data = response.json()
|
data = response.json()
|
||||||
speech = (
|
speech = (
|
||||||
data.get("response", {})
|
data.get("response", {})
|
||||||
|
|
@ -54,18 +57,19 @@ class LLMProvider(LLMProviderBase):
|
||||||
.get("speech", "")
|
.get("speech", "")
|
||||||
)
|
)
|
||||||
|
|
||||||
# 返回生成的内容
|
# Return generated content
|
||||||
if speech:
|
if speech:
|
||||||
yield speech
|
yield speech
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
|
logger.bind(tag=TAG).warning(
|
||||||
|
"No speech content in API returned data")
|
||||||
|
|
||||||
except RequestException as e:
|
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:
|
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):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
logger.bind(tag=TAG).error(
|
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"
|
||||||
)
|
)
|
||||||
|
|
@ -3,54 +3,63 @@ from openai import OpenAI
|
||||||
import json
|
import json
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.model_name = config.get("model_name")
|
self.model_name = config.get("model_name")
|
||||||
self.base_url = config.get("base_url", "http://localhost:11434")
|
self.base_url = config.get("base_url", "http://localhost:11434")
|
||||||
# Initialize OpenAI client with Ollama base URL
|
# Initialize OpenAI client with Ollama base URL
|
||||||
# 如果没有v1,增加v1
|
# If there's no v1, add v1
|
||||||
if not self.base_url.endswith("/v1"):
|
if not self.base_url.endswith("/v1"):
|
||||||
self.base_url = f"{self.base_url}/v1"
|
self.base_url = f"{self.base_url}/v1"
|
||||||
|
|
||||||
|
|
||||||
self.client = OpenAI(
|
self.client = OpenAI(
|
||||||
base_url=self.base_url,
|
base_url=self.base_url,
|
||||||
api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
|
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")
|
self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3")
|
||||||
|
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
try:
|
||||||
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
|
# If it's a qwen3 model, add /no_think instruction to the user's last message
|
||||||
if self.is_qwen3:
|
if self.is_qwen3:
|
||||||
# 复制对话列表,避免修改原始对话
|
# Copy dialogue list to avoid modifying the original dialogue
|
||||||
dialogue_copy = dialogue.copy()
|
dialogue_copy = dialogue.copy()
|
||||||
|
|
||||||
# 找到最后一条用户消息
|
|
||||||
|
# Find the last user message
|
||||||
for i in range(len(dialogue_copy) - 1, -1, -1):
|
for i in range(len(dialogue_copy) - 1, -1, -1):
|
||||||
if dialogue_copy[i]["role"] == "user":
|
if dialogue_copy[i]["role"] == "user":
|
||||||
# 在用户消息前添加/no_think指令
|
# Add /no_think instruction before user message
|
||||||
dialogue_copy[i]["content"] = (
|
dialogue_copy[i]["content"] = (
|
||||||
"/no_think " + 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
|
break
|
||||||
|
|
||||||
# 使用修改后的对话
|
|
||||||
|
# Use the modified dialogue
|
||||||
dialogue = dialogue_copy
|
dialogue = dialogue_copy
|
||||||
|
|
||||||
|
|
||||||
responses = self.client.chat.completions.create(
|
responses = self.client.chat.completions.create(
|
||||||
model=self.model_name, messages=dialogue, stream=True
|
model=self.model_name, messages=dialogue, stream=True
|
||||||
)
|
)
|
||||||
is_active = True
|
is_active = True
|
||||||
# 用于处理跨chunk的标签
|
# Used to handle cross-chunk tags
|
||||||
buffer = ""
|
buffer = ""
|
||||||
|
|
||||||
|
|
||||||
for chunk in responses:
|
for chunk in responses:
|
||||||
try:
|
try:
|
||||||
delta = (
|
delta = (
|
||||||
|
|
@ -60,59 +69,70 @@ class LLMProvider(LLMProviderBase):
|
||||||
)
|
)
|
||||||
content = delta.content if hasattr(delta, "content") else ""
|
content = delta.content if hasattr(delta, "content") else ""
|
||||||
|
|
||||||
|
|
||||||
if content:
|
if content:
|
||||||
# 将内容添加到缓冲区
|
# Add content to buffer
|
||||||
buffer += content
|
buffer += content
|
||||||
|
|
||||||
# 处理缓冲区中的标签
|
|
||||||
|
# Process tags in buffer
|
||||||
while "<think>" in buffer and "</think>" in buffer:
|
while "<think>" in buffer and "</think>" in buffer:
|
||||||
# 找到完整的<think></think>标签并移除
|
# Find and remove complete <think></think> tags
|
||||||
pre = buffer.split("<think>", 1)[0]
|
pre = buffer.split("<think>", 1)[0]
|
||||||
post = buffer.split("</think>", 1)[1]
|
post = buffer.split("</think>", 1)[1]
|
||||||
buffer = pre + post
|
buffer = pre + post
|
||||||
|
|
||||||
# 处理只有开始标签的情况
|
|
||||||
|
# Handle case with only opening tag
|
||||||
if "<think>" in buffer:
|
if "<think>" in buffer:
|
||||||
is_active = False
|
is_active = False
|
||||||
buffer = buffer.split("<think>", 1)[0]
|
buffer = buffer.split("<think>", 1)[0]
|
||||||
|
|
||||||
# 处理只有结束标签的情况
|
|
||||||
|
# Handle case with only closing tag
|
||||||
if "</think>" in buffer:
|
if "</think>" in buffer:
|
||||||
is_active = True
|
is_active = True
|
||||||
buffer = buffer.split("</think>", 1)[1]
|
buffer = buffer.split("</think>", 1)[1]
|
||||||
|
|
||||||
# 如果当前处于活动状态且缓冲区有内容,则输出
|
|
||||||
|
# If currently active and buffer has content, output
|
||||||
if is_active and buffer:
|
if is_active and buffer:
|
||||||
yield buffer
|
yield buffer
|
||||||
buffer = "" # 清空缓冲区
|
buffer = "" # Clear buffer
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {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):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
try:
|
try:
|
||||||
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
|
# If it's a qwen3 model, add /no_think instruction to the user's last message
|
||||||
if self.is_qwen3:
|
if self.is_qwen3:
|
||||||
# 复制对话列表,避免修改原始对话
|
# Copy dialogue list to avoid modifying the original dialogue
|
||||||
dialogue_copy = dialogue.copy()
|
dialogue_copy = dialogue.copy()
|
||||||
|
|
||||||
# 找到最后一条用户消息
|
|
||||||
|
# Find the last user message
|
||||||
for i in range(len(dialogue_copy) - 1, -1, -1):
|
for i in range(len(dialogue_copy) - 1, -1, -1):
|
||||||
if dialogue_copy[i]["role"] == "user":
|
if dialogue_copy[i]["role"] == "user":
|
||||||
# 在用户消息前添加/no_think指令
|
# Add /no_think instruction before user message
|
||||||
dialogue_copy[i]["content"] = (
|
dialogue_copy[i]["content"] = (
|
||||||
"/no_think " + 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
|
break
|
||||||
|
|
||||||
# 使用修改后的对话
|
|
||||||
|
# Use the modified dialogue
|
||||||
dialogue = dialogue_copy
|
dialogue = dialogue_copy
|
||||||
|
|
||||||
|
|
||||||
stream = self.client.chat.completions.create(
|
stream = self.client.chat.completions.create(
|
||||||
model=self.model_name,
|
model=self.model_name,
|
||||||
messages=dialogue,
|
messages=dialogue,
|
||||||
|
|
@ -120,9 +140,11 @@ class LLMProvider(LLMProviderBase):
|
||||||
tools=functions,
|
tools=functions,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
is_active = True
|
is_active = True
|
||||||
buffer = ""
|
buffer = ""
|
||||||
|
|
||||||
|
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
try:
|
try:
|
||||||
delta = (
|
delta = (
|
||||||
|
|
@ -135,41 +157,48 @@ class LLMProvider(LLMProviderBase):
|
||||||
delta.tool_calls if hasattr(delta, "tool_calls") else None
|
delta.tool_calls if hasattr(delta, "tool_calls") else None
|
||||||
)
|
)
|
||||||
|
|
||||||
# 如果是工具调用,直接传递
|
|
||||||
|
# If it's a tool call, pass directly
|
||||||
if tool_calls:
|
if tool_calls:
|
||||||
yield None, tool_calls
|
yield None, tool_calls
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 处理文本内容
|
|
||||||
|
# Process text content
|
||||||
if content:
|
if content:
|
||||||
# 将内容添加到缓冲区
|
# Add content to buffer
|
||||||
buffer += content
|
buffer += content
|
||||||
|
|
||||||
# 处理缓冲区中的标签
|
|
||||||
|
# Process tags in buffer
|
||||||
while "<think>" in buffer and "</think>" in buffer:
|
while "<think>" in buffer and "</think>" in buffer:
|
||||||
# 找到完整的<think></think>标签并移除
|
# Find and remove complete <think></think> tags
|
||||||
pre = buffer.split("<think>", 1)[0]
|
pre = buffer.split("<think>", 1)[0]
|
||||||
post = buffer.split("</think>", 1)[1]
|
post = buffer.split("</think>", 1)[1]
|
||||||
buffer = pre + post
|
buffer = pre + post
|
||||||
|
|
||||||
# 处理只有开始标签的情况
|
|
||||||
|
# Handle case with only opening tag
|
||||||
if "<think>" in buffer:
|
if "<think>" in buffer:
|
||||||
is_active = False
|
is_active = False
|
||||||
buffer = buffer.split("<think>", 1)[0]
|
buffer = buffer.split("<think>", 1)[0]
|
||||||
|
|
||||||
# 处理只有结束标签的情况
|
|
||||||
|
# Handle case with only closing tag
|
||||||
if "</think>" in buffer:
|
if "</think>" in buffer:
|
||||||
is_active = True
|
is_active = True
|
||||||
buffer = buffer.split("</think>", 1)[1]
|
buffer = buffer.split("</think>", 1)[1]
|
||||||
|
|
||||||
# 如果当前处于活动状态且缓冲区有内容,则输出
|
|
||||||
|
# If currently active and buffer has content, output
|
||||||
if is_active and buffer:
|
if is_active and buffer:
|
||||||
yield buffer, None
|
yield buffer, None
|
||||||
buffer = "" # 清空缓冲区
|
buffer = "" # Clear buffer
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error processing function chunk: {e}")
|
logger.bind(tag=TAG).error(f"Error processing function chunk: {e}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama function call: {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
|
||||||
|
|
@ -5,10 +5,12 @@ from config.logger import setup_logging
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.model_name = config.get("model_name")
|
self.model_name = config.get("model_name")
|
||||||
|
|
@ -17,10 +19,11 @@ class LLMProvider(LLMProviderBase):
|
||||||
self.base_url = config.get("base_url")
|
self.base_url = config.get("base_url")
|
||||||
else:
|
else:
|
||||||
self.base_url = config.get("url")
|
self.base_url = config.get("url")
|
||||||
# 增加timeout的配置项,单位为秒
|
# Add timeout configuration item, unit is seconds
|
||||||
timeout = config.get("timeout", 300)
|
timeout = config.get("timeout", 300)
|
||||||
self.timeout = int(timeout) if timeout else 300
|
self.timeout = int(timeout) if timeout else 300
|
||||||
|
|
||||||
|
|
||||||
param_defaults = {
|
param_defaults = {
|
||||||
"max_tokens": (500, int),
|
"max_tokens": (500, int),
|
||||||
"temperature": (0.7, lambda x: round(float(x), 1)),
|
"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)),
|
"frequency_penalty": (0, lambda x: round(float(x), 1)),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
for param, (default, converter) in param_defaults.items():
|
for param, (default, converter) in param_defaults.items():
|
||||||
value = config.get(param)
|
value = config.get(param)
|
||||||
try:
|
try:
|
||||||
|
|
@ -39,15 +43,18 @@ class LLMProvider(LLMProviderBase):
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
setattr(self, param, default)
|
setattr(self, param, default)
|
||||||
|
|
||||||
|
|
||||||
logger.debug(
|
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)
|
model_key_msg = check_model_key("LLM", self.api_key)
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
logger.bind(tag=TAG).error(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))
|
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):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
try:
|
||||||
responses = self.client.chat.completions.create(
|
responses = self.client.chat.completions.create(
|
||||||
|
|
@ -62,10 +69,11 @@ class LLMProvider(LLMProviderBase):
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
is_active = True
|
is_active = True
|
||||||
for chunk in responses:
|
for chunk in responses:
|
||||||
try:
|
try:
|
||||||
# 检查是否存在有效的choice且content不为空
|
# Check if valid choice exists and content is not empty
|
||||||
delta = (
|
delta = (
|
||||||
chunk.choices[0].delta
|
chunk.choices[0].delta
|
||||||
if getattr(chunk, "choices", None)
|
if getattr(chunk, "choices", None)
|
||||||
|
|
@ -75,7 +83,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
except IndexError:
|
except IndexError:
|
||||||
content = ""
|
content = ""
|
||||||
if content:
|
if content:
|
||||||
# 处理标签跨多个chunk的情况
|
# Handle case where tags span multiple chunks
|
||||||
if "<think>" in content:
|
if "<think>" in content:
|
||||||
is_active = False
|
is_active = False
|
||||||
content = content.split("<think>")[0]
|
content = content.split("<think>")[0]
|
||||||
|
|
@ -85,30 +93,34 @@ class LLMProvider(LLMProviderBase):
|
||||||
if is_active:
|
if is_active:
|
||||||
yield content
|
yield content
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
||||||
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
try:
|
try:
|
||||||
stream = self.client.chat.completions.create(
|
stream = self.client.chat.completions.create(
|
||||||
model=self.model_name, messages=dialogue, stream=True, tools=functions
|
model=self.model_name, messages=dialogue, stream=True, tools=functions
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
# 检查是否存在有效的choice且content不为空
|
# Check if valid choice exists and content is not empty
|
||||||
if getattr(chunk, "choices", None):
|
if getattr(chunk, "choices", None):
|
||||||
yield chunk.choices[0].delta.content, chunk.choices[
|
yield chunk.choices[0].delta.content, chunk.choices[
|
||||||
0
|
0
|
||||||
].delta.tool_calls
|
].delta.tool_calls
|
||||||
# 存在 CompletionUsage 消息时,生成 Token 消耗 log
|
# When CompletionUsage message exists, generate Token consumption log
|
||||||
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
||||||
usage_info = getattr(chunk, "usage", None)
|
usage_info = getattr(chunk, "usage", None)
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
|
f"Token consumption: input {getattr(usage_info, 'prompt_tokens', 'unknown')}, "
|
||||||
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
|
f"output {getattr(usage_info, 'completion_tokens', 'unknown')}, "
|
||||||
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
|
f"total {getattr(usage_info, 'total_tokens', 'unknown')}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in function call streaming: {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
|
||||||
|
|
@ -1,23 +1,28 @@
|
||||||
def get_system_prompt_for_function(functions: str) -> str:
|
def get_system_prompt_for_function(functions: str) -> str:
|
||||||
"""
|
"""
|
||||||
生成系统提示信息
|
Generate system prompt message
|
||||||
:param functions: 可用的函数列表
|
:param functions: List of available functions
|
||||||
:return: 系统提示信息
|
:return: System prompt message
|
||||||
"""
|
"""
|
||||||
|
|
||||||
SYSTEM_PROMPT = f"""
|
SYSTEM_PROMPT = f"""
|
||||||
====
|
====
|
||||||
|
|
||||||
|
|
||||||
TOOL USE
|
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 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.
|
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 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.
|
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:
|
Here's the structure:
|
||||||
|
|
||||||
|
|
||||||
<tool_call>
|
<tool_call>
|
||||||
{{
|
{{
|
||||||
"name": "function name",
|
"name": "function name",
|
||||||
|
|
@ -29,20 +34,22 @@ Here's the structure:
|
||||||
}}
|
}}
|
||||||
<tool_call>
|
<tool_call>
|
||||||
|
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
if you got tool as follow
|
if you got tool as follow
|
||||||
|
|
||||||
|
|
||||||
{{
|
{{
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {{
|
"function": {{
|
||||||
"name": "handle_exit_intent",
|
"name": "handle_exit_intent",
|
||||||
"description": "当用户想结束对话或需要退出系统时调用",
|
"description": "Called when user wants to end conversation or needs to exit system",
|
||||||
"parameters": {{
|
"parameters": {{
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {{
|
"properties": {{
|
||||||
"say_goodbye": {{
|
"say_goodbye": {{
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "和用户友好结束对话的告别语",
|
"description": "Friendly goodbye message to end conversation with user",
|
||||||
}}
|
}}
|
||||||
}},
|
}},
|
||||||
"required": ["say_goodbye"],
|
"required": ["say_goodbye"],
|
||||||
|
|
@ -50,26 +57,33 @@ if you got tool as follow
|
||||||
}},
|
}},
|
||||||
}}
|
}}
|
||||||
|
|
||||||
|
|
||||||
you should respond with the following format:
|
you should respond with the following format:
|
||||||
|
|
||||||
|
|
||||||
<tool_call>
|
<tool_call>
|
||||||
{{
|
{{
|
||||||
"name": "handle_exit_intent",
|
"name": "handle_exit_intent",
|
||||||
"arguments": {{
|
"arguments": {{
|
||||||
"say_goodbye": "再见,祝您生活愉快!"
|
"say_goodbye": "Goodbye, have a pleasant life!"
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
</tool_call>
|
</tool_call>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Always adhere to this format for the tool use to ensure proper parsing and execution.
|
Always adhere to this format for the tool use to ensure proper parsing and execution.
|
||||||
|
|
||||||
|
|
||||||
# Tools
|
# Tools
|
||||||
|
|
||||||
|
|
||||||
{functions}
|
{functions}
|
||||||
|
|
||||||
|
|
||||||
# Tool Use Guidelines
|
# Tool Use Guidelines
|
||||||
|
|
||||||
|
|
||||||
1. Tools must be called in a separate message, Do not add thoughts when calling tools. The message must start with <tool_call> and end with </tool_call>, with the tool invocation JSON data in between. No additional response content is needed.
|
1. Tools must be called in a separate message, Do not add thoughts when calling tools. The message must start with <tool_call> and end with </tool_call>, 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.
|
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.
|
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.
|
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.
|
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:
|
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.
|
1. Confirm the success of each step before proceeding.
|
||||||
2. Address any issues or errors that arise immediately.
|
2. Address any issues or errors that arise immediately.
|
||||||
3. Adapt your approach based on new information or unexpected results.
|
3. Adapt your approach based on new information or unexpected results.
|
||||||
4. Ensure that each action builds correctly on the previous ones.
|
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.
|
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
|
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.
|
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
|
return SYSTEM_PROMPT
|
||||||
|
|
@ -3,6 +3,7 @@ from openai import OpenAI
|
||||||
import json
|
import json
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -12,7 +13,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
self.model_name = config.get("model_name")
|
self.model_name = config.get("model_name")
|
||||||
self.base_url = config.get("base_url", "http://localhost:9997")
|
self.base_url = config.get("base_url", "http://localhost:9997")
|
||||||
# Initialize OpenAI client with Xinference base URL
|
# Initialize OpenAI client with Xinference base URL
|
||||||
# 如果没有v1,增加v1
|
# If there's no v1, add v1
|
||||||
if not self.base_url.endswith("/v1"):
|
if not self.base_url.endswith("/v1"):
|
||||||
self.base_url = f"{self.base_url}/v1"
|
self.base_url = f"{self.base_url}/v1"
|
||||||
|
|
||||||
|
|
@ -23,11 +24,14 @@ class LLMProvider(LLMProviderBase):
|
||||||
try:
|
try:
|
||||||
self.client = OpenAI(
|
self.client = OpenAI(
|
||||||
base_url=self.base_url,
|
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:
|
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
|
raise
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
|
|
@ -46,7 +50,8 @@ class LLMProvider(LLMProviderBase):
|
||||||
if getattr(chunk, "choices", None)
|
if getattr(chunk, "choices", None)
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
content = delta.content if hasattr(delta, "content") else ""
|
content = delta.content if hasattr(
|
||||||
|
delta, "content") else ""
|
||||||
if content:
|
if content:
|
||||||
if "<think>" in content:
|
if "<think>" in content:
|
||||||
is_active = False
|
is_active = False
|
||||||
|
|
@ -60,8 +65,9 @@ class LLMProvider(LLMProviderBase):
|
||||||
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}")
|
logger.bind(tag=TAG).error(
|
||||||
yield "【Xinference服务响应异常】"
|
f"Error in Xinference response generation: {e}")
|
||||||
|
yield "[Xinference Service Response Exception]"
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
try:
|
try:
|
||||||
|
|
@ -91,8 +97,9 @@ class LLMProvider(LLMProviderBase):
|
||||||
yield None, tool_calls
|
yield None, tool_calls
|
||||||
|
|
||||||
except Exception as e:
|
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 {
|
yield {
|
||||||
"type": "content",
|
"type": "content",
|
||||||
"content": f"【Xinference服务响应异常: {str(e)}】",
|
"content": f"[Xinference Service Response Exception: {str(e)}]",
|
||||||
}
|
}
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from ..base import MemoryProviderBase, logger
|
from ..base import MemoryProviderBase, logger
|
||||||
from mem0 import MemoryClient
|
from mem0 import MemoryClient
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
|
@ -22,10 +21,13 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.client = MemoryClient(api_key=self.api_key)
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"连接到 Mem0ai 服务时发生错误: {str(e)}")
|
logger.bind(tag=TAG).error(
|
||||||
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
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
|
self.use_mem0 = False
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs):
|
||||||
|
|
@ -46,7 +48,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
)
|
)
|
||||||
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
async def query_memory(self, query: str) -> str:
|
async def query_memory(self, query: str) -> str:
|
||||||
|
|
@ -73,7 +75,8 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
memory = entry.get("memory", "")
|
memory = entry.get("memory", "")
|
||||||
if timestamp and memory:
|
if timestamp and memory:
|
||||||
# Store tuple of (timestamp, formatted_string) for sorting
|
# 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)
|
# Sort by timestamp in descending order (newest first)
|
||||||
memories.sort(key=lambda x: x[0], reverse=True)
|
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}")
|
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
|
||||||
return memories_str
|
return memories_str
|
||||||
except Exception as e:
|
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 ""
|
return ""
|
||||||
|
|
|
||||||
|
|
@ -9,81 +9,80 @@ from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
|
||||||
short_term_memory_prompt = """
|
short_term_memory_prompt = """
|
||||||
# 时空记忆编织者
|
# Temporal Memory Weaver
|
||||||
|
|
||||||
## 核心使命
|
## Core Mission
|
||||||
构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹
|
Build a growable dynamic memory network that retains key information within limited space while intelligently maintaining information evolution trajectories
|
||||||
根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务
|
Summarize important user information based on conversation records to provide more personalized services in future conversations
|
||||||
|
|
||||||
## 记忆法则
|
## Memory Rules
|
||||||
### 1. 三维度记忆评估(每次更新必执行)
|
### 1. Three-Dimensional Memory Assessment (Must execute on every update)
|
||||||
| 维度 | 评估标准 | 权重分 |
|
| Dimension | Assessment Criteria | Weight |
|
||||||
|------------|---------------------------|--------|
|
|----------------|----------------------------------|--------|
|
||||||
| 时效性 | 信息新鲜度(按对话轮次) | 40% |
|
| Timeliness | Information freshness (by turns) | 40% |
|
||||||
| 情感强度 | 含💖标记/重复提及次数 | 35% |
|
| Emotional Intensity | Contains 💖 marks/repeat mentions | 35% |
|
||||||
| 关联密度 | 与其他信息的连接数量 | 25% |
|
| Association Density | Number of connections to other info | 25% |
|
||||||
|
|
||||||
### 2. 动态更新机制
|
### 2. Dynamic Update Mechanism
|
||||||
**名字变更处理示例:**
|
**Name Change Handling Example:**
|
||||||
原始记忆:"曾用名": ["张三"], "现用名": "张三丰"
|
Original memory: "former_names": ["Zhang San"], "current_name": "Zhang Sanfeng"
|
||||||
触发条件:当检测到「我叫X」「称呼我Y」等命名信号时
|
Trigger condition: When detecting naming signals like "My name is X" "Call me Y"
|
||||||
操作流程:
|
Operation process:
|
||||||
1. 将旧名移入"曾用名"列表
|
1. Move old name to "former_names" list
|
||||||
2. 记录命名时间轴:"2024-02-15 14:32:启用张三丰"
|
2. Record naming timeline: "2024-02-15 14:32: Activated Zhang Sanfeng"
|
||||||
3. 在记忆立方追加:「从张三到张三丰的身份蜕变」
|
3. Append to memory cube: "Identity transformation from Zhang San to Zhang Sanfeng"
|
||||||
|
|
||||||
### 3. 空间优化策略
|
### 3. Space Optimization Strategy
|
||||||
- **信息压缩术**:用符号体系提升密度
|
- **Information Compression**: Use symbol system to enhance density
|
||||||
- ✅"张三丰[北/软工/🐱]"
|
- ✅"Zhang Sanfeng[Beijing/SoftEng/🐱]"
|
||||||
- ❌"北京软件工程师,养猫"
|
- ❌"Beijing software engineer, owns cat"
|
||||||
- **淘汰预警**:当总字数≥900时触发
|
- **Elimination Warning**: Triggered when total word count ≥900
|
||||||
1. 删除权重分<60且3轮未提及的信息
|
1. Delete info with weight score <60 and not mentioned for 3 rounds
|
||||||
2. 合并相似条目(保留时间戳最近的)
|
2. Merge similar entries (keep most recent timestamp)
|
||||||
|
|
||||||
## 记忆结构
|
## Memory Structure
|
||||||
输出格式必须为可解析的json字符串,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容
|
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
|
```json
|
||||||
{
|
{
|
||||||
"时空档案": {
|
"temporal_profile": {
|
||||||
"身份图谱": {
|
"identity_map": {
|
||||||
"现用名": "",
|
"current_name": "",
|
||||||
"特征标记": []
|
"feature_tags": []
|
||||||
},
|
},
|
||||||
"记忆立方": [
|
"memory_cube": [
|
||||||
{
|
{
|
||||||
"事件": "入职新公司",
|
"event": "Started new job",
|
||||||
"时间戳": "2024-03-20",
|
"timestamp": "2024-03-20",
|
||||||
"情感值": 0.9,
|
"emotional_value": 0.9,
|
||||||
"关联项": ["下午茶"],
|
"related_items": ["afternoon tea"],
|
||||||
"保鲜期": 30
|
"freshness_period": 30
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"关系网络": {
|
"relationship_network": {
|
||||||
"高频话题": {"职场": 12},
|
"frequent_topics": {"workplace": 12},
|
||||||
"暗线联系": [""]
|
"hidden_connections": [""]
|
||||||
},
|
},
|
||||||
"待响应": {
|
"pending_response": {
|
||||||
"紧急事项": ["需立即处理的任务"],
|
"urgent_matters": ["Tasks requiring immediate attention"],
|
||||||
"潜在关怀": ["可主动提供的帮助"]
|
"potential_care": ["Help that can be proactively offered"]
|
||||||
},
|
},
|
||||||
"高光语录": [
|
"highlight_quotes": [
|
||||||
"最打动人心的瞬间,强烈的情感表达,user的原话"
|
"Most touching moments, strong emotional expressions, user's original words"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
"""
|
"""
|
||||||
|
|
||||||
short_term_memory_prompt_only_content = """
|
short_term_memory_prompt_only_content = """
|
||||||
你是一个经验丰富的记忆总结者,擅长将对话内容进行总结摘要,遵循以下规则:
|
You are an experienced memory summarizer, skilled at summarizing conversation content, following these rules:
|
||||||
1、总结user的重要信息,以便在未来的对话中提供更个性化的服务
|
1. Summarize important user information to provide more personalized services in future conversations
|
||||||
2、不要重复总结,不要遗忘之前记忆,除非原来的记忆超过了1800字内,否则不要遗忘、不要压缩用户的历史记忆
|
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、用户操控的设备音量、播放音乐、天气、退出、不想对话等和用户本身无关的内容,这些信息不需要加入到总结中
|
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、聊天内容中的今天的日期时间、今天的天气情况与用户事件无关的数据,这些信息如果当成记忆存储会影响后序对话,这些信息不需要加入到总结中
|
4. Don't include device control success/failure results in the summary, and don't include user's meaningless chatter
|
||||||
5、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中
|
5. Don't summarize for the sake of summarizing, if user's chat is meaningless, returning the original historical record is acceptable
|
||||||
6、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的
|
6. Only return summary digest, strictly control within 1800 words
|
||||||
7、只需要返回总结摘要,严格控制在1800字内
|
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
|
||||||
8、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -99,7 +98,7 @@ def extract_json_data(json_code):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Error:", e)
|
print("Error:", e)
|
||||||
return ""
|
return ""
|
||||||
jsonData = json_code[start + 7 : end]
|
jsonData = json_code[start + 7: end]
|
||||||
return jsonData
|
return jsonData
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -122,7 +121,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
self.load_memory(summary_memory)
|
self.load_memory(summary_memory)
|
||||||
|
|
||||||
def load_memory(self, 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:
|
if summary_memory or not self.save_to_file:
|
||||||
self.short_memory = summary_memory
|
self.short_memory = summary_memory
|
||||||
return
|
return
|
||||||
|
|
@ -144,11 +143,18 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
yaml.dump(all_memory, f, allow_unicode=True)
|
yaml.dump(all_memory, f, allow_unicode=True)
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs):
|
||||||
# 打印使用的模型信息
|
# Check if llm is set
|
||||||
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
if not hasattr(self, 'llm') or self.llm is None:
|
||||||
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
|
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)
|
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:
|
if memory_key_msg:
|
||||||
logger.bind(tag=TAG).error(memory_key_msg)
|
logger.bind(tag=TAG).error(memory_key_msg)
|
||||||
if self.llm is None:
|
if self.llm is None:
|
||||||
|
|
@ -165,12 +171,12 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
elif msg.role == "assistant":
|
elif msg.role == "assistant":
|
||||||
msgStr += f"Assistant: {msg.content}\n"
|
msgStr += f"Assistant: {msg.content}\n"
|
||||||
if self.short_memory and len(self.short_memory) > 0:
|
if self.short_memory and len(self.short_memory) > 0:
|
||||||
msgStr += "历史记忆:\n"
|
msgStr += "Historical Memory:\n"
|
||||||
msgStr += self.short_memory
|
msgStr += self.short_memory
|
||||||
|
|
||||||
# 当前时间
|
# Current time
|
||||||
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
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:
|
if self.save_to_file:
|
||||||
result = self.llm.response_no_stream(
|
result = self.llm.response_no_stream(
|
||||||
|
|
@ -181,7 +187,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
)
|
)
|
||||||
json_str = extract_json_data(result)
|
json_str = extract_json_data(result)
|
||||||
try:
|
try:
|
||||||
json.loads(json_str) # 检查json格式是否正确
|
json.loads(json_str) # Check if JSON format is correct
|
||||||
self.short_memory = json_str
|
self.short_memory = json_str
|
||||||
self.save_memory_to_file()
|
self.save_memory_to_file()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -194,7 +200,8 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
temperature=0.2,
|
temperature=0.2,
|
||||||
)
|
)
|
||||||
save_mem_local_short(self.role_id, result)
|
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
|
return self.short_memory
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,21 @@
|
||||||
"""
|
"""
|
||||||
不使用记忆,可以选择此模块
|
If not using memory, you can choose this module
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from ..base import MemoryProviderBase, logger
|
from ..base import MemoryProviderBase, logger
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
class MemoryProvider(MemoryProviderBase):
|
class MemoryProvider(MemoryProviderBase):
|
||||||
def __init__(self, config, summary_memory=None):
|
def __init__(self, config, summary_memory=None):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
|
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs):
|
||||||
logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.")
|
logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def query_memory(self, query: str) -> str:
|
async def query_memory(self, query: str) -> str:
|
||||||
logger.bind(tag=TAG).debug("nomem mode: No memory query is performed.")
|
logger.bind(tag=TAG).debug("nomem mode: No memory query is performed.")
|
||||||
return ""
|
return ""
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""基础工具定义模块"""
|
"""Base tool definition module"""
|
||||||
|
|
||||||
from .tool_types import ToolType, ToolDefinition
|
from .tool_types import ToolType, ToolDefinition
|
||||||
from .tool_executor import ToolExecutor
|
from .tool_executor import ToolExecutor
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,26 @@
|
||||||
"""工具执行器基类定义"""
|
"""Tool executor base class definition"""
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from .tool_types import ToolDefinition
|
from .tool_types import ToolDefinition
|
||||||
from plugins_func.register import ActionResponse
|
from plugins_func.register import ActionResponse
|
||||||
|
|
||||||
|
|
||||||
class ToolExecutor(ABC):
|
class ToolExecutor(ABC):
|
||||||
"""工具执行器抽象基类"""
|
"""Tool executor abstract base class"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行工具调用"""
|
"""Execute tool call"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_tools(self) -> Dict[str, ToolDefinition]:
|
def get_tools(self) -> Dict[str, ToolDefinition]:
|
||||||
"""获取该执行器管理的所有工具"""
|
"""Get all tools managed by this executor"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
def has_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否有指定工具"""
|
"""Check if specified tool exists"""
|
||||||
pass
|
pass
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,25 @@
|
||||||
"""工具系统的类型定义"""
|
"""Type definitions for tool system"""
|
||||||
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
from plugins_func.register import Action
|
from plugins_func.register import Action
|
||||||
|
|
||||||
|
|
||||||
class ToolType(Enum):
|
class ToolType(Enum):
|
||||||
"""工具类型枚举"""
|
"""Tool type enumeration"""
|
||||||
|
SERVER_PLUGIN = "server_plugin" # Server-side plugin
|
||||||
SERVER_PLUGIN = "server_plugin" # 服务端插件
|
SERVER_MCP = "server_mcp" # Server-side MCP
|
||||||
SERVER_MCP = "server_mcp" # 服务端MCP
|
DEVICE_IOT = "device_iot" # Device-side IoT
|
||||||
DEVICE_IOT = "device_iot" # 设备端IoT
|
DEVICE_MCP = "device_mcp" # Device-side MCP
|
||||||
DEVICE_MCP = "device_mcp" # 设备端MCP
|
MCP_ENDPOINT = "mcp_endpoint" # MCP endpoint
|
||||||
MCP_ENDPOINT = "mcp_endpoint" # MCP接入点
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ToolDefinition:
|
class ToolDefinition:
|
||||||
"""工具定义"""
|
"""Tool definition"""
|
||||||
|
name: str # Tool name
|
||||||
name: str # 工具名称
|
# Tool description (OpenAI function call format)
|
||||||
description: Dict[str, Any] # 工具描述(OpenAI函数调用格式)
|
description: Dict[str, Any]
|
||||||
tool_type: ToolType # 工具类型
|
tool_type: ToolType # Tool type
|
||||||
parameters: Optional[Dict[str, Any]] = None # 额外参数
|
parameters: Optional[Dict[str, Any]] = None # Additional parameters
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""设备端IoT工具模块"""
|
"""Device-side IoT tool module"""
|
||||||
|
|
||||||
from .iot_descriptor import IotDescriptor
|
from .iot_descriptor import IotDescriptor
|
||||||
from .iot_handler import handleIotDescriptors, handleIotStatus
|
from .iot_handler import handleIotDescriptors, handleIotStatus
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,12 @@
|
||||||
"""IoT设备描述符定义"""
|
"""IoT device descriptor definition"""
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class IotDescriptor:
|
class IotDescriptor:
|
||||||
"""IoT设备描述符"""
|
"""IoT device descriptor"""
|
||||||
|
|
||||||
def __init__(self, name, description, properties, methods):
|
def __init__(self, name, description, properties, methods):
|
||||||
self.name = name
|
self.name = name
|
||||||
|
|
@ -15,7 +14,7 @@ class IotDescriptor:
|
||||||
self.properties = []
|
self.properties = []
|
||||||
self.methods = []
|
self.methods = []
|
||||||
|
|
||||||
# 根据描述创建属性
|
# Create properties based on description
|
||||||
if properties is not None:
|
if properties is not None:
|
||||||
for key, value in properties.items():
|
for key, value in properties.items():
|
||||||
property_item = {}
|
property_item = {}
|
||||||
|
|
@ -29,13 +28,13 @@ class IotDescriptor:
|
||||||
property_item["value"] = ""
|
property_item["value"] = ""
|
||||||
self.properties.append(property_item)
|
self.properties.append(property_item)
|
||||||
|
|
||||||
# 根据描述创建方法
|
# Create methods based on description
|
||||||
if methods is not None:
|
if methods is not None:
|
||||||
for key, value in methods.items():
|
for key, value in methods.items():
|
||||||
method = {}
|
method = {}
|
||||||
method["description"] = value["description"]
|
method["description"] = value["description"]
|
||||||
method["name"] = key
|
method["name"] = key
|
||||||
# 检查方法是否有参数
|
# Check if method has parameters
|
||||||
if "parameters" in value:
|
if "parameters" in value:
|
||||||
method["parameters"] = {}
|
method["parameters"] = {}
|
||||||
for k, v in value["parameters"].items():
|
for k, v in value["parameters"].items():
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""设备端IoT工具执行器"""
|
"""Device-side IoT tool executor"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
@ -6,9 +6,8 @@ from typing import Dict, Any
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
|
|
||||||
|
|
||||||
class DeviceIoTExecutor(ToolExecutor):
|
class DeviceIoTExecutor(ToolExecutor):
|
||||||
"""设备端IoT工具执行器"""
|
"""Device-side IoT tool executor"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -17,65 +16,63 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行设备端IoT工具"""
|
"""Execute device-side IoT tool"""
|
||||||
if not self.has_tool(tool_name):
|
if not self.has_tool(tool_name):
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.NOTFOUND, response=f"IoT工具 {tool_name} 不存在"
|
action=Action.NOTFOUND, response=f"IoT tool {tool_name} does not exist"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 解析工具名称,获取设备名和操作类型
|
# Parse tool name to get device name and operation type
|
||||||
if tool_name.startswith("get_"):
|
if tool_name.startswith("get_"):
|
||||||
# 查询操作:get_devicename_property
|
# Query operation: get_devicename_property
|
||||||
parts = tool_name.split("_", 2)
|
parts = tool_name.split("_", 2)
|
||||||
if len(parts) >= 3:
|
if len(parts) >= 3:
|
||||||
device_name = parts[1]
|
device_name = parts[1]
|
||||||
property_name = parts[2]
|
property_name = parts[2]
|
||||||
|
|
||||||
value = await self._get_iot_status(device_name, property_name)
|
value = await self._get_iot_status(device_name, property_name)
|
||||||
|
|
||||||
if value is not None:
|
if value is not None:
|
||||||
# 处理响应模板
|
# Process response template
|
||||||
response_success = arguments.get(
|
response_success = arguments.get(
|
||||||
"response_success", "查询成功:{value}"
|
"response_success", "Query successful: {value}"
|
||||||
)
|
)
|
||||||
response = response_success.replace("{value}", str(value))
|
response = response_success.replace("{value}", str(value))
|
||||||
|
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.RESPONSE,
|
action=Action.RESPONSE,
|
||||||
response=response,
|
response=response,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
response_failure = arguments.get(
|
response_failure = arguments.get(
|
||||||
"response_failure", f"无法获取{device_name}的状态"
|
"response_failure", f"Unable to get status of {device_name}"
|
||||||
)
|
)
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR, response=response_failure
|
action=Action.ERROR, response=response_failure
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# 控制操作:devicename_method
|
# Control operation: devicename_method
|
||||||
parts = tool_name.split("_", 1)
|
parts = tool_name.split("_", 1)
|
||||||
if len(parts) >= 2:
|
if len(parts) >= 2:
|
||||||
device_name = parts[0]
|
device_name = parts[0]
|
||||||
method_name = parts[1]
|
method_name = parts[1]
|
||||||
|
|
||||||
# 提取控制参数(排除响应参数)
|
# Extract control parameters (exclude response parameters)
|
||||||
control_params = {
|
control_params = {
|
||||||
k: v
|
k: v
|
||||||
for k, v in arguments.items()
|
for k, v in arguments.items()
|
||||||
if k not in ["response_success", "response_failure"]
|
if k not in ["response_success", "response_failure"]
|
||||||
}
|
}
|
||||||
|
|
||||||
# 发送IoT控制命令
|
# Send IoT control command
|
||||||
await self._send_iot_command(
|
await self._send_iot_command(
|
||||||
device_name, method_name, control_params
|
device_name, method_name, control_params
|
||||||
)
|
)
|
||||||
|
|
||||||
# 等待状态更新
|
# Wait for status update
|
||||||
await asyncio.sleep(0.1)
|
await asyncio.sleep(0.1)
|
||||||
|
response_success = arguments.get("response_success", "Operation successful")
|
||||||
|
|
||||||
response_success = arguments.get("response_success", "操作成功")
|
# Handle placeholders in response
|
||||||
|
|
||||||
# 处理响应中的占位符
|
|
||||||
for param_name, param_value in control_params.items():
|
for param_name, param_value in control_params.items():
|
||||||
placeholder = "{" + param_name + "}"
|
placeholder = "{" + param_name + "}"
|
||||||
if placeholder in response_success:
|
if placeholder in response_success:
|
||||||
|
|
@ -93,14 +90,14 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
result=response_success,
|
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:
|
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)
|
return ActionResponse(action=Action.ERROR, response=response_failure)
|
||||||
|
|
||||||
async def _get_iot_status(self, device_name: str, property_name: str):
|
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():
|
for key, value in self.conn.iot_descriptors.items():
|
||||||
if key.lower() == device_name.lower():
|
if key.lower() == device_name.lower():
|
||||||
for property_item in value.properties:
|
for property_item in value.properties:
|
||||||
|
|
@ -111,7 +108,7 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
async def _send_iot_command(
|
async def _send_iot_command(
|
||||||
self, device_name: str, method_name: str, parameters: Dict[str, Any]
|
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():
|
for key, value in self.conn.iot_descriptors.items():
|
||||||
if key.lower() == device_name.lower():
|
if key.lower() == device_name.lower():
|
||||||
for method in value.methods:
|
for method in value.methods:
|
||||||
|
|
@ -120,7 +117,6 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
"name": key,
|
"name": key,
|
||||||
"method": method["name"],
|
"method": method["name"],
|
||||||
}
|
}
|
||||||
|
|
||||||
if parameters:
|
if parameters:
|
||||||
command["parameters"] = parameters
|
command["parameters"] = parameters
|
||||||
|
|
||||||
|
|
@ -130,34 +126,33 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
await self.conn.websocket.send(send_message)
|
await self.conn.websocket.send(send_message)
|
||||||
return
|
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):
|
def register_iot_tools(self, descriptors: list):
|
||||||
"""注册IoT工具"""
|
"""Register IoT tools"""
|
||||||
for descriptor in descriptors:
|
for descriptor in descriptors:
|
||||||
device_name = descriptor["name"]
|
device_name = descriptor["name"]
|
||||||
device_desc = descriptor["description"]
|
device_desc = descriptor["description"]
|
||||||
|
|
||||||
# 注册查询工具
|
# Register query tools
|
||||||
if "properties" in descriptor:
|
if "properties" in descriptor:
|
||||||
for prop_name, prop_info in descriptor["properties"].items():
|
for prop_name, prop_info in descriptor["properties"].items():
|
||||||
tool_name = f"get_{device_name.lower()}_{prop_name.lower()}"
|
tool_name = f"get_{device_name.lower()}_{prop_name.lower()}"
|
||||||
|
|
||||||
tool_desc = {
|
tool_desc = {
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": tool_name,
|
"name": tool_name,
|
||||||
"description": f"查询{device_desc}的{prop_info['description']}",
|
"description": f"Query {prop_info['description']} of {device_desc}",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"response_success": {
|
"response_success": {
|
||||||
"type": "string",
|
"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": {
|
"response_failure": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": f"查询失败时的友好回复",
|
"description": f"Friendly reply when query fails",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"required": ["response_success", "response_failure"],
|
"required": ["response_success", "response_failure"],
|
||||||
|
|
@ -171,16 +166,16 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
tool_type=ToolType.DEVICE_IOT,
|
tool_type=ToolType.DEVICE_IOT,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 注册控制工具
|
# Register control tools
|
||||||
if "methods" in descriptor:
|
if "methods" in descriptor:
|
||||||
for method_name, method_info in descriptor["methods"].items():
|
for method_name, method_info in descriptor["methods"].items():
|
||||||
tool_name = f"{device_name.lower()}_{method_name.lower()}"
|
tool_name = f"{device_name.lower()}_{method_name.lower()}"
|
||||||
|
|
||||||
# 构建参数
|
# Build parameters
|
||||||
parameters = {}
|
parameters = {}
|
||||||
required_params = []
|
required_params = []
|
||||||
|
|
||||||
# 添加方法的原始参数
|
# Add original method parameters
|
||||||
if "parameters" in method_info:
|
if "parameters" in method_info:
|
||||||
parameters.update(
|
parameters.update(
|
||||||
{
|
{
|
||||||
|
|
@ -195,16 +190,16 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
)
|
)
|
||||||
required_params.extend(method_info["parameters"].keys())
|
required_params.extend(method_info["parameters"].keys())
|
||||||
|
|
||||||
# 添加响应参数
|
# Add response parameters
|
||||||
parameters.update(
|
parameters.update(
|
||||||
{
|
{
|
||||||
"response_success": {
|
"response_success": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "操作成功时的友好回复",
|
"description": "Friendly reply when operation is successful",
|
||||||
},
|
},
|
||||||
"response_failure": {
|
"response_failure": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "操作失败时的友好回复",
|
"description": "Friendly reply when operation fails",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
@ -230,9 +225,9 @@ class DeviceIoTExecutor(ToolExecutor):
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_tools(self) -> Dict[str, ToolDefinition]:
|
def get_tools(self) -> Dict[str, ToolDefinition]:
|
||||||
"""获取所有设备端IoT工具"""
|
"""Get all device-side IoT tools"""
|
||||||
return self.iot_tools.copy()
|
return self.iot_tools.copy()
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
def has_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否有指定的设备端IoT工具"""
|
"""Check if the specified device-side IoT tool exists"""
|
||||||
return tool_name in self.iot_tools
|
return tool_name in self.iot_tools
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""IoT设备支持模块,提供IoT设备描述符和状态处理"""
|
"""IoT device support module, provides IoT device descriptor and status handling"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
@ -9,7 +9,7 @@ logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
async def handleIotDescriptors(conn, descriptors):
|
async def handleIotDescriptors(conn, descriptors):
|
||||||
"""处理物联网描述"""
|
"""Handle IoT descriptors"""
|
||||||
wait_max_time = 5
|
wait_max_time = 5
|
||||||
while (
|
while (
|
||||||
not hasattr(conn, "func_handler")
|
not hasattr(conn, "func_handler")
|
||||||
|
|
@ -19,31 +19,30 @@ async def handleIotDescriptors(conn, descriptors):
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
wait_max_time -= 1
|
wait_max_time -= 1
|
||||||
if wait_max_time <= 0:
|
if wait_max_time <= 0:
|
||||||
logger.bind(tag=TAG).debug("连接对象没有func_handler")
|
logger.bind(tag=TAG).debug("Connection object has no func_handler")
|
||||||
return
|
return
|
||||||
|
|
||||||
functions_changed = False
|
functions_changed = False
|
||||||
|
|
||||||
for descriptor in descriptors:
|
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:
|
if "properties" not in descriptor and "methods" not in descriptor:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 处理缺失properties的情况
|
# Handle missing properties case
|
||||||
if "properties" not in descriptor:
|
if "properties" not in descriptor:
|
||||||
descriptor["properties"] = {}
|
descriptor["properties"] = {}
|
||||||
# 从methods中提取所有参数作为properties
|
# Extract all parameters from methods as properties
|
||||||
if "methods" in descriptor:
|
if "methods" in descriptor:
|
||||||
for method_name, method_info in descriptor["methods"].items():
|
for method_name, method_info in descriptor["methods"].items():
|
||||||
if "parameters" in method_info:
|
if "parameters" in method_info:
|
||||||
for param_name, param_info in method_info["parameters"].items():
|
for param_name, param_info in method_info["parameters"].items():
|
||||||
# 将参数信息转换为属性信息
|
# Convert parameter info to property info
|
||||||
descriptor["properties"][param_name] = {
|
descriptor["properties"][param_name] = {
|
||||||
"description": param_info["description"],
|
"description": param_info["description"],
|
||||||
"type": param_info["type"],
|
"type": param_info["type"],
|
||||||
}
|
}
|
||||||
|
|
||||||
# 创建IOT设备描述符
|
# Create IoT device descriptor
|
||||||
iot_descriptor = IotDescriptor(
|
iot_descriptor = IotDescriptor(
|
||||||
descriptor["name"],
|
descriptor["name"],
|
||||||
descriptor["description"],
|
descriptor["description"],
|
||||||
|
|
@ -53,16 +52,15 @@ async def handleIotDescriptors(conn, descriptors):
|
||||||
conn.iot_descriptors[descriptor["name"]] = iot_descriptor
|
conn.iot_descriptors[descriptor["name"]] = iot_descriptor
|
||||||
functions_changed = True
|
functions_changed = True
|
||||||
|
|
||||||
# 如果注册了新函数,更新function描述列表
|
# If new functions are registered, update function description list
|
||||||
if functions_changed and hasattr(conn, "func_handler"):
|
if functions_changed and hasattr(conn, "func_handler"):
|
||||||
# 注册IoT工具到统一工具处理器
|
# Register IoT tools to unified tool handler
|
||||||
await conn.func_handler.register_iot_tools(descriptors)
|
await conn.func_handler.register_iot_tools(descriptors)
|
||||||
|
|
||||||
conn.func_handler.current_support_functions()
|
conn.func_handler.current_support_functions()
|
||||||
|
|
||||||
|
|
||||||
async def handleIotStatus(conn, states):
|
async def handleIotStatus(conn, states):
|
||||||
"""处理物联网状态"""
|
"""Handle IoT status"""
|
||||||
for state in states:
|
for state in states:
|
||||||
for key, value in conn.iot_descriptors.items():
|
for key, value in conn.iot_descriptors.items():
|
||||||
if key == state["name"]:
|
if key == state["name"]:
|
||||||
|
|
@ -71,13 +69,13 @@ async def handleIotStatus(conn, states):
|
||||||
if property_item["name"] == k:
|
if property_item["name"] == k:
|
||||||
if type(v) != type(property_item["value"]):
|
if type(v) != type(property_item["value"]):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"属性{property_item['name']}的值类型不匹配"
|
f"Property {property_item['name']} value type mismatch"
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
property_item["value"] = v
|
property_item["value"] = v
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"物联网状态更新: {key} , {property_item['name']} = {v}"
|
f"IoT status update: {key}, {property_item['name']} = {v}"
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
break
|
break
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
"""设备端MCP工具模块"""
|
"""Device-side MCP tool module"""
|
||||||
|
|
||||||
from .mcp_client import MCPClient
|
from .mcp_client import MCPClient
|
||||||
|
|
||||||
from .mcp_handler import (
|
from .mcp_handler import (
|
||||||
send_mcp_message,
|
send_mcp_message,
|
||||||
handle_mcp_message,
|
handle_mcp_message,
|
||||||
|
|
@ -8,6 +9,7 @@ from .mcp_handler import (
|
||||||
send_mcp_tools_list_request,
|
send_mcp_tools_list_request,
|
||||||
call_mcp_tool,
|
call_mcp_tool,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .mcp_executor import DeviceMCPExecutor
|
from .mcp_executor import DeviceMCPExecutor
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""设备端MCP客户端定义"""
|
"""Device-side MCP client definition"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from concurrent.futures import Future
|
from concurrent.futures import Future
|
||||||
|
|
@ -8,9 +8,8 @@ from config.logger import setup_logging
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class MCPClient:
|
class MCPClient:
|
||||||
"""设备端MCP客户端,用于管理MCP状态和工具"""
|
"""Device-side MCP client for managing MCP state and tools"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.tools = {} # sanitized_name -> tool_data
|
self.tools = {} # sanitized_name -> tool_data
|
||||||
|
|
@ -59,9 +58,7 @@ class MCPClient:
|
||||||
sanitized_name = sanitize_tool_name(tool_data["name"])
|
sanitized_name = sanitize_tool_name(tool_data["name"])
|
||||||
self.tools[sanitized_name] = tool_data
|
self.tools[sanitized_name] = tool_data
|
||||||
self.name_mapping[sanitized_name] = tool_data["name"]
|
self.name_mapping[sanitized_name] = tool_data["name"]
|
||||||
self._cached_available_tools = (
|
self._cached_available_tools = None # Invalidate the cache when a tool is added
|
||||||
None # Invalidate the cache when a tool is added
|
|
||||||
)
|
|
||||||
|
|
||||||
async def get_next_id(self) -> int:
|
async def get_next_id(self) -> int:
|
||||||
async with self.lock:
|
async with self.lock:
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,12 @@
|
||||||
"""设备端MCP工具执行器"""
|
"""Device-side MCP tool executor"""
|
||||||
|
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
from .mcp_handler import call_mcp_tool
|
from .mcp_handler import call_mcp_tool
|
||||||
|
|
||||||
|
|
||||||
class DeviceMCPExecutor(ToolExecutor):
|
class DeviceMCPExecutor(ToolExecutor):
|
||||||
"""设备端MCP工具执行器"""
|
"""Device-side MCP tool executor"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -15,26 +14,25 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行设备端MCP工具"""
|
"""Execute device-side MCP tool"""
|
||||||
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
|
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
action=Action.ERROR,
|
||||||
response="设备端MCP客户端未初始化",
|
response="Device-side MCP client not initialized",
|
||||||
)
|
)
|
||||||
|
|
||||||
if not await conn.mcp_client.is_ready():
|
if not await conn.mcp_client.is_ready():
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
action=Action.ERROR,
|
||||||
response="设备端MCP客户端未准备就绪",
|
response="Device-side MCP client not ready",
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 转换参数为JSON字符串
|
# Convert parameters to JSON string
|
||||||
import json
|
import json
|
||||||
|
|
||||||
args_str = json.dumps(arguments) if arguments else "{}"
|
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)
|
result = await call_mcp_tool(conn, conn.mcp_client, tool_name, args_str)
|
||||||
|
|
||||||
resultJson = None
|
resultJson = None
|
||||||
|
|
@ -44,7 +42,7 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 视觉大模型不经过二次LLM处理
|
# Vision models do not go through secondary LLM processing
|
||||||
if (
|
if (
|
||||||
resultJson is not None
|
resultJson is not None
|
||||||
and isinstance(resultJson, dict)
|
and isinstance(resultJson, dict)
|
||||||
|
|
@ -63,7 +61,7 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
return ActionResponse(action=Action.ERROR, response=str(e))
|
return ActionResponse(action=Action.ERROR, response=str(e))
|
||||||
|
|
||||||
def get_tools(self) -> Dict[str, ToolDefinition]:
|
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:
|
if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
@ -73,7 +71,6 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
for tool in mcp_tools:
|
for tool in mcp_tools:
|
||||||
func_def = tool.get("function", {})
|
func_def = tool.get("function", {})
|
||||||
tool_name = func_def.get("name", "")
|
tool_name = func_def.get("name", "")
|
||||||
|
|
||||||
if tool_name:
|
if tool_name:
|
||||||
tools[tool_name] = ToolDefinition(
|
tools[tool_name] = ToolDefinition(
|
||||||
name=tool_name, description=tool, tool_type=ToolType.DEVICE_MCP
|
name=tool_name, description=tool, tool_type=ToolType.DEVICE_MCP
|
||||||
|
|
@ -82,8 +79,7 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
return tools
|
return tools
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
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:
|
if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return self.conn.mcp_client.has_tool(tool_name)
|
return self.conn.mcp_client.has_tool(tool_name)
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""设备端MCP客户端支持模块"""
|
"""Device-side MCP client support module"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
@ -12,111 +12,28 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
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):
|
async def send_mcp_message(conn, payload: dict):
|
||||||
"""Helper to send MCP messages, encapsulating common logic."""
|
"""Helper to send MCP messages, encapsulating common logic."""
|
||||||
if not conn.features.get("mcp"):
|
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
|
return
|
||||||
|
|
||||||
message = json.dumps({"type": "mcp", "payload": payload})
|
message = json.dumps({"type": "mcp", "payload": payload})
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await conn.websocket.send(message)
|
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:
|
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):
|
async def handle_mcp_message(conn, mcp_client, payload: dict):
|
||||||
"""处理MCP消息,包括初始化、工具列表和工具调用响应等"""
|
"""Handle MCP messages, including initialization, tool list and tool call responses"""
|
||||||
logger.bind(tag=TAG).info(f"处理MCP消息: {str(payload)[:100]}")
|
logger.bind(tag=TAG).info(f"Handling MCP message: {str(payload)[:100]}")
|
||||||
|
|
||||||
if not isinstance(payload, dict):
|
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
|
return
|
||||||
|
|
||||||
# Handle result
|
# Handle result
|
||||||
|
|
@ -127,32 +44,32 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
|
||||||
# Check for tool call response first
|
# Check for tool call response first
|
||||||
if msg_id in mcp_client.call_results:
|
if msg_id in mcp_client.call_results:
|
||||||
logger.bind(tag=TAG).debug(
|
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)
|
await mcp_client.resolve_call_result(msg_id, result)
|
||||||
return
|
return
|
||||||
|
|
||||||
if msg_id == 1: # mcpInitializeID
|
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")
|
server_info = result.get("serverInfo")
|
||||||
if isinstance(server_info, dict):
|
if isinstance(server_info, dict):
|
||||||
name = server_info.get("name")
|
name = server_info.get("name")
|
||||||
version = server_info.get("version")
|
version = server_info.get("version")
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"客户端MCP服务器信息: name={name}, version={version}"
|
f"Client MCP server info: name={name}, version={version}"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
elif msg_id == 2: # mcpToolsListID
|
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:
|
if isinstance(result, dict) and "tools" in result:
|
||||||
tools_data = result["tools"]
|
tools_data = result["tools"]
|
||||||
if not isinstance(tools_data, list):
|
if not isinstance(tools_data, list):
|
||||||
logger.bind(tag=TAG).error("工具列表格式错误")
|
logger.bind(tag=TAG).error("Tools list format error")
|
||||||
return
|
return
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
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):
|
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", "")
|
name = tool.get("name", "")
|
||||||
description = tool.get("description", "")
|
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):
|
if "inputSchema" in tool and isinstance(tool["inputSchema"], dict):
|
||||||
schema = tool["inputSchema"]
|
schema = tool["inputSchema"]
|
||||||
input_schema["type"] = schema.get("type", "object")
|
input_schema["type"] = schema.get("type", "object")
|
||||||
input_schema["properties"] = schema.get("properties", {})
|
input_schema["properties"] = schema.get(
|
||||||
|
"properties", {})
|
||||||
input_schema["required"] = [
|
input_schema["required"] = [
|
||||||
s for s in schema.get("required", []) if isinstance(s, str)
|
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,
|
"description": description,
|
||||||
"inputSchema": input_schema,
|
"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():
|
for tool_data in mcp_client.tools.values():
|
||||||
if "description" in tool_data:
|
if "description" in tool_data:
|
||||||
description = tool_data["description"]
|
description = tool_data["description"]
|
||||||
# 遍历所有工具名称进行替换
|
# Iterate through all tool names for replacement
|
||||||
for (
|
for (
|
||||||
sanitized_name,
|
sanitized_name,
|
||||||
original_name,
|
original_name,
|
||||||
|
|
@ -195,13 +115,15 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
|
||||||
|
|
||||||
next_cursor = result.get("nextCursor", "")
|
next_cursor = result.get("nextCursor", "")
|
||||||
if next_cursor:
|
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)
|
await send_mcp_tools_list_continue_request(conn, next_cursor)
|
||||||
else:
|
else:
|
||||||
await mcp_client.set_ready(True)
|
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:
|
if hasattr(conn, "func_handler") and conn.func_handler:
|
||||||
conn.func_handler.tool_manager.refresh_tools()
|
conn.func_handler.tool_manager.refresh_tools()
|
||||||
conn.func_handler.current_support_functions()
|
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)
|
# Handle method calls (requests from the client)
|
||||||
elif "method" in payload:
|
elif "method" in payload:
|
||||||
method = payload["method"]
|
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:
|
elif "error" in payload:
|
||||||
error_data = payload["error"]
|
error_data = payload["error"]
|
||||||
error_msg = error_data.get("message", "未知错误")
|
error_msg = error_data.get("message", "Unknown error")
|
||||||
logger.bind(tag=TAG).error(f"收到MCP错误响应: {error_msg}")
|
logger.bind(tag=TAG).error(f"Received MCP error response: {error_msg}")
|
||||||
|
|
||||||
msg_id = int(payload.get("id", 0))
|
msg_id = int(payload.get("id", 0))
|
||||||
if msg_id in mcp_client.call_results:
|
if msg_id in mcp_client.call_results:
|
||||||
await mcp_client.reject_call_result(
|
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):
|
async def send_mcp_initialize_message(conn):
|
||||||
"""发送MCP初始化消息"""
|
"""Send MCP initialization message"""
|
||||||
|
|
||||||
vision_url = get_vision_url(conn.config)
|
vision_url = get_vision_url(conn.config)
|
||||||
|
# Generate token using key
|
||||||
# 密钥生成token
|
|
||||||
auth = AuthToken(conn.config["server"]["auth_key"])
|
auth = AuthToken(conn.config["server"]["auth_key"])
|
||||||
token = auth.generate_token(conn.headers.get("device-id"))
|
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)
|
await send_mcp_message(conn, payload)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_tools_list_request(conn):
|
async def send_mcp_tools_list_request(conn):
|
||||||
"""发送MCP工具列表请求"""
|
"""Send MCP tools list request"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 2, # mcpToolsListID
|
"id": 2, # mcpToolsListID
|
||||||
"method": "tools/list",
|
"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)
|
await send_mcp_message(conn, payload)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_tools_list_continue_request(conn, cursor: str):
|
async def send_mcp_tools_list_continue_request(conn, cursor: str):
|
||||||
"""发送带有cursor的MCP工具列表请求"""
|
"""Send MCP tools list request with cursor"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 2, # mcpToolsListID (same ID for continuation)
|
"id": 2, # mcpToolsListID (same ID for continuation)
|
||||||
"method": "tools/list",
|
"method": "tools/list",
|
||||||
"params": {"cursor": cursor},
|
"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)
|
await send_mcp_message(conn, payload)
|
||||||
|
|
||||||
|
|
||||||
async def call_mcp_tool(
|
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():
|
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):
|
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()
|
tool_call_id = await mcp_client.get_next_id()
|
||||||
result_future = asyncio.Future()
|
result_future = asyncio.Future()
|
||||||
await mcp_client.register_call_result_future(tool_call_id, result_future)
|
await mcp_client.register_call_result_future(tool_call_id, result_future)
|
||||||
|
|
||||||
# 处理参数
|
# Handle parameters
|
||||||
try:
|
try:
|
||||||
if isinstance(args, str):
|
if isinstance(args, str):
|
||||||
# 确保字符串是有效的JSON
|
# Ensure string is valid JSON
|
||||||
if not args.strip():
|
if not args.strip():
|
||||||
arguments = {}
|
arguments = {}
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
# 尝试直接解析
|
# Try to parse directly
|
||||||
arguments = json.loads(args)
|
arguments = json.loads(args)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
# 如果解析失败,尝试合并多个JSON对象
|
# If parsing fails, try to merge multiple JSON objects
|
||||||
try:
|
try:
|
||||||
# 使用正则表达式匹配所有JSON对象
|
# Use regex to match all JSON objects
|
||||||
json_objects = re.findall(r"\{[^{}]*\}", args)
|
json_objects = re.findall(r"\{[^{}]*\}", args)
|
||||||
if len(json_objects) > 1:
|
if len(json_objects) > 1:
|
||||||
# 合并所有JSON对象
|
# Merge all JSON objects
|
||||||
merged_dict = {}
|
merged_dict = {}
|
||||||
for json_str in json_objects:
|
for json_str in json_objects:
|
||||||
try:
|
try:
|
||||||
|
|
@ -326,29 +248,35 @@ async def call_mcp_tool(
|
||||||
if merged_dict:
|
if merged_dict:
|
||||||
arguments = merged_dict
|
arguments = merged_dict
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"无法解析任何有效的JSON对象: {args}")
|
raise ValueError(
|
||||||
|
f"Cannot parse any valid JSON objects: {args}")
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"参数JSON解析失败: {args}")
|
raise ValueError(
|
||||||
|
f"Parameter JSON parsing failed: {args}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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):
|
elif isinstance(args, dict):
|
||||||
arguments = args
|
arguments = args
|
||||||
else:
|
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):
|
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:
|
except Exception as e:
|
||||||
if not isinstance(e, ValueError):
|
if not isinstance(e, ValueError):
|
||||||
raise ValueError(f"参数处理失败: {str(e)}")
|
raise ValueError(f"Parameter processing failed: {str(e)}")
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
|
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": tool_call_id,
|
"id": tool_call_id,
|
||||||
|
|
@ -356,33 +284,36 @@ async def call_mcp_tool(
|
||||||
"params": {"name": actual_name, "arguments": arguments},
|
"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)
|
await send_mcp_message(conn, payload)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Wait for response or timeout
|
# Wait for response or timeout
|
||||||
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
|
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
|
||||||
logger.bind(tag=TAG).info(
|
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 isinstance(raw_result, dict):
|
||||||
if raw_result.get("isError") is True:
|
if raw_result.get("isError") is True:
|
||||||
error_msg = raw_result.get(
|
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")
|
content = raw_result.get("content")
|
||||||
if isinstance(content, list) and len(content) > 0:
|
if isinstance(content, list) and len(content) > 0:
|
||||||
if isinstance(content[0], dict) and "text" in content[0]:
|
if isinstance(content[0], dict) and "text" in content[0]:
|
||||||
# 直接返回文本内容,不进行JSON解析
|
# Return text content directly without JSON parsing
|
||||||
return content[0]["text"]
|
return content[0]["text"]
|
||||||
# 如果结果不是预期的格式,将其转换为字符串
|
|
||||||
|
# If result is not in expected format, convert to string
|
||||||
return str(raw_result)
|
return str(raw_result)
|
||||||
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
await mcp_client.cleanup_call_result(tool_call_id)
|
await mcp_client.cleanup_call_result(tool_call_id)
|
||||||
raise TimeoutError("工具调用请求超时")
|
raise TimeoutError("Tool call request timeout")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await mcp_client.cleanup_call_result(tool_call_id)
|
await mcp_client.cleanup_call_result(tool_call_id)
|
||||||
raise e
|
raise e
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
"""MCP接入点工具模块"""
|
"""MCP endpoint tool module"""
|
||||||
|
|
||||||
from .mcp_endpoint_executor import MCPEndpointExecutor
|
from .mcp_endpoint_executor import MCPEndpointExecutor
|
||||||
|
|
||||||
from .mcp_endpoint_client import MCPEndpointClient
|
from .mcp_endpoint_client import MCPEndpointClient
|
||||||
|
|
||||||
from .mcp_endpoint_handler import (
|
from .mcp_endpoint_handler import (
|
||||||
connect_mcp_endpoint,
|
connect_mcp_endpoint,
|
||||||
send_mcp_endpoint_initialize,
|
send_mcp_endpoint_initialize,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""MCP接入点客户端定义"""
|
"""MCP endpoint client definition"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from concurrent.futures import Future
|
from concurrent.futures import Future
|
||||||
|
|
@ -8,9 +8,8 @@ from config.logger import setup_logging
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class MCPEndpointClient:
|
class MCPEndpointClient:
|
||||||
"""MCP接入点客户端,用于管理MCP接入点状态和工具"""
|
"""MCP endpoint client for managing MCP endpoint state and tools"""
|
||||||
|
|
||||||
def __init__(self, conn=None):
|
def __init__(self, conn=None):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -21,7 +20,7 @@ class MCPEndpointClient:
|
||||||
self.next_id = 1
|
self.next_id = 1
|
||||||
self.lock = asyncio.Lock()
|
self.lock = asyncio.Lock()
|
||||||
self._cached_available_tools = None # Cache for get_available_tools
|
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:
|
def has_tool(self, name: str) -> bool:
|
||||||
return name in self.tools
|
return name in self.tools
|
||||||
|
|
@ -61,9 +60,7 @@ class MCPEndpointClient:
|
||||||
sanitized_name = sanitize_tool_name(tool_data["name"])
|
sanitized_name = sanitize_tool_name(tool_data["name"])
|
||||||
self.tools[sanitized_name] = tool_data
|
self.tools[sanitized_name] = tool_data
|
||||||
self.name_mapping[sanitized_name] = tool_data["name"]
|
self.name_mapping[sanitized_name] = tool_data["name"]
|
||||||
self._cached_available_tools = (
|
self._cached_available_tools = None # Invalidate the cache when a tool is added
|
||||||
None # Invalidate the cache when a tool is added
|
|
||||||
)
|
|
||||||
|
|
||||||
async def get_next_id(self) -> int:
|
async def get_next_id(self) -> int:
|
||||||
async with self.lock:
|
async with self.lock:
|
||||||
|
|
@ -95,18 +92,18 @@ class MCPEndpointClient:
|
||||||
self.call_results.pop(id)
|
self.call_results.pop(id)
|
||||||
|
|
||||||
def set_websocket(self, websocket):
|
def set_websocket(self, websocket):
|
||||||
"""设置WebSocket连接"""
|
"""Set WebSocket connection"""
|
||||||
self.websocket = websocket
|
self.websocket = websocket
|
||||||
|
|
||||||
async def send_message(self, message: str):
|
async def send_message(self, message: str):
|
||||||
"""发送消息到MCP接入点"""
|
"""Send message to MCP endpoint"""
|
||||||
if self.websocket:
|
if self.websocket:
|
||||||
await self.websocket.send(message)
|
await self.websocket.send(message)
|
||||||
else:
|
else:
|
||||||
raise RuntimeError("WebSocket连接未建立")
|
raise RuntimeError("WebSocket connection not established")
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""关闭WebSocket连接"""
|
"""Close WebSocket connection"""
|
||||||
if self.websocket:
|
if self.websocket:
|
||||||
await self.websocket.close()
|
await self.websocket.close()
|
||||||
self.websocket = None
|
self.websocket = None
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""MCP接入点工具执行器"""
|
"""MCP endpoint tool executor"""
|
||||||
|
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
|
|
@ -7,7 +7,7 @@ from .mcp_endpoint_handler import call_mcp_endpoint_tool
|
||||||
|
|
||||||
|
|
||||||
class MCPEndpointExecutor(ToolExecutor):
|
class MCPEndpointExecutor(ToolExecutor):
|
||||||
"""MCP接入点工具执行器"""
|
"""MCP endpoint tool executor"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -15,26 +15,25 @@ class MCPEndpointExecutor(ToolExecutor):
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行MCP接入点工具"""
|
"""Execute MCP endpoint tool"""
|
||||||
if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client:
|
if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
action=Action.ERROR,
|
||||||
response="MCP接入点客户端未初始化",
|
response="MCP endpoint client not initialized",
|
||||||
)
|
)
|
||||||
|
|
||||||
if not await conn.mcp_endpoint_client.is_ready():
|
if not await conn.mcp_endpoint_client.is_ready():
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
action=Action.ERROR,
|
||||||
response="MCP接入点客户端未准备就绪",
|
response="MCP endpoint client not ready",
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 转换参数为JSON字符串
|
# Convert parameters to JSON string
|
||||||
import json
|
import json
|
||||||
|
|
||||||
args_str = json.dumps(arguments) if arguments else "{}"
|
args_str = json.dumps(arguments) if arguments else "{}"
|
||||||
|
|
||||||
# 调用MCP接入点工具
|
# Call MCP endpoint tool
|
||||||
result = await call_mcp_endpoint_tool(
|
result = await call_mcp_endpoint_tool(
|
||||||
conn.mcp_endpoint_client, tool_name, args_str
|
conn.mcp_endpoint_client, tool_name, args_str
|
||||||
)
|
)
|
||||||
|
|
@ -46,7 +45,7 @@ class MCPEndpointExecutor(ToolExecutor):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 视觉大模型不经过二次LLM处理
|
# Vision models do not go through secondary LLM processing
|
||||||
if (
|
if (
|
||||||
resultJson is not None
|
resultJson is not None
|
||||||
and isinstance(resultJson, dict)
|
and isinstance(resultJson, dict)
|
||||||
|
|
@ -65,7 +64,7 @@ class MCPEndpointExecutor(ToolExecutor):
|
||||||
return ActionResponse(action=Action.ERROR, response=str(e))
|
return ActionResponse(action=Action.ERROR, response=str(e))
|
||||||
|
|
||||||
def get_tools(self) -> Dict[str, ToolDefinition]:
|
def get_tools(self) -> Dict[str, ToolDefinition]:
|
||||||
"""获取所有MCP接入点工具"""
|
"""Get all MCP endpoint tools"""
|
||||||
if (
|
if (
|
||||||
not hasattr(self.conn, "mcp_endpoint_client")
|
not hasattr(self.conn, "mcp_endpoint_client")
|
||||||
or not self.conn.mcp_endpoint_client
|
or not self.conn.mcp_endpoint_client
|
||||||
|
|
@ -78,7 +77,6 @@ class MCPEndpointExecutor(ToolExecutor):
|
||||||
for tool in mcp_tools:
|
for tool in mcp_tools:
|
||||||
func_def = tool.get("function", {})
|
func_def = tool.get("function", {})
|
||||||
tool_name = func_def.get("name", "")
|
tool_name = func_def.get("name", "")
|
||||||
|
|
||||||
if tool_name:
|
if tool_name:
|
||||||
tools[tool_name] = ToolDefinition(
|
tools[tool_name] = ToolDefinition(
|
||||||
name=tool_name, description=tool, tool_type=ToolType.MCP_ENDPOINT
|
name=tool_name, description=tool, tool_type=ToolType.MCP_ENDPOINT
|
||||||
|
|
@ -87,11 +85,10 @@ class MCPEndpointExecutor(ToolExecutor):
|
||||||
return tools
|
return tools
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
def has_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否有指定的MCP接入点工具"""
|
"""Check if the specified MCP endpoint tool exists"""
|
||||||
if (
|
if (
|
||||||
not hasattr(self.conn, "mcp_endpoint_client")
|
not hasattr(self.conn, "mcp_endpoint_client")
|
||||||
or not self.conn.mcp_endpoint_client
|
or not self.conn.mcp_endpoint_client
|
||||||
):
|
):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return self.conn.mcp_endpoint_client.has_tool(tool_name)
|
return self.conn.mcp_endpoint_client.has_tool(tool_name)
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""MCP接入点处理器"""
|
"""MCP endpoint handler"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
@ -12,92 +12,93 @@ logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
async def connect_mcp_endpoint(mcp_endpoint_url: str, conn=None) -> MCPEndpointClient:
|
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":
|
if not mcp_endpoint_url or "你的" in mcp_endpoint_url or mcp_endpoint_url == "null":
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
websocket = await websockets.connect(mcp_endpoint_url)
|
websocket = await websockets.connect(mcp_endpoint_url)
|
||||||
|
|
||||||
mcp_client = MCPEndpointClient(conn)
|
mcp_client = MCPEndpointClient(conn)
|
||||||
mcp_client.set_websocket(websocket)
|
mcp_client.set_websocket(websocket)
|
||||||
|
|
||||||
# 启动消息监听器
|
# Start message listener
|
||||||
asyncio.create_task(_message_listener(mcp_client))
|
asyncio.create_task(_message_listener(mcp_client))
|
||||||
|
|
||||||
# 发送初始化消息
|
# Send initialization message
|
||||||
await send_mcp_endpoint_initialize(mcp_client)
|
await send_mcp_endpoint_initialize(mcp_client)
|
||||||
|
|
||||||
# 发送初始化完成通知
|
# Send initialization complete notification
|
||||||
await send_mcp_endpoint_notification(mcp_client, "notifications/initialized")
|
await send_mcp_endpoint_notification(mcp_client, "notifications/initialized")
|
||||||
|
|
||||||
# 获取工具列表
|
# Get tools list
|
||||||
await send_mcp_endpoint_tools_list(mcp_client)
|
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
|
return mcp_client
|
||||||
|
|
||||||
except Exception as e:
|
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
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def _message_listener(mcp_client: MCPEndpointClient):
|
async def _message_listener(mcp_client: MCPEndpointClient):
|
||||||
"""监听MCP接入点消息"""
|
"""Listen for MCP endpoint messages"""
|
||||||
try:
|
try:
|
||||||
async for message in mcp_client.websocket:
|
async for message in mcp_client.websocket:
|
||||||
await handle_mcp_endpoint_message(mcp_client, message)
|
await handle_mcp_endpoint_message(mcp_client, message)
|
||||||
except websockets.exceptions.ConnectionClosed:
|
except websockets.exceptions.ConnectionClosed:
|
||||||
logger.bind(tag=TAG).info("MCP接入点连接已关闭")
|
logger.bind(tag=TAG).info("MCP endpoint connection closed")
|
||||||
except Exception as e:
|
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:
|
finally:
|
||||||
await mcp_client.set_ready(False)
|
await mcp_client.set_ready(False)
|
||||||
|
|
||||||
|
|
||||||
async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: str):
|
async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: str):
|
||||||
"""处理MCP接入点消息"""
|
"""Handle MCP endpoint messages"""
|
||||||
try:
|
try:
|
||||||
payload = json.loads(message)
|
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):
|
if not isinstance(payload, dict):
|
||||||
logger.bind(tag=TAG).error("MCP接入点消息格式错误")
|
logger.bind(tag=TAG).error("MCP endpoint message format error")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Handle result
|
# Handle result
|
||||||
if "result" in payload:
|
if "result" in payload:
|
||||||
result = payload["result"]
|
result = payload["result"]
|
||||||
# 安全地获取消息ID,如果为None则使用0
|
# Safely get message ID, use 0 if None
|
||||||
msg_id_raw = payload.get("id")
|
msg_id_raw = payload.get("id")
|
||||||
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
|
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
|
||||||
|
|
||||||
# Check for tool call response first
|
# Check for tool call response first
|
||||||
if msg_id in mcp_client.call_results:
|
if msg_id in mcp_client.call_results:
|
||||||
logger.bind(tag=TAG).debug(
|
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)
|
await mcp_client.resolve_call_result(msg_id, result)
|
||||||
return
|
return
|
||||||
|
|
||||||
if msg_id == 1: # mcpInitializeID
|
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):
|
if result is not None and isinstance(result, dict):
|
||||||
server_info = result.get("serverInfo")
|
server_info = result.get("serverInfo")
|
||||||
if isinstance(server_info, dict):
|
if isinstance(server_info, dict):
|
||||||
name = server_info.get("name")
|
name = server_info.get("name")
|
||||||
version = server_info.get("version")
|
version = server_info.get("version")
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"MCP接入点服务器信息: name={name}, version={version}"
|
f"MCP endpoint server info: name={name}, version={version}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).warning(
|
logger.bind(tag=TAG).warning(
|
||||||
"MCP接入点初始化响应结果为空或格式错误"
|
"MCP endpoint initialization response result is empty or format error"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
elif msg_id == 2: # mcpToolsListID
|
elif msg_id == 2: # mcpToolsListID
|
||||||
logger.bind(tag=TAG).debug("收到MCP接入点工具列表响应")
|
logger.bind(tag=TAG).debug(
|
||||||
|
"Received MCP endpoint tools list response")
|
||||||
if (
|
if (
|
||||||
result is not None
|
result is not None
|
||||||
and isinstance(result, dict)
|
and isinstance(result, dict)
|
||||||
|
|
@ -105,11 +106,11 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
|
||||||
):
|
):
|
||||||
tools_data = result["tools"]
|
tools_data = result["tools"]
|
||||||
if not isinstance(tools_data, list):
|
if not isinstance(tools_data, list):
|
||||||
logger.bind(tag=TAG).error("工具列表格式错误")
|
logger.bind(tag=TAG).error("Tools list format error")
|
||||||
return
|
return
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
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):
|
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"]
|
schema = tool["inputSchema"]
|
||||||
input_schema["type"] = schema.get("type", "object")
|
input_schema["type"] = schema.get("type", "object")
|
||||||
input_schema["properties"] = schema.get("properties", {})
|
input_schema["properties"] = schema.get(
|
||||||
|
"properties", {})
|
||||||
input_schema["required"] = [
|
input_schema["required"] = [
|
||||||
s
|
s
|
||||||
for s in schema.get("required", [])
|
for s in schema.get("required", [])
|
||||||
|
|
@ -141,14 +143,16 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
|
||||||
"description": description,
|
"description": description,
|
||||||
"inputSchema": input_schema,
|
"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():
|
for tool_data in mcp_client.tools.values():
|
||||||
if "description" in tool_data:
|
if "description" in tool_data:
|
||||||
description = tool_data["description"]
|
description = tool_data["description"]
|
||||||
# 遍历所有工具名称进行替换
|
# Iterate through all tool names for replacement
|
||||||
for (
|
for (
|
||||||
sanitized_name,
|
sanitized_name,
|
||||||
original_name,
|
original_name,
|
||||||
|
|
@ -159,11 +163,13 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
|
||||||
tool_data["description"] = description
|
tool_data["description"] = description
|
||||||
|
|
||||||
next_cursor = (
|
next_cursor = (
|
||||||
result.get("nextCursor", "") if result is not None else ""
|
result.get(
|
||||||
|
"nextCursor", "") if result is not None else ""
|
||||||
)
|
)
|
||||||
|
|
||||||
if next_cursor:
|
if next_cursor:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"有更多工具,nextCursor: {next_cursor}"
|
f"More tools available, nextCursor: {next_cursor}"
|
||||||
)
|
)
|
||||||
await send_mcp_endpoint_tools_list_continue(
|
await send_mcp_endpoint_tools_list_continue(
|
||||||
mcp_client, next_cursor
|
mcp_client, next_cursor
|
||||||
|
|
@ -171,10 +177,10 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
|
||||||
else:
|
else:
|
||||||
await mcp_client.set_ready(True)
|
await mcp_client.set_ready(True)
|
||||||
logger.bind(tag=TAG).info(
|
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 (
|
if (
|
||||||
hasattr(mcp_client, "conn")
|
hasattr(mcp_client, "conn")
|
||||||
and 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()
|
mcp_client.conn.func_handler.current_support_functions()
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"MCP接入点工具获取完成,共 {len(mcp_client.tools)} 个工具"
|
f"MCP endpoint tools retrieval completed, total {len(mcp_client.tools)} tools"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).warning(
|
logger.bind(tag=TAG).warning(
|
||||||
"MCP接入点工具列表响应结果为空或格式错误"
|
"MCP endpoint tools list response result is empty or format error"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# Handle method calls (requests from the endpoint)
|
# Handle method calls (requests from the endpoint)
|
||||||
elif "method" in payload:
|
elif "method" in payload:
|
||||||
method = payload["method"]
|
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:
|
elif "error" in payload:
|
||||||
error_data = payload["error"]
|
error_data = payload["error"]
|
||||||
error_msg = error_data.get("message", "未知错误")
|
error_msg = error_data.get("message", "Unknown error")
|
||||||
logger.bind(tag=TAG).error(f"收到MCP接入点错误响应: {error_msg}")
|
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_raw = payload.get("id")
|
||||||
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
|
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
|
||||||
|
|
||||||
if msg_id in mcp_client.call_results:
|
if msg_id in mcp_client.call_results:
|
||||||
await mcp_client.reject_call_result(
|
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:
|
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:
|
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
|
import traceback
|
||||||
|
logger.bind(tag=TAG).error(f"Error details: {traceback.format_exc()}")
|
||||||
logger.bind(tag=TAG).error(f"错误详情: {traceback.format_exc()}")
|
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
|
async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
|
||||||
"""发送MCP接入点初始化消息"""
|
"""Send MCP endpoint initialization message"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 1, # mcpInitializeID
|
"id": 1, # mcpInitializeID
|
||||||
|
|
@ -239,47 +247,52 @@ async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
message = json.dumps(payload)
|
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)
|
await mcp_client.send_message(message)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_endpoint_notification(mcp_client: MCPEndpointClient, method: str):
|
async def send_mcp_endpoint_notification(mcp_client: MCPEndpointClient, method: str):
|
||||||
"""发送MCP接入点通知消息"""
|
"""Send MCP endpoint notification message"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"method": method,
|
"method": method,
|
||||||
"params": {},
|
"params": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
message = json.dumps(payload)
|
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)
|
await mcp_client.send_message(message)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_endpoint_tools_list(mcp_client: MCPEndpointClient):
|
async def send_mcp_endpoint_tools_list(mcp_client: MCPEndpointClient):
|
||||||
"""发送MCP接入点工具列表请求"""
|
"""Send MCP endpoint tools list request"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 2, # mcpToolsListID
|
"id": 2, # mcpToolsListID
|
||||||
"method": "tools/list",
|
"method": "tools/list",
|
||||||
}
|
}
|
||||||
|
|
||||||
message = json.dumps(payload)
|
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)
|
await mcp_client.send_message(message)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_endpoint_tools_list_continue(
|
async def send_mcp_endpoint_tools_list_continue(
|
||||||
mcp_client: MCPEndpointClient, cursor: str
|
mcp_client: MCPEndpointClient, cursor: str
|
||||||
):
|
):
|
||||||
"""发送带有cursor的MCP接入点工具列表请求"""
|
"""Send MCP endpoint tools list request with cursor"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": 2, # mcpToolsListID (same ID for continuation)
|
"id": 2, # mcpToolsListID (same ID for continuation)
|
||||||
"method": "tools/list",
|
"method": "tools/list",
|
||||||
"params": {"cursor": cursor},
|
"params": {"cursor": cursor},
|
||||||
}
|
}
|
||||||
|
|
||||||
message = json.dumps(payload)
|
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)
|
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_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():
|
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):
|
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()
|
tool_call_id = await mcp_client.get_next_id()
|
||||||
result_future = asyncio.Future()
|
result_future = asyncio.Future()
|
||||||
await mcp_client.register_call_result_future(tool_call_id, result_future)
|
await mcp_client.register_call_result_future(tool_call_id, result_future)
|
||||||
|
|
||||||
# 处理参数
|
# Handle parameters
|
||||||
try:
|
try:
|
||||||
if isinstance(args, str):
|
if isinstance(args, str):
|
||||||
# 确保字符串是有效的JSON
|
# Ensure string is valid JSON
|
||||||
if not args.strip():
|
if not args.strip():
|
||||||
arguments = {}
|
arguments = {}
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
# 尝试直接解析
|
# Try to parse directly
|
||||||
arguments = json.loads(args)
|
arguments = json.loads(args)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
# 如果解析失败,尝试合并多个JSON对象
|
# If parsing fails, try to merge multiple JSON objects
|
||||||
try:
|
try:
|
||||||
# 使用正则表达式匹配所有JSON对象
|
# Use regex to match all JSON objects
|
||||||
json_objects = re.findall(r"\{[^{}]*\}", args)
|
json_objects = re.findall(r"\{[^{}]*\}", args)
|
||||||
if len(json_objects) > 1:
|
if len(json_objects) > 1:
|
||||||
# 合并所有JSON对象
|
# Merge all JSON objects
|
||||||
merged_dict = {}
|
merged_dict = {}
|
||||||
for json_str in json_objects:
|
for json_str in json_objects:
|
||||||
try:
|
try:
|
||||||
|
|
@ -327,29 +340,35 @@ async def call_mcp_endpoint_tool(
|
||||||
if merged_dict:
|
if merged_dict:
|
||||||
arguments = merged_dict
|
arguments = merged_dict
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"无法解析任何有效的JSON对象: {args}")
|
raise ValueError(
|
||||||
|
f"Cannot parse any valid JSON objects: {args}")
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"参数JSON解析失败: {args}")
|
raise ValueError(
|
||||||
|
f"Parameter JSON parsing failed: {args}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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):
|
elif isinstance(args, dict):
|
||||||
arguments = args
|
arguments = args
|
||||||
else:
|
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):
|
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:
|
except Exception as e:
|
||||||
if not isinstance(e, ValueError):
|
if not isinstance(e, ValueError):
|
||||||
raise ValueError(f"参数处理失败: {str(e)}")
|
raise ValueError(f"Parameter processing failed: {str(e)}")
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
|
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": tool_call_id,
|
"id": tool_call_id,
|
||||||
|
|
@ -358,33 +377,36 @@ async def call_mcp_endpoint_tool(
|
||||||
}
|
}
|
||||||
|
|
||||||
message = json.dumps(payload)
|
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)
|
await mcp_client.send_message(message)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Wait for response or timeout
|
# Wait for response or timeout
|
||||||
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
|
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
|
||||||
logger.bind(tag=TAG).info(
|
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 isinstance(raw_result, dict):
|
||||||
if raw_result.get("isError") is True:
|
if raw_result.get("isError") is True:
|
||||||
error_msg = raw_result.get(
|
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")
|
content = raw_result.get("content")
|
||||||
if isinstance(content, list) and len(content) > 0:
|
if isinstance(content, list) and len(content) > 0:
|
||||||
if isinstance(content[0], dict) and "text" in content[0]:
|
if isinstance(content[0], dict) and "text" in content[0]:
|
||||||
# 直接返回文本内容,不进行JSON解析
|
# Return text content directly without JSON parsing
|
||||||
return content[0]["text"]
|
return content[0]["text"]
|
||||||
# 如果结果不是预期的格式,将其转换为字符串
|
|
||||||
|
# If result is not in expected format, convert to string
|
||||||
return str(raw_result)
|
return str(raw_result)
|
||||||
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
await mcp_client.cleanup_call_result(tool_call_id)
|
await mcp_client.cleanup_call_result(tool_call_id)
|
||||||
raise TimeoutError("工具调用请求超时")
|
raise TimeoutError("Tool call request timeout")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await mcp_client.cleanup_call_result(tool_call_id)
|
await mcp_client.cleanup_call_result(tool_call_id)
|
||||||
raise e
|
raise e
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""服务端MCP工具模块"""
|
"""Server-side MCP tool module"""
|
||||||
|
|
||||||
from .mcp_manager import ServerMCPManager
|
from .mcp_manager import ServerMCPManager
|
||||||
from .mcp_executor import ServerMCPExecutor
|
from .mcp_executor import ServerMCPExecutor
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
"""服务端MCP客户端"""
|
"""Server-side MCP client"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
|
@ -9,7 +8,6 @@ import shutil
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
from contextlib import AsyncExitStack
|
from contextlib import AsyncExitStack
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional, List, Dict, Any
|
||||||
|
|
||||||
from mcp import ClientSession, StdioServerParameters
|
from mcp import ClientSession, StdioServerParameters
|
||||||
from mcp.client.stdio import stdio_client
|
from mcp.client.stdio import stdio_client
|
||||||
from mcp.client.sse import sse_client
|
from mcp.client.sse import sse_client
|
||||||
|
|
@ -20,42 +18,40 @@ TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
class ServerMCPClient:
|
class ServerMCPClient:
|
||||||
"""服务端MCP客户端,用于连接和管理MCP服务"""
|
"""Server-side MCP client for connecting and managing MCP services"""
|
||||||
|
|
||||||
def __init__(self, config: Dict[str, Any]):
|
def __init__(self, config: Dict[str, Any]):
|
||||||
"""初始化服务端MCP客户端
|
"""Initialize server-side MCP client
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
config: MCP服务配置字典
|
config: MCP service configuration dictionary
|
||||||
"""
|
"""
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
self._worker_task: Optional[asyncio.Task] = None
|
self._worker_task: Optional[asyncio.Task] = None
|
||||||
self._ready_evt = asyncio.Event()
|
self._ready_evt = asyncio.Event()
|
||||||
self._shutdown_evt = asyncio.Event()
|
self._shutdown_evt = asyncio.Event()
|
||||||
|
|
||||||
self.session: Optional[ClientSession] = None
|
self.session: Optional[ClientSession] = None
|
||||||
self.tools: List = [] # 原始工具对象
|
self.tools: List = [] # Original tool objects
|
||||||
self.tools_dict: Dict[str, Any] = {}
|
self.tools_dict: Dict[str, Any] = {}
|
||||||
self.name_mapping: Dict[str, str] = {}
|
self.name_mapping: Dict[str, str] = {}
|
||||||
|
|
||||||
async def initialize(self):
|
async def initialize(self):
|
||||||
"""初始化MCP客户端连接"""
|
"""Initialize MCP client connection"""
|
||||||
if self._worker_task:
|
if self._worker_task:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._worker_task = asyncio.create_task(
|
self._worker_task = asyncio.create_task(
|
||||||
self._worker(), name="ServerMCPClientWorker"
|
self._worker(), name="ServerMCPClientWorker"
|
||||||
)
|
)
|
||||||
await self._ready_evt.wait()
|
|
||||||
|
|
||||||
|
await self._ready_evt.wait()
|
||||||
self.logger.bind(tag=TAG).info(
|
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):
|
async def cleanup(self):
|
||||||
"""清理MCP客户端资源"""
|
"""Clean up MCP client resources"""
|
||||||
if not self._worker_task:
|
if not self._worker_task:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -63,26 +59,27 @@ class ServerMCPClient:
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(self._worker_task, timeout=20)
|
await asyncio.wait_for(self._worker_task, timeout=20)
|
||||||
except (asyncio.TimeoutError, Exception) as e:
|
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:
|
finally:
|
||||||
self._worker_task = None
|
self._worker_task = None
|
||||||
|
|
||||||
def has_tool(self, name: str) -> bool:
|
def has_tool(self, name: str) -> bool:
|
||||||
"""检查是否包含指定工具
|
"""Check if the specified tool is included
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name: 工具名称
|
name: Tool name
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 是否包含该工具
|
bool: Whether the tool is included
|
||||||
"""
|
"""
|
||||||
return name in self.tools_dict
|
return name in self.tools_dict
|
||||||
|
|
||||||
def get_available_tools(self) -> List[Dict[str, Any]]:
|
def get_available_tools(self) -> List[Dict[str, Any]]:
|
||||||
"""获取所有可用工具的定义
|
"""Get definitions of all available tools
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List[Dict[str, Any]]: 工具定义列表
|
List[Dict[str, Any]]: Tool definition list
|
||||||
"""
|
"""
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
|
|
@ -97,20 +94,20 @@ class ServerMCPClient:
|
||||||
]
|
]
|
||||||
|
|
||||||
async def call_tool(self, name: str, args: dict) -> Any:
|
async def call_tool(self, name: str, args: dict) -> Any:
|
||||||
"""调用指定工具
|
"""Call the specified tool
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name: 工具名称
|
name: Tool name
|
||||||
args: 工具参数
|
args: Tool parameters
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Any: 工具执行结果
|
Any: Tool execution result
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
RuntimeError: 客户端未初始化时抛出
|
RuntimeError: Thrown when client is not initialized
|
||||||
"""
|
"""
|
||||||
if not self.session:
|
if not self.session:
|
||||||
raise RuntimeError("服务端MCP客户端未初始化")
|
raise RuntimeError("Server-side MCP client not initialized")
|
||||||
|
|
||||||
real_name = self.name_mapping.get(name, name)
|
real_name = self.name_mapping.get(name, name)
|
||||||
loop = self._worker_task.get_loop()
|
loop = self._worker_task.get_loop()
|
||||||
|
|
@ -119,35 +116,36 @@ class ServerMCPClient:
|
||||||
if loop is asyncio.get_running_loop():
|
if loop is asyncio.get_running_loop():
|
||||||
return await coro
|
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)
|
return await asyncio.wrap_future(fut)
|
||||||
|
|
||||||
def is_connected(self) -> bool:
|
def is_connected(self) -> bool:
|
||||||
"""检查MCP客户端是否连接正常
|
"""Check if MCP client is connected normally
|
||||||
|
|
||||||
Returns:
|
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:
|
if self._worker_task is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 检查工作任务是否已经完成或取消
|
# Check if worker task is completed or cancelled
|
||||||
if self._worker_task.done():
|
if self._worker_task.done():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 检查会话是否存在
|
# Check if session exists
|
||||||
if self.session is None:
|
if self.session is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 所有检查都通过,连接正常
|
# All checks passed, connection is normal
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def _worker(self):
|
async def _worker(self):
|
||||||
"""MCP客户端工作协程"""
|
"""MCP client worker coroutine"""
|
||||||
async with AsyncExitStack() as stack:
|
async with AsyncExitStack() as stack:
|
||||||
try:
|
try:
|
||||||
# 建立 StdioClient
|
# Establish StdioClient
|
||||||
if "command" in self.config:
|
if "command" in self.config:
|
||||||
cmd = (
|
cmd = (
|
||||||
shutil.which("npx")
|
shutil.which("npx")
|
||||||
|
|
@ -165,7 +163,7 @@ class ServerMCPClient:
|
||||||
)
|
)
|
||||||
read_stream, write_stream = stdio_r, stdio_w
|
read_stream, write_stream = stdio_r, stdio_w
|
||||||
|
|
||||||
# 建立SSEClient
|
# Establish SSEClient
|
||||||
elif "url" in self.config:
|
elif "url" in self.config:
|
||||||
if "API_ACCESS_TOKEN" in self.config:
|
if "API_ACCESS_TOKEN" in self.config:
|
||||||
headers = {
|
headers = {
|
||||||
|
|
@ -173,13 +171,15 @@ class ServerMCPClient:
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
headers = {}
|
headers = {}
|
||||||
|
|
||||||
sse_r, sse_w = await stack.enter_async_context(
|
sse_r, sse_w = await stack.enter_async_context(
|
||||||
sse_client(self.config["url"], headers=headers)
|
sse_client(self.config["url"], headers=headers)
|
||||||
)
|
)
|
||||||
read_stream, write_stream = sse_r, sse_w
|
read_stream, write_stream = sse_r, sse_w
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise ValueError("MCP客户端配置必须包含'command'或'url'")
|
raise ValueError(
|
||||||
|
"MCP client configuration must contain 'command' or 'url'")
|
||||||
|
|
||||||
self.session = await stack.enter_async_context(
|
self.session = await stack.enter_async_context(
|
||||||
ClientSession(
|
ClientSession(
|
||||||
|
|
@ -188,10 +188,12 @@ class ServerMCPClient:
|
||||||
read_timeout_seconds=timedelta(seconds=15),
|
read_timeout_seconds=timedelta(seconds=15),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
await self.session.initialize()
|
await self.session.initialize()
|
||||||
|
|
||||||
# 获取工具
|
# Get tools
|
||||||
self.tools = (await self.session.list_tools()).tools
|
self.tools = (await self.session.list_tools()).tools
|
||||||
|
|
||||||
for t in self.tools:
|
for t in self.tools:
|
||||||
sanitized = sanitize_tool_name(t.name)
|
sanitized = sanitize_tool_name(t.name)
|
||||||
self.tools_dict[sanitized] = t
|
self.tools_dict[sanitized] = t
|
||||||
|
|
@ -199,10 +201,11 @@ class ServerMCPClient:
|
||||||
|
|
||||||
self._ready_evt.set()
|
self._ready_evt.set()
|
||||||
|
|
||||||
# 挂起等待关闭
|
# Suspend and wait for shutdown
|
||||||
await self._shutdown_evt.wait()
|
await self._shutdown_evt.wait()
|
||||||
|
|
||||||
except Exception as e:
|
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()
|
self._ready_evt.set()
|
||||||
raise
|
raise
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,15 @@
|
||||||
"""服务端MCP工具执行器"""
|
"""Server-side MCP tool executor"""
|
||||||
|
|
||||||
from typing import Dict, Any, Optional
|
from typing import Dict, Any, Optional
|
||||||
|
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
|
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
|
|
||||||
from .mcp_manager import ServerMCPManager
|
from .mcp_manager import ServerMCPManager
|
||||||
|
|
||||||
|
|
||||||
class ServerMCPExecutor(ToolExecutor):
|
class ServerMCPExecutor(ToolExecutor):
|
||||||
"""服务端MCP工具执行器"""
|
"""Server-side MCP tool executor"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -15,7 +17,7 @@ class ServerMCPExecutor(ToolExecutor):
|
||||||
self._initialized = False
|
self._initialized = False
|
||||||
|
|
||||||
async def initialize(self):
|
async def initialize(self):
|
||||||
"""初始化MCP管理器"""
|
"""Initialize MCP manager"""
|
||||||
if not self._initialized:
|
if not self._initialized:
|
||||||
self.mcp_manager = ServerMCPManager(self.conn)
|
self.mcp_manager = ServerMCPManager(self.conn)
|
||||||
await self.mcp_manager.initialize_servers()
|
await self.mcp_manager.initialize_servers()
|
||||||
|
|
@ -24,21 +26,20 @@ class ServerMCPExecutor(ToolExecutor):
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行服务端MCP工具"""
|
"""Execute server-side MCP tool"""
|
||||||
if not self._initialized or not self.mcp_manager:
|
if not self._initialized or not self.mcp_manager:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
action=Action.ERROR,
|
||||||
response="MCP管理器未初始化",
|
response="MCP manager not initialized",
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 移除mcp_前缀(如果有)
|
# Remove mcp_ prefix (if present)
|
||||||
actual_tool_name = tool_name
|
actual_tool_name = tool_name
|
||||||
if tool_name.startswith("mcp_"):
|
if tool_name.startswith("mcp_"):
|
||||||
actual_tool_name = tool_name[4:]
|
actual_tool_name = tool_name[4:]
|
||||||
|
|
||||||
result = await self.mcp_manager.execute_tool(actual_tool_name, arguments)
|
result = await self.mcp_manager.execute_tool(actual_tool_name, arguments)
|
||||||
|
|
||||||
return ActionResponse(action=Action.REQLLM, result=str(result))
|
return ActionResponse(action=Action.REQLLM, result=str(result))
|
||||||
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
|
|
@ -53,7 +54,7 @@ class ServerMCPExecutor(ToolExecutor):
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_tools(self) -> Dict[str, ToolDefinition]:
|
def get_tools(self) -> Dict[str, ToolDefinition]:
|
||||||
"""获取所有服务端MCP工具"""
|
"""Get all server-side MCP tools"""
|
||||||
if not self._initialized or not self.mcp_manager:
|
if not self._initialized or not self.mcp_manager:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
@ -65,6 +66,7 @@ class ServerMCPExecutor(ToolExecutor):
|
||||||
tool_name = func_def.get("name", "")
|
tool_name = func_def.get("name", "")
|
||||||
if tool_name == "":
|
if tool_name == "":
|
||||||
continue
|
continue
|
||||||
|
|
||||||
tools[tool_name] = ToolDefinition(
|
tools[tool_name] = ToolDefinition(
|
||||||
name=tool_name, description=tool, tool_type=ToolType.SERVER_MCP
|
name=tool_name, description=tool, tool_type=ToolType.SERVER_MCP
|
||||||
)
|
)
|
||||||
|
|
@ -72,11 +74,11 @@ class ServerMCPExecutor(ToolExecutor):
|
||||||
return tools
|
return tools
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
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:
|
if not self._initialized or not self.mcp_manager:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 移除mcp_前缀(如果有)
|
# Remove mcp_ prefix (if present)
|
||||||
actual_tool_name = tool_name
|
actual_tool_name = tool_name
|
||||||
if tool_name.startswith("mcp_"):
|
if tool_name.startswith("mcp_"):
|
||||||
actual_tool_name = tool_name[4:]
|
actual_tool_name = tool_name[4:]
|
||||||
|
|
@ -84,6 +86,6 @@ class ServerMCPExecutor(ToolExecutor):
|
||||||
return self.mcp_manager.is_mcp_tool(actual_tool_name)
|
return self.mcp_manager.is_mcp_tool(actual_tool_name)
|
||||||
|
|
||||||
async def cleanup(self):
|
async def cleanup(self):
|
||||||
"""清理MCP连接"""
|
"""Clean up MCP connections"""
|
||||||
if self.mcp_manager:
|
if self.mcp_manager:
|
||||||
await self.mcp_manager.cleanup_all()
|
await self.mcp_manager.cleanup_all()
|
||||||
|
|
@ -1,34 +1,43 @@
|
||||||
"""服务端MCP管理器"""
|
"""Server-side MCP manager"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
|
|
||||||
from config.config_loader import get_project_dir
|
from config.config_loader import get_project_dir
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from .mcp_client import ServerMCPClient
|
from .mcp_client import ServerMCPClient
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ServerMCPManager:
|
class ServerMCPManager:
|
||||||
"""管理多个服务端MCP服务的集中管理器"""
|
"""Centralized manager for managing multiple server-side MCP services"""
|
||||||
|
|
||||||
def __init__(self, conn) -> None:
|
def __init__(self, conn) -> None:
|
||||||
"""初始化MCP管理器"""
|
"""Initialize MCP manager"""
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
|
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
|
||||||
|
|
||||||
if not os.path.exists(self.config_path):
|
if not os.path.exists(self.config_path):
|
||||||
self.config_path = ""
|
self.config_path = ""
|
||||||
logger.bind(tag=TAG).warning(
|
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.clients: Dict[str, ServerMCPClient] = {}
|
||||||
self.tools = []
|
self.tools = []
|
||||||
|
|
||||||
def load_config(self) -> Dict[str, Any]:
|
def load_config(self) -> Dict[str, Any]:
|
||||||
"""加载MCP服务配置"""
|
"""Load MCP service configuration"""
|
||||||
if len(self.config_path) == 0:
|
if len(self.config_path) == 0:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
@ -43,8 +52,9 @@ class ServerMCPManager:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
async def initialize_servers(self) -> None:
|
async def initialize_servers(self) -> None:
|
||||||
"""初始化所有MCP服务"""
|
"""Initialize all MCP services"""
|
||||||
config = self.load_config()
|
config = self.load_config()
|
||||||
|
|
||||||
for name, srv_config in config.items():
|
for name, srv_config in config.items():
|
||||||
if not srv_config.get("command") and not srv_config.get("url"):
|
if not srv_config.get("command") and not srv_config.get("url"):
|
||||||
logger.bind(tag=TAG).warning(
|
logger.bind(tag=TAG).warning(
|
||||||
|
|
@ -53,11 +63,13 @@ class ServerMCPManager:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 初始化服务端MCP客户端
|
# Initialize server-side MCP client
|
||||||
logger.bind(tag=TAG).info(f"初始化服务端MCP客户端: {name}")
|
logger.bind(tag=TAG).info(
|
||||||
|
f"Initializing server-side MCP client: {name}")
|
||||||
client = ServerMCPClient(srv_config)
|
client = ServerMCPClient(srv_config)
|
||||||
await client.initialize()
|
await client.initialize()
|
||||||
self.clients[name] = client
|
self.clients[name] = client
|
||||||
|
|
||||||
client_tools = client.get_available_tools()
|
client_tools = client.get_available_tools()
|
||||||
self.tools.extend(client_tools)
|
self.tools.extend(client_tools)
|
||||||
|
|
||||||
|
|
@ -66,16 +78,16 @@ class ServerMCPManager:
|
||||||
f"Failed to initialize MCP server {name}: {e}"
|
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:
|
if hasattr(self.conn, "func_handler") and self.conn.func_handler:
|
||||||
self.conn.func_handler.current_support_functions()
|
self.conn.func_handler.current_support_functions()
|
||||||
|
|
||||||
def get_all_tools(self) -> List[Dict[str, Any]]:
|
def get_all_tools(self) -> List[Dict[str, Any]]:
|
||||||
"""获取所有服务的工具function定义"""
|
"""Get function definitions for all service tools"""
|
||||||
return self.tools
|
return self.tools
|
||||||
|
|
||||||
def is_mcp_tool(self, tool_name: str) -> bool:
|
def is_mcp_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否是MCP工具"""
|
"""Check if it's an MCP tool"""
|
||||||
for tool in self.tools:
|
for tool in self.tools:
|
||||||
if (
|
if (
|
||||||
tool.get("function") is not None
|
tool.get("function") is not None
|
||||||
|
|
@ -85,15 +97,17 @@ class ServerMCPManager:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
||||||
"""执行工具调用,失败时会尝试重新连接"""
|
"""Execute tool call, will attempt to reconnect on failure"""
|
||||||
logger.bind(tag=TAG).info(f"执行服务端MCP工具 {tool_name},参数: {arguments}")
|
logger.bind(tag=TAG).info(
|
||||||
|
f"Executing server-side MCP tool {tool_name}, parameters: {arguments}")
|
||||||
|
|
||||||
max_retries = 3 # 最大重试次数
|
max_retries = 3 # Maximum retry attempts
|
||||||
retry_interval = 2 # 重试间隔(秒)
|
retry_interval = 2 # Retry interval (seconds)
|
||||||
|
|
||||||
# 找到对应的客户端
|
# Find the corresponding client
|
||||||
client_name = None
|
client_name = None
|
||||||
target_client = None
|
target_client = None
|
||||||
|
|
||||||
for name, client in self.clients.items():
|
for name, client in self.clients.items():
|
||||||
if client.has_tool(tool_name):
|
if client.has_tool(tool_name):
|
||||||
client_name = name
|
client_name = name
|
||||||
|
|
@ -101,38 +115,40 @@ class ServerMCPManager:
|
||||||
break
|
break
|
||||||
|
|
||||||
if not target_client:
|
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):
|
for attempt in range(max_retries):
|
||||||
try:
|
try:
|
||||||
return await target_client.call_tool(tool_name, arguments)
|
return await target_client.call_tool(tool_name, arguments)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 最后一次尝试失败时直接抛出异常
|
# Throw exception directly on last attempt failure
|
||||||
if attempt == max_retries - 1:
|
if attempt == max_retries - 1:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
logger.bind(tag=TAG).warning(
|
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(
|
logger.bind(tag=TAG).info(
|
||||||
f"重试前尝试重新连接 MCP 客户端 {client_name}"
|
f"Attempting to reconnect MCP client {client_name} before retry"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 关闭旧的连接
|
# Close old connection
|
||||||
await target_client.cleanup()
|
await target_client.cleanup()
|
||||||
|
|
||||||
# 重新初始化客户端
|
# Reinitialize client
|
||||||
config = self.load_config()
|
config = self.load_config()
|
||||||
if client_name in config:
|
if client_name in config:
|
||||||
client = ServerMCPClient(config[client_name])
|
client = ServerMCPClient(config[client_name])
|
||||||
await client.initialize()
|
await client.initialize()
|
||||||
self.clients[client_name] = client
|
self.clients[client_name] = client
|
||||||
target_client = client
|
target_client = client
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"成功重新连接 MCP 客户端: {client_name}"
|
f"Successfully reconnected MCP client: {client_name}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
|
|
@ -143,16 +159,19 @@ class ServerMCPManager:
|
||||||
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
|
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 等待一段时间再重试
|
# Wait for a while before retrying
|
||||||
await asyncio.sleep(retry_interval)
|
await asyncio.sleep(retry_interval)
|
||||||
|
|
||||||
async def cleanup_all(self) -> None:
|
async def cleanup_all(self) -> None:
|
||||||
"""关闭所有 MCP客户端"""
|
"""Close all MCP clients"""
|
||||||
for name, client in list(self.clients.items()):
|
for name, client in list(self.clients.items()):
|
||||||
try:
|
try:
|
||||||
if hasattr(client, "cleanup"):
|
if hasattr(client, "cleanup"):
|
||||||
await asyncio.wait_for(client.cleanup(), timeout=20)
|
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:
|
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()
|
self.clients.clear()
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""服务端插件工具模块"""
|
"""Server-side plugin tool module"""
|
||||||
|
|
||||||
from .plugin_executor import ServerPluginExecutor
|
from .plugin_executor import ServerPluginExecutor
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
"""服务端插件工具执行器"""
|
"""Server-side plugin tool executor"""
|
||||||
|
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
|
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
|
|
||||||
from plugins_func.register import all_function_registry, Action, ActionResponse
|
from plugins_func.register import all_function_registry, Action, ActionResponse
|
||||||
|
|
||||||
|
|
||||||
class ServerPluginExecutor(ToolExecutor):
|
class ServerPluginExecutor(ToolExecutor):
|
||||||
"""服务端插件工具执行器"""
|
"""Server-side plugin tool executor"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -15,18 +17,19 @@ class ServerPluginExecutor(ToolExecutor):
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行服务端插件工具"""
|
"""Execute server-side plugin tool"""
|
||||||
func_item = all_function_registry.get(tool_name)
|
func_item = all_function_registry.get(tool_name)
|
||||||
if not func_item:
|
if not func_item:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.NOTFOUND, response=f"插件函数 {tool_name} 不存在"
|
action=Action.NOTFOUND, response=f"Plugin function {tool_name} does not exist"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 根据工具类型决定如何调用
|
# Decide how to call based on tool type
|
||||||
if hasattr(func_item, "type"):
|
if hasattr(func_item, "type"):
|
||||||
func_type = 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)
|
result = func_item.func(conn, **arguments)
|
||||||
elif func_type.code == 2: # WAIT
|
elif func_type.code == 2: # WAIT
|
||||||
result = func_item.func(**arguments)
|
result = func_item.func(**arguments)
|
||||||
|
|
@ -35,7 +38,7 @@ class ServerPluginExecutor(ToolExecutor):
|
||||||
else:
|
else:
|
||||||
result = func_item.func(**arguments)
|
result = func_item.func(**arguments)
|
||||||
else:
|
else:
|
||||||
# 默认不传conn参数
|
# Default: don't pass conn parameter
|
||||||
result = func_item.func(**arguments)
|
result = func_item.func(**arguments)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
@ -47,26 +50,27 @@ class ServerPluginExecutor(ToolExecutor):
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_tools(self) -> Dict[str, ToolDefinition]:
|
def get_tools(self) -> Dict[str, ToolDefinition]:
|
||||||
"""获取所有注册的服务端插件工具"""
|
"""Get all registered server-side plugin tools"""
|
||||||
tools = {}
|
tools = {}
|
||||||
|
|
||||||
# 获取必要的函数
|
# Get necessary functions
|
||||||
necessary_functions = ["handle_exit_intent", "get_lunar"]
|
necessary_functions = ["handle_exit_intent", "get_time", "get_lunar"]
|
||||||
|
|
||||||
# 获取配置中的函数
|
# Get functions from config
|
||||||
config_functions = self.config["Intent"][
|
config_functions = self.config["Intent"][
|
||||||
self.config["selected_module"]["Intent"]
|
self.config["selected_module"]["Intent"]
|
||||||
].get("functions", [])
|
].get("functions", [])
|
||||||
|
|
||||||
# 转换为列表
|
# Convert to list
|
||||||
if not isinstance(config_functions, list):
|
if not isinstance(config_functions, list):
|
||||||
try:
|
try:
|
||||||
config_functions = list(config_functions)
|
config_functions = list(config_functions)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
config_functions = []
|
config_functions = []
|
||||||
|
|
||||||
# 合并所有需要的函数
|
# Merge all required functions
|
||||||
all_required_functions = list(set(necessary_functions + config_functions))
|
all_required_functions = list(
|
||||||
|
set(necessary_functions + config_functions))
|
||||||
|
|
||||||
for func_name in all_required_functions:
|
for func_name in all_required_functions:
|
||||||
func_item = all_function_registry.get(func_name)
|
func_item = all_function_registry.get(func_name)
|
||||||
|
|
@ -80,5 +84,5 @@ class ServerPluginExecutor(ToolExecutor):
|
||||||
return tools
|
return tools
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
def has_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否有指定的服务端插件工具"""
|
"""Check if the specified server-side plugin tool exists"""
|
||||||
return tool_name in all_function_registry
|
return tool_name in all_function_registry
|
||||||
|
|
@ -1,39 +1,49 @@
|
||||||
"""统一工具处理器"""
|
"""Unified tool handler"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from typing import Dict, List, Any, Optional
|
from typing import Dict, List, Any, Optional
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from plugins_func.loadplugins import auto_import_modules
|
from plugins_func.loadplugins import auto_import_modules
|
||||||
|
|
||||||
from .base import ToolType
|
from .base import ToolType
|
||||||
|
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
|
|
||||||
from .unified_tool_manager import ToolManager
|
from .unified_tool_manager import ToolManager
|
||||||
|
|
||||||
from .server_plugins import ServerPluginExecutor
|
from .server_plugins import ServerPluginExecutor
|
||||||
|
|
||||||
from .server_mcp import ServerMCPExecutor
|
from .server_mcp import ServerMCPExecutor
|
||||||
|
|
||||||
from .device_iot import DeviceIoTExecutor
|
from .device_iot import DeviceIoTExecutor
|
||||||
|
|
||||||
from .device_mcp import DeviceMCPExecutor
|
from .device_mcp import DeviceMCPExecutor
|
||||||
|
|
||||||
from .mcp_endpoint import MCPEndpointExecutor
|
from .mcp_endpoint import MCPEndpointExecutor
|
||||||
|
|
||||||
|
|
||||||
class UnifiedToolHandler:
|
class UnifiedToolHandler:
|
||||||
"""统一工具处理器"""
|
"""Unified tool handler"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
self.config = conn.config
|
self.config = conn.config
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
|
|
||||||
# 创建工具管理器
|
# Create tool manager
|
||||||
self.tool_manager = ToolManager(conn)
|
self.tool_manager = ToolManager(conn)
|
||||||
|
|
||||||
# 创建各类执行器
|
# Create various executors
|
||||||
self.server_plugin_executor = ServerPluginExecutor(conn)
|
self.server_plugin_executor = ServerPluginExecutor(conn)
|
||||||
self.server_mcp_executor = ServerMCPExecutor(conn)
|
self.server_mcp_executor = ServerMCPExecutor(conn)
|
||||||
self.device_iot_executor = DeviceIoTExecutor(conn)
|
self.device_iot_executor = DeviceIoTExecutor(conn)
|
||||||
self.device_mcp_executor = DeviceMCPExecutor(conn)
|
self.device_mcp_executor = DeviceMCPExecutor(conn)
|
||||||
self.mcp_endpoint_executor = MCPEndpointExecutor(conn)
|
self.mcp_endpoint_executor = MCPEndpointExecutor(conn)
|
||||||
|
|
||||||
# 注册执行器
|
# Register executors
|
||||||
self.tool_manager.register_executor(
|
self.tool_manager.register_executor(
|
||||||
ToolType.SERVER_PLUGIN, self.server_plugin_executor
|
ToolType.SERVER_PLUGIN, self.server_plugin_executor
|
||||||
)
|
)
|
||||||
|
|
@ -50,39 +60,40 @@ class UnifiedToolHandler:
|
||||||
ToolType.MCP_ENDPOINT, self.mcp_endpoint_executor
|
ToolType.MCP_ENDPOINT, self.mcp_endpoint_executor
|
||||||
)
|
)
|
||||||
|
|
||||||
# 初始化标志
|
# Initialization flag
|
||||||
self.finish_init = False
|
self.finish_init = False
|
||||||
|
|
||||||
async def _initialize(self):
|
async def _initialize(self):
|
||||||
"""异步初始化"""
|
"""Asynchronous initialization"""
|
||||||
try:
|
try:
|
||||||
# 自动导入插件模块
|
# Auto import plugin modules
|
||||||
auto_import_modules("plugins_func.functions")
|
auto_import_modules("plugins_func.functions")
|
||||||
|
|
||||||
# 初始化服务端MCP
|
# Initialize server-side MCP
|
||||||
await self.server_mcp_executor.initialize()
|
await self.server_mcp_executor.initialize()
|
||||||
|
|
||||||
# 初始化MCP接入点
|
# Initialize MCP endpoint
|
||||||
await self._initialize_mcp_endpoint()
|
await self._initialize_mcp_endpoint()
|
||||||
|
|
||||||
# 初始化Home Assistant(如果需要)
|
# Initialize Home Assistant (if needed)
|
||||||
self._initialize_home_assistant()
|
self._initialize_home_assistant()
|
||||||
|
|
||||||
self.finish_init = True
|
self.finish_init = True
|
||||||
self.logger.info("统一工具处理器初始化完成")
|
self.logger.info("Unified tool handler initialization completed")
|
||||||
|
|
||||||
# 输出当前支持的所有工具列表
|
# Output current supported tool list
|
||||||
self.current_support_functions()
|
self.current_support_functions()
|
||||||
|
|
||||||
except Exception as e:
|
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):
|
async def _initialize_mcp_endpoint(self):
|
||||||
"""初始化MCP接入点"""
|
"""Initialize MCP endpoint"""
|
||||||
try:
|
try:
|
||||||
from .mcp_endpoint import connect_mcp_endpoint
|
from .mcp_endpoint import connect_mcp_endpoint
|
||||||
|
|
||||||
# 从配置中获取MCP接入点URL
|
# Get MCP endpoint URL from config
|
||||||
mcp_endpoint_url = self.config.get("mcp_endpoint", "")
|
mcp_endpoint_url = self.config.get("mcp_endpoint", "")
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
|
@ -90,57 +101,58 @@ class UnifiedToolHandler:
|
||||||
and "你的" not in mcp_endpoint_url
|
and "你的" not in mcp_endpoint_url
|
||||||
and mcp_endpoint_url != "null"
|
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_client = await connect_mcp_endpoint(
|
||||||
mcp_endpoint_url, self.conn
|
mcp_endpoint_url, self.conn
|
||||||
)
|
)
|
||||||
|
|
||||||
if mcp_endpoint_client:
|
if mcp_endpoint_client:
|
||||||
# 将MCP接入点客户端保存到连接对象中
|
# Save MCP endpoint client to connection object
|
||||||
self.conn.mcp_endpoint_client = mcp_endpoint_client
|
self.conn.mcp_endpoint_client = mcp_endpoint_client
|
||||||
self.logger.info("MCP接入点初始化成功")
|
self.logger.info("MCP endpoint initialization successful")
|
||||||
else:
|
else:
|
||||||
self.logger.warning("MCP接入点初始化失败")
|
self.logger.warning("MCP endpoint initialization failed")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"初始化MCP接入点失败: {e}")
|
self.logger.error(f"MCP endpoint initialization failed: {e}")
|
||||||
|
|
||||||
def _initialize_home_assistant(self):
|
def _initialize_home_assistant(self):
|
||||||
"""初始化Home Assistant提示词"""
|
"""Initialize Home Assistant prompt"""
|
||||||
try:
|
try:
|
||||||
from plugins_func.functions.hass_init import append_devices_to_prompt
|
from plugins_func.functions.hass_init import append_devices_to_prompt
|
||||||
|
|
||||||
append_devices_to_prompt(self.conn)
|
append_devices_to_prompt(self.conn)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass # 忽略导入错误
|
pass # Ignore import errors
|
||||||
except Exception as e:
|
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]]:
|
def get_functions(self) -> List[Dict[str, Any]]:
|
||||||
"""获取所有工具的函数描述"""
|
"""Get function descriptions for all tools"""
|
||||||
return self.tool_manager.get_function_descriptions()
|
return self.tool_manager.get_function_descriptions()
|
||||||
|
|
||||||
def current_support_functions(self) -> List[str]:
|
def current_support_functions(self) -> List[str]:
|
||||||
"""获取当前支持的函数名称列表"""
|
"""Get list of currently supported function names"""
|
||||||
func_names = self.tool_manager.get_supported_tool_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
|
return func_names
|
||||||
|
|
||||||
def upload_functions_desc(self):
|
def upload_functions_desc(self):
|
||||||
"""刷新函数描述列表"""
|
"""Refresh function description list"""
|
||||||
self.tool_manager.refresh_tools()
|
self.tool_manager.refresh_tools()
|
||||||
self.logger.info("函数描述列表已刷新")
|
self.logger.info("Function description list refreshed")
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
def has_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否有指定工具"""
|
"""Check if the specified tool exists"""
|
||||||
return self.tool_manager.has_tool(tool_name)
|
return self.tool_manager.has_tool(tool_name)
|
||||||
|
|
||||||
async def handle_llm_function_call(
|
async def handle_llm_function_call(
|
||||||
self, conn, function_call_data: Dict[str, Any]
|
self, conn, function_call_data: Dict[str, Any]
|
||||||
) -> Optional[ActionResponse]:
|
) -> Optional[ActionResponse]:
|
||||||
"""处理LLM函数调用"""
|
"""Handle LLM function calls"""
|
||||||
try:
|
try:
|
||||||
# 处理多函数调用
|
# Handle multiple function calls
|
||||||
if "function_calls" in function_call_data:
|
if "function_calls" in function_call_data:
|
||||||
responses = []
|
responses = []
|
||||||
for call in function_call_data["function_calls"]:
|
for call in function_call_data["function_calls"]:
|
||||||
|
|
@ -150,52 +162,53 @@ class UnifiedToolHandler:
|
||||||
responses.append(result)
|
responses.append(result)
|
||||||
return self._combine_responses(responses)
|
return self._combine_responses(responses)
|
||||||
|
|
||||||
# 处理单函数调用
|
# Handle single function call
|
||||||
function_name = function_call_data["name"]
|
function_name = function_call_data["name"]
|
||||||
arguments = function_call_data.get("arguments", {})
|
arguments = function_call_data.get("arguments", {})
|
||||||
|
|
||||||
# 如果arguments是字符串,尝试解析为JSON
|
# If arguments is a string, try to parse as JSON
|
||||||
if isinstance(arguments, str):
|
if isinstance(arguments, str):
|
||||||
try:
|
try:
|
||||||
arguments = json.loads(arguments) if arguments else {}
|
arguments = json.loads(arguments) if arguments else {}
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
self.logger.error(f"无法解析函数参数: {arguments}")
|
self.logger.error(
|
||||||
|
f"Unable to parse function arguments: {arguments}")
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
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)
|
result = await self.tool_manager.execute_tool(function_name, arguments)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
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))
|
return ActionResponse(action=Action.ERROR, response=str(e))
|
||||||
|
|
||||||
def _combine_responses(self, responses: List[ActionResponse]) -> ActionResponse:
|
def _combine_responses(self, responses: List[ActionResponse]) -> ActionResponse:
|
||||||
"""合并多个函数调用的响应"""
|
"""Combine responses from multiple function calls"""
|
||||||
if not responses:
|
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:
|
for response in responses:
|
||||||
if response.action == Action.ERROR:
|
if response.action == Action.ERROR:
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# 合并所有成功的响应
|
# Combine all successful responses
|
||||||
contents = []
|
contents = []
|
||||||
responses_text = []
|
responses_text = []
|
||||||
|
|
||||||
for response in responses:
|
for response in responses:
|
||||||
if response.content:
|
if response.content:
|
||||||
contents.append(response.content)
|
contents.append(response.content)
|
||||||
if response.response:
|
if response.response:
|
||||||
responses_text.append(response.response)
|
responses_text.append(response.response)
|
||||||
|
|
||||||
# 确定最终的动作类型
|
# Determine final action type
|
||||||
final_action = Action.RESPONSE
|
final_action = Action.RESPONSE
|
||||||
for response in responses:
|
for response in responses:
|
||||||
if response.action == Action.REQLLM:
|
if response.action == Action.REQLLM:
|
||||||
|
|
@ -209,27 +222,28 @@ class UnifiedToolHandler:
|
||||||
)
|
)
|
||||||
|
|
||||||
async def register_iot_tools(self, descriptors: List[Dict[str, Any]]):
|
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.device_iot_executor.register_iot_tools(descriptors)
|
||||||
self.tool_manager.refresh_tools()
|
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]:
|
def get_tool_statistics(self) -> Dict[str, int]:
|
||||||
"""获取工具统计信息"""
|
"""Get tool statistics"""
|
||||||
return self.tool_manager.get_tool_statistics()
|
return self.tool_manager.get_tool_statistics()
|
||||||
|
|
||||||
async def cleanup(self):
|
async def cleanup(self):
|
||||||
"""清理资源"""
|
"""Clean up resources"""
|
||||||
try:
|
try:
|
||||||
await self.server_mcp_executor.cleanup()
|
await self.server_mcp_executor.cleanup()
|
||||||
|
|
||||||
# 清理MCP接入点连接
|
# Clean up MCP endpoint connection
|
||||||
if (
|
if (
|
||||||
hasattr(self.conn, "mcp_endpoint_client")
|
hasattr(self.conn, "mcp_endpoint_client")
|
||||||
and self.conn.mcp_endpoint_client
|
and self.conn.mcp_endpoint_client
|
||||||
):
|
):
|
||||||
await self.conn.mcp_endpoint_client.close()
|
await self.conn.mcp_endpoint_client.close()
|
||||||
|
|
||||||
self.logger.info("工具处理器清理完成")
|
self.logger.info("Tool handler cleanup completed")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"工具处理器清理失败: {e}")
|
self.logger.error(f"Tool handler cleanup failed: {e}")
|
||||||
|
|
@ -1,13 +1,16 @@
|
||||||
"""统一工具管理器"""
|
"""Unified tool manager"""
|
||||||
|
|
||||||
from typing import Dict, List, Optional, Any
|
from typing import Dict, List, Optional, Any
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
|
|
||||||
from .base import ToolType, ToolDefinition, ToolExecutor
|
from .base import ToolType, ToolDefinition, ToolExecutor
|
||||||
|
|
||||||
|
|
||||||
class ToolManager:
|
class ToolManager:
|
||||||
"""统一工具管理器,管理所有类型的工具"""
|
"""Unified tool manager, manages all types of tools"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
@ -17,18 +20,18 @@ class ToolManager:
|
||||||
self._cached_function_descriptions: Optional[List[Dict[str, Any]]] = None
|
self._cached_function_descriptions: Optional[List[Dict[str, Any]]] = None
|
||||||
|
|
||||||
def register_executor(self, tool_type: ToolType, executor: ToolExecutor):
|
def register_executor(self, tool_type: ToolType, executor: ToolExecutor):
|
||||||
"""注册工具执行器"""
|
"""Register tool executor"""
|
||||||
self.executors[tool_type] = executor
|
self.executors[tool_type] = executor
|
||||||
self._invalidate_cache()
|
self._invalidate_cache()
|
||||||
self.logger.info(f"注册工具执行器: {tool_type.value}")
|
self.logger.info(f"Registered tool executor: {tool_type.value}")
|
||||||
|
|
||||||
def _invalidate_cache(self):
|
def _invalidate_cache(self):
|
||||||
"""使缓存失效"""
|
"""Invalidate cache"""
|
||||||
self._cached_tools = None
|
self._cached_tools = None
|
||||||
self._cached_function_descriptions = None
|
self._cached_function_descriptions = None
|
||||||
|
|
||||||
def get_all_tools(self) -> Dict[str, ToolDefinition]:
|
def get_all_tools(self) -> Dict[str, ToolDefinition]:
|
||||||
"""获取所有工具定义"""
|
"""Get all tool definitions"""
|
||||||
if self._cached_tools is not None:
|
if self._cached_tools is not None:
|
||||||
return self._cached_tools
|
return self._cached_tools
|
||||||
|
|
||||||
|
|
@ -38,21 +41,23 @@ class ToolManager:
|
||||||
tools = executor.get_tools()
|
tools = executor.get_tools()
|
||||||
for name, definition in tools.items():
|
for name, definition in tools.items():
|
||||||
if name in all_tools:
|
if name in all_tools:
|
||||||
self.logger.warning(f"工具名称冲突: {name}")
|
self.logger.warning(f"Tool name conflict: {name}")
|
||||||
all_tools[name] = definition
|
all_tools[name] = definition
|
||||||
except Exception as e:
|
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
|
self._cached_tools = all_tools
|
||||||
return all_tools
|
return all_tools
|
||||||
|
|
||||||
def get_function_descriptions(self) -> List[Dict[str, Any]]:
|
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:
|
if self._cached_function_descriptions is not None:
|
||||||
return self._cached_function_descriptions
|
return self._cached_function_descriptions
|
||||||
|
|
||||||
descriptions = []
|
descriptions = []
|
||||||
tools = self.get_all_tools()
|
tools = self.get_all_tools()
|
||||||
|
|
||||||
for tool_definition in tools.values():
|
for tool_definition in tools.values():
|
||||||
descriptions.append(tool_definition.description)
|
descriptions.append(tool_definition.description)
|
||||||
|
|
||||||
|
|
@ -60,12 +65,12 @@ class ToolManager:
|
||||||
return descriptions
|
return descriptions
|
||||||
|
|
||||||
def has_tool(self, tool_name: str) -> bool:
|
def has_tool(self, tool_name: str) -> bool:
|
||||||
"""检查是否存在指定工具"""
|
"""Check if the specified tool exists"""
|
||||||
tools = self.get_all_tools()
|
tools = self.get_all_tools()
|
||||||
return tool_name in tools
|
return tool_name in tools
|
||||||
|
|
||||||
def get_tool_type(self, tool_name: str) -> Optional[ToolType]:
|
def get_tool_type(self, tool_name: str) -> Optional[ToolType]:
|
||||||
"""获取工具类型"""
|
"""Get tool type"""
|
||||||
tools = self.get_all_tools()
|
tools = self.get_all_tools()
|
||||||
tool_def = tools.get(tool_name)
|
tool_def = tools.get(tool_name)
|
||||||
return tool_def.tool_type if tool_def else None
|
return tool_def.tool_type if tool_def else None
|
||||||
|
|
@ -73,52 +78,54 @@ class ToolManager:
|
||||||
async def execute_tool(
|
async def execute_tool(
|
||||||
self, tool_name: str, arguments: Dict[str, Any]
|
self, tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行工具调用"""
|
"""Execute tool call"""
|
||||||
try:
|
try:
|
||||||
# 查找工具类型
|
# Find tool type
|
||||||
tool_type = self.get_tool_type(tool_name)
|
tool_type = self.get_tool_type(tool_name)
|
||||||
if not tool_type:
|
if not tool_type:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.NOTFOUND,
|
action=Action.NOTFOUND,
|
||||||
response=f"工具 {tool_name} 不存在",
|
response=f"Tool {tool_name} does not exist",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 获取对应的执行器
|
# Get corresponding executor
|
||||||
executor = self.executors.get(tool_type)
|
executor = self.executors.get(tool_type)
|
||||||
if not executor:
|
if not executor:
|
||||||
return ActionResponse(
|
return ActionResponse(
|
||||||
action=Action.ERROR,
|
action=Action.ERROR,
|
||||||
response=f"工具类型 {tool_type.value} 的执行器未注册",
|
response=f"Executor for tool type {tool_type.value} is not registered",
|
||||||
)
|
)
|
||||||
|
|
||||||
# 执行工具
|
# Execute tool
|
||||||
self.logger.info(f"执行工具: {tool_name},参数: {arguments}")
|
self.logger.info(
|
||||||
|
f"Executing tool: {tool_name}, arguments: {arguments}")
|
||||||
result = await executor.execute(self.conn, tool_name, 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
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
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))
|
return ActionResponse(action=Action.ERROR, response=str(e))
|
||||||
|
|
||||||
def get_supported_tool_names(self) -> List[str]:
|
def get_supported_tool_names(self) -> List[str]:
|
||||||
"""获取所有支持的工具名称"""
|
"""Get all supported tool names"""
|
||||||
tools = self.get_all_tools()
|
tools = self.get_all_tools()
|
||||||
return list(tools.keys())
|
return list(tools.keys())
|
||||||
|
|
||||||
def refresh_tools(self):
|
def refresh_tools(self):
|
||||||
"""刷新工具缓存"""
|
"""Refresh tool cache"""
|
||||||
self._invalidate_cache()
|
self._invalidate_cache()
|
||||||
self.logger.info("工具缓存已刷新")
|
self.logger.info("Tool cache refreshed")
|
||||||
|
|
||||||
def get_tool_statistics(self) -> Dict[str, int]:
|
def get_tool_statistics(self) -> Dict[str, int]:
|
||||||
"""获取工具统计信息"""
|
"""Get tool statistics"""
|
||||||
stats = {}
|
stats = {}
|
||||||
for tool_type, executor in self.executors.items():
|
for tool_type, executor in self.executors.items():
|
||||||
try:
|
try:
|
||||||
tools = executor.get_tools()
|
tools = executor.get_tools()
|
||||||
stats[tool_type.value] = len(tools)
|
stats[tool_type.value] = len(tools)
|
||||||
except Exception as e:
|
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
|
stats[tool_type.value] = 0
|
||||||
return stats
|
return stats
|
||||||
|
|
|
||||||
|
|
@ -1,205 +1,354 @@
|
||||||
import uuid
|
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__
|
import json
|
||||||
logger = setup_logging()
|
|
||||||
|
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:
|
class AccessToken:
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _encode_text(text):
|
def _encode_text(text):
|
||||||
|
|
||||||
encoded_text = parse.quote_plus(text)
|
encoded_text = parse.quote_plus(text)
|
||||||
|
|
||||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _encode_dict(dic):
|
def _encode_dict(dic):
|
||||||
|
|
||||||
keys = dic.keys()
|
keys = dic.keys()
|
||||||
|
|
||||||
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
|
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
|
||||||
|
|
||||||
encoded_text = parse.urlencode(dic_sorted)
|
encoded_text = parse.urlencode(dic_sorted)
|
||||||
|
|
||||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_token(access_key_id, access_key_secret):
|
def create_token(access_key_id, access_key_secret):
|
||||||
|
|
||||||
parameters = {
|
parameters = {
|
||||||
|
|
||||||
"AccessKeyId": access_key_id,
|
"AccessKeyId": access_key_id,
|
||||||
|
|
||||||
"Action": "CreateToken",
|
"Action": "CreateToken",
|
||||||
|
|
||||||
"Format": "JSON",
|
"Format": "JSON",
|
||||||
|
|
||||||
"RegionId": "cn-shanghai",
|
"RegionId": "cn-shanghai",
|
||||||
|
|
||||||
"SignatureMethod": "HMAC-SHA1",
|
"SignatureMethod": "HMAC-SHA1",
|
||||||
|
|
||||||
"SignatureNonce": str(uuid.uuid1()),
|
"SignatureNonce": str(uuid.uuid1()),
|
||||||
|
|
||||||
"SignatureVersion": "1.0",
|
"SignatureVersion": "1.0",
|
||||||
|
|
||||||
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
|
|
||||||
"Version": "2019-02-28",
|
"Version": "2019-02-28",
|
||||||
|
|
||||||
}
|
}
|
||||||
# 构造规范化的请求字符串
|
|
||||||
|
# Construct normalized request string
|
||||||
|
|
||||||
query_string = AccessToken._encode_dict(parameters)
|
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 = (
|
string_to_sign = (
|
||||||
|
|
||||||
"GET"
|
"GET"
|
||||||
|
|
||||||
+ "&"
|
+ "&"
|
||||||
|
|
||||||
+ AccessToken._encode_text("/")
|
+ AccessToken._encode_text("/")
|
||||||
|
|
||||||
+ "&"
|
+ "&"
|
||||||
|
|
||||||
+ AccessToken._encode_text(query_string)
|
+ 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(
|
secreted_string = hmac.new(
|
||||||
|
|
||||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
bytes(access_key_secret + "&", encoding="utf-8"),
|
||||||
|
|
||||||
bytes(string_to_sign, encoding="utf-8"),
|
bytes(string_to_sign, encoding="utf-8"),
|
||||||
|
|
||||||
hashlib.sha1,
|
hashlib.sha1,
|
||||||
|
|
||||||
).digest()
|
).digest()
|
||||||
|
|
||||||
signature = base64.b64encode(secreted_string)
|
signature = base64.b64encode(secreted_string)
|
||||||
# print('签名: %s' % signature)
|
|
||||||
# 进行URL编码
|
# print('Signature: %s' % signature)
|
||||||
|
|
||||||
|
# URL encode
|
||||||
|
|
||||||
signature = AccessToken._encode_text(signature)
|
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" % (
|
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
|
||||||
|
|
||||||
signature,
|
signature,
|
||||||
|
|
||||||
query_string,
|
query_string,
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# print('url: %s' % full_url)
|
# print('url: %s' % full_url)
|
||||||
# 提交HTTP GET请求
|
|
||||||
|
# Submit HTTP GET request
|
||||||
|
|
||||||
response = requests.get(full_url)
|
response = requests.get(full_url)
|
||||||
|
|
||||||
if response.ok:
|
if response.ok:
|
||||||
|
|
||||||
root_obj = response.json()
|
root_obj = response.json()
|
||||||
|
|
||||||
key = "Token"
|
key = "Token"
|
||||||
|
|
||||||
if key in root_obj:
|
if key in root_obj:
|
||||||
|
|
||||||
token = root_obj[key]["Id"]
|
token = root_obj[key]["Id"]
|
||||||
|
|
||||||
expire_time = root_obj[key]["ExpireTime"]
|
expire_time = root_obj[key]["ExpireTime"]
|
||||||
|
|
||||||
return token, expire_time
|
return token, expire_time
|
||||||
|
|
||||||
# print(response.text)
|
# print(response.text)
|
||||||
|
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(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_id = config.get("access_key_id")
|
||||||
|
|
||||||
self.access_key_secret = config.get("access_key_secret")
|
self.access_key_secret = config.get("access_key_secret")
|
||||||
|
|
||||||
self.appkey = config.get("appkey")
|
self.appkey = config.get("appkey")
|
||||||
|
|
||||||
self.format = config.get("format", "wav")
|
self.format = config.get("format", "wav")
|
||||||
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
self.audio_file_type = config.get("format", "wav")
|
||||||
|
|
||||||
sample_rate = config.get("sample_rate", "16000")
|
sample_rate = config.get("sample_rate", "16000")
|
||||||
|
|
||||||
self.sample_rate = int(sample_rate) if sample_rate else 16000
|
self.sample_rate = int(sample_rate) if sample_rate else 16000
|
||||||
|
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
|
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
self.voice = config.get("voice", "xiaoyun")
|
self.voice = config.get("voice", "xiaoyun")
|
||||||
|
|
||||||
volume = config.get("volume", "50")
|
volume = config.get("volume", "50")
|
||||||
|
|
||||||
self.volume = int(volume) if volume else 50
|
self.volume = int(volume) if volume else 50
|
||||||
|
|
||||||
speech_rate = config.get("speech_rate", "0")
|
speech_rate = config.get("speech_rate", "0")
|
||||||
|
|
||||||
self.speech_rate = int(speech_rate) if speech_rate else 0
|
self.speech_rate = int(speech_rate) if speech_rate else 0
|
||||||
|
|
||||||
pitch_rate = config.get("pitch_rate", "0")
|
pitch_rate = config.get("pitch_rate", "0")
|
||||||
|
|
||||||
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
|
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
|
||||||
|
|
||||||
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
||||||
|
|
||||||
self.api_url = f"https://{self.host}/stream/v1/tts"
|
self.api_url = f"https://{self.host}/stream/v1/tts"
|
||||||
|
|
||||||
self.header = {"Content-Type": "application/json"}
|
self.header = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
if self.access_key_id and self.access_key_secret:
|
if self.access_key_id and self.access_key_secret:
|
||||||
# 使用密钥对生成临时token
|
|
||||||
|
# Use key pair to generate temporary token
|
||||||
|
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# 直接使用预生成的长期token
|
|
||||||
|
# Directly use pre-generated long-term token
|
||||||
|
|
||||||
self.token = config.get("token")
|
self.token = config.get("token")
|
||||||
|
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
def _refresh_token(self):
|
def _refresh_token(self):
|
||||||
"""刷新Token并记录过期时间"""
|
"""Refresh Token and record expiration time"""
|
||||||
|
|
||||||
if self.access_key_id and self.access_key_secret:
|
if self.access_key_id and self.access_key_secret:
|
||||||
|
|
||||||
self.token, expire_time_str = AccessToken.create_token(
|
self.token, expire_time_str = AccessToken.create_token(
|
||||||
|
|
||||||
self.access_key_id, self.access_key_secret
|
self.access_key_id, self.access_key_secret
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if not expire_time_str:
|
if not expire_time_str:
|
||||||
raise ValueError("无法获取有效的Token过期时间")
|
|
||||||
|
raise ValueError("Unable to get valid Token expiration time")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 统一转换为字符串处理
|
|
||||||
|
# Uniformly convert to string processing
|
||||||
|
|
||||||
expire_str = str(expire_time_str).strip()
|
expire_str = str(expire_time_str).strip()
|
||||||
|
|
||||||
if expire_str.isdigit():
|
if expire_str.isdigit():
|
||||||
|
|
||||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
expire_time = datetime.fromtimestamp(int(expire_str))
|
||||||
|
|
||||||
else:
|
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
|
self.expire_time = expire_time.timestamp() - 60
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
|
|
||||||
|
raise ValueError(
|
||||||
|
f"Invalid expiration time format: {expire_str}") from e
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
if not self.token:
|
if not self.token:
|
||||||
raise ValueError("无法获取有效的访问Token")
|
|
||||||
|
raise ValueError("Unable to get valid access Token")
|
||||||
|
|
||||||
def _is_token_expired(self):
|
def _is_token_expired(self):
|
||||||
"""检查Token是否过期"""
|
"""Check if Token has expired"""
|
||||||
|
|
||||||
if not self.expire_time:
|
if not self.expire_time:
|
||||||
return False # 长期Token不过期
|
|
||||||
# 新增调试日志
|
return False # Long-term Token does not expire
|
||||||
|
|
||||||
|
# Add debug log
|
||||||
|
|
||||||
# current_time = time.time()
|
# current_time = time.time()
|
||||||
|
|
||||||
# remaining = self.expire_time - current_time
|
# remaining = self.expire_time - current_time
|
||||||
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
|
|
||||||
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
|
# print(f"Token expiration check: current time {datetime.fromtimestamp(current_time)} | "
|
||||||
# f"剩余 {remaining:.2f}秒")
|
|
||||||
|
# f"expiration time {datetime.fromtimestamp(self.expire_time)} | "
|
||||||
|
|
||||||
|
# f"remaining {remaining:.2f}seconds")
|
||||||
|
|
||||||
return time.time() > self.expire_time
|
return time.time() > self.expire_time
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
logger.warning("Token已过期,正在自动刷新...")
|
|
||||||
|
logger.warning("Token has expired, automatically refreshing...")
|
||||||
|
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
|
|
||||||
request_json = {
|
request_json = {
|
||||||
|
|
||||||
"appkey": self.appkey,
|
"appkey": self.appkey,
|
||||||
|
|
||||||
"token": self.token,
|
"token": self.token,
|
||||||
|
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
||||||
"format": self.format,
|
"format": self.format,
|
||||||
|
|
||||||
"sample_rate": self.sample_rate,
|
"sample_rate": self.sample_rate,
|
||||||
|
|
||||||
"voice": self.voice,
|
"voice": self.voice,
|
||||||
|
|
||||||
"volume": self.volume,
|
"volume": self.volume,
|
||||||
|
|
||||||
"speech_rate": self.speech_rate,
|
"speech_rate": self.speech_rate,
|
||||||
|
|
||||||
"pitch_rate": self.pitch_rate,
|
"pitch_rate": self.pitch_rate,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# print(self.api_url, json.dumps(request_json, ensure_ascii=False))
|
# print(self.api_url, json.dumps(request_json, ensure_ascii=False))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
|
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
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()
|
self._refresh_token()
|
||||||
|
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
|
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
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 resp.headers["Content-Type"].startswith("audio/"):
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as f:
|
with open(output_file, "wb") as f:
|
||||||
|
|
||||||
f.write(resp.content)
|
f.write(resp.content)
|
||||||
|
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return resp.content
|
return resp.content
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
raise Exception(
|
raise Exception(
|
||||||
|
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
@ -41,7 +41,7 @@ class AccessToken:
|
||||||
"AccessKeyId": access_key_id,
|
"AccessKeyId": access_key_id,
|
||||||
"Action": "CreateToken",
|
"Action": "CreateToken",
|
||||||
"Format": "JSON",
|
"Format": "JSON",
|
||||||
"RegionId": "cn-shanghai", # 使用上海地域进行Token获取
|
"RegionId": "cn-shanghai", # Use Shanghai region for Token acquisition
|
||||||
"SignatureMethod": "HMAC-SHA1",
|
"SignatureMethod": "HMAC-SHA1",
|
||||||
"SignatureNonce": str(uuid.uuid1()),
|
"SignatureNonce": str(uuid.uuid1()),
|
||||||
"SignatureVersion": "1.0",
|
"SignatureVersion": "1.0",
|
||||||
|
|
@ -88,27 +88,28 @@ class TTSProvider(TTSProviderBase):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
# 设置为流式接口类型
|
# Set to streaming interface type
|
||||||
self.interface_type = InterfaceType.DUAL_STREAM
|
self.interface_type = InterfaceType.DUAL_STREAM
|
||||||
|
|
||||||
# 基础配置
|
# Basic configuration
|
||||||
self.access_key_id = config.get("access_key_id")
|
self.access_key_id = config.get("access_key_id")
|
||||||
self.access_key_secret = config.get("access_key_secret")
|
self.access_key_secret = config.get("access_key_secret")
|
||||||
self.appkey = config.get("appkey")
|
self.appkey = config.get("appkey")
|
||||||
self.format = config.get("format", "pcm")
|
self.format = config.get("format", "pcm")
|
||||||
self.audio_file_type = config.get("format", "pcm")
|
self.audio_file_type = config.get("format", "pcm")
|
||||||
|
|
||||||
# 采样率配置
|
# Sample rate configuration
|
||||||
sample_rate = config.get("sample_rate", "16000")
|
sample_rate = config.get("sample_rate", "16000")
|
||||||
self.sample_rate = int(sample_rate) if sample_rate else 16000
|
self.sample_rate = int(sample_rate) if sample_rate else 16000
|
||||||
|
|
||||||
# 音色配置 - CosyVoice大模型音色
|
# Voice configuration - CosyVoice large model voice
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
else:
|
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")
|
volume = config.get("volume", "50")
|
||||||
self.volume = int(volume) if volume else 50
|
self.volume = int(volume) if volume else 50
|
||||||
|
|
||||||
|
|
@ -118,27 +119,27 @@ class TTSProvider(TTSProviderBase):
|
||||||
pitch_rate = config.get("pitch_rate", "0")
|
pitch_rate = config.get("pitch_rate", "0")
|
||||||
self.pitch_rate = int(pitch_rate) if pitch_rate else 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")
|
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:
|
if "-internal." in self.host:
|
||||||
self.ws_url = f"ws://{self.host}/ws/v1"
|
self.ws_url = f"ws://{self.host}/ws/v1"
|
||||||
else:
|
else:
|
||||||
# 默认使用wss协议
|
# Default to wss protocol
|
||||||
self.ws_url = f"wss://{self.host}/ws/v1"
|
self.ws_url = f"wss://{self.host}/ws/v1"
|
||||||
self.ws = None
|
self.ws = None
|
||||||
self._monitor_task = None
|
self._monitor_task = None
|
||||||
self.last_active_time = None
|
self.last_active_time = None
|
||||||
|
|
||||||
# 专属tts设置
|
# Dedicated TTS settings
|
||||||
self.message_id = ""
|
self.message_id = ""
|
||||||
|
|
||||||
# 创建Opus编码器
|
# Create Opus encoder
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
||||||
sample_rate=16000, channels=1, frame_size_ms=60
|
sample_rate=16000, channels=1, frame_size_ms=60
|
||||||
)
|
)
|
||||||
|
|
||||||
# Token管理
|
# Token management
|
||||||
if self.access_key_id and self.access_key_secret:
|
if self.access_key_id and self.access_key_secret:
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
else:
|
else:
|
||||||
|
|
@ -146,13 +147,13 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
def _refresh_token(self):
|
def _refresh_token(self):
|
||||||
"""刷新Token并记录过期时间"""
|
"""Refresh Token and record expiration time"""
|
||||||
if self.access_key_id and self.access_key_secret:
|
if self.access_key_id and self.access_key_secret:
|
||||||
self.token, expire_time_str = AccessToken.create_token(
|
self.token, expire_time_str = AccessToken.create_token(
|
||||||
self.access_key_id, self.access_key_secret
|
self.access_key_id, self.access_key_secret
|
||||||
)
|
)
|
||||||
if not expire_time_str:
|
if not expire_time_str:
|
||||||
raise ValueError("无法获取有效的Token过期时间")
|
raise ValueError("Unable to get valid Token expiration time")
|
||||||
|
|
||||||
expire_str = str(expire_time_str).strip()
|
expire_str = str(expire_time_str).strip()
|
||||||
|
|
||||||
|
|
@ -160,34 +161,38 @@ class TTSProvider(TTSProviderBase):
|
||||||
if expire_str.isdigit():
|
if expire_str.isdigit():
|
||||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
expire_time = datetime.fromtimestamp(int(expire_str))
|
||||||
else:
|
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
|
self.expire_time = expire_time.timestamp() - 60
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
|
raise ValueError(
|
||||||
|
f"Invalid expiration time format: {expire_str}") from e
|
||||||
else:
|
else:
|
||||||
self.expire_time = None
|
self.expire_time = None
|
||||||
|
|
||||||
if not self.token:
|
if not self.token:
|
||||||
raise ValueError("无法获取有效的访问Token")
|
raise ValueError("Unable to get valid access Token")
|
||||||
|
|
||||||
def _is_token_expired(self):
|
def _is_token_expired(self):
|
||||||
"""检查Token是否过期"""
|
"""Check if Token is expired"""
|
||||||
if not self.expire_time:
|
if not self.expire_time:
|
||||||
return False
|
return False
|
||||||
return time.time() > self.expire_time
|
return time.time() > self.expire_time
|
||||||
|
|
||||||
async def _ensure_connection(self):
|
async def _ensure_connection(self):
|
||||||
"""确保WebSocket连接可用"""
|
"""Ensure WebSocket connection is available"""
|
||||||
try:
|
try:
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
|
logger.bind(tag=TAG).warning(
|
||||||
|
"Token has expired, automatically refreshing...")
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
current_time = time.time()
|
current_time = time.time()
|
||||||
if self.ws and current_time - self.last_active_time < 10:
|
if self.ws and current_time - self.last_active_time < 10:
|
||||||
# 10秒内才可以复用链接进行连续对话
|
# Can only reuse connection for continuous conversation within 10 seconds
|
||||||
logger.bind(tag=TAG).info(f"使用已有链接...")
|
logger.bind(tag=TAG).info(f"Using existing connection...")
|
||||||
return self.ws
|
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 = await websockets.connect(
|
||||||
self.ws_url,
|
self.ws_url,
|
||||||
|
|
@ -196,106 +201,118 @@ class TTSProvider(TTSProviderBase):
|
||||||
ping_timeout=10,
|
ping_timeout=10,
|
||||||
close_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()
|
self.last_active_time = time.time()
|
||||||
return self.ws
|
return self.ws
|
||||||
except Exception as e:
|
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.ws = None
|
||||||
self.last_active_time = None
|
self.last_active_time = None
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
def tts_text_priority_thread(self):
|
||||||
"""流式文本处理线程"""
|
"""Streaming text processing thread"""
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
message = self.tts_text_queue.get(timeout=1)
|
message = self.tts_text_queue.get(timeout=1)
|
||||||
logger.bind(tag=TAG).debug(
|
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:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
self.conn.client_abort = False
|
self.conn.client_abort = False
|
||||||
|
|
||||||
if self.conn.client_abort:
|
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
|
continue
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
# 初始化参数
|
# Initialize parameters
|
||||||
try:
|
try:
|
||||||
if not getattr(self.conn, "sentence_id", None):
|
if not getattr(self.conn, "sentence_id", None):
|
||||||
self.conn.sentence_id = uuid.uuid4().hex
|
self.conn.sentence_id = uuid.uuid4().hex
|
||||||
logger.bind(tag=TAG).info(
|
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)
|
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(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.start_session(self.conn.sentence_id),
|
self.start_session(self.conn.sentence_id),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
self.before_stop_play_files.clear()
|
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:
|
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
|
continue
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
if message.content_detail:
|
if message.content_detail:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"开始发送TTS文本: {message.content_detail}"
|
f"Starting to send TTS text: {message.content_detail}"
|
||||||
)
|
)
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
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,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
logger.bind(tag=TAG).debug("TTS文本发送成功")
|
logger.bind(tag=TAG).debug(
|
||||||
|
"TTS text sent successfully")
|
||||||
except Exception as e:
|
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
|
continue
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
elif ContentType.FILE == message.content_type:
|
||||||
logger.bind(tag=TAG).info(
|
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):
|
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)
|
file_audio = self._process_audio_file(
|
||||||
|
message.content_file)
|
||||||
self.before_stop_play_files.append(
|
self.before_stop_play_files.append(
|
||||||
(file_audio, message.content_detail)
|
(file_audio, message.content_detail)
|
||||||
)
|
)
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).info("开始结束TTS会话...")
|
logger.bind(tag=TAG).info(
|
||||||
|
"Starting to end TTS session...")
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.finish_session(self.conn.sentence_id),
|
self.finish_session(self.conn.sentence_id),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
except Exception as e:
|
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
|
continue
|
||||||
|
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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, _):
|
async def text_to_speak(self, text, _):
|
||||||
try:
|
try:
|
||||||
if self.ws is None:
|
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
|
return
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||||
run_request = {
|
run_request = {
|
||||||
|
|
@ -313,7 +330,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
return
|
return
|
||||||
|
|
||||||
except Exception as e:
|
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:
|
if self.ws:
|
||||||
try:
|
try:
|
||||||
await self.ws.close()
|
await self.ws.close()
|
||||||
|
|
@ -323,24 +340,25 @@ class TTSProvider(TTSProviderBase):
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def start_session(self, session_id):
|
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:
|
try:
|
||||||
# 会话开始时检测上个会话的监听状态
|
# Check previous session monitoring status when session starts
|
||||||
if (
|
if (
|
||||||
self._monitor_task is not None
|
self._monitor_task is not None
|
||||||
and isinstance(self._monitor_task, Task)
|
and isinstance(self._monitor_task, Task)
|
||||||
and not self._monitor_task.done()
|
and not self._monitor_task.done()
|
||||||
):
|
):
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
"检测到未完成的上个会话,关闭监听任务和连接..."
|
"Detected incomplete previous session, closing monitoring task and connection..."
|
||||||
)
|
)
|
||||||
await self.close()
|
await self.close()
|
||||||
|
|
||||||
# 建立新连接
|
# Establish new connection
|
||||||
await self._ensure_connection()
|
await self._ensure_connection()
|
||||||
|
|
||||||
# 启动监听任务
|
# Start monitoring task
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
self._monitor_task = asyncio.create_task(
|
||||||
|
self._start_monitor_tts_response())
|
||||||
|
|
||||||
start_request = {
|
start_request = {
|
||||||
"header": {
|
"header": {
|
||||||
|
|
@ -362,15 +380,15 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
await self.ws.send(json.dumps(start_request))
|
await self.ws.send(json.dumps(start_request))
|
||||||
self.last_active_time = time.time()
|
self.last_active_time = time.time()
|
||||||
logger.bind(tag=TAG).info("会话启动请求已发送")
|
logger.bind(tag=TAG).info("Session start request sent")
|
||||||
except Exception as e:
|
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()
|
await self.close()
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def finish_session(self, session_id):
|
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:
|
try:
|
||||||
if self.ws:
|
if self.ws:
|
||||||
stop_request = {
|
stop_request = {
|
||||||
|
|
@ -383,25 +401,25 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await self.ws.send(json.dumps(stop_request))
|
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()
|
self.last_active_time = time.time()
|
||||||
if self._monitor_task:
|
if self._monitor_task:
|
||||||
try:
|
try:
|
||||||
await self._monitor_task
|
await self._monitor_task
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"等待监听任务完成时发生错误: {str(e)}"
|
f"Error occurred while waiting for monitoring task to complete: {str(e)}"
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
self._monitor_task = None
|
self._monitor_task = None
|
||||||
except Exception as e:
|
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()
|
await self.close()
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""资源清理"""
|
"""Resource cleanup"""
|
||||||
if self._monitor_task:
|
if self._monitor_task:
|
||||||
try:
|
try:
|
||||||
self._monitor_task.cancel()
|
self._monitor_task.cancel()
|
||||||
|
|
@ -409,7 +427,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
pass
|
pass
|
||||||
except Exception as e:
|
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
|
self._monitor_task = None
|
||||||
|
|
||||||
if self.ws:
|
if self.ws:
|
||||||
|
|
@ -421,27 +440,29 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.last_active_time = None
|
self.last_active_time = None
|
||||||
|
|
||||||
async def _start_monitor_tts_response(self):
|
async def _start_monitor_tts_response(self):
|
||||||
"""监听TTS响应"""
|
"""Monitor TTS responses"""
|
||||||
opus_datas_cache = []
|
opus_datas_cache = []
|
||||||
is_first_sentence = True
|
is_first_sentence = True
|
||||||
first_sentence_segment_count = 0 # 添加计数器
|
first_sentence_segment_count = 0 # Add counter
|
||||||
try:
|
try:
|
||||||
session_finished = False # 标记会话是否正常结束
|
session_finished = False # Mark whether session ended normally
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
msg = await self.ws.recv()
|
msg = await self.ws.recv()
|
||||||
self.last_active_time = time.time()
|
self.last_active_time = time.time()
|
||||||
# 检查客户端是否中止
|
# Check if client aborted
|
||||||
if self.conn.client_abort:
|
if self.conn.client_abort:
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
|
logger.bind(tag=TAG).info(
|
||||||
|
"Received interruption signal, terminating TTS response monitoring")
|
||||||
break
|
break
|
||||||
if isinstance(msg, str): # 文本控制消息
|
if isinstance(msg, str): # Text control message
|
||||||
try:
|
try:
|
||||||
data = json.loads(msg)
|
data = json.loads(msg)
|
||||||
header = data.get("header", {})
|
header = data.get("header", {})
|
||||||
event_name = header.get("name")
|
event_name = header.get("name")
|
||||||
if event_name == "SynthesisStarted":
|
if event_name == "SynthesisStarted":
|
||||||
logger.bind(tag=TAG).debug("TTS合成已启动")
|
logger.bind(tag=TAG).debug(
|
||||||
|
"TTS synthesis started")
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.FIRST, [], None)
|
(SentenceType.FIRST, [], None)
|
||||||
)
|
)
|
||||||
|
|
@ -452,34 +473,38 @@ class TTSProvider(TTSProviderBase):
|
||||||
not is_first_sentence
|
not is_first_sentence
|
||||||
or first_sentence_segment_count > 10
|
or first_sentence_segment_count > 10
|
||||||
):
|
):
|
||||||
# 发送缓存的数据
|
# Send cached data
|
||||||
if self.conn.tts_MessageText:
|
if self.conn.tts_MessageText:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"句子语音生成成功: {self.conn.tts_MessageText}"
|
f"Sentence voice generation successful: {self.conn.tts_MessageText}"
|
||||||
)
|
)
|
||||||
self.tts_audio_queue.put(
|
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
|
self.conn.tts_MessageText = None
|
||||||
else:
|
else:
|
||||||
self.tts_audio_queue.put(
|
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
|
is_first_sentence = False
|
||||||
elif event_name == "SynthesisCompleted":
|
elif event_name == "SynthesisCompleted":
|
||||||
logger.bind(tag=TAG).debug(f"会话结束~~")
|
logger.bind(tag=TAG).debug(f"Session ended~~")
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
session_finished = True
|
session_finished = True
|
||||||
break
|
break
|
||||||
except json.JSONDecodeError:
|
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)):
|
elif isinstance(msg, (bytes, bytearray)):
|
||||||
logger.bind(tag=TAG).debug(f"推送数据到队列里面~~")
|
logger.bind(tag=TAG).debug(f"Pushing data to queue~~")
|
||||||
opus_datas = self.opus_encoder.encode_pcm_to_opus(msg, False)
|
opus_datas = self.opus_encoder.encode_pcm_to_opus(
|
||||||
|
msg, False)
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"推送数据到队列里面帧数~~{len(opus_datas)}"
|
f"Pushing data to queue frame count~~{len(opus_datas)}"
|
||||||
)
|
)
|
||||||
if is_first_sentence:
|
if is_first_sentence:
|
||||||
first_sentence_segment_count += 1
|
first_sentence_segment_count += 1
|
||||||
|
|
@ -490,46 +515,46 @@ class TTSProvider(TTSProviderBase):
|
||||||
else:
|
else:
|
||||||
opus_datas_cache.extend(opus_datas)
|
opus_datas_cache.extend(opus_datas)
|
||||||
else:
|
else:
|
||||||
# 后续句子缓存
|
# Cache subsequent sentences
|
||||||
opus_datas_cache.extend(opus_datas)
|
opus_datas_cache.extend(opus_datas)
|
||||||
|
|
||||||
except websockets.ConnectionClosed:
|
except websockets.ConnectionClosed:
|
||||||
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
|
logger.bind(tag=TAG).warning("WebSocket connection closed")
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
f"Error processing TTS response: {e}\n{traceback.format_exc()}"
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
# 仅在连接异常时才关闭
|
# Only close on connection exception
|
||||||
if not session_finished and self.ws:
|
if not session_finished and self.ws:
|
||||||
try:
|
try:
|
||||||
await self.ws.close()
|
await self.ws.close()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
self.ws = None
|
self.ws = None
|
||||||
# 监听任务退出时清理引用
|
# Clean up references when monitoring task exits
|
||||||
finally:
|
finally:
|
||||||
self._monitor_task = None
|
self._monitor_task = None
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
def to_tts(self, text: str) -> list:
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景"""
|
"""Non-streaming TTS processing, used for testing and saving audio files scenarios"""
|
||||||
try:
|
try:
|
||||||
# 创建新的事件循环
|
# Create new event loop
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
|
|
||||||
# 生成会话ID
|
# Generate session ID
|
||||||
session_id = uuid.uuid4().hex
|
session_id = uuid.uuid4().hex
|
||||||
# 存储音频数据
|
# Store audio data
|
||||||
audio_data = []
|
audio_data = []
|
||||||
|
|
||||||
async def _generate_audio():
|
async def _generate_audio():
|
||||||
# 刷新Token(如果需要)
|
# Refresh Token (if needed)
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
|
|
||||||
# 建立WebSocket连接
|
# Establish WebSocket connection
|
||||||
ws = await websockets.connect(
|
ws = await websockets.connect(
|
||||||
self.ws_url,
|
self.ws_url,
|
||||||
additional_headers={"X-NLS-Token": self.token},
|
additional_headers={"X-NLS-Token": self.token},
|
||||||
|
|
@ -538,7 +563,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
close_timeout=10,
|
close_timeout=10,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
# 发送StartSynthesis请求
|
# Send StartSynthesis request
|
||||||
start_message_id = str(uuid.uuid4().hex)
|
start_message_id = str(uuid.uuid4().hex)
|
||||||
start_request = {
|
start_request = {
|
||||||
"header": {
|
"header": {
|
||||||
|
|
@ -560,7 +585,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
await ws.send(json.dumps(start_request))
|
await ws.send(json.dumps(start_request))
|
||||||
|
|
||||||
# 等待SynthesisStarted响应
|
# Wait for SynthesisStarted response
|
||||||
synthesis_started = False
|
synthesis_started = False
|
||||||
while not synthesis_started:
|
while not synthesis_started:
|
||||||
msg = await ws.recv()
|
msg = await ws.recv()
|
||||||
|
|
@ -569,7 +594,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
header = data.get("header", {})
|
header = data.get("header", {})
|
||||||
if header.get("name") == "SynthesisStarted":
|
if header.get("name") == "SynthesisStarted":
|
||||||
synthesis_started = True
|
synthesis_started = True
|
||||||
logger.bind(tag=TAG).debug("TTS合成已启动")
|
logger.bind(tag=TAG).debug(
|
||||||
|
"TTS synthesis started")
|
||||||
elif header.get("name") == "TaskFailed":
|
elif header.get("name") == "TaskFailed":
|
||||||
error_info = data.get("payload", {}).get(
|
error_info = data.get("payload", {}).get(
|
||||||
"error_info", {}
|
"error_info", {}
|
||||||
|
|
@ -579,10 +605,10 @@ class TTSProvider(TTSProviderBase):
|
||||||
"error_message", "未知错误"
|
"error_message", "未知错误"
|
||||||
)
|
)
|
||||||
raise Exception(
|
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)
|
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||||
run_message_id = str(uuid.uuid4().hex)
|
run_message_id = str(uuid.uuid4().hex)
|
||||||
run_request = {
|
run_request = {
|
||||||
|
|
@ -597,7 +623,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
await ws.send(json.dumps(run_request))
|
await ws.send(json.dumps(run_request))
|
||||||
|
|
||||||
# 发送停止合成请求
|
# Send stop synthesis request
|
||||||
stop_message_id = str(uuid.uuid4().hex)
|
stop_message_id = str(uuid.uuid4().hex)
|
||||||
stop_request = {
|
stop_request = {
|
||||||
"header": {
|
"header": {
|
||||||
|
|
@ -610,12 +636,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
await ws.send(json.dumps(stop_request))
|
await ws.send(json.dumps(stop_request))
|
||||||
|
|
||||||
# 接收音频数据
|
# Receive audio data
|
||||||
synthesis_completed = False
|
synthesis_completed = False
|
||||||
while not synthesis_completed:
|
while not synthesis_completed:
|
||||||
msg = await ws.recv()
|
msg = await ws.recv()
|
||||||
if isinstance(msg, (bytes, bytearray)):
|
if isinstance(msg, (bytes, bytearray)):
|
||||||
# 编码为Opus并收集
|
# Encode to Opus and collect
|
||||||
opus_frames = self.opus_encoder.encode_pcm_to_opus(
|
opus_frames = self.opus_encoder.encode_pcm_to_opus(
|
||||||
msg, False
|
msg, False
|
||||||
)
|
)
|
||||||
|
|
@ -626,7 +652,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
event_name = header.get("name")
|
event_name = header.get("name")
|
||||||
if event_name == "SynthesisCompleted":
|
if event_name == "SynthesisCompleted":
|
||||||
synthesis_completed = True
|
synthesis_completed = True
|
||||||
logger.bind(tag=TAG).debug("TTS合成完成")
|
logger.bind(tag=TAG).debug(
|
||||||
|
"TTS synthesis completed")
|
||||||
elif event_name == "TaskFailed":
|
elif event_name == "TaskFailed":
|
||||||
error_info = data.get("payload", {}).get(
|
error_info = data.get("payload", {}).get(
|
||||||
"error_info", {}
|
"error_info", {}
|
||||||
|
|
@ -636,7 +663,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
"error_message", "未知错误"
|
"error_message", "未知错误"
|
||||||
)
|
)
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"合成失败: {error_code} - {error_message}"
|
f"Synthesis failed: {error_code} - {error_message}"
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
|
|
@ -649,5 +676,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
return audio_data
|
return audio_data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
|
logger.bind(tag=TAG).error(
|
||||||
|
f"Failed to generate audio data: {str(e)}")
|
||||||
return []
|
return []
|
||||||
|
|
@ -20,13 +20,11 @@ from core.providers.tts.dto.dto import (
|
||||||
ContentType,
|
ContentType,
|
||||||
InterfaceType,
|
InterfaceType,
|
||||||
)
|
)
|
||||||
|
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class TTSProviderBase(ABC):
|
class TTSProviderBase(ABC):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
self.interface_type = InterfaceType.NON_STREAM
|
self.interface_type = InterfaceType.NON_STREAM
|
||||||
|
|
@ -39,7 +37,6 @@ class TTSProviderBase(ABC):
|
||||||
self.tts_audio_queue = queue.Queue()
|
self.tts_audio_queue = queue.Queue()
|
||||||
self.tts_audio_first_sentence = True
|
self.tts_audio_first_sentence = True
|
||||||
self.before_stop_play_files = []
|
self.before_stop_play_files = []
|
||||||
|
|
||||||
self.tts_text_buff = []
|
self.tts_text_buff = []
|
||||||
self.punctuations = (
|
self.punctuations = (
|
||||||
"。",
|
"。",
|
||||||
|
|
@ -81,7 +78,7 @@ class TTSProviderBase(ABC):
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
max_repeat_time = 5
|
max_repeat_time = 5
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
# 需要删除文件的直接转为音频数据
|
# Files that need to be deleted are directly converted to audio data
|
||||||
while max_repeat_time > 0:
|
while max_repeat_time > 0:
|
||||||
try:
|
try:
|
||||||
audio_bytes = asyncio.run(self.text_to_speak(text, None))
|
audio_bytes = asyncio.run(self.text_to_speak(text, None))
|
||||||
|
|
@ -94,16 +91,17 @@ class TTSProviderBase(ABC):
|
||||||
max_repeat_time -= 1
|
max_repeat_time -= 1
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(
|
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
|
max_repeat_time -= 1
|
||||||
|
|
||||||
if max_repeat_time > 0:
|
if max_repeat_time > 0:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
|
f"Speech generation successful: {text}, retried {5 - max_repeat_time} times"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
f"Speech generation failed: {text}, please check network or service status"
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
|
|
@ -114,22 +112,21 @@ class TTSProviderBase(ABC):
|
||||||
asyncio.run(self.text_to_speak(text, tmp_file))
|
asyncio.run(self.text_to_speak(text, tmp_file))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(
|
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):
|
if os.path.exists(tmp_file):
|
||||||
os.remove(tmp_file)
|
os.remove(tmp_file)
|
||||||
max_repeat_time -= 1
|
max_repeat_time -= 1
|
||||||
|
|
||||||
if max_repeat_time > 0:
|
if max_repeat_time > 0:
|
||||||
logger.bind(tag=TAG).info(
|
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:
|
else:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
f"Speech generation failed: {text}, please check network or service status"
|
||||||
)
|
)
|
||||||
|
|
||||||
return tmp_file
|
return tmp_file
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
||||||
|
|
@ -140,11 +137,11 @@ class TTSProviderBase(ABC):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def audio_to_pcm_data(self, audio_file_path):
|
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)
|
return audio_to_data(audio_file_path, is_opus=False)
|
||||||
|
|
||||||
def audio_to_opus_data(self, audio_file_path):
|
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)
|
return audio_to_data(audio_file_path, is_opus=True)
|
||||||
|
|
||||||
def tts_one_sentence(
|
def tts_one_sentence(
|
||||||
|
|
@ -155,14 +152,15 @@ class TTSProviderBase(ABC):
|
||||||
content_file=None,
|
content_file=None,
|
||||||
sentence_id=None,
|
sentence_id=None,
|
||||||
):
|
):
|
||||||
"""发送一句话"""
|
"""Send one sentence"""
|
||||||
if not sentence_id:
|
if not sentence_id:
|
||||||
if conn.sentence_id:
|
if conn.sentence_id:
|
||||||
sentence_id = conn.sentence_id
|
sentence_id = conn.sentence_id
|
||||||
else:
|
else:
|
||||||
sentence_id = str(uuid.uuid4().hex)
|
sentence_id = str(uuid.uuid4().hex)
|
||||||
conn.sentence_id = sentence_id
|
conn.sentence_id = sentence_id
|
||||||
# 对于单句的文本,进行分段处理
|
|
||||||
|
# For single sentence text, perform segmentation processing
|
||||||
segments = re.split(r"([。!?!?;;\n])", content_detail)
|
segments = re.split(r"([。!?!?;;\n])", content_detail)
|
||||||
for seg in segments:
|
for seg in segments:
|
||||||
self.tts_text_queue.put(
|
self.tts_text_queue.put(
|
||||||
|
|
@ -178,36 +176,38 @@ class TTSProviderBase(ABC):
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
self.tts_timeout = conn.config.get("tts_timeout", 10)
|
self.tts_timeout = conn.config.get("tts_timeout", 10)
|
||||||
# tts 消化线程
|
# TTS processing thread
|
||||||
self.tts_priority_thread = threading.Thread(
|
self.tts_priority_thread = threading.Thread(
|
||||||
target=self.tts_text_priority_thread, daemon=True
|
target=self.tts_text_priority_thread, daemon=True
|
||||||
)
|
)
|
||||||
self.tts_priority_thread.start()
|
self.tts_priority_thread.start()
|
||||||
|
# Audio playback processing thread
|
||||||
# 音频播放 消化线程
|
|
||||||
self.audio_play_priority_thread = threading.Thread(
|
self.audio_play_priority_thread = threading.Thread(
|
||||||
target=self._audio_play_priority_thread, daemon=True
|
target=self._audio_play_priority_thread, daemon=True
|
||||||
)
|
)
|
||||||
self.audio_play_priority_thread.start()
|
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):
|
def tts_text_priority_thread(self):
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
message = self.tts_text_queue.get(timeout=1)
|
message = self.tts_text_queue.get(timeout=1)
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
self.conn.client_abort = False
|
self.conn.client_abort = False
|
||||||
|
|
||||||
if self.conn.client_abort:
|
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
|
continue
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
# 初始化参数
|
# Initialize parameters
|
||||||
self.tts_stop_request = False
|
self.tts_stop_request = False
|
||||||
self.processed_chars = 0
|
self.processed_chars = 0
|
||||||
self.tts_text_buff = []
|
self.tts_text_buff = []
|
||||||
self.is_first_sentence = True
|
self.is_first_sentence = True
|
||||||
self.tts_audio_first_sentence = True
|
self.tts_audio_first_sentence = True
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
self.tts_text_buff.append(message.content_detail)
|
self.tts_text_buff.append(message.content_detail)
|
||||||
segment_text = self._get_segment_text()
|
segment_text = self._get_segment_text()
|
||||||
|
|
@ -225,6 +225,7 @@ class TTSProviderBase(ABC):
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(message.sentence_type, audio_datas, segment_text)
|
(message.sentence_type, audio_datas, segment_text)
|
||||||
)
|
)
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
elif ContentType.FILE == message.content_type:
|
||||||
self._process_remaining_text()
|
self._process_remaining_text()
|
||||||
tts_file = message.content_file
|
tts_file = message.content_file
|
||||||
|
|
@ -244,7 +245,7 @@ class TTSProviderBase(ABC):
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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
|
continue
|
||||||
|
|
||||||
|
|
@ -260,14 +261,18 @@ class TTSProviderBase(ABC):
|
||||||
if self.conn.stop_event.is_set():
|
if self.conn.stop_event.is_set():
|
||||||
break
|
break
|
||||||
continue
|
continue
|
||||||
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
|
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
|
||||||
self.conn.loop,
|
self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
|
|
||||||
if self.conn.max_output_size > 0 and text:
|
if self.conn.max_output_size > 0 and text:
|
||||||
add_device_output(self.conn.headers.get("device-id"), len(text))
|
add_device_output(self.conn.headers.get("device-id"), len(text))
|
||||||
|
|
||||||
enqueue_tts_report(self.conn, text, audio_datas)
|
enqueue_tts_report(self.conn, text, audio_datas)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"audio_play_priority priority_thread: {text} {e}"
|
f"audio_play_priority priority_thread: {text} {e}"
|
||||||
|
|
@ -280,17 +285,17 @@ class TTSProviderBase(ABC):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""资源清理方法"""
|
"""Resource cleanup method"""
|
||||||
if hasattr(self, "ws") and self.ws:
|
if hasattr(self, "ws") and self.ws:
|
||||||
await self.ws.close()
|
await self.ws.close()
|
||||||
|
|
||||||
def _get_segment_text(self):
|
def _get_segment_text(self):
|
||||||
# 合并当前全部文本并处理未分割部分
|
# Merge all current text and process unsegmented parts
|
||||||
full_text = "".join(self.tts_text_buff)
|
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
|
last_punct_pos = -1
|
||||||
|
|
||||||
# 根据是否是第一句话选择不同的标点符号集合
|
# Choose different punctuation sets based on whether it's the first sentence
|
||||||
punctuations_to_use = (
|
punctuations_to_use = (
|
||||||
self.first_sentence_punctuations
|
self.first_sentence_punctuations
|
||||||
if self.is_first_sentence
|
if self.is_first_sentence
|
||||||
|
|
@ -309,26 +314,24 @@ class TTSProviderBase(ABC):
|
||||||
segment_text = textUtils.get_string_no_punctuation_or_emoji(
|
segment_text = textUtils.get_string_no_punctuation_or_emoji(
|
||||||
segment_text_raw
|
segment_text_raw
|
||||||
)
|
)
|
||||||
self.processed_chars += len(segment_text_raw) # 更新已处理字符位置
|
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
|
||||||
# 如果是第一句话,在找到第一个逗号后,将标志设置为False
|
|
||||||
if self.is_first_sentence:
|
if self.is_first_sentence:
|
||||||
self.is_first_sentence = False
|
self.is_first_sentence = False
|
||||||
|
|
||||||
return segment_text
|
return segment_text
|
||||||
elif self.tts_stop_request and current_text:
|
elif self.tts_stop_request and current_text:
|
||||||
segment_text = current_text
|
segment_text = current_text
|
||||||
self.is_first_sentence = True # 重置标志
|
self.is_first_sentence = True # Reset flag
|
||||||
return segment_text
|
return segment_text
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _process_audio_file(self, tts_file):
|
def _process_audio_file(self, tts_file):
|
||||||
"""处理音频文件并转换为指定格式
|
"""Process audio file and convert to specified format
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tts_file: 音频文件路径
|
tts_file: Audio file path
|
||||||
content_detail: 内容详情
|
content_detail: Content details
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
tuple: (sentence_type, audio_datas, content_detail)
|
tuple: (sentence_type, audio_datas, content_detail)
|
||||||
|
|
@ -347,6 +350,7 @@ class TTSProviderBase(ABC):
|
||||||
and tts_file.startswith(self.output_file)
|
and tts_file.startswith(self.output_file)
|
||||||
):
|
):
|
||||||
os.remove(tts_file)
|
os.remove(tts_file)
|
||||||
|
|
||||||
return audio_datas
|
return audio_datas
|
||||||
|
|
||||||
def _process_before_stop_play_files(self):
|
def _process_before_stop_play_files(self):
|
||||||
|
|
@ -356,15 +360,17 @@ class TTSProviderBase(ABC):
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
|
|
||||||
def _process_remaining_text(self):
|
def _process_remaining_text(self):
|
||||||
"""处理剩余的文本并生成语音
|
"""Process remaining text and generate speech
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 是否成功处理了文本
|
bool: Whether text was successfully processed
|
||||||
"""
|
"""
|
||||||
full_text = "".join(self.tts_text_buff)
|
full_text = "".join(self.tts_text_buff)
|
||||||
remaining_text = full_text[self.processed_chars :]
|
remaining_text = full_text[self.processed_chars:]
|
||||||
if remaining_text:
|
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 segment_text:
|
||||||
if self.delete_audio_file:
|
if self.delete_audio_file:
|
||||||
audio_datas = self.to_tts(segment_text)
|
audio_datas = self.to_tts(segment_text)
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,76 @@
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.model = config.get("model")
|
self.model = config.get("model")
|
||||||
|
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
|
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
|
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
|
|
||||||
self.response_format = config.get("response_format", "wav")
|
self.response_format = config.get("response_format", "wav")
|
||||||
|
|
||||||
self.audio_file_type = config.get("response_format", "wav")
|
self.audio_file_type = config.get("response_format", "wav")
|
||||||
|
|
||||||
self.host = "api.coze.cn"
|
self.host = "api.coze.cn"
|
||||||
|
|
||||||
self.api_url = f"https://{self.host}/v1/audio/speech"
|
self.api_url = f"https://{self.host}/v1/audio/speech"
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
request_json = {
|
request_json = {
|
||||||
|
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
|
|
||||||
"input": text,
|
"input": text,
|
||||||
|
|
||||||
"voice_id": self.voice,
|
"voice_id": self.voice,
|
||||||
|
|
||||||
"response_format": self.response_format,
|
"response_format": self.response_format,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
|
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
"Authorization": f"Bearer {self.access_token}",
|
||||||
|
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
response = requests.request(
|
response = requests.request(
|
||||||
|
|
||||||
"POST", self.api_url, json=request_json, headers=headers
|
"POST", self.api_url, json=request_json, headers=headers
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
data = response.content
|
data = response.content
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as file_to_save:
|
with open(output_file, "wb") as file_to_save:
|
||||||
|
|
||||||
file_to_save.write(data)
|
file_to_save.write(data)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
|
||||||
|
|
@ -1,54 +1,95 @@
|
||||||
import os
|
import os
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.url = config.get("url")
|
self.url = config.get("url")
|
||||||
|
|
||||||
self.method = config.get("method", "GET")
|
self.method = config.get("method", "GET")
|
||||||
|
|
||||||
self.headers = config.get("headers", {})
|
self.headers = config.get("headers", {})
|
||||||
|
|
||||||
self.format = config.get("format", "wav")
|
self.format = config.get("format", "wav")
|
||||||
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
self.audio_file_type = config.get("format", "wav")
|
||||||
|
|
||||||
self.output_file = config.get("output_dir", "tmp/")
|
self.output_file = config.get("output_dir", "tmp/")
|
||||||
|
|
||||||
self.params = config.get("params")
|
self.params = config.get("params")
|
||||||
|
|
||||||
if isinstance(self.params, str):
|
if isinstance(self.params, str):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
self.params = json.loads(self.params)
|
self.params = json.loads(self.params)
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
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):
|
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):
|
def generate_filename(self):
|
||||||
|
|
||||||
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}")
|
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):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
request_params = {}
|
request_params = {}
|
||||||
|
|
||||||
for k, v in self.params.items():
|
for k, v in self.params.items():
|
||||||
|
|
||||||
if isinstance(v, str) and "{prompt_text}" in v:
|
if isinstance(v, str) and "{prompt_text}" in v:
|
||||||
|
|
||||||
v = v.replace("{prompt_text}", text)
|
v = v.replace("{prompt_text}", text)
|
||||||
|
|
||||||
request_params[k] = v
|
request_params[k] = v
|
||||||
|
|
||||||
if self.method.upper() == "POST":
|
if self.method.upper() == "POST":
|
||||||
|
|
||||||
resp = requests.post(self.url, json=request_params, headers=self.headers)
|
resp = requests.post(self.url, json=request_params, headers=self.headers)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
resp = requests.get(self.url, params=request_params, headers=self.headers)
|
resp = requests.get(self.url, params=request_params, headers=self.headers)
|
||||||
|
|
||||||
if resp.status_code == 200:
|
if resp.status_code == 200:
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as file:
|
with open(output_file, "wb") as file:
|
||||||
|
|
||||||
file.write(resp.content)
|
file.write(resp.content)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return resp.content
|
return resp.content
|
||||||
|
|
||||||
else:
|
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)
|
logger.bind(tag=TAG).error(error_msg)
|
||||||
raise Exception(error_msg) # 抛出异常,让调用方捕获
|
|
||||||
|
raise Exception(error_msg) # Throw exception for caller to catch
|
||||||
|
|
@ -1,23 +1,34 @@
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class DefaultTTS(TTSProviderBase):
|
class DefaultTTS(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file=True):
|
def __init__(self, config, delete_audio_file=True):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.output_dir = config.get("output_dir", "output")
|
self.output_dir = config.get("output_dir", "output")
|
||||||
|
|
||||||
if not os.path.exists(self.output_dir):
|
if not os.path.exists(self.output_dir):
|
||||||
|
|
||||||
os.makedirs(self.output_dir)
|
os.makedirs(self.output_dir)
|
||||||
|
|
||||||
def generate_filename(self):
|
def generate_filename(self):
|
||||||
"""生成唯一的音频文件名"""
|
"""Generate unique audio filename"""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
return os.path.join(self.output_dir, f"{uuid.uuid4()}.wav")
|
return os.path.join(self.output_dir, f"{uuid.uuid4()}.wav")
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
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")
|
||||||
|
|
|
||||||
|
|
@ -1,86 +1,155 @@
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
if config.get("appid"):
|
if config.get("appid"):
|
||||||
|
|
||||||
self.appid = int(config.get("appid"))
|
self.appid = int(config.get("appid"))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
self.appid = ""
|
self.appid = ""
|
||||||
|
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
|
|
||||||
self.cluster = config.get("cluster")
|
self.cluster = config.get("cluster")
|
||||||
|
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
|
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
|
|
||||||
# 处理空字符串的情况
|
# Handle empty string cases
|
||||||
|
|
||||||
speed_ratio = config.get("speed_ratio", "1.0")
|
speed_ratio = config.get("speed_ratio", "1.0")
|
||||||
|
|
||||||
volume_ratio = config.get("volume_ratio", "1.0")
|
volume_ratio = config.get("volume_ratio", "1.0")
|
||||||
|
|
||||||
pitch_ratio = config.get("pitch_ratio", "1.0")
|
pitch_ratio = config.get("pitch_ratio", "1.0")
|
||||||
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
self.audio_file_type = config.get("format", "wav")
|
||||||
|
|
||||||
self.speed_ratio = float(speed_ratio) if speed_ratio else 1.0
|
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.volume_ratio = float(volume_ratio) if volume_ratio else 1.0
|
||||||
|
|
||||||
self.pitch_ratio = float(pitch_ratio) if pitch_ratio else 1.0
|
self.pitch_ratio = float(pitch_ratio) if pitch_ratio else 1.0
|
||||||
|
|
||||||
self.api_url = config.get("api_url")
|
self.api_url = config.get("api_url")
|
||||||
|
|
||||||
self.authorization = config.get("authorization")
|
self.authorization = config.get("authorization")
|
||||||
|
|
||||||
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
|
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
|
||||||
|
|
||||||
model_key_msg = check_model_key("TTS", self.access_token)
|
model_key_msg = check_model_key("TTS", self.access_token)
|
||||||
|
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
|
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
request_json = {
|
request_json = {
|
||||||
|
|
||||||
"app": {
|
"app": {
|
||||||
|
|
||||||
"appid": f"{self.appid}",
|
"appid": f"{self.appid}",
|
||||||
|
|
||||||
"token": self.access_token,
|
"token": self.access_token,
|
||||||
|
|
||||||
"cluster": self.cluster,
|
"cluster": self.cluster,
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
"user": {"uid": "1"},
|
"user": {"uid": "1"},
|
||||||
|
|
||||||
"audio": {
|
"audio": {
|
||||||
|
|
||||||
"voice_type": self.voice,
|
"voice_type": self.voice,
|
||||||
|
|
||||||
"encoding": self.audio_file_type,
|
"encoding": self.audio_file_type,
|
||||||
|
|
||||||
"speed_ratio": self.speed_ratio,
|
"speed_ratio": self.speed_ratio,
|
||||||
|
|
||||||
"volume_ratio": self.volume_ratio,
|
"volume_ratio": self.volume_ratio,
|
||||||
|
|
||||||
"pitch_ratio": self.pitch_ratio,
|
"pitch_ratio": self.pitch_ratio,
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
"request": {
|
"request": {
|
||||||
|
|
||||||
"reqid": str(uuid.uuid4()),
|
"reqid": str(uuid.uuid4()),
|
||||||
|
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
||||||
"text_type": "plain",
|
"text_type": "plain",
|
||||||
|
|
||||||
"operation": "query",
|
"operation": "query",
|
||||||
|
|
||||||
"with_frontend": 1,
|
"with_frontend": 1,
|
||||||
|
|
||||||
"frontend_type": "unitTson",
|
"frontend_type": "unitTson",
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
|
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
self.api_url, json.dumps(request_json), headers=self.header
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if "data" in resp.json():
|
if "data" in resp.json():
|
||||||
|
|
||||||
data = resp.json()["data"]
|
data = resp.json()["data"]
|
||||||
|
|
||||||
audio_bytes = base64.b64decode(data)
|
audio_bytes = base64.b64decode(data)
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as file_to_save:
|
with open(output_file, "wb") as file_to_save:
|
||||||
|
|
||||||
file_to_save.write(audio_bytes)
|
file_to_save.write(audio_bytes)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return audio_bytes
|
return audio_bytes
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
raise Exception(
|
raise Exception(
|
||||||
|
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
@ -3,37 +3,37 @@ from typing import Union, Optional
|
||||||
|
|
||||||
|
|
||||||
class SentenceType(Enum):
|
class SentenceType(Enum):
|
||||||
# 说话阶段
|
# Speaking stage
|
||||||
FIRST = "FIRST" # 首句话
|
FIRST = "FIRST" # First sentence
|
||||||
MIDDLE = "MIDDLE" # 说话中
|
MIDDLE = "MIDDLE" # Speaking in progress
|
||||||
LAST = "LAST" # 最后一句
|
LAST = "LAST" # Last sentence
|
||||||
|
|
||||||
|
|
||||||
class ContentType(Enum):
|
class ContentType(Enum):
|
||||||
# 内容类型
|
# Content type
|
||||||
TEXT = "TEXT" # 文本内容
|
TEXT = "TEXT" # Text content
|
||||||
FILE = "FILE" # 文件内容
|
FILE = "FILE" # File content
|
||||||
ACTION = "ACTION" # 动作内容
|
ACTION = "ACTION" # Action content
|
||||||
|
|
||||||
|
|
||||||
class InterfaceType(Enum):
|
class InterfaceType(Enum):
|
||||||
# 接口类型
|
# Interface type
|
||||||
DUAL_STREAM = "DUAL_STREAM" # 双流式
|
DUAL_STREAM = "DUAL_STREAM" # Dual streaming
|
||||||
SINGLE_STREAM = "SINGLE_STREAM" # 单流式
|
SINGLE_STREAM = "SINGLE_STREAM" # Single streaming
|
||||||
NON_STREAM = "NON_STREAM" # 非流式
|
NON_STREAM = "NON_STREAM" # Non-streaming
|
||||||
|
|
||||||
|
|
||||||
class TTSMessageDTO:
|
class TTSMessageDTO:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
sentence_id: str,
|
sentence_id: str,
|
||||||
# 说话阶段
|
# Speaking stage
|
||||||
sentence_type: SentenceType,
|
sentence_type: SentenceType,
|
||||||
# 内容类型
|
# Content type
|
||||||
content_type: ContentType,
|
content_type: ContentType,
|
||||||
# 内容详情,一般是需要转换的文本或者音频的歌词
|
# Content details, usually text to be converted or lyrics of audio
|
||||||
content_detail: Optional[str] = None,
|
content_detail: Optional[str] = None,
|
||||||
# 如果内容类型为文件,则需要传入文件路径
|
# If content type is file, need to pass file path
|
||||||
content_file: Optional[str] = None,
|
content_file: Optional[str] = None,
|
||||||
):
|
):
|
||||||
self.sentence_id = sentence_id
|
self.sentence_id = sentence_id
|
||||||
|
|
|
||||||
|
|
@ -1,46 +1,81 @@
|
||||||
import os
|
import os
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
import edge_tts
|
import edge_tts
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
|
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
|
|
||||||
self.audio_file_type = config.get("format", "mp3")
|
self.audio_file_type = config.get("format", "mp3")
|
||||||
|
|
||||||
def generate_filename(self, extension=".mp3"):
|
def generate_filename(self, extension=".mp3"):
|
||||||
|
|
||||||
return os.path.join(
|
return os.path.join(
|
||||||
|
|
||||||
self.output_file,
|
self.output_file,
|
||||||
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
communicate = edge_tts.Communicate(text, voice=self.voice)
|
communicate = edge_tts.Communicate(text, voice=self.voice)
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
# 确保目录存在并创建空文件
|
|
||||||
|
# Ensure directory exists and create empty file
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
||||||
|
|
||||||
with open(output_file, "wb") as f:
|
with open(output_file, "wb") as f:
|
||||||
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 流式写入音频数据
|
# Stream write audio data
|
||||||
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
|
|
||||||
|
with open(output_file, "ab") as f: # Change to append mode to avoid overwrite
|
||||||
|
|
||||||
async for chunk in communicate.stream():
|
async for chunk in communicate.stream():
|
||||||
if chunk["type"] == "audio": # 只处理音频数据块
|
|
||||||
|
if chunk["type"] == "audio": # Only process audio data chunks
|
||||||
|
|
||||||
f.write(chunk["data"])
|
f.write(chunk["data"])
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# 返回音频二进制数据
|
|
||||||
|
# Return audio binary data
|
||||||
|
|
||||||
audio_bytes = b""
|
audio_bytes = b""
|
||||||
|
|
||||||
async for chunk in communicate.stream():
|
async for chunk in communicate.stream():
|
||||||
|
|
||||||
if chunk["type"] == "audio":
|
if chunk["type"] == "audio":
|
||||||
|
|
||||||
audio_bytes += chunk["data"]
|
audio_bytes += chunk["data"]
|
||||||
|
|
||||||
return audio_bytes
|
return audio_bytes
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_msg = f"Edge TTS请求失败: {e}"
|
|
||||||
raise Exception(error_msg) # 抛出异常,让调用方捕获
|
error_msg = f"Edge TTS request failed: {e}"
|
||||||
|
|
||||||
|
raise Exception(error_msg) # Throw exception for caller to catch
|
||||||
|
|
@ -9,43 +9,54 @@ logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
"""
|
"""
|
||||||
ElevenLabs TTS Provider
|
ElevenLabs TTS Provider
|
||||||
Supports high-quality voice synthesis with multiple voices and languages
|
Supports high-quality voice synthesis with multiple voices and languages
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
self.api_key = config.get("api_key","sk_7bbbc42db83364614c2e07da3991c16a91256df9e7281f37")
|
self.api_key = config.get(
|
||||||
|
"api_key", "sk_7bbbc42db83364614c2e07da3991c16a91256df9e7281f37")
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
raise ValueError("ElevenLabs API key is required")
|
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
|
# ElevenLabs API endpoint
|
||||||
|
|
||||||
self.api_url = f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}"
|
self.api_url = f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}"
|
||||||
|
|
||||||
# Voice settings
|
# Voice settings
|
||||||
|
|
||||||
self.stability = float(config.get("stability", "0.75"))
|
self.stability = float(config.get("stability", "0.75"))
|
||||||
self.similarity_boost = float(config.get("similarity_boost", "0.75"))
|
self.similarity_boost = float(config.get("similarity_boost", "0.75"))
|
||||||
self.style = float(config.get("style", "0.0")) # For v2 models
|
self.style = float(config.get("style", "0.0")) # For v2 models
|
||||||
self.use_speaker_boost = config.get("use_speaker_boost", True)
|
self.use_speaker_boost = config.get("use_speaker_boost", True)
|
||||||
|
|
||||||
# Output format (ElevenLabs supports mp3, pcm, ulaw, mulaw)
|
# Output format (ElevenLabs supports mp3, pcm, ulaw, mulaw)
|
||||||
|
|
||||||
self.output_format = config.get("output_format", "mp3_44100_128")
|
self.output_format = config.get("output_format", "mp3_44100_128")
|
||||||
self.audio_file_type = "mp3" if "mp3" in self.output_format else "wav"
|
self.audio_file_type = "mp3" if "mp3" in self.output_format else "wav"
|
||||||
|
|
||||||
# Streaming settings
|
# 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/")
|
self.output_file = config.get("output_dir", "tmp/")
|
||||||
|
|
||||||
model_key_msg = check_model_key("ElevenLabs TTS", self.api_key)
|
model_key_msg = check_model_key("ElevenLabs TTS", self.api_key)
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
# Validate API key format
|
# Validate API key format
|
||||||
if self.api_key and len(self.api_key) < 32:
|
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):
|
async def text_to_speak(self, text, output_file):
|
||||||
"""
|
"""
|
||||||
|
|
@ -62,74 +73,133 @@ class TTSProvider(TTSProviderBase):
|
||||||
"model_id": self.model_id,
|
"model_id": self.model_id,
|
||||||
"voice_settings": {
|
"voice_settings": {
|
||||||
"stability": self.stability,
|
"stability": self.stability,
|
||||||
|
|
||||||
"similarity_boost": self.similarity_boost,
|
"similarity_boost": self.similarity_boost,
|
||||||
|
|
||||||
"style": self.style,
|
"style": self.style,
|
||||||
|
|
||||||
"use_speaker_boost": self.use_speaker_boost
|
"use_speaker_boost": self.use_speaker_boost
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Add streaming optimization if specified
|
# Add streaming optimization if specified
|
||||||
|
|
||||||
if self.optimize_streaming_latency > 0:
|
if self.optimize_streaming_latency > 0:
|
||||||
|
|
||||||
params = {
|
params = {
|
||||||
|
|
||||||
"optimize_streaming_latency": self.optimize_streaming_latency,
|
"optimize_streaming_latency": self.optimize_streaming_latency,
|
||||||
|
|
||||||
"output_format": self.output_format
|
"output_format": self.output_format
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
params = {
|
params = {
|
||||||
|
|
||||||
"output_format": self.output_format
|
"output_format": self.output_format
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
|
|
||||||
self.api_url,
|
self.api_url,
|
||||||
|
|
||||||
json=data,
|
json=data,
|
||||||
|
|
||||||
headers=headers,
|
headers=headers,
|
||||||
|
|
||||||
params=params,
|
params=params,
|
||||||
|
|
||||||
timeout=30
|
timeout=30
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as audio_file:
|
with open(output_file, "wb") as audio_file:
|
||||||
|
|
||||||
audio_file.write(response.content)
|
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:
|
else:
|
||||||
|
|
||||||
return response.content
|
return response.content
|
||||||
|
|
||||||
else:
|
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(
|
raise Exception(
|
||||||
|
|
||||||
f"ElevenLabs TTS request failed: {response.status_code} - {error_data}"
|
f"ElevenLabs TTS request failed: {response.status_code} - {error_data}"
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
except requests.exceptions.Timeout:
|
except requests.exceptions.Timeout:
|
||||||
|
|
||||||
raise Exception("ElevenLabs TTS request timed out")
|
raise Exception("ElevenLabs TTS request timed out")
|
||||||
|
|
||||||
except requests.exceptions.RequestException as e:
|
except requests.exceptions.RequestException as e:
|
||||||
|
|
||||||
raise Exception(f"ElevenLabs TTS network error: {str(e)}")
|
raise Exception(f"ElevenLabs TTS network error: {str(e)}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
logger.bind(tag=TAG).error(f"ElevenLabs TTS error: {str(e)}")
|
logger.bind(tag=TAG).error(f"ElevenLabs TTS error: {str(e)}")
|
||||||
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def get_available_voices(self):
|
def get_available_voices(self):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
Helper method to get available voices from ElevenLabs
|
Helper method to get available voices from ElevenLabs
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
|
|
||||||
"Accept": "application/json",
|
"Accept": "application/json",
|
||||||
|
|
||||||
"xi-api-key": self.api_key
|
"xi-api-key": self.api_key
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
response = requests.get(
|
response = requests.get(
|
||||||
|
|
||||||
"https://api.elevenlabs.io/v1/voices",
|
"https://api.elevenlabs.io/v1/voices",
|
||||||
|
|
||||||
headers=headers
|
headers=headers
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
|
|
||||||
voices = response.json()["voices"]
|
voices = response.json()["voices"]
|
||||||
|
|
||||||
return [(v["voice_id"], v["name"]) for v in voices]
|
return [(v["voice_id"], v["name"]) for v in voices]
|
||||||
|
|
||||||
else:
|
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 []
|
return []
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
logger.bind(tag=TAG).error(f"Error fetching voices: {str(e)}")
|
logger.bind(tag=TAG).error(f"Error fetching voices: {str(e)}")
|
||||||
|
|
||||||
return []
|
return []
|
||||||
|
|
@ -1,188 +1,319 @@
|
||||||
import base64
|
import base64
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
import ormsgpack
|
import ormsgpack
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from pydantic import BaseModel, Field, conint, model_validator
|
from pydantic import BaseModel, Field, conint, model_validator
|
||||||
|
|
||||||
from typing_extensions import Annotated
|
from typing_extensions import Annotated
|
||||||
|
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
|
|
||||||
from core.utils.util import check_model_key, parse_string_to_list
|
from core.utils.util import check_model_key, parse_string_to_list
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ServeReferenceAudio(BaseModel):
|
class ServeReferenceAudio(BaseModel):
|
||||||
|
|
||||||
audio: bytes
|
audio: bytes
|
||||||
|
|
||||||
text: str
|
text: str
|
||||||
|
|
||||||
@model_validator(mode="before")
|
@model_validator(mode="before")
|
||||||
|
|
||||||
def decode_audio(cls, values):
|
def decode_audio(cls, values):
|
||||||
|
|
||||||
audio = values.get("audio")
|
audio = values.get("audio")
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
|
||||||
isinstance(audio, str) and len(audio) > 255
|
isinstance(audio, str) and len(audio) > 255
|
||||||
): # Check if audio is a string (Base64)
|
|
||||||
|
): # Check if audio is a string (Base64)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
values["audio"] = base64.b64decode(audio)
|
values["audio"] = base64.b64decode(audio)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
# If the audio is not a valid base64 string, we will just ignore it and let the server handle it
|
# If the audio is not a valid base64 string, we will just ignore it and let the server handle it
|
||||||
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return values
|
return values
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
|
|
||||||
return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})"
|
return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})"
|
||||||
|
|
||||||
|
|
||||||
class ServeTTSRequest(BaseModel):
|
class ServeTTSRequest(BaseModel):
|
||||||
|
|
||||||
text: str
|
text: str
|
||||||
|
|
||||||
chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
|
chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
|
||||||
|
|
||||||
# Audio format
|
# Audio format
|
||||||
|
|
||||||
format: Literal["wav", "pcm", "mp3"] = "wav"
|
format: Literal["wav", "pcm", "mp3"] = "wav"
|
||||||
|
|
||||||
# References audios for in-context learning
|
# References audios for in-context learning
|
||||||
|
|
||||||
references: list[ServeReferenceAudio] = []
|
references: list[ServeReferenceAudio] = []
|
||||||
|
|
||||||
# Reference id
|
# Reference id
|
||||||
|
|
||||||
# For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
|
# For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
|
||||||
|
|
||||||
# Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
|
# Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
|
||||||
|
|
||||||
reference_id: str | None = None
|
reference_id: str | None = None
|
||||||
|
|
||||||
seed: int | None = None
|
seed: int | None = None
|
||||||
|
|
||||||
use_memory_cache: Literal["on", "off"] = "off"
|
use_memory_cache: Literal["on", "off"] = "off"
|
||||||
|
|
||||||
# Normalize text for en & zh, this increase stability for numbers
|
# Normalize text for en & zh, this increase stability for numbers
|
||||||
|
|
||||||
normalize: bool = True
|
normalize: bool = True
|
||||||
|
|
||||||
# not usually used below
|
# not usually used below
|
||||||
|
|
||||||
streaming: bool = False
|
streaming: bool = False
|
||||||
|
|
||||||
max_new_tokens: int = 1024
|
max_new_tokens: int = 1024
|
||||||
|
|
||||||
top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
|
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
|
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
|
temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
|
|
||||||
# Allow arbitrary types for pytorch related types
|
# Allow arbitrary types for pytorch related types
|
||||||
|
|
||||||
arbitrary_types_allowed = True
|
arbitrary_types_allowed = True
|
||||||
|
|
||||||
|
|
||||||
def audio_to_bytes(file_path):
|
def audio_to_bytes(file_path):
|
||||||
|
|
||||||
if not file_path or not Path(file_path).exists():
|
if not file_path or not Path(file_path).exists():
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
with open(file_path, "rb") as wav_file:
|
with open(file_path, "rb") as wav_file:
|
||||||
|
|
||||||
wav = wav_file.read()
|
wav = wav_file.read()
|
||||||
|
|
||||||
return wav
|
return wav
|
||||||
|
|
||||||
|
|
||||||
def read_ref_text(ref_text):
|
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):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.reference_id = (
|
self.reference_id = (
|
||||||
|
|
||||||
None if not config.get("reference_id") else config.get("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")
|
channels = config.get("channels", "1")
|
||||||
|
|
||||||
rate = config.get("rate", "44100")
|
rate = config.get("rate", "44100")
|
||||||
|
|
||||||
max_new_tokens = config.get("max_new_tokens", "1024")
|
max_new_tokens = config.get("max_new_tokens", "1024")
|
||||||
|
|
||||||
chunk_length = config.get("chunk_length", "200")
|
chunk_length = config.get("chunk_length", "200")
|
||||||
|
|
||||||
self.channels = int(channels) if channels else 1
|
self.channels = int(channels) if channels else 1
|
||||||
|
|
||||||
self.rate = int(rate) if rate else 44100
|
self.rate = int(rate) if rate else 44100
|
||||||
|
|
||||||
self.max_new_tokens = int(max_new_tokens) if max_new_tokens else 1024
|
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
|
self.chunk_length = int(chunk_length) if chunk_length else 200
|
||||||
|
|
||||||
# 处理空字符串的情况
|
# Handle empty string cases
|
||||||
|
|
||||||
top_p = config.get("top_p", "0.7")
|
top_p = config.get("top_p", "0.7")
|
||||||
|
|
||||||
temperature = config.get("temperature", "0.7")
|
temperature = config.get("temperature", "0.7")
|
||||||
|
|
||||||
repetition_penalty = config.get("repetition_penalty", "1.2")
|
repetition_penalty = config.get("repetition_penalty", "1.2")
|
||||||
|
|
||||||
self.top_p = float(top_p) if top_p else 0.7
|
self.top_p = float(top_p) if top_p else 0.7
|
||||||
|
|
||||||
self.temperature = float(temperature) if temperature else 0.7
|
self.temperature = float(temperature) if temperature else 0.7
|
||||||
|
|
||||||
self.repetition_penalty = (
|
self.repetition_penalty = (
|
||||||
|
|
||||||
float(repetition_penalty) if repetition_penalty else 1.2
|
float(repetition_penalty) if repetition_penalty else 1.2
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.streaming = str(config.get("streaming", False)).lower() in (
|
self.streaming = str(config.get("streaming", False)).lower() in (
|
||||||
|
|
||||||
"true",
|
"true",
|
||||||
|
|
||||||
"1",
|
"1",
|
||||||
|
|
||||||
"yes",
|
"yes",
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.use_memory_cache = config.get("use_memory_cache", "on")
|
self.use_memory_cache = config.get("use_memory_cache", "on")
|
||||||
|
|
||||||
self.seed = int(config.get("seed")) if config.get("seed") else None
|
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")
|
self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
# Prepare reference data
|
# Prepare reference data
|
||||||
|
|
||||||
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
|
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]
|
ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text]
|
||||||
|
|
||||||
data = {
|
data = {
|
||||||
|
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
||||||
"references": [
|
"references": [
|
||||||
|
|
||||||
ServeReferenceAudio(audio=audio if audio else b"", text=text)
|
ServeReferenceAudio(audio=audio if audio else b"", text=text)
|
||||||
|
|
||||||
for text, audio in zip(ref_texts, byte_audios)
|
for text, audio in zip(ref_texts, byte_audios)
|
||||||
|
|
||||||
],
|
],
|
||||||
|
|
||||||
"reference_id": self.reference_id,
|
"reference_id": self.reference_id,
|
||||||
|
|
||||||
"normalize": self.normalize,
|
"normalize": self.normalize,
|
||||||
|
|
||||||
"format": self.format,
|
"format": self.format,
|
||||||
|
|
||||||
"max_new_tokens": self.max_new_tokens,
|
"max_new_tokens": self.max_new_tokens,
|
||||||
|
|
||||||
"chunk_length": self.chunk_length,
|
"chunk_length": self.chunk_length,
|
||||||
|
|
||||||
"top_p": self.top_p,
|
"top_p": self.top_p,
|
||||||
|
|
||||||
"repetition_penalty": self.repetition_penalty,
|
"repetition_penalty": self.repetition_penalty,
|
||||||
|
|
||||||
"temperature": self.temperature,
|
"temperature": self.temperature,
|
||||||
|
|
||||||
"streaming": self.streaming,
|
"streaming": self.streaming,
|
||||||
|
|
||||||
"use_memory_cache": self.use_memory_cache,
|
"use_memory_cache": self.use_memory_cache,
|
||||||
|
|
||||||
"seed": self.seed,
|
"seed": self.seed,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pydantic_data = ServeTTSRequest(**data)
|
pydantic_data = ServeTTSRequest(**data)
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
|
|
||||||
self.api_url,
|
self.api_url,
|
||||||
|
|
||||||
data=ormsgpack.packb(
|
data=ormsgpack.packb(
|
||||||
|
|
||||||
pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
|
pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
|
||||||
|
|
||||||
),
|
),
|
||||||
|
|
||||||
headers={
|
headers={
|
||||||
|
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
|
|
||||||
"Content-Type": "application/msgpack",
|
"Content-Type": "application/msgpack",
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
|
|
||||||
audio_content = response.content
|
audio_content = response.content
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as audio_file:
|
with open(output_file, "wb") as audio_file:
|
||||||
|
|
||||||
audio_file.write(audio_content)
|
audio_file.write(audio_content)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return audio_content
|
return audio_content
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
error_msg = f"Request failed with status code {response.status_code}"
|
error_msg = f"Request failed with status code {response.status_code}"
|
||||||
|
|
||||||
print(error_msg)
|
print(error_msg)
|
||||||
|
|
||||||
print(response.json())
|
print(response.json())
|
||||||
|
|
||||||
raise Exception(error_msg)
|
raise Exception(error_msg)
|
||||||
|
|
@ -1,103 +1,185 @@
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
from core.utils.util import parse_string_to_list
|
from core.utils.util import parse_string_to_list
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.url = config.get("url")
|
self.url = config.get("url")
|
||||||
|
|
||||||
self.text_lang = config.get("text_lang", "zh")
|
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")
|
self.prompt_lang = config.get("prompt_lang", "zh")
|
||||||
|
|
||||||
# 处理空字符串的情况
|
# Handle empty string cases
|
||||||
|
|
||||||
top_k = config.get("top_k", "5")
|
top_k = config.get("top_k", "5")
|
||||||
|
|
||||||
top_p = config.get("top_p", "1")
|
top_p = config.get("top_p", "1")
|
||||||
|
|
||||||
temperature = config.get("temperature", "1")
|
temperature = config.get("temperature", "1")
|
||||||
|
|
||||||
batch_threshold = config.get("batch_threshold", "0.75")
|
batch_threshold = config.get("batch_threshold", "0.75")
|
||||||
|
|
||||||
batch_size = config.get("batch_size", "1")
|
batch_size = config.get("batch_size", "1")
|
||||||
|
|
||||||
speed_factor = config.get("speed_factor", "1.0")
|
speed_factor = config.get("speed_factor", "1.0")
|
||||||
|
|
||||||
seed = config.get("seed", "-1")
|
seed = config.get("seed", "-1")
|
||||||
|
|
||||||
repetition_penalty = config.get("repetition_penalty", "1.35")
|
repetition_penalty = config.get("repetition_penalty", "1.35")
|
||||||
|
|
||||||
self.top_k = int(top_k) if top_k else 5
|
self.top_k = int(top_k) if top_k else 5
|
||||||
|
|
||||||
self.top_p = float(top_p) if top_p else 1
|
self.top_p = float(top_p) if top_p else 1
|
||||||
|
|
||||||
self.temperature = float(temperature) if temperature 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.batch_size = int(batch_size) if batch_size else 1
|
||||||
|
|
||||||
self.speed_factor = float(speed_factor) if speed_factor else 1.0
|
self.speed_factor = float(speed_factor) if speed_factor else 1.0
|
||||||
|
|
||||||
self.seed = int(seed) if seed else -1
|
self.seed = int(seed) if seed else -1
|
||||||
|
|
||||||
self.repetition_penalty = (
|
self.repetition_penalty = (
|
||||||
|
|
||||||
float(repetition_penalty) if repetition_penalty else 1.35
|
float(repetition_penalty) if repetition_penalty else 1.35
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.text_split_method = config.get("text_split_method", "cut0")
|
self.text_split_method = config.get("text_split_method", "cut0")
|
||||||
|
|
||||||
self.split_bucket = str(config.get("split_bucket", True)).lower() in (
|
self.split_bucket = str(config.get("split_bucket", True)).lower() in (
|
||||||
|
|
||||||
"true",
|
"true",
|
||||||
|
|
||||||
"1",
|
"1",
|
||||||
|
|
||||||
"yes",
|
"yes",
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.return_fragment = str(config.get("return_fragment", False)).lower() in (
|
self.return_fragment = str(config.get("return_fragment", False)).lower() in (
|
||||||
|
|
||||||
"true",
|
"true",
|
||||||
|
|
||||||
"1",
|
"1",
|
||||||
|
|
||||||
"yes",
|
"yes",
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.streaming_mode = str(config.get("streaming_mode", False)).lower() in (
|
self.streaming_mode = str(config.get("streaming_mode", False)).lower() in (
|
||||||
|
|
||||||
"true",
|
"true",
|
||||||
|
|
||||||
"1",
|
"1",
|
||||||
|
|
||||||
"yes",
|
"yes",
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.parallel_infer = str(config.get("parallel_infer", True)).lower() in (
|
self.parallel_infer = str(config.get("parallel_infer", True)).lower() in (
|
||||||
|
|
||||||
"true",
|
"true",
|
||||||
|
|
||||||
"1",
|
"1",
|
||||||
|
|
||||||
"yes",
|
"yes",
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.aux_ref_audio_paths = parse_string_to_list(
|
self.aux_ref_audio_paths = parse_string_to_list(
|
||||||
|
|
||||||
config.get("aux_ref_audio_paths")
|
config.get("aux_ref_audio_paths")
|
||||||
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
self.audio_file_type = config.get("format", "wav")
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
request_json = {
|
request_json = {
|
||||||
|
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
||||||
"text_lang": self.text_lang,
|
"text_lang": self.text_lang,
|
||||||
|
|
||||||
"ref_audio_path": self.ref_audio_path,
|
"ref_audio_path": self.ref_audio_path,
|
||||||
|
|
||||||
"aux_ref_audio_paths": self.aux_ref_audio_paths,
|
"aux_ref_audio_paths": self.aux_ref_audio_paths,
|
||||||
|
|
||||||
"prompt_text": self.prompt_text,
|
"prompt_text": self.prompt_text,
|
||||||
|
|
||||||
"prompt_lang": self.prompt_lang,
|
"prompt_lang": self.prompt_lang,
|
||||||
|
|
||||||
"top_k": self.top_k,
|
"top_k": self.top_k,
|
||||||
|
|
||||||
"top_p": self.top_p,
|
"top_p": self.top_p,
|
||||||
|
|
||||||
"temperature": self.temperature,
|
"temperature": self.temperature,
|
||||||
|
|
||||||
"text_split_method": self.text_split_method,
|
"text_split_method": self.text_split_method,
|
||||||
|
|
||||||
"batch_size": self.batch_size,
|
"batch_size": self.batch_size,
|
||||||
|
|
||||||
"batch_threshold": self.batch_threshold,
|
"batch_threshold": self.batch_threshold,
|
||||||
|
|
||||||
"split_bucket": self.split_bucket,
|
"split_bucket": self.split_bucket,
|
||||||
|
|
||||||
"return_fragment": self.return_fragment,
|
"return_fragment": self.return_fragment,
|
||||||
|
|
||||||
"speed_factor": self.speed_factor,
|
"speed_factor": self.speed_factor,
|
||||||
|
|
||||||
"streaming_mode": self.streaming_mode,
|
"streaming_mode": self.streaming_mode,
|
||||||
|
|
||||||
"seed": self.seed,
|
"seed": self.seed,
|
||||||
|
|
||||||
"parallel_infer": self.parallel_infer,
|
"parallel_infer": self.parallel_infer,
|
||||||
|
|
||||||
"repetition_penalty": self.repetition_penalty,
|
"repetition_penalty": self.repetition_penalty,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
resp = requests.post(self.url, json=request_json)
|
resp = requests.post(self.url, json=request_json)
|
||||||
|
|
||||||
if resp.status_code == 200:
|
if resp.status_code == 200:
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as file:
|
with open(output_file, "wb") as file:
|
||||||
|
|
||||||
file.write(resp.content)
|
file.write(resp.content)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return resp.content
|
return resp.content
|
||||||
|
|
||||||
else:
|
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)
|
logger.bind(tag=TAG).error(error_msg)
|
||||||
|
|
||||||
raise Exception(error_msg)
|
raise Exception(error_msg)
|
||||||
|
|
|
||||||
|
|
@ -1,64 +1,111 @@
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
from core.utils.util import parse_string_to_list
|
from core.utils.util import parse_string_to_list
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
|
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.url = config.get("url")
|
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.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_text = config.get('ref_text')if config.get('ref_text') else config.get("prompt_text")
|
||||||
|
|
||||||
self.prompt_language = config.get("prompt_language")
|
self.prompt_language = config.get("prompt_language")
|
||||||
|
|
||||||
self.text_language = config.get("text_language", "audo")
|
self.text_language = config.get("text_language", "audo")
|
||||||
|
|
||||||
# 处理空字符串的情况
|
# Handle empty string cases
|
||||||
|
|
||||||
top_k = config.get("top_k", "15")
|
top_k = config.get("top_k", "15")
|
||||||
|
|
||||||
top_p = config.get("top_p", "1.0")
|
top_p = config.get("top_p", "1.0")
|
||||||
|
|
||||||
temperature = config.get("temperature", "1.0")
|
temperature = config.get("temperature", "1.0")
|
||||||
|
|
||||||
sample_steps = config.get("sample_steps", "32")
|
sample_steps = config.get("sample_steps", "32")
|
||||||
|
|
||||||
speed = config.get("speed", "1.0")
|
speed = config.get("speed", "1.0")
|
||||||
|
|
||||||
self.top_k = int(top_k) if top_k else 15
|
self.top_k = int(top_k) if top_k else 15
|
||||||
|
|
||||||
self.top_p = float(top_p) if top_p else 1.0
|
self.top_p = float(top_p) if top_p else 1.0
|
||||||
|
|
||||||
self.temperature = float(temperature) if temperature else 1.0
|
self.temperature = float(temperature) if temperature else 1.0
|
||||||
|
|
||||||
self.sample_steps = int(sample_steps) if sample_steps else 32
|
self.sample_steps = int(sample_steps) if sample_steps else 32
|
||||||
|
|
||||||
self.speed = float(speed) if speed else 1.0
|
self.speed = float(speed) if speed else 1.0
|
||||||
|
|
||||||
self.cut_punc = config.get("cut_punc", "")
|
self.cut_punc = config.get("cut_punc", "")
|
||||||
|
|
||||||
self.inp_refs = parse_string_to_list(config.get("inp_refs"))
|
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.if_sr = str(config.get("if_sr", False)).lower() in ("true", "1", "yes")
|
||||||
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
self.audio_file_type = config.get("format", "wav")
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
|
|
||||||
request_params = {
|
request_params = {
|
||||||
|
|
||||||
"refer_wav_path": self.refer_wav_path,
|
"refer_wav_path": self.refer_wav_path,
|
||||||
|
|
||||||
"prompt_text": self.prompt_text,
|
"prompt_text": self.prompt_text,
|
||||||
|
|
||||||
"prompt_language": self.prompt_language,
|
"prompt_language": self.prompt_language,
|
||||||
|
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
||||||
"text_language": self.text_language,
|
"text_language": self.text_language,
|
||||||
|
|
||||||
"top_k": self.top_k,
|
"top_k": self.top_k,
|
||||||
|
|
||||||
"top_p": self.top_p,
|
"top_p": self.top_p,
|
||||||
|
|
||||||
"temperature": self.temperature,
|
"temperature": self.temperature,
|
||||||
|
|
||||||
"cut_punc": self.cut_punc,
|
"cut_punc": self.cut_punc,
|
||||||
|
|
||||||
"speed": self.speed,
|
"speed": self.speed,
|
||||||
|
|
||||||
"inp_refs": self.inp_refs,
|
"inp_refs": self.inp_refs,
|
||||||
|
|
||||||
"sample_steps": self.sample_steps,
|
"sample_steps": self.sample_steps,
|
||||||
|
|
||||||
"if_sr": self.if_sr,
|
"if_sr": self.if_sr,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
resp = requests.get(self.url, params=request_params)
|
resp = requests.get(self.url, params=request_params)
|
||||||
|
|
||||||
if resp.status_code == 200:
|
if resp.status_code == 200:
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
|
|
||||||
with open(output_file, "wb") as file:
|
with open(output_file, "wb") as file:
|
||||||
|
|
||||||
file.write(resp.content)
|
file.write(resp.content)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
||||||
return resp.content
|
return resp.content
|
||||||
|
|
||||||
else:
|
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)
|
logger.bind(tag=TAG).error(error_msg)
|
||||||
|
|
||||||
raise Exception(error_msg)
|
raise Exception(error_msg)
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -29,27 +29,28 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.before_stop_play_files = []
|
self.before_stop_play_files = []
|
||||||
self.segment_count = 0
|
self.segment_count = 0
|
||||||
|
|
||||||
# 创建Opus编码器 需注意接口返回的采样率为24000
|
# Create Opus encoder Note: interface returns sample rate of 24000
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
||||||
sample_rate=24000, channels=1, frame_size_ms=60
|
sample_rate=24000, channels=1, frame_size_ms=60
|
||||||
)
|
)
|
||||||
|
|
||||||
# 文本缓冲区和PCM缓冲区
|
# Text buffer and PCM buffer
|
||||||
self.text_buffer = ""
|
self.text_buffer = ""
|
||||||
self.pcm_buffer = bytearray()
|
self.pcm_buffer = bytearray()
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
def tts_text_priority_thread(self):
|
||||||
"""流式文本处理线程"""
|
"""Streaming text processing thread"""
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
message = self.tts_text_queue.get(timeout=1)
|
message = self.tts_text_queue.get(timeout=1)
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
# 初始化参数
|
# Initialize parameters
|
||||||
self.tts_stop_request = False
|
self.tts_stop_request = False
|
||||||
self.processed_chars = 0
|
self.processed_chars = 0
|
||||||
self.tts_text_buff = []
|
self.tts_text_buff = []
|
||||||
self.segment_count = 0
|
self.segment_count = 0
|
||||||
self.before_stop_play_files.clear()
|
self.before_stop_play_files.clear()
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
self.tts_text_buff.append(message.content_detail)
|
self.tts_text_buff.append(message.content_detail)
|
||||||
segment_text = self._get_segment_text()
|
segment_text = self._get_segment_text()
|
||||||
|
|
@ -58,35 +59,39 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
elif ContentType.FILE == message.content_type:
|
||||||
logger.bind(tag=TAG).info(
|
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):
|
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)
|
file_audio = self._process_audio_file(
|
||||||
|
message.content_file)
|
||||||
self.before_stop_play_files.append(
|
self.before_stop_play_files.append(
|
||||||
(file_audio, message.content_detail)
|
(file_audio, message.content_detail)
|
||||||
)
|
)
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
# 处理剩余的文本
|
# Process remaining text
|
||||||
self._process_remaining_text(True)
|
self._process_remaining_text(True)
|
||||||
|
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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):
|
def _process_remaining_text(self, is_last=False):
|
||||||
"""处理剩余的文本并生成语音
|
"""Process remaining text and generate speech
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 是否成功处理了文本
|
bool: Whether text was successfully processed
|
||||||
"""
|
"""
|
||||||
full_text = "".join(self.tts_text_buff)
|
full_text = "".join(self.tts_text_buff)
|
||||||
remaining_text = full_text[self.processed_chars :]
|
remaining_text = full_text[self.processed_chars:]
|
||||||
if remaining_text:
|
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 segment_text:
|
||||||
self.to_tts_single_stream(segment_text, is_last)
|
self.to_tts_single_stream(segment_text, is_last)
|
||||||
self.processed_chars += len(full_text)
|
self.processed_chars += len(full_text)
|
||||||
|
|
@ -103,27 +108,27 @@ class TTSProvider(TTSProviderBase):
|
||||||
asyncio.run(self.text_to_speak(text, is_last))
|
asyncio.run(self.text_to_speak(text, is_last))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(
|
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:
|
max_repeat_time -= 1
|
||||||
logger.bind(tag=TAG).info(
|
if max_repeat_time > 0:
|
||||||
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
|
logger.bind(tag=TAG).info(
|
||||||
)
|
f"Speech generation successful: {text}, retried {5 - max_repeat_time} times"
|
||||||
else:
|
)
|
||||||
logger.bind(tag=TAG).error(
|
else:
|
||||||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
logger.bind(tag=TAG).error(
|
||||||
)
|
f"Speech generation failed: {text}, please check network or service status"
|
||||||
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
||||||
finally:
|
finally:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def text_to_speak(self, text, is_last):
|
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}
|
payload = {"text": text, "character": self.voice}
|
||||||
|
|
||||||
frame_bytes = int(
|
frame_bytes = int(
|
||||||
self.opus_encoder.sample_rate
|
self.opus_encoder.sample_rate
|
||||||
* self.opus_encoder.channels # 1
|
* self.opus_encoder.channels # 1
|
||||||
|
|
@ -131,25 +136,25 @@ class TTSProvider(TTSProviderBase):
|
||||||
/ 1000
|
/ 1000
|
||||||
* 2
|
* 2
|
||||||
) # 16-bit = 2 bytes
|
) # 16-bit = 2 bytes
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.post(self.api_url, json=payload, timeout=10) as resp:
|
async with session.post(self.api_url, json=payload, timeout=10) as resp:
|
||||||
|
|
||||||
if resp.status != 200:
|
if resp.status != 200:
|
||||||
logger.bind(tag=TAG).error(
|
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))
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
return
|
return
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
opus_datas_cache = []
|
opus_datas_cache = []
|
||||||
|
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
||||||
|
|
||||||
# 处理音频流数据
|
# Process audio stream data
|
||||||
async for chunk in resp.content.iter_any():
|
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:
|
if not data:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
@ -161,8 +166,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
opus = self.opus_encoder.encode_pcm_to_opus(
|
opus = self.opus_encoder.encode_pcm_to_opus(
|
||||||
frame, end_of_stream=False
|
frame, end_of_stream=False
|
||||||
)
|
)
|
||||||
|
|
||||||
if opus:
|
if opus:
|
||||||
if self.segment_count < 10: # 前10个片段直接发送
|
if self.segment_count < 10: # Send first 10 segments directly
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, opus, None)
|
(SentenceType.MIDDLE, opus, None)
|
||||||
)
|
)
|
||||||
|
|
@ -170,72 +176,74 @@ class TTSProvider(TTSProviderBase):
|
||||||
else:
|
else:
|
||||||
opus_datas_cache.extend(opus)
|
opus_datas_cache.extend(opus)
|
||||||
|
|
||||||
# flush 剩余不足一帧的数据
|
# Flush remaining data that doesn't fill a complete frame
|
||||||
if self.pcm_buffer:
|
if self.pcm_buffer:
|
||||||
opus = self.opus_encoder.encode_pcm_to_opus(
|
opus = self.opus_encoder.encode_pcm_to_opus(
|
||||||
bytes(self.pcm_buffer), end_of_stream=True
|
bytes(self.pcm_buffer), end_of_stream=True
|
||||||
)
|
)
|
||||||
|
|
||||||
if opus:
|
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(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, opus, None)
|
(SentenceType.MIDDLE, opus, None)
|
||||||
)
|
)
|
||||||
self.segment_count += 1
|
self.segment_count += 1
|
||||||
else:
|
else:
|
||||||
# 后续片段缓存
|
# Cache subsequent segments
|
||||||
opus_datas_cache.extend(opus)
|
opus_datas_cache.extend(opus)
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
|
|
||||||
# 如果不是前10个片段,发送缓存的数据
|
# If not in first 10 segments, send cached data
|
||||||
if self.segment_count >= 10 and opus_datas_cache:
|
if self.segment_count >= 10 and opus_datas_cache:
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, opus_datas_cache, None)
|
(SentenceType.MIDDLE, opus_datas_cache, None)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 如果是最后一段,输出音频获取完毕
|
# If this is the last segment, audio acquisition complete
|
||||||
if is_last:
|
if is_last:
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
except Exception as e:
|
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))
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""资源清理"""
|
"""Resource cleanup"""
|
||||||
await super().close()
|
await super().close()
|
||||||
if hasattr(self, "opus_encoder"):
|
if hasattr(self, "opus_encoder"):
|
||||||
self.opus_encoder.close()
|
self.opus_encoder.close()
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
def to_tts(self, text: str) -> list:
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景
|
"""Non-streaming TTS processing for testing and saving audio files
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
text: 要转换的文本
|
text: Text to convert
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
list: 返回opus编码后的音频数据列表
|
list: Returns opus-encoded audio data list
|
||||||
"""
|
"""
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
|
||||||
payload = {"text": text, "character": self.character}
|
payload = {"text": text, "character": self.character}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with requests.post(self.api_url, json=payload, timeout=5) as response:
|
with requests.post(self.api_url, json=payload, timeout=5) as response:
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"TTS请求失败: {response.status_code}, {response.text}"
|
f"TTS request failed: {response.status_code}, {response.text}"
|
||||||
)
|
)
|
||||||
return []
|
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 = []
|
opus_datas = []
|
||||||
pcm_data = response.content
|
pcm_data = response.content
|
||||||
|
|
||||||
# 计算每帧的字节数
|
# Calculate bytes per frame
|
||||||
frame_bytes = int(
|
frame_bytes = int(
|
||||||
self.opus_encoder.sample_rate
|
self.opus_encoder.sample_rate
|
||||||
* self.opus_encoder.channels
|
* self.opus_encoder.channels
|
||||||
|
|
@ -244,21 +252,22 @@ class TTSProvider(TTSProviderBase):
|
||||||
* 2
|
* 2
|
||||||
)
|
)
|
||||||
|
|
||||||
# 分帧处理PCM数据
|
# Process PCM data frame by frame
|
||||||
for i in range(0, len(pcm_data), frame_bytes):
|
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:
|
if len(frame) < frame_bytes:
|
||||||
# 最后一帧可能不足,用0填充
|
# Last frame might be insufficient, pad with zeros
|
||||||
frame = frame + b"\x00" * (frame_bytes - len(frame))
|
frame = frame + b"\x00" * (frame_bytes - len(frame))
|
||||||
|
|
||||||
opus = self.opus_encoder.encode_pcm_to_opus(
|
opus = self.opus_encoder.encode_pcm_to_opus(
|
||||||
frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
|
frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
|
||||||
)
|
)
|
||||||
|
|
||||||
if opus:
|
if opus:
|
||||||
opus_datas.extend(opus)
|
opus_datas.extend(opus)
|
||||||
|
|
||||||
return opus_datas
|
return opus_datas
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
logger.bind(tag=TAG).error(f"TTS request exception: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
@ -14,7 +14,6 @@ from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
@ -24,35 +23,35 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.api_url = config.get("api_url")
|
self.api_url = config.get("api_url")
|
||||||
self.audio_format = "pcm"
|
self.audio_format = "pcm"
|
||||||
self.before_stop_play_files = []
|
self.before_stop_play_files = []
|
||||||
self.segment_count = 0 # 添加片段计数器
|
self.segment_count = 0 # Add segment counter
|
||||||
|
|
||||||
# 创建Opus编码器
|
# Create Opus encoder
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
||||||
sample_rate=16000, channels=1, frame_size_ms=60
|
sample_rate=16000, channels=1, frame_size_ms=60
|
||||||
)
|
)
|
||||||
|
|
||||||
# 添加文本缓冲区
|
# Add text buffer
|
||||||
self.text_buffer = ""
|
self.text_buffer = ""
|
||||||
|
# PCM buffer
|
||||||
# PCM缓冲区
|
|
||||||
self.pcm_buffer = bytearray()
|
self.pcm_buffer = bytearray()
|
||||||
|
|
||||||
###################################################################################
|
###################################################################################
|
||||||
# linkerai单流式TTS重写父类的方法--开始
|
# linkerai single-stream TTS override parent class methods - Start
|
||||||
###################################################################################
|
###################################################################################
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
def tts_text_priority_thread(self):
|
||||||
"""流式文本处理线程"""
|
"""Streaming text processing thread"""
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
message = self.tts_text_queue.get(timeout=1)
|
message = self.tts_text_queue.get(timeout=1)
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
# 初始化参数
|
# Initialize parameters
|
||||||
self.tts_stop_request = False
|
self.tts_stop_request = False
|
||||||
self.processed_chars = 0
|
self.processed_chars = 0
|
||||||
self.tts_text_buff = []
|
self.tts_text_buff = []
|
||||||
self.segment_count = 0
|
self.segment_count = 0
|
||||||
self.before_stop_play_files.clear()
|
self.before_stop_play_files.clear()
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
self.tts_text_buff.append(message.content_detail)
|
self.tts_text_buff.append(message.content_detail)
|
||||||
segment_text = self._get_segment_text()
|
segment_text = self._get_segment_text()
|
||||||
|
|
@ -61,31 +60,32 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
elif ContentType.FILE == message.content_type:
|
||||||
logger.bind(tag=TAG).info(
|
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):
|
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)
|
file_audio = self._process_audio_file(message.content_file)
|
||||||
self.before_stop_play_files.append(
|
self.before_stop_play_files.append(
|
||||||
(file_audio, message.content_detail)
|
(file_audio, message.content_detail)
|
||||||
)
|
)
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
# 处理剩余的文本
|
# Process remaining text
|
||||||
self._process_remaining_text(True)
|
self._process_remaining_text(True)
|
||||||
|
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
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):
|
def _process_remaining_text(self, is_last=False):
|
||||||
"""处理剩余的文本并生成语音
|
"""Process remaining text and generate speech
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 是否成功处理了文本
|
bool: Whether text was successfully processed
|
||||||
"""
|
"""
|
||||||
full_text = "".join(self.tts_text_buff)
|
full_text = "".join(self.tts_text_buff)
|
||||||
remaining_text = full_text[self.processed_chars :]
|
remaining_text = full_text[self.processed_chars :]
|
||||||
|
|
@ -107,33 +107,34 @@ class TTSProvider(TTSProviderBase):
|
||||||
asyncio.run(self.text_to_speak(text, is_last))
|
asyncio.run(self.text_to_speak(text, is_last))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(
|
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:
|
max_repeat_time -= 1
|
||||||
logger.bind(tag=TAG).info(
|
if max_repeat_time > 0:
|
||||||
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
|
logger.bind(tag=TAG).info(
|
||||||
)
|
f"Speech generation successful: {text}, retried {5 - max_repeat_time} times"
|
||||||
else:
|
)
|
||||||
logger.bind(tag=TAG).error(
|
else:
|
||||||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
logger.bind(tag=TAG).error(
|
||||||
)
|
f"Speech generation failed: {text}, please check network or service status"
|
||||||
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
||||||
finally:
|
finally:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
###################################################################################
|
###################################################################################
|
||||||
# linkerai单流式TTS重写父类的方法--结束
|
# linkerai single-stream TTS override parent class methods - End
|
||||||
###################################################################################
|
###################################################################################
|
||||||
|
|
||||||
async def text_to_speak(self, text, is_last):
|
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)
|
await self._tts_request(text, is_last)
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""资源清理"""
|
"""Resource cleanup"""
|
||||||
await super().close()
|
await super().close()
|
||||||
if hasattr(self, "opus_encoder"):
|
if hasattr(self, "opus_encoder"):
|
||||||
self.opus_encoder.close()
|
self.opus_encoder.close()
|
||||||
|
|
@ -146,14 +147,15 @@ class TTSProvider(TTSProviderBase):
|
||||||
"stream": "true",
|
"stream": "true",
|
||||||
"target_sr": 16000,
|
"target_sr": 16000,
|
||||||
"audio_format": "pcm",
|
"audio_format": "pcm",
|
||||||
"instruct_text": "请生成一段自然流畅的语音",
|
"instruct_text": "Please generate natural and fluent speech",
|
||||||
}
|
}
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
"Authorization": f"Bearer {self.access_token}",
|
||||||
"Content-Type": "application/json",
|
"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(
|
frame_bytes = int(
|
||||||
self.opus_encoder.sample_rate
|
self.opus_encoder.sample_rate
|
||||||
* self.opus_encoder.channels # 1
|
* self.opus_encoder.channels # 1
|
||||||
|
|
@ -167,38 +169,36 @@ class TTSProvider(TTSProviderBase):
|
||||||
async with session.get(
|
async with session.get(
|
||||||
self.api_url, params=params, headers=headers, timeout=10
|
self.api_url, params=params, headers=headers, timeout=10
|
||||||
) as resp:
|
) as resp:
|
||||||
|
|
||||||
if resp.status != 200:
|
if resp.status != 200:
|
||||||
logger.bind(tag=TAG).error(
|
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))
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
return
|
return
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
opus_datas_cache = []
|
opus_datas_cache = []
|
||||||
|
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
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():
|
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:
|
if not data:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 拼到 buffer
|
# Append to buffer
|
||||||
self.pcm_buffer.extend(data)
|
self.pcm_buffer.extend(data)
|
||||||
|
|
||||||
# 够一帧就编码
|
# Encode when enough for one frame
|
||||||
while len(self.pcm_buffer) >= frame_bytes:
|
while len(self.pcm_buffer) >= frame_bytes:
|
||||||
frame = bytes(self.pcm_buffer[:frame_bytes])
|
frame = bytes(self.pcm_buffer[:frame_bytes])
|
||||||
del self.pcm_buffer[:frame_bytes]
|
del self.pcm_buffer[:frame_bytes]
|
||||||
|
|
||||||
opus = self.opus_encoder.encode_pcm_to_opus(
|
opus = self.opus_encoder.encode_pcm_to_opus(
|
||||||
frame, end_of_stream=False
|
frame, end_of_stream=False
|
||||||
)
|
)
|
||||||
|
|
||||||
if opus:
|
if opus:
|
||||||
if self.segment_count < 10: # 前10个片段直接发送
|
if self.segment_count < 10: # Send first 10 segments directly
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, opus, None)
|
(SentenceType.MIDDLE, opus, None)
|
||||||
)
|
)
|
||||||
|
|
@ -206,49 +206,50 @@ class TTSProvider(TTSProviderBase):
|
||||||
else:
|
else:
|
||||||
opus_datas_cache.extend(opus)
|
opus_datas_cache.extend(opus)
|
||||||
|
|
||||||
# flush 剩余不足一帧的数据
|
# Flush remaining data that doesn't fill a complete frame
|
||||||
if self.pcm_buffer:
|
if self.pcm_buffer:
|
||||||
opus = self.opus_encoder.encode_pcm_to_opus(
|
opus = self.opus_encoder.encode_pcm_to_opus(
|
||||||
bytes(self.pcm_buffer), end_of_stream=True
|
bytes(self.pcm_buffer), end_of_stream=True
|
||||||
)
|
)
|
||||||
|
|
||||||
if opus:
|
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(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, opus, None)
|
(SentenceType.MIDDLE, opus, None)
|
||||||
)
|
)
|
||||||
self.segment_count += 1
|
self.segment_count += 1
|
||||||
else:
|
else:
|
||||||
# 后续片段缓存
|
# Cache subsequent segments
|
||||||
opus_datas_cache.extend(opus)
|
opus_datas_cache.extend(opus)
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
self.pcm_buffer.clear()
|
||||||
|
|
||||||
# 如果不是前10个片段,发送缓存的数据
|
# If not in first 10 segments, send cached data
|
||||||
if self.segment_count >= 10 and opus_datas_cache:
|
if self.segment_count >= 10 and opus_datas_cache:
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, opus_datas_cache, None)
|
(SentenceType.MIDDLE, opus_datas_cache, None)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 如果是最后一段,输出音频获取完毕
|
# If this is the last segment, audio acquisition complete
|
||||||
if is_last:
|
if is_last:
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
except Exception as e:
|
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))
|
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
def to_tts(self, text: str) -> list:
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景
|
"""Non-streaming TTS processing for testing and saving audio files
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
text: 要转换的文本
|
text: Text to convert
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
list: 返回opus编码后的音频数据列表
|
list: Returns opus-encoded audio data list
|
||||||
"""
|
"""
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
|
||||||
params = {
|
params = {
|
||||||
"tts_text": text,
|
"tts_text": text,
|
||||||
"spk_id": self.voice,
|
"spk_id": self.voice,
|
||||||
|
|
@ -256,8 +257,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
"stream": False,
|
"stream": False,
|
||||||
"target_sr": 16000,
|
"target_sr": 16000,
|
||||||
"audio_format": self.audio_format,
|
"audio_format": self.audio_format,
|
||||||
"instruct_text": "请生成一段自然流畅的语音",
|
"instruct_text": "Please generate natural and fluent speech",
|
||||||
}
|
}
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
"Authorization": f"Bearer {self.access_token}",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
|
@ -269,17 +271,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
) as response:
|
) as response:
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"TTS请求失败: {response.status_code}, {response.text}"
|
f"TTS request failed: {response.status_code}, {response.text}"
|
||||||
)
|
)
|
||||||
return []
|
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 = []
|
opus_datas = []
|
||||||
pcm_data = response.content
|
pcm_data = response.content
|
||||||
|
|
||||||
# 计算每帧的字节数
|
# Calculate bytes per frame
|
||||||
frame_bytes = int(
|
frame_bytes = int(
|
||||||
self.opus_encoder.sample_rate
|
self.opus_encoder.sample_rate
|
||||||
* self.opus_encoder.channels
|
* self.opus_encoder.channels
|
||||||
|
|
@ -288,21 +290,22 @@ class TTSProvider(TTSProviderBase):
|
||||||
* 2
|
* 2
|
||||||
)
|
)
|
||||||
|
|
||||||
# 分帧处理PCM数据
|
# Process PCM data frame by frame
|
||||||
for i in range(0, len(pcm_data), frame_bytes):
|
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:
|
if len(frame) < frame_bytes:
|
||||||
# 最后一帧可能不足,用0填充
|
# Last frame might be insufficient, pad with zeros
|
||||||
frame = frame + b"\x00" * (frame_bytes - len(frame))
|
frame = frame + b"\x00" * (frame_bytes - len(frame))
|
||||||
|
|
||||||
opus = self.opus_encoder.encode_pcm_to_opus(
|
opus = self.opus_encoder.encode_pcm_to_opus(
|
||||||
frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
|
frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
|
||||||
)
|
)
|
||||||
|
|
||||||
if opus:
|
if opus:
|
||||||
opus_datas.extend(opus)
|
opus_datas.extend(opus)
|
||||||
|
|
||||||
return opus_datas
|
return opus_datas
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
logger.bind(tag=TAG).error(f"TTS request exception: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
@ -6,13 +6,13 @@ from datetime import datetime
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from core.utils.util import parse_string_to_list
|
from core.utils.util import parse_string_to_list
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
self.group_id = config.get("group_id")
|
self.group_id = config.get("group_id")
|
||||||
self.api_key = config.get("api_key")
|
self.api_key = config.get("api_key")
|
||||||
self.model = config.get("model")
|
self.model = config.get("model")
|
||||||
|
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
else:
|
else:
|
||||||
|
|
@ -25,6 +25,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
"pitch": 0,
|
"pitch": 0,
|
||||||
"emotion": "happy",
|
"emotion": "happy",
|
||||||
}
|
}
|
||||||
|
|
||||||
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
||||||
defult_audio_setting = {
|
defult_audio_setting = {
|
||||||
"sample_rate": 32000,
|
"sample_rate": 32000,
|
||||||
|
|
@ -32,14 +33,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
"format": "mp3",
|
"format": "mp3",
|
||||||
"channel": 1,
|
"channel": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
self.voice_setting = {
|
self.voice_setting = {
|
||||||
**default_voice_setting,
|
**default_voice_setting,
|
||||||
**config.get("voice_setting", {}),
|
**config.get("voice_setting", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.pronunciation_dict = {
|
self.pronunciation_dict = {
|
||||||
**default_pronunciation_dict,
|
**default_pronunciation_dict,
|
||||||
**config.get("pronunciation_dict", {}),
|
**config.get("pronunciation_dict", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
|
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
|
||||||
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
|
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
|
||||||
|
|
||||||
|
|
@ -78,10 +82,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
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:
|
if resp.json()["base_resp"]["status_code"] == 0:
|
||||||
data = resp.json()["data"]["audio"]
|
data = resp.json()["data"]["audio"]
|
||||||
audio_bytes = bytes.fromhex(data)
|
audio_bytes = bytes.fromhex(data)
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
with open(output_file, "wb") as file_to_save:
|
with open(output_file, "wb") as file_to_save:
|
||||||
file_to_save.write(audio_bytes)
|
file_to_save.write(audio_bytes)
|
||||||
|
|
@ -91,5 +97,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"{__name__} error: {e}")
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
|
||||||
|
|
@ -7,13 +7,13 @@ from typing import Iterator, Optional, Union
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from core.utils.util import parse_string_to_list
|
from core.utils.util import parse_string_to_list
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
self.group_id = config.get("group_id")
|
self.group_id = config.get("group_id")
|
||||||
self.api_key = config.get("api_key")
|
self.api_key = config.get("api_key")
|
||||||
self.model = config.get("model")
|
self.model = config.get("model")
|
||||||
|
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
self.voice = config.get("private_voice")
|
self.voice = config.get("private_voice")
|
||||||
else:
|
else:
|
||||||
|
|
@ -26,6 +26,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
"pitch": 0,
|
"pitch": 0,
|
||||||
"emotion": "happy",
|
"emotion": "happy",
|
||||||
}
|
}
|
||||||
|
|
||||||
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
||||||
defult_audio_setting = {
|
defult_audio_setting = {
|
||||||
"sample_rate": 32000,
|
"sample_rate": 32000,
|
||||||
|
|
@ -33,14 +34,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
"format": "mp3",
|
"format": "mp3",
|
||||||
"channel": 1,
|
"channel": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
self.voice_setting = {
|
self.voice_setting = {
|
||||||
**default_voice_setting,
|
**default_voice_setting,
|
||||||
**config.get("voice_setting", {}),
|
**config.get("voice_setting", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.pronunciation_dict = {
|
self.pronunciation_dict = {
|
||||||
**default_pronunciation_dict,
|
**default_pronunciation_dict,
|
||||||
**config.get("pronunciation_dict", {}),
|
**config.get("pronunciation_dict", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
|
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
|
||||||
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
|
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
|
||||||
|
|
||||||
|
|
@ -62,7 +66,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
)
|
)
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
"""非流式语音合成(保留原有实现)"""
|
"""Non-streaming speech synthesis (preserves original implementation)"""
|
||||||
request_json = {
|
request_json = {
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
"text": text,
|
"text": text,
|
||||||
|
|
@ -80,9 +84,11 @@ class TTSProvider(TTSProviderBase):
|
||||||
resp = requests.post(
|
resp = requests.post(
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
self.api_url, json.dumps(request_json), headers=self.header
|
||||||
)
|
)
|
||||||
|
|
||||||
if resp.json()["base_resp"]["status_code"] == 0:
|
if resp.json()["base_resp"]["status_code"] == 0:
|
||||||
data = resp.json()["data"]["audio"]
|
data = resp.json()["data"]["audio"]
|
||||||
audio_bytes = bytes.fromhex(data)
|
audio_bytes = bytes.fromhex(data)
|
||||||
|
|
||||||
if output_file:
|
if output_file:
|
||||||
with open(output_file, "wb") as file_to_save:
|
with open(output_file, "wb") as file_to_save:
|
||||||
file_to_save.write(audio_bytes)
|
file_to_save.write(audio_bytes)
|
||||||
|
|
@ -92,6 +98,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"{__name__} error: {e}")
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
||||||
|
|
@ -101,10 +108,11 @@ class TTSProvider(TTSProviderBase):
|
||||||
chunk_callback: Optional[callable] = None
|
chunk_callback: Optional[callable] = None
|
||||||
) -> Iterator[bytes]:
|
) -> Iterator[bytes]:
|
||||||
"""
|
"""
|
||||||
流式语音合成方法
|
Streaming speech synthesis method
|
||||||
:param text: 要合成的文本
|
|
||||||
:param chunk_callback: 可选的回调函数,用于处理每个音频块
|
:param text: Text to synthesize
|
||||||
:return: 生成器,每次产生一个音频数据块(bytes)
|
:param chunk_callback: Optional callback function to process each audio chunk
|
||||||
|
:return: Generator that yields an audio data chunk (bytes) each time
|
||||||
"""
|
"""
|
||||||
request_json = {
|
request_json = {
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
|
|
@ -126,32 +134,31 @@ class TTSProvider(TTSProviderBase):
|
||||||
headers=self.header,
|
headers=self.header,
|
||||||
stream=True
|
stream=True
|
||||||
) as response:
|
) as response:
|
||||||
|
# Check HTTP status code
|
||||||
# 检查HTTP状态码
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"HTTP error: {response.status_code}, response: {response.text}"
|
f"HTTP error: {response.status_code}, response: {response.text}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 处理流式响应
|
# Process streaming response
|
||||||
for line in response.iter_lines():
|
for line in response.iter_lines():
|
||||||
if line: # 过滤空行
|
if line: # Filter empty lines
|
||||||
# 检查是否为数据行 (SSE格式)
|
# Check if it's a data line (SSE format)
|
||||||
if line.startswith(b'data:'):
|
if line.startswith(b'data:'):
|
||||||
try:
|
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:
|
if data.get("base_resp", {}).get("status_code", -1) != 0:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"API error: {data.get('base_resp', {}).get('status_msg')}"
|
f"API error: {data.get('base_resp', {}).get('status_msg')}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 跳过非音频数据块
|
# Skip non-audio data chunks
|
||||||
if "extra_info" in data:
|
if "extra_info" in data:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 提取音频数据
|
# Extract audio data
|
||||||
audio_hex = data.get("data", {}).get("audio")
|
audio_hex = data.get("data", {}).get("audio")
|
||||||
if audio_hex:
|
if audio_hex:
|
||||||
audio_chunk = bytes.fromhex(audio_hex)
|
audio_chunk = bytes.fromhex(audio_hex)
|
||||||
|
|
@ -160,7 +167,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
yield audio_chunk
|
yield audio_chunk
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
# 忽略JSON解析错误(可能是心跳包等)
|
# Ignore JSON parsing errors (might be heartbeat packets, etc.)
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise e
|
raise e
|
||||||
|
|
@ -175,18 +182,19 @@ class TTSProvider(TTSProviderBase):
|
||||||
progress_callback: Optional[callable] = None
|
progress_callback: Optional[callable] = None
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
流式合成并保存到文件
|
Stream synthesis and save to file
|
||||||
:param text: 要合成的文本
|
|
||||||
:param output_file: 输出文件路径,如果为None则自动生成
|
:param text: Text to synthesize
|
||||||
:param progress_callback: 可选的回调函数,接收已写入的字节数
|
:param output_file: Output file path, auto-generated if None
|
||||||
:return: 保存的文件路径
|
:param progress_callback: Optional callback function that receives bytes written
|
||||||
|
:return: Saved file path
|
||||||
"""
|
"""
|
||||||
if not output_file:
|
if not output_file:
|
||||||
output_file = self.generate_filename(extension=f".{self.audio_file_type}")
|
output_file = self.generate_filename(extension=f".{self.audio_file_type}")
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
||||||
|
|
||||||
total_bytes = 0
|
total_bytes = 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(output_file, "wb") as audio_file:
|
with open(output_file, "wb") as audio_file:
|
||||||
for audio_chunk in self.text_to_speak_stream(text):
|
for audio_chunk in self.text_to_speak_stream(text):
|
||||||
|
|
@ -195,18 +203,21 @@ class TTSProvider(TTSProviderBase):
|
||||||
total_bytes += len(audio_chunk)
|
total_bytes += len(audio_chunk)
|
||||||
if progress_callback:
|
if progress_callback:
|
||||||
progress_callback(total_bytes)
|
progress_callback(total_bytes)
|
||||||
|
|
||||||
return output_file
|
return output_file
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 清理可能创建的不完整文件
|
# Clean up potentially created incomplete file
|
||||||
if os.path.exists(output_file):
|
if os.path.exists(output_file):
|
||||||
os.remove(output_file)
|
os.remove(output_file)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
def stream_to_audio_player(self, text: str, player_command: list = None):
|
def stream_to_audio_player(self, text: str, player_command: list = None):
|
||||||
"""
|
"""
|
||||||
流式合成并直接播放音频
|
Stream synthesis and play audio directly
|
||||||
:param text: 要合成的文本
|
|
||||||
:param player_command: 音频播放器命令,默认使用mpv
|
:param text: Text to synthesize
|
||||||
|
:param player_command: Audio player command, defaults to mpv
|
||||||
"""
|
"""
|
||||||
if player_command is None:
|
if player_command is None:
|
||||||
player_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"]
|
player_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"]
|
||||||
|
|
@ -226,5 +237,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
player_process.stdin.close()
|
player_process.stdin.close()
|
||||||
player_process.wait()
|
player_process.wait()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"Audio player error: {e}")
|
raise Exception(f"Audio player error: {e}")
|
||||||
|
|
@ -16,7 +16,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.api_key = config.get("api_key")
|
self.api_key = config.get("api_key")
|
||||||
self.model = config.get("model")
|
self.model = config.get("model")
|
||||||
|
|
||||||
# 初始化语音设置
|
# Initialize voice settings
|
||||||
default_voice_setting = {
|
default_voice_setting = {
|
||||||
"voice_id": "female-shaonv",
|
"voice_id": "female-shaonv",
|
||||||
"speed": 1,
|
"speed": 1,
|
||||||
|
|
@ -24,7 +24,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
"pitch": 0,
|
"pitch": 0,
|
||||||
"emotion": "happy",
|
"emotion": "happy",
|
||||||
}
|
}
|
||||||
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
|
||||||
|
default_pronunciation_dict = {
|
||||||
|
"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
||||||
default_audio_setting = {
|
default_audio_setting = {
|
||||||
"sample_rate": 32000,
|
"sample_rate": 32000,
|
||||||
"bitrate": 128000,
|
"bitrate": 128000,
|
||||||
|
|
@ -32,44 +34,49 @@ class TTSProvider(TTSProviderBase):
|
||||||
"channel": 1,
|
"channel": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
# 合并配置
|
# Merge configurations
|
||||||
self.voice_setting = {
|
self.voice_setting = {
|
||||||
**default_voice_setting,
|
**default_voice_setting,
|
||||||
**config.get("voice_setting", {}),
|
**config.get("voice_setting", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.pronunciation_dict = {
|
self.pronunciation_dict = {
|
||||||
**default_pronunciation_dict,
|
**default_pronunciation_dict,
|
||||||
**config.get("pronunciation_dict", {}),
|
**config.get("pronunciation_dict", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
self.audio_setting = {
|
self.audio_setting = {
|
||||||
**default_audio_setting,
|
**default_audio_setting,
|
||||||
**config.get("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"):
|
if config.get("private_voice"):
|
||||||
self.voice_setting["voice_id"] = config.get("private_voice")
|
self.voice_setting["voice_id"] = config.get("private_voice")
|
||||||
elif config.get("voice_id"):
|
elif config.get("voice_id"):
|
||||||
self.voice_setting["voice_id"] = 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.ws_url = "wss://api.minimaxi.com/ws/v1/t2a_v2"
|
||||||
self.headers = {
|
self.headers = {
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
"GroupId": self.group_id
|
"GroupId": self.group_id
|
||||||
}
|
}
|
||||||
|
|
||||||
self.audio_file_type = self.audio_setting.get("format", "mp3")
|
self.audio_file_type = self.audio_setting.get("format", "mp3")
|
||||||
|
|
||||||
def generate_filename(self, extension=".mp3"):
|
def generate_filename(self, extension=".mp3"):
|
||||||
"""生成唯一的音频文件名"""
|
"""Generate unique audio filename"""
|
||||||
return os.path.join(
|
return os.path.join(
|
||||||
self.output_file,
|
self.output_file,
|
||||||
f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _establish_connection(self):
|
async def _establish_connection(self):
|
||||||
"""建立WebSocket连接"""
|
"""Establish WebSocket connection"""
|
||||||
ssl_context = ssl.create_default_context()
|
ssl_context = ssl.create_default_context()
|
||||||
ssl_context.check_hostname = False
|
ssl_context.check_hostname = False
|
||||||
ssl_context.verify_mode = ssl.CERT_NONE
|
ssl_context.verify_mode = ssl.CERT_NONE
|
||||||
|
|
@ -80,17 +87,19 @@ class TTSProvider(TTSProviderBase):
|
||||||
additional_headers=self.headers,
|
additional_headers=self.headers,
|
||||||
ssl=ssl_context
|
ssl=ssl_context
|
||||||
)
|
)
|
||||||
|
|
||||||
connected = json.loads(await ws.recv())
|
connected = json.loads(await ws.recv())
|
||||||
if connected.get("event") == "connected_success":
|
if connected.get("event") == "connected_success":
|
||||||
print("连接成功")
|
print("Connection successful")
|
||||||
return ws
|
return ws
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"连接失败: {e}")
|
print(f"Connection failed: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def _start_task(self, websocket):
|
async def _start_task(self, websocket):
|
||||||
"""发送任务开始请求"""
|
"""Send task start request"""
|
||||||
start_msg = {
|
start_msg = {
|
||||||
"event": "task_start",
|
"event": "task_start",
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
|
|
@ -108,7 +117,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
return response.get("event") == "task_started"
|
return response.get("event") == "task_started"
|
||||||
|
|
||||||
async def _continue_task(self, websocket, text):
|
async def _continue_task(self, websocket, text):
|
||||||
"""发送继续请求并收集音频数据"""
|
"""Send continue request and collect audio data"""
|
||||||
await websocket.send(json.dumps({
|
await websocket.send(json.dumps({
|
||||||
"event": "task_continue",
|
"event": "task_continue",
|
||||||
"text": text
|
"text": text
|
||||||
|
|
@ -121,36 +130,37 @@ class TTSProvider(TTSProviderBase):
|
||||||
audio_chunks.append(response["data"]["audio"])
|
audio_chunks.append(response["data"]["audio"])
|
||||||
if response.get("is_final"):
|
if response.get("is_final"):
|
||||||
break
|
break
|
||||||
|
|
||||||
return "".join(audio_chunks)
|
return "".join(audio_chunks)
|
||||||
|
|
||||||
async def _close_connection(self, websocket):
|
async def _close_connection(self, websocket):
|
||||||
"""关闭连接"""
|
"""Close connection"""
|
||||||
if websocket:
|
if websocket:
|
||||||
await websocket.send(json.dumps({"event": "task_finish"}))
|
await websocket.send(json.dumps({"event": "task_finish"}))
|
||||||
await websocket.close()
|
await websocket.close()
|
||||||
print("连接已关闭")
|
print("Connection closed")
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file=None):
|
async def text_to_speak(self, text, output_file=None):
|
||||||
"""主方法:文本转语音"""
|
"""Main method: text to speech"""
|
||||||
ws = await self._establish_connection()
|
ws = await self._establish_connection()
|
||||||
if not ws:
|
if not ws:
|
||||||
raise Exception("无法建立WebSocket连接")
|
raise Exception("Unable to establish WebSocket connection")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if not await self._start_task(ws):
|
if not await self._start_task(ws):
|
||||||
raise Exception("任务启动失败")
|
raise Exception("Task start failed")
|
||||||
|
|
||||||
hex_audio = await self._continue_task(ws, text)
|
hex_audio = await self._continue_task(ws, text)
|
||||||
audio_bytes = bytes.fromhex(hex_audio)
|
audio_bytes = bytes.fromhex(hex_audio)
|
||||||
|
|
||||||
# 保存到文件或返回二进制数据
|
# Save to file or return binary data
|
||||||
if output_file:
|
if output_file:
|
||||||
with open(output_file, "wb") as f:
|
with open(output_file, "wb") as f:
|
||||||
f.write(audio_bytes)
|
f.write(audio_bytes)
|
||||||
print(f"音频已保存为{output_file}")
|
print(f"Audio saved as {output_file}")
|
||||||
return output_file
|
return output_file
|
||||||
else:
|
else:
|
||||||
# 返回音频二进制数据(不播放)
|
# Return audio binary data (no playback)
|
||||||
return audio_bytes
|
return audio_bytes
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
|
@ -158,12 +168,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
"""测试用主函数"""
|
"""Test main function"""
|
||||||
# 示例配置
|
# Example configuration
|
||||||
config = {
|
config = {
|
||||||
"group_id": "YOUR_GROUP_ID", # 替换为实际的group_id
|
"group_id": "YOUR_GROUP_ID", # Replace with actual group_id
|
||||||
"api_key": "YOUR_API_KEY", # 替换为实际的api_key
|
"api_key": "YOUR_API_KEY", # Replace with actual api_key
|
||||||
"model": "your-model", # 替换为实际的模型名称
|
"model": "your-model", # Replace with actual model name
|
||||||
"voice_id": "male-qn-qingse",
|
"voice_id": "male-qn-qingse",
|
||||||
"voice_setting": {
|
"voice_setting": {
|
||||||
"speed": 1.2,
|
"speed": 1.2,
|
||||||
|
|
@ -173,8 +183,7 @@ async def main():
|
||||||
|
|
||||||
tts = TTSProvider(config, delete_audio_file=True)
|
tts = TTSProvider(config, delete_audio_file=True)
|
||||||
output_file = tts.generate_filename()
|
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__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
@ -11,7 +11,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
self.api_key = config.get("api_key")
|
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")
|
self.model = config.get("model", "tts-1")
|
||||||
if config.get("private_voice"):
|
if config.get("private_voice"):
|
||||||
self.voice = 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.response_format = config.get("format", "wav")
|
||||||
self.audio_file_type = config.get("format", "wav")
|
self.audio_file_type = config.get("format", "wav")
|
||||||
|
|
||||||
# 处理空字符串的情况
|
# Handle empty string case
|
||||||
speed = config.get("speed", "1.0")
|
speed = config.get("speed", "1.0")
|
||||||
self.speed = float(speed) if speed else 1.0
|
self.speed = float(speed) if speed else 1.0
|
||||||
|
|
||||||
self.output_file = config.get("output_dir", "tmp/")
|
self.output_file = config.get("output_dir", "tmp/")
|
||||||
|
|
||||||
model_key_msg = check_model_key("TTS", self.api_key)
|
model_key_msg = check_model_key("TTS", self.api_key)
|
||||||
if model_key_msg:
|
if model_key_msg:
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
@ -34,6 +35,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
}
|
}
|
||||||
|
|
||||||
data = {
|
data = {
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
"input": text,
|
"input": text,
|
||||||
|
|
@ -41,7 +43,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
"response_format": "wav",
|
"response_format": "wav",
|
||||||
"speed": self.speed,
|
"speed": self.speed,
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.post(self.api_url, json=data, headers=headers)
|
response = requests.post(self.api_url, json=data, headers=headers)
|
||||||
|
|
||||||
if response.status_code == 200:
|
if response.status_code == 200:
|
||||||
if output_file:
|
if output_file:
|
||||||
with open(output_file, "wb") as audio_file:
|
with open(output_file, "wb") as audio_file:
|
||||||
|
|
@ -50,5 +54,5 @@ class TTSProvider(TTSProviderBase):
|
||||||
return response.content
|
return response.content
|
||||||
else:
|
else:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"OpenAI TTS请求失败: {response.status_code} - {response.text}"
|
f"OpenAI TTS request failed: {response.status_code} - {response.text}"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue