Merge branch 'doubao-asr' into feat/doubao-asr-dev

This commit is contained in:
欣南科技 2025-02-21 09:58:05 +08:00 committed by GitHub
commit 25a4d4e0bb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 570 additions and 1025 deletions

View file

@ -37,11 +37,6 @@ RUN poetry install --no-root
# 从构建阶段复制虚拟环境和前端构建产物
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /app/manager/static/webui
# 下载模型文件(断点续传 + 自动重试)
RUN mkdir -p /app/model/SenseVoiceSmall && \
wget -O /app/model/SenseVoiceSmall/model.pt -c --tries=5 --waitretry=5 \
https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt
# 设置虚拟环境路径
ENV PATH="/app/.venv/bin:$PATH"

149
README.md
View file

@ -4,13 +4,15 @@
(中文 | [English](README_en.md))
本项目为开源智能硬件项目 [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) 提供后端服务。根据 [小智通信协议](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) 使用 `Python` 实现。
本项目为开源智能硬件项目 [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32)
提供后端服务。根据 [小智通信协议](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) 使用 `Python` 实现。
---
## 适用人群 👥
本项目需要配合 ESP32 硬件设备使用。如果您已经购买了 ESP32 相关硬件,且成功对接过虾哥部署的后端服务,并希望独立搭建自己的 `xiaozhi-esp32` 后端服务,那么本项目非常适合您。
本项目需要配合 ESP32 硬件设备使用。如果您已经购买了 ESP32 相关硬件,且成功对接过虾哥部署的后端服务,并希望独立搭建自己的
`xiaozhi-esp32` 后端服务,那么本项目非常适合您。
跳转到[使用方式](#使用方式-)
@ -26,7 +28,8 @@
## 系统要求与部署前提 🖥️
- **硬件**:一套兼容 `xiaozhi-esp32` 的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
- **硬件**:一套兼容 `xiaozhi-esp32`
的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
- **服务器**:至少 4 核 CPU、8G 内存的电脑或服务器。
- **固件编译**:请将后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译固件并烧录到设备上。
@ -56,7 +59,7 @@ server:
- **通信协议**
基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。
- **对话交互**
支持唤醒对话、手动对话及实时打断。
支持唤醒对话、手动对话及实时打断。长时间无对话时自动休眠
- **多语言识别**
支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。
- **LLM 模块**
@ -66,25 +69,27 @@ server:
### 正在开发 🚧
- 长时间无对话时自动休眠
- 对话记忆功能
- 多种心情模式
- 智控台webui
![图片](docs/images/webui.png)
---
## 本项目支持的平台/组件列表 📋
### LLM
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:----:|:-----------------------------:|:-------------------:|:--------:|:-----------------------------------------------------------------------------:|
| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) |
| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) |
| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) |
| LLM | OllamaLLM | ollama 接口调用 | 免费/自定义 | 需预先下载模型(`ollama pull`),服务地址:`http://localhost:11434` |
| LLM | DifyLLM | dify 接口调用 | 消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 |
| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) |
| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 |
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:---:|:------------------:|:---------------------:|:--------:|:-----------------------------------------------------------------:|
| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) |
| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) |
| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) |
| LLM | OllamaLLM | ollama 接口调用 | 免费/自定义 | 需预先下载模型(`ollama pull`),服务地址:`http://localhost:11434` |
| LLM | DifyLLM | dify 接口调用 | 消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 |
| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) |
| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 |
| LLM | Home Assistant | homeassistant语音助手接口调用 | 免费 | 需提供home assistant令牌 |
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
@ -92,30 +97,30 @@ server:
### TTS
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:----:|:-----------------------------------:|:---------------:|:-------------:|:-------------------------------------------------------------------------------------------------------------------------:|
| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 |
| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 |
| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav |
| TTS | CozeCnTTS | 接口调用 | 消耗 token | 需提供 Coze API key;输出格式为 wav |
| TTS | FishSpeech | 接口调用 | 免费/自定义 | 本地启动 TTS 服务;启动方法见配置文件内说明 |
| TTS | GPT_SOVITS_V2 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 |
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:---:|:----------------------:|:----:|:--------:|:-------------------------------------------------------------------------:|
| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 |
| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 |
| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav |
| TTS | CozeCnTTS | 接口调用 | 消耗 token | 需提供 Coze API key;输出格式为 wav |
| TTS | FishSpeech | 接口调用 | 免费/自定义 | 本地启动 TTS 服务;启动方法见配置文件内说明 |
| TTS | GPT_SOVITS_V2 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 |
---
### VAD
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:----:|:----------:|:---------:|:--------:|:----:|
| VAD | SileroVAD | 本地使用 | 免费 | |
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | 本地使用 | 免费 | |
---
### ASR
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:----:|:--------:|:---------:|:--------:|:----:|
| ASR | FunASR | 本地使用 | 免费 | |
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:---:|:------:|:----:|:----:|:--:|
| ASR | FunASR | 本地使用 | 免费 | |
---
@ -123,10 +128,10 @@ server:
### 一、[部署文档](./docs/Deployment.md)
1. **[本地源码运行](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C)**
适合熟悉 Conda 环境或希望从零搭建运行环境的用户。
对于对响应速度要求较高的场景,推荐使用本地源码运行方式以降低额外开销。
1.**[本地源码运行](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C)**
适合熟悉 Conda 环境或希望从零搭建运行环境的用户。
对于对响应速度要求较高的场景,推荐使用本地源码运行方式以降低额外开销。
### 二、[固件编译](./docs/firmware-build.md)
@ -145,11 +150,12 @@ server:
### 2、我想通过小智控制电灯、空调、远程开关机等操作 💡
建议:在配置文件中将 `LLM` 设置为 `DifyLLM`,并通过 `Dify` 编排智能体来实现相关控制。
建议:在配置文件中将 `LLM` 设置为 `HomeAssistant`,通过 调用`HomeAssistant`接口实现相关控制。
### 3、我说话很慢,停顿时小智老是抢话 🗣️
建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`):
```yaml
VAD:
SileroVAD:
@ -158,48 +164,79 @@ VAD:
min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大
```
### 4、如何提高小智对话响应速度? ⚡
### 4、为什么我说的话,小智识别出来很多韩文、日文、英文?🇰🇷
建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt`文件,如果没有就要下载,查看这里[下载语音识别模型文件](docs/Deployment.md#模型文件)
### 5、为什么会出现“TTS 任务出错 文件不存在”?📁
建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。
如果没有安装,就安装
```
conda install conda-forge::libopus
conda install conda-forge::ffmpeg
```
### 6、如何提高小智对话响应速度? ⚡
本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决“跑得动”的问题,再优化“跑得快”。
如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺):
#### LLM 类组件
| 影响因素 | 因素值 |
|:-----:|:----------------:|
| 测试地点 | 广东省广州市海珠区 |
| 测试时间 | 2025年2月19日 12:52 |
| 宽带运营商 | 中国联通 |
| 排名 | 组件名称 | 响应速度(ms) |
|:---:|:---------------:|:------------:|
| 1 | AliLLM | 630 |
| 2 | ChatGLMLLM | 2000 |
| 3 | DeepSeekLLM | 6800 |
测试方法:
1、把各组件的密钥配置上去,只有配置了密钥的组件才参与测试。
2、配置完密钥后,执行以下方法
```
测试地点:广东省佛山市禅城区
测试时间:2025年2月9日 16:12
宽带运营商:中国移动
测试方法:更换配置后,执行 core/utils/llm.py 文件
# 进入项目根目录,执行以下命令:
conda activate xiaozhi-esp32-server
python performance_tester.py
```
#### TTS 类组件
生成报告如下
| 排名 | 组件名称 | 响应速度(ms) |
|:---:|:--------------:|:------------:|
| 1 | DoubaoTTS | 645 |
| 2 | EdgeTTS | 1019 |
LLM 性能排行:
```
测试地点:广东省佛山市禅城区
测试时间:2025年2月9日 16:12
宽带运营商:中国移动
测试方法:更换配置后,执行 core/utils/tts.py 文件
```
| 模块名称 | 平均首Token时间 | 平均总响应时间 |
|:-----------|:-----------|:--------|
| AliLLM | 0.547s | 1.485s |
| ChatGLMLLM | 0.677s | 3.057s |
| OllamaLLM | 0.003s | 0.003s |
TTS 性能排行:
| 模块名称 | 平均合成时间 |
|----------------------|--------|
| EdgeTTS | 1.019s |
| DoubaoTTS | 0.503s |
| CosyVoiceSiliconflow | 3.732s |
推荐配置组合 (综合响应速度):
| 组合方案 | 综合得分 | LLM首Token | TTS合成 |
|-------------------------------|-------|-----------|--------|
| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s |
| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s |
| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s |
| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s |
| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s |
### 结论 🔍
`2025年2月9日`,如果我的电脑在`广东省佛山市禅城区`,且使用的是`中国移动`网络,我会优先使用:
`2025年2月19日`,如果我的电脑在`广东省广州市海珠区`,且使用的是`中国联通`网络,我会优先使用:
- LLM:`AliLLM`
- TTS:`DoubaoTTS`
### 5、更多问题,可联系我们反馈 💬
### 7、更多问题,可联系我们反馈 💬
![图片](docs/images/wechat.jpg)

