Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98c314a485 | ||
|
|
a377d89dcd | ||
|
|
d687121e99 | ||
|
|
badf6fe3d0 | ||
|
|
adb4a15f2d | ||
|
|
a5f9a782d6 | ||
|
|
ca8ff121d4 | ||
|
|
9f63b255fb | ||
|
|
9d34360a2c | ||
|
|
2f18e2ee0a | ||
|
|
fd05dd5159 | ||
|
|
ba22f5b765 | ||
|
|
ffd4ab74d7 | ||
|
|
f0ebebfa85 | ||
|
|
61136b958b | ||
|
|
05f0da0639 | ||
|
|
af1982c424 | ||
|
|
9bd668aebc | ||
|
|
d027432432 | ||
|
|
3972df6e4e | ||
|
|
8f2dda09cf | ||
|
|
d4ff9c5c17 | ||
|
|
3709540efd | ||
|
|
333050ae2e | ||
|
|
95ce49ffc9 | ||
|
|
be75e7bd39 | ||
|
|
24fbf7eee2 | ||
|
|
855a64cbb9 | ||
|
|
fdf280f84a | ||
|
|
498191519c | ||
|
|
f614489d81 | ||
|
|
6f958ee4a6 | ||
|
|
b226ee5430 | ||
|
|
9c30b5e035 | ||
|
|
d531d04281 | ||
|
|
d8f8a4a083 | ||
|
|
37d4330224 | ||
|
|
7873984f9f | ||
|
|
6840210ea8 | ||
|
|
0a54124d0d | ||
|
|
ddc441bc59 | ||
|
|
9b7fb3e826 | ||
|
|
a6cdbf9410 | ||
|
|
75fd5d8cc3 | ||
|
|
6fe5630346 |
No files matched your search
@@ -22,6 +22,7 @@
|
|||||||
<a href="./docs/readme/README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
<a href="./docs/readme/README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./docs/readme/README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./docs/readme/README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
<a href="./docs/readme/README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
<a href="./docs/readme/README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
|
<a href="./docs/readme/README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
@@ -169,8 +170,8 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
|
|||||||
#### 🚀 部署方式选择
|
#### 🚀 部署方式选择
|
||||||
| 部署方式 | 特点 | 适用场景 | 部署文档 | 配置要求 | 视频教程 |
|
| 部署方式 | 特点 | 适用场景 | 部署文档 | 配置要求 | 视频教程 |
|
||||||
|---------|------|---------|---------|---------|---------|
|
|---------|------|---------|---------|---------|---------|
|
||||||
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①Docker版](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②源码部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 如果使用`FunASR`要2核4G,如果全API,要2核2G | - |
|
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①Docker版](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②源码部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 本地跑 `FunASR` 较耗内存,全部走 API 时资源占用低 | - |
|
||||||
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①Docker版](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②源码部署](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③源码部署自动更新教程](./docs/dev-ops-integration.md) | 如果使用`FunASR`要4核8G,如果全API,要2核4G| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①Docker版](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②源码部署](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③源码部署自动更新教程](./docs/dev-ops-integration.md) | 本地跑 `FunASR` 较耗内存,另需数据库资源,全部走 API 时资源占用低| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
常见问题及相关教程,可参考[这个链接](./docs/FAQ.md)
|
常见问题及相关教程,可参考[这个链接](./docs/FAQ.md)
|
||||||
|
|
||||||
@@ -211,8 +212,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||||||
|
|
||||||
| 工具名称 | 位置 | 使用方法 | 功能说明 |
|
| 工具名称 | 位置 | 使用方法 | 功能说明 |
|
||||||
|:---:|:---|:---:|:---:|
|
|:---:|:---|:---:|:---:|
|
||||||
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 执行 `python start.py` 后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
|
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 按其 README 装好依赖后执行 `python start.py`,然后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
|
||||||
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)三个核心模块的响应速度 |
|
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)等核心模块的响应速度 |
|
||||||
|
|
||||||
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。
|
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。
|
||||||
|
|
||||||
@@ -232,10 +233,10 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||||||
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
|
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
|
||||||
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
|
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
|
||||||
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
|
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
|
||||||
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文显示 |
|
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文、德语、越南语、巴西葡萄牙语显示 |
|
||||||
| 测试工具 | 提供性能测试工具、视觉模型测试工具和音频交互测试工具 |
|
| 测试工具 | 提供模型响应性能测试工具和音频交互测试工具 |
|
||||||
| 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 |
|
| 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 |
|
||||||
| 插件系统 | 支持功能插件扩展、自定义插件开发和插件热加载 |
|
| 插件系统 | 支持功能插件扩展、自定义插件开发;新增插件文件在下次设备连接时自动加载,改动已加载插件的代码需重启服务 |
|
||||||
|
|
||||||
### 正在开发 🚧
|
### 正在开发 🚧
|
||||||
|
|
||||||
@@ -255,7 +256,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||||||
|
|
||||||
| 使用方式 | 支持平台 | 免费平台 |
|
| 使用方式 | 支持平台 | 免费平台 |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞 | 智谱、Gemini |
|
| openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞、LM Studio | 智谱、Gemini |
|
||||||
| ollama 接口调用 | Ollama | - |
|
| ollama 接口调用 | Ollama | - |
|
||||||
| dify 接口调用 | Dify | - |
|
| dify 接口调用 | Dify | - |
|
||||||
| fastgpt 接口调用 | Fastgpt | - |
|
| fastgpt 接口调用 | Fastgpt | - |
|
||||||
@@ -281,8 +282,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||||||
|
|
||||||
| 使用方式 | 支持平台 | 免费平台 |
|
| 使用方式 | 支持平台 | 免费平台 |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS、灵犀流式TTS、MinimaxTTS | 灵犀流式TTS、EdgeTTS、CosyVoiceSiliconflow(部分) |
|
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、CustomTTS、OpenAITTS、MinimaxTTS | EdgeTTS、CosyVoiceSiliconflow(部分) |
|
||||||
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、Index-TTS、PaddleSpeech | Index-TTS、PaddleSpeech、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
|
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、IndexStreamTTS、PaddleSpeechTTS | IndexStreamTTS、PaddleSpeechTTS、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -298,8 +299,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||||||
|
|
||||||
| 使用方式 | 支持平台 | 免费平台 |
|
| 使用方式 | 支持平台 | 免费平台 |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR |
|
| 本地使用 | FunASR、SherpaASR、SherpaParaformerASR、VoskASR | FunASR、SherpaASR、SherpaParaformerASR、VoskASR |
|
||||||
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云、百度云、OpenAI ASR | FunASRServer |
|
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云及百炼、百度云、OpenAI ASR、GroqASR、Qwen3ASRFlash | FunASRServer |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -307,7 +308,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
|||||||
|
|
||||||
| 使用方式 | 支持平台 | 免费平台 |
|
| 使用方式 | 支持平台 | 免费平台 |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| 本地使用 | 3D-Speaker | 3D-Speaker |
|
| 接口调用 | 声纹识别服务(voiceprint-api) | - |
|
||||||
|
|
||||||
|
声纹识别需要单独部署 [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) 服务(基于 3D-Speaker),并依赖 MySQL,详见[声纹识别启用指南](./docs/voiceprint-integration.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# 语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
|
# 语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
|
||||||
|
|
||||||
1.在main/xiaozhi-server目录下创建data目录
|
1.在main/xiaozhi-server目录下创建data目录
|
||||||
2.在data目录下创建.config.yaml文件
|
2.在data目录下创建.config.yaml文件
|
||||||
|
|||||||
+38
-36
@@ -6,7 +6,7 @@
|
|||||||
Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme<br/>und bietet Backend-Dienste für das Open-Source-Hardware-Projekt
|
Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme<br/>und bietet Backend-Dienste für das Open-Source-Hardware-Projekt
|
||||||
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||||
Implementiert mit Python, Java und Vue gemäß dem <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi-Kommunikationsprotokoll</a><br/>
|
Implementiert mit Python, Java und Vue gemäß dem <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi-Kommunikationsprotokoll</a><br/>
|
||||||
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung
|
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte, Stimmabdruckerkennung und Wissensdatenbank
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@@ -22,6 +22,7 @@ Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabd
|
|||||||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
|
||||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
|
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
@@ -54,31 +55,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
<img alt="Gefühl der Antwortgeschwindigkeit" src="../images/demo9.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
<img alt="Das Geheimnis der Geschwindigkeitsoptimierung" src="../images/demo6.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
<img alt="Xiaozhi-Digitalmensch mit Sprachaktivierung" src="../images/demo8.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
<img alt="Anruf von Gerät zu Gerät" src="../images/demo0.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
<img alt="Komplexes medizinisches Szenario" src="../images/demo1.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -86,31 +87,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
<img alt="Musik abspielen, Wetter abfragen und Nachrichten vorlesen" src="../images/demo7.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
<img alt="Unterbrechung in Echtzeit" src="../images/demo10.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
<img alt="Objekte per Foto erkennen" src="../images/demo12.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
<img alt="Haushaltsgeräte ein- und ausschalten" src="../images/demo5.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
<img alt="Aufgaben mit mehreren Befehlen" src="../images/demo11.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -118,31 +119,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
<img alt="MCP-Endpunkt" src="../images/demo13.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
<img alt="MQTT-Befehlsübermittlung" src="../images/demo4.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
<img alt="Stimmabdruckerkennung" src="../images/demo14.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
<img alt="Eigene Stimmfarbe" src="../images/demo2.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
<img alt="Gespräch auf Kantonesisch" src="../images/demo3.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -167,8 +168,8 @@ Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend
|
|||||||
#### 🚀 Auswahl der Bereitstellungsmethode
|
#### 🚀 Auswahl der Bereitstellungsmethode
|
||||||
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
|
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
|
||||||
|---------|------|---------|---------|---------|---------|
|
|---------|------|---------|---------|---------|---------|
|
||||||
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 Kerne 4GB bei Verwendung von `FunASR`, 2 Kerne 2GB bei allen APIs | - |
|
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Lokales `FunASR` benötigt mehr Arbeitsspeicher; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering | - |
|
||||||
| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](../dev-ops-integration.md) | 4 Kerne 8GB bei Verwendung von `FunASR`, 2 Kerne 4GB bei allen APIs| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](../dev-ops-integration.md) | Lokales `FunASR` benötigt mehr Arbeitsspeicher, zusätzlich werden Datenbankressourcen benötigt; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](../FAQ.md)
|
Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](../FAQ.md)
|
||||||
|
|
||||||
@@ -209,15 +210,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
|
|||||||
|
|
||||||
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|
||||||
|:---:|:---|:---:|:---:|
|
|:---:|:---|:---:|:---:|
|
||||||
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` `python start.py` ausführen und dann `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
|
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` zuerst die Abhängigkeiten wie in der README installieren, dann `python start.py` ausführen und `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
|
||||||
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) drei Kernmodulen |
|
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von Kernmodulen wie ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) |
|
||||||
|
|
||||||
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
|
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
|
||||||
|
|
||||||
---
|
---
|
||||||
## Funktionsliste ✨
|
## Funktionsliste ✨
|
||||||
### Implementiert ✅
|
### Implementiert ✅
|
||||||

|

