Merge branch 'main' of https://github.com/bo-scnu/xiaozhi-esp32-server into dev
46
.github/workflows/docker-image.yml
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
name: Docker Image CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*.*.*' # 只在以 v 开头的标签推送时触发,例如 v1.0.0
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Release Docker image
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
packages: write
|
||||||
|
contents: write
|
||||||
|
id-token: write
|
||||||
|
issues: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out the repo
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Log in to the GitHub Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract version from tag
|
||||||
|
id: get_version
|
||||||
|
run: |
|
||||||
|
echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build_push
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
ghcr.io/${{ github.repository }}:${{ env.VERSION }}
|
||||||
|
ghcr.io/${{ github.repository }}:latest
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
2
.gitignore
vendored
|
|
@ -1,5 +1,6 @@
|
||||||
# Byte-compiled / optimized / DLL files
|
# Byte-compiled / optimized / DLL files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
.idea/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
*$py.class
|
*$py.class
|
||||||
|
|
||||||
|
|
@ -144,4 +145,5 @@ tmp
|
||||||
.config.yaml
|
.config.yaml
|
||||||
.secrets.yaml
|
.secrets.yaml
|
||||||
.private_config.yaml
|
.private_config.yaml
|
||||||
|
.env.development
|
||||||
docker-compose.yml
|
docker-compose.yml
|
||||||
|
|
|
||||||
51
Dockerfile
|
|
@ -1,46 +1,45 @@
|
||||||
# 第一阶段:前端构建
|
# 第一阶段:前端构建
|
||||||
FROM node:18 AS frontend-builder
|
|
||||||
|
FROM kalicyh/node:v18-alpine AS frontend-builder
|
||||||
|
|
||||||
WORKDIR /app/ZhiKongTaiWeb
|
WORKDIR /app/ZhiKongTaiWeb
|
||||||
|
|
||||||
RUN corepack enable && yarn config set registry https://registry.npmmirror.com
|
# RUN corepack enable && yarn config set registry https://registry.npmmirror.com
|
||||||
|
|
||||||
COPY ZhiKongTaiWeb/package.json ZhiKongTaiWeb/yarn.lock ./
|
COPY ZhiKongTaiWeb/package.json ZhiKongTaiWeb/yarn.lock ./
|
||||||
|
|
||||||
RUN mkdir node_modules && yarn install --frozen-lockfile
|
RUN yarn install --frozen-lockfile
|
||||||
|
|
||||||
COPY ZhiKongTaiWeb .
|
COPY ZhiKongTaiWeb .
|
||||||
RUN yarn build
|
RUN yarn build
|
||||||
|
|
||||||
# 第二阶段:构建 Python 依赖
|
# 第二阶段:构建 Python 依赖
|
||||||
FROM ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest AS builder
|
|
||||||
|
FROM kalicyh/poetry:v3.10_xiaozhi AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY pyproject.toml poetry.lock /app/
|
|
||||||
|
# 同时拷贝本地环境.venv
|
||||||
|
COPY . .
|
||||||
|
# 检查是否有缺失
|
||||||
RUN poetry install --no-root
|
RUN poetry install --no-root
|
||||||
|
|
||||||
# 第三阶段:生产镜像
|
# 使用清华源加速apt安装,该镜像内置所以注释
|
||||||
FROM python:3.10-slim
|
# RUN rm -rf /etc/apt/sources.list.d/* && \
|
||||||
|
# echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list && \
|
||||||
WORKDIR /opt/xiaozhi-esp32-server
|
# echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
|
# echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
# 使用清华源加速apt安装
|
# echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
RUN rm -rf /etc/apt/sources.list.d/* && \
|
# apt-get update && \
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list && \
|
# apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
# apt-get clean
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
|
||||||
apt-get update && \
|
|
||||||
apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
|
||||||
apt-get clean
|
|
||||||
|
|
||||||
# 从构建阶段复制虚拟环境和前端构建产物
|
# 从构建阶段复制虚拟环境和前端构建产物
|
||||||
COPY --from=builder /app/.venv /opt/venv
|
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /app/manager/static/webui
|
||||||
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /opt/xiaozhi-esp32-server/manager/static/webui
|
|
||||||
# 设置虚拟环境路径
|
|
||||||
ENV PATH="/opt/venv/bin:$PATH"
|
|
||||||
|
|
||||||
# 复制应用代码
|
# 设置虚拟环境路径
|
||||||
COPY . .
|
ENV PATH="/app/.venv/bin:$PATH"
|
||||||
|
|
||||||
# 启动应用
|
# 启动应用
|
||||||
CMD ["python", "app.py"]
|
ENTRYPOINT ["poetry", "run", "python"]
|
||||||
|
CMD ["app.py"]
|
||||||
51
Dockerfile-pip
Executable file
|
|
@ -0,0 +1,51 @@
|
||||||
|
# 第一阶段:前端构建
|
||||||
|
FROM node:18 AS frontend-builder
|
||||||
|
|
||||||
|
WORKDIR /app/ZhiKongTaiWeb
|
||||||
|
|
||||||
|
# 配置npm使用淘宝源
|
||||||
|
RUN npm config set registry https://registry.npmmirror.com
|
||||||
|
|
||||||
|
COPY ZhiKongTaiWeb/package*.json ./
|
||||||
|
|
||||||
|
# 安装axios依赖
|
||||||
|
RUN npm install axios
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
COPY ZhiKongTaiWeb .
|
||||||
|
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# 第二阶段:构建Python依赖
|
||||||
|
FROM python:3.10-slim AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
|
||||||
|
# 优化apt安装
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt \
|
||||||
|
-i https://mirrors.aliyun.com/pypi/simple/
|
||||||
|
|
||||||
|
# 第三阶段:生产镜像
|
||||||
|
FROM python:3.10-slim
|
||||||
|
|
||||||
|
WORKDIR /opt/xiaozhi-esp32-server
|
||||||
|
|
||||||
|
# 优化apt安装
|
||||||
|
RUN echo "deb https://mirrors.aliyun.com/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list && \
|
||||||
|
echo "deb https://mirrors.aliyun.com/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list && \
|
||||||
|
apt-get update && \
|
||||||
|
apt-get install -y --no-install-recommends libopus0 ffmpeg && \
|
||||||
|
apt-get clean && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# 从构建阶段复制Python包和前端构建产物
|
||||||
|
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
|
||||||
|
COPY --from=frontend-builder /app/ZhiKongTaiWeb/dist /opt/xiaozhi-esp32-server/manager/static/webui
|
||||||
|
|
||||||
|
# 复制应用代码
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# 启动应用
|
||||||
|
CMD ["python", "app.py"]
|
||||||
188
README.md
|
|
@ -4,29 +4,81 @@
|
||||||
|
|
||||||
(中文 | [English](README_en.md))
|
(中文 | [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` 后端服务,那么本项目非常适合您。
|
||||||
|
|
||||||
跳转到[使用方式](#使用方式-)
|
想看使用效果?请猛戳视频 🎥
|
||||||
|
|
||||||
想看使用效果?请猛戳这个视频 🎥
|
<table>
|
||||||
|
<tr>
|
||||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX">
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="小智esp32连接自己的后台模型" src="docs/images/demo.png" />
|
<img alt="小智esp32连接自己的后台模型" src="docs/images/demo1.png" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="自定义音色" src="docs/images/demo2.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="使用粤语交流" src="docs/images/demo3.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/av114036381327149" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="控制家电开关" src="docs/images/demo5.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1kgA2eYEQ9" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="成本最低配置" src="docs/images/demo4.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 系统要求与部署前提 🖥️
|
## 系统要求与部署前提 🖥️
|
||||||
|
|
||||||
- **硬件**:一套兼容 `xiaozhi-esp32` 的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
|
- **硬件**:一套兼容 `xiaozhi-esp32`
|
||||||
|
的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
|
||||||
- **服务器**:至少 4 核 CPU、8G 内存的电脑或服务器。
|
- **服务器**:至少 4 核 CPU、8G 内存的电脑或服务器。
|
||||||
- **固件编译**:请将后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译固件并烧录到设备上。
|
- **固件编译**:请将后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译固件并烧录到设备上。
|
||||||
|
|
||||||
|
|
@ -56,7 +108,7 @@ server:
|
||||||
- **通信协议**
|
- **通信协议**
|
||||||
基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。
|
基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。
|
||||||
- **对话交互**
|
- **对话交互**
|
||||||
支持唤醒对话、手动对话及实时打断。
|
支持唤醒对话、手动对话及实时打断。长时间无对话时自动休眠
|
||||||
- **多语言识别**
|
- **多语言识别**
|
||||||
支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。
|
支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。
|
||||||
- **LLM 模块**
|
- **LLM 模块**
|
||||||
|
|
@ -66,10 +118,11 @@ server:
|
||||||
|
|
||||||
### 正在开发 🚧
|
### 正在开发 🚧
|
||||||
|
|
||||||
- 长时间无对话时自动休眠
|
|
||||||
- 对话记忆功能
|
- 对话记忆功能
|
||||||
- 多种心情模式
|
- 多种心情模式
|
||||||
|
- 智控台webui
|
||||||
|
|
||||||
|

|
||||||
---
|
---
|
||||||
|
|
||||||
## 本项目支持的平台/组件列表 📋
|
## 本项目支持的平台/组件列表 📋
|
||||||
|
|
@ -77,7 +130,7 @@ server:
|
||||||
### LLM
|
### LLM
|
||||||
|
|
||||||
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|:----:|:-----------------------------:|:-------------------:|:--------:|:-----------------------------------------------------------------------------:|
|
|:---:|:------------------:|:---------------------:|:--------:|:-----------------------------------------------------------------:|
|
||||||
| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) |
|
| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) |
|
||||||
| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) |
|
| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) |
|
||||||
| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) |
|
| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) |
|
||||||
|
|
@ -85,6 +138,7 @@ server:
|
||||||
| LLM | DifyLLM | dify 接口调用 | 消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 |
|
| LLM | DifyLLM | dify 接口调用 | 消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 |
|
||||||
| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) |
|
| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) |
|
||||||
| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 |
|
| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 |
|
||||||
|
| LLM | Home Assistant | homeassistant语音助手接口调用 | 免费 | 需提供home assistant令牌 |
|
||||||
|
|
||||||
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
|
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
|
||||||
|
|
||||||
|
|
@ -93,7 +147,7 @@ server:
|
||||||
### TTS
|
### TTS
|
||||||
|
|
||||||
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|:----:|:-----------------------------------:|:---------------:|:-------------:|:-------------------------------------------------------------------------------------------------------------------------:|
|
|:---:|:----------------------:|:----:|:--------:|:-------------------------------------------------------------------------:|
|
||||||
| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 |
|
| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 |
|
||||||
| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 |
|
| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 |
|
||||||
| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav |
|
| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav |
|
||||||
|
|
@ -106,7 +160,7 @@ server:
|
||||||
### VAD
|
### VAD
|
||||||
|
|
||||||
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|:----:|:----------:|:---------:|:--------:|:----:|
|
|:---:|:---------:|:----:|:----:|:--:|
|
||||||
| VAD | SileroVAD | 本地使用 | 免费 | |
|
| VAD | SileroVAD | 本地使用 | 免费 | |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
@ -114,8 +168,9 @@ server:
|
||||||
### ASR
|
### ASR
|
||||||
|
|
||||||
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|:----:|:--------:|:---------:|:--------:|:----:|
|
|:---:|:---------:|:----:|:----:|:--:|
|
||||||
| ASR | FunASR | 本地使用 | 免费 | |
|
| ASR | FunASR | 本地使用 | 免费 | |
|
||||||
|
| ASR | DoubaoASR | 接口调用 | 收费 | |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -123,18 +178,21 @@ server:
|
||||||
|
|
||||||
### 一、[部署文档](./docs/Deployment.md)
|
### 一、[部署文档](./docs/Deployment.md)
|
||||||
|
|
||||||
[精简版部署文档](./docs/Deployment-silm.md)
|
|
||||||
|
|
||||||
本项目支持以下三种部署方式,您可根据实际需求选择:
|
本项目支持以下三种部署方式,您可根据实际需求选择:
|
||||||
|
|
||||||
1. **[Docker 快速部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%BF%AB%E9%80%9F%E9%83%A8%E7%BD%B2)**
|
1. [Docker 快速部署](./docs/Deployment.md)
|
||||||
适合快速体验,不需过多环境配置。
|
|
||||||
2. **[借助 Docker 环境运行部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2)**
|
|
||||||
适用于已安装 Docker 且希望对代码进行自定义修改的用户。
|
|
||||||
3. **[本地源码运行](./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 环境或希望从零搭建运行环境的用户。
|
|
||||||
对于对响应速度要求较高的场景,推荐使用本地源码运行方式以降低额外开销。
|
|
||||||
|
|
||||||
|
适合快速体验的普通用户,不需过多环境配置。缺点是,拉取镜像有点慢。
|
||||||
|
|
||||||
|
2. [借助 Docker 环境运行部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2)
|
||||||
|
|
||||||
|
适用于已安装 Docker 且希望对代码进行自定义修改的软件工程师。
|
||||||
|
|
||||||
|
3. [本地源码运行](./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)
|
### 二、[固件编译](./docs/firmware-build.md)
|
||||||
|
|
||||||
|
|
@ -153,11 +211,12 @@ server:
|
||||||
|
|
||||||
### 2、我想通过小智控制电灯、空调、远程开关机等操作 💡
|
### 2、我想通过小智控制电灯、空调、远程开关机等操作 💡
|
||||||
|
|
||||||
建议:在配置文件中将 `LLM` 设置为 `DifyLLM`,并通过 `Dify` 编排智能体来实现相关控制。
|
建议:在配置文件中将 `LLM` 设置为 `HomeAssistant`,通过 调用`HomeAssistant`接口实现相关控制。
|
||||||
|
|
||||||
### 3、我说话很慢,停顿时小智老是抢话 🗣️
|
### 3、我说话很慢,停顿时小智老是抢话 🗣️
|
||||||
|
|
||||||
建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`):
|
建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`):
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
VAD:
|
VAD:
|
||||||
SileroVAD:
|
SileroVAD:
|
||||||
|
|
@ -166,48 +225,81 @@ VAD:
|
||||||
min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大
|
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 |
|
1、把各组件的密钥配置上去,只有配置了密钥的组件才参与测试。
|
||||||
| 2 | ChatGLMLLM | 2000 |
|
|
||||||
| 3 | DeepSeekLLM | 6800 |
|
2、配置完密钥后,执行以下方法
|
||||||
|
|
||||||
```
|
```
|
||||||
测试地点:广东省佛山市禅城区
|
# 进入项目根目录,执行以下命令:
|
||||||
测试时间:2025年2月9日 16:12
|
conda activate xiaozhi-esp32-server
|
||||||
宽带运营商:中国移动
|
python performance_tester.py
|
||||||
测试方法:更换配置后,执行 core/utils/llm.py 文件
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### TTS 类组件
|
生成报告如下
|
||||||
|
|
||||||
| 排名 | 组件名称 | 响应速度(ms) |
|
LLM 性能排行:
|
||||||
|:---:|:--------------:|:------------:|
|
|
||||||
| 1 | DoubaoTTS | 645 |
|
|
||||||
| 2 | EdgeTTS | 1019 |
|
|
||||||
|
|
||||||
```
|
| 模块名称 | 平均首Token时间 | 平均总响应时间 |
|
||||||
测试地点:广东省佛山市禅城区
|
|:-----------|:-----------|:--------|
|
||||||
测试时间:2025年2月9日 16:12
|
| AliLLM | 0.547s | 1.485s |
|
||||||
宽带运营商:中国移动
|
| ChatGLMLLM | 0.677s | 3.057s |
|
||||||
测试方法:更换配置后,执行 core/utils/tts.py 文件
|
| 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`
|
- LLM:`AliLLM`
|
||||||
- TTS:`DoubaoTTS`
|
- TTS:`DoubaoTTS`
|
||||||
|
|
||||||
### 5、更多问题,可联系我们反馈 💬
|
### 7、更多问题,可联系我们反馈 💬
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,88 @@
|
||||||
# Vue 3 + Vite
|
# Vue 3 + Vite 项目配置文档
|
||||||
|
|
||||||
项目使用Vue3 + Vite实现
|
## 开发环境配置
|
||||||
|
|
||||||
在当前目录执行以下命令进入开发模式
|
### 使用 Poetry 配置开发环境
|
||||||
|
|
||||||
|
在项目根目录中执行以下命令安装 Python 依赖:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
poetry install
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 安装项目依赖
|
||||||
|
|
||||||
|
你可以选择以下任意一个包管理工具(`npm`、`yarn` 或 `pnpm`)来管理项目依赖。
|
||||||
|
|
||||||
|
### 通用命令
|
||||||
|
|
||||||
|
- `install`:安装项目依赖
|
||||||
|
- `dev`:同时启动前后端
|
||||||
|
- `dev:ui`:启动前端
|
||||||
|
- `dev:api`:启动后端
|
||||||
|
- `dev:d`:在 Docker 环境下同时启动前后端
|
||||||
|
- `build`:打包项目
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 使用 npm
|
||||||
|
|
||||||
|
1. 安装依赖:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 启动开发模式:
|
||||||
|
|
||||||
|
```sh
|
||||||
npm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
执行以下命令打包
|
3. 打包项目:
|
||||||
```
|
|
||||||
|
```sh
|
||||||
npm run build
|
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
|
||||||
|
```
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,10 @@
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"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 app.py",
|
||||||
|
"dev:d": "docker exec xiaozhi-env poetry run python app.py",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
|
|
@ -15,6 +18,7 @@
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-vue": "^5.1.4",
|
"@vitejs/plugin-vue": "^5.1.4",
|
||||||
|
"concurrently": "^9.1.2",
|
||||||
"vite": "^5.4.8"
|
"vite": "^5.4.8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -337,6 +337,18 @@
|
||||||
resolved "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.13.tgz#87b309a6379c22b926e696893237826f64339b6f"
|
resolved "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.13.tgz#87b309a6379c22b926e696893237826f64339b6f"
|
||||||
integrity sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==
|
integrity sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==
|
||||||
|
|
||||||
|
ansi-regex@^5.0.1:
|
||||||
|
version "5.0.1"
|
||||||
|
resolved "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
|
||||||
|
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
|
||||||
|
|
||||||
|
ansi-styles@^4.0.0, ansi-styles@^4.1.0:
|
||||||
|
version "4.3.0"
|
||||||
|
resolved "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937"
|
||||||
|
integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==
|
||||||
|
dependencies:
|
||||||
|
color-convert "^2.0.1"
|
||||||
|
|
||||||
asynckit@^0.4.0:
|
asynckit@^0.4.0:
|
||||||
version "0.4.0"
|
version "0.4.0"
|
||||||
resolved "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
|
resolved "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
|
||||||
|
|
@ -359,6 +371,35 @@ call-bind-apply-helpers@^1.0.1:
|
||||||
es-errors "^1.3.0"
|
es-errors "^1.3.0"
|
||||||
function-bind "^1.1.2"
|
function-bind "^1.1.2"
|
||||||
|
|
||||||
|
chalk@^4.1.2:
|
||||||
|
version "4.1.2"
|
||||||
|
resolved "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01"
|
||||||
|
integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==
|
||||||
|
dependencies:
|
||||||
|
ansi-styles "^4.1.0"
|
||||||
|
supports-color "^7.1.0"
|
||||||
|
|
||||||
|
cliui@^8.0.1:
|
||||||
|
version "8.0.1"
|
||||||
|
resolved "https://registry.npmmirror.com/cliui/-/cliui-8.0.1.tgz#0c04b075db02cbfe60dc8e6cf2f5486b1a3608aa"
|
||||||
|
integrity sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==
|
||||||
|
dependencies:
|
||||||
|
string-width "^4.2.0"
|
||||||
|
strip-ansi "^6.0.1"
|
||||||
|
wrap-ansi "^7.0.0"
|
||||||
|
|
||||||
|
color-convert@^2.0.1:
|
||||||
|
version "2.0.1"
|
||||||
|
resolved "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3"
|
||||||
|
integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==
|
||||||
|
dependencies:
|
||||||
|
color-name "~1.1.4"
|
||||||
|
|
||||||
|
color-name@~1.1.4:
|
||||||
|
version "1.1.4"
|
||||||
|
resolved "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
|
||||||
|
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
|
||||||
|
|
||||||
combined-stream@^1.0.8:
|
combined-stream@^1.0.8:
|
||||||
version "1.0.8"
|
version "1.0.8"
|
||||||
resolved "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
|
resolved "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
|
||||||
|
|
@ -366,6 +407,19 @@ combined-stream@^1.0.8:
|
||||||
dependencies:
|
dependencies:
|
||||||
delayed-stream "~1.0.0"
|
delayed-stream "~1.0.0"
|
||||||
|
|
||||||
|
concurrently@^9.1.2:
|
||||||
|
version "9.1.2"
|
||||||
|
resolved "https://registry.npmmirror.com/concurrently/-/concurrently-9.1.2.tgz#22d9109296961eaee773e12bfb1ce9a66bc9836c"
|
||||||
|
integrity sha512-H9MWcoPsYddwbOGM6difjVwVZHl63nwMEwDJG/L7VGtuaJhb12h2caPG2tVPWs7emuYix252iGfqOyrz1GczTQ==
|
||||||
|
dependencies:
|
||||||
|
chalk "^4.1.2"
|
||||||
|
lodash "^4.17.21"
|
||||||
|
rxjs "^7.8.1"
|
||||||
|
shell-quote "^1.8.1"
|
||||||
|
supports-color "^8.1.1"
|
||||||
|
tree-kill "^1.2.2"
|
||||||
|
yargs "^17.7.2"
|
||||||
|
|
||||||
csstype@^3.1.3:
|
csstype@^3.1.3:
|
||||||
version "3.1.3"
|
version "3.1.3"
|
||||||
resolved "https://registry.npmmirror.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81"
|
resolved "https://registry.npmmirror.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81"
|
||||||
|
|
@ -385,6 +439,11 @@ dunder-proto@^1.0.1:
|
||||||
es-errors "^1.3.0"
|
es-errors "^1.3.0"
|
||||||
gopd "^1.2.0"
|
gopd "^1.2.0"
|
||||||
|
|
||||||
|
emoji-regex@^8.0.0:
|
||||||
|
version "8.0.0"
|
||||||
|
resolved "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
|
||||||
|
integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
|
||||||
|
|
||||||
entities@^4.5.0:
|
entities@^4.5.0:
|
||||||
version "4.5.0"
|
version "4.5.0"
|
||||||
resolved "https://registry.npmmirror.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48"
|
resolved "https://registry.npmmirror.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48"
|
||||||
|
|
@ -446,6 +505,11 @@ esbuild@^0.21.3:
|
||||||
"@esbuild/win32-ia32" "0.21.5"
|
"@esbuild/win32-ia32" "0.21.5"
|
||||||
"@esbuild/win32-x64" "0.21.5"
|
"@esbuild/win32-x64" "0.21.5"
|
||||||
|
|
||||||
|
escalade@^3.1.1:
|
||||||
|
version "3.2.0"
|
||||||
|
resolved "https://registry.npmmirror.com/escalade/-/escalade-3.2.0.tgz#011a3f69856ba189dffa7dc8fcce99d2a87903e5"
|
||||||
|
integrity sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==
|
||||||
|
|
||||||
estree-walker@^2.0.2:
|
estree-walker@^2.0.2:
|
||||||
version "2.0.2"
|
version "2.0.2"
|
||||||
resolved "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz#52f010178c2a4c117a7757cfe942adb7d2da4cac"
|
resolved "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz#52f010178c2a4c117a7757cfe942adb7d2da4cac"
|
||||||
|
|
@ -476,6 +540,11 @@ function-bind@^1.1.2:
|
||||||
resolved "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c"
|
resolved "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c"
|
||||||
integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==
|
integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==
|
||||||
|
|
||||||
|
get-caller-file@^2.0.5:
|
||||||
|
version "2.0.5"
|
||||||
|
resolved "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e"
|
||||||
|
integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==
|
||||||
|
|
||||||
get-intrinsic@^1.2.6:
|
get-intrinsic@^1.2.6:
|
||||||
version "1.2.7"
|
version "1.2.7"
|
||||||
resolved "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.7.tgz#dcfcb33d3272e15f445d15124bc0a216189b9044"
|
resolved "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.2.7.tgz#dcfcb33d3272e15f445d15124bc0a216189b9044"
|
||||||
|
|
@ -505,6 +574,11 @@ gopd@^1.2.0:
|
||||||
resolved "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1"
|
resolved "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz#89f56b8217bdbc8802bd299df6d7f1081d7e51a1"
|
||||||
integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==
|
integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==
|
||||||
|
|
||||||
|
has-flag@^4.0.0:
|
||||||
|
version "4.0.0"
|
||||||
|
resolved "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b"
|
||||||
|
integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==
|
||||||
|
|
||||||
has-symbols@^1.0.3, has-symbols@^1.1.0:
|
has-symbols@^1.0.3, has-symbols@^1.1.0:
|
||||||
version "1.1.0"
|
version "1.1.0"
|
||||||
resolved "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338"
|
resolved "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz#fc9c6a783a084951d0b971fe1018de813707a338"
|
||||||
|
|
@ -524,6 +598,16 @@ hasown@^2.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
function-bind "^1.1.2"
|
function-bind "^1.1.2"
|
||||||
|
|
||||||
|
is-fullwidth-code-point@^3.0.0:
|
||||||
|
version "3.0.0"
|
||||||
|
resolved "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
|
||||||
|
integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
|
||||||
|
|
||||||
|
lodash@^4.17.21:
|
||||||
|
version "4.17.21"
|
||||||
|
resolved "https://registry.npmmirror.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
|
||||||
|
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
|
||||||
|
|
||||||
magic-string@^0.30.11:
|
magic-string@^0.30.11:
|
||||||
version "0.30.17"
|
version "0.30.17"
|
||||||
resolved "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.17.tgz#450a449673d2460e5bbcfba9a61916a1714c7453"
|
resolved "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.17.tgz#450a449673d2460e5bbcfba9a61916a1714c7453"
|
||||||
|
|
@ -572,6 +656,11 @@ proxy-from-env@^1.1.0:
|
||||||
resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
|
resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
|
||||||
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
|
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
|
||||||
|
|
||||||
|
require-directory@^2.1.1:
|
||||||
|
version "2.1.1"
|
||||||
|
resolved "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"
|
||||||
|
integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==
|
||||||
|
|
||||||
rollup@^4.20.0:
|
rollup@^4.20.0:
|
||||||
version "4.34.7"
|
version "4.34.7"
|
||||||
resolved "https://registry.npmmirror.com/rollup/-/rollup-4.34.7.tgz#e00d8550688a616a3481c6446bb688d4c753ba8f"
|
resolved "https://registry.npmmirror.com/rollup/-/rollup-4.34.7.tgz#e00d8550688a616a3481c6446bb688d4c753ba8f"
|
||||||
|
|
@ -600,11 +689,63 @@ rollup@^4.20.0:
|
||||||
"@rollup/rollup-win32-x64-msvc" "4.34.7"
|
"@rollup/rollup-win32-x64-msvc" "4.34.7"
|
||||||
fsevents "~2.3.2"
|
fsevents "~2.3.2"
|
||||||
|
|
||||||
|
rxjs@^7.8.1:
|
||||||
|
version "7.8.1"
|
||||||
|
resolved "https://registry.npmmirror.com/rxjs/-/rxjs-7.8.1.tgz#6f6f3d99ea8044291efd92e7c7fcf562c4057543"
|
||||||
|
integrity sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==
|
||||||
|
dependencies:
|
||||||
|
tslib "^2.1.0"
|
||||||
|
|
||||||
|
shell-quote@^1.8.1:
|
||||||
|
version "1.8.2"
|
||||||
|
resolved "https://registry.npmmirror.com/shell-quote/-/shell-quote-1.8.2.tgz#d2d83e057959d53ec261311e9e9b8f51dcb2934a"
|
||||||
|
integrity sha512-AzqKpGKjrj7EM6rKVQEPpB288oCfnrEIuyoT9cyF4nmGa7V8Zk6f7RRqYisX8X9m+Q7bd632aZW4ky7EhbQztA==
|
||||||
|
|
||||||
source-map-js@^1.2.0, source-map-js@^1.2.1:
|
source-map-js@^1.2.0, source-map-js@^1.2.1:
|
||||||
version "1.2.1"
|
version "1.2.1"
|
||||||
resolved "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz#1ce5650fddd87abc099eda37dcff024c2667ae46"
|
resolved "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz#1ce5650fddd87abc099eda37dcff024c2667ae46"
|
||||||
integrity sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==
|
integrity sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==
|
||||||
|
|
||||||
|
string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
|
||||||
|
version "4.2.3"
|
||||||
|
resolved "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
||||||
|
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||||
|
dependencies:
|
||||||
|
emoji-regex "^8.0.0"
|
||||||
|
is-fullwidth-code-point "^3.0.0"
|
||||||
|
strip-ansi "^6.0.1"
|
||||||
|
|
||||||
|
strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
||||||
|
version "6.0.1"
|
||||||
|
resolved "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
||||||
|
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||||
|
dependencies:
|
||||||
|
ansi-regex "^5.0.1"
|
||||||
|
|
||||||
|
supports-color@^7.1.0:
|
||||||
|
version "7.2.0"
|
||||||
|
resolved "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da"
|
||||||
|
integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==
|
||||||
|
dependencies:
|
||||||
|
has-flag "^4.0.0"
|
||||||
|
|
||||||
|
supports-color@^8.1.1:
|
||||||
|
version "8.1.1"
|
||||||
|
resolved "https://registry.npmmirror.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c"
|
||||||
|
integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==
|
||||||
|
dependencies:
|
||||||
|
has-flag "^4.0.0"
|
||||||
|
|
||||||
|
tree-kill@^1.2.2:
|
||||||
|
version "1.2.2"
|
||||||
|
resolved "https://registry.npmmirror.com/tree-kill/-/tree-kill-1.2.2.tgz#4ca09a9092c88b73a7cdc5e8a01b507b0790a0cc"
|
||||||
|
integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==
|
||||||
|
|
||||||
|
tslib@^2.1.0:
|
||||||
|
version "2.8.1"
|
||||||
|
resolved "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f"
|
||||||
|
integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==
|
||||||
|
|
||||||
vite@^5.4.8:
|
vite@^5.4.8:
|
||||||
version "5.4.14"
|
version "5.4.14"
|
||||||
resolved "https://registry.npmmirror.com/vite/-/vite-5.4.14.tgz#ff8255edb02134df180dcfca1916c37a6abe8408"
|
resolved "https://registry.npmmirror.com/vite/-/vite-5.4.14.tgz#ff8255edb02134df180dcfca1916c37a6abe8408"
|
||||||
|
|
@ -633,3 +774,35 @@ vue@^3.5.10:
|
||||||
"@vue/runtime-dom" "3.5.13"
|
"@vue/runtime-dom" "3.5.13"
|
||||||
"@vue/server-renderer" "3.5.13"
|
"@vue/server-renderer" "3.5.13"
|
||||||
"@vue/shared" "3.5.13"
|
"@vue/shared" "3.5.13"
|
||||||
|
|
||||||
|
wrap-ansi@^7.0.0:
|
||||||
|
version "7.0.0"
|
||||||
|
resolved "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
||||||
|
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||||
|
dependencies:
|
||||||
|
ansi-styles "^4.0.0"
|
||||||
|
string-width "^4.1.0"
|
||||||
|
strip-ansi "^6.0.0"
|
||||||
|
|
||||||
|
y18n@^5.0.5:
|
||||||
|
version "5.0.8"
|
||||||
|
resolved "https://registry.npmmirror.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"
|
||||||
|
integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==
|
||||||
|
|
||||||
|
yargs-parser@^21.1.1:
|
||||||
|
version "21.1.1"
|
||||||
|
resolved "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35"
|
||||||
|
integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==
|
||||||
|
|
||||||
|
yargs@^17.7.2:
|
||||||
|
version "17.7.2"
|
||||||
|
resolved "https://registry.npmmirror.com/yargs/-/yargs-17.7.2.tgz#991df39aca675a192b816e1e0363f9d75d2aa269"
|
||||||
|
integrity sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==
|
||||||
|
dependencies:
|
||||||
|
cliui "^8.0.1"
|
||||||
|
escalade "^3.1.1"
|
||||||
|
get-caller-file "^2.0.5"
|
||||||
|
require-directory "^2.1.1"
|
||||||
|
string-width "^4.2.3"
|
||||||
|
y18n "^5.0.5"
|
||||||
|
yargs-parser "^21.1.1"
|
||||||
|
|
|
||||||
88
config.yaml
|
|
@ -22,6 +22,19 @@ server:
|
||||||
# 可选:设备白名单,如果设置了白名单,那么白名单的机器无论是什么token都可以连接。
|
# 可选:设备白名单,如果设置了白名单,那么白名单的机器无论是什么token都可以连接。
|
||||||
#allowed_devices:
|
#allowed_devices:
|
||||||
# - "24:0A:C4:1D:3B:F0" # MAC地址列表
|
# - "24:0A:C4:1D:3B:F0" # MAC地址列表
|
||||||
|
log:
|
||||||
|
# 设置控制台输出的日志格式,时间、日志级别、标签、消息
|
||||||
|
log_format: "<green>{time:YY-MM-DD HH:mm:ss}</green>[<light-blue>{extra[tag]}</light-blue>] - <level>{level}</level> - <light-green>{message}</light-green>"
|
||||||
|
# 设置日志文件输出的格式,时间、日志级别、标签、消息
|
||||||
|
log_format_simple: "{time:YYYY-MM-DD HH:mm:ss} - {name} - {level} - {extra[tag]} - {message}"
|
||||||
|
# 设置日志等级:INFO、DEBUG
|
||||||
|
log_level: INFO
|
||||||
|
# 设置日志路径
|
||||||
|
log_dir: tmp
|
||||||
|
# 设置日志文件
|
||||||
|
log_file: "server.log"
|
||||||
|
# 设置数据文件路径
|
||||||
|
data_dir: data
|
||||||
manager:
|
manager:
|
||||||
# 是否启用管理后台
|
# 是否启用管理后台
|
||||||
# 目前这个模块还在开发中,建议:不要修改enabled选项
|
# 目前这个模块还在开发中,建议:不要修改enabled选项
|
||||||
|
|
@ -68,9 +81,15 @@ selected_module:
|
||||||
|
|
||||||
ASR:
|
ASR:
|
||||||
FunASR:
|
FunASR:
|
||||||
|
type: fun_local
|
||||||
model_dir: models/SenseVoiceSmall
|
model_dir: models/SenseVoiceSmall
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
|
DoubaoASR:
|
||||||
|
type: doubao
|
||||||
|
appid: 你的火山引擎语音合成服务appid
|
||||||
|
access_token: 你的火山引擎语音合成服务access_token
|
||||||
|
cluster: volcengine_input_common
|
||||||
|
output_dir: tmp/
|
||||||
VAD:
|
VAD:
|
||||||
SileroVAD:
|
SileroVAD:
|
||||||
threshold: 0.5
|
threshold: 0.5
|
||||||
|
|
@ -128,11 +147,6 @@ LLM:
|
||||||
user_id: 你的user_id
|
user_id: 你的user_id
|
||||||
base_url: "https://api.coze.cn/open_api/v2/chat" # 服务地址
|
base_url: "https://api.coze.cn/open_api/v2/chat" # 服务地址
|
||||||
personal_access_token: 你的coze个人令牌
|
personal_access_token: 你的coze个人令牌
|
||||||
vLLm:
|
|
||||||
type: vllm
|
|
||||||
base_url: http://localhost:8000
|
|
||||||
model_name: "Qwen/Qwen2.5-1.5B-Instruct"
|
|
||||||
|
|
||||||
TTS:
|
TTS:
|
||||||
# 当前支持的type为edge、doubao,可自行适配
|
# 当前支持的type为edge、doubao,可自行适配
|
||||||
EdgeTTS:
|
EdgeTTS:
|
||||||
|
|
@ -222,3 +236,65 @@ TTS:
|
||||||
parallel_infer: true
|
parallel_infer: true
|
||||||
repetition_penalty: 1.35
|
repetition_penalty: 1.35
|
||||||
aux_ref_audio_paths: []
|
aux_ref_audio_paths: []
|
||||||
|
MinimaxTTS:
|
||||||
|
# Minimax语音合成服务,需要先在minimax平台创建账户充值,并获取登录信息
|
||||||
|
# 平台地址:https://platform.minimaxi.com/
|
||||||
|
# 充值地址:https://platform.minimaxi.com/user-center/payment/balance
|
||||||
|
# group_id地址:https://platform.minimaxi.com/user-center/basic-information
|
||||||
|
# api_key地址:https://platform.minimaxi.com/user-center/basic-information/interface-key
|
||||||
|
# 定义TTS API类型
|
||||||
|
type: minimax
|
||||||
|
output_file: tmp/
|
||||||
|
group_id: 你的minimax平台groupID
|
||||||
|
api_key: 你的minimax平台接口密钥
|
||||||
|
model: "speech-01-turbo"
|
||||||
|
# 此处设置将优先于voice_setting中voice_id的设置;如都不设置,默认为 female-shaonv
|
||||||
|
voice_id: "female-shaonv"
|
||||||
|
# 以下可不用设置,使用默认设置
|
||||||
|
# voice_setting:
|
||||||
|
# voice_id: "male-qn-qingse"
|
||||||
|
# speed: 1
|
||||||
|
# vol: 1
|
||||||
|
# pitch: 0
|
||||||
|
# emotion: "happy"
|
||||||
|
# pronunciation_dict:
|
||||||
|
# tone:
|
||||||
|
# - "处理/(chu3)(li3)"
|
||||||
|
# - "危险/dangerous"
|
||||||
|
# audio_setting:
|
||||||
|
# sample_rate: 32000
|
||||||
|
# bitrate: 128000
|
||||||
|
# format: "mp3"
|
||||||
|
# channel: 1
|
||||||
|
# timber_weights:
|
||||||
|
# -
|
||||||
|
# voice_id: male-qn-qingse
|
||||||
|
# weight: 1
|
||||||
|
# -
|
||||||
|
# voice_id: female-shaonv
|
||||||
|
# weight: 1
|
||||||
|
# language_boost: auto
|
||||||
|
AliyunTTS:
|
||||||
|
# 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
|
||||||
|
# 平台地址:https://nls-portal.console.aliyun.com/
|
||||||
|
# appkey地址:https://nls-portal.console.aliyun.com/applist
|
||||||
|
# token地址:https://nls-portal.console.aliyun.com/overview
|
||||||
|
# 定义TTS API类型
|
||||||
|
type: aliyun
|
||||||
|
output_file: tmp/
|
||||||
|
appkey: 你的阿里云智能语音交互服务项目Appkey
|
||||||
|
token: 你的阿里云智能语音交互服务AccessToken
|
||||||
|
voice: xiaoyun
|
||||||
|
# 以下可不用设置,使用默认设置
|
||||||
|
# format: wav
|
||||||
|
# sample_rate: 16000
|
||||||
|
# volume: 50
|
||||||
|
# speech_rate: 0
|
||||||
|
# pitch_rate: 0
|
||||||
|
|
||||||
|
# 模块测试配置
|
||||||
|
module_test:
|
||||||
|
test_sentences: # 自定义测试语句
|
||||||
|
- "你好,请介绍一下你自己"
|
||||||
|
- "What's the weather like today?"
|
||||||
|
- "请用100字概括量子计算的基本原理和应用前景"
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,29 @@
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
from config.settings import load_config
|
||||||
|
|
||||||
|
def setup_logging():
|
||||||
|
"""从配置文件中读取日志配置,并设置日志输出格式和级别"""
|
||||||
|
config = load_config()
|
||||||
|
log_config = config["log"]
|
||||||
|
log_format = log_config.get("log_format", "<green>{time:YY-MM-DD HH:mm:ss}</green>[<light-blue>{extra[tag]}</light-blue>] - <level>{level}</level> - <light-green>{message}</light-green>")
|
||||||
|
log_format_simple = log_config.get("log_format_file", "{time:YYYY-MM-DD HH:mm:ss} - {name} - {level} - {extra[tag]} - {message}")
|
||||||
|
log_level = log_config.get("log_level", "INFO")
|
||||||
|
log_dir = log_config.get("log_dir", "tmp")
|
||||||
|
log_file = log_config.get("log_file", "server.log")
|
||||||
|
data_dir = log_config.get("data_dir", "data")
|
||||||
|
|
||||||
def setup_logging(log_dir='tmp', data_dir='data'):
|
|
||||||
"""配置全局彩色日志(不同区块不同标签)"""
|
|
||||||
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)
|
||||||
|
|
||||||
# 设置日志格式,时间、日志级别、标签、消息
|
|
||||||
log_format = (
|
|
||||||
"<green>{time:YYYY-MM-DD HH:mm:ss}</green>"
|
|
||||||
"[<light-blue>{extra[tag]}</light-blue>]"
|
|
||||||
" - <level>{level}</level> - "
|
|
||||||
"<light-green>{message}</light-green>"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 配置日志输出
|
# 配置日志输出
|
||||||
logger.remove()
|
logger.remove()
|
||||||
|
|
||||||
# 输出到控制台
|
# 输出到控制台
|
||||||
logger.add(sys.stdout, format=log_format, level="INFO")
|
logger.add(sys.stdout, format=log_format, level=log_level)
|
||||||
|
|
||||||
# 输出到文件
|
# 输出到文件
|
||||||
logger.add(os.path.join(log_dir, "server.log"), format="{time:YYYY-MM-DD HH:mm:ss} - {name} - {level} - {extra[tag]} - {message}", level="INFO")
|
logger.add(os.path.join(log_dir, log_file), format=log_format_simple, level=log_level)
|
||||||
|
|
||||||
return logger
|
return logger
|
||||||
|
|
|
||||||
|
|
@ -172,21 +172,12 @@ class PrivateConfig:
|
||||||
# 判断存在私有配置,并且self.device_id在私有配置中
|
# 判断存在私有配置,并且self.device_id在私有配置中
|
||||||
if not self.private_config:
|
if not self.private_config:
|
||||||
self.logger.bind(tag=TAG).error("Private config not found for device_id: {}", self.device_id)
|
self.logger.bind(tag=TAG).error("Private config not found for device_id: {}", self.device_id)
|
||||||
return None, None, None, None
|
return None, None
|
||||||
|
|
||||||
"""创建私有处理模块实例"""
|
"""创建私有处理模块实例"""
|
||||||
config = self.private_config
|
config = self.private_config
|
||||||
selected_modules = config['selected_module']
|
selected_modules = config['selected_module']
|
||||||
return (
|
return (
|
||||||
vad.create_instance(
|
|
||||||
selected_modules["VAD"],
|
|
||||||
config["VAD"][selected_modules["VAD"]]
|
|
||||||
),
|
|
||||||
asr.create_instance(
|
|
||||||
selected_modules["ASR"],
|
|
||||||
config["ASR"][selected_modules["ASR"]],
|
|
||||||
self.default_config.get("delete_audio", True) # Using default_config for global settings
|
|
||||||
),
|
|
||||||
llm.create_instance(
|
llm.create_instance(
|
||||||
selected_modules["LLM"]
|
selected_modules["LLM"]
|
||||||
if not 'type' in config["LLM"][selected_modules["LLM"]]
|
if not 'type' in config["LLM"][selected_modules["LLM"]]
|
||||||
|
|
|
||||||
|
|
@ -108,10 +108,8 @@ class ConnectionHandler:
|
||||||
if self.is_device_verified:
|
if self.is_device_verified:
|
||||||
await self.private_config.update_last_chat_time()
|
await self.private_config.update_last_chat_time()
|
||||||
|
|
||||||
vad, asr, llm, tts = self.private_config.create_private_instances()
|
llm, tts = self.private_config.create_private_instances()
|
||||||
if all([vad, asr, llm, tts]):
|
if all([llm, tts]):
|
||||||
self.vad = vad
|
|
||||||
self.asr = asr
|
|
||||||
self.llm = llm
|
self.llm = llm
|
||||||
self.tts = tts
|
self.tts = tts
|
||||||
self.logger.bind(tag=TAG).info(f"Loaded private config and instances for device {device_id}")
|
self.logger.bind(tag=TAG).info(f"Loaded private config and instances for device {device_id}")
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,11 @@ async def handleAudioMessage(conn, audio):
|
||||||
if conn.client_voice_stop:
|
if conn.client_voice_stop:
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
conn.asr_server_receive = False
|
conn.asr_server_receive = False
|
||||||
text, file_path = conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
|
# 音频太短了,无法识别
|
||||||
|
if len(conn.asr_audio) < 3:
|
||||||
|
conn.asr_server_receive = True
|
||||||
|
else:
|
||||||
|
text, file_path = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
|
||||||
logger.bind(tag=TAG).info(f"识别文本: {text}")
|
logger.bind(tag=TAG).info(f"识别文本: {text}")
|
||||||
text_len, text_without_punctuation = remove_punctuation_and_length(text)
|
text_len, text_without_punctuation = remove_punctuation_and_length(text)
|
||||||
if text_len <= conn.max_cmd_length and await handleCMDMessage(conn, text_without_punctuation):
|
if text_len <= conn.max_cmd_length and await handleCMDMessage(conn, text_without_punctuation):
|
||||||
|
|
@ -40,7 +44,6 @@ async def handleAudioMessage(conn, audio):
|
||||||
conn.asr_audio.clear()
|
conn.asr_audio.clear()
|
||||||
conn.reset_vad_states()
|
conn.reset_vad_states()
|
||||||
|
|
||||||
|
|
||||||
async def handleCMDMessage(conn, text):
|
async def handleCMDMessage(conn, text):
|
||||||
cmd_exit = conn.cmd_exit
|
cmd_exit = conn.cmd_exit
|
||||||
for cmd in cmd_exit:
|
for cmd in cmd_exit:
|
||||||
|
|
|
||||||
19
core/providers/asr/base.py
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Optional, Tuple, List
|
||||||
|
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
class ASRProviderBase(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
|
||||||
|
"""解码Opus数据并保存为WAV文件"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""将语音数据转换为文本"""
|
||||||
|
pass
|
||||||
286
core/providers/asr/doubao.py
Normal file
|
|
@ -0,0 +1,286 @@
|
||||||
|
import time
|
||||||
|
import io
|
||||||
|
import wave
|
||||||
|
import os
|
||||||
|
from typing import Optional, Tuple, List
|
||||||
|
import uuid
|
||||||
|
import websockets
|
||||||
|
import json
|
||||||
|
import gzip
|
||||||
|
|
||||||
|
import opuslib_next
|
||||||
|
from core.providers.asr.base import ASRProviderBase
|
||||||
|
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
CLIENT_FULL_REQUEST = 0b0001
|
||||||
|
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
|
||||||
|
|
||||||
|
NO_SEQUENCE = 0b0000
|
||||||
|
NEG_SEQUENCE = 0b0010
|
||||||
|
|
||||||
|
SERVER_FULL_RESPONSE = 0b1001
|
||||||
|
SERVER_ACK = 0b1011
|
||||||
|
SERVER_ERROR_RESPONSE = 0b1111
|
||||||
|
|
||||||
|
NO_SERIALIZATION = 0b0000
|
||||||
|
JSON = 0b0001
|
||||||
|
THRIFT = 0b0011
|
||||||
|
CUSTOM_TYPE = 0b1111
|
||||||
|
NO_COMPRESSION = 0b0000
|
||||||
|
GZIP = 0b0001
|
||||||
|
CUSTOM_COMPRESSION = 0b1111
|
||||||
|
|
||||||
|
|
||||||
|
def parse_response(res):
|
||||||
|
"""
|
||||||
|
protocol_version(4 bits), header_size(4 bits),
|
||||||
|
message_type(4 bits), message_type_specific_flags(4 bits)
|
||||||
|
serialization_method(4 bits) message_compression(4 bits)
|
||||||
|
reserved (8bits) 保留字段
|
||||||
|
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
|
||||||
|
payload 类似与http 请求体
|
||||||
|
"""
|
||||||
|
protocol_version = res[0] >> 4
|
||||||
|
header_size = res[0] & 0x0f
|
||||||
|
message_type = res[1] >> 4
|
||||||
|
message_type_specific_flags = res[1] & 0x0f
|
||||||
|
serialization_method = res[2] >> 4
|
||||||
|
message_compression = res[2] & 0x0f
|
||||||
|
reserved = res[3]
|
||||||
|
header_extensions = res[4:header_size * 4]
|
||||||
|
payload = res[header_size * 4:]
|
||||||
|
result = {}
|
||||||
|
payload_msg = None
|
||||||
|
payload_size = 0
|
||||||
|
if message_type == SERVER_FULL_RESPONSE:
|
||||||
|
payload_size = int.from_bytes(payload[:4], "big", signed=True)
|
||||||
|
payload_msg = payload[4:]
|
||||||
|
elif message_type == SERVER_ACK:
|
||||||
|
seq = int.from_bytes(payload[:4], "big", signed=True)
|
||||||
|
result['seq'] = seq
|
||||||
|
if len(payload) >= 8:
|
||||||
|
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
||||||
|
payload_msg = payload[8:]
|
||||||
|
elif message_type == SERVER_ERROR_RESPONSE:
|
||||||
|
code = int.from_bytes(payload[:4], "big", signed=False)
|
||||||
|
result['code'] = code
|
||||||
|
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
|
||||||
|
payload_msg = payload[8:]
|
||||||
|
if payload_msg is None:
|
||||||
|
return result
|
||||||
|
if message_compression == GZIP:
|
||||||
|
payload_msg = gzip.decompress(payload_msg)
|
||||||
|
if serialization_method == JSON:
|
||||||
|
payload_msg = json.loads(str(payload_msg, "utf-8"))
|
||||||
|
elif serialization_method != NO_SERIALIZATION:
|
||||||
|
payload_msg = str(payload_msg, "utf-8")
|
||||||
|
result['payload_msg'] = payload_msg
|
||||||
|
result['payload_size'] = payload_size
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class ASRProvider(ASRProviderBase):
|
||||||
|
def __init__(self, config: dict, delete_audio_file: bool):
|
||||||
|
self.appid = config.get("appid")
|
||||||
|
self.cluster = config.get("cluster")
|
||||||
|
self.access_token = config.get("access_token")
|
||||||
|
self.output_dir = config.get("output_dir")
|
||||||
|
|
||||||
|
self.host = "openspeech.bytedance.com"
|
||||||
|
self.ws_url = f"wss://{self.host}/api/v2/asr"
|
||||||
|
self.success_code = 1000
|
||||||
|
self.seg_duration = 15000
|
||||||
|
|
||||||
|
# 确保输出目录存在
|
||||||
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
|
def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
|
||||||
|
"""将Opus音频数据解码并保存为WAV文件"""
|
||||||
|
file_name = f"asr_{session_id}_{uuid.uuid4()}.wav"
|
||||||
|
file_path = os.path.join(self.output_dir, file_name)
|
||||||
|
|
||||||
|
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
|
||||||
|
pcm_data = []
|
||||||
|
|
||||||
|
for opus_packet in opus_data:
|
||||||
|
try:
|
||||||
|
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
||||||
|
pcm_data.append(pcm_frame)
|
||||||
|
except opuslib_next.OpusError as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
|
||||||
|
|
||||||
|
with wave.open(file_path, "wb") as wf:
|
||||||
|
wf.setnchannels(1)
|
||||||
|
wf.setsampwidth(2) # 2 bytes = 16-bit
|
||||||
|
wf.setframerate(16000)
|
||||||
|
wf.writeframes(b"".join(pcm_data))
|
||||||
|
|
||||||
|
return file_path
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _generate_header(message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE) -> bytearray:
|
||||||
|
"""Generate protocol header."""
|
||||||
|
header = bytearray()
|
||||||
|
header_size = 1
|
||||||
|
header.append((0b0001 << 4) | header_size) # Protocol version
|
||||||
|
header.append((message_type << 4) | message_type_specific_flags)
|
||||||
|
header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression
|
||||||
|
header.append(0x00) # reserved
|
||||||
|
return header
|
||||||
|
|
||||||
|
def _construct_request(self, reqid) -> dict:
|
||||||
|
"""Construct the request payload."""
|
||||||
|
return {
|
||||||
|
"app": {
|
||||||
|
"appid": f"{self.appid}",
|
||||||
|
"cluster": self.cluster,
|
||||||
|
"token": self.access_token,
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"uid": str(uuid.uuid4()),
|
||||||
|
},
|
||||||
|
"request": {
|
||||||
|
"reqid": reqid,
|
||||||
|
"show_utterances": False,
|
||||||
|
"sequence": 1
|
||||||
|
},
|
||||||
|
"audio": {
|
||||||
|
"format": "wav",
|
||||||
|
"rate": 16000,
|
||||||
|
"language": "zh-CN",
|
||||||
|
"bits": 16,
|
||||||
|
"channel": 1,
|
||||||
|
"codec": "raw",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _send_request(self, audio_data: List[bytes], segment_size: int) -> Optional[str]:
|
||||||
|
"""Send request to Volcano ASR service."""
|
||||||
|
try:
|
||||||
|
auth_header = {'Authorization': 'Bearer; {}'.format(self.access_token)}
|
||||||
|
async with websockets.connect(self.ws_url, additional_headers=auth_header) as websocket:
|
||||||
|
# Prepare request data
|
||||||
|
request_params = self._construct_request(str(uuid.uuid4()))
|
||||||
|
print(request_params)
|
||||||
|
payload_bytes = str.encode(json.dumps(request_params))
|
||||||
|
payload_bytes = gzip.compress(payload_bytes)
|
||||||
|
full_client_request = self._generate_header()
|
||||||
|
full_client_request.extend((len(payload_bytes)).to_bytes(4, 'big')) # payload size(4 bytes)
|
||||||
|
full_client_request.extend(payload_bytes) # payload
|
||||||
|
|
||||||
|
# Send header and metadata
|
||||||
|
# full_client_request
|
||||||
|
await websocket.send(full_client_request)
|
||||||
|
res = await websocket.recv()
|
||||||
|
result = parse_response(res)
|
||||||
|
if 'payload_msg' in result and result['payload_msg']['code'] != self.success_code:
|
||||||
|
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
for seq, (chunk, last) in enumerate(self.slice_data(audio_data, segment_size), 1):
|
||||||
|
if last:
|
||||||
|
audio_only_request = self._generate_header(
|
||||||
|
message_type=CLIENT_AUDIO_ONLY_REQUEST,
|
||||||
|
message_type_specific_flags=NEG_SEQUENCE
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
audio_only_request = self._generate_header(
|
||||||
|
message_type=CLIENT_AUDIO_ONLY_REQUEST
|
||||||
|
)
|
||||||
|
payload_bytes = gzip.compress(chunk)
|
||||||
|
audio_only_request.extend((len(payload_bytes)).to_bytes(4, 'big')) # payload size(4 bytes)
|
||||||
|
audio_only_request.extend(payload_bytes) # payload
|
||||||
|
# Send audio data
|
||||||
|
await websocket.send(audio_only_request)
|
||||||
|
|
||||||
|
# Receive response
|
||||||
|
response = await websocket.recv()
|
||||||
|
result = parse_response(response)
|
||||||
|
|
||||||
|
if 'payload_msg' in result and result['payload_msg']['code'] == self.success_code:
|
||||||
|
if len(result['payload_msg']['result']) > 0:
|
||||||
|
return result['payload_msg']['result'][0]["text"]
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
logger.bind(tag=TAG).error(f"ASR error: {result}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def decode_opus(opus_data: List[bytes], session_id: str) -> List[bytes]:
|
||||||
|
|
||||||
|
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
|
||||||
|
pcm_data = []
|
||||||
|
|
||||||
|
for opus_packet in opus_data:
|
||||||
|
try:
|
||||||
|
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
||||||
|
pcm_data.append(pcm_frame)
|
||||||
|
except opuslib_next.OpusError as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
|
||||||
|
|
||||||
|
return pcm_data
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def read_wav_info(data: io.BytesIO = None) -> (int, int, int, int, int):
|
||||||
|
with io.BytesIO(data) as _f:
|
||||||
|
wave_fp = wave.open(_f, 'rb')
|
||||||
|
nchannels, sampwidth, framerate, nframes = wave_fp.getparams()[:4]
|
||||||
|
wave_bytes = wave_fp.readframes(nframes)
|
||||||
|
return nchannels, sampwidth, framerate, nframes, len(wave_bytes)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def slice_data(data: bytes, chunk_size: int) -> (list, bool):
|
||||||
|
"""
|
||||||
|
slice data
|
||||||
|
:param data: wav data
|
||||||
|
:param chunk_size: the segment size in one request
|
||||||
|
:return: segment data, last flag
|
||||||
|
"""
|
||||||
|
data_len = len(data)
|
||||||
|
offset = 0
|
||||||
|
while offset + chunk_size < data_len:
|
||||||
|
yield data[offset: offset + chunk_size], False
|
||||||
|
offset += chunk_size
|
||||||
|
else:
|
||||||
|
yield data[offset: data_len], True
|
||||||
|
|
||||||
|
async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""将语音数据转换为文本"""
|
||||||
|
try:
|
||||||
|
# 合并所有opus数据包
|
||||||
|
pcm_data = self.decode_opus(opus_data, session_id)
|
||||||
|
combined_pcm_data = b''.join(pcm_data)
|
||||||
|
|
||||||
|
wav_buffer = io.BytesIO()
|
||||||
|
|
||||||
|
with wave.open(wav_buffer, "wb") as wav_file:
|
||||||
|
wav_file.setnchannels(1) # 设置声道数
|
||||||
|
wav_file.setsampwidth(2) # 设置采样宽度
|
||||||
|
wav_file.setframerate(16000) # 设置采样率
|
||||||
|
wav_file.writeframes(combined_pcm_data) # 写入 PCM 数据
|
||||||
|
|
||||||
|
# 获取封装后的 WAV 数据
|
||||||
|
wav_data = wav_buffer.getvalue()
|
||||||
|
nchannels, sampwidth, framerate, nframes, wav_len = self.read_wav_info(wav_data)
|
||||||
|
size_per_sec = nchannels * sampwidth * framerate
|
||||||
|
segment_size = int(size_per_sec * self.seg_duration / 1000)
|
||||||
|
|
||||||
|
# 语音识别
|
||||||
|
start_time = time.time()
|
||||||
|
text = await self._send_request(wav_data, segment_size)
|
||||||
|
if text:
|
||||||
|
logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}")
|
||||||
|
return text, None
|
||||||
|
return "", None
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||||
|
return "", None
|
||||||
110
core/providers/asr/fun_local.py
Normal file
|
|
@ -0,0 +1,110 @@
|
||||||
|
import time
|
||||||
|
import wave
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import io
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from typing import Optional, Tuple, List
|
||||||
|
import uuid
|
||||||
|
import opuslib_next
|
||||||
|
from core.providers.asr.base import ASRProviderBase
|
||||||
|
|
||||||
|
from funasr import AutoModel
|
||||||
|
from funasr.utils.postprocess_utils import rich_transcription_postprocess
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
# 捕获标准输出
|
||||||
|
class CaptureOutput:
|
||||||
|
def __enter__(self):
|
||||||
|
self._output = io.StringIO()
|
||||||
|
self._original_stdout = sys.stdout
|
||||||
|
sys.stdout = self._output
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
|
sys.stdout = self._original_stdout
|
||||||
|
self.output = self._output.getvalue()
|
||||||
|
self._output.close()
|
||||||
|
|
||||||
|
# 将捕获到的内容通过 logger 输出
|
||||||
|
if self.output:
|
||||||
|
logger.bind(tag=TAG).info(self.output.strip())
|
||||||
|
|
||||||
|
|
||||||
|
class ASRProvider(ASRProviderBase):
|
||||||
|
def __init__(self, config: dict, delete_audio_file: bool):
|
||||||
|
self.model_dir = config.get("model_dir")
|
||||||
|
self.output_dir = config.get("output_dir") # 修正配置键名
|
||||||
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
|
# 确保输出目录存在
|
||||||
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
with CaptureOutput():
|
||||||
|
self.model = AutoModel(
|
||||||
|
model=self.model_dir,
|
||||||
|
vad_kwargs={"max_single_segment_time": 30000},
|
||||||
|
disable_update=True,
|
||||||
|
hub="hf"
|
||||||
|
# device="cuda:0", # 启用GPU加速
|
||||||
|
)
|
||||||
|
|
||||||
|
def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
|
||||||
|
"""将Opus音频数据解码并保存为WAV文件"""
|
||||||
|
file_name = f"asr_{session_id}_{uuid.uuid4()}.wav"
|
||||||
|
file_path = os.path.join(self.output_dir, file_name)
|
||||||
|
|
||||||
|
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
|
||||||
|
pcm_data = []
|
||||||
|
|
||||||
|
for opus_packet in opus_data:
|
||||||
|
try:
|
||||||
|
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
||||||
|
pcm_data.append(pcm_frame)
|
||||||
|
except opuslib_next.OpusError as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
|
||||||
|
|
||||||
|
with wave.open(file_path, "wb") as wf:
|
||||||
|
wf.setnchannels(1)
|
||||||
|
wf.setsampwidth(2) # 2 bytes = 16-bit
|
||||||
|
wf.setframerate(16000)
|
||||||
|
wf.writeframes(b"".join(pcm_data))
|
||||||
|
|
||||||
|
return file_path
|
||||||
|
|
||||||
|
async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""语音转文本主处理逻辑"""
|
||||||
|
file_path = None
|
||||||
|
try:
|
||||||
|
# 保存音频文件
|
||||||
|
start_time = time.time()
|
||||||
|
file_path = self.save_audio_to_file(opus_data, session_id)
|
||||||
|
logger.bind(tag=TAG).debug(f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}")
|
||||||
|
|
||||||
|
# 语音识别
|
||||||
|
start_time = time.time()
|
||||||
|
result = self.model.generate(
|
||||||
|
input=file_path,
|
||||||
|
cache={},
|
||||||
|
language="auto",
|
||||||
|
use_itn=True,
|
||||||
|
batch_size_s=60,
|
||||||
|
)
|
||||||
|
text = rich_transcription_postprocess(result[0]["text"])
|
||||||
|
logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}")
|
||||||
|
|
||||||
|
return text, file_path
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||||
|
return "", None
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# 文件清理逻辑
|
||||||
|
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||||
|
try:
|
||||||
|
os.remove(file_path)
|
||||||
|
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
||||||
62
core/providers/llm/homeassistant/homeassistant.py
Normal 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}")
|
||||||
57
core/providers/tts/aliyun.py
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
from datetime import datetime
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
self.appkey = config.get("appkey")
|
||||||
|
self.token = config.get("token")
|
||||||
|
self.format = config.get("format", "wav")
|
||||||
|
self.sample_rate = config.get("sample_rate", 16000)
|
||||||
|
self.voice = config.get("voice", "xiaoyun")
|
||||||
|
self.volume = config.get("volume", 50)
|
||||||
|
self.speech_rate = config.get("speech_rate", 0)
|
||||||
|
self.pitch_rate = config.get("pitch_rate", 0)
|
||||||
|
|
||||||
|
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
||||||
|
self.api_url = f"https://{self.host}/stream/v1/tts"
|
||||||
|
self.header = {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
def generate_filename(self, extension=".wav"):
|
||||||
|
return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
request_json = {
|
||||||
|
"appkey": self.appkey,
|
||||||
|
"token": self.token,
|
||||||
|
"text": text,
|
||||||
|
"format": self.format,
|
||||||
|
"sample_rate": self.sample_rate,
|
||||||
|
"voice": self.voice,
|
||||||
|
"volume": self.volume,
|
||||||
|
"speech_rate": self.speech_rate,
|
||||||
|
"pitch_rate": self.pitch_rate
|
||||||
|
}
|
||||||
|
|
||||||
|
print(self.api_url, json.dumps(request_json, ensure_ascii=False))
|
||||||
|
try:
|
||||||
|
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
||||||
|
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
|
||||||
|
if resp.headers['Content-Type'].startswith('audio/'):
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
f.write(resp.content)
|
||||||
|
return output_file
|
||||||
|
else:
|
||||||
|
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
@ -2,7 +2,7 @@ import asyncio
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import os
|
import os
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import opuslib
|
import opuslib_next
|
||||||
from pydub import AudioSegment
|
from pydub import AudioSegment
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
|
||||||
|
|
@ -58,7 +58,7 @@ class TTSProviderBase(ABC):
|
||||||
raw_data = audio.raw_data
|
raw_data = audio.raw_data
|
||||||
|
|
||||||
# 初始化Opus编码器
|
# 初始化Opus编码器
|
||||||
encoder = opuslib.Encoder(16000, 1, opuslib.APPLICATION_AUDIO)
|
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
|
||||||
|
|
||||||
# 编码参数
|
# 编码参数
|
||||||
frame_duration = 60 # 60ms per frame
|
frame_duration = 60 # 60ms per frame
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
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": self.appid,
|
"appid": f"{self.appid}",
|
||||||
"token": "access_token",
|
"token": "access_token",
|
||||||
"cluster": self.cluster
|
"cluster": self.cluster
|
||||||
},
|
},
|
||||||
|
|
@ -49,8 +49,13 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
resp = requests.post(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"]
|
||||||
file_to_save = open(output_file, "wb")
|
file_to_save = open(output_file, "wb")
|
||||||
file_to_save.write(base64.b64decode(data))
|
file_to_save.write(base64.b64decode(data))
|
||||||
|
else:
|
||||||
|
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,11 @@ from pydantic import BaseModel, Field, conint, model_validator
|
||||||
from typing_extensions import Annotated
|
from typing_extensions import Annotated
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
# from base import TTSProviderBase
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ServeReferenceAudio(BaseModel):
|
class ServeReferenceAudio(BaseModel):
|
||||||
|
|
@ -86,6 +89,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.channels = config.get("channels",1)
|
self.channels = config.get("channels",1)
|
||||||
self.rate = config.get("rate",44100)
|
self.rate = config.get("rate",44100)
|
||||||
self.api_key = config.get("api_key","YOUR_API_KEY")
|
self.api_key = config.get("api_key","YOUR_API_KEY")
|
||||||
|
if "你" in self.api_key:
|
||||||
|
logger.bind(tag=TAG).error("你还没配置FishSpeech TTS的密钥,请在配置文件中配置密钥,否则无法正常工作")
|
||||||
|
return
|
||||||
self.normalize = config.get("normalize",True)
|
self.normalize = config.get("normalize",True)
|
||||||
self.max_new_tokens = config.get("max_new_tokens",1024)
|
self.max_new_tokens = config.get("max_new_tokens",1024)
|
||||||
self.chunk_length = config.get("chunk_length",200)
|
self.chunk_length = config.get("chunk_length",200)
|
||||||
|
|
|
||||||
77
core/providers/tts/minimax.py
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
from datetime import datetime
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
self.group_id = config.get("group_id")
|
||||||
|
self.api_key = config.get("api_key")
|
||||||
|
self.model = config.get("model")
|
||||||
|
self.voice_id = config.get("voice_id")
|
||||||
|
|
||||||
|
default_voice_setting = {
|
||||||
|
"voice_id": "female-shaonv",
|
||||||
|
"speed": 1,
|
||||||
|
"vol": 1,
|
||||||
|
"pitch": 0,
|
||||||
|
"emotion": "happy"
|
||||||
|
}
|
||||||
|
default_pronunciation_dict = {
|
||||||
|
"tone": [
|
||||||
|
"处理/(chu3)(li3)", "危险/dangerous"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
defult_audio_setting = {
|
||||||
|
"sample_rate": 32000,
|
||||||
|
"bitrate": 128000,
|
||||||
|
"format": "mp3",
|
||||||
|
"channel": 1
|
||||||
|
}
|
||||||
|
self.voice_setting = {**default_voice_setting, **config.get("voice_setting", {})}
|
||||||
|
self.pronunciation_dict = {**default_pronunciation_dict, **config.get("pronunciation_dict", {})}
|
||||||
|
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
|
||||||
|
self.timber_weights = config.get("timber_weights", [])
|
||||||
|
|
||||||
|
if self.voice_id:
|
||||||
|
self.voice_setting["voice_id"] = self.voice_id
|
||||||
|
|
||||||
|
self.host = "api.minimax.chat"
|
||||||
|
self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}"
|
||||||
|
self.header = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Bearer {self.api_key}"
|
||||||
|
}
|
||||||
|
|
||||||
|
def generate_filename(self, extension=".mp3"):
|
||||||
|
return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
request_json = {
|
||||||
|
"model": self.model,
|
||||||
|
"text": text,
|
||||||
|
"stream": False,
|
||||||
|
"voice_setting": self.voice_setting,
|
||||||
|
"pronunciation_dict": self.pronunciation_dict,
|
||||||
|
"audio_setting": self.audio_setting,
|
||||||
|
}
|
||||||
|
|
||||||
|
if type(self.timber_weights) is list and len(self.timber_weights) > 0:
|
||||||
|
request_json["timber_weights"] = self.timber_weights
|
||||||
|
request_json["voice_setting"]["voice_id"] = ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
||||||
|
# 检查返回请求数据的status_code是否为0
|
||||||
|
if resp.json()["base_resp"]["status_code"] == 0:
|
||||||
|
data = resp.json()['data']['audio']
|
||||||
|
file_to_save = open(output_file, "wb")
|
||||||
|
file_to_save.write(bytes.fromhex(data))
|
||||||
|
else:
|
||||||
|
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
@ -1,7 +1,5 @@
|
||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
import json
|
|
||||||
import base64
|
|
||||||
import requests
|
import requests
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
|
|
||||||
|
|
@ -1,114 +1,24 @@
|
||||||
|
import importlib
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
import time
|
import time
|
||||||
import wave
|
import wave
|
||||||
import os
|
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from typing import Optional, Tuple, List
|
|
||||||
import uuid
|
import uuid
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
import opuslib
|
from typing import Optional, Tuple, List
|
||||||
from funasr import AutoModel
|
from core.providers.asr.base import ASRProviderBase
|
||||||
from funasr.utils.postprocess_utils import rich_transcription_postprocess
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
class ASR(ABC):
|
def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase:
|
||||||
@abstractmethod
|
|
||||||
def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
|
|
||||||
"""解码Opus数据并保存为WAV文件"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]:
|
|
||||||
"""将语音数据转换为文本"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class FunASR(ASR):
|
|
||||||
def __init__(self, config: dict, delete_audio_file: bool):
|
|
||||||
self.model_dir = config.get("model_dir")
|
|
||||||
self.output_dir = config.get("output_dir") # 修正配置键名
|
|
||||||
self.delete_audio_file = delete_audio_file
|
|
||||||
|
|
||||||
# 确保输出目录存在
|
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
|
||||||
|
|
||||||
self.model = AutoModel(
|
|
||||||
model=self.model_dir,
|
|
||||||
vad_kwargs={"max_single_segment_time": 30000},
|
|
||||||
disable_update=True,
|
|
||||||
hub="hf"
|
|
||||||
# device="cuda:0", # 启用GPU加速
|
|
||||||
)
|
|
||||||
|
|
||||||
def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
|
|
||||||
"""将Opus音频数据解码并保存为WAV文件"""
|
|
||||||
file_name = f"asr_{session_id}_{uuid.uuid4()}.wav"
|
|
||||||
file_path = os.path.join(self.output_dir, file_name)
|
|
||||||
|
|
||||||
decoder = opuslib.Decoder(16000, 1) # 16kHz, 单声道
|
|
||||||
pcm_data = []
|
|
||||||
|
|
||||||
for opus_packet in opus_data:
|
|
||||||
try:
|
|
||||||
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
|
|
||||||
pcm_data.append(pcm_frame)
|
|
||||||
except opuslib.OpusError as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
|
|
||||||
|
|
||||||
with wave.open(file_path, "wb") as wf:
|
|
||||||
wf.setnchannels(1)
|
|
||||||
wf.setsampwidth(2) # 2 bytes = 16-bit
|
|
||||||
wf.setframerate(16000)
|
|
||||||
wf.writeframes(b"".join(pcm_data))
|
|
||||||
|
|
||||||
return file_path
|
|
||||||
|
|
||||||
def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]:
|
|
||||||
"""语音转文本主处理逻辑"""
|
|
||||||
file_path = None
|
|
||||||
try:
|
|
||||||
# 保存音频文件
|
|
||||||
start_time = time.time()
|
|
||||||
file_path = self.save_audio_to_file(opus_data, session_id)
|
|
||||||
logger.bind(tag=TAG).debug(f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}")
|
|
||||||
|
|
||||||
# 语音识别
|
|
||||||
start_time = time.time()
|
|
||||||
result = self.model.generate(
|
|
||||||
input=file_path,
|
|
||||||
cache={},
|
|
||||||
language="auto",
|
|
||||||
use_itn=True,
|
|
||||||
batch_size_s=60,
|
|
||||||
)
|
|
||||||
text = rich_transcription_postprocess(result[0]["text"])
|
|
||||||
logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}")
|
|
||||||
|
|
||||||
return text, file_path
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
finally:
|
|
||||||
# 文件清理逻辑
|
|
||||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
|
||||||
try:
|
|
||||||
os.remove(file_path)
|
|
||||||
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
def create_instance(class_name: str, *args, **kwargs) -> ASR:
|
|
||||||
"""工厂方法创建ASR实例"""
|
"""工厂方法创建ASR实例"""
|
||||||
cls_map = {
|
if os.path.exists(os.path.join('core', 'providers', 'asr', f'{class_name}.py')):
|
||||||
"FunASR": FunASR,
|
lib_name = f'core.providers.asr.{class_name}'
|
||||||
# 可扩展其他ASR实现
|
if lib_name not in sys.modules:
|
||||||
}
|
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
|
||||||
|
return sys.modules[lib_name].ASRProvider(*args, **kwargs)
|
||||||
|
|
||||||
if cls := cls_map.get(class_name):
|
raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确")
|
||||||
return cls(*args, **kwargs)
|
|
||||||
raise ValueError(f"不支持的ASR类型: {class_name}")
|
|
||||||
|
|
@ -1,5 +1,13 @@
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import asyncio
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
|
||||||
|
# 添加项目根目录到Python路径
|
||||||
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
|
||||||
|
sys.path.insert(0, project_root)
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import importlib
|
import importlib
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
@ -21,39 +29,115 @@ def create_instance(class_name, *args, **kwargs):
|
||||||
raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")
|
raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
async def test_single_model(llm_name: str, llm_config: Dict[str, Any], test_prompt: str, config: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""异步测试单个模型"""
|
||||||
响应速度测试
|
try:
|
||||||
"""
|
# 获取实际的LLM类型
|
||||||
config = read_config(get_project_dir() + "config.yaml")
|
llm_type = llm_config["type"] if "type" in llm_config else llm_name
|
||||||
llm = create_instance(
|
llm = create_instance(llm_type, llm_config)
|
||||||
config["selected_module"]["LLM"]
|
|
||||||
if not "type" in config["LLM"][config["selected_module"]["LLM"]]
|
|
||||||
else
|
|
||||||
config["LLM"][config["selected_module"]["LLM"]]["type"],
|
|
||||||
config["LLM"][config["selected_module"]["LLM"]]
|
|
||||||
)
|
|
||||||
|
|
||||||
start_time = datetime.now()
|
|
||||||
|
|
||||||
|
# 开始测试
|
||||||
dialogue = []
|
dialogue = []
|
||||||
dialogue.append({"role": "system", "content": config.get("prompt")})
|
dialogue.append({"role": "system", "content": config.get("prompt")})
|
||||||
dialogue.append({"role": "user", "content": "你好小智"})
|
dialogue.append({"role": "user", "content": test_prompt})
|
||||||
|
|
||||||
|
start_time = datetime.now()
|
||||||
llm_responses = llm.response("test", dialogue)
|
llm_responses = llm.response("test", dialogue)
|
||||||
response_message = []
|
response_message = []
|
||||||
first_text = None
|
first_response_time = None
|
||||||
|
total_response_time = None
|
||||||
start = 0
|
start = 0
|
||||||
|
full_response = ""
|
||||||
|
|
||||||
for content in llm_responses:
|
for content in llm_responses:
|
||||||
response_message.append(content)
|
response_message.append(content)
|
||||||
|
full_response += content
|
||||||
|
|
||||||
if is_segment(response_message):
|
if is_segment(response_message):
|
||||||
segment_text = "".join(response_message[start:])
|
segment_text = "".join(response_message[start:])
|
||||||
segment_text = get_string_no_punctuation_or_emoji(segment_text)
|
segment_text = get_string_no_punctuation_or_emoji(segment_text)
|
||||||
if len(segment_text) > 0:
|
if len(segment_text) > 0:
|
||||||
if first_text is None:
|
if first_response_time is None:
|
||||||
first_text = segment_text
|
first_response_time = (datetime.now() - start_time).total_seconds()
|
||||||
print("大模型首次返回耗时:" + str(datetime.now() - start_time))
|
|
||||||
start = len(response_message)
|
start = len(response_message)
|
||||||
|
|
||||||
print("大模型返回总耗时:" + str(datetime.now() - start_time))
|
total_response_time = (datetime.now() - start_time).total_seconds()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"name": llm_name,
|
||||||
|
"type": llm_type,
|
||||||
|
"first_response_time": first_response_time,
|
||||||
|
"total_response_time": total_response_time,
|
||||||
|
"response_length": len(full_response),
|
||||||
|
"status": "成功",
|
||||||
|
"response": full_response
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"测试 {llm_name} 时发生错误: {str(e)}")
|
||||||
|
return {
|
||||||
|
"name": llm_name,
|
||||||
|
"type": llm_config.get("type", llm_name),
|
||||||
|
"first_response_time": None,
|
||||||
|
"total_response_time": None,
|
||||||
|
"response_length": 0,
|
||||||
|
"status": f"失败 - {str(e)}",
|
||||||
|
"response": ""
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
"""
|
||||||
|
LLM模型响应速度测试和排行(异步版本)
|
||||||
|
"""
|
||||||
|
config = read_config(get_project_dir() + "config.yaml")
|
||||||
|
test_prompt = "你好小智"
|
||||||
|
|
||||||
|
print("开始并发测试所有模型...")
|
||||||
|
|
||||||
|
# 创建所有模型的测试任务
|
||||||
|
tasks = []
|
||||||
|
for llm_name, llm_config in config["LLM"].items():
|
||||||
|
task = asyncio.create_task(test_single_model(llm_name, llm_config, test_prompt, config))
|
||||||
|
tasks.append(task)
|
||||||
|
|
||||||
|
# 等待所有测试完成
|
||||||
|
test_results = await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
# 打印测试结果排行榜
|
||||||
|
print("\n========= LLM模型性能测试排行榜 =========")
|
||||||
|
print("测试提示词:", test_prompt)
|
||||||
|
|
||||||
|
# 过滤出成功的结果,并确保数值有效
|
||||||
|
successful_results = [r for r in test_results if r["status"] == "成功" and r["first_response_time"] is not None]
|
||||||
|
|
||||||
|
if successful_results:
|
||||||
|
print("\n1. 首次响应时间排行:")
|
||||||
|
sorted_by_first = sorted(successful_results, key=lambda x: x["first_response_time"])
|
||||||
|
for i, result in enumerate(sorted_by_first, 1):
|
||||||
|
print(f"{i}. {result['name']}({result['type']}) - {result['first_response_time']:.2f}秒")
|
||||||
|
print(f" 响应内容: {result['response'][:50]}...") # 只显示前50个字符
|
||||||
|
|
||||||
|
print("\n2. 总响应时间排行:")
|
||||||
|
sorted_by_total = sorted(successful_results, key=lambda x: x["total_response_time"] or float('inf'))
|
||||||
|
for i, result in enumerate(sorted_by_total, 1):
|
||||||
|
if result["total_response_time"] is not None:
|
||||||
|
print(f"{i}. {result['name']}({result['type']}) - {result['total_response_time']:.2f}秒")
|
||||||
|
|
||||||
|
print("\n3. 响应长度比较:")
|
||||||
|
sorted_by_length = sorted(successful_results, key=lambda x: x["response_length"], reverse=True)
|
||||||
|
for i, result in enumerate(sorted_by_length, 1):
|
||||||
|
print(f"{i}. {result['name']}({result['type']}) - {result['response_length']}字符")
|
||||||
|
else:
|
||||||
|
print("\n没有成功完成测试的模型。")
|
||||||
|
|
||||||
|
if len(test_results) != len(successful_results):
|
||||||
|
print("\n测试失败的模型:")
|
||||||
|
failed_results = [r for r in test_results if r["status"] != "成功" or r["first_response_time"] is None]
|
||||||
|
for result in failed_results:
|
||||||
|
print(f"- {result['name']}({result['type']}): {result['status']}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 运行异步主函数
|
||||||
|
asyncio.run(main())
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,7 @@ def remove_punctuation_and_length(text):
|
||||||
char not in full_width_punctuations and char not in half_width_punctuations and char not in space and char not in full_width_space])
|
char not in full_width_punctuations and char not in half_width_punctuations and char not in space and char not in full_width_space])
|
||||||
|
|
||||||
if result == "Yeah":
|
if result == "Yeah":
|
||||||
return 0
|
return 0, ""
|
||||||
return len(result), result
|
return len(result), result
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import opuslib
|
import opuslib_next
|
||||||
import time
|
import time
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
|
|
@ -24,7 +24,7 @@ class SileroVAD(VAD):
|
||||||
force_reload=False)
|
force_reload=False)
|
||||||
(get_speech_timestamps, _, _, _, _) = self.utils
|
(get_speech_timestamps, _, _, _, _) = self.utils
|
||||||
|
|
||||||
self.decoder = opuslib.Decoder(16000, 1)
|
self.decoder = opuslib_next.Decoder(16000, 1)
|
||||||
self.vad_threshold = config.get("threshold")
|
self.vad_threshold = config.get("threshold")
|
||||||
self.silence_threshold_ms = config.get("min_silence_duration_ms")
|
self.silence_threshold_ms = config.get("min_silence_duration_ms")
|
||||||
|
|
||||||
|
|
@ -59,7 +59,7 @@ class SileroVAD(VAD):
|
||||||
conn.client_have_voice_last_time = time.time() * 1000
|
conn.client_have_voice_last_time = time.time() * 1000
|
||||||
|
|
||||||
return client_have_voice
|
return client_have_voice
|
||||||
except opuslib.OpusError as e:
|
except opuslib_next.OpusError as e:
|
||||||
logger.bind(tag=TAG).info(f"解码错误: {e}")
|
logger.bind(tag=TAG).info(f"解码错误: {e}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")
|
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ from core.utils import asr, vad, llm, tts
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
class WebSocketServer:
|
class WebSocketServer:
|
||||||
def __init__(self, config: dict):
|
def __init__(self, config: dict):
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
@ -21,7 +22,10 @@ class WebSocketServer:
|
||||||
self.config["VAD"][self.config["selected_module"]["VAD"]]
|
self.config["VAD"][self.config["selected_module"]["VAD"]]
|
||||||
),
|
),
|
||||||
asr.create_instance(
|
asr.create_instance(
|
||||||
self.config["selected_module"]["ASR"],
|
self.config["selected_module"]["ASR"]
|
||||||
|
if not 'type' in self.config["ASR"][self.config["selected_module"]["ASR"]]
|
||||||
|
else
|
||||||
|
self.config["ASR"][self.config["selected_module"]["ASR"]]["type"],
|
||||||
self.config["ASR"][self.config["selected_module"]["ASR"]],
|
self.config["ASR"][self.config["selected_module"]["ASR"]],
|
||||||
self.config["delete_audio"]
|
self.config["delete_audio"]
|
||||||
),
|
),
|
||||||
|
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
services:
|
|
||||||
xiaozhi-esp32-server:
|
|
||||||
image: ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
container_name: xiaozhi-esp32-server
|
|
||||||
restart: always
|
|
||||||
#security_opt:
|
|
||||||
# - seccomp:unconfined
|
|
||||||
ports:
|
|
||||||
- "8000:8000"
|
|
||||||
- "8002:8002"
|
|
||||||
volumes:
|
|
||||||
- ./.config.yaml:/opt/xiaozhi-esp32-server/config.yaml
|
|
||||||
|
|
@ -1,11 +1,17 @@
|
||||||
services:
|
services:
|
||||||
xiaozhi-esp32-server:
|
xiaozhi-esp32-server:
|
||||||
image: ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:latest
|
||||||
container_name: xiaozhi-esp32-server
|
container_name: xiaozhi-esp32-server
|
||||||
restart: always
|
restart: always
|
||||||
#security_opt:
|
security_opt:
|
||||||
# - seccomp:unconfined
|
- seccomp:unconfined
|
||||||
ports:
|
ports:
|
||||||
|
# ws服务端
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
|
# 管理后台
|
||||||
|
- "8002:8002"
|
||||||
volumes:
|
volumes:
|
||||||
- ./.config.yaml:/opt/xiaozhi-esp32-server/config.yaml
|
# 配置文件目录
|
||||||
|
- ./data:/app/data
|
||||||
|
# 模型文件挂接,很重要
|
||||||
|
- ./models/SenseVoiceSmall/model.pt:/app/models/SenseVoiceSmall/model.pt
|
||||||
|
|
@ -1,217 +0,0 @@
|
||||||
# 部署指南
|
|
||||||
|
|
||||||
本项目支持 **x86** 和 **arm64** 架构,可运行于国产操作系统。
|
|
||||||
|
|
||||||
## 方式一:快速部署(推荐)
|
|
||||||
|
|
||||||
### 1. 安装 Docker
|
|
||||||
|
|
||||||
如果未安装 Docker,可参考 [Docker 安装教程](https://www.runoob.com/docker/ubuntu-docker-install.html)。
|
|
||||||
|
|
||||||
### 2. 创建项目目录
|
|
||||||
|
|
||||||
选择一个空目录作为 **项目目录**。
|
|
||||||
|
|
||||||
### 3. 下载配置文件
|
|
||||||
|
|
||||||
访问 [config.yaml](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/config.yaml),点击 `RAW` 旁的下载按钮,保存到 **项目目录**。
|
|
||||||
|
|
||||||
### 4. 运行 Docker
|
|
||||||
|
|
||||||
打开终端,`cd` 进入 **项目目录**,执行:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
docker run -d --name xiaozhi-esp32-server --restart always --security-opt seccomp:unconfined \
|
|
||||||
-p 8000:8000 \
|
|
||||||
-v $(pwd)/config.yaml:/opt/xiaozhi-esp32-server/config.yaml \
|
|
||||||
ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. 确认运行状态
|
|
||||||
|
|
||||||
```sh
|
|
||||||
docker ps # 查看容器状态
|
|
||||||
docker logs -f xiaozhi-esp32-server # 查看日志
|
|
||||||
```
|
|
||||||
|
|
||||||
## 方式二:使用 Docker Compose 部署
|
|
||||||
|
|
||||||
### 1. 创建 `docker-compose.yml`
|
|
||||||
在 `项目目录` 下创建 `docker-compose.yml` 文件,内容如下:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
version: '3'
|
|
||||||
services:
|
|
||||||
xiaozhi-esp32-server:
|
|
||||||
image: ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
container_name: xiaozhi-esp32-server
|
|
||||||
restart: always
|
|
||||||
security_opt:
|
|
||||||
- seccomp:unconfined
|
|
||||||
ports:
|
|
||||||
- "8000:8000"
|
|
||||||
volumes:
|
|
||||||
- ./config.yaml:/opt/xiaozhi-esp32-server/config.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. 启动服务
|
|
||||||
```sh
|
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. 确认运行状态
|
|
||||||
```sh
|
|
||||||
docker-compose ps
|
|
||||||
docker-compose logs -f
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. 停止和删除容器
|
|
||||||
```sh
|
|
||||||
docker-compose down
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. 版本升级
|
|
||||||
|
|
||||||
#### 备份配置文件
|
|
||||||
```sh
|
|
||||||
cp config.yaml config_backup.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 更新 Docker 镜像
|
|
||||||
```sh
|
|
||||||
docker-compose pull
|
|
||||||
docker-compose down
|
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## 方式三:源码部署(免环境部署/可修改代码)
|
|
||||||
|
|
||||||
### 1. 下载源码
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git clone https://github.com/xinnan-tech/xiaozhi-esp32-server.git
|
|
||||||
cd xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
或手动下载 [ZIP 包](https://github.com/xinnan-tech/xiaozhi-esp32-server/archive/refs/heads/main.zip),解压后重命名为 `xiaozhi-esp32-server`。
|
|
||||||
|
|
||||||
## 2.运行docker
|
|
||||||
|
|
||||||
修改完配置后,打开命令行工具,`cd`进入到你的项目目录下,执行以下命令
|
|
||||||
|
|
||||||
```sh
|
|
||||||
docker run -it --name xiaozhi-env --restart always --security-opt seccomp:unconfined \
|
|
||||||
-p 8000:8000 \
|
|
||||||
-p 8002:8002 \
|
|
||||||
-v ./:/app \
|
|
||||||
ccr.ccs.tencentyun.com/kalicyh/poetry:v3.10_latest
|
|
||||||
```
|
|
||||||
|
|
||||||
然后就和正常开发一样了
|
|
||||||
|
|
||||||
## 3.安装依赖
|
|
||||||
|
|
||||||
在刚刚的打开的终端运行
|
|
||||||
|
|
||||||
```sh
|
|
||||||
poetry install --no-root
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends libopus0 ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
速度慢可以尝试使用清华镜像
|
|
||||||
|
|
||||||
```sh
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware" > /etc/apt/sources.list
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
|
||||||
echo "deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware" >> /etc/apt/sources.list
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends libopus0 ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4.运行项目
|
|
||||||
|
|
||||||
```sh
|
|
||||||
poetry run python app.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## 方式三:本地运行(适用于开发)
|
|
||||||
|
|
||||||
### 1. 安装环境
|
|
||||||
|
|
||||||
```sh
|
|
||||||
conda create -n xiaozhi-esp32-server python=3.10 -y
|
|
||||||
conda activate xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Mac/Windows:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
conda install conda-forge::libopus conda-forge::ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Ubuntu:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
apt-get install libopus0 ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. 下载源码 & 安装依赖
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git clone https://github.com/xinnan-tech/xiaozhi-esp32-server.git
|
|
||||||
cd xiaozhi-esp32-server
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. 运行项目
|
|
||||||
|
|
||||||
```sh
|
|
||||||
python app.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## 版本升级
|
|
||||||
|
|
||||||
```sh
|
|
||||||
docker stop xiaozhi-esp32-server
|
|
||||||
docker rm xiaozhi-esp32-server
|
|
||||||
docker rmi ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
然后重新按照 **方式一** 或 **方式二** 运行 Docker。
|
|
||||||
|
|
||||||
## 重要配置
|
|
||||||
|
|
||||||
修改 `config.yaml` 以适配不同 LLM 和 TTS 组件。
|
|
||||||
|
|
||||||
示例:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
selected_module:
|
|
||||||
ASR: FunASR
|
|
||||||
VAD: SileroVAD
|
|
||||||
LLM: ChatGLMLLM
|
|
||||||
TTS: EdgeTTS
|
|
||||||
```
|
|
||||||
|
|
||||||
如需使用 `Dify` 或 `DeepSeekLLM`,修改 `LLM` 部分并填写密钥。
|
|
||||||
|
|
||||||
## 模型文件下载
|
|
||||||
|
|
||||||
语音转文字默认使用 `SenseVoiceSmall`,需下载 `model.pt` 并存放至 `model/SenseVoiceSmall` 目录。
|
|
||||||
|
|
||||||
- [阿里魔塔下载](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
|
||||||
- [百度网盘下载](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:`qvna`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
如遇问题,可参考 `docker logs -f xiaozhi-esp32-server` 进行排查。
|
|
||||||
|
|
||||||
**至此,部署完成!** 🚀
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -10,37 +10,97 @@ docker镜像已支持x86架构、arm64架构的CPU,支持在国产操作系统
|
||||||
|
|
||||||
安装完后,你需要为这个项目找一个安放配置文件的目录,我们暂且称它为`项目目录`,这个目录最好是一个新建的空的目录。
|
安装完后,你需要为这个项目找一个安放配置文件的目录,我们暂且称它为`项目目录`,这个目录最好是一个新建的空的目录。
|
||||||
|
|
||||||
|
创建好目录后,你需要在`项目目录`下面创建`data`文件夹和`models`文件夹,`models`下面还要再创建`SenseVoiceSmall`文件夹。
|
||||||
|
|
||||||
|
最终目录结构如下所示:
|
||||||
|
|
||||||
|
```
|
||||||
|
你的项目根目录
|
||||||
|
├─ data
|
||||||
|
├─ models
|
||||||
|
├─ SenseVoiceSmall
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. 下载语音识别模型文件
|
||||||
|
|
||||||
|
你需要下载语音识别的模型文件,因为本项目的默认语音识别用的是本地离线语音识别方案。可通过这个方式下载
|
||||||
|
[跳转到下载语音识别模型文件](#模型文件)
|
||||||
|
|
||||||
|
下载完后,回到本教程。
|
||||||
|
|
||||||
|
## 3. 下载docker-compose.yaml
|
||||||
|
|
||||||
|
用浏览器打开[这个链接](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docker-compose.yml)。
|
||||||
|
|
||||||
|
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`docker-compose.yml`文件。 把文件下载到你的
|
||||||
|
`项目目录`中。
|
||||||
|
|
||||||
|
下载完后,回到本教程继续往下。
|
||||||
|
|
||||||
## 3. 下载配置文件
|
## 3. 下载配置文件
|
||||||
|
|
||||||
用浏览器打开[这个链接](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/config.yaml)。
|
用浏览器打开[这个链接](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/config.yaml)。
|
||||||
|
|
||||||
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config.yaml`文件。 把文件下载到你的
|
在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config.yaml`文件。 把文件下载到你的
|
||||||
`项目目录`。
|
`项目目录`下面的`data`文件夹中,然后把`config.yaml`文件重命名为`.config.yaml`。
|
||||||
|
|
||||||
## 4.[跳转到配置项目文件](#配置项目)
|
下载完配置文件后,我们确认一下整个`项目目录`里面的文件如下所示:
|
||||||
|
|
||||||
|
```
|
||||||
|
你的项目根目录
|
||||||
|
├─ docker-compose.yml
|
||||||
|
├─ data
|
||||||
|
├─ .config.yaml
|
||||||
|
├─ models
|
||||||
|
├─ SenseVoiceSmall
|
||||||
|
├─ model.pt
|
||||||
|
```
|
||||||
|
|
||||||
|
如果你的文件目录结构也是上面的,就继续往下。如果不是,你就再仔细看看是不是漏操作了什么。
|
||||||
|
|
||||||
|
## 4. 配置项目文件
|
||||||
|
|
||||||
|
接下里,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
|
||||||
|
[跳转到配置项目文件](#配置项目)
|
||||||
|
|
||||||
|
配置完项目文件后,回到本教程继续往下。
|
||||||
|
|
||||||
## 5. 执行docker命令
|
## 5. 执行docker命令
|
||||||
|
|
||||||
打开命令行工具,`cd` 进入到你的`项目目录`,执行以下命令
|
打开命令行工具,使用`终端`或`命令行`工具 进入到你的`项目目录`,执行以下命令
|
||||||
|
|
||||||
```
|
```
|
||||||
#如果你是linux,执行
|
docker-compose up -d
|
||||||
ls
|
|
||||||
#如果你是windows,执行
|
|
||||||
dir
|
|
||||||
```
|
```
|
||||||
|
|
||||||
如果你能看到`config.yaml`文件,确确实实进入到了`项目目录`,接着执行以下命令:
|
执行完后,再执行以下命令,查看日志信息。
|
||||||
|
|
||||||
```
|
```
|
||||||
docker run -d --name xiaozhi-esp32-server --restart always --security-opt seccomp:unconfined -p 8000:8000 -v $(pwd)/config.yaml:/opt/xiaozhi-esp32-server/config.yaml ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
docker logs -f xiaozhi-esp32-server
|
||||||
```
|
```
|
||||||
|
|
||||||
## 6.[跳转到运行状态确认](#运行状态确认)
|
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
|
||||||
|
|
||||||
## [跳转到版本升级操作](#版本升级操作)
|
## 6.版本升级操作
|
||||||
|
|
||||||
# 方式二:借助docker环境运行部署(仅限开发人员/小白勿用)
|
如果后期想升级版本,可以这么操作
|
||||||
|
|
||||||
|
1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
|
||||||
|
请注意是对关键密钥逐个复制,不要直接覆盖。因为新的`.config.yaml`文件可能有一些新的配置项,旧的`.config.yaml`文件不一定有。
|
||||||
|
|
||||||
|
2、执行以下命令
|
||||||
|
|
||||||
|
```
|
||||||
|
docker stop xiaozhi-esp32-server
|
||||||
|
docker rm xiaozhi-esp32-server
|
||||||
|
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
3、重新按docker方式部署
|
||||||
|
|
||||||
|
# 方式二:借助Docker环境运行部署
|
||||||
|
|
||||||
|
开发人员如果不想安装`conda`环境,可以使用这种方法管理好依赖。
|
||||||
|
|
||||||
## 1.克隆项目
|
## 1.克隆项目
|
||||||
|
|
||||||
|
|
@ -96,26 +156,15 @@ poetry run python app.py
|
||||||
|
|
||||||
## 1.安装基础环境
|
## 1.安装基础环境
|
||||||
|
|
||||||
本项目使用`conda`管理依赖环境,安装好后,开始执行以下命令。
|
本项目使用`conda`管理依赖环境。如果不方便安装`conda`,需要根据实际的操作系统安装好`libopus`和`ffmpeg`。
|
||||||
|
如果确定使用`conda`,则安装好后,开始执行以下命令。
|
||||||
|
|
||||||
```
|
```
|
||||||
conda remove -n xiaozhi-esp32-server --all -y
|
conda remove -n xiaozhi-esp32-server --all -y
|
||||||
conda create -n xiaozhi-esp32-server python=3.10 -y
|
conda create -n xiaozhi-esp32-server python=3.10 -y
|
||||||
conda activate xiaozhi-esp32-server
|
conda activate xiaozhi-esp32-server
|
||||||
```
|
conda install conda-forge::libopus -y
|
||||||
|
conda install conda-forge::ffmpeg -y
|
||||||
执行以上命令后, 如果你的电脑是Windows或Mac,执行下面的语句:
|
|
||||||
|
|
||||||
```
|
|
||||||
conda activate xiaozhi-esp32-server
|
|
||||||
conda install conda-forge::libopus
|
|
||||||
conda install conda-forge::ffmpeg
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你的电脑是ubuntu,执行下面的语句:
|
|
||||||
|
|
||||||
```
|
|
||||||
apt-get install libopus0 ffmpeg
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 2.安装本项目依赖
|
## 2.安装本项目依赖
|
||||||
|
|
@ -136,9 +185,17 @@ pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
## 3.[跳转到下载语音识别模型文件](#模型文件)
|
## 3.下载语音识别模型文件
|
||||||
|
|
||||||
## 4.[跳转到配置项目文件](#配置项目)
|
你需要下载语音识别的模型文件,因为本项目的默认语音识别用的是本地离线语音识别方案。可通过这个方式下载
|
||||||
|
[跳转到下载语音识别模型文件](#模型文件)
|
||||||
|
|
||||||
|
下载完后,回到本教程。
|
||||||
|
|
||||||
|
## 4.配置项目文件
|
||||||
|
|
||||||
|
接下里,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
|
||||||
|
[跳转到配置项目文件](#配置项目)
|
||||||
|
|
||||||
## 5.运行项目
|
## 5.运行项目
|
||||||
|
|
||||||
|
|
@ -148,25 +205,20 @@ conda activate xiaozhi-esp32-server
|
||||||
python app.py
|
python app.py
|
||||||
```
|
```
|
||||||
|
|
||||||
## 6.[跳转到运行状态确认](#运行状态确认)
|
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
|
||||||
|
|
||||||
# 汇总
|
# 汇总
|
||||||
|
|
||||||
## 配置项目
|
## 配置项目
|
||||||
|
|
||||||
修改`config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM`
|
如果你的`项目目录`目录没有`data`,你需要创建`data`目录。
|
||||||
|
如果你的`data`下面没有`.config.yaml`文件,你可以把源码目录下的`config.yaml`文件复制一份,重命名为`.config.yaml`
|
||||||
|
|
||||||
|
修改`项目目录`下`data`目录下的`.config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM`
|
||||||
,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。
|
,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。
|
||||||
默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。
|
默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。
|
||||||
|
|
||||||
```
|
|
||||||
# 如果您是一名开发者,建议阅读以下内容。如果不是开发者,可以忽略这部分内容。
|
|
||||||
# 在开发中,在项目根目录创建data目录,将【config.yaml】复制一份,改成【.config.yaml】,放进data目录中
|
|
||||||
# 系统会优先读取【data/.config.yaml】文件的配置。
|
|
||||||
# 这样做,可以避免在提交代码的时候,错误地提交密钥信息,保护您的密钥安全。
|
|
||||||
```
|
|
||||||
|
|
||||||
配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。
|
配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。
|
||||||
|
|
||||||
本项目的默认配置仅是成本最低配置(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。
|
本项目的默认配置仅是成本最低配置(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
@ -197,7 +249,7 @@ LLM:
|
||||||
|
|
||||||
## 模型文件
|
## 模型文件
|
||||||
|
|
||||||
下载源码后,需要下载模型文件。 默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
|
本项目语音识别模型,默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
|
||||||
文件放在`model/SenseVoiceSmall`
|
文件放在`model/SenseVoiceSmall`
|
||||||
目录下。下面两个下载路线任选一个。
|
目录下。下面两个下载路线任选一个。
|
||||||
|
|
||||||
|
|
@ -205,46 +257,21 @@ LLM:
|
||||||
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
|
- 线路二:百度网盘下载[SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) 提取码:
|
||||||
`qvna`
|
`qvna`
|
||||||
|
|
||||||
|
|
||||||
## 运行状态确认
|
## 运行状态确认
|
||||||
|
|
||||||
如果首次执行,可能需要几分钟时间,你要耐心等待他完成拉取。正常拉取完成后,你可以在命令行执行以下命令查看服务是否启动成功
|
|
||||||
|
|
||||||
```
|
|
||||||
docker ps
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你能看到`xiaozhi-server`,说明服务启动成功。那你还可以进一步执行以下命令,查看服务的日志
|
|
||||||
|
|
||||||
```
|
|
||||||
docker logs -f xiaozhi-esp32-server
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
|
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
|
||||||
|
|
||||||
```
|
```
|
||||||
2025-xx-xx xx:51:59,492 - core.server - INFO - Server is running at ws://xx.xx.xx.xxx:8000
|
25-02-23 12:01:09[core.websocket_server] - INFO - Server is running at ws://xxx.xx.xx.xx:8000
|
||||||
2025-xx-xx xx:51:59,516 - websockets.server - INFO - server listening on 0.0.0.0:8000
|
25-02-23 12:01:09[core.websocket_server] - INFO - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
|
||||||
```
|
```
|
||||||
|
|
||||||
接下来,你就可以开始 `编译esp32固件`了,请往下翻,翻到编译`esp32固件`相关章节。那么由于你是用docker部署,你要自己查看自己本机电脑的ip是多少。
|
正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。
|
||||||
正常来说,假设你的ip是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。这个信息很有用的,后面`编译esp32固件`
|
但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。
|
||||||
需要用到。
|
|
||||||
|
|
||||||
请注意,你的接口地址是`websocket`协议的地址,你可以使用`apifox`等工具调试。但是不能直接用浏览器打开访问,如果用浏览器打开,日志会显示错误,会让你怀疑是否部署成功了。
|
最正确的方法,是根据电脑的局域网IP来确定你的接口地址。
|
||||||
|
如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。
|
||||||
|
|
||||||
## 版本升级操作
|
这个信息很有用的,后面`编译esp32固件`需要用到。
|
||||||
|
|
||||||
如果想升级版本,可以这么操作
|
接下来,你就可以开始 [编译esp32固件](firmware-build.md)了。
|
||||||
|
|
||||||
1、备份好`config.yaml`文件,一些关键的配置到时复制到新的`config.yaml`文件里。
|
|
||||||
|
|
||||||
2、执行以下命令
|
|
||||||
|
|
||||||
```
|
|
||||||
docker stop xiaozhi-esp32-server
|
|
||||||
docker rm xiaozhi-esp32-server
|
|
||||||
docker rmi ccr.ccs.tencentyun.com/xinnan/xiaozhi-esp32-server:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
3、重新开始安装
|
|
||||||
|
|
@ -1,4 +1,7 @@
|
||||||
# 编译docker镜像
|
# 本地编译docker镜像方法
|
||||||
|
|
||||||
|
现在本项目已经使用github自动编译docker功能,本文档是提供给有本地编译docker镜像需求的朋友准备的。
|
||||||
|
|
||||||
1、安装docker
|
1、安装docker
|
||||||
```
|
```
|
||||||
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
|
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
|
||||||
|
|
@ -6,7 +9,7 @@ sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin
|
||||||
2、编译docker镜像
|
2、编译docker镜像
|
||||||
```
|
```
|
||||||
# 普通编译
|
# 普通编译
|
||||||
docker build -t xiaozhi-esp32-server:local -f ./Dockerfile .
|
docker build -t xiaozhi-esp32-server:local -f ./Dockerfile-pip .
|
||||||
```
|
```
|
||||||
3、测试本地镜像
|
3、测试本地镜像
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 249 KiB |
BIN
docs/images/demo1.png
Normal file
|
After Width: | Height: | Size: 258 KiB |
BIN
docs/images/demo2.png
Normal file
|
After Width: | Height: | Size: 269 KiB |
BIN
docs/images/demo3.png
Normal file
|
After Width: | Height: | Size: 387 KiB |
BIN
docs/images/demo4.png
Normal file
|
After Width: | Height: | Size: 404 KiB |
BIN
docs/images/demo5.png
Normal file
|
After Width: | Height: | Size: 288 KiB |
BIN
docs/images/webui.png
Normal file
|
After Width: | Height: | Size: 484 KiB |
|
Before Width: | Height: | Size: 447 KiB After Width: | Height: | Size: 446 KiB |
|
|
@ -38,7 +38,7 @@ class WebUI:
|
||||||
self.session_manager = SessionManager()
|
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_routes()
|
||||||
self.setup_cors()
|
self.setup_cors()
|
||||||
|
|
|
||||||
47
manager/static/webui/assets/index-DF7ROAy9.js
Normal file
1
manager/static/webui/assets/index-D_oCZVZF.css
Normal file
BIN
manager/static/webui/favicon.ico
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
|
|
@ -2,7 +2,7 @@
|
||||||
<html lang="en" style="height: 100%;">
|
<html lang="en" style="height: 100%;">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8"/>
|
<meta charset="UTF-8"/>
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<link rel="icon" href="/favicon.ico"/>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||||
<title>智控台</title>
|
<title>智控台</title>
|
||||||
<style>
|
<style>
|
||||||
|
|
@ -13,13 +13,14 @@
|
||||||
width: 100%;
|
width: 100%;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
#app {
|
#app {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<script type="module" crossorigin src="/assets/index-CvO82KVk.js"></script>
|
<script type="module" crossorigin src="/assets/index-DF7ROAy9.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/assets/index-_IjUUKjO.css">
|
<link rel="stylesheet" crossorigin href="/assets/index-D_oCZVZF.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|
|
||||||
436
performance_tester.py
Normal file
|
|
@ -0,0 +1,436 @@
|
||||||
|
import time
|
||||||
|
import aiohttp
|
||||||
|
import asyncio
|
||||||
|
from tabulate import tabulate
|
||||||
|
from typing import Dict, List
|
||||||
|
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
|
||||||
|
import inspect
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
# 设置全局日志级别为WARNING,抑制INFO级别日志
|
||||||
|
logging.basicConfig(level=logging.WARNING)
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncPerformanceTester:
|
||||||
|
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": []
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _check_ollama_service(self, base_url: str, model_name: str) -> bool:
|
||||||
|
"""异步检查Ollama服务状态"""
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
try:
|
||||||
|
# 检查服务是否可用
|
||||||
|
async with session.get(f"{base_url}/api/version") as response:
|
||||||
|
if response.status != 200:
|
||||||
|
print(f"🚫 Ollama服务未启动或无法访问: {base_url}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 检查模型是否存在
|
||||||
|
async with session.get(f"{base_url}/api/tags") as response:
|
||||||
|
if response.status == 200:
|
||||||
|
data = await response.json()
|
||||||
|
models = data.get("models", [])
|
||||||
|
if not any(model["name"] == model_name for model in models):
|
||||||
|
print(f"🚫 Ollama模型 {model_name} 未找到,请先使用 ollama pull {model_name} 下载")
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
print(f"🚫 无法获取Ollama模型列表")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"🚫 无法连接到Ollama服务: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async 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 {"name": tts_name, "type": "tts", "errors": 1}
|
||||||
|
|
||||||
|
module_type = config.get('type', tts_name)
|
||||||
|
tts = create_tts_instance(
|
||||||
|
module_type,
|
||||||
|
config,
|
||||||
|
delete_audio_file=True
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"🎵 测试 TTS: {tts_name}")
|
||||||
|
|
||||||
|
tmp_file = tts.generate_filename()
|
||||||
|
await tts.text_to_speak("连接测试", tmp_file)
|
||||||
|
|
||||||
|
if not tmp_file or not os.path.exists(tmp_file):
|
||||||
|
print(f"❌ {tts_name} 连接失败")
|
||||||
|
return {"name": tts_name, "type": "tts", "errors": 1}
|
||||||
|
|
||||||
|
total_time = 0
|
||||||
|
test_count = len(self.test_sentences[:2])
|
||||||
|
|
||||||
|
for i, sentence in enumerate(self.test_sentences[:2], 1):
|
||||||
|
start = time.time()
|
||||||
|
tmp_file = tts.generate_filename()
|
||||||
|
await tts.text_to_speak(sentence, tmp_file)
|
||||||
|
duration = time.time() - start
|
||||||
|
total_time += duration
|
||||||
|
|
||||||
|
if tmp_file and os.path.exists(tmp_file):
|
||||||
|
print(f"✓ {tts_name} [{i}/{test_count}]")
|
||||||
|
else:
|
||||||
|
print(f"✗ {tts_name} [{i}/{test_count}]")
|
||||||
|
return {"name": tts_name, "type": "tts", "errors": 1}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"name": tts_name,
|
||||||
|
"type": "tts",
|
||||||
|
"avg_time": total_time / test_count,
|
||||||
|
"errors": 0
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ {tts_name} 测试失败: {str(e)}")
|
||||||
|
return {"name": tts_name, "type": "tts", "errors": 1}
|
||||||
|
|
||||||
|
async def _test_llm(self, llm_name: str, config: Dict) -> Dict:
|
||||||
|
"""异步测试单个LLM性能"""
|
||||||
|
try:
|
||||||
|
# 对于Ollama,跳过api_key检查并进行特殊处理
|
||||||
|
if llm_name == "Ollama":
|
||||||
|
base_url = config.get('base_url', 'http://localhost:11434')
|
||||||
|
model_name = config.get('model_name')
|
||||||
|
if not model_name:
|
||||||
|
print(f"🚫 Ollama未配置model_name")
|
||||||
|
return {"name": llm_name, "type": "llm", "errors": 1}
|
||||||
|
|
||||||
|
if not await self._check_ollama_service(base_url, model_name):
|
||||||
|
return {"name": llm_name, "type": "llm", "errors": 1}
|
||||||
|
else:
|
||||||
|
if "api_key" in config and any(x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]):
|
||||||
|
print(f"🚫 跳过未配置的LLM: {llm_name}")
|
||||||
|
return {"name": llm_name, "type": "llm", "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]
|
||||||
|
|
||||||
|
# 创建所有句子的测试任务
|
||||||
|
sentence_tasks = []
|
||||||
|
for sentence in test_sentences:
|
||||||
|
sentence_tasks.append(self._test_single_sentence(llm_name, llm, sentence))
|
||||||
|
|
||||||
|
# 并发执行所有句子测试
|
||||||
|
sentence_results = await asyncio.gather(*sentence_tasks)
|
||||||
|
|
||||||
|
# 处理结果
|
||||||
|
valid_results = [r for r in sentence_results if r is not None]
|
||||||
|
if not valid_results:
|
||||||
|
print(f"⚠️ {llm_name} 无有效数据,可能配置错误")
|
||||||
|
return {"name": llm_name, "type": "llm", "errors": 1}
|
||||||
|
|
||||||
|
first_token_times = [r["first_token_time"] for r in valid_results]
|
||||||
|
response_times = [r["response_time"] for r in valid_results]
|
||||||
|
|
||||||
|
# 过滤异常数据
|
||||||
|
mean = statistics.mean(response_times)
|
||||||
|
stdev = statistics.stdev(response_times) if len(response_times) > 1 else 0
|
||||||
|
filtered_times = [t for t in response_times if t <= mean + 3 * stdev]
|
||||||
|
|
||||||
|
if len(filtered_times) < len(test_sentences) * 0.5:
|
||||||
|
print(f"⚠️ {llm_name} 有效数据不足,可能网络不稳定")
|
||||||
|
return {"name": llm_name, "type": "llm", "errors": 1}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"name": llm_name,
|
||||||
|
"type": "llm",
|
||||||
|
"avg_response": sum(response_times) / len(response_times),
|
||||||
|
"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(response_times) if len(response_times) > 1 else 0,
|
||||||
|
"errors": 0
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"LLM {llm_name} 测试失败: {str(e)}")
|
||||||
|
return {"name": llm_name, "type": "llm", "errors": 1}
|
||||||
|
|
||||||
|
async def _test_single_sentence(self, llm_name: str, llm, sentence: str) -> Dict:
|
||||||
|
"""测试单个句子的性能"""
|
||||||
|
try:
|
||||||
|
print(f"📝 {llm_name} 开始测试: {sentence[:20]}...")
|
||||||
|
sentence_start = time.time()
|
||||||
|
first_token_received = False
|
||||||
|
first_token_time = None
|
||||||
|
|
||||||
|
async def process_response():
|
||||||
|
nonlocal first_token_received, first_token_time
|
||||||
|
for chunk in llm.response("perf_test", [{"role": "user", "content": sentence}]):
|
||||||
|
if not first_token_received and chunk.strip() != '':
|
||||||
|
first_token_time = time.time() - sentence_start
|
||||||
|
first_token_received = True
|
||||||
|
print(f"✓ {llm_name} 首个Token: {first_token_time:.3f}s")
|
||||||
|
yield chunk
|
||||||
|
|
||||||
|
response_chunks = []
|
||||||
|
async for chunk in process_response():
|
||||||
|
response_chunks.append(chunk)
|
||||||
|
|
||||||
|
response_time = time.time() - sentence_start
|
||||||
|
print(f"✓ {llm_name} 完成响应: {response_time:.3f}s")
|
||||||
|
|
||||||
|
if first_token_time is None:
|
||||||
|
first_token_time = response_time # 如果没有检测到first token,使用总响应时间
|
||||||
|
|
||||||
|
return {
|
||||||
|
"name": llm_name,
|
||||||
|
"type": "llm",
|
||||||
|
"first_token_time": first_token_time,
|
||||||
|
"response_time": response_time
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ {llm_name} 句子测试失败: {str(e)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _generate_combinations(self):
|
||||||
|
"""生成最佳组合建议"""
|
||||||
|
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]
|
||||||
|
|
||||||
|
# 找出基准值
|
||||||
|
min_first_token = min([self.results["llm"][llm]["avg_first_token"] for llm in valid_llms]) if valid_llms else 1
|
||||||
|
min_tts_time = min([self.results["tts"][tts]["avg_time"] for tts in valid_tts]) if valid_tts else 1
|
||||||
|
|
||||||
|
for llm in valid_llms:
|
||||||
|
for tts in valid_tts:
|
||||||
|
# 计算相对性能分数(越小越好)
|
||||||
|
llm_score = self.results["llm"][llm]["avg_first_token"] / min_first_token
|
||||||
|
tts_score = self.results["tts"][tts]["avg_time"] / min_tts_time
|
||||||
|
|
||||||
|
# 计算稳定性分数(标准差/平均值,越小越稳定)
|
||||||
|
llm_stability = self.results["llm"][llm]["std_first_token"] / self.results["llm"][llm][
|
||||||
|
"avg_first_token"]
|
||||||
|
|
||||||
|
# 综合得分(考虑性能和稳定性)
|
||||||
|
# 性能权重0.7,稳定性权重0.3
|
||||||
|
llm_final_score = llm_score * 0.7 + llm_stability * 0.3
|
||||||
|
|
||||||
|
# 总分 = LLM得分(70%) + TTS得分(30%)
|
||||||
|
total_score = llm_final_score * 0.7 + tts_score * 0.3
|
||||||
|
|
||||||
|
self.results["combinations"].append({
|
||||||
|
"llm": llm,
|
||||||
|
"tts": tts,
|
||||||
|
"score": total_score,
|
||||||
|
"details": {
|
||||||
|
"llm_first_token": self.results["llm"][llm]["avg_first_token"],
|
||||||
|
"llm_stability": llm_stability,
|
||||||
|
"tts_time": self.results["tts"][tts]["avg_time"]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
# 分数越小越好
|
||||||
|
self.results["combinations"].sort(key=lambda x: x["score"])
|
||||||
|
|
||||||
|
def _print_results(self):
|
||||||
|
"""打印测试结果"""
|
||||||
|
llm_table = []
|
||||||
|
for name, data in self.results["llm"].items():
|
||||||
|
if data["errors"] == 0:
|
||||||
|
stability = data["std_first_token"] / data["avg_first_token"]
|
||||||
|
llm_table.append([
|
||||||
|
name, # 不需要固定宽度,让tabulate自己处理对齐
|
||||||
|
f"{data['avg_first_token']:.3f}秒",
|
||||||
|
f"{data['avg_response']:.3f}秒",
|
||||||
|
f"{stability:.3f}"
|
||||||
|
])
|
||||||
|
|
||||||
|
if llm_table:
|
||||||
|
print("\nLLM 性能排行:")
|
||||||
|
print(tabulate(
|
||||||
|
llm_table,
|
||||||
|
headers=["模型名称", "首字耗时", "总耗时", "稳定性"],
|
||||||
|
tablefmt="github",
|
||||||
|
colalign=("left", "right", "right", "right"),
|
||||||
|
disable_numparse=True
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
print("\n⚠️ 没有可用的LLM模块进行测试。")
|
||||||
|
|
||||||
|
tts_table = []
|
||||||
|
for name, data in self.results["tts"].items():
|
||||||
|
if data["errors"] == 0:
|
||||||
|
tts_table.append([
|
||||||
|
name, # 不需要固定宽度
|
||||||
|
f"{data['avg_time']:.3f}秒"
|
||||||
|
])
|
||||||
|
|
||||||
|
if tts_table:
|
||||||
|
print("\nTTS 性能排行:")
|
||||||
|
print(tabulate(
|
||||||
|
tts_table,
|
||||||
|
headers=["模型名称", "合成耗时"],
|
||||||
|
tablefmt="github",
|
||||||
|
colalign=("left", "right"),
|
||||||
|
disable_numparse=True
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
print("\n⚠️ 没有可用的TTS模块进行测试。")
|
||||||
|
|
||||||
|
if self.results["combinations"]:
|
||||||
|
print("\n推荐配置组合 (得分越小越好):")
|
||||||
|
combo_table = []
|
||||||
|
for combo in self.results["combinations"][:5]:
|
||||||
|
combo_table.append([
|
||||||
|
f"{combo['llm']} + {combo['tts']}", # 不需要固定宽度
|
||||||
|
f"{combo['score']:.3f}",
|
||||||
|
f"{combo['details']['llm_first_token']:.3f}秒",
|
||||||
|
f"{combo['details']['llm_stability']:.3f}",
|
||||||
|
f"{combo['details']['tts_time']:.3f}秒"
|
||||||
|
])
|
||||||
|
|
||||||
|
print(tabulate(
|
||||||
|
combo_table,
|
||||||
|
headers=["组合方案", "综合得分", "LLM首字耗时", "稳定性", "TTS合成耗时"],
|
||||||
|
tablefmt="github",
|
||||||
|
colalign=("left", "right", "right", "right", "right"),
|
||||||
|
disable_numparse=True
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
print("\n⚠️ 没有可用的模块组合建议。")
|
||||||
|
|
||||||
|
def _process_results(self, all_results):
|
||||||
|
"""处理测试结果"""
|
||||||
|
for result in all_results:
|
||||||
|
if result["errors"] == 0:
|
||||||
|
if result["type"] == "llm":
|
||||||
|
self.results["llm"][result["name"]] = result
|
||||||
|
else:
|
||||||
|
self.results["tts"][result["name"]] = result
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行全量异步测试"""
|
||||||
|
print("🔍 开始筛选可用模块...")
|
||||||
|
|
||||||
|
# 创建所有测试任务
|
||||||
|
all_tasks = []
|
||||||
|
|
||||||
|
# LLM测试任务
|
||||||
|
for llm_name, config in self.config.get("LLM", {}).items():
|
||||||
|
# 检查配置有效性
|
||||||
|
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
|
||||||
|
elif "api_key" in config and any(x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]):
|
||||||
|
print(f"⏭️ LLM {llm_name} 未配置api_key,已跳过")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 对于Ollama,先检查服务状态
|
||||||
|
if llm_name == "Ollama":
|
||||||
|
base_url = config.get('base_url', 'http://localhost:11434')
|
||||||
|
model_name = config.get('model_name')
|
||||||
|
if not model_name:
|
||||||
|
print(f"🚫 Ollama未配置model_name")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not await self._check_ollama_service(base_url, model_name):
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"📋 添加LLM测试任务: {llm_name}")
|
||||||
|
module_type = config.get('type', llm_name)
|
||||||
|
llm = create_llm_instance(module_type, config)
|
||||||
|
|
||||||
|
# 为每个句子创建独立任务
|
||||||
|
for sentence in self.test_sentences:
|
||||||
|
sentence = sentence.encode('utf-8').decode('utf-8')
|
||||||
|
all_tasks.append(self._test_single_sentence(llm_name, llm, sentence))
|
||||||
|
|
||||||
|
# TTS测试任务
|
||||||
|
for tts_name, config in self.config.get("TTS", {}).items():
|
||||||
|
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}")
|
||||||
|
all_tasks.append(self._test_tts(tts_name, config))
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"\n✅ 找到 {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} 个可用LLM模块")
|
||||||
|
print(f"✅ 找到 {len([t for t in all_tasks if '_test_tts' in str(t)])} 个可用TTS模块")
|
||||||
|
print("\n⏳ 开始并发测试所有模块...\n")
|
||||||
|
|
||||||
|
# 并发执行所有测试任务
|
||||||
|
all_results = await asyncio.gather(*all_tasks, return_exceptions=True)
|
||||||
|
|
||||||
|
# 处理LLM结果
|
||||||
|
llm_results = {}
|
||||||
|
for result in [r for r in all_results if r and isinstance(r, dict) and r.get("type") == "llm"]:
|
||||||
|
llm_name = result["name"]
|
||||||
|
if llm_name not in llm_results:
|
||||||
|
llm_results[llm_name] = {
|
||||||
|
"name": llm_name,
|
||||||
|
"type": "llm",
|
||||||
|
"first_token_times": [],
|
||||||
|
"response_times": [],
|
||||||
|
"errors": 0
|
||||||
|
}
|
||||||
|
llm_results[llm_name]["first_token_times"].append(result["first_token_time"])
|
||||||
|
llm_results[llm_name]["response_times"].append(result["response_time"])
|
||||||
|
|
||||||
|
# 计算LLM平均值和标准差
|
||||||
|
for llm_name, data in llm_results.items():
|
||||||
|
if len(data["first_token_times"]) >= len(self.test_sentences) * 0.5:
|
||||||
|
self.results["llm"][llm_name] = {
|
||||||
|
"name": llm_name,
|
||||||
|
"type": "llm",
|
||||||
|
"avg_response": sum(data["response_times"]) / len(data["response_times"]),
|
||||||
|
"avg_first_token": sum(data["first_token_times"]) / len(data["first_token_times"]),
|
||||||
|
"std_first_token": statistics.stdev(data["first_token_times"]) if len(
|
||||||
|
data["first_token_times"]) > 1 else 0,
|
||||||
|
"std_response": statistics.stdev(data["response_times"]) if len(data["response_times"]) > 1 else 0,
|
||||||
|
"errors": 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# 处理TTS结果
|
||||||
|
for result in [r for r in all_results if r and isinstance(r, dict) and r.get("type") == "tts"]:
|
||||||
|
if result["errors"] == 0:
|
||||||
|
self.results["tts"][result["name"]] = result
|
||||||
|
|
||||||
|
# 生成组合建议并打印结果
|
||||||
|
print("\n📊 生成测试报告...")
|
||||||
|
self._generate_combinations()
|
||||||
|
self._print_results()
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
tester = AsyncPerformanceTester()
|
||||||
|
await tester.run()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
677
poetry.lock
generated
|
|
@ -11,7 +11,6 @@ pyyml = "0.0.2"
|
||||||
torch = "2.2.2"
|
torch = "2.2.2"
|
||||||
silero-vad = "5.1.2"
|
silero-vad = "5.1.2"
|
||||||
websockets = "14.2"
|
websockets = "14.2"
|
||||||
opuslib = "3.0.1"
|
|
||||||
numpy = "1.26.4"
|
numpy = "1.26.4"
|
||||||
pydub = "0.25.1"
|
pydub = "0.25.1"
|
||||||
funasr = "1.2.3"
|
funasr = "1.2.3"
|
||||||
|
|
@ -26,13 +25,9 @@ ormsgpack = "1.7.0"
|
||||||
ruamel-yaml = "0.18.10"
|
ruamel-yaml = "0.18.10"
|
||||||
setuptools = "^75.8.0"
|
setuptools = "^75.8.0"
|
||||||
loguru = "^0.7.3"
|
loguru = "^0.7.3"
|
||||||
|
opuslib-next = "^1.1.2"
|
||||||
|
|
||||||
|
|
||||||
[[tool.poetry.source]]
|
|
||||||
name = "mirrors"
|
|
||||||
url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
|
|
||||||
priority = "primary"
|
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["poetry-core"]
|
requires = ["poetry-core"]
|
||||||
build-backend = "poetry.core.masonry.api"
|
build-backend = "poetry.core.masonry.api"
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ pyyml==0.0.2
|
||||||
torch==2.2.2
|
torch==2.2.2
|
||||||
silero_vad==5.1.2
|
silero_vad==5.1.2
|
||||||
websockets==14.2
|
websockets==14.2
|
||||||
opuslib==3.0.1
|
opuslib_next==1.1.2
|
||||||
numpy==1.26.4
|
numpy==1.26.4
|
||||||
pydub==0.25.1
|
pydub==0.25.1
|
||||||
funasr==1.2.3
|
funasr==1.2.3
|
||||||
|
|
@ -16,3 +16,4 @@ aiohttp_cors==0.7.0
|
||||||
ormsgpack==1.7.0
|
ormsgpack==1.7.0
|
||||||
ruamel.yaml==0.18.10
|
ruamel.yaml==0.18.10
|
||||||
loguru==0.7.3
|
loguru==0.7.3
|
||||||
|
requests>=2.0.0
|
||||||