View file

@ -1,14 +1,88 @@
# Vue 3 + Vite
# Vue 3 + Vite 项目配置文档
项目使用Vue3 + Vite实现
## 开发环境配置
在当前目录执行以下命令进入开发模式
### 使用 Poetry 配置开发环境
```
npm run dev
在项目根目录中执行以下命令安装 Python 依赖:
```sh
poetry install
```
执行以下命令打包
```
npm run build
```
---
## 安装项目依赖
你可以选择以下任意一个包管理工具(`npm`、`yarn` 或 `pnpm`)来管理项目依赖。
### 通用命令
- `install`:安装项目依赖
- `dev`:同时启动前后端
- `dev:ui`:启动前端
- `dev:api`:启动后端
- `dev:d`:在 Docker 环境下同时启动前后端
- `build`:打包项目
---
### 使用 npm
1. 安装依赖:
```sh
npm install
```
2. 启动开发模式:
```sh
npm run dev
```
3. 打包项目:
```sh
npm run build
```
### 使用 yarn
1. 安装依赖:
```sh
yarn install
```
2. 启动开发模式:
```sh
yarn dev
```
3. 打包项目:
```sh
yarn build
```
### 使用 pnpm
1. 安装依赖:
```sh
pnpm install
```
2. 启动开发模式:
```sh
pnpm run dev
```
3. 打包项目:
```sh
pnpm run build
```

View file

@ -6,7 +6,8 @@
"scripts": {
"dev": "concurrently -n 'Frontend,Backend' -c 'blue,green' 'yarn run dev:ui' 'npm run dev:api'",
"dev:ui": "vite",
"dev:api": "cd .. && poetry run python manager/http_server.py",
"dev:api": "cd .. && poetry run python app.py",
"dev:d": "docker exec xiaozhi-env poetry run python app.py",
"build": "vite build",
"preview": "vite preview"
},

View file

@ -157,6 +157,12 @@ LLM:
user_id: 你的user_id
base_url: "https://api.coze.cn/open_api/v2/chat" # 服务地址
personal_access_token: 你的coze个人令牌
HomeAssistant:
# 定义LLM API类型
type: homeassistant
base_url: http://homeassistant.local:8123
agent_id: conversation.chatgpt
api_key: 你的home assistant api访问令牌
TTS:
# 当前支持的type为edge、doubao,可自行适配
EdgeTTS:
@ -301,3 +307,10 @@ TTS:
# volume: 50
# speech_rate: 0
# pitch_rate: 0
# 模块测试配置
module_test:
test_sentences: # 自定义测试语句
- "你好,请介绍一下你自己"
- "What's the weather like today?"
- "请用100字概括量子计算的基本原理和应用前景"

View file

@ -0,0 +1,62 @@
import requests
from requests.exceptions import RequestException
from config.logger import setup_logging
from core.providers.llm.base import LLMProviderBase
TAG = __name__
logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.agent_id = config.get("agent_id") # 对应 agent_id
self.api_key = config.get("api_key")
self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url
self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
def response(self, session_id, dialogue):
print(dialogue)
try:
# home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
# 提取最后一个 role 为 'user' 的 content
input_text = None
if isinstance(dialogue, list): # 确保 dialogue 是一个列表
# 逆序遍历,找到最后一个 role 为 'user' 的消息
for message in reversed(dialogue):
if message.get("role") == "user": # 找到 role 为 'user' 的消息
input_text = message.get("content", "")
break # 找到后立即退出循环
# 构造请求数据
payload = {
"text": input_text,
"agent_id": self.agent_id,
"conversation_id": session_id # 使用 session_id 作为 conversation_id
}
# 设置请求头
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
# 发起 POST 请求
response = requests.post(self.api_url, json=payload, headers=headers)
# 检查请求是否成功
response.raise_for_status()
# 解析返回数据
data = response.json()
speech = data.get("response", {}).get("speech", {}).get("plain", {}).get("speech", "")
# 返回生成的内容
if speech:
yield speech
else:
logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
except RequestException as e:
logger.bind(tag=TAG).error(f"HTTP 请求错误: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"生成响应时出错: {e}")

View file

@ -9,8 +9,11 @@ from pydantic import BaseModel, Field, conint, model_validator
from typing_extensions import Annotated
from datetime import datetime
from typing import Literal
# from base import TTSProviderBase
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class ServeReferenceAudio(BaseModel):
@ -86,6 +89,9 @@ class TTSProvider(TTSProviderBase):
self.channels = config.get("channels",1)
self.rate = config.get("rate",44100)
self.api_key = config.get("api_key","YOUR_API_KEY")
if not self.api_key or "你" in self.api_key:
logger.bind(tag=TAG).error("你还没配置FishSpeech TTS的密钥,请在配置文件中配置密钥,否则无法正常工作")
return
self.normalize = config.get("normalize",True)
self.max_new_tokens = config.get("max_new_tokens",1024)
self.chunk_length = config.get("chunk_length",200)

View file

@ -1,7 +1,5 @@
import os
import uuid
import json
import base64
import requests
from datetime import datetime
from core.providers.tts.base import TTSProviderBase

View file

@ -10,3 +10,4 @@ services:
- "8002:8002"
volumes:
- ./data:/app/data
- ./models/SenseVoiceSmall/model.pt:/app/models/SenseVoiceSmall/model.pt

View file

@ -105,7 +105,7 @@ docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconf
-p 8000:8000 \
-p 8002:8002 \
-v ./:/app \
kalicyh/poetry:v3.10_xiaozhi
kalicyh/poetry:v3.10_latest
```
然后就和正常开发一样了