|
||||||
| Funktionsmodul | Beschreibung |
|
| Funktionsmodul | Beschreibung |
|
||||||
|:---:|:---|
|
|:---:|:---|
|
||||||
| Kernarchitektur | Basierend auf [MQTT+UDP-Gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket und HTTP-Servern, bietet vollständiges Konsolenverwaltungs- und Authentifizierungssystem |
|
| Kernarchitektur | Basierend auf [MQTT+UDP-Gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket und HTTP-Servern, bietet vollständiges Konsolenverwaltungs- und Authentifizierungssystem |
|
||||||
@@ -225,15 +226,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
|
|||||||
| Stimmabdruckerkennung | Unterstützt Mehrbenutzer-Stimmabdruckregistrierung, -verwaltung und -erkennung, verarbeitet parallel mit ASR, Echtzeit-Sprecheridentitätserkennung und Weitergabe an LLM für personalisierte Antworten |
|
| Stimmabdruckerkennung | Unterstützt Mehrbenutzer-Stimmabdruckregistrierung, -verwaltung und -erkennung, verarbeitet parallel mit ASR, Echtzeit-Sprecheridentitätserkennung und Weitergabe an LLM für personalisierte Antworten |
|
||||||
| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
|
| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
|
||||||
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
|
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
|
||||||
| Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
|
| Absichtserkennung | Unterstützt externe LLM-Absichtserkennung, autonome Funktionsaufrufe durch große Modelle, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
|
||||||
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, PowerMem intelligentes Gedächtnis, mit Gedächtniszusammenfassungsfunktion |
|
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, PowerMem intelligentes Gedächtnis, mit Gedächtniszusammenfassungsfunktion |
|
||||||
| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
|
| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
|
||||||
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
|
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
|
||||||
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
|
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
|
||||||
| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch und englische Anzeige |
|
| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch, Englisch, Deutsch, Vietnamesisch und brasilianisches Portugiesisch an |
|
||||||
| Testwerkzeuge | Bietet Leistungstestwerkzeuge, Vision-Modell-Testwerkzeuge und Audio-Interaktionstestwerkzeuge |
|
| Testwerkzeuge | Bietet Leistungstestwerkzeuge für Modellantworten und Audio-Interaktionstestwerkzeuge |
|
||||||
| Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung |
|
| Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung |
|
||||||
| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen, benutzerdefinierte Plugin-Entwicklung und Plugin-Hot-Loading |
|
| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen und benutzerdefinierte Plugin-Entwicklung; neu hinzugefügte Plugin-Dateien werden bei der nächsten Geräteverbindung geladen, Änderungen an bereits geladenen Plugins erfordern einen Neustart des Dienstes |
|
||||||
|
|
||||||
### In Entwicklung 🚧
|
### In Entwicklung 🚧
|
||||||
|
|
||||||
@@ -253,7 +254,7 @@ Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich
|
|||||||
|
|
||||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, Volcano Engine AI Gateway, DeepSeek, Zhipu ChatGLM, Gemini, iFLYTEK, LM Studio | Zhipu ChatGLM, Gemini |
|
||||||
| Ollama-Schnittstellenaufrufe | Ollama | - |
|
| Ollama-Schnittstellenaufrufe | Ollama | - |
|
||||||
| Dify-Schnittstellenaufrufe | Dify | - |
|
| Dify-Schnittstellenaufrufe | Dify | - |
|
||||||
| FastGPT-Schnittstellenaufrufe | FastGPT | - |
|
| FastGPT-Schnittstellenaufrufe | FastGPT | - |
|
||||||
@@ -279,8 +280,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||||||
|
|
||||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Schnittstellenaufrufe | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS, Volcano Dual-Stream TTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow (teilweise) |
|
| Schnittstellenaufrufe | EdgeTTS, iFLYTEK, Volcano Engine Doubao TTS, Volcano Engine AI Gateway TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, Alibaba Bailian CosyVoice TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS, Volcano Dual-Stream TTS | EdgeTTS, CosyVoiceSiliconflow (teilweise) |
|
||||||
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -296,8 +297,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||||||
|
|
||||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Lokale Verwendung | FunASR, SherpaASR | FunASR, SherpaASR |
|
| Lokale Verwendung | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||||
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, FunASRServer, TencentASR, AliyunASR, Aliyun Streaming ASR, Baidu ASR, OpenAI ASR | FunASRServer |
|
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, Doubao Streaming ASR V2, FunASRServer, iFLYTEK, TencentASR, AliyunASR, Aliyun Streaming ASR, Alibaba Bailian Streaming ASR, Baidu ASR, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -305,7 +306,9 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||||||
|
|
||||||
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Lokale Verwendung | 3D-Speaker | 3D-Speaker |
|
| Schnittstellenaufrufe | Voiceprint-Dienst (voiceprint-api) | - |
|
||||||
|
|
||||||
|
Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)-Dienst (auf Basis von 3D-Speaker) sowie MySQL. Siehe [Anleitung zur Stimmabdruckerkennung](../voiceprint-integration.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -351,11 +354,10 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
|||||||
| <img src="../images/logo_contributors.png" width="160"> | [Code-Mitwirkende](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Dank an [alle Code-Mitwirkenden](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), Ihre Bemühungen haben das Projekt robuster und leistungsfähiger gemacht. |
|
| <img src="../images/logo_contributors.png" width="160"> | [Code-Mitwirkende](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Dank an [alle Code-Mitwirkenden](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), Ihre Bemühungen haben das Projekt robuster und leistungsfähiger gemacht. |
|
||||||
|
|
||||||
|
|
||||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||||
|
|
||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
+37
-35
@@ -22,6 +22,7 @@ Support for MQTT+UDP protocol, Websocket protocol, MCP access point, voiceprint
|
|||||||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
|
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
@@ -54,31 +55,31 @@ Want to see the usage effects? Click the videos below 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
<img alt="The feel of the response speed" src="../images/demo9.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
<img alt="The secret to speeding things up" src="../images/demo6.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
<img alt="Xiaozhi digital human with voice wake-up" src="../images/demo8.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
<img alt="Device-to-device calling" src="../images/demo0.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
<img alt="A complex medical scenario" src="../images/demo1.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -86,31 +87,31 @@ Want to see the usage effects? Click the videos below 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
<img alt="Play music, check the weather, and read the news" src="../images/demo7.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
<img alt="Real-time interruption" src="../images/demo10.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
<img alt="Take a photo to identify objects" src="../images/demo12.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
<img alt="Turn home appliances on and off" src="../images/demo5.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
<img alt="Multi-command tasks" src="../images/demo11.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -118,31 +119,31 @@ Want to see the usage effects? Click the videos below 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
<img alt="MCP access point" src="../images/demo13.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
<img alt="MQTT command delivery" src="../images/demo4.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
<img alt="Voiceprint recognition" src="../images/demo14.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
<img alt="Custom voice timbre" src="../images/demo2.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
<img alt="Talking in Cantonese" src="../images/demo3.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -167,8 +168,8 @@ This project provides two deployment methods. Please choose based on your specif
|
|||||||
#### 🚀 Deployment Method Selection
|
#### 🚀 Deployment Method Selection
|
||||||
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|
||||||
|---------|------|---------|---------|---------|---------|
|
|---------|------|---------|---------|---------|---------|
|
||||||
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 cores 4GB if using `FunASR`, 2 cores 2GB if all APIs | - |
|
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Local `FunASR` needs more memory; using APIs for everything keeps resource usage low | - |
|
||||||
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Source Code Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Source Code Deployment Auto-Update Tutorial](../dev-ops-integration.md) | 4 cores 8GB if using `FunASR`, 2 cores 4GB if all APIs| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Source Code Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Source Code Deployment Auto-Update Tutorial](../dev-ops-integration.md) | Local `FunASR` needs more memory plus database resources; using APIs for everything keeps resource usage low| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
For frequently asked questions and related tutorials, please refer to [this link](../FAQ.md)
|
For frequently asked questions and related tutorials, please refer to [this link](../FAQ.md)
|
||||||
|
|
||||||
@@ -209,15 +210,15 @@ This project provides the following testing tools to help you verify the system
|
|||||||
|
|
||||||
| Tool Name | Location | Usage Method | Function Description |
|
| Tool Name | Location | Usage Method | Function Description |
|
||||||
|:---:|:---|:---:|:---:|
|
|:---:|:---|:---:|:---:|
|
||||||
| Audio Interaction Test Tool | main》digital-human》index.html | Run `python start.py` in `main/digital-human`, then open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
|
| Audio Interaction Test Tool | main》digital-human》index.html | In `main/digital-human`, install dependencies as its README says, then run `python start.py` and open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
|
||||||
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
|
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of core modules such as ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
|
||||||
|
|
||||||
> 💡 Note: When testing model speed, only models with configured keys will be tested.
|
> 💡 Note: When testing model speed, only models with configured keys will be tested.
|
||||||
|
|
||||||
---
|
---
|
||||||
## Feature List ✨
|
## Feature List ✨
|
||||||
### Implemented ✅
|
### Implemented ✅
|
||||||

|

|
||||||
| Feature Module | Description |
|
| Feature Module | Description |
|
||||||
|:---:|:---|
|
|:---:|:---|
|
||||||
| Core Architecture | Based on [MQTT+UDP gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket and HTTP servers, provides complete console management and authentication system |
|
| Core Architecture | Based on [MQTT+UDP gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket and HTTP servers, provides complete console management and authentication system |
|
||||||
@@ -225,15 +226,15 @@ This project provides the following testing tools to help you verify the system
|
|||||||
| Voiceprint Recognition | Supports multi-user voiceprint registration, management, and recognition, processes in parallel with ASR, real-time speaker identity recognition and passes to LLM for personalized responses |
|
| Voiceprint Recognition | Supports multi-user voiceprint registration, management, and recognition, processes in parallel with ASR, real-time speaker identity recognition and passes to LLM for personalized responses |
|
||||||
| Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
|
| Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
|
||||||
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
|
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
|
||||||
| Intent Recognition | Supports LLM intent recognition, Function Call function calling, provides plugin-based intent processing mechanism |
|
| Intent Recognition | Supports pluggable external LLM intent recognition and autonomous LLM function calling, provides plugin-based intent processing mechanism |
|
||||||
| Memory System | Supports local short-term memory, mem0ai interface memory, PowerMem intelligent memory, with memory summarization functionality |
|
| Memory System | Supports local short-term memory, mem0ai interface memory, PowerMem intelligent memory, with memory summarization functionality |
|
||||||
| Knowledge Base | Supports RAGFlow knowledge base, enabling LLM to judge whether to schedule the knowledge base after receiving the user's question, and then answer the question |
|
| Knowledge Base | Supports RAGFlow knowledge base, enabling LLM to judge whether to schedule the knowledge base after receiving the user's question, and then answer the question |
|
||||||
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
|
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
|
||||||
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
|
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
|
||||||
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese and English display |
|
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese, English, German, Vietnamese and Brazilian Portuguese display |
|
||||||
| Testing Tools | Provides performance testing tools, vision model testing tools, and audio interaction testing tools |
|
| Testing Tools | Provides model response performance testing tools and audio interaction testing tools |
|
||||||
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
|
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
|
||||||
| Plugin System | Supports functional plugin extensions, custom plugin development, and plugin hot-loading |
|
| Plugin System | Supports functional plugin extensions and custom plugin development; newly added plugin files are loaded on the next device connection, code changes to already loaded plugins require a service restart |
|
||||||
|
|
||||||
### Under Development 🚧
|
### Under Development 🚧
|
||||||
|
|
||||||
@@ -253,7 +254,7 @@ Xiaozhi is an ecosystem. When using this product, you can also check out other [
|
|||||||
|
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
|
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||||
| Ollama interface calls | Ollama | - |
|
| Ollama interface calls | Ollama | - |
|
||||||
| Dify interface calls | Dify | - |
|
| Dify interface calls | Dify | - |
|
||||||
| FastGPT interface calls | FastGPT | - |
|
| FastGPT interface calls | FastGPT | - |
|
||||||
@@ -279,8 +280,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||||||
|
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(partial) |
|
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(partial) |
|
||||||
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -296,8 +297,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||||||
|
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Local use | FunASR, SherpaASR | FunASR, SherpaASR |
|
| Local use | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||||
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud and Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -305,7 +306,9 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||||||
|
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Local use | 3D-Speaker | 3D-Speaker |
|
| Interface calls | Voiceprint service (voiceprint-api) | - |
|
||||||
|
|
||||||
|
Voiceprint recognition requires a separately deployed [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) service (based on 3D-Speaker) and MySQL. See the [voiceprint integration guide](../voiceprint-integration.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -351,11 +354,10 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
|||||||
| <img src="../images/logo_contributors.png" width="160"> | [Code Contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Thanks to [all code contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), your efforts have made the project more robust and powerful. |
|
| <img src="../images/logo_contributors.png" width="160"> | [Code Contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Thanks to [all code contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), your efforts have made the project more robust and powerful. |
|
||||||
|
|
||||||
|
|
||||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||||
|
|
||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
[](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
||||||
|
|
||||||
|
<h1 align="center">Servicio backend Xiaozhi xiaozhi-esp32-server</h1>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
Este proyecto desarrolla sistemas de hardware y software para terminales inteligentes a partir de la teoría y la tecnología de la inteligencia simbiótica humano-máquina<br/>y ofrece el servicio backend del proyecto de hardware inteligente de código abierto
|
||||||
|
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||||
|
Implementado en Python, Java y Vue según el <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">protocolo de comunicación Xiaozhi</a><br/>
|
||||||
|
Compatible con el protocolo MQTT+UDP, el protocolo WebSocket, puntos de acceso MCP, reconocimiento de huella de voz y bases de conocimiento
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="../FAQ.md">Preguntas frecuentes</a>
|
||||||
|
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Informar de problemas</a>
|
||||||
|
· <a href="../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Documentación de despliegue</a>
|
||||||
|
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Notas de la versión</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="../../README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DFE0E5"></a>
|
||||||
|
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a>
|
||||||
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
|
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DBEDFA"></a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE">
|
||||||
|
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
|
||||||
|
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
Liderado por el equipo del profesor Siyuan Liu (Universidad Tecnológica del Sur de China)
|
||||||
|
</br>
|
||||||
|
刘思源教授团队主导研发(华南理工大学)
|
||||||
|
</br>
|
||||||
|
<img src="../images/hnlg.jpg" alt="Universidad Tecnológica del Sur de China (华南理工大学)" width="50%">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## A quién va dirigido 👥
|
||||||
|
|
||||||
|
Este proyecto debe usarse junto con hardware ESP32. Si ya ha comprado hardware relacionado con ESP32, se ha conectado con éxito al servicio backend desplegado por Brother Xia (虾哥) y quiere montar por su cuenta su propio servicio backend `xiaozhi-esp32`, este proyecto encaja con lo que busca.
|
||||||
|
|
||||||
|
¿Quiere ver cómo se usa? Pulse los vídeos 🎥
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Sensación de la velocidad de respuesta" src="../images/demo9.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="El secreto para optimizar la velocidad" src="../images/demo6.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Humano digital Xiaozhi con activación por voz" src="../images/demo8.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Llamadas de dispositivo a dispositivo" src="../images/demo0.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Escenario médico complejo" src="../images/demo1.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Reproducir música, consultar el tiempo y leer noticias" src="../images/demo7.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Interrupción en tiempo real" src="../images/demo10.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Reconocer objetos con una foto" src="../images/demo12.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Controlar el encendido de electrodomésticos" src="../images/demo5.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Tareas con varias instrucciones" src="../images/demo11.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Punto de acceso MCP" src="../images/demo13.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Envío de instrucciones MQTT" src="../images/demo4.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Reconocimiento de huella de voz" src="../images/demo14.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Tono de voz personalizado" src="../images/demo2.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Conversación en cantonés" src="../images/demo3.png" /></picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Advertencias ⚠️
|
||||||
|
|
||||||
|
1. Este proyecto es software de código abierto. Este software no mantiene relación comercial alguna con los proveedores de API de terceros a los que se conecta (incluidos, entre otros, plataformas de reconocimiento de voz, modelos de lenguaje y síntesis de voz), y no ofrece ninguna garantía sobre la calidad del servicio de dichos proveedores ni sobre la seguridad de sus fondos. Se recomienda elegir de forma preferente proveedores que cuenten con las licencias de actividad correspondientes y leer con atención sus condiciones de servicio y su política de privacidad. Este software no custodia ninguna clave de cuenta, no interviene en el movimiento de fondos y no asume el riesgo de pérdida del saldo recargado.
|
||||||
|
|
||||||
|
2. Las funciones de este proyecto no están completas y no ha superado una evaluación de seguridad de red. No lo utilice en entornos de producción. Si despliega este proyecto en una red pública con fines de aprendizaje, aplique las protecciones necesarias.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentación de despliegue
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Este proyecto ofrece dos formas de despliegue. Elija según lo que necesite:
|
||||||
|
|
||||||
|
#### 🚀 Elección del método de despliegue
|
||||||
|
| Método de despliegue | Características | Escenarios | Documentación de despliegue | Requisitos | Tutoriales en vídeo |
|
||||||
|
|---------|------|---------|---------|---------|---------|
|
||||||
|
| **Instalación simplificada** | Diálogo inteligente, gestión de un solo agente | Entornos con pocos recursos; los datos se guardan en archivos de configuración y no hace falta base de datos | [①Versión Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Despliegue desde el código fuente](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Ejecutar `FunASR` en local consume bastante memoria; si todo va por API, el consumo de recursos es bajo | - |
|
||||||
|
| **Instalación de todos los módulos** | Diálogo inteligente, gestión multiusuario, gestión de varios agentes, uso de la interfaz de la consola inteligente | Experiencia con todas las funciones; los datos se guardan en una base de datos |[①Versión Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Despliegue desde el código fuente](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de actualización automática desde el código fuente](../dev-ops-integration.md) | Ejecutar `FunASR` en local consume bastante memoria, y además requiere recursos de base de datos; si todo va por API, el consumo de recursos es bajo | [Tutorial en vídeo para arrancar el código fuente en local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
|
Las preguntas frecuentes y los tutoriales relacionados están en [este enlace](../FAQ.md)
|
||||||
|
|
||||||
|
> 💡 Nota: a continuación hay una plataforma de prueba desplegada con el código más reciente. Si lo necesita, puede grabar el firmware y probarla. La concurrencia es de 6 usuarios y los datos se borran cada día.
|
||||||
|
|
||||||
|
```
|
||||||
|
Dirección de la consola inteligente: https://2662r3426b.vicp.fun
|
||||||
|
Consola inteligente (versión H5): https://2662r3426b.vicp.fun/h5/index.html
|
||||||
|
|
||||||
|
Herramienta de prueba del servicio: https://2662r3426b.vicp.fun/test/
|
||||||
|
Dirección de la interfaz OTA: https://2662r3426b.vicp.fun/xiaozhi/ota/
|
||||||
|
Dirección de la interfaz WebSocket: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 🚩 Descripción y recomendaciones de configuración
|
||||||
|
> [!Note]
|
||||||
|
> Este proyecto ofrece dos esquemas de configuración:
|
||||||
|
>
|
||||||
|
> 1. `Configuración básica y totalmente gratuita`: adecuada para uso personal y doméstico. Todos los componentes usan opciones gratuitas y no hay que pagar nada más.
|
||||||
|
>
|
||||||
|
> 2. `Configuración en streaming`: adecuada para demostraciones, formación y escenarios con más de 2 usuarios concurrentes. Usa procesamiento en streaming, responde antes y se siente mejor.
|
||||||
|
>
|
||||||
|
> Desde la versión `0.5.2`, el proyecto admite la configuración en streaming. Frente a las versiones anteriores, el tiempo de respuesta mejora unos `2,5 segundos` y la experiencia de uso mejora de forma notable.
|
||||||
|
|
||||||
|
| Módulo | Configuración básica y totalmente gratuita | Configuración en streaming |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| ASR (reconocimiento de voz) | FunASR (local) | 👍XunfeiStreamASR (iFLYTEK en streaming) |
|
||||||
|
| LLM (modelo de lenguaje) | glm-4-flash (Zhipu) | 👍qwen-flash (Alibaba Bailian) |
|
||||||
|
| VLLM (modelo de visión) | glm-4v-flash (Zhipu) | 👍qwen3.5-flash (Alibaba Bailian) |
|
||||||
|
| TTS (síntesis de voz) | EdgeTTS (Microsoft) | 👍HuoshanDoubleStreamTTS (Volcano en streaming) |
|
||||||
|
| Intent (reconocimiento de intención) | function_call (llamada a funciones) | function_call (llamada a funciones) |
|
||||||
|
| Memory (memoria) | mem_local_short (memoria local a corto plazo) | mem_local_short (memoria local a corto plazo) |
|
||||||
|
|
||||||
|
Si le importa el tiempo que tarda cada componente, consulte el [informe de rendimiento de los componentes de Xiaozhi](https://github.com/xinnan-tech/xiaozhi-performance-research) y pruebe en su propio entorno con el método que describe el informe.
|
||||||
|
|
||||||
|
#### 🔧 Herramientas de prueba
|
||||||
|
Este proyecto incluye las siguientes herramientas para comprobar el sistema y elegir un modelo adecuado:
|
||||||
|
|
||||||
|
| Herramienta | Ubicación | Uso | Qué hace |
|
||||||
|
|:---:|:---|:---:|:---:|
|
||||||
|
| Prueba de interacción de audio | main》digital-human》index.html | En `main/digital-human`, instale las dependencias como indica su README, después ejecute `python start.py` y abra `http://127.0.0.1:8006/index.html` | Prueba la reproducción y la recepción de audio, y comprueba que el procesamiento de audio en Python funciona |
|
||||||
|
| Prueba de respuesta de los modelos | main》xiaozhi-server》performance_tester.py | Ejecute `python performance_tester.py` | Mide la velocidad de respuesta de los principales módulos: ASR (reconocimiento de voz), LLM (modelo de lenguaje), VLLM (modelo de visión) y TTS (síntesis de voz) |
|
||||||
|
|
||||||
|
> 💡 Nota: al medir la velocidad de los modelos, solo se prueban los modelos que tienen una clave configurada.
|
||||||
|
|
||||||
|
---
|
||||||
|
## Lista de funciones ✨
|
||||||
|
### Implementado ✅
|
||||||
|

|
||||||
|
| Módulo | Descripción |
|
||||||
|
|:---:|:---|
|
||||||
|
| Arquitectura principal | Basada en la [pasarela MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md) y en servidores WebSocket y HTTP; ofrece un sistema completo de gestión de consola y de autenticación |
|
||||||
|
| Interacción por voz | Admite ASR en streaming (reconocimiento de voz), TTS en streaming (síntesis de voz) y VAD (detección de actividad de voz), además de reconocimiento multilingüe y procesamiento de voz |
|
||||||
|
| Huella de voz | Admite el registro, la gestión y el reconocimiento de la huella de voz de varios usuarios; se procesa en paralelo con el ASR, identifica en tiempo real quién habla y se lo pasa al LLM para una respuesta personalizada |
|
||||||
|
| Diálogo inteligente | Admite varios LLM (modelos de lenguaje) para mantener un diálogo inteligente |
|
||||||
|
| Percepción visual | Admite varios VLLM (modelos de visión) para una interacción multimodal |
|
||||||
|
| Reconocimiento de intención | Admite el reconocimiento de intención con un modelo de lenguaje (LLM) externo y conectable, y la llamada autónoma a funciones del modelo, y ofrece un mecanismo de procesamiento de intenciones mediante plugins |
|
||||||
|
| Sistema de memoria | Admite memoria local a corto plazo, memoria por la interfaz mem0ai y memoria inteligente PowerMem, con resumen de la memoria |
|
||||||
|
| Base de conocimiento | Admite la base de conocimiento RAGFlow, para que el modelo decida si debe consultarla antes de responder |
|
||||||
|
| Llamada a herramientas | Admite el protocolo IOT del cliente, el protocolo MCP del cliente, el protocolo MCP del servidor, el protocolo de punto de acceso MCP y funciones de herramientas personalizadas |
|
||||||
|
| Envío de instrucciones | Apoyado en el protocolo MQTT, permite enviar instrucciones MCP desde la consola inteligente a los dispositivos ESP32 |
|
||||||
|
| Backend de administración | Ofrece una interfaz web de administración, con gestión de usuarios, configuración del sistema y gestión de dispositivos. La interfaz se muestra en chino simplificado, chino tradicional, inglés, alemán, vietnamita y portugués de Brasil |
|
||||||
|
| Herramientas de prueba | Incluye herramientas de prueba de rendimiento y de interacción de audio |
|
||||||
|
| Soporte de despliegue | Admite el despliegue con Docker y el despliegue local, y ofrece una gestión completa de los archivos de configuración |
|
||||||
|
| Sistema de plugins | Admite extensiones de plugins funcionales y el desarrollo de plugins propios; los nuevos archivos de plugin se cargan automáticamente en la siguiente conexión del dispositivo, y los cambios en el código de un plugin ya cargado requieren reiniciar el servicio |
|
||||||
|
|
||||||
|
### En desarrollo 🚧
|
||||||
|
|
||||||
|
Para ver el avance concreto del plan de desarrollo, [pulse aquí](https://github.com/users/xinnan-tech/projects/3). Las preguntas frecuentes y los tutoriales relacionados están en [este enlace](../FAQ.md)
|
||||||
|
|
||||||
|
Si desarrolla software, aquí tiene una [carta abierta a quienes desarrollan](../contributor_open_letter.md). La invitación está hecha.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ecosistema del producto 👬
|
||||||
|
Xiaozhi es un ecosistema. Al usar este producto, también puede ver otros [proyectos destacados](https://github.com/78/xiaozhi-esp32/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) de este ecosistema
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plataformas y componentes compatibles 📋
|
||||||
|
### LLM, modelos de lenguaje
|
||||||
|
|
||||||
|
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||||
|
| Llamadas por la interfaz Ollama | Ollama | - |
|
||||||
|
| Llamadas por la interfaz Dify | Dify | - |
|
||||||
|
| Llamadas por la interfaz FastGPT | FastGPT | - |
|
||||||
|
| Llamadas por la interfaz Coze | Coze | - |
|
||||||
|
| Llamadas por la interfaz Xinference | Xinference | - |
|
||||||
|
| Llamadas por la interfaz HomeAssistant | HomeAssistant | - |
|
||||||
|
|
||||||
|
En la práctica, se puede integrar cualquier LLM que admita llamadas por la interfaz OpenAI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### VLLM, modelos de visión
|
||||||
|
|
||||||
|
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
|
En la práctica, se puede integrar cualquier VLLM que admita llamadas por la interfaz OpenAI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### TTS, síntesis de voz
|
||||||
|
|
||||||
|
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Llamadas por interfaz | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud y Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow (parcial) |
|
||||||
|
| Servicio local | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### VAD, detección de actividad de voz
|
||||||
|
|
||||||
|
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||||
|
|:---:|:---------:|:----:|:----:|:--:|
|
||||||
|
| VAD | SileroVAD | Uso local | Gratuito | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ASR, reconocimiento de voz
|
||||||
|
|
||||||
|
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||||
|
| Llamadas por interfaz | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud y Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Voiceprint, huella de voz
|
||||||
|
|
||||||
|
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Llamadas por interfaz | Servicio de reconocimiento de huella de voz (voiceprint-api) | - |
|
||||||
|
|
||||||
|
El reconocimiento de huella de voz requiere desplegar por separado el servicio [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) (basado en 3D-Speaker), que depende de MySQL; consulte la [guía de integración de la huella de voz](../voiceprint-integration.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Memory, almacenamiento de memoria
|
||||||
|
|
||||||
|
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||||
|
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||||
|
| Memory | mem0ai | Llamadas por interfaz | Cuota de 1000 veces al mes | |
|
||||||
|
| Memory | [powermem](../powermem-integration.md) | Resumen local | Depende del LLM y de la base de datos | OceanBase de código abierto; admite búsqueda inteligente |
|
||||||
|
| Memory | mem_local_short | Resumen local | Gratuito | |
|
||||||
|
| Memory | nomem | Modo sin memoria | Gratuito | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Intent, reconocimiento de intención
|
||||||
|
|
||||||
|
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||||
|
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||||
|
| Intent | intent_llm | Llamadas por interfaz | Según el precio del LLM | Reconoce la intención mediante el modelo de lenguaje (LLM); gran capacidad de generalización |
|
||||||
|
| Intent | function_call | Llamadas por interfaz | Según el precio del LLM | Completa la intención con llamadas a funciones del modelo; rápido y con buen resultado |
|
||||||
|
| Intent | nointent | Modo sin intención | Gratuito | No reconoce la intención y devuelve directamente el resultado del diálogo |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Rag, generación aumentada por recuperación
|
||||||
|
|
||||||
|
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|
||||||
|
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||||
|
| Rag | ragflow | Llamadas por interfaz | Cobrado según los tokens consumidos en el troceado y la segmentación | Usa la generación aumentada por recuperación de RagFlow para dar respuestas más precisas |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Agradecimientos 🙏
|
||||||
|
|
||||||
|
| Logo | Proyecto o empresa | Descripción |
|
||||||
|
|:---:|:---:|:---|
|
||||||
|
| <img src="../images/logo_bailing.png" width="160"> | [Robot de diálogo por voz Bailing (百聆语音对话机器人)](https://github.com/wwbin2017/bailing) | Este proyecto parte del [robot de diálogo por voz Bailing](https://github.com/wwbin2017/bailing) y se construye sobre esa base |
|
||||||
|
| <img src="../images/logo_tenclass.png" width="160"> | [Tenclass (十方融海)](https://www.tenclass.com/) | Gracias a [Tenclass](https://www.tenclass.com/) por definir el protocolo de comunicación estándar del ecosistema Xiaozhi, las soluciones de compatibilidad con varios dispositivos y los ejemplos prácticos de alta concurrencia, y por el apoyo de documentación técnica de todo el recorrido de este proyecto |
|
||||||
|
| <img src="../images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology (玄凤科技)](https://github.com/Eric0308) | Gracias a [Xuanfeng Technology](https://github.com/Eric0308) por el código del marco de llamada a funciones, del protocolo de comunicación MCP y del mecanismo de llamadas basado en plugins. Con un sistema estandarizado de despacho de instrucciones y capacidad de ampliación dinámica, mejora de forma clara la eficiencia de interacción y la extensibilidad de los dispositivos de frontend (IoT) |
|
||||||
|
| <img src="../images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Gracias a [huangjunsen](https://github.com/huangjunsen0406) por el módulo `consola inteligente móvil`, que permite controlar con eficacia dispositivos móviles de varias plataformas e interactuar en tiempo real, y mejora mucho la comodidad de uso y la eficiencia de gestión en escenarios móviles |
|
||||||
|
| <img src="../images/logo_huiyuan.png" width="160"> | [Huiyuan Design (汇远设计)](http://ui.kwd988.net/) | Gracias a [Huiyuan Design](http://ui.kwd988.net/) por la solución visual de este proyecto, y por poner al servicio de la experiencia de uso la práctica de diseño acumulada con más de mil empresas |
|
||||||
|
| <img src="../images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology (西安勤人信息科技)](https://www.029app.com/) | Gracias a [Xi'an Qinren Information Technology](https://www.029app.com/) por profundizar el sistema visual de este proyecto y mantener un estilo coherente y ampliable en distintos escenarios |
|
||||||
|
| <img src="../images/logo_contributors.png" width="160"> | [Quienes contribuyen código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Gracias a [todas las personas que contribuyen código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors). Su trabajo hace el proyecto más sólido y más capaz. |
|
||||||
|
|
||||||
|
|
||||||
|
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
+37
-35
@@ -22,6 +22,7 @@ Suporte ao protocolo MQTT+UDP, protocolo WebSocket, ponto de acesso MCP, reconhe
|
|||||||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DBEDFA"></a>
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DBEDFA"></a>
|
||||||
|
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
@@ -54,31 +55,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
<img alt="A sensação da velocidade de resposta" src="../images/demo9.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
<img alt="O segredo para otimizar a velocidade" src="../images/demo6.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
<img alt="Humano digital Xiaozhi com ativação por voz" src="../images/demo8.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
<img alt="Chamadas de dispositivo para dispositivo" src="../images/demo0.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
<img alt="Cenário médico complexo" src="../images/demo1.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -86,31 +87,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
<img alt="Reproduzir música, consultar o tempo e ler as notícias" src="../images/demo7.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
<img alt="Interrupção em tempo real" src="../images/demo10.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
<img alt="Reconhecer objetos com uma foto" src="../images/demo12.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
<img alt="Controlar o acionamento de eletrodomésticos" src="../images/demo5.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
<img alt="Tarefas com vários comandos" src="../images/demo11.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -118,31 +119,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
<img alt="Ponto de acesso MCP" src="../images/demo13.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
<img alt="Envio de comandos MQTT" src="../images/demo4.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
<img alt="Reconhecimento de impressão vocal" src="../images/demo14.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
<img alt="Tom de voz personalizado" src="../images/demo2.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
<img alt="Conversa em cantonês" src="../images/demo3.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -167,8 +168,8 @@ Este projeto oferece dois métodos de implantação. Por favor, escolha de acord
|
|||||||
#### 🚀 Seleção do Método de Implantação
|
#### 🚀 Seleção do Método de Implantação
|
||||||
| Método de Implantação | Funcionalidades | Cenários Aplicáveis | Documentação de Implantação | Requisitos de Configuração | Tutoriais em Vídeo |
|
| Método de Implantação | Funcionalidades | Cenários Aplicáveis | Documentação de Implantação | Requisitos de Configuração | Tutoriais em Vídeo |
|
||||||
|---------|------|---------|---------|---------|---------|
|
|---------|------|---------|---------|---------|---------|
|
||||||
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 núcleos 4GB se usar `FunASR`, 2 núcleos 2GB se todas APIs | - |
|
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| `FunASR` local exige mais memória; usar apenas APIs mantém o consumo de recursos baixo | - |
|
||||||
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Implantação via Código-Fonte](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de Atualização Automática via Código-Fonte](../dev-ops-integration.md) | 4 núcleos 8GB se usar `FunASR`, 2 núcleos 4GB se todas APIs| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Implantação via Código-Fonte](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de Atualização Automática via Código-Fonte](../dev-ops-integration.md) | `FunASR` local exige mais memória e recursos de banco de dados; usar apenas APIs mantém o consumo de recursos baixo| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](../FAQ.md)
|
Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](../FAQ.md)
|
||||||
|
|
||||||
@@ -209,15 +210,15 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
|
|||||||
|
|
||||||
| Nome da Ferramenta | Localização | Método de Uso | Descrição da Função |
|
| Nome da Ferramenta | Localização | Método de Uso | Descrição da Função |
|
||||||
|:---:|:---|:---:|:---:|
|
|:---:|:---|:---:|:---:|
|
||||||
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Execute `python start.py` em `main/digital-human` e depois abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
|
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Em `main/digital-human`, instale as dependências como indica o README, depois execute `python start.py` e abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
|
||||||
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta dos três módulos principais: ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
|
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta de módulos principais como ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
|
||||||
|
|
||||||
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
|
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
|
||||||
|
|
||||||
---
|
---
|
||||||
## Lista de Funcionalidades ✨
|
## Lista de Funcionalidades ✨
|
||||||
### Implementado ✅
|
### Implementado ✅
|
||||||

|

|
||||||
| Módulo de Funcionalidade | Descrição |
|
| Módulo de Funcionalidade | Descrição |
|
||||||
|:---:|:---|
|
|:---:|:---|
|
||||||
| Arquitetura Principal | Baseado em [gateway MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), servidores WebSocket e HTTP, fornece sistema completo de gerenciamento de console e autenticação |
|
| Arquitetura Principal | Baseado em [gateway MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), servidores WebSocket e HTTP, fornece sistema completo de gerenciamento de console e autenticação |
|
||||||
@@ -225,15 +226,15 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
|
|||||||
| Reconhecimento de Impressão Vocal | Suporta registro, gerenciamento e reconhecimento de impressão vocal de múltiplos usuários, processa em paralelo com o ASR, reconhecimento de identidade do falante em tempo real e repassa ao LLM para respostas personalizadas |
|
| Reconhecimento de Impressão Vocal | Suporta registro, gerenciamento e reconhecimento de impressão vocal de múltiplos usuários, processa em paralelo com o ASR, reconhecimento de identidade do falante em tempo real e repassa ao LLM para respostas personalizadas |
|
||||||
| Diálogo Inteligente | Suporta múltiplos LLM (modelos de linguagem de grande porte), implementa diálogo inteligente |
|
| Diálogo Inteligente | Suporta múltiplos LLM (modelos de linguagem de grande porte), implementa diálogo inteligente |
|
||||||
| Percepção Visual | Suporta múltiplos VLLM (modelos de visão de grande porte), implementa interação multimodal |
|
| Percepção Visual | Suporta múltiplos VLLM (modelos de visão de grande porte), implementa interação multimodal |
|
||||||
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM, Function Call (chamada de função), fornece mecanismo de processamento de intenção baseado em plugins |
|
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM externo e conectável, chamada de função autônoma do modelo de linguagem, fornece mecanismo de processamento de intenção baseado em plugins |
|
||||||
| Sistema de Memória | Suporta memória local de curto prazo, memória via interface mem0ai, memória inteligente PowerMem, com funcionalidade de resumo de memória |
|
| Sistema de Memória | Suporta memória local de curto prazo, memória via interface mem0ai, memória inteligente PowerMem, com funcionalidade de resumo de memória |
|
||||||
| Base de Conhecimento | Suporta base de conhecimento RAGFlow, permitindo que o LLM julgue se deve acionar a base de conhecimento após receber a pergunta do usuário, e então responda à pergunta |
|
| Base de Conhecimento | Suporta base de conhecimento RAGFlow, permitindo que o LLM julgue se deve acionar a base de conhecimento após receber a pergunta do usuário, e então responda à pergunta |
|
||||||
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de endpoint MCP, funções de ferramentas personalizadas |
|
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de endpoint MCP, funções de ferramentas personalizadas |
|
||||||
| Envio de Comandos | Suporta envio de comandos MCP para dispositivos ESP32 via protocolo MQTT a partir do Console Inteligente |
|
| Envio de Comandos | Suporta envio de comandos MCP para dispositivos ESP32 via protocolo MQTT a partir do Console Inteligente |
|
||||||
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional e Inglês |
|
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional, Inglês, Alemão, Vietnamita e Português do Brasil |
|
||||||
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho, ferramentas de teste de modelo de visão e ferramentas de teste de interação por áudio |
|
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho de resposta de modelo e ferramentas de teste de interação por áudio |
|
||||||
| Suporte à Implantação | Suporta implantação via Docker e implantação local, fornece gerenciamento completo de arquivos de configuração |
|
| Suporte à Implantação | Suporta implantação via Docker e implantação local, fornece gerenciamento completo de arquivos de configuração |
|
||||||
| Sistema de Plugins | Suporta extensões de plugins funcionais, desenvolvimento de plugins personalizados e carregamento dinâmico de plugins |
|
| Sistema de Plugins | Suporta extensões de plugins funcionais e desenvolvimento de plugins personalizados; novos arquivos de plugin são carregados na próxima conexão do dispositivo e alterações em plugins já carregados exigem reiniciar o serviço |
|
||||||
|
|
||||||
### Em Desenvolvimento 🚧
|
### Em Desenvolvimento 🚧
|
||||||
|
|
||||||
@@ -253,7 +254,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
|
|||||||
|
|
||||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
|
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||||
| Chamadas via interface Ollama | Ollama | - |
|
| Chamadas via interface Ollama | Ollama | - |
|
||||||
| Chamadas via interface Dify | Dify | - |
|
| Chamadas via interface Dify | Dify | - |
|
||||||
| Chamadas via interface FastGPT | FastGPT | - |
|
| Chamadas via interface FastGPT | FastGPT | - |
|
||||||
@@ -279,8 +280,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||||||
|
|
||||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(parcial) |
|
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(parcial) |
|
||||||
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -296,8 +297,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||||||
|
|
||||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Uso local | FunASR, SherpaASR | FunASR, SherpaASR |
|
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||||
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud e Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -305,7 +306,9 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||||||
|
|
||||||
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Uso local | 3D-Speaker | 3D-Speaker |
|
| Chamadas via interface | Serviço de voiceprint (voiceprint-api) | - |
|
||||||
|
|
||||||
|
O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) implantado separadamente (baseado em 3D-Speaker) e MySQL. Veja o [guia de integração de voiceprint](../voiceprint-integration.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -351,11 +354,10 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
|
|||||||
| <img src="../images/logo_contributors.png" width="160"> | [Contribuidores de Código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Agradecimentos a [todos os contribuidores de código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), seus esforços tornaram o projeto mais robusto e poderoso. |
|
| <img src="../images/logo_contributors.png" width="160"> | [Contribuidores de Código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Agradecimentos a [todos os contribuidores de código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), seus esforços tornaram o projeto mais robusto e poderoso. |
|
||||||
|
|
||||||
|
|
||||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||||
|
|
||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
+39
-37
@@ -6,7 +6,7 @@
|
|||||||
Dự án này dựa trên lý thuyết và công nghệ trí tuệ cộng sinh người-máy để phát triển hệ thống phần mềm và phần cứng thiết bị đầu cuối thông minh<br/>Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở
|
Dự án này dựa trên lý thuyết và công nghệ trí tuệ cộng sinh người-máy để phát triển hệ thống phần mềm và phần cứng thiết bị đầu cuối thông minh<br/>Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở
|
||||||
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||||
Được triển khai bằng Python, Java, Vue theo <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">giao thức truyền thông Xiaozhi</a><br/>
|
Được triển khai bằng Python, Java, Vue theo <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">giao thức truyền thông Xiaozhi</a><br/>
|
||||||
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng giọng nói và kho tri thức
|
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng vân giọng và kho tri thức
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@@ -22,6 +22,7 @@ Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP,
|
|||||||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DBEDFA"></a>
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DBEDFA"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
|
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
@@ -38,7 +39,7 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
|
|||||||
</br>
|
</br>
|
||||||
Được dẫn dắt bởi nhóm Giáo sư Lưu Tư Nguyên (Đại học Bách khoa Nam Trung Quốc)
|
Được dẫn dắt bởi nhóm Giáo sư Lưu Tư Nguyên (Đại học Bách khoa Nam Trung Quốc)
|
||||||
</br>
|
</br>
|
||||||
<img src="../images/hnlg.jpg" alt="华南理工大学" width="50%">
|
<img src="../images/hnlg.jpg" alt="Đại học Bách khoa Nam Trung Quốc" width="50%">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -54,31 +55,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
|
<img alt="Cảm giác tốc độ phản hồi" src="../images/demo9.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
|
<img alt="Bí quyết tối ưu tốc độ" src="../images/demo6.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
|
<img alt="Người ảo số Xiaozhi có đánh thức bằng giọng nói" src="../images/demo8.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
|
<img alt="Gọi giữa các thiết bị" src="../images/demo0.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
|
<img alt="Tình huống y tế phức tạp" src="../images/demo1.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -86,31 +87,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
|
<img alt="Phát nhạc, tra cứu thời tiết và đọc tin tức" src="../images/demo7.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
|
<img alt="Ngắt giữa chừng theo thời gian thực" src="../images/demo10.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
|
<img alt="Nhận dạng vật thể qua ảnh chụp" src="../images/demo12.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
|
<img alt="Bật tắt thiết bị gia dụng" src="../images/demo5.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
|
<img alt="Nhiệm vụ nhiều lệnh" src="../images/demo11.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -118,31 +119,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
|
|||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
|
<img alt="Điểm truy cập MCP" src="../images/demo13.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
|
<img alt="Gửi lệnh MQTT" src="../images/demo4.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
|
<img alt="Nhận dạng vân giọng" src="../images/demo14.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
|
<img alt="Giọng nói tùy chỉnh" src="../images/demo2.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
<picture>
|
<picture>
|
||||||
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
|
<img alt="Trò chuyện bằng tiếng Quảng Đông" src="../images/demo3.png" /></picture>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -168,8 +169,8 @@ Dự án này cung cấp hai phương pháp triển khai, vui lòng chọn theo
|
|||||||
#### 🚀 Lựa chọn phương pháp triển khai
|
#### 🚀 Lựa chọn phương pháp triển khai
|
||||||
| Phương pháp triển khai | Đặc điểm | Tình huống áp dụng | Tài liệu triển khai | Yêu cầu cấu hình | Video hướng dẫn |
|
| Phương pháp triển khai | Đặc điểm | Tình huống áp dụng | Tài liệu triển khai | Yêu cầu cấu hình | Video hướng dẫn |
|
||||||
|---------|------|---------|---------|---------|---------|
|
|---------|------|---------|---------|---------|---------|
|
||||||
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 nhân 4GB nếu dùng `FunASR`, 2 nhân 2GB nếu toàn API | - |
|
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| `FunASR` cục bộ cần nhiều bộ nhớ; dùng toàn API thì mức dùng tài nguyên thấp | - |
|
||||||
| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](../dev-ops-integration.md) | 4 nhân 8GB nếu dùng `FunASR`, 2 nhân 4GB nếu toàn API| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, thao tác qua bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](../dev-ops-integration.md) | `FunASR` cục bộ cần nhiều bộ nhớ, thêm tài nguyên cơ sở dữ liệu; dùng toàn API thì mức dùng tài nguyên thấp| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
Câu hỏi thường gặp và hướng dẫn liên quan, vui lòng tham khảo [liên kết này](../FAQ.md)
|
Câu hỏi thường gặp và hướng dẫn liên quan, vui lòng tham khảo [liên kết này](../FAQ.md)
|
||||||
|
|
||||||
@@ -192,7 +193,7 @@ Công cụ kiểm tra dịch vụ: https://2662r3426b.vicp.fun/test/
|
|||||||
>
|
>
|
||||||
> 2. `Cấu hình streaming`: Phù hợp với demo, đào tạo, hơn 2 đồng thời, v.v., sử dụng công nghệ xử lý streaming, tốc độ phản hồi nhanh hơn, trải nghiệm tốt hơn.
|
> 2. `Cấu hình streaming`: Phù hợp với demo, đào tạo, hơn 2 đồng thời, v.v., sử dụng công nghệ xử lý streaming, tốc độ phản hồi nhanh hơn, trải nghiệm tốt hơn.
|
||||||
>
|
>
|
||||||
> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với phiên bản đầu, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
|
> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với các phiên bản trước đó, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
|
||||||
|
|
||||||
| Tên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
|
| Tên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
@@ -210,15 +211,15 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
|
|||||||
|
|
||||||
| Tên công cụ | Vị trí | Phương pháp sử dụng | Mô tả chức năng |
|
| Tên công cụ | Vị trí | Phương pháp sử dụng | Mô tả chức năng |
|
||||||
|:---:|:---|:---:|:---:|
|
|:---:|:---|:---:|:---:|
|
||||||
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Chạy `python start.py` trong `main/digital-human`, sau đó mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
|
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Trong `main/digital-human`, cài đặt các phụ thuộc theo README, rồi chạy `python start.py` và mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
|
||||||
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của ba module cốt lõi ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
|
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của các module cốt lõi như ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
|
||||||
|
|
||||||
> 💡 Gợi ý: Khi kiểm tra tốc độ mô hình, chỉ kiểm tra các mô hình đã cấu hình khóa.
|
> 💡 Gợi ý: Khi kiểm tra tốc độ mô hình, chỉ kiểm tra các mô hình đã cấu hình khóa.
|
||||||
|
|
||||||
---
|
---
|
||||||
## Danh sách tính năng ✨
|
## Danh sách tính năng ✨
|
||||||
### Đã thực hiện ✅
|
### Đã thực hiện ✅
|
||||||

|

|
||||||
| Module chức năng | Mô tả |
|
| Module chức năng | Mô tả |
|
||||||
|:---:|:---|
|
|:---:|:---|
|
||||||
| Kiến trúc cốt lõi | Dựa trên [cổng MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket, máy chủ HTTP, cung cấp hệ thống quản lý bảng điều khiển và xác thực hoàn chỉnh |
|
| Kiến trúc cốt lõi | Dựa trên [cổng MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket, máy chủ HTTP, cung cấp hệ thống quản lý bảng điều khiển và xác thực hoàn chỉnh |
|
||||||
@@ -231,10 +232,10 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
|
|||||||
| Kho tri thức | Hỗ trợ kho tri thức RAGFlow, cho phép mô hình lớn đánh giá cần gọi kho tri thức trước khi trả lời |
|
| Kho tri thức | Hỗ trợ kho tri thức RAGFlow, cho phép mô hình lớn đánh giá cần gọi kho tri thức trước khi trả lời |
|
||||||
| Gọi công cụ | Hỗ trợ giao thức IOT phía client, giao thức MCP phía client, giao thức MCP phía server, giao thức điểm truy cập MCP, hàm công cụ tùy chỉnh |
|
| Gọi công cụ | Hỗ trợ giao thức IOT phía client, giao thức MCP phía client, giao thức MCP phía server, giao thức điểm truy cập MCP, hàm công cụ tùy chỉnh |
|
||||||
| Gửi lệnh | Dựa vào giao thức MQTT, hỗ trợ gửi lệnh MCP từ bảng điều khiển thông minh xuống thiết bị ESP32 |
|
| Gửi lệnh | Dựa vào giao thức MQTT, hỗ trợ gửi lệnh MCP từ bảng điều khiển thông minh xuống thiết bị ESP32 |
|
||||||
| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh |
|
| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh, tiếng Đức, tiếng Việt và tiếng Bồ Đào Nha Brazil |
|
||||||
| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất, công cụ kiểm tra mô hình thị giác và công cụ kiểm tra tương tác âm thanh |
|
| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất phản hồi mô hình và công cụ kiểm tra tương tác âm thanh |
|
||||||
| Hỗ trợ triển khai | Hỗ trợ triển khai Docker và triển khai cục bộ, cung cấp quản lý tệp cấu hình hoàn chỉnh |
|
| Hỗ trợ triển khai | Hỗ trợ triển khai Docker và triển khai cục bộ, cung cấp quản lý tệp cấu hình hoàn chỉnh |
|
||||||
| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng, phát triển plugin tùy chỉnh và hot loading plugin |
|
| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng và phát triển plugin tùy chỉnh; file plugin mới được tải ở lần kết nối thiết bị tiếp theo, thay đổi mã của plugin đã tải cần khởi động lại dịch vụ |
|
||||||
|
|
||||||
### Đang phát triển 🚧
|
### Đang phát triển 🚧
|
||||||
|
|
||||||
@@ -254,7 +255,7 @@ Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạ
|
|||||||
|
|
||||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFlytek | Zhipu, Gemini |
|
| Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
|
||||||
| Gọi giao diện ollama | Ollama | - |
|
| Gọi giao diện ollama | Ollama | - |
|
||||||
| Gọi giao diện dify | Dify | - |
|
| Gọi giao diện dify | Dify | - |
|
||||||
| Gọi giao diện fastgpt | Fastgpt | - |
|
| Gọi giao diện fastgpt | Fastgpt | - |
|
||||||
@@ -280,8 +281,8 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||||||
|
|
||||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Gọi giao diện | EdgeTTS, iFlytek, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi streaming TTS, MinimaxTTS | Lingxi streaming TTS, EdgeTTS, CosyVoiceSiliconflow(một phần) |
|
| Gọi giao diện | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(một phần) |
|
||||||
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -297,8 +298,8 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||||||
|
|
||||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Sử dụng cục bộ | FunASR, SherpaASR | FunASR, SherpaASR |
|
| Sử dụng cục bộ | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
|
||||||
| Gọi giao diện | FunASRServer, Volcano Engine, iFlytek, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
| Gọi giao diện | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud và Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -306,7 +307,9 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||||||
|
|
||||||
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Sử dụng cục bộ | 3D-Speaker | 3D-Speaker |
|
| Gọi giao diện | Dịch vụ nhận dạng vân giọng (voiceprint-api) | - |
|
||||||
|
|
||||||
|
Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) được triển khai riêng (dựa trên 3D-Speaker) và MySQL. Xem [hướng dẫn tích hợp voiceprint](../voiceprint-integration.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -352,11 +355,10 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
|||||||
| <img src="../images/logo_contributors.png" width="160"> | [Người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Cảm ơn [tất cả người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), sự cống hiến của bạn khiến dự án mạnh mẽ và vững chắc hơn. |
|
| <img src="../images/logo_contributors.png" width="160"> | [Người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Cảm ơn [tất cả người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), sự cống hiến của bạn khiến dự án mạnh mẽ và vững chắc hơn. |
|
||||||
|
|
||||||
|
|
||||||
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
|
||||||
|
|
||||||
<picture>
|
<picture>
|
||||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
@@ -31,6 +31,8 @@ class AudioPlugin(Plugin):
|
|||||||
self.source.stop()
|
self.source.stop()
|
||||||
|
|
||||||
def shutdown(self) -> None:
|
def shutdown(self) -> None:
|
||||||
|
if self.source is not None:
|
||||||
|
self.source.stop()
|
||||||
if self.app is not None:
|
if self.app is not None:
|
||||||
self.app.audio_source = None
|
self.app.audio_source = None
|
||||||
self.source = None
|
self.source = None
|
||||||
|
|||||||
@@ -51,13 +51,14 @@ class TestRuntimeApplication:
|
|||||||
logger.info("test runtime application started")
|
logger.info("test runtime application started")
|
||||||
|
|
||||||
def stop(self) -> None:
|
def stop(self) -> None:
|
||||||
if not self._is_running:
|
was_running = self._is_running
|
||||||
return
|
|
||||||
|
|
||||||
self.event_bridge.publish_service_stopping()
|
|
||||||
self.plugins.stop_all()
|
|
||||||
self._is_running = False
|
self._is_running = False
|
||||||
logger.info("test runtime application stopped")
|
if was_running:
|
||||||
|
self.event_bridge.publish_service_stopping()
|
||||||
|
logger.info("test runtime application stopped")
|
||||||
|
# 启动中途失败时 _is_running 还是 False,但插件可能已经开过采集流,
|
||||||
|
# 这里不提前返回,保证采集流一定被关掉
|
||||||
|
self.plugins.stop_all()
|
||||||
|
|
||||||
def shutdown(self) -> None:
|
def shutdown(self) -> None:
|
||||||
self.stop()
|
self.stop()
|
||||||
|
|||||||
@@ -324,7 +324,7 @@ public interface Constant {
|
|||||||
/**
|
/**
|
||||||
* 版本号
|
* 版本号
|
||||||
*/
|
*/
|
||||||
public static final String VERSION = "0.9.7";
|
public static final String VERSION = "0.9.8";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无效固件URL
|
* 无效固件URL
|
||||||
|
|||||||
@@ -19,8 +19,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
|||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.Parameters;
|
import io.swagger.v3.oas.annotations.Parameters;
|
||||||
@@ -44,7 +42,6 @@ import xiaozhi.modules.agent.dto.AgentDTO;
|
|||||||
import xiaozhi.modules.agent.dto.AgentMemoryDTO;
|
import xiaozhi.modules.agent.dto.AgentMemoryDTO;
|
||||||
import xiaozhi.modules.agent.dto.AgentUpdateDTO;
|
import xiaozhi.modules.agent.dto.AgentUpdateDTO;
|
||||||
import xiaozhi.modules.agent.entity.AgentEntity;
|
import xiaozhi.modules.agent.entity.AgentEntity;
|
||||||
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
|
|
||||||
import xiaozhi.modules.agent.dto.AgentTagDTO;
|
import xiaozhi.modules.agent.dto.AgentTagDTO;
|
||||||
import xiaozhi.modules.agent.entity.AgentTagEntity;
|
import xiaozhi.modules.agent.entity.AgentTagEntity;
|
||||||
import xiaozhi.modules.agent.service.AgentTagService;
|
import xiaozhi.modules.agent.service.AgentTagService;
|
||||||
@@ -52,7 +49,6 @@ import xiaozhi.modules.agent.service.AgentChatAudioService;
|
|||||||
import xiaozhi.modules.agent.service.AgentChatHistoryService;
|
import xiaozhi.modules.agent.service.AgentChatHistoryService;
|
||||||
import xiaozhi.modules.agent.service.AgentChatSummaryService;
|
import xiaozhi.modules.agent.service.AgentChatSummaryService;
|
||||||
import xiaozhi.modules.agent.service.AgentService;
|
import xiaozhi.modules.agent.service.AgentService;
|
||||||
import xiaozhi.modules.agent.service.AgentTemplateService;
|
|
||||||
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
|
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
|
||||||
import xiaozhi.modules.agent.vo.AgentInfoVO;
|
import xiaozhi.modules.agent.vo.AgentInfoVO;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
@@ -65,7 +61,6 @@ public class AgentController {
|
|||||||
private static final long AUDIO_PLAY_TOKEN_EXPIRE_SECONDS = 300L;
|
private static final long AUDIO_PLAY_TOKEN_EXPIRE_SECONDS = 300L;
|
||||||
|
|
||||||
private final AgentService agentService;
|
private final AgentService agentService;
|
||||||
private final AgentTemplateService agentTemplateService;
|
|
||||||
private final AgentChatHistoryService agentChatHistoryService;
|
private final AgentChatHistoryService agentChatHistoryService;
|
||||||
private final AgentChatAudioService agentChatAudioService;
|
private final AgentChatAudioService agentChatAudioService;
|
||||||
private final AgentChatSummaryService agentChatSummaryService;
|
private final AgentChatSummaryService agentChatSummaryService;
|
||||||
@@ -192,15 +187,6 @@ public class AgentController {
|
|||||||
return new Result<>();
|
return new Result<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/template")
|
|
||||||
@Operation(summary = "智能体模板模板列表")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
public Result<List<AgentTemplateEntity>> templateList() {
|
|
||||||
List<AgentTemplateEntity> list = agentTemplateService
|
|
||||||
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
|
|
||||||
return new Result<List<AgentTemplateEntity>>().ok(list);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{id}/sessions")
|
@GetMapping("/{id}/sessions")
|
||||||
@Operation(summary = "获取智能体会话列表")
|
@Operation(summary = "获取智能体会话列表")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
|
|||||||
+11
@@ -41,6 +41,17 @@ public class AgentTemplateController {
|
|||||||
|
|
||||||
private final AgentTemplateService agentTemplateService;
|
private final AgentTemplateService agentTemplateService;
|
||||||
|
|
||||||
|
// 单独用 normal 权限(而非类级 superAdmin)是有意保留:
|
||||||
|
// 普通用户也需查询可用模板,与 /page 的管理入口分离,保持原行为契约。
|
||||||
|
@GetMapping
|
||||||
|
@Operation(summary = "智能体模板列表")
|
||||||
|
@RequiresPermissions("sys:role:normal")
|
||||||
|
public Result<List<AgentTemplateEntity>> getAgentTemplates() {
|
||||||
|
List<AgentTemplateEntity> list = agentTemplateService
|
||||||
|
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
|
||||||
|
return new Result<List<AgentTemplateEntity>>().ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/page")
|
@GetMapping("/page")
|
||||||
@Operation(summary = "获取模板分页列表")
|
@Operation(summary = "获取模板分页列表")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
|
|||||||
+5
-6
@@ -174,6 +174,9 @@ public class DeviceController {
|
|||||||
@Operation(summary = "获取设备通讯录")
|
@Operation(summary = "获取设备通讯录")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
public Result<Object> getAddressBook(@PathVariable String macAddress) {
|
public Result<Object> getAddressBook(@PathVariable String macAddress) {
|
||||||
|
if (deviceService.getOwnedDeviceByMacAddress(macAddress) == null) {
|
||||||
|
return new Result<Object>().error(ErrorCode.DEVICE_NOT_EXIST);
|
||||||
|
}
|
||||||
return new Result<Object>().ok(deviceAddressBookService.getAddressBookList(macAddress));
|
return new Result<Object>().ok(deviceAddressBookService.getAddressBookList(macAddress));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,9 +195,7 @@ public class DeviceController {
|
|||||||
@Operation(summary = "更新设备通讯录别名")
|
@Operation(summary = "更新设备通讯录别名")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
public Result<Void> updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) {
|
public Result<Void> updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) {
|
||||||
UserDetail user = SecurityUser.getUser();
|
if (deviceService.getOwnedDeviceByMacAddress(dto.getMacAddress()) == null) {
|
||||||
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
|
|
||||||
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
|
|
||||||
return new Result<Void>().error("无权限操作该设备");
|
return new Result<Void>().error("无权限操作该设备");
|
||||||
}
|
}
|
||||||
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null);
|
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null);
|
||||||
@@ -205,9 +206,7 @@ public class DeviceController {
|
|||||||
@Operation(summary = "更新设备通讯录权限")
|
@Operation(summary = "更新设备通讯录权限")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
public Result<Void> updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) {
|
public Result<Void> updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) {
|
||||||
UserDetail user = SecurityUser.getUser();
|
if (deviceService.getOwnedDeviceByMacAddress(dto.getMacAddress()) == null) {
|
||||||
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
|
|
||||||
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
|
|
||||||
return new Result<Void>().error("无权限操作该设备");
|
return new Result<Void>().error("无权限操作该设备");
|
||||||
}
|
}
|
||||||
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission());
|
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission());
|
||||||
|
|||||||
@@ -83,6 +83,16 @@ public interface DeviceService extends BaseService<DeviceEntity> {
|
|||||||
*/
|
*/
|
||||||
DeviceEntity getDeviceByMacAddress(String macAddress);
|
DeviceEntity getDeviceByMacAddress(String macAddress);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据MAC地址获取当前登录用户名下的设备信息
|
||||||
|
* <p>
|
||||||
|
* 设备不存在或不属于当前用户时返回null,调用方无需再自行比对归属。
|
||||||
|
*
|
||||||
|
* @param macAddress MAC地址
|
||||||
|
* @return 当前用户名下的设备信息,不存在或无权限时返回null
|
||||||
|
*/
|
||||||
|
DeviceEntity getOwnedDeviceByMacAddress(String macAddress);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据设备ID获取激活码
|
* 根据设备ID获取激活码
|
||||||
*
|
*
|
||||||
|
|||||||
+103
-25
@@ -1,9 +1,13 @@
|
|||||||
package xiaozhi.modules.device.service.impl;
|
package xiaozhi.modules.device.service.impl;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
@@ -18,6 +22,7 @@ import xiaozhi.common.redis.RedisKeys;
|
|||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
import xiaozhi.modules.device.dao.DeviceAddressBookDao;
|
import xiaozhi.modules.device.dao.DeviceAddressBookDao;
|
||||||
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
|
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
|
||||||
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceAddressBookService;
|
import xiaozhi.modules.device.service.DeviceAddressBookService;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
@@ -40,7 +45,11 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<DeviceAddressBookEntity> getAddressBookList(String macAddress) {
|
public List<DeviceAddressBookEntity> getAddressBookList(String macAddress) {
|
||||||
return deviceAddressBookDao.getAddressBookList(macAddress);
|
List<DeviceAddressBookEntity> rows = assignUniqueAliases(deviceAddressBookDao.getAddressBookList(macAddress));
|
||||||
|
// 取名按固定顺序算完了,前端要看的是最近改过的排前面,放回去
|
||||||
|
rows.sort(Comparator
|
||||||
|
.comparing(DeviceAddressBookEntity::getUpdateDate, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||||
|
return rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -63,7 +72,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 主动呼叫模式
|
// 主动呼叫模式
|
||||||
Map<String, String> callerBook = allBooks.get(callerMac.toLowerCase());
|
Map<String, String> callerBook = allBooks.get(bookKey(callerMac));
|
||||||
if (callerBook == null) {
|
if (callerBook == null) {
|
||||||
return errorResult("未找到备注为'" + nickname + "'的设备");
|
return errorResult("未找到备注为'" + nickname + "'的设备");
|
||||||
}
|
}
|
||||||
@@ -80,13 +89,16 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 获取目标设备如何称呼主叫方
|
// 获取目标设备如何称呼主叫方
|
||||||
Map<String, String> targetBook = allBooks.get(targetMac.toLowerCase());
|
Map<String, String> targetBook = allBooks.get(bookKey(targetMac));
|
||||||
String callerNickname = null;
|
String callerNickname = null;
|
||||||
if (targetBook != null) {
|
if (targetBook != null) {
|
||||||
callerNickname = targetBook.get(callerMac.toLowerCase());
|
callerNickname = targetBook.get(bookKey(callerMac));
|
||||||
}
|
}
|
||||||
if (StringUtils.isBlank(callerNickname)) {
|
if (StringUtils.isBlank(callerNickname)) {
|
||||||
callerNickname = deviceService.getDeviceByMacAddress(callerMac).getAlias();
|
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(callerMac);
|
||||||
|
if (callerDevice != null) {
|
||||||
|
callerNickname = callerDevice.getAlias();
|
||||||
|
}
|
||||||
if (StringUtils.isBlank(callerNickname)) {
|
if (StringUtils.isBlank(callerNickname)) {
|
||||||
callerNickname = formatMacAsDeviceName(callerMac);
|
callerNickname = formatMacAsDeviceName(callerMac);
|
||||||
}
|
}
|
||||||
@@ -100,32 +112,26 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
@Override
|
@Override
|
||||||
public void refreshCache() {
|
public void refreshCache() {
|
||||||
Map<String, Map<String, String>> result = new HashMap<>();
|
Map<String, Map<String, String>> result = new HashMap<>();
|
||||||
List<DeviceAddressBookEntity> allRecords = deviceAddressBookDao.selectList(null);
|
List<DeviceAddressBookEntity> allRecords = assignUniqueAliases(deviceAddressBookDao.selectList(null));
|
||||||
Map<String, String> reverseMap = new HashMap<>();
|
Map<String, String> reverseMap = new HashMap<>();
|
||||||
|
|
||||||
for (DeviceAddressBookEntity entity : allRecords) {
|
for (DeviceAddressBookEntity entity : allRecords) {
|
||||||
String macA = entity.getMacAddress().toLowerCase();
|
String macA = bookKey(entity.getMacAddress());
|
||||||
String macB = entity.getTargetMac().toLowerCase();
|
String macB = bookKey(entity.getTargetMac());
|
||||||
String alias = entity.getAlias();
|
|
||||||
Boolean hasPermission = entity.getHasPermission();
|
|
||||||
|
|
||||||
// 构建正向映射: A对B的映射 nickname -> macB|permission
|
// 构建正向映射: A对B的映射 nickname -> macB|permission
|
||||||
if (alias != null && !alias.isEmpty()) {
|
Map<String, String> book = result.computeIfAbsent(macA, k -> new HashMap<>());
|
||||||
result.computeIfAbsent(macA, k -> new HashMap<>());
|
String permStr = (Boolean.TRUE.equals(entity.getHasPermission())) ? "1" : "0";
|
||||||
String permStr = (hasPermission != null && hasPermission) ? "1" : "0";
|
book.put(entity.getAlias(), macB + "|" + permStr);
|
||||||
result.get(macA).put(alias, macB + "|" + permStr);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建反向记录用于查找B对A的称呼
|
// 构建反向记录用于查找B对A的称呼,用同一个去重后的名字,两边才对得上
|
||||||
if (alias != null && !alias.isEmpty()) {
|
reverseMap.put(macB + ":" + macA, entity.getAlias());
|
||||||
reverseMap.put(macB + ":" + macA, alias);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 构建反向映射: B对A的映射 macA -> nickname
|
// 构建反向映射: B对A的映射 macA -> nickname
|
||||||
for (DeviceAddressBookEntity entity : allRecords) {
|
for (DeviceAddressBookEntity entity : allRecords) {
|
||||||
String macA = entity.getMacAddress().toLowerCase();
|
String macA = bookKey(entity.getMacAddress());
|
||||||
String macB = entity.getTargetMac().toLowerCase();
|
String macB = bookKey(entity.getTargetMac());
|
||||||
String aliasBtoA = reverseMap.get(macA + ":" + macB);
|
String aliasBtoA = reverseMap.get(macA + ":" + macB);
|
||||||
if (aliasBtoA != null && !aliasBtoA.isEmpty()) {
|
if (aliasBtoA != null && !aliasBtoA.isEmpty()) {
|
||||||
result.computeIfAbsent(macB, k -> new HashMap<>());
|
result.computeIfAbsent(macB, k -> new HashMap<>());
|
||||||
@@ -136,6 +142,54 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
redisUtils.set(RedisKeys.getAddressBookKey(), result);
|
redisUtils.set(RedisKeys.getAddressBookKey(), result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给每行算出一个不重名的称呼,返回排好序、alias 已写好的新列表
|
||||||
|
*
|
||||||
|
* 昵称在同一个人的通讯录里是索引,同名后写的会盖掉先写的,按昵称呼会呼错设备。
|
||||||
|
* 库里本来就有重名:空别名补出来的尾号称呼只有 256 种取值,一本通讯录十几条
|
||||||
|
* 没起名就撞上了。所以显示和呼叫都得走这一份,
|
||||||
|
* 不然前端看到的字和呼叫时用的名字对不上,用户照着点的名字呼不到人。
|
||||||
|
* 不改传入的那个列表:它是 DAO 刚查出来的,调用方还要按自己的顺序用
|
||||||
|
*/
|
||||||
|
private List<DeviceAddressBookEntity> assignUniqueAliases(List<DeviceAddressBookEntity> rows) {
|
||||||
|
// 取名要靠先后定谁拿原名,而 selectList 不带 order by,返回顺序不保证。
|
||||||
|
// 排一次,同样的数据每次算出来的结果一样,缓存不会来回变。
|
||||||
|
// 按归一后的地址排:同一个人不管库里是哪种写法都排到一起,
|
||||||
|
// 后面两级比较器再分先后。同一本里 target_mac 不会重复(主键摆着),
|
||||||
|
// 所以顺序还是由这三个键定死的,不会掉回"跟着数据库返回顺序走"
|
||||||
|
List<DeviceAddressBookEntity> ordered = new ArrayList<>(rows);
|
||||||
|
ordered.sort(Comparator
|
||||||
|
.comparing((DeviceAddressBookEntity row) -> bookKey(row.getMacAddress()),
|
||||||
|
Comparator.nullsFirst(Comparator.naturalOrder()))
|
||||||
|
// 权限排在地址前面:撞名时让对方准许呼我的那台先拿原名。
|
||||||
|
// 排在后面等于不起作用,两条地址不同时谁先谁后是地址定的,
|
||||||
|
// 没权限那条照样占住原名,用户照前端看到的名字呼叫命中的就是它,
|
||||||
|
// 界面上只会说没权限,怎么点都不通
|
||||||
|
.thenComparing(DeviceAddressBookEntity::getHasPermission,
|
||||||
|
Comparator.nullsLast(Comparator.reverseOrder()))
|
||||||
|
.thenComparing(DeviceAddressBookEntity::getTargetMac, Comparator.nullsFirst(Comparator.naturalOrder())));
|
||||||
|
|
||||||
|
Map<String, Set<String>> takenByOwner = new HashMap<>();
|
||||||
|
for (DeviceAddressBookEntity row : ordered) {
|
||||||
|
// 建表时 alias 默认是空的,用户没起名就是空的,这是默认状态不是异常。
|
||||||
|
// 补个尾号称呼顶上,整条跳过的话接口照样返回成功,对方却再也呼不过来
|
||||||
|
String alias = StringUtils.isBlank(row.getAlias())
|
||||||
|
? formatMacAsDeviceName(row.getTargetMac())
|
||||||
|
: row.getAlias();
|
||||||
|
|
||||||
|
// 加后缀的写法跟 generateUniqueAlias 保持一致,不搞两套命名规则
|
||||||
|
Set<String> taken = takenByOwner.computeIfAbsent(bookKey(row.getMacAddress()), k -> new HashSet<>());
|
||||||
|
String uniqueAlias = alias;
|
||||||
|
int suffix = 1;
|
||||||
|
while (taken.contains(uniqueAlias)) {
|
||||||
|
uniqueAlias = alias + suffix++;
|
||||||
|
}
|
||||||
|
taken.add(uniqueAlias);
|
||||||
|
row.setAlias(uniqueAlias);
|
||||||
|
}
|
||||||
|
return ordered;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void updateAlias(String macAddress, String targetMac, String alias) {
|
public void updateAlias(String macAddress, String targetMac, String alias) {
|
||||||
String finalAlias = generateUniqueAlias(macAddress, targetMac, alias);
|
String finalAlias = generateUniqueAlias(macAddress, targetMac, alias);
|
||||||
@@ -154,14 +208,22 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
QueryWrapper<DeviceAddressBookEntity> wrapper = new QueryWrapper<>();
|
QueryWrapper<DeviceAddressBookEntity> wrapper = new QueryWrapper<>();
|
||||||
wrapper.eq("mac_address", macAddress).eq("target_mac", targetMac);
|
wrapper.eq("mac_address", macAddress).eq("target_mac", targetMac);
|
||||||
DeviceAddressBookEntity record = deviceAddressBookDao.selectOne(wrapper);
|
DeviceAddressBookEntity record = deviceAddressBookDao.selectOne(wrapper);
|
||||||
System.out.println("saveOrUpdate - mac=" + macAddress + ", targetMac=" + targetMac + ", alias=" + alias + ", record=" + (record == null ? "null" : "not null"));
|
|
||||||
if (record == null) {
|
if (record == null) {
|
||||||
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
|
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
|
||||||
entity.setMacAddress(macAddress);
|
entity.setMacAddress(macAddress);
|
||||||
entity.setTargetMac(targetMac);
|
entity.setTargetMac(targetMac);
|
||||||
// 如果 alias 为空,就默认使用设备名称
|
// 如果 alias 为空,就默认使用设备名称;对方设备尚未登记时退回尾号称呼
|
||||||
if (StringUtils.isBlank(alias)) {
|
if (StringUtils.isBlank(alias)) {
|
||||||
alias = deviceService.getDeviceByMacAddress(targetMac).getAlias();
|
DeviceEntity targetDevice = deviceService.getDeviceByMacAddress(targetMac);
|
||||||
|
if (targetDevice != null) {
|
||||||
|
alias = targetDevice.getAlias();
|
||||||
|
}
|
||||||
|
// 设备登记了但用户没起过名,alias 建表就是 null,这是默认状态
|
||||||
|
// 不是异常。这时候落个 null 进去,缓存刷新会把整条跳过,
|
||||||
|
// 接口照样返回成功,对方却永远呼不过来
|
||||||
|
if (StringUtils.isBlank(alias)) {
|
||||||
|
alias = formatMacAsDeviceName(targetMac);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// 检查重名
|
// 检查重名
|
||||||
alias = generateUniqueAlias(macAddress, targetMac, alias);
|
alias = generateUniqueAlias(macAddress, targetMac, alias);
|
||||||
@@ -229,11 +291,27 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通讯录里当主人用的地址键
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* 写缓存、查缓存、算称呼都靠它分组,三处必须是同一个值。少归一一次,同一个人的两行
|
||||||
|
* 会被当成两个人:各自拿到同名,写进同一本时后者盖掉前者,一台设备直接从缓存里消失。
|
||||||
|
* 库里确实能出现这种数据——表是 utf8mb4_0900_ai_ci,主键 (mac_address, target_mac)
|
||||||
|
* 大小写不敏感,owner 只差大小写而 target 不同的话两行不撞
|
||||||
|
*/
|
||||||
|
private static String bookKey(String macAddress) {
|
||||||
|
return macAddress == null ? null : macAddress.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
private String formatMacAsDeviceName(String mac) {
|
private String formatMacAsDeviceName(String mac) {
|
||||||
if (StringUtils.isBlank(mac) || mac.length() < 2) {
|
if (StringUtils.isBlank(mac) || mac.length() < 2) {
|
||||||
return mac;
|
return mac;
|
||||||
}
|
}
|
||||||
String lastTwo = mac.substring(mac.length() - 2);
|
// MAC 本身不区分大小写,落库、查库走的都是小写化的值。
|
||||||
|
// 这里跟着小写化,不跟着的话同一个地址在两条路径上会算出两个称呼,
|
||||||
|
// 数据搬到智控台上看到的名字就叫不到人了
|
||||||
|
String lastTwo = mac.substring(mac.length() - 2).toLowerCase();
|
||||||
return "尾号为" + lastTwo + "的设备";
|
return "尾号为" + lastTwo + "的设备";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+29
@@ -316,6 +316,12 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
|||||||
if (device == null) {
|
if (device == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// 后面删通讯录那步是按 mac_address 删的,不看 user_id。
|
||||||
|
// 设备本身因为带了 user_id 条件删不掉,通讯录却会照删不误,
|
||||||
|
// 任意登录用户知道对方的设备 id 就能把对方整本通讯录清空
|
||||||
|
if (userId == null || device.getUserId() == null || !device.getUserId().equals(userId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
String macAddress = device.getMacAddress();
|
String macAddress = device.getMacAddress();
|
||||||
if (StringUtils.isNotBlank(device.getAgentId())) {
|
if (StringUtils.isNotBlank(device.getAgentId())) {
|
||||||
// 清除智能体设备数量缓存
|
// 清除智能体设备数量缓存
|
||||||
@@ -400,6 +406,29 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
|||||||
return baseDao.selectOne(wrapper);
|
return baseDao.selectOne(wrapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DeviceEntity getOwnedDeviceByMacAddress(String macAddress) {
|
||||||
|
if (StringUtils.isBlank(macAddress)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// 同一 MAC 可能有两行只差大小写,selectOne 会抛 TooManyResultsException
|
||||||
|
// 把整个读通讯录接口带崩。按 id 取第一条做归属校验,撞行不报错
|
||||||
|
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
|
||||||
|
wrapper.eq("mac_address", macAddress).orderByAsc("id");
|
||||||
|
List<DeviceEntity> devices = baseDao.selectList(wrapper);
|
||||||
|
if (devices == null || devices.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
DeviceEntity device = devices.get(0);
|
||||||
|
UserDetail user = SecurityUser.getUser();
|
||||||
|
// getUser() 在取不到 subject、principal 时返回的是空对象,不是 null,
|
||||||
|
// 所以这里不会拿到 null。匿名调用走的就是空对象那一条,id 是空的,比不上
|
||||||
|
if (device.getUserId() == null || !device.getUserId().equals(user.getId())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return device;
|
||||||
|
}
|
||||||
|
|
||||||
private DeviceReportRespDTO.ServerTime buildServerTime() {
|
private DeviceReportRespDTO.ServerTime buildServerTime() {
|
||||||
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
|
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
|
||||||
TimeZone tz = TimeZone.getDefault();
|
TimeZone tz = TimeZone.getDefault();
|
||||||
|
|||||||
+8
-7
@@ -110,8 +110,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||||||
// 1. 参数验证
|
// 1. 参数验证
|
||||||
validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO);
|
validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO);
|
||||||
|
|
||||||
// 2. 验证模型提供者
|
// 2. 验证模型提供者,使用注册类型的大小写
|
||||||
validateModelProvider(modelType, provideCode);
|
String registeredModelType = resolveModelType(modelType, provideCode);
|
||||||
|
|
||||||
// 3. 获取原始配置(不经过敏感数据处理)
|
// 3. 获取原始配置(不经过敏感数据处理)
|
||||||
ModelConfigEntity originalEntity = getOriginalConfigFromDb(id);
|
ModelConfigEntity originalEntity = getOriginalConfigFromDb(id);
|
||||||
@@ -120,7 +120,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||||||
validateLlmConfiguration(modelConfigBodyDTO);
|
validateLlmConfiguration(modelConfigBodyDTO);
|
||||||
|
|
||||||
// 5. 准备更新实体并处理敏感数据
|
// 5. 准备更新实体并处理敏感数据
|
||||||
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, modelType, id);
|
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, registeredModelType, id);
|
||||||
|
|
||||||
// 6. 执行数据库更新
|
// 6. 执行数据库更新
|
||||||
modelConfigDao.updateById(modelConfigEntity);
|
modelConfigDao.updateById(modelConfigEntity);
|
||||||
@@ -136,9 +136,9 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||||||
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
|
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
|
||||||
validateAddParameters(modelType, provideCode, modelConfigBodyDTO);
|
validateAddParameters(modelType, provideCode, modelConfigBodyDTO);
|
||||||
|
|
||||||
validateModelProvider(modelType, provideCode);
|
String registeredModelType = resolveModelType(modelType, provideCode);
|
||||||
|
|
||||||
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, modelType);
|
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, registeredModelType);
|
||||||
|
|
||||||
modelConfigDao.insert(modelConfigEntity);
|
modelConfigDao.insert(modelConfigEntity);
|
||||||
|
|
||||||
@@ -283,13 +283,14 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 验证模型提供者
|
* 验证模型提供者并获取注册类型,保留 TTS、Memory、Intent 等类型的大小写
|
||||||
*/
|
*/
|
||||||
private void validateModelProvider(String modelType, String provideCode) {
|
private String resolveModelType(String modelType, String provideCode) {
|
||||||
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
|
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
|
||||||
if (CollectionUtil.isEmpty(providerList)) {
|
if (CollectionUtil.isEmpty(providerList)) {
|
||||||
throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST);
|
throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST);
|
||||||
}
|
}
|
||||||
|
return providerList.get(0).getModelType();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ public class ShiroConfig {
|
|||||||
filterMap.put("/user/captcha", "anon");
|
filterMap.put("/user/captcha", "anon");
|
||||||
filterMap.put("/user/smsVerification", "anon");
|
filterMap.put("/user/smsVerification", "anon");
|
||||||
filterMap.put("/user/login", "anon");
|
filterMap.put("/user/login", "anon");
|
||||||
|
filterMap.put("/user/refresh", "anon");
|
||||||
filterMap.put("/user/pub-config", "anon");
|
filterMap.put("/user/pub-config", "anon");
|
||||||
filterMap.put("/user/register", "anon");
|
filterMap.put("/user/register", "anon");
|
||||||
filterMap.put("/user/retrieve-password", "anon");
|
filterMap.put("/user/retrieve-password", "anon");
|
||||||
|
|||||||
+12
@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -110,6 +111,17 @@ public class LoginController {
|
|||||||
return sysUserTokenService.createToken(userDTO.getId());
|
return sysUserTokenService.createToken(userDTO.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/refresh")
|
||||||
|
@Operation(summary = "刷新token:用旧token换新token")
|
||||||
|
public Result<TokenDTO> refresh(HttpServletRequest request) {
|
||||||
|
String authorization = request.getHeader(Constant.AUTHORIZATION);
|
||||||
|
if (StringUtils.isBlank(authorization) || !authorization.startsWith("Bearer ")) {
|
||||||
|
throw new RenException(ErrorCode.UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
String oldToken = authorization.replace("Bearer ", "");
|
||||||
|
return sysUserTokenService.refreshToken(oldToken);
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
@Operation(summary = "注册")
|
@Operation(summary = "注册")
|
||||||
public Result<Void> register(@RequestBody LoginDTO login) {
|
public Result<Void> register(@RequestBody LoginDTO login) {
|
||||||
|
|||||||
@@ -21,4 +21,14 @@ public interface SysUserTokenDao extends BaseDao<SysUserTokenEntity> {
|
|||||||
SysUserTokenEntity getByUserId(Long userId);
|
SysUserTokenEntity getByUserId(Long userId);
|
||||||
|
|
||||||
void logout(@Param("userId") Long userId, @Param("expireDate") Date expireDate);
|
void logout(@Param("userId") Long userId, @Param("expireDate") Date expireDate);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用旧 token 换新 token 的 CAS 更新:仅当旧 token 未过期且属于指定 user 时才覆盖。
|
||||||
|
* 返回受影响行数(0 表示条件不满足 = token 已被并发刷新或过期)。
|
||||||
|
*/
|
||||||
|
int refreshTokenCAS(@Param("userId") Long userId,
|
||||||
|
@Param("oldToken") String oldToken,
|
||||||
|
@Param("newToken") String newToken,
|
||||||
|
@Param("newExpire") Date newExpire,
|
||||||
|
@Param("updateDate") Date updateDate);
|
||||||
}
|
}
|
||||||
+7
@@ -21,6 +21,13 @@ public interface SysUserTokenService extends BaseService<SysUserTokenEntity> {
|
|||||||
*/
|
*/
|
||||||
Result<TokenDTO> createToken(Long userId);
|
Result<TokenDTO> createToken(Long userId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用旧token换新token,旧token立即失效
|
||||||
|
*
|
||||||
|
* @param oldToken 旧token字符串
|
||||||
|
*/
|
||||||
|
Result<TokenDTO> refreshToken(String oldToken);
|
||||||
|
|
||||||
SysUserDTO getUserByToken(String token);
|
SysUserDTO getUserByToken(String token);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+32
@@ -2,7 +2,9 @@ package xiaozhi.modules.security.service.impl;
|
|||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import cn.hutool.core.date.DateUtil;
|
import cn.hutool.core.date.DateUtil;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -81,6 +83,36 @@ public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, Sy
|
|||||||
return new Result<TokenDTO>().ok(tokenDTO);
|
return new Result<TokenDTO>().ok(tokenDTO);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public Result<TokenDTO> refreshToken(String oldToken) {
|
||||||
|
if (StringUtils.isBlank(oldToken)) {
|
||||||
|
throw new RenException(ErrorCode.UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
SysUserTokenEntity tokenEntity = baseDao.getByToken(oldToken);
|
||||||
|
if (tokenEntity == null) {
|
||||||
|
throw new RenException(ErrorCode.TOKEN_INVALID);
|
||||||
|
}
|
||||||
|
if (tokenEntity.getExpireDate().before(new Date())) {
|
||||||
|
throw new RenException(ErrorCode.UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
// CAS 更新:并发场景下只有一个请求能匹配到该 oldToken,另一个返 0 行
|
||||||
|
String newToken = TokenGenerator.generateValue();
|
||||||
|
Date now = new Date();
|
||||||
|
Date expireTime = new Date(now.getTime() + EXPIRE * 1000L);
|
||||||
|
int affected = baseDao.refreshTokenCAS(tokenEntity.getUserId(), oldToken, newToken, expireTime, now);
|
||||||
|
if (affected == 0) {
|
||||||
|
throw new RenException(ErrorCode.TOKEN_INVALID);
|
||||||
|
}
|
||||||
|
|
||||||
|
TokenDTO dto = new TokenDTO();
|
||||||
|
dto.setToken(newToken);
|
||||||
|
dto.setExpire(EXPIRE);
|
||||||
|
dto.setClientHash(HttpContextUtils.getClientCode());
|
||||||
|
return new Result<TokenDTO>().ok(dto);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SysUserDTO getUserByToken(String token) {
|
public SysUserDTO getUserByToken(String token) {
|
||||||
SysUserTokenEntity userToken = baseDao.getByToken(token);
|
SysUserTokenEntity userToken = baseDao.getByToken(token);
|
||||||
|
|||||||
@@ -14,4 +14,12 @@
|
|||||||
<update id="logout">
|
<update id="logout">
|
||||||
update sys_user_token set expire_date = #{expireDate} where user_id = #{userId}
|
update sys_user_token set expire_date = #{expireDate} where user_id = #{userId}
|
||||||
</update>
|
</update>
|
||||||
|
|
||||||
|
<update id="refreshTokenCAS">
|
||||||
|
update sys_user_token
|
||||||
|
set token = #{newToken}, update_date = #{updateDate}, expire_date = #{newExpire}
|
||||||
|
where token = #{oldToken}
|
||||||
|
and expire_date > NOW()
|
||||||
|
and user_id = #{userId}
|
||||||
|
</update>
|
||||||
</mapper>
|
</mapper>
|
||||||
@@ -44,7 +44,7 @@ class SensitiveDataUtilsTest {
|
|||||||
void maskMiddle_keeps_four_at_each_end_for_long_strings() {
|
void maskMiddle_keeps_four_at_each_end_for_long_strings() {
|
||||||
String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123");
|
String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123");
|
||||||
assertTrue(masked.startsWith("very"));
|
assertTrue(masked.startsWith("very"));
|
||||||
assertTrue(masked.endsWith("3123"));
|
assertTrue(masked.endsWith("e123"));
|
||||||
assertTrue(masked.contains("****"));
|
assertTrue(masked.contains("****"));
|
||||||
assertEquals("verylongapikeyvalue123".length(), masked.length());
|
assertEquals("verylongapikeyvalue123".length(), masked.length());
|
||||||
}
|
}
|
||||||
|
|||||||
+86
-3
@@ -1,11 +1,15 @@
|
|||||||
package xiaozhi.modules.device.controller;
|
package xiaozhi.modules.device.controller;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.mockStatic;
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.MockedStatic;
|
import org.mockito.MockedStatic;
|
||||||
@@ -15,7 +19,10 @@ import xiaozhi.common.redis.RedisUtils;
|
|||||||
import xiaozhi.common.user.UserDetail;
|
import xiaozhi.common.user.UserDetail;
|
||||||
import xiaozhi.common.utils.MessageUtils;
|
import xiaozhi.common.utils.MessageUtils;
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
|
import xiaozhi.modules.device.dto.DeviceAddressBookAliasDTO;
|
||||||
|
import xiaozhi.modules.device.dto.DeviceAddressBookPermissionDTO;
|
||||||
import xiaozhi.modules.device.dto.DeviceUpdateDTO;
|
import xiaozhi.modules.device.dto.DeviceUpdateDTO;
|
||||||
|
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
|
||||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceAddressBookService;
|
import xiaozhi.modules.device.service.DeviceAddressBookService;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
@@ -26,6 +33,8 @@ import xiaozhi.modules.sys.service.SysParamsService;
|
|||||||
class DeviceControllerTest {
|
class DeviceControllerTest {
|
||||||
|
|
||||||
private static final String DEVICE_ID = "device-id";
|
private static final String DEVICE_ID = "device-id";
|
||||||
|
private static final String MAC = "00:11:22:33:44:55";
|
||||||
|
private static final String OTHER_MAC = "00:11:22:33:44:66";
|
||||||
private static final long USER_ID = 1L;
|
private static final long USER_ID = 1L;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -35,7 +44,7 @@ class DeviceControllerTest {
|
|||||||
DeviceEntity entity = ownedDevice();
|
DeviceEntity entity = ownedDevice();
|
||||||
when(deviceService.selectById(DEVICE_ID)).thenReturn(entity);
|
when(deviceService.selectById(DEVICE_ID)).thenReturn(entity);
|
||||||
when(deviceService.updateById(entity)).thenReturn(false);
|
when(deviceService.updateById(entity)).thenReturn(false);
|
||||||
DeviceController controller = controller(deviceService);
|
DeviceController controller = controller(deviceService, mock(DeviceAddressBookService.class));
|
||||||
|
|
||||||
DeviceUpdateDTO update = new DeviceUpdateDTO();
|
DeviceUpdateDTO update = new DeviceUpdateDTO();
|
||||||
update.setAutoUpdate(0);
|
update.setAutoUpdate(0);
|
||||||
@@ -54,10 +63,84 @@ class DeviceControllerTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private DeviceController controller(DeviceService deviceService) {
|
@Test
|
||||||
|
@DisplayName("读取他人设备通讯录时一律按设备不存在处理")
|
||||||
|
void addressBookOfDeviceOwnedByAnotherUserIsRejected() {
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
|
||||||
|
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
|
||||||
|
DeviceController controller = controller(deviceService, addressBookService);
|
||||||
|
|
||||||
|
try (MockedStatic<MessageUtils> messageUtils = mockStatic(MessageUtils.class)) {
|
||||||
|
messageUtils.when(() -> MessageUtils.getMessage(ErrorCode.DEVICE_NOT_EXIST))
|
||||||
|
.thenReturn("Device not exist");
|
||||||
|
|
||||||
|
Result<Object> result = controller.getAddressBook(OTHER_MAC);
|
||||||
|
|
||||||
|
assertEquals(ErrorCode.DEVICE_NOT_EXIST, result.getCode());
|
||||||
|
assertNull(result.getData());
|
||||||
|
verify(addressBookService, never()).getAddressBookList(OTHER_MAC);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("读取本机设备通讯录照常返回")
|
||||||
|
void addressBookOfOwnDeviceIsReturned() {
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
|
||||||
|
List<DeviceAddressBookEntity> entries = List.of(new DeviceAddressBookEntity());
|
||||||
|
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(ownedDevice());
|
||||||
|
when(addressBookService.getAddressBookList(MAC)).thenReturn(entries);
|
||||||
|
DeviceController controller = controller(deviceService, addressBookService);
|
||||||
|
|
||||||
|
Result<Object> result = controller.getAddressBook(MAC);
|
||||||
|
|
||||||
|
assertEquals(0, result.getCode());
|
||||||
|
assertEquals(entries, result.getData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("以他人设备名义改别名被拒")
|
||||||
|
void updateAliasOnDeviceOwnedByAnotherUserIsRejected() {
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
|
||||||
|
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
|
||||||
|
DeviceController controller = controller(deviceService, addressBookService);
|
||||||
|
|
||||||
|
DeviceAddressBookAliasDTO dto = new DeviceAddressBookAliasDTO();
|
||||||
|
dto.setMacAddress(OTHER_MAC);
|
||||||
|
dto.setTargetMac(MAC);
|
||||||
|
dto.setAlias("office");
|
||||||
|
|
||||||
|
Result<Void> result = controller.updateAlias(dto);
|
||||||
|
|
||||||
|
assertEquals("无权限操作该设备", result.getMsg());
|
||||||
|
verify(addressBookService, never()).saveOrUpdate(OTHER_MAC, MAC, "office", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("以他人设备名义改权限被拒")
|
||||||
|
void updatePermissionOnDeviceOwnedByAnotherUserIsRejected() {
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
|
||||||
|
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
|
||||||
|
DeviceController controller = controller(deviceService, addressBookService);
|
||||||
|
|
||||||
|
DeviceAddressBookPermissionDTO dto = new DeviceAddressBookPermissionDTO();
|
||||||
|
dto.setMacAddress(OTHER_MAC);
|
||||||
|
dto.setTargetMac(MAC);
|
||||||
|
dto.setHasPermission(true);
|
||||||
|
|
||||||
|
Result<Void> result = controller.updatePermission(dto);
|
||||||
|
|
||||||
|
assertEquals("无权限操作该设备", result.getMsg());
|
||||||
|
verify(addressBookService, never()).saveOrUpdate(OTHER_MAC, MAC, null, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceController controller(DeviceService deviceService, DeviceAddressBookService addressBookService) {
|
||||||
return new DeviceController(
|
return new DeviceController(
|
||||||
deviceService,
|
deviceService,
|
||||||
mock(DeviceAddressBookService.class),
|
addressBookService,
|
||||||
mock(RedisUtils.class),
|
mock(RedisUtils.class),
|
||||||
mock(SysParamsService.class));
|
mock(SysParamsService.class));
|
||||||
}
|
}
|
||||||
|
|||||||
+372
-3
@@ -1,26 +1,47 @@
|
|||||||
package xiaozhi.modules.device.service.impl;
|
package xiaozhi.modules.device.service.impl;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import xiaozhi.common.constant.Constant;
|
||||||
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
import xiaozhi.modules.device.dao.DeviceAddressBookDao;
|
import xiaozhi.modules.device.dao.DeviceAddressBookDao;
|
||||||
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
|
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
|
||||||
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
|
|
||||||
class DeviceAddressBookServiceImplTest {
|
class DeviceAddressBookServiceImplTest {
|
||||||
|
|
||||||
|
private static final String MAC = "00:11:22:33:44:55";
|
||||||
|
private static final String OTHER_MAC = "00:11:22:33:44:66";
|
||||||
|
private static final String THIRD_MAC = "00:11:22:33:44:77";
|
||||||
|
// 纯数字的 MAC 大小写化后跟原来一模一样,拿它造不出"只差大小写"的两行
|
||||||
|
private static final String HEX_MAC = "00:11:22:33:44:ab";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void newEntryUsesTheDedicatedAddressBookInsertMapping() {
|
void newEntryUsesTheDedicatedAddressBookInsertMapping() {
|
||||||
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
@@ -32,15 +53,363 @@ class DeviceAddressBookServiceImplTest {
|
|||||||
when(addressBookDao.selectOne(any())).thenReturn(null);
|
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||||
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||||
|
|
||||||
service.saveOrUpdate("00:11:22:33:44:55", "00:11:22:33:44:66", "living-room", true);
|
service.saveOrUpdate(MAC, OTHER_MAC, "living-room", true);
|
||||||
|
|
||||||
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||||
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||||
DeviceAddressBookEntity entity = entityCaptor.getValue();
|
DeviceAddressBookEntity entity = entityCaptor.getValue();
|
||||||
assertEquals("00:11:22:33:44:55", entity.getMacAddress());
|
assertEquals(MAC, entity.getMacAddress());
|
||||||
assertEquals("00:11:22:33:44:66", entity.getTargetMac());
|
assertEquals(OTHER_MAC, entity.getTargetMac());
|
||||||
assertEquals("living-room", entity.getAlias());
|
assertEquals("living-room", entity.getAlias());
|
||||||
assertTrue(entity.getHasPermission());
|
assertTrue(entity.getHasPermission());
|
||||||
verify(addressBookDao, never()).insert(any(DeviceAddressBookEntity.class));
|
verify(addressBookDao, never()).insert(any(DeviceAddressBookEntity.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blankAliasOnUnregisteredTargetFallsBackToMacSuffix() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||||
|
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||||
|
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
|
||||||
|
|
||||||
|
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
|
||||||
|
|
||||||
|
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||||
|
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||||
|
DeviceAddressBookEntity entity = entityCaptor.getValue();
|
||||||
|
assertNotNull(entity.getAlias());
|
||||||
|
assertEquals("尾号为66的设备", entity.getAlias());
|
||||||
|
assertTrue(entity.getHasPermission());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blankAliasOnRegisteredTargetWithoutNicknameFallsBackToMacSuffix() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||||
|
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||||
|
DeviceEntity registered = new DeviceEntity();
|
||||||
|
registered.setMacAddress(OTHER_MAC);
|
||||||
|
registered.setAlias(null);
|
||||||
|
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
|
||||||
|
|
||||||
|
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
|
||||||
|
|
||||||
|
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||||
|
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||||
|
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
|
||||||
|
"登记了但没起名的设备落个空名,缓存刷新会跳过这条,对方永远呼不过来");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void refreshCacheKeepsEntriesWhoseAliasWasNeverFilledIn() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of(row(MAC, OTHER_MAC, null)));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
service.refreshCache();
|
||||||
|
|
||||||
|
Map<String, String> book = cachedBook(service, redisUtils).get(MAC);
|
||||||
|
assertNotNull(book, "空别名整条被跳过,这条设备就再也呼不过来了");
|
||||||
|
assertEquals(OTHER_MAC + "|1", book.get("尾号为66的设备"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void refreshCacheDisambiguatesTwoEntriesSharingAnAlias() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of(
|
||||||
|
row(MAC, OTHER_MAC, "客厅"),
|
||||||
|
row(MAC, THIRD_MAC, "客厅")));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
service.refreshCache();
|
||||||
|
|
||||||
|
Map<String, String> book = cachedBook(service, redisUtils).get(MAC);
|
||||||
|
assertEquals(2, book.size(), "撞名的两台设备只留得下一台:" + book);
|
||||||
|
assertEquals(OTHER_MAC + "|1", book.get("客厅"));
|
||||||
|
assertEquals(THIRD_MAC + "|1", book.get("客厅1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void refreshCacheGivesTheSameResultWhateverOrderRowsComeBackIn() {
|
||||||
|
DeviceAddressBookEntity first = row(MAC, OTHER_MAC, "客厅");
|
||||||
|
DeviceAddressBookEntity second = row(MAC, THIRD_MAC, "客厅");
|
||||||
|
|
||||||
|
Map<String, String> inOrder = refreshAndRead(List.of(first, second));
|
||||||
|
Map<String, String> reversed = refreshAndRead(List.of(second, first));
|
||||||
|
|
||||||
|
assertEquals(inOrder, reversed, "同样的数据两次刷新结果不一样,缓存里的称呼会来回变");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 库里能同时存在两条 owner 只差大小写的行:表是 utf8mb4_0900_ai_ci,
|
||||||
|
* 主键 (mac_address, target_mac) 大小写不敏感,target 不同就不会撞。
|
||||||
|
* 这是同一个人,算称呼和写缓存都得按小写归成一本
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void ownersDifferingOnlyInCaseShareOneBook() {
|
||||||
|
String upper = HEX_MAC.toUpperCase();
|
||||||
|
assertNotEquals(HEX_MAC, upper, "这个用例得真的造出大小写差异才有效");
|
||||||
|
|
||||||
|
Map<String, Map<String, String>> books = refreshAndReadAll(List.of(
|
||||||
|
row(upper, OTHER_MAC, "客厅"),
|
||||||
|
row(HEX_MAC, THIRD_MAC, "客厅")));
|
||||||
|
|
||||||
|
Map<String, String> book = books.get(HEX_MAC);
|
||||||
|
assertNotNull(book, "同一个人被算成了两个人:" + books.keySet());
|
||||||
|
assertEquals(2, book.size(), "两台设备只剩一台,另一台从缓存里消失了:" + book);
|
||||||
|
assertEquals(OTHER_MAC + "|1", book.get("客厅"));
|
||||||
|
assertEquals(THIRD_MAC + "|1", book.get("客厅1"));
|
||||||
|
assertEquals(1, books.size(), "两种写法的地址被拆成了两本:" + books.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listAndCacheAgreeWhenOwnersDifferOnlyInCase() {
|
||||||
|
String upper = HEX_MAC.toUpperCase();
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
when(addressBookDao.getAddressBookList(upper)).thenReturn(new ArrayList<>(List.of(
|
||||||
|
row(upper, OTHER_MAC, "客厅"), row(HEX_MAC, THIRD_MAC, "客厅"))));
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of(
|
||||||
|
row(upper, OTHER_MAC, "客厅"), row(HEX_MAC, THIRD_MAC, "客厅")));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
Map<String, String> shownToConsole = namesByTargetMac(service.getAddressBookList(upper));
|
||||||
|
assertEquals(2, shownToConsole.size(),
|
||||||
|
"接口按原值分组,同一个人的两台设备被算成一个,前端只能看到一台:" + shownToConsole);
|
||||||
|
|
||||||
|
service.refreshCache();
|
||||||
|
Map<String, String> callableNames = new HashMap<>();
|
||||||
|
cachedBook(service, redisUtils).get(HEX_MAC)
|
||||||
|
.forEach((name, macAndPerm) -> callableNames.put(name, macAndPerm.split("\\|")[0]));
|
||||||
|
|
||||||
|
assertEquals(shownToConsole, callableNames,
|
||||||
|
"接口按原值分组、缓存按小写分组,用户照前端看到的名字呼,命中的不是同一台设备");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nameAssignmentDoesNotDependOnWhichSpellingOfTheOwnerCameBack() {
|
||||||
|
String upper = HEX_MAC.toUpperCase();
|
||||||
|
Map<String, String> expected = Map.of("客厅", OTHER_MAC + "|1", "客厅1", THIRD_MAC + "|1");
|
||||||
|
|
||||||
|
Map<String, String> lowerFirst = refreshAndRead(HEX_MAC, List.of(
|
||||||
|
row(HEX_MAC, OTHER_MAC, "客厅"), row(upper, THIRD_MAC, "客厅")));
|
||||||
|
Map<String, String> upperFirst = refreshAndRead(HEX_MAC, List.of(
|
||||||
|
row(upper, THIRD_MAC, "客厅"), row(HEX_MAC, OTHER_MAC, "客厅")));
|
||||||
|
|
||||||
|
assertEquals(expected, lowerFirst,
|
||||||
|
"同一个人的称呼取决于库里哪种写法先返回,刷新一次就换一次名字");
|
||||||
|
assertEquals(expected, upperFirst, "顺序反过来结果就该不一样:" + upperFirst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Map<String, String>> refreshAndReadAll(List<DeviceAddressBookEntity> rows) {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(rows);
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
service.refreshCache();
|
||||||
|
|
||||||
|
return cachedBook(service, redisUtils);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> refreshAndRead(List<DeviceAddressBookEntity> rows) {
|
||||||
|
return refreshAndRead(MAC, rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> refreshAndRead(String owner, List<DeviceAddressBookEntity> rows) {
|
||||||
|
return refreshAndReadAll(rows).get(owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Map<String, String>> cachedBook(DeviceAddressBookServiceImpl service, RedisUtils redisUtils) {
|
||||||
|
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(redisUtils).set(eq(RedisKeys.getAddressBookKey()), captor.capture());
|
||||||
|
return (Map<String, Map<String, String>>) captor.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceAddressBookEntity row(String macAddress, String targetMac, String alias) {
|
||||||
|
return row(macAddress, targetMac, alias, Boolean.TRUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceAddressBookEntity row(String macAddress, String targetMac, String alias, Boolean hasPermission) {
|
||||||
|
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
|
||||||
|
entity.setMacAddress(macAddress);
|
||||||
|
entity.setTargetMac(targetMac);
|
||||||
|
entity.setAlias(alias);
|
||||||
|
entity.setHasPermission(hasPermission);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listAndCacheHandOutTheSameNameForCollidingEntries() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
// 两次 DAO 调用各给一份新行:取名会写回实体,共用同一份的话第二遍读到的是算过的名字
|
||||||
|
// 用可变列表,跟 MyBatis 实际返回的一致,免得排序那步先炸掉、断言根本没跑到
|
||||||
|
when(addressBookDao.getAddressBookList(MAC)).thenReturn(
|
||||||
|
new ArrayList<>(List.of(row(MAC, OTHER_MAC, "客厅"), row(MAC, THIRD_MAC, "客厅"))));
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of(
|
||||||
|
row(MAC, OTHER_MAC, "客厅"), row(MAC, THIRD_MAC, "客厅")));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
Map<String, String> shownToConsole = namesByTargetMac(service.getAddressBookList(MAC));
|
||||||
|
service.refreshCache();
|
||||||
|
Map<String, String> callableNames = new HashMap<>();
|
||||||
|
cachedBook(service, redisUtils).get(MAC)
|
||||||
|
.forEach((name, macAndPerm) -> callableNames.put(name, macAndPerm.split("\\|")[0]));
|
||||||
|
|
||||||
|
assertEquals(callableNames, shownToConsole,
|
||||||
|
"接口和缓存给的是两个名字,用户照前端看到的那个名字呼叫,命中的不是同一台设备");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void theCallableEntryKeepsThePlainNameWhenTwoCollide() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
// OTHER_MAC 的 target_mac 排在前面,没权限的那条会先占住原名
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of(
|
||||||
|
row(MAC, OTHER_MAC, "客厅", Boolean.FALSE),
|
||||||
|
row(MAC, THIRD_MAC, "客厅", Boolean.TRUE)));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
service.refreshCache();
|
||||||
|
|
||||||
|
Map<String, String> book = cachedBook(service, redisUtils).get(MAC);
|
||||||
|
assertEquals(THIRD_MAC + "|1", book.get("客厅"),
|
||||||
|
"能呼的那台被挤到后缀名上了,用户照前端看到的名字点,界面只会说没权限");
|
||||||
|
assertEquals(OTHER_MAC + "|0", book.get("客厅1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listFillsInBlankAliasesSoTheConsoleShowsWhatCanBeCalled() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
when(addressBookDao.getAddressBookList(MAC)).thenReturn(new ArrayList<>(List.of(row(MAC, OTHER_MAC, null))));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
List<DeviceAddressBookEntity> rows = service.getAddressBookList(MAC);
|
||||||
|
|
||||||
|
assertEquals("尾号为66的设备", rows.get(0).getAlias(),
|
||||||
|
"空别名原样返回的话前端回落显示设备名,用户照着那个名字呼叫却只会说找不到备注");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void anUppercaseMacGetsTheSameNameWhicheverPathAddsItToTheBook() {
|
||||||
|
// 兜底称呼只有这一处算法:存进去的时候算一次,之后接口和缓存里显示的
|
||||||
|
// 都是同一个字符串。不跟着小写化的话同一个地址在两条路径上算出两个称呼,
|
||||||
|
// 用户照着看到的名字呼过去,命中的不是自己刚存的那台
|
||||||
|
//
|
||||||
|
// 运行期这一侧:saveOrUpdate 传的是 DTO 原样过来的地址,大小写没归一
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
when(addressBookDao.selectOne(any())).thenReturn(null);
|
||||||
|
when(addressBookDao.selectList(null)).thenReturn(List.of());
|
||||||
|
when(deviceService.getDeviceByMacAddress(anyString())).thenReturn(null);
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, deviceService, mock(SysParamsService.class));
|
||||||
|
|
||||||
|
service.saveOrUpdate(MAC, "ff:ee:dd:cc:bb:AB", null, true);
|
||||||
|
|
||||||
|
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
|
||||||
|
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
|
||||||
|
assertEquals("尾号为ab的设备", entityCaptor.getValue().getAlias(),
|
||||||
|
"MAC 大小写不区分,末尾两位要跟着小写化,否则接口和呼叫那边算出来的称呼对不上");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口按最近改过的排前面
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* 智控台那条 Vue 是按 targetMac 把 alias 合进 allDevices 的,接口顺序被丢掉了,
|
||||||
|
* 这条现在对 console 没有效果。用例留着是把这个契约钉住:哪天当无用代码删了,
|
||||||
|
* 会有用例报出来,而不是静悄悄换掉接口的返回顺序
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void listPutsTheMostRecentlyTouchedEntryFirst() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
DeviceAddressBookEntity older = row(MAC, OTHER_MAC, "客厅");
|
||||||
|
older.setUpdateDate(new Date(1767321840000L));
|
||||||
|
DeviceAddressBookEntity newer = row(MAC, THIRD_MAC, "书房");
|
||||||
|
newer.setUpdateDate(new Date(1778000000000L));
|
||||||
|
DeviceAddressBookEntity neverTouched = row(MAC, "00:11:22:33:44:88", "阳台");
|
||||||
|
when(addressBookDao.getAddressBookList(MAC)).thenReturn(
|
||||||
|
new ArrayList<>(List.of(older, neverTouched, newer)));
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
|
||||||
|
|
||||||
|
List<DeviceAddressBookEntity> rows = service.getAddressBookList(MAC);
|
||||||
|
|
||||||
|
assertEquals(List.of("书房", "客厅", "阳台"), rows.stream().map(DeviceAddressBookEntity::getAlias).toList(),
|
||||||
|
"最近改过的应该排前面,没改过的排最后");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private Map<String, String> namesByTargetMac(List<DeviceAddressBookEntity> rows) {
|
||||||
|
Map<String, String> byAlias = new HashMap<>();
|
||||||
|
for (DeviceAddressBookEntity row : rows) {
|
||||||
|
byAlias.put(row.getAlias(), row.getTargetMac());
|
||||||
|
}
|
||||||
|
return byAlias;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void callByNicknameFallsBackToMacSuffixWhenCallerHasNoAlias() {
|
||||||
|
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
|
||||||
|
RedisUtils redisUtils = mock(RedisUtils.class);
|
||||||
|
DeviceService deviceService = mock(DeviceService.class);
|
||||||
|
SysParamsService sysParamsService = mock(SysParamsService.class);
|
||||||
|
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
|
||||||
|
addressBookDao, redisUtils, deviceService, sysParamsService);
|
||||||
|
|
||||||
|
Map<String, Map<String, String>> books = new HashMap<>();
|
||||||
|
Map<String, String> callerBook = new HashMap<>();
|
||||||
|
callerBook.put("office", OTHER_MAC + "|1");
|
||||||
|
books.put(MAC, callerBook);
|
||||||
|
when(redisUtils.get(RedisKeys.getAddressBookKey())).thenReturn(books);
|
||||||
|
when(deviceService.getDeviceByMacAddress(MAC)).thenReturn(null);
|
||||||
|
when(sysParamsService.getValue("server.mqtt_manager_api", true)).thenReturn("127.0.0.1:1883");
|
||||||
|
when(sysParamsService.getValue(Constant.SERVER_MQTT_SECRET, true)).thenReturn("gateway-key");
|
||||||
|
|
||||||
|
// 网关是真的 http 调用,桩掉它,否则测试会往 127.0.0.1:1883 真发请求
|
||||||
|
AtomicReference<String> sentUrl = new AtomicReference<>();
|
||||||
|
AtomicReference<String> sentBody = new AtomicReference<>();
|
||||||
|
Map<String, Object> result;
|
||||||
|
try (MockedStatic<MqttGatewayAuthorization> gateway = mockStatic(MqttGatewayAuthorization.class)) {
|
||||||
|
gateway.when(() -> MqttGatewayAuthorization.postJson(
|
||||||
|
anyString(), anyString(), anyString(), any(), anyInt()))
|
||||||
|
.thenAnswer(invocation -> {
|
||||||
|
sentUrl.set(invocation.getArgument(0));
|
||||||
|
sentBody.set(invocation.getArgument(1));
|
||||||
|
return "{\"status\":\"success\",\"message\":\"ok\"}";
|
||||||
|
});
|
||||||
|
result = service.callByNickname(MAC, "office", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("success", result.get("status"));
|
||||||
|
assertEquals("http://127.0.0.1:1883/api/call/request", sentUrl.get());
|
||||||
|
assertTrue(sentBody.get().contains("尾号为55的设备"),
|
||||||
|
"主叫方没登记也没起名时该退回尾号称呼:" + sentBody.get());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+184
@@ -0,0 +1,184 @@
|
|||||||
|
package xiaozhi.modules.device.service.impl;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyList;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||||
|
|
||||||
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
|
import xiaozhi.common.user.UserDetail;
|
||||||
|
import xiaozhi.modules.device.dao.DeviceDao;
|
||||||
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
|
import xiaozhi.modules.device.service.DeviceAddressBookService;
|
||||||
|
import xiaozhi.modules.device.service.OtaService;
|
||||||
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
|
import xiaozhi.modules.sys.service.SysUserUtilService;
|
||||||
|
|
||||||
|
@DisplayName("设备归属校验回归测试")
|
||||||
|
class DeviceServiceImplTest {
|
||||||
|
|
||||||
|
private static final String MAC = "00:11:22:33:44:55";
|
||||||
|
private static final long USER_ID = 1L;
|
||||||
|
private static final long OTHER_USER_ID = 2L;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("设备属于当前用户时返回设备")
|
||||||
|
void deviceOwnedByCurrentUserIsReturned() {
|
||||||
|
DeviceEntity device = device(USER_ID);
|
||||||
|
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device));
|
||||||
|
|
||||||
|
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
|
||||||
|
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
|
||||||
|
|
||||||
|
assertSame(device, service.getOwnedDeviceByMacAddress(MAC));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("设备属于他人时按查不到处理")
|
||||||
|
void deviceOwnedByAnotherUserIsHidden() {
|
||||||
|
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device(OTHER_USER_ID)));
|
||||||
|
|
||||||
|
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
|
||||||
|
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
|
||||||
|
|
||||||
|
assertNull(service.getOwnedDeviceByMacAddress(MAC));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("设备未登记时按查不到处理")
|
||||||
|
void unregisteredDeviceIsHidden() {
|
||||||
|
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(List.of()));
|
||||||
|
|
||||||
|
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
|
||||||
|
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
|
||||||
|
|
||||||
|
assertNull(service.getOwnedDeviceByMacAddress(MAC));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("设备没有归属人时按查不到处理")
|
||||||
|
void unboundDeviceIsHidden() {
|
||||||
|
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device(null)));
|
||||||
|
|
||||||
|
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
|
||||||
|
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
|
||||||
|
|
||||||
|
assertNull(service.getOwnedDeviceByMacAddress(MAC));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("没有登录用户时按查不到处理")
|
||||||
|
void anonymousCallerGetsNothing() {
|
||||||
|
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device(USER_ID)));
|
||||||
|
|
||||||
|
// 匿名调用的实际形态:getUser() 返回空对象,id 是空的,不是返回 null
|
||||||
|
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
|
||||||
|
securityUser.when(SecurityUser::getUser).thenReturn(new UserDetail());
|
||||||
|
|
||||||
|
assertNull(service.getOwnedDeviceByMacAddress(MAC));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("库里同一 MAC 有两行只差大小写时,取第一条做归属校验,不再抛异常")
|
||||||
|
void duplicateMacDifferingOnlyInCaseStillReturnsTheDevice() {
|
||||||
|
DeviceEntity first = device(USER_ID, "device-1");
|
||||||
|
DeviceEntity second = device(USER_ID, "device-2");
|
||||||
|
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(List.of(first, second)));
|
||||||
|
|
||||||
|
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
|
||||||
|
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
|
||||||
|
|
||||||
|
assertSame(first, service.getOwnedDeviceByMacAddress(MAC));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("解绑自己的设备时,通讯录跟着一起清")
|
||||||
|
void unbindOwnDeviceClearsItsAddressBook() {
|
||||||
|
DeviceDao dao = mock(DeviceDao.class);
|
||||||
|
when(dao.selectById("device-1")).thenReturn(device(USER_ID, "device-1"));
|
||||||
|
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
|
||||||
|
DeviceServiceImpl service = serviceWithDao(dao, addressBookService);
|
||||||
|
|
||||||
|
service.unbindDevice(USER_ID, "device-1");
|
||||||
|
|
||||||
|
verify(dao).delete(any(UpdateWrapper.class));
|
||||||
|
verify(addressBookService).deleteByMacAddresses(List.of(MAC));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("解绑别人的设备时什么都不删,通讯录不能跟着没")
|
||||||
|
void unbindAnotherUsersDeviceDeletesNothing() {
|
||||||
|
DeviceDao dao = mock(DeviceDao.class);
|
||||||
|
when(dao.selectById("device-1")).thenReturn(device(OTHER_USER_ID, "device-1"));
|
||||||
|
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
|
||||||
|
DeviceServiceImpl service = serviceWithDao(dao, addressBookService);
|
||||||
|
|
||||||
|
service.unbindDevice(USER_ID, "device-1");
|
||||||
|
|
||||||
|
verify(dao, never()).delete(any(UpdateWrapper.class));
|
||||||
|
verify(addressBookService, never()).deleteByMacAddresses(anyList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceServiceImpl serviceWithDao(DeviceDao dao, DeviceAddressBookService addressBookService) {
|
||||||
|
// baseDao 由父类持有,子类内部赋给 this,测试类自己碰不到它
|
||||||
|
return new DeviceServiceImpl(
|
||||||
|
dao, mock(SysUserUtilService.class), mock(SysParamsService.class),
|
||||||
|
mock(RedisUtils.class), mock(OtaService.class), addressBookService) {
|
||||||
|
{
|
||||||
|
this.baseDao = dao;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceServiceImpl serviceWithDeviceDao(DeviceDao dao) {
|
||||||
|
return serviceWithDao(dao, mock(DeviceAddressBookService.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceDao daoReturning(DeviceEntity device) {
|
||||||
|
return daoReturning(List.of(device));
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceDao daoReturning(List<DeviceEntity> rows) {
|
||||||
|
DeviceDao dao = mock(DeviceDao.class);
|
||||||
|
when(dao.selectList(any())).thenReturn(rows);
|
||||||
|
return dao;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceEntity device(Long userId) {
|
||||||
|
return device(userId, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeviceEntity device(Long userId, String id) {
|
||||||
|
DeviceEntity entity = new DeviceEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setMacAddress(MAC);
|
||||||
|
entity.setUserId(userId);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserDetail user(long id) {
|
||||||
|
UserDetail user = new UserDetail();
|
||||||
|
user.setId(id);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
package xiaozhi.modules.model.service.impl;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import cn.hutool.json.JSONObject;
|
||||||
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
|
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||||
|
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||||
|
import xiaozhi.modules.model.service.ModelConfigService;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("dev")
|
||||||
|
@Transactional
|
||||||
|
class ModelConfigPersistenceTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ModelConfigService service;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JdbcTemplate jdbc;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RedisUtils redis;
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@CsvSource({"tts,TTS", "memory,Memory", "intent,Intent"})
|
||||||
|
void preservesRegisteredTypeWhenAddingAndEditing(String requestedType, String registeredType) {
|
||||||
|
String id = UUID.randomUUID().toString().replace("-", "");
|
||||||
|
String providerCode = "test-" + id;
|
||||||
|
jdbc.update("INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
id, registeredType, providerCode, "Persistence test provider", "[]");
|
||||||
|
|
||||||
|
ModelConfigBodyDTO body = new ModelConfigBodyDTO();
|
||||||
|
body.setId(id);
|
||||||
|
body.setModelCode(providerCode);
|
||||||
|
body.setModelName("Persistence test model");
|
||||||
|
body.setIsDefault(0);
|
||||||
|
body.setIsEnabled(1);
|
||||||
|
body.setSort(1);
|
||||||
|
body.setConfigJson(new JSONObject().set("type", providerCode));
|
||||||
|
|
||||||
|
ModelConfigDTO added = service.add(requestedType, providerCode, body);
|
||||||
|
assertEquals(registeredType, added.getModelType());
|
||||||
|
assertEquals(registeredType,
|
||||||
|
jdbc.queryForObject("SELECT model_type FROM ai_model_config WHERE id = ?", String.class, id));
|
||||||
|
|
||||||
|
String cacheKey = RedisKeys.getModelConfigById(id);
|
||||||
|
try {
|
||||||
|
redis.set(cacheKey, "cached model");
|
||||||
|
body.setModelName("Updated persistence test model");
|
||||||
|
ModelConfigDTO edited = service.edit(requestedType, providerCode, id, body);
|
||||||
|
|
||||||
|
assertEquals(registeredType, edited.getModelType());
|
||||||
|
assertEquals(registeredType,
|
||||||
|
jdbc.queryForObject("SELECT model_type FROM ai_model_config WHERE id = ?", String.class, id));
|
||||||
|
assertEquals(body.getModelName(),
|
||||||
|
jdbc.queryForObject("SELECT model_name FROM ai_model_config WHERE id = ?", String.class, id));
|
||||||
|
assertNull(redis.get(cacheKey));
|
||||||
|
} finally {
|
||||||
|
redis.delete(cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
package xiaozhi.modules.model.service.impl;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import xiaozhi.common.exception.ErrorCode;
|
||||||
|
import xiaozhi.common.exception.RenException;
|
||||||
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
|
import xiaozhi.common.utils.MessageUtils;
|
||||||
|
import xiaozhi.modules.agent.dao.AgentDao;
|
||||||
|
import xiaozhi.modules.model.dao.ModelConfigDao;
|
||||||
|
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||||
|
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||||
|
import xiaozhi.modules.model.dto.ModelProviderDTO;
|
||||||
|
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
||||||
|
import xiaozhi.modules.model.service.ModelProviderService;
|
||||||
|
|
||||||
|
class ModelConfigServiceImplTest {
|
||||||
|
|
||||||
|
private ModelConfigDao modelConfigDao;
|
||||||
|
private ModelProviderService modelProviderService;
|
||||||
|
private ModelConfigServiceImpl service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
modelConfigDao = mock(ModelConfigDao.class);
|
||||||
|
modelProviderService = mock(ModelProviderService.class);
|
||||||
|
service = new ModelConfigServiceImpl(
|
||||||
|
modelConfigDao, modelProviderService, mock(RedisUtils.class), mock(AgentDao.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@CsvSource({
|
||||||
|
"vad, VAD", "asr, ASR", "tts, TTS", "llm, LLM", "vllm, VLLM",
|
||||||
|
"memory, Memory", "intent, Intent", "rag, RAG", "LLM, LLM"
|
||||||
|
})
|
||||||
|
void addPreservesRegisteredProviderModelType(String requestedType, String registeredType) {
|
||||||
|
registerProvider(requestedType, registeredType);
|
||||||
|
|
||||||
|
ModelConfigDTO result = service.add(requestedType, "test-provider", modelBody());
|
||||||
|
|
||||||
|
ArgumentCaptor<ModelConfigEntity> saved = ArgumentCaptor.forClass(ModelConfigEntity.class);
|
||||||
|
verify(modelConfigDao).insert(saved.capture());
|
||||||
|
assertEquals(registeredType, saved.getValue().getModelType());
|
||||||
|
assertEquals(registeredType, result.getModelType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@CsvSource({
|
||||||
|
"vad, VAD", "asr, ASR", "tts, TTS", "llm, LLM", "vllm, VLLM",
|
||||||
|
"memory, Memory", "intent, Intent", "rag, RAG", "LLM, LLM"
|
||||||
|
})
|
||||||
|
void editPreservesRegisteredProviderModelType(String requestedType, String registeredType) {
|
||||||
|
registerProvider(requestedType, registeredType);
|
||||||
|
ModelConfigEntity original = new ModelConfigEntity();
|
||||||
|
original.setId("test-model");
|
||||||
|
original.setModelType(registeredType);
|
||||||
|
when(modelConfigDao.selectById("test-model")).thenReturn(original);
|
||||||
|
|
||||||
|
ModelConfigDTO result = service.edit(requestedType, "test-provider", "test-model", modelBody());
|
||||||
|
|
||||||
|
ArgumentCaptor<ModelConfigEntity> saved = ArgumentCaptor.forClass(ModelConfigEntity.class);
|
||||||
|
verify(modelConfigDao).updateById(saved.capture());
|
||||||
|
assertEquals(registeredType, saved.getValue().getModelType());
|
||||||
|
assertEquals(registeredType, result.getModelType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(booleans = {false, true})
|
||||||
|
void rejectsUnknownProviderBeforeWriting(boolean editing) {
|
||||||
|
when(modelProviderService.getList("tts", "missing")).thenReturn(List.of());
|
||||||
|
|
||||||
|
try (MockedStatic<MessageUtils> messages = mockStatic(MessageUtils.class)) {
|
||||||
|
messages.when(() -> MessageUtils.getMessage(ErrorCode.MODEL_PROVIDER_NOT_EXIST))
|
||||||
|
.thenReturn("Model provider does not exist");
|
||||||
|
RenException error = assertThrows(RenException.class, () -> {
|
||||||
|
if (editing) {
|
||||||
|
service.edit("tts", "missing", "test-model", modelBody());
|
||||||
|
} else {
|
||||||
|
service.add("tts", "missing", modelBody());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assertEquals(ErrorCode.MODEL_PROVIDER_NOT_EXIST, error.getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
verify(modelConfigDao, never()).insert(any(ModelConfigEntity.class));
|
||||||
|
verify(modelConfigDao, never()).updateById(any(ModelConfigEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void registerProvider(String requestedType, String registeredType) {
|
||||||
|
ModelProviderDTO provider = new ModelProviderDTO();
|
||||||
|
provider.setModelType(registeredType);
|
||||||
|
provider.setProviderCode("test-provider");
|
||||||
|
when(modelProviderService.getList(requestedType, "test-provider")).thenReturn(List.of(provider));
|
||||||
|
}
|
||||||
|
|
||||||
|
private ModelConfigBodyDTO modelBody() {
|
||||||
|
ModelConfigBodyDTO body = new ModelConfigBodyDTO();
|
||||||
|
body.setId("test-model");
|
||||||
|
body.setModelName("Test model");
|
||||||
|
body.setIsEnabled(1);
|
||||||
|
body.setSort(1);
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -265,7 +265,7 @@ function showAbout() {
|
|||||||
title: t('settings.aboutApp', { appName: import.meta.env.VITE_APP_TITLE }),
|
title: t('settings.aboutApp', { appName: import.meta.env.VITE_APP_TITLE }),
|
||||||
content: t('settings.aboutContent', {
|
content: t('settings.aboutContent', {
|
||||||
appName: import.meta.env.VITE_APP_TITLE,
|
appName: import.meta.env.VITE_APP_TITLE,
|
||||||
version: '0.9.7',
|
version: '0.9.8',
|
||||||
}),
|
}),
|
||||||
showCancel: false,
|
showCancel: false,
|
||||||
confirmText: t('common.confirm'),
|
confirmText: t('common.confirm'),
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import Fly from 'flyio/dist/npm/fly';
|
import Fly from 'flyio/dist/npm/fly';
|
||||||
import store from '../store/index';
|
import store from '../store/index';
|
||||||
import Constant from '../utils/constant';
|
import Constant from '../utils/constant';
|
||||||
|
import { getServiceUrl } from '../apis/api';
|
||||||
import { goToPage, isNotNull, showDanger, showWarning } from '../utils/index';
|
import { goToPage, isNotNull, showDanger, showWarning } from '../utils/index';
|
||||||
import i18n from '../i18n/index';
|
import i18n from '../i18n/index';
|
||||||
|
|
||||||
@@ -8,13 +9,98 @@ const fly = new Fly()
|
|||||||
// 设置超时
|
// 设置超时
|
||||||
fly.config.timeout = 30000
|
fly.config.timeout = 30000
|
||||||
|
|
||||||
|
// 独立 fly 实例给 silent refresh 用,避免任何回调链回到 sendRequest
|
||||||
|
const refreshFly = new Fly()
|
||||||
|
refreshFly.config.timeout = 30000
|
||||||
|
|
||||||
|
// silent refresh:剩 1h 触发换 token,单飞锁避免并发
|
||||||
|
const REFRESH_AHEAD_MS = 60 * 60 * 1000
|
||||||
|
let refreshPromise = null
|
||||||
|
|
||||||
|
function getTokenExpireAt() {
|
||||||
|
// 与 persistTokenExpireAt 同源读 localStorage(store 走的是 state.token 缓存,
|
||||||
|
// 刚写入 localStorage 后再走 store 拿不到补写的 _localStoredAt)
|
||||||
|
const raw = localStorage.getItem('token')
|
||||||
|
if (!raw) return 0
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
if (!parsed || !parsed.expire) return 0
|
||||||
|
// login.vue 写入 store 时是 setToken(now),token 对象里没有 createdAt;
|
||||||
|
// 用 _localStoredAt 作为本地落地时间基准
|
||||||
|
return (parsed._localStoredAt || 0) + parsed.expire * 1000
|
||||||
|
} catch (e) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 首次见到该 token 时记下落地时间;同步刷新 localStorage 与 store,保证两端一致
|
||||||
|
function persistTokenExpireAt() {
|
||||||
|
const raw = localStorage.getItem('token')
|
||||||
|
if (!raw) return
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
if (parsed && parsed.expire && !parsed._localStoredAt) {
|
||||||
|
parsed._localStoredAt = Date.now()
|
||||||
|
const next = JSON.stringify(parsed)
|
||||||
|
localStorage.setItem('token', next)
|
||||||
|
store.commit('setToken', next)
|
||||||
|
}
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function shouldRefresh() {
|
||||||
|
persistTokenExpireAt()
|
||||||
|
const exp = getTokenExpireAt()
|
||||||
|
if (!exp) return false
|
||||||
|
return exp - Date.now() < REFRESH_AHEAD_MS
|
||||||
|
}
|
||||||
|
|
||||||
|
function doRefresh() {
|
||||||
|
// 直接走 fly.request,绕过 sendRequest,避免死循环触发 silent refresh
|
||||||
|
const raw = localStorage.getItem('token')
|
||||||
|
if (!raw) return Promise.reject(new Error('no token'))
|
||||||
|
let bearer
|
||||||
|
try {
|
||||||
|
bearer = JSON.parse(raw).token
|
||||||
|
} catch (e) {
|
||||||
|
return Promise.reject(e)
|
||||||
|
}
|
||||||
|
return refreshFly.request(getServiceUrl() + '/user/refresh', {}, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: 'Bearer ' + bearer }
|
||||||
|
}).then((res) => {
|
||||||
|
const body = res && res.data
|
||||||
|
if (!body || (body.code !== 0 && body.code !== 'success')) {
|
||||||
|
throw new Error('refresh failed: ' + (body && body.msg))
|
||||||
|
}
|
||||||
|
const newDto = body.data
|
||||||
|
newDto._localStoredAt = Date.now()
|
||||||
|
store.commit('setToken', JSON.stringify(newDto))
|
||||||
|
return newDto
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerSilentRefresh() {
|
||||||
|
if (!refreshPromise) {
|
||||||
|
refreshPromise = doRefresh().catch((err) => {
|
||||||
|
store.commit('clearAuth')
|
||||||
|
goToPage(Constant.PAGE.LOGIN, true)
|
||||||
|
throw err
|
||||||
|
}).finally(() => {
|
||||||
|
refreshPromise = null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return refreshPromise
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request服务封装
|
* Request服务封装
|
||||||
*/
|
*/
|
||||||
export default {
|
export default {
|
||||||
sendRequest,
|
sendRequest,
|
||||||
reAjaxFun,
|
reAjaxFun,
|
||||||
clearRequestTime
|
clearRequestTime,
|
||||||
|
triggerSilentRefresh
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendRequest() {
|
function sendRequest() {
|
||||||
@@ -37,30 +123,41 @@ function sendRequest() {
|
|||||||
acceptLanguage = 'en-US';
|
acceptLanguage = 'en-US';
|
||||||
}
|
}
|
||||||
this._header['Accept-Language'] = acceptLanguage;
|
this._header['Accept-Language'] = acceptLanguage;
|
||||||
|
|
||||||
if (isNotNull(store.getters.getToken)) {
|
const doSend = () => {
|
||||||
this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token
|
if (isNotNull(store.getters.getToken)) {
|
||||||
|
this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打印请求信息
|
||||||
|
fly.request(this._url, this._data, {
|
||||||
|
method: this._method,
|
||||||
|
headers: this._header,
|
||||||
|
responseType: this._responseType
|
||||||
|
}).then((res) => {
|
||||||
|
const error = httpHandlerError(res, this._failCallback, this._networkFailCallback);
|
||||||
|
if (error) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._sucCallback) {
|
||||||
|
this._sucCallback(res)
|
||||||
|
}
|
||||||
|
}).catch((res) => {
|
||||||
|
// 打印失败响应
|
||||||
|
console.log('catch', res)
|
||||||
|
httpHandlerError(res, this._failCallback, this._networkFailCallback)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 打印请求信息
|
// 剩 1h 内过期就先 silent refresh 再发,确保请求带新 token
|
||||||
fly.request(this._url, this._data, {
|
if (shouldRefresh()) {
|
||||||
method: this._method,
|
triggerSilentRefresh().then(doSend).catch(() => {
|
||||||
headers: this._header,
|
// 触发 refresh 后被拦截跳登录,这里什么都不用做
|
||||||
responseType: this._responseType
|
})
|
||||||
}).then((res) => {
|
} else {
|
||||||
const error = httpHandlerError(res, this._failCallback, this._networkFailCallback);
|
doSend()
|
||||||
if (error) {
|
}
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._sucCallback) {
|
|
||||||
this._sucCallback(res)
|
|
||||||
}
|
|
||||||
}).catch((res) => {
|
|
||||||
// 打印失败响应
|
|
||||||
console.log('catch', res)
|
|
||||||
httpHandlerError(res, this._failCallback, this._networkFailCallback)
|
|
||||||
})
|
|
||||||
return this
|
return this
|
||||||
},
|
},
|
||||||
'success'(callback) {
|
'success'(callback) {
|
||||||
|
|||||||
@@ -77,7 +77,10 @@
|
|||||||
<el-form :model="formData.configJson" label-width="auto" label-position="left" class="custom-form">
|
<el-form :model="formData.configJson" label-width="auto" label-position="left" class="custom-form">
|
||||||
<div v-for="(row, rowIndex) in chunkedCallInfoFields" :key="rowIndex" class="form-row">
|
<div v-for="(row, rowIndex) in chunkedCallInfoFields" :key="rowIndex" class="form-row">
|
||||||
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop" style="flex: 1;">
|
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop" style="flex: 1;">
|
||||||
<el-input v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
|
<el-input v-if="field.type === 'json-textarea'" v-model="formData.configJson[field.prop]" type="textarea"
|
||||||
|
:rows="3" :placeholder="field.placeholder" class="custom-input-bg">
|
||||||
|
</el-input>
|
||||||
|
<el-input v-else v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
|
||||||
:type="field.type || 'text'" class="custom-input-bg" :show-password="field.type === 'password'">
|
:type="field.type || 'text'" class="custom-input-bg" :show-password="field.type === 'password'">
|
||||||
</el-input>
|
</el-input>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
@@ -161,7 +164,7 @@ export default {
|
|||||||
fields: JSON.parse(item.fields || '[]').map(f => ({
|
fields: JSON.parse(item.fields || '[]').map(f => ({
|
||||||
label: f.label,
|
label: f.label,
|
||||||
prop: f.key,
|
prop: f.key,
|
||||||
type: f.type === 'password' ? 'password' : 'text',
|
type: f.type === 'dict' ? 'json-textarea' : f.type === 'password' ? 'password' : 'text',
|
||||||
placeholder: `请输入${f.key}`
|
placeholder: `请输入${f.key}`
|
||||||
}))
|
}))
|
||||||
}))
|
}))
|
||||||
@@ -204,6 +207,24 @@ export default {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dict 字段必须解析为 JSON 对象再提交,否则会以字符串入库
|
||||||
|
for (const field of this.providerFields) {
|
||||||
|
if (field.type !== 'json-textarea') continue;
|
||||||
|
const raw = this.formData.configJson[field.prop];
|
||||||
|
if (!raw || typeof raw === 'object') continue;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||||
|
throw new Error('not object');
|
||||||
|
}
|
||||||
|
this.formData.configJson[field.prop] = parsed;
|
||||||
|
} catch (e) {
|
||||||
|
this.$message.error('必须输入字典格式(如 {"key":"value"})');
|
||||||
|
this.saving = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const submitData = {
|
const submitData = {
|
||||||
id: this.formData.id || '',
|
id: this.formData.id || '',
|
||||||
modelName: this.formData.modelName || '',
|
modelName: this.formData.modelName || '',
|
||||||
|
|||||||
@@ -330,6 +330,17 @@ export default {
|
|||||||
if (!configJson.hasOwnProperty(field.prop)) {
|
if (!configJson.hasOwnProperty(field.prop)) {
|
||||||
configJson[field.prop] = "";
|
configJson[field.prop] = "";
|
||||||
} else if (field.type === "json-textarea") {
|
} else if (field.type === "json-textarea") {
|
||||||
|
// 兼容已保存为 JSON 字符串的字典,避免再次序列化后无法编辑。
|
||||||
|
if (typeof configJson[field.prop] === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(configJson[field.prop]);
|
||||||
|
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||||
|
configJson[field.prop] = parsed;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 保留非法值的显示,由现有校验提示用户修正。
|
||||||
|
}
|
||||||
|
}
|
||||||
this.$set(
|
this.$set(
|
||||||
this.fieldJsonMap,
|
this.fieldJsonMap,
|
||||||
field.prop,
|
field.prop,
|
||||||
|
|||||||
@@ -22,6 +22,13 @@ Vue.config.productionTip = false
|
|||||||
// 注册Service Worker
|
// 注册Service Worker
|
||||||
registerServiceWorker();
|
registerServiceWorker();
|
||||||
|
|
||||||
|
// 应用启动时把 localStorage 里的 token 同步进 store,避免守卫放行后首次请求时
|
||||||
|
// httpRequest 读到 state.token=null 而漏带 Authorization 头触发 401 跳登录
|
||||||
|
const cachedToken = localStorage.getItem('token')
|
||||||
|
if (cachedToken) {
|
||||||
|
store.commit('setToken', cachedToken)
|
||||||
|
}
|
||||||
|
|
||||||
// 创建Vue实例
|
// 创建Vue实例
|
||||||
new Vue({
|
new Vue({
|
||||||
router,
|
router,
|
||||||
|
|||||||
@@ -613,6 +613,8 @@ export default {
|
|||||||
.nav-panel {
|
.nav-panel {
|
||||||
min-width: 242px;
|
min-width: 242px;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
overflow-y: auto;
|
||||||
border-right: 1px solid #ebeef5;
|
border-right: 1px solid #ebeef5;
|
||||||
background: linear-gradient(
|
background: linear-gradient(
|
||||||
120deg,
|
120deg,
|
||||||
@@ -629,6 +631,7 @@ export default {
|
|||||||
|
|
||||||
.nav-panel .el-menu-item {
|
.nav-panel .el-menu-item {
|
||||||
height: 50px;
|
height: 50px;
|
||||||
|
flex-shrink: 0;
|
||||||
background: #e9f0ff;
|
background: #e9f0ff;
|
||||||
line-height: 50px;
|
line-height: 50px;
|
||||||
border-radius: 4px 0 0 4px !important;
|
border-radius: 4px 0 0 4px !important;
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ const functionDialogSource = await readFile(
|
|||||||
new URL('../src/components/FunctionDialog.vue', import.meta.url),
|
new URL('../src/components/FunctionDialog.vue', import.meta.url),
|
||||||
'utf8',
|
'utf8',
|
||||||
);
|
);
|
||||||
|
const modelConfigSource = await readFile(
|
||||||
|
new URL('../src/views/ModelConfig.vue', import.meta.url),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
|
||||||
test('address-book permission state consistently uses the target device MAC', () => {
|
test('address-book permission state consistently uses the target device MAC', () => {
|
||||||
assert.match(
|
assert.match(
|
||||||
@@ -66,6 +70,74 @@ test('correct-word pagination maps the UI page size to the backend limit query',
|
|||||||
assert.doesNotMatch(correctWordApiSource, /pageSize: params\.pageSize/);
|
assert.doesNotMatch(correctWordApiSource, /pageSize: params\.pageSize/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('model navigation keeps its scrollable layout declarations', () => {
|
||||||
|
const navStyles = modelConfigSource.match(/\.nav-panel\s*\{([^}]*)\}/)?.[1];
|
||||||
|
const itemStyles = modelConfigSource.match(
|
||||||
|
/\.nav-panel\s+\.el-menu-item\s*\{([^}]*)\}/,
|
||||||
|
)?.[1];
|
||||||
|
|
||||||
|
assert.ok(navStyles, 'model navigation should define its layout');
|
||||||
|
assert.ok(itemStyles, 'model menu items should define their layout');
|
||||||
|
const wrapperStyles = modelConfigSource.match(/\.main-wrapper\s*\{([^}]*)\}/)?.[1];
|
||||||
|
assert.ok(wrapperStyles, 'model page wrapper should define its height');
|
||||||
|
|
||||||
|
assert.match(navStyles, /box-sizing:\s*border-box;/);
|
||||||
|
assert.match(navStyles, /overflow-y:\s*auto;/);
|
||||||
|
assert.match(navStyles, /display:\s*flex;/);
|
||||||
|
assert.match(navStyles, /flex-direction:\s*column;/);
|
||||||
|
assert.match(itemStyles, /flex-shrink:\s*0;/);
|
||||||
|
assert.match(wrapperStyles, /height:\s*calc\([^)]*vh[^)]*\)/);
|
||||||
|
|
||||||
|
// 断言只取第一条同名规则,后面再补一条就能盖掉上面三条,必须挡住
|
||||||
|
assert.equal(
|
||||||
|
(modelConfigSource.match(/\.nav-panel\s*\{/g) || []).length,
|
||||||
|
1,
|
||||||
|
'model navigation should keep a single rule',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
(modelConfigSource.match(/\.nav-panel\s+\.el-menu-item\s*\{/g) || []).length,
|
||||||
|
1,
|
||||||
|
'model menu items should keep a single rule',
|
||||||
|
);
|
||||||
|
// 复合选择器特异性更高,能直接盖掉可滚属性
|
||||||
|
assert.equal(
|
||||||
|
(modelConfigSource.match(/\.nav-panel[.:\[#][^{}]*\{/g) || []).length,
|
||||||
|
0,
|
||||||
|
'model navigation should not use composite selectors',
|
||||||
|
);
|
||||||
|
|
||||||
|
const styleSource = modelConfigSource.match(/<style[^>]*>([\s\S]*?)<\/style>/)?.[1];
|
||||||
|
assert.ok(styleSource, 'model config should define its styles');
|
||||||
|
const ruleSelectors = styleSource
|
||||||
|
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||||
|
.replace(/\/\/[^\n]*/g, '')
|
||||||
|
.split('}')
|
||||||
|
.map((chunk) => {
|
||||||
|
const open = chunk.indexOf('{');
|
||||||
|
return open < 0 ? null : chunk.slice(0, open).trim();
|
||||||
|
})
|
||||||
|
.filter((selector) => selector && !selector.startsWith('@'));
|
||||||
|
|
||||||
|
// 上面几条挡不住带伪类的后代选择器(.nav-panel .el-menu-item:hover),
|
||||||
|
// 它特异性一样更高,照样能盖掉可滚属性,所以把 nav 相关的选择器逐条列出来核对
|
||||||
|
assert.deepEqual(
|
||||||
|
ruleSelectors.filter((selector) => selector.includes('.nav-panel')).sort(),
|
||||||
|
[
|
||||||
|
'.nav-panel',
|
||||||
|
'.nav-panel .el-menu-item',
|
||||||
|
'.nav-panel .el-menu-item.is-active',
|
||||||
|
'.nav-panel .el-menu-item.is-active::before',
|
||||||
|
'::v-deep .nav-panel .el-menu-item.is-active .menu-text',
|
||||||
|
].sort(),
|
||||||
|
'model navigation should keep its declared rules',
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
ruleSelectors.filter((selector) => selector.includes('.main-wrapper')),
|
||||||
|
['.main-wrapper'],
|
||||||
|
'model page wrapper should keep a single rule',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test('function dialog footer stays above the expanding MCP tools section', () => {
|
test('function dialog footer stays above the expanding MCP tools section', () => {
|
||||||
const mcpLayer = functionDialogSource.match(
|
const mcpLayer = functionDialogSource.match(
|
||||||
/\.mcp-access-point\s*\{[^}]*z-index:\s*(\d+);/s,
|
/\.mcp-access-point\s*\{[^}]*z-index:\s*(\d+);/s,
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import Vue from 'vue';
|
||||||
|
import { parseComponent } from 'vue-template-compiler';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import source from '../src/components/AddModelDialog.vue?raw';
|
||||||
|
|
||||||
|
// The unit-test runner has no Vue SFC plugin. Load the real component's script
|
||||||
|
// with its API and dialog dependencies stubbed; keep Vue's reactivity.
|
||||||
|
const script = parseComponent(source).script.content
|
||||||
|
.replace(/^import .*;$/gm, '')
|
||||||
|
.replace('export default', 'return');
|
||||||
|
const component = new Function('CustomDialog', 'Api', script)({}, {});
|
||||||
|
|
||||||
|
function makeVm() {
|
||||||
|
const vm = new Vue({
|
||||||
|
...component,
|
||||||
|
propsData: { visible: false, modelType: 'TTS' },
|
||||||
|
});
|
||||||
|
vm.$message = { error: vi.fn() };
|
||||||
|
vm.$t = (key) => key;
|
||||||
|
vm.providerFields = [
|
||||||
|
{ label: '音量', prop: 'volume', type: 'json-textarea', placeholder: '请输入volume' },
|
||||||
|
{ label: '密钥', prop: 'api_key', type: 'password', placeholder: '请输入api_key' },
|
||||||
|
];
|
||||||
|
vm.formData.supplier = 'test-provider';
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitted(vm) {
|
||||||
|
let captured;
|
||||||
|
vm.$on('confirm', (data) => {
|
||||||
|
captured = data;
|
||||||
|
});
|
||||||
|
vm.confirm();
|
||||||
|
return captured;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('add dialog dict fields', () => {
|
||||||
|
it('parses valid JSON dict input into an object before submit', () => {
|
||||||
|
const vm = makeVm();
|
||||||
|
vm.formData.configJson = { volume: '{"speed":1,"volume":10}', api_key: 'sk-xxx' };
|
||||||
|
|
||||||
|
const data = submitted(vm);
|
||||||
|
|
||||||
|
expect(data.configJson.volume).toEqual({ speed: 1, volume: 10 });
|
||||||
|
expect(data.configJson.api_key).toBe('sk-xxx');
|
||||||
|
expect(vm.$message.error).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('blocks invalid JSON input and does not emit confirm', () => {
|
||||||
|
const vm = makeVm();
|
||||||
|
vm.formData.configJson = { volume: '{bad json', api_key: 'sk-xxx' };
|
||||||
|
|
||||||
|
expect(submitted(vm)).toBeUndefined();
|
||||||
|
expect(vm.$message.error).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['[1,2]', 'null', '"text"', '1'])(
|
||||||
|
'blocks non-object JSON %s',
|
||||||
|
(value) => {
|
||||||
|
const vm = makeVm();
|
||||||
|
vm.formData.configJson = { volume: value, api_key: 'sk-xxx' };
|
||||||
|
|
||||||
|
expect(submitted(vm)).toBeUndefined();
|
||||||
|
expect(vm.$message.error).toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('leaves empty strings and existing object values untouched', () => {
|
||||||
|
const vm = makeVm();
|
||||||
|
const obj = { speed: 2 };
|
||||||
|
vm.formData.configJson = { volume: obj, api_key: '' };
|
||||||
|
|
||||||
|
const data = submitted(vm);
|
||||||
|
|
||||||
|
expect(data.configJson.volume).toBe(obj);
|
||||||
|
expect(data.configJson.api_key).toBe('');
|
||||||
|
expect(vm.$message.error).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import Vue from 'vue';
|
||||||
|
import { parseComponent } from 'vue-template-compiler';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import source from '../src/components/ModelEditDialog.vue?raw';
|
||||||
|
|
||||||
|
// The unit-test runner has no Vue SFC plugin. Load the real component's script
|
||||||
|
// with its API and child-dialog dependencies stubbed; keep Vue's reactivity.
|
||||||
|
const script = parseComponent(source).script.content
|
||||||
|
.replace(/^import .*;$/gm, '')
|
||||||
|
.replace('export default', 'return');
|
||||||
|
const component = new Function('CustomDialog', 'Api', script)({}, {});
|
||||||
|
|
||||||
|
let vm;
|
||||||
|
let saved;
|
||||||
|
|
||||||
|
function openModel(value) {
|
||||||
|
vm.processModelData({
|
||||||
|
id: 'test-model',
|
||||||
|
modelName: 'Test model',
|
||||||
|
configJson: { type: 'test-provider', prosody: value },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vm = new Vue({
|
||||||
|
...component,
|
||||||
|
propsData: { modelType: 'TTS', modelData: { id: 'test-model' } },
|
||||||
|
});
|
||||||
|
vm.$message = { error: vi.fn() };
|
||||||
|
vm.dynamicCallInfoFields = [{ prop: 'prosody', type: 'json-textarea' }];
|
||||||
|
saved = vi.fn();
|
||||||
|
vm.$on('save', saved);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vm.$destroy();
|
||||||
|
vi.clearAllTimers();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('stored dictionary fields', () => {
|
||||||
|
it('opens a JSON string as an editable dictionary instead of a quoted string', () => {
|
||||||
|
openModel('{"speed":1,"volume":10}');
|
||||||
|
|
||||||
|
expect(JSON.parse(vm.fieldJsonMap.prosody)).toEqual({ speed: 1, volume: 10 });
|
||||||
|
expect(vm.form.configJson.prosody).toEqual({ speed: 1, volume: 10 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves a stored JSON string when saving without changes', () => {
|
||||||
|
openModel('{"speed":1,"volume":10}');
|
||||||
|
vm.handleSave();
|
||||||
|
|
||||||
|
expect(vm.$message.error).not.toHaveBeenCalled();
|
||||||
|
expect(saved.mock.calls[0][0].formData.configJson.prosody).toEqual({
|
||||||
|
speed: 1,
|
||||||
|
volume: 10,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps edits after saving and reopening the returned object', () => {
|
||||||
|
openModel('{"speed":1,"volume":10}');
|
||||||
|
vm.fieldJsonMap.prosody = '{"speed":2,"volume":5}';
|
||||||
|
vm.handleSave();
|
||||||
|
const config = saved.mock.calls[0][0].formData.configJson;
|
||||||
|
|
||||||
|
vm.resetForm();
|
||||||
|
openModel(JSON.parse(JSON.stringify(config.prosody)));
|
||||||
|
vm.handleSave();
|
||||||
|
|
||||||
|
expect(JSON.parse(vm.fieldJsonMap.prosody)).toEqual({ speed: 2, volume: 5 });
|
||||||
|
expect(saved.mock.calls[1][0].formData.configJson.prosody).toEqual({
|
||||||
|
speed: 2,
|
||||||
|
volume: 5,
|
||||||
|
});
|
||||||
|
expect(vm.$message.error).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves nested values and masked secrets in existing dictionary objects', () => {
|
||||||
|
const value = { speed: 0, enabled: false, nested: { api_key: 'ab****yz' }, tags: ['a'] };
|
||||||
|
openModel(value);
|
||||||
|
vm.handleSave();
|
||||||
|
|
||||||
|
expect(saved.mock.calls[0][0].formData.configJson.prosody).toEqual(value);
|
||||||
|
expect(vm.$message.error).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['not json', 'null', '[]', '1', 'true', '"text"'])(
|
||||||
|
'does not reinterpret %s as a dictionary',
|
||||||
|
(value) => {
|
||||||
|
openModel(value);
|
||||||
|
|
||||||
|
expect(JSON.parse(vm.fieldJsonMap.prosody)).toBe(value);
|
||||||
|
expect(vm.validateJson(vm.fieldJsonMap.prosody)).toBeNull();
|
||||||
|
expect(vm.$message.error).toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -6,7 +6,7 @@ from config.config_loader import load_config
|
|||||||
from config.settings import check_config_file
|
from config.settings import check_config_file
|
||||||
from core.utils.cache.manager import cache_manager, CacheType
|
from core.utils.cache.manager import cache_manager, CacheType
|
||||||
|
|
||||||
SERVER_VERSION = "0.9.7"
|
SERVER_VERSION = "0.9.8"
|
||||||
_logger_initialized = False
|
_logger_initialized = False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from core.connection import ConnectionHandler
|
from core.connection import ConnectionHandler
|
||||||
from core.utils.dialogue import Message
|
from core.utils.dialogue import Message
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data, audio_file_to_wav_bytes
|
||||||
from core.providers.tts.dto.dto import SentenceType
|
from core.providers.tts.dto.dto import SentenceType
|
||||||
from core.utils.wakeup_word import WakeupWordsConfig
|
from core.utils.wakeup_word import WakeupWordsConfig
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
|
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
|
||||||
@@ -148,8 +148,13 @@ async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
|||||||
# 获取当前音色
|
# 获取当前音色
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
voice = getattr(conn.tts, "voice", "default")
|
||||||
|
|
||||||
# 使用链接的sample_rate
|
# 保留的 TTS 音频是文件路径而非 Opus 帧:直接转目标采样率 wav,跳过有损 Opus 往返
|
||||||
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=conn.sample_rate)
|
if isinstance(tts_result, str):
|
||||||
|
wav_bytes = await asyncio.to_thread(
|
||||||
|
audio_file_to_wav_bytes, tts_result, conn.sample_rate
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=conn.sample_rate)
|
||||||
file_path = wakeup_words_config.generate_file_path(voice)
|
file_path = wakeup_words_config.generate_file_path(voice)
|
||||||
with open(file_path, "wb") as f:
|
with open(file_path, "wb") as f:
|
||||||
f.write(wav_bytes)
|
f.write(wav_bytes)
|
||||||
|
|||||||
@@ -17,7 +17,11 @@ class MCPClient:
|
|||||||
self.name_mapping = {}
|
self.name_mapping = {}
|
||||||
self.ready = False
|
self.ready = False
|
||||||
self.call_results = {} # To store Futures for tool call responses
|
self.call_results = {} # To store Futures for tool call responses
|
||||||
self.next_id = 1
|
# Handshake hardcodes id=1 (initialize) and id=2 (tools/list) in mcp_handler.
|
||||||
|
# JSON-RPC 2.0 forbids reusing request ids on the same connection, and
|
||||||
|
# compliant device MCP servers reject tools/call with id 1/2 (see #3461).
|
||||||
|
# Official protocol sequence expects the first tools/call to use id=3.
|
||||||
|
self.next_id = 3
|
||||||
self.lock = asyncio.Lock()
|
self.lock = asyncio.Lock()
|
||||||
self._cached_available_tools = None # Cache for get_available_tools
|
self._cached_available_tools = None # Cache for get_available_tools
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,10 @@
|
|||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
import re
|
import re
|
||||||
from concurrent.futures import Future
|
from core.utils.util import get_vision_url
|
||||||
from core.utils.util import get_vision_url, sanitize_tool_name
|
|
||||||
from core.utils.auth import AuthToken
|
from core.utils.auth import AuthToken
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from .mcp_client import MCPClient
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@@ -15,91 +15,6 @@ if TYPE_CHECKING:
|
|||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class MCPClient:
|
|
||||||
"""设备端MCP客户端,用于管理MCP状态和工具"""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.tools = {} # sanitized_name -> tool_data
|
|
||||||
self.name_mapping = {}
|
|
||||||
self.ready = False
|
|
||||||
self.call_results = {} # To store Futures for tool call responses
|
|
||||||
self.next_id = 1
|
|
||||||
self.lock = asyncio.Lock()
|
|
||||||
self._cached_available_tools = None # Cache for get_available_tools
|
|
||||||
|
|
||||||
def has_tool(self, name: str) -> bool:
|
|
||||||
return name in self.tools
|
|
||||||
|
|
||||||
def get_available_tools(self) -> list:
|
|
||||||
# Check if the cache is valid
|
|
||||||
if self._cached_available_tools is not None:
|
|
||||||
return self._cached_available_tools
|
|
||||||
|
|
||||||
# If cache is not valid, regenerate the list
|
|
||||||
result = []
|
|
||||||
for tool_name, tool_data in self.tools.items():
|
|
||||||
function_def = {
|
|
||||||
"name": tool_name,
|
|
||||||
"description": tool_data["description"],
|
|
||||||
"parameters": {
|
|
||||||
"type": tool_data["inputSchema"].get("type", "object"),
|
|
||||||
"properties": tool_data["inputSchema"].get("properties", {}),
|
|
||||||
"required": tool_data["inputSchema"].get("required", []),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
result.append({"type": "function", "function": function_def})
|
|
||||||
|
|
||||||
self._cached_available_tools = result # Store the generated list in cache
|
|
||||||
return result
|
|
||||||
|
|
||||||
async def is_ready(self) -> bool:
|
|
||||||
async with self.lock:
|
|
||||||
return self.ready
|
|
||||||
|
|
||||||
async def set_ready(self, status: bool):
|
|
||||||
async with self.lock:
|
|
||||||
self.ready = status
|
|
||||||
|
|
||||||
async def add_tool(self, tool_data: dict):
|
|
||||||
async with self.lock:
|
|
||||||
sanitized_name = sanitize_tool_name(tool_data["name"])
|
|
||||||
self.tools[sanitized_name] = tool_data
|
|
||||||
self.name_mapping[sanitized_name] = tool_data["name"]
|
|
||||||
self._cached_available_tools = (
|
|
||||||
None # Invalidate the cache when a tool is added
|
|
||||||
)
|
|
||||||
|
|
||||||
async def get_next_id(self) -> int:
|
|
||||||
async with self.lock:
|
|
||||||
current_id = self.next_id
|
|
||||||
self.next_id += 1
|
|
||||||
return current_id
|
|
||||||
|
|
||||||
async def register_call_result_future(self, id: int, future: Future):
|
|
||||||
async with self.lock:
|
|
||||||
self.call_results[id] = future
|
|
||||||
|
|
||||||
async def resolve_call_result(self, id: int, result: any):
|
|
||||||
async with self.lock:
|
|
||||||
if id in self.call_results:
|
|
||||||
future = self.call_results.pop(id)
|
|
||||||
if not future.done():
|
|
||||||
future.set_result(result)
|
|
||||||
|
|
||||||
async def reject_call_result(self, id: int, exception: Exception):
|
|
||||||
async with self.lock:
|
|
||||||
if id in self.call_results:
|
|
||||||
future = self.call_results.pop(id)
|
|
||||||
if not future.done():
|
|
||||||
future.set_exception(exception)
|
|
||||||
|
|
||||||
async def cleanup_call_result(self, id: int):
|
|
||||||
async with self.lock:
|
|
||||||
if id in self.call_results:
|
|
||||||
self.call_results.pop(id)
|
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_message(conn: "ConnectionHandler", payload: dict):
|
async def send_mcp_message(conn: "ConnectionHandler", payload: dict):
|
||||||
"""Helper to send MCP messages, encapsulating common logic."""
|
"""Helper to send MCP messages, encapsulating common logic."""
|
||||||
if not conn.features.get("mcp"):
|
if not conn.features.get("mcp"):
|
||||||
|
|||||||
@@ -18,7 +18,9 @@ class MCPEndpointClient:
|
|||||||
self.name_mapping = {}
|
self.name_mapping = {}
|
||||||
self.ready = False
|
self.ready = False
|
||||||
self.call_results = {} # To store Futures for tool call responses
|
self.call_results = {} # To store Futures for tool call responses
|
||||||
self.next_id = 1
|
# Handshake hardcodes id=1 (initialize) and id=2 (tools/list) in
|
||||||
|
# mcp_endpoint_handler; tools/call must start at 3 to avoid id reuse.
|
||||||
|
self.next_id = 3
|
||||||
self.lock = asyncio.Lock()
|
self.lock = asyncio.Lock()
|
||||||
self._cached_available_tools = None # Cache for get_available_tools
|
self._cached_available_tools = None # Cache for get_available_tools
|
||||||
self.websocket = None # WebSocket连接
|
self.websocket = None # WebSocket连接
|
||||||
|
|||||||
@@ -10,12 +10,13 @@ import concurrent.futures
|
|||||||
from contextlib import AsyncExitStack
|
from contextlib import AsyncExitStack
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional, List, Dict, Any
|
||||||
|
|
||||||
|
import httpx2
|
||||||
from mcp import ClientSession, StdioServerParameters, Implementation
|
from mcp import ClientSession, StdioServerParameters, Implementation
|
||||||
from mcp.client.session import SamplingFnT, ElicitationFnT, ListRootsFnT, LoggingFnT, MessageHandlerFnT
|
from mcp.client.session import SamplingFnT, ElicitationFnT, ListRootsFnT, LoggingFnT, MessageHandlerFnT
|
||||||
from mcp.client.stdio import stdio_client
|
from mcp.client.stdio import stdio_client
|
||||||
from mcp.client.sse import sse_client
|
from mcp.client.sse import sse_client
|
||||||
from mcp.client.streamable_http import streamablehttp_client
|
from mcp.client.streamable_http import streamable_http_client
|
||||||
from mcp.shared.session import ProgressFnT
|
from mcp.shared.dispatcher import ProgressFnT # mcp 2.x:从 mcp.shared.session 移来
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.utils.util import sanitize_tool_name
|
from core.utils.util import sanitize_tool_name
|
||||||
@@ -203,13 +204,21 @@ class ServerMCPClient:
|
|||||||
|
|
||||||
if transport_type == "streamable-http" or transport_type == "http":
|
if transport_type == "streamable-http" or transport_type == "http":
|
||||||
# 使用 Streamable HTTP 传输
|
# 使用 Streamable HTTP 传输
|
||||||
http_r, http_w, get_session_id = await stack.enter_async_context(
|
# mcp 2.x:headers/timeout 改由 http_client 承载,产出从 3 元组变为 2 元组
|
||||||
streamablehttp_client(
|
http_client = httpx2.AsyncClient(
|
||||||
|
headers=headers,
|
||||||
|
timeout=httpx2.Timeout(
|
||||||
|
self.config.get("timeout", 30),
|
||||||
|
read=self.config.get("sse_read_timeout", 60 * 5),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
stack.push_async_callback(http_client.aclose)
|
||||||
|
|
||||||
|
http_r, http_w = await stack.enter_async_context(
|
||||||
|
streamable_http_client(
|
||||||
url=self.config["url"],
|
url=self.config["url"],
|
||||||
headers=headers,
|
http_client=http_client,
|
||||||
timeout=self.config.get("timeout", 30),
|
terminate_on_close=self.config.get("terminate_on_close", True),
|
||||||
sse_read_timeout=self.config.get("sse_read_timeout", 60 * 5),
|
|
||||||
terminate_on_close=self.config.get("terminate_on_close", True)
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
read_stream, write_stream = http_r, http_w
|
read_stream, write_stream = http_r, http_w
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ class TTSProvider(TTSProviderBase):
|
|||||||
self.ws = None
|
self.ws = None
|
||||||
self.interface_type = InterfaceType.DUAL_STREAM
|
self.interface_type = InterfaceType.DUAL_STREAM
|
||||||
self._monitor_task = None # 监听任务引用
|
self._monitor_task = None # 监听任务引用
|
||||||
|
self._pending_prefix = ""
|
||||||
self.appId = config.get("appid")
|
self.appId = config.get("appid")
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
self.cluster = config.get("cluster")
|
self.cluster = config.get("cluster")
|
||||||
@@ -306,6 +307,9 @@ class TTSProvider(TTSProviderBase):
|
|||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
# 重置流式处理状态
|
# 重置流式处理状态
|
||||||
self.reset_stream_state()
|
self.reset_stream_state()
|
||||||
|
# 重置 opus 流式编码器跨轮残留
|
||||||
|
if hasattr(self, "opus_encoder") and self.opus_encoder:
|
||||||
|
self.opus_encoder.reset_state()
|
||||||
# 初始化参数
|
# 初始化参数
|
||||||
try:
|
try:
|
||||||
if not getattr(self.conn, "sentence_id", None):
|
if not getattr(self.conn, "sentence_id", None):
|
||||||
@@ -433,6 +437,9 @@ class TTSProvider(TTSProviderBase):
|
|||||||
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
|
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
|
||||||
try:
|
try:
|
||||||
if self.ws:
|
if self.ws:
|
||||||
|
# 句尾替换词滑动窗口残留先发出去
|
||||||
|
if self._pending_prefix:
|
||||||
|
await self.text_to_speak(self._pending_prefix, None)
|
||||||
header = Header(
|
header = Header(
|
||||||
message_type=FULL_CLIENT_REQUEST,
|
message_type=FULL_CLIENT_REQUEST,
|
||||||
message_type_specific_flags=MsgTypeFlagWithEvent,
|
message_type_specific_flags=MsgTypeFlagWithEvent,
|
||||||
@@ -490,7 +497,6 @@ class TTSProvider(TTSProviderBase):
|
|||||||
try:
|
try:
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
# 确保 `recv()` 运行在同一个 event loop
|
|
||||||
msg = await self.ws.recv()
|
msg = await self.ws.recv()
|
||||||
res = self.parser_response(msg)
|
res = self.parser_response(msg)
|
||||||
self.print_response(res, "send_text res:")
|
self.print_response(res, "send_text res:")
|
||||||
@@ -500,17 +506,18 @@ class TTSProvider(TTSProviderBase):
|
|||||||
logger.bind(tag=TAG).debug(f"链接关闭成功~~")
|
logger.bind(tag=TAG).debug(f"链接关闭成功~~")
|
||||||
break
|
break
|
||||||
|
|
||||||
# 只处理当前活跃会话的响应
|
# 只处理当前活跃会话的响应;旧会话事件不影响当前 activate_session
|
||||||
if res.optional.sessionId and self.conn.sentence_id != res.optional.sessionId:
|
if res.optional.sessionId and self.conn.sentence_id != res.optional.sessionId:
|
||||||
# 如果是会话结束相关事件,即使会话ID不匹配也要重置状态
|
|
||||||
if res.optional.event in [EVENT_SessionCanceled, EVENT_SessionFailed, EVENT_SessionFinished]:
|
|
||||||
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
|
|
||||||
self.activate_session = False
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if res.optional.event == EVENT_SessionCanceled:
|
if res.optional.event == EVENT_SessionCanceled:
|
||||||
logger.bind(tag=TAG).debug(f"释放服务端资源成功~~")
|
logger.bind(tag=TAG).debug(f"释放服务端资源成功~~")
|
||||||
self.activate_session = False
|
self.activate_session = False
|
||||||
|
elif res.optional.event == EVENT_SessionFailed:
|
||||||
|
logger.bind(tag=TAG).error(
|
||||||
|
f"TTS 会话被服务端拒绝: {self.conn.sentence_id}"
|
||||||
|
)
|
||||||
|
self.activate_session = False
|
||||||
elif not self.resource_type and res.optional.event == EVENT_TTSSentenceStart:
|
elif not self.resource_type and res.optional.event == EVENT_TTSSentenceStart:
|
||||||
json_data = json.loads(res.payload.decode("utf-8"))
|
json_data = json.loads(res.payload.decode("utf-8"))
|
||||||
self.tts_text = json_data.get("text", "")
|
self.tts_text = json_data.get("text", "")
|
||||||
@@ -538,6 +545,11 @@ class TTSProvider(TTSProviderBase):
|
|||||||
logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}")
|
logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}")
|
||||||
elif res.optional.event == EVENT_SessionFinished:
|
elif res.optional.event == EVENT_SessionFinished:
|
||||||
logger.bind(tag=TAG).debug(f"会话结束~~")
|
logger.bind(tag=TAG).debug(f"会话结束~~")
|
||||||
|
# 句尾冲刷流式 opus 编码器不足一帧的 PCM 残量
|
||||||
|
if hasattr(self, "opus_encoder") and self.opus_encoder:
|
||||||
|
self.wav_to_opus_data_audio_raw_stream(
|
||||||
|
b"", is_end=True, callback=self.handle_opus
|
||||||
|
)
|
||||||
self.activate_session = False
|
self.activate_session = False
|
||||||
self._process_before_stop_play_files()
|
self._process_before_stop_play_files()
|
||||||
# 非复用模式下,会话结束后发送 FinishConnection
|
# 非复用模式下,会话结束后发送 FinishConnection
|
||||||
@@ -552,16 +564,14 @@ class TTSProvider(TTSProviderBase):
|
|||||||
)
|
)
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
break
|
break
|
||||||
# 连接异常时关闭WebSocket
|
finally:
|
||||||
|
# 退出时关闭连接并清理引用
|
||||||
if self.ws:
|
if self.ws:
|
||||||
try:
|
try:
|
||||||
await self.ws.close()
|
await self.ws.close()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
self.ws = None
|
self.ws = None
|
||||||
# 监听任务退出时清理引用
|
|
||||||
finally:
|
|
||||||
self.activate_session = False
|
|
||||||
self._monitor_task = None
|
self._monitor_task = None
|
||||||
|
|
||||||
async def send_event(
|
async def send_event(
|
||||||
@@ -619,21 +629,23 @@ class TTSProvider(TTSProviderBase):
|
|||||||
# 解析结果
|
# 解析结果
|
||||||
# header
|
# header
|
||||||
header = response.header
|
header = response.header
|
||||||
num = 0b00001111
|
mask = 0b00001111
|
||||||
header.protocol_version = res[0] >> 4 & num
|
header.protocol_version = res[0] >> 4 & mask
|
||||||
header.header_size = res[0] & 0x0F
|
header.header_size = res[0] & 0x0F
|
||||||
header.message_type = (res[1] >> 4) & num
|
header.message_type = (res[1] >> 4) & mask
|
||||||
header.message_type_specific_flags = res[1] & 0x0F
|
header.message_type_specific_flags = res[1] & 0x0F
|
||||||
header.serialization_method = res[2] >> num
|
header.serialization_method = res[2] >> 4
|
||||||
header.message_compression = res[2] & 0x0F
|
header.message_compression = res[2] & 0x0F
|
||||||
header.reserved = res[3]
|
header.reserved = res[3]
|
||||||
#
|
#
|
||||||
offset = 4
|
offset = header.header_size * 4
|
||||||
optional = response.optional
|
optional = response.optional
|
||||||
if header.message_type == FULL_SERVER_RESPONSE or AUDIO_ONLY_RESPONSE:
|
if header.message_type in (FULL_SERVER_RESPONSE, AUDIO_ONLY_RESPONSE):
|
||||||
# read event
|
# read event
|
||||||
if header.message_type_specific_flags == MsgTypeFlagWithEvent:
|
if header.message_type_specific_flags == MsgTypeFlagWithEvent:
|
||||||
optional.event = int.from_bytes(res[offset:8], "big", signed=True)
|
optional.event = int.from_bytes(
|
||||||
|
res[offset : offset + 4], "big", signed=True
|
||||||
|
)
|
||||||
offset += 4
|
offset += 4
|
||||||
if optional.event == EVENT_NONE:
|
if optional.event == EVENT_NONE:
|
||||||
return response
|
return response
|
||||||
@@ -644,10 +656,11 @@ class TTSProvider(TTSProviderBase):
|
|||||||
optional.response_meta_json, offset = self.read_res_content(
|
optional.response_meta_json, offset = self.read_res_content(
|
||||||
res, offset
|
res, offset
|
||||||
)
|
)
|
||||||
elif (
|
elif optional.event in (
|
||||||
optional.event == EVENT_SessionStarted
|
EVENT_SessionStarted,
|
||||||
or optional.event == EVENT_SessionFailed
|
EVENT_SessionFailed,
|
||||||
or optional.event == EVENT_SessionFinished
|
EVENT_SessionFinished,
|
||||||
|
EVENT_SessionCanceled,
|
||||||
):
|
):
|
||||||
optional.sessionId, offset = self.read_res_content(res, offset)
|
optional.sessionId, offset = self.read_res_content(res, offset)
|
||||||
optional.response_meta_json, offset = self.read_res_content(
|
optional.response_meta_json, offset = self.read_res_content(
|
||||||
@@ -820,6 +833,13 @@ class TTSProvider(TTSProviderBase):
|
|||||||
):
|
):
|
||||||
self.wav_to_opus_data_audio_raw_stream(res.payload, callback=lambda opus_frame: audio_data.append(opus_frame))
|
self.wav_to_opus_data_audio_raw_stream(res.payload, callback=lambda opus_frame: audio_data.append(opus_frame))
|
||||||
elif res.optional.event == EVENT_SessionFinished:
|
elif res.optional.event == EVENT_SessionFinished:
|
||||||
|
# 句尾冲刷流式 opus 编码器不足一帧的 PCM 残量
|
||||||
|
if hasattr(self, "opus_encoder") and self.opus_encoder:
|
||||||
|
self.wav_to_opus_data_audio_raw_stream(
|
||||||
|
b"",
|
||||||
|
is_end=True,
|
||||||
|
callback=lambda opus_frame: audio_data.append(opus_frame),
|
||||||
|
)
|
||||||
break
|
break
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -475,6 +475,21 @@ def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def audio_file_to_wav_bytes(audio_file_path, sample_rate=16000):
|
||||||
|
"""音频文件直接转目标采样率的 wav 字节流,不经 Opus 编解码,避免有损"""
|
||||||
|
file_type = os.path.splitext(audio_file_path)[1]
|
||||||
|
if file_type:
|
||||||
|
file_type = file_type.lstrip(".")
|
||||||
|
with _ffmpeg_path_override():
|
||||||
|
audio = AudioSegment.from_file(
|
||||||
|
audio_file_path, format=file_type, parameters=["-nostdin"]
|
||||||
|
)
|
||||||
|
audio = audio.set_channels(1).set_frame_rate(sample_rate).set_sample_width(2)
|
||||||
|
buffer = BytesIO()
|
||||||
|
audio.export(buffer, format="wav")
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
def check_vad_update(before_config, new_config):
|
def check_vad_update(before_config, new_config):
|
||||||
if (
|
if (
|
||||||
new_config.get("selected_module") is None
|
new_config.get("selected_module") is None
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import os
|
|||||||
import importlib.util
|
import importlib.util
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
print("使用前请根据doc/performance_testerer.md的说明准备配置。")
|
print("使用前请根据仓库根目录下 docs/performance_tester.md 的说明准备配置。")
|
||||||
|
|
||||||
|
|
||||||
def list_performance_tester_modules():
|
def list_performance_tester_modules():
|
||||||
|
|||||||
@@ -7,36 +7,38 @@ numpy==1.26.4
|
|||||||
websockets==14.2
|
websockets==14.2
|
||||||
#--------- 以下是可升级的依赖
|
#--------- 以下是可升级的依赖
|
||||||
pyyml==0.0.2
|
pyyml==0.0.2
|
||||||
silero_vad==6.2.1
|
silero_vad==6.2.3
|
||||||
opuslib_next==1.3.1
|
opuslib_next==1.3.1
|
||||||
pydub==0.25.1
|
pydub==0.25.1
|
||||||
funasr==1.2.7
|
funasr==1.4.16
|
||||||
|
# transformers>=5 要求 torch>=2.6,与本项目 torch 2.2.2 冲突(会禁用 PyTorch,fun_local 加载不了模型)
|
||||||
|
transformers<5
|
||||||
openai==2.8.1
|
openai==2.8.1
|
||||||
google-generativeai==0.8.5
|
google-generativeai==0.8.6
|
||||||
edge_tts==7.3.1
|
edge_tts==7.3.1
|
||||||
httpx==0.28.1
|
httpx==0.28.1
|
||||||
aiohttp==3.13.2
|
aiohttp==3.14.5
|
||||||
aiohttp_cors==0.8.1
|
aiohttp_cors==0.8.1
|
||||||
ormsgpack==1.12.0
|
ormsgpack==1.12.2
|
||||||
ruamel.yaml==0.18.16
|
ruamel.yaml==0.18.16
|
||||||
loguru==0.7.3
|
loguru==0.7.3
|
||||||
requests==2.32.5
|
requests==2.34.2
|
||||||
cozepy==0.20.0
|
cozepy==0.20.0
|
||||||
mem0ai==1.0.0
|
mem0ai==2.2.1
|
||||||
powermem>=0.3.1
|
powermem>=0.3.1
|
||||||
bs4==0.0.2
|
bs4==0.0.2
|
||||||
modelscope==1.39.1
|
modelscope==1.40.2
|
||||||
sherpa_onnx==1.12.29
|
sherpa_onnx==1.13.8
|
||||||
mcp==1.22.0
|
mcp==2.3.0
|
||||||
cnlunar==0.2.4
|
cnlunar==0.2.5
|
||||||
PySocks==1.7.1
|
PySocks==1.7.1
|
||||||
dashscope==1.25.2
|
dashscope==1.27.7
|
||||||
baidu-aip==4.16.13
|
baidu-aip==4.16.13
|
||||||
aioconsole==0.8.2
|
aioconsole==0.8.2
|
||||||
markitdown==0.1.3
|
markitdown==0.1.8
|
||||||
mcp-proxy==0.12.0
|
mcp-proxy==0.12.0
|
||||||
PyJWT==2.10.1
|
PyJWT==2.15.1
|
||||||
psutil==7.1.3
|
psutil==7.2.2
|
||||||
portalocker==3.2.0 # 暂留 3.x:4.x 与 qdrant-client<1.20 的 portalocker<4.0 约束冲突 (PR #3360)
|
portalocker==3.2.0 # 暂留 3.x:4.x 与 qdrant-client<1.20 的 portalocker<4.0 约束冲突 (PR #3360)
|
||||||
Jinja2==3.1.6
|
Jinja2==3.1.6
|
||||||
vosk==0.3.45
|
vosk==0.3.45
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""Wakeup caching accepts both return forms of TTSProviderBase.to_tts."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import math
|
||||||
|
import struct
|
||||||
|
import wave
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def wakeup_runtime(tmp_path, monkeypatch):
|
||||||
|
# conftest supplies local configuration; no deployment config is required.
|
||||||
|
from config import settings
|
||||||
|
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
monkeypatch.setattr(settings, "config_file_valid", True)
|
||||||
|
from core.handle import helloHandle
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
from core.utils.wakeup_word import WakeupWordsConfig
|
||||||
|
|
||||||
|
class LocalTTS(TTSProviderBase):
|
||||||
|
"""Replace only remote synthesis; keep the real file and Opus conversion."""
|
||||||
|
|
||||||
|
def __init__(self, output_dir, delete_audio_file):
|
||||||
|
super().__init__({"output_dir": str(output_dir)}, delete_audio_file)
|
||||||
|
self.voice = "test-voice"
|
||||||
|
self.filename = output_dir / "retained.wav"
|
||||||
|
buffer = BytesIO()
|
||||||
|
with wave.open(buffer, "wb") as audio:
|
||||||
|
audio.setnchannels(1)
|
||||||
|
audio.setsampwidth(2)
|
||||||
|
audio.setframerate(22050)
|
||||||
|
audio.writeframes(
|
||||||
|
b"".join(
|
||||||
|
struct.pack(
|
||||||
|
"<h", int(8000 * math.sin(2 * math.pi * 440 * i / 22050))
|
||||||
|
)
|
||||||
|
# 1.1s 源音频:给重采样留裕量,规避重采样器 off-by-one
|
||||||
|
for i in range(int(22050 * 1.1))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.audio_bytes = buffer.getvalue()
|
||||||
|
|
||||||
|
def generate_filename(self):
|
||||||
|
return str(self.filename)
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
if output_file is not None:
|
||||||
|
Path(output_file).write_bytes(self.audio_bytes)
|
||||||
|
return self.audio_bytes
|
||||||
|
|
||||||
|
cache = WakeupWordsConfig()
|
||||||
|
monkeypatch.setattr(helloHandle, "wakeup_words_config", cache)
|
||||||
|
monkeypatch.setattr(helloHandle, "_wakeup_response_lock", asyncio.Lock())
|
||||||
|
return helloHandle, cache, LocalTTS
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("sample_rate", [16000, 24000])
|
||||||
|
@pytest.mark.parametrize("delete_audio_file", [False, True])
|
||||||
|
def test_wakeup_cache_accepts_retained_files_and_opus_frames(
|
||||||
|
tmp_path, wakeup_runtime, sample_rate, delete_audio_file
|
||||||
|
):
|
||||||
|
helloHandle, wakeup_cache, LocalTTS = wakeup_runtime
|
||||||
|
tts = LocalTTS(tmp_path, delete_audio_file)
|
||||||
|
conn = SimpleNamespace(tts=tts, sample_rate=sample_rate)
|
||||||
|
tts.conn = conn
|
||||||
|
|
||||||
|
asyncio.run(helloHandle.wakeupWordsResponse(conn))
|
||||||
|
|
||||||
|
response = wakeup_cache.get_wakeup_response(tts.voice)
|
||||||
|
assert response is not None
|
||||||
|
assert response["text"] in helloHandle.WAKEUP_CONFIG["responses"]
|
||||||
|
with wave.open(response["file_path"], "rb") as audio:
|
||||||
|
assert audio.getnchannels() == 1
|
||||||
|
assert audio.getsampwidth() == 2
|
||||||
|
assert audio.getframerate() == sample_rate
|
||||||
|
assert audio.getnframes() >= sample_rate
|
||||||
|
assert any(audio.readframes(audio.getnframes()))
|
||||||
|
if not delete_audio_file:
|
||||||
|
assert tts.filename.read_bytes() == tts.audio_bytes
|
||||||
|
assert not helloHandle._wakeup_response_lock.locked()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("tts_result", [None, []])
|
||||||
|
def test_empty_synthesis_does_not_replace_cached_response(wakeup_runtime, tts_result):
|
||||||
|
helloHandle, wakeup_cache, _ = wakeup_runtime
|
||||||
|
wakeup_cache.generate_file_path = Mock()
|
||||||
|
wakeup_cache.update_wakeup_response = Mock()
|
||||||
|
conn = SimpleNamespace(tts=SimpleNamespace(to_tts=lambda _: tts_result))
|
||||||
|
|
||||||
|
asyncio.run(helloHandle.wakeupWordsResponse(conn))
|
||||||
|
|
||||||
|
wakeup_cache.generate_file_path.assert_not_called()
|
||||||
|
wakeup_cache.update_wakeup_response.assert_not_called()
|
||||||
|
assert not helloHandle._wakeup_response_lock.locked()
|
||||||
|
|
||||||
|
|
||||||
|
def test_retained_file_skips_opus_roundtrip(wakeup_runtime, tmp_path, monkeypatch):
|
||||||
|
"""保留文件路径必须直转 wav,不得经过 Opus 编解码。"""
|
||||||
|
from core.utils import util
|
||||||
|
|
||||||
|
helloHandle, wakeup_cache, LocalTTS = wakeup_runtime
|
||||||
|
|
||||||
|
def _forbid_opus(*_args, **_kwargs):
|
||||||
|
raise AssertionError("retained file path must not run Opus encoding")
|
||||||
|
|
||||||
|
monkeypatch.setattr(util, "pcm_to_data_stream", _forbid_opus)
|
||||||
|
tts = LocalTTS(tmp_path, False)
|
||||||
|
conn = SimpleNamespace(tts=tts, sample_rate=16000)
|
||||||
|
tts.conn = conn
|
||||||
|
|
||||||
|
asyncio.run(helloHandle.wakeupWordsResponse(conn))
|
||||||
|
|
||||||
|
assert wakeup_cache.get_wakeup_response(tts.voice) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_retained_file_preserves_cache_and_releases_lock(wakeup_runtime):
|
||||||
|
helloHandle, wakeup_cache, _ = wakeup_runtime
|
||||||
|
wakeup_cache.generate_file_path = Mock()
|
||||||
|
wakeup_cache.update_wakeup_response = Mock()
|
||||||
|
conn = SimpleNamespace(
|
||||||
|
tts=SimpleNamespace(voice="test-voice", to_tts=lambda _: "missing.wav"),
|
||||||
|
sample_rate=16000,
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
asyncio.run(helloHandle.wakeupWordsResponse(conn))
|
||||||
|
|
||||||
|
wakeup_cache.generate_file_path.assert_not_called()
|
||||||
|
wakeup_cache.update_wakeup_response.assert_not_called()
|
||||||
|
assert not helloHandle._wakeup_response_lock.locked()
|
||||||
Reference in new issue
Block a user