View file

@ -112,6 +112,15 @@ LLM:
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
`qvna`
huggingface地址:
```
https://huggingface.co/jinaai/jina-embeddings-v2-base-zh?clone=true
https://huggingface.co/FunAudioLLM/SenseVoiceSmall/tree/main?clone=true
```
镜像地址`https://hf-mirror.com/`
## 运行状态确认

BIN
docs/images/webui.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 KiB

After

Width:  |  Height:  |  Size: 462 KiB

View file

@ -38,7 +38,7 @@ class WebUI:
self.session_manager = SessionManager()
# 添加静态文件路径
self.static_path = os.path.join(root_dir, 'manager', 'static', 'webui')
self.static_path = os.path.join(root_dir, 'ZhiKongTaiWeb', 'dist')
self.setup_routes()
self.setup_cors()

287
performance_tester.py Normal file
View file

@ -0,0 +1,287 @@
import time
from tabulate import tabulate
from typing import Dict
from core.utils.llm import create_instance as create_llm_instance
from core.utils.tts import create_instance as create_tts_instance
from core.utils.util import read_config
import statistics
from config.settings import get_config_file
from concurrent.futures import ThreadPoolExecutor
import inspect
import os
import requests
import logging
# 设置全局日志级别为WARNING,抑制INFO级别日志
logging.basicConfig(level=logging.WARNING)
class PerformanceTester:
def __init__(self):
self.config = read_config(get_config_file())
# 从配置读取测试句子,如果不存在则使用默认
self.test_sentences = self.config.get("module_test", {}).get(
"test_sentences",
["你好,请介绍一下你自己", "What's the weather like today?",
"请用100字概括量子计算的基本原理和应用前景"]
)
self.results = {
"llm": {},
"tts": {},
"combinations": []
}
def _test_llm(self, llm_name: str, config: Dict) -> Dict:
"""测试单个LLM性能"""
try:
# 跳过未配置密钥的模块
if "api_key" in config and any(x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]):
print(f"🚫 跳过未配置的LLM: {llm_name}")
return {"errors": 1}
# 获取实际类型(兼容旧配置)
module_type = config.get('type', llm_name)
llm = create_llm_instance(module_type, config)
# 统一使用UTF-8编码
test_sentences = [s.encode('utf-8').decode('utf-8') for s in self.test_sentences]
total_time = 0
first_token_times = []
valid_times = []
for sentence in test_sentences:
sentence_start = time.time() # 记录整句开始时间
first_token_received = False
# 遍历响应流
for chunk in llm.response("perf_test", [{"role": "user", "content": sentence}]):
if not first_token_received and chunk.strip() != '':
first_token_times.append(time.time() - sentence_start)
first_token_received = True
# 计算整句耗时
sentence_duration = time.time() - sentence_start
total_time += sentence_duration
valid_times.append(sentence_duration)
# 新增有效性检查
if len(first_token_times) == 0 or len(valid_times) == 0:
print(f"⚠️ {llm_name} 无有效数据,可能配置错误")
return {"errors": 1}
# 过滤异常数据(超过3倍标准差)
mean = statistics.mean(valid_times)
stdev = statistics.stdev(valid_times) if len(valid_times) > 1 else 0
filtered_times = [t for t in valid_times if t <= mean + 3*stdev]
# 当有效数据不足时标记错误
if len(filtered_times) < len(test_sentences) * 0.5:
print(f"⚠️ {llm_name} 有效数据不足,可能网络不稳定")
return {"errors": 1}
return {
"avg_response": total_time / len(test_sentences),
"avg_first_token": sum(first_token_times)/len(first_token_times),
"std_first_token": statistics.stdev(first_token_times) if len(first_token_times) > 1 else 0,
"std_response": statistics.stdev(valid_times) if len(valid_times) > 1 else 0,
"errors": 0
}
except Exception as e:
print(f"LLM {llm_name} 测试失败: {str(e)}")
return {"errors": 1}
def _test_tts(self, tts_name: str, config: Dict) -> Dict:
"""测试单个TTS性能"""
try:
# 关闭详细日志
logging.getLogger("core.providers.tts.base").setLevel(logging.WARNING)
# 跳过未配置密钥的模块
token_fields = ["access_token", "api_key", "token"]
if any(field in config and any(x in config[field] for x in ["你的", "placeholder"]) for field in token_fields):
print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过")
return {"errors": 1}
# 获取实际类型(兼容旧配置)
module_type = config.get('type', tts_name)
tts = create_tts_instance(
module_type,
config,
delete_audio_file=True # 确保参数名称正确
)
# 简化后的输出
print(f"\n🎵 正在测试 TTS: {tts_name}")
print(f"🔊 测试 {tts_name}:", end="", flush=True)
# 连接测试
test_conn = tts.to_tts("连接测试")
if not os.path.exists(test_conn):
print("❌ 连接失败")
return {"errors": 1}
else:
print("✅")
total_time = 0
test_count = len(self.test_sentences[:2])
for i, sentence in enumerate(self.test_sentences[:2], 1):
start = time.time()
file_path = tts.to_tts(sentence)
duration = time.time() - start
total_time += duration
# 显示简单的进度标识
if os.path.exists(file_path):
print(f"✓[{i}/{test_count}]", end="", flush=True)
else:
print(f"✗[{i}/{test_count}]", end="", flush=True)
print() # 换行
return {"avg_time": total_time / test_count, "errors": 0}
except requests.exceptions.ConnectionError:
print(f"\n⛔ {tts_name} 无法连接服务端")
return {"errors": 1}
except Exception as e:
print(f"\n⚠️ {tts_name} 测试失败: {str(e)}")
return {"errors": 1}
def run(self):
"""执行全量测试并自动跳过未配置的模块"""
print("🔍 开始自动检测已配置的模块...")
# 测试所有LLM
for llm_name, config in self.config.get("LLM", {}).items():
# 特殊处理CozeLLM的配置检查
if llm_name == "CozeLLM":
if any(x in config.get("bot_id", "") for x in ["你的"]) \
or any(x in config.get("user_id", "") for x in ["你的"]):
print(f"⏭️ LLM {llm_name} 未配置bot_id/user_id,已跳过")
continue
# 通用的api_key配置检查
if "api_key" in config and any(x in config["api_key"] for x in ["你的", "placeholder"]):
print(f"⏭️ LLM {llm_name} 未配置api_key,已跳过")
continue
print(f"🚀 正在测试 LLM: {llm_name}")
self.results["llm"][llm_name] = self._test_llm(llm_name, config)
# 测试所有TTS
for tts_name, config in self.config.get("TTS", {}).items():
# 根据不同服务的token字段检测
token_fields = ["access_token", "api_key", "token"]
if any(field in config and any(x in config[field] for x in ["你的", "placeholder"]) for field in token_fields):
print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过")
continue
print(f"🎵 正在测试 TTS: {tts_name}")
self.results["tts"][tts_name] = self._test_tts(tts_name, config)
# 生成组合建议
self._generate_combinations()
self._print_results()
def _generate_combinations(self):
"""生成最佳组合建议"""
# 调整过滤条件,例如设为 >= 0.05
valid_llms = [
k for k, v in self.results["llm"].items()
if v["errors"] == 0 and v["avg_first_token"] >= 0.05
]
valid_tts = [k for k, v in self.results["tts"].items() if v["errors"] == 0]
for llm in valid_llms:
for tts in valid_tts:
llm_weight = 0.8 if self.results["llm"][llm]["avg_first_token"] < 1.0 else 0.6
tts_weight = 1 - llm_weight
score = (
self.results["llm"][llm]["avg_first_token"] * llm_weight +
self.results["tts"][tts]["avg_time"] * tts_weight
)
self.results["combinations"].append({
"llm": llm,
"tts": tts,
"score": score,
"details": {
"llm_first_token": self.results["llm"][llm]["avg_first_token"],
"tts_time": self.results["tts"][tts]["avg_time"]
}
})
# 按综合得分排序
self.results["combinations"].sort(key=lambda x: x["score"])
def _print_results(self):
"""控制台输出结果"""
# LLM结果表格
llm_table = []
for name, data in self.results["llm"].items():
if data["errors"] == 0:
llm_table.append([
name,
f"{data['avg_first_token']:.3f}s",
f"{data['avg_response']:.3f}s"
])
if llm_table:
print("\nLLM 性能排行:")
print(tabulate(
llm_table,
headers=["模块名称", "平均首Token时间", "平均总响应时间"],
tablefmt="github"
))
else:
print("\n⚠️ 没有可用的LLM模块进行测试。")
# TTS结果表格
tts_table = []
for name, data in self.results["tts"].items():
if data["errors"] == 0:
tts_table.append([
name,
f"{data['avg_time']:.3f}s"
])
if tts_table:
print("\nTTS 性能排行:")
print(tabulate(
tts_table,
headers=["模块名称", "平均合成时间"],
tablefmt="github"
))
else:
print("\n⚠️ 没有可用的TTS模块进行测试。")
# 最佳组合建议
if self.results["combinations"]:
print("\n推荐配置组合 (综合响应速度):")
combo_table = []
for combo in self.results["combinations"][:5]: # 显示前5名
combo_table.append([
f"{combo['llm']} + {combo['tts']}",
f"{combo['score']:.3f}",
f"{combo['details']['llm_first_token']:.3f}s",
f"{combo['details']['tts_time']:.3f}s"
])
print(tabulate(
combo_table,
headers=["组合方案", "综合得分", "LLM首Token", "TTS合成"],
tablefmt="github"
))
else:
print("\n⚠️ 没有可用的模块组合建议。")
def _execute_with_timeout(self, func, args=(), kwargs={}, timeout=None):
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(func, *args, **kwargs)
try:
result = future.result(timeout)
return list(result) if inspect.isgenerator(result) else result
except TimeoutError:
raise Exception("操作超时")
if __name__ == "__main__":
tester = PerformanceTester()
tester.run()

941
poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -26,8 +26,6 @@ ruamel-yaml = "0.18.10"
setuptools = "^75.8.0"
loguru = "^0.7.3"
opuslib-next = "^1.1.2"
sentence-transformers = {version = "3.4.1", extras = ["onnx"]}
[build-system]

View file

@ -15,5 +15,6 @@ aiohttp==3.9.3
aiohttp_cors==0.7.0
ormsgpack==1.7.0
ruamel.yaml==0.18.10
sentence-transformers[onnx]==3.4.1
loguru==0.7.3
requests>=2.0.0
#sentence-transformers[onnx]==3.4.1