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R4L%5fdo9MPU9KC;Ne*Pw@V?4_9u`k?R?9WkRls>eng6s)oQLSA0ZBl&`1r-!xf<
z#2|XHzW)h$eJ+fVz3^)ui9yu)SO0&p{@)O?wg1i~+fMXCecOmM%q7=iq6YtM8|+3uze#6a}@-}=h;
z^k~ML0R2@7M54xDC^YOW7H-XW=vl`~%7G!X-3
z)J{%Ge5%nm9b%i?_3)+oT`lu^Mt#b&g6m@!;#!geYwLrN?>gT^!rpx9!+5e{6ES{H
z9gIv{ny1%J##X=UEO}HgKU0p!Satwk{O((@orgZzJ1$Fj_S`-*^Nj4%^cAx`vB<~H
zWcC`|)~uQ*b?XNwX5^g8Q%|isjrEW
zPNu&Uf0Up1IP-gyU!(fBq^9pMuw+xpoanu_cd91_pEXPV_&BGBobk_OBD#0|_AY9$
zbC44raj9|D$V#>>S7g?`W6azhxaN92+%qGScX#L=x&MfmM+}P|>|crZcfEH`>v#O@
zEbQw0E;ZI(knOR*>5!cZ+vyXrbAl%hyVc=~;i=9mohUVSrmjd0p~
zaC+>(Ij|c?#s9^tcDf)gPh>dmeLal`ecCPUAU-NMrPBDG$b0Zai6(v@?X^ZHoB2(-q}Iy(XyuUq0}PBWS9#-
zKHjK5i;Eyz4zsPJ{Yaj9k8ofA`>nud?(Jtz^?rBP-*nuclYdk3Rh94k_iBYcDgM3x
NK4~}KZS<
literal 0
HcmV?d00001
diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py
index 75b9fcb23..df8376b66 100644
--- a/main/xiaozhi-server/core/handle/helloHandle.py
+++ b/main/xiaozhi-server/core/handle/helloHandle.py
@@ -19,6 +19,10 @@ TAG = __name__
WAKEUP_CONFIG = {
"refresh_time": 5,
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
+ "responses": [
+ "我在", "在的呢", "在的哦", "来啦", "你说", "请讲",
+ "听着呢", "请说", "需要我做些什么", "请指示"
+ ],
}
# 创建全局的唤醒词配置管理器
@@ -85,9 +89,9 @@ async def checkWakeupWords(conn, text):
if not response or not response.get("file_path"):
response = {
"voice": "default",
- "file_path": "config/assets/wakeup_words.wav",
+ "file_path": "config/assets/wakeup_words_short.wav",
"time": 0,
- "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
+ "text": "我在这里哦!",
}
# 获取音频数据
@@ -110,7 +114,7 @@ async def checkWakeupWords(conn, text):
async def wakeupWordsResponse(conn):
- if not conn.tts or not conn.llm or not conn.llm.response_no_stream:
+ if not conn.tts:
return
try:
@@ -118,16 +122,8 @@ async def wakeupWordsResponse(conn):
if not await _wakeup_response_lock.acquire():
return
- # 生成唤醒词回复
- wakeup_word = random.choice(WAKEUP_CONFIG["words"])
- question = (
- "此刻用户正在和你说```"
- + wakeup_word
- + "```。\n请你根据以上用户的内容进行20-30字回复。要符合系统设置的角色情感和态度,不要像机器人一样说话。\n"
- + "请勿对这条内容本身进行任何解释和回应,请勿返回表情符号,仅返回对用户的内容的回复。"
- )
-
- result = conn.llm.response_no_stream(conn.config["prompt"], question)
+ # 从预定义回复列表中随机选择一个回复
+ result = random.choice(WAKEUP_CONFIG["responses"])
if not result or len(result) == 0:
return
From a10e94bef6b53961a1b3a01bb80e2e74cd292b04 Mon Sep 17 00:00:00 2001
From: Chingfeng Li
Date: Sat, 11 Oct 2025 17:52:15 +0800
Subject: [PATCH 013/182] =?UTF-8?q?=E5=85=88=E8=AE=A4=E8=AF=81=EF=BC=8C?=
=?UTF-8?q?=E5=90=8E=E5=88=9B=E5=BB=BA=E8=BF=9E=E6=8E=A5=EF=BC=8C=E9=98=B2?=
=?UTF-8?q?=E6=AD=A2=E6=97=A0=E6=95=88=E8=BF=9E=E6=8E=A5=E5=BB=BA=E7=AB=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/core/connection.py | 29 ------------
main/xiaozhi-server/core/websocket_server.py | 47 ++++++++++++++++++++
2 files changed, 47 insertions(+), 29 deletions(-)
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 4152e926c..bd14a6fdf 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -11,7 +11,6 @@ import traceback
import subprocess
import websockets
-from core.ota_auth import AuthManager
from core.utils.util import (
extract_json_from_string,
check_vad_update,
@@ -69,17 +68,6 @@ class ConnectionHandler:
self.logger = setup_logging()
self.server = server # 保存server实例的引用
- # 认证相关
- auth_config = self.config["server"].get("auth", {})
- self.auth_enable = auth_config.get("enabled", False)
- # 设备白名单
- self.allowed_devices = set(
- auth_config.get("allowed_devices", [])
- )
- secret_key = auth_config.get("signature_key", "")
- expire_seconds = auth_config.get("expire_seconds", None)
- self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
-
self.need_bind = False
self.bind_code = None
self.read_config_from_api = self.config.get("read_config_from_api", False)
@@ -208,23 +196,6 @@ class ConnectionHandler:
self.device_id = self.headers.get("device-id", None)
- # 是否开启了认证,如果开启了则进行认证,否则不认证
- if self.auth_enable:
- # 如果启用了白名单则优先处理白名单
- if self.allowed_devices and self.device_id not in self.allowed_devices:
- raise AuthenticationError("未经授权的DeviceID")
- else:
- # 否则校验token
- token = self.headers.get("authorization", "")
- if token.startswith('Bearer '):
- token = token[7:] # 移除'Bearer '前缀
- else:
- raise AuthenticationError("Missing or invalid Authorization header")
- # 进行认证
- auth_success = self.auth.verify_token(token, client_id=self.headers.get("client-id"), username=self.headers.get("device-id"))
- if not auth_success:
- raise AuthenticationError("Invalid token")
-
# 认证通过,继续处理
self.websocket = ws
diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py
index 09ba79615..b3a5a7d93 100644
--- a/main/xiaozhi-server/core/websocket_server.py
+++ b/main/xiaozhi-server/core/websocket_server.py
@@ -1,8 +1,12 @@
import asyncio
+import json
+
import websockets
from config.logger import setup_logging
+from core.auth import AuthenticationError
from core.connection import ConnectionHandler
from config.config_loader import get_config_from_api
+from core.ota_auth import AuthManager
from core.utils.modules_initialize import initialize_modules
from core.utils.util import check_vad_update, check_asr_update
@@ -32,6 +36,16 @@ class WebSocketServer:
self.active_connections = set()
+ auth_config = self.config["server"].get("auth", {})
+ self.auth_enable = auth_config.get("enabled", False)
+ # 设备白名单
+ self.allowed_devices = set(
+ auth_config.get("allowed_devices", [])
+ )
+ secret_key = auth_config.get("signature_key", "")
+ expire_seconds = auth_config.get("expire_seconds", None)
+ self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
+
async def start(self):
server_config = self.config["server"]
host = server_config.get("ip", "0.0.0.0")
@@ -44,6 +58,18 @@ class WebSocketServer:
async def _handle_connection(self, websocket):
"""处理新连接,每次创建独立的ConnectionHandler"""
+ # 先认证,后建立连接
+ try:
+ await self._handle_auth(websocket)
+ except AuthenticationError:
+ await websocket.send(json.dumps({
+ "type": "alert",
+ "status": "ERROR",
+ "message": "认证失败",
+ "emotion": "sad"
+ }))
+ await websocket.close()
+ return
# 创建ConnectionHandler时传入当前server实例
handler = ConnectionHandler(
self.config,
@@ -136,3 +162,24 @@ class WebSocketServer:
except Exception as e:
self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}")
return False
+
+ async def _handle_auth(self, websocket):
+ # 先认证,后建立连接
+ if self.auth_enable:
+ headers = dict(websocket.request.headers)
+ device_id = headers.get("device-id", None)
+ client_id = headers.get("client-id", None)
+ # 如果启用了白名单则优先处理白名单
+ if self.allowed_devices and device_id not in self.allowed_devices:
+ raise AuthenticationError("未经授权的DeviceID")
+ else:
+ # 否则校验token
+ token = headers.get("authorization", "")
+ if token.startswith('Bearer '):
+ token = token[7:] # 移除'Bearer '前缀
+ else:
+ raise AuthenticationError("Missing or invalid Authorization header")
+ # 进行认证
+ auth_success = self.auth.verify_token(token, client_id=client_id, username=device_id)
+ if not auth_success:
+ raise AuthenticationError("Invalid token")
From 44f41ebd113b71d75ee61bee4d9bae1a41b2a301 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sun, 12 Oct 2025 23:24:43 +0800
Subject: [PATCH 014/182] =?UTF-8?q?fix:=E5=9B=9E=E5=A4=8D=E8=AF=8D?=
=?UTF-8?q?=E5=A4=AA=E7=9F=AD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/core/handle/helloHandle.py | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py
index df8376b66..0c13ea1dc 100644
--- a/main/xiaozhi-server/core/handle/helloHandle.py
+++ b/main/xiaozhi-server/core/handle/helloHandle.py
@@ -17,11 +17,17 @@ from core.providers.tools.device_mcp import (
TAG = __name__
WAKEUP_CONFIG = {
- "refresh_time": 5,
- "words": ["你好", "你好啊", "嘿,你好", "嗨"],
+ "refresh_time": 10,
"responses": [
- "我在", "在的呢", "在的哦", "来啦", "你说", "请讲",
- "听着呢", "请说", "需要我做些什么", "请指示"
+ "我一直都在呢,您请说。",
+ "在的呢,请随时吩咐我。",
+ "来啦来啦,请告诉我吧。",
+ "您请说,我正听着。",
+ "请您讲话,我准备好了。",
+ "请您说出指令吧。",
+ "我认真听着呢,请讲。",
+ "请问您需要什么帮助?",
+ "我在这里,等候您的指令。",
],
}
@@ -77,7 +83,6 @@ async def checkWakeupWords(conn, text):
return False
conn.just_woken_up = True
- await send_stt_message(conn, text)
# 获取当前音色
voice = getattr(conn.tts, "voice", "default")
@@ -144,4 +149,4 @@ async def wakeupWordsResponse(conn):
finally:
# 确保在任何情况下都释放锁
if _wakeup_response_lock.locked():
- _wakeup_response_lock.release()
\ No newline at end of file
+ _wakeup_response_lock.release()
From 374f2a92aaae6685aadb39b9f703d49ae4e41087 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E4=BA=8E=E5=B0=8F=E4=B8=98?=
Date: Mon, 13 Oct 2025 09:26:16 +0800
Subject: [PATCH 015/182] =?UTF-8?q?=E4=BD=BF=E7=94=A8uuid=E5=8C=85?=
=?UTF-8?q?=E6=9D=A5=E7=94=9F=E6=88=90uuidv4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../src/pages/forgot-password/index.vue | 12 ++------
main/manager-mobile/src/pages/login/index.vue | 28 +++++++----------
.../src/pages/register/index.vue | 30 +++++++------------
main/manager-web/package-lock.json | 25 ++++++++++++----
main/manager-web/package.json | 1 +
5 files changed, 44 insertions(+), 52 deletions(-)
diff --git a/main/manager-mobile/src/pages/forgot-password/index.vue b/main/manager-mobile/src/pages/forgot-password/index.vue
index f574d0e91..fb5ac0fe9 100644
--- a/main/manager-mobile/src/pages/forgot-password/index.vue
+++ b/main/manager-mobile/src/pages/forgot-password/index.vue
@@ -11,6 +11,7 @@
-
-
diff --git a/main/manager-web/src/views/DeviceManagement.vue b/main/manager-web/src/views/DeviceManagement.vue
index 053fcbc60..faac13054 100644
--- a/main/manager-web/src/views/DeviceManagement.vue
+++ b/main/manager-web/src/views/DeviceManagement.vue
@@ -64,9 +64,6 @@
{{ $t('device.unbind') }}
-
- {{ $t('device.toolCall') }}
-
@@ -82,9 +79,9 @@
{{ $t('device.manualAdd') }}
- {{
- $t('device.unbind')
- }}
+
+ {{ $t('device.unbind') }}
+
@@ -117,7 +116,6 @@
@refresh="fetchBindDevices(currentAgentId)" />
-
@@ -127,20 +125,17 @@ import Api from '@/apis/api';
import AddDeviceDialog from "@/components/AddDeviceDialog.vue";
import HeaderBar from "@/components/HeaderBar.vue";
import ManualAddDeviceDialog from "@/components/ManualAddDeviceDialog.vue";
-import McpToolCallDialog from "@/components/McpToolCallDialog.vue";
export default {
components: {
HeaderBar,
AddDeviceDialog,
- ManualAddDeviceDialog,
- McpToolCallDialog
+ ManualAddDeviceDialog
},
data() {
return {
addDeviceDialogVisible: false,
manualAddDeviceDialogVisible: false,
- mcpToolCallDialogVisible: false,
selectedDeviceId: '',
searchKeyword: "",
activeSearchKeyword: "",
@@ -280,11 +275,6 @@ export default {
handleManualAddDevice() {
this.manualAddDeviceDialogVisible = true;
},
-
- handleMcpToolCall(deviceId) {
- this.selectedDeviceId = deviceId;
- this.mcpToolCallDialogVisible = true;
- },
submitRemark(row) {
if (row._submitting) return;
@@ -383,7 +373,7 @@ export default {
.sort((a, b) => a.rawBindTime - b.rawBindTime);
this.activeSearchKeyword = "";
this.searchKeyword = "";
-
+
// 获取设备列表后,立即获取设备状态
this.fetchDeviceStatus(agentId);
} else {
@@ -391,7 +381,7 @@ export default {
}
});
},
-
+
// 获取设备状态
fetchDeviceStatus(agentId) {
Api.device.getDeviceStatus(agentId, ({ data }) => {
@@ -399,7 +389,7 @@ export default {
try {
// 解析后端返回的设备状态JSON
const statusData = JSON.parse(data.data);
-
+
// 直接使用解析后的数据作为设备状态映射(不需要devices字段包装)
if (statusData && typeof statusData === 'object') {
// 更新设备状态
@@ -411,7 +401,7 @@ export default {
}
});
},
-
+
// 根据API响应更新设备状态
updateDeviceStatusFromResponse(deviceStatusMap) {
this.deviceList.forEach(device => {
@@ -419,11 +409,11 @@ export default {
const macAddress = device.macAddress ? device.macAddress.replace(/:/g, '_') : 'unknown';
const groupId = device.model ? device.model.replace(/:/g, '_') : 'GID_default';
const mqttClientId = `${groupId}@@@${macAddress}@@@${macAddress}`;
-
+
// 从状态映射中获取设备状态
if (deviceStatusMap[mqttClientId]) {
const statusInfo = deviceStatusMap[mqttClientId];
-
+
let isOnline = false;
if (statusInfo.isAlive === true) {
isOnline = true;
@@ -434,7 +424,7 @@ export default {
} else {
isOnline = false;
}
-
+
device.deviceStatus = isOnline ? 'online' : 'offline';
} else {
// 如果没有找到对应的状态信息,默认为离线
From da8d8c53c0f19884a2caf7feddf1414b646f6ae0 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Thu, 23 Oct 2025 12:24:16 +0800
Subject: [PATCH 084/182] =?UTF-8?q?update:=E4=BC=98=E5=8C=96=E6=96=87?=
=?UTF-8?q?=E6=A1=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
docs/Deployment.md | 16 +++++++++++-----
docs/Deployment_all.md | 12 +++++++-----
docs/FAQ.md | 14 +++++++-------
3 files changed, 25 insertions(+), 17 deletions(-)
diff --git a/docs/Deployment.md b/docs/Deployment.md
index f020b4177..55fef3c33 100644
--- a/docs/Deployment.md
+++ b/docs/Deployment.md
@@ -139,6 +139,9 @@ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/
conda install libopus -y
conda install ffmpeg -y
+
+# 在 Linux 环境下进行部署时,如出现类似缺失 libiconv.so.2 动态库的报错 请通过以下命令进行安装
+conda install libiconv -y
```
请注意,以上命令,不是一股脑执行就成功的,你需要一步步执行,每一步执行完后,都检查一下输出的日志,查看是否成功。
@@ -267,7 +270,8 @@ LLM:
6、[我说话很慢,停顿时小智老是抢话](./FAQ.md)
## 部署相关教程
1、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
-2、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
+2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
+3、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
## 拓展相关教程
1、[如何开启手机号码注册智控台](./ali-sms-integration.md)
2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)
@@ -275,11 +279,13 @@ LLM:
4、[如何部署MCP接入点](./mcp-endpoint-enable.md)
5、[如何接入MCP接入点](./mcp-endpoint-integration.md)
6、[如何开启声纹识别](./voiceprint-integration.md)
-10、[新闻插件源配置指南](./newsnow_plugin_config.md)
+7、[新闻插件源配置指南](./newsnow_plugin_config.md)
+8、[天气插件使用指南](./weather-integration.md)
## 语音克隆、本地语音部署相关教程
-1、[如何部署集成index-tts本地语音](./index-stream-integration.md)
-2、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
-3、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
+1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)
+2、[如何部署集成index-tts本地语音](./index-stream-integration.md)
+3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
+4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
## 性能测试教程
1、[各组件速度测试指南](./performance_tester.md)
2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)
diff --git a/docs/Deployment_all.md b/docs/Deployment_all.md
index c63941dc9..f7d87cc3a 100644
--- a/docs/Deployment_all.md
+++ b/docs/Deployment_all.md
@@ -357,7 +357,7 @@ conda install libopus -y
conda install ffmpeg -y
# 在 Linux 环境下进行部署时,如出现类似缺失 libiconv.so.2 动态库的报错 请通过以下命令进行安装
-conda install libiconv
+conda install libiconv -y
```
请注意,以上命令,不是一股脑执行就成功的,你需要一步步执行,每一步执行完后,都检查一下输出的日志,查看是否成功。
@@ -471,7 +471,8 @@ ws://你电脑局域网的ip:8000/xiaozhi/v1/
6、[我说话很慢,停顿时小智老是抢话](./FAQ.md)
## 部署相关教程
1、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
-2、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
+2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
+3、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
## 拓展相关教程
1、[如何开启手机号码注册智控台](./ali-sms-integration.md)
2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)
@@ -482,9 +483,10 @@ ws://你电脑局域网的ip:8000/xiaozhi/v1/
7、[新闻插件源配置指南](./newsnow_plugin_config.md)
8、[天气插件使用指南](./weather-integration.md)
## 语音克隆、本地语音部署相关教程
-1、[如何部署集成index-tts本地语音](./index-stream-integration.md)
-2、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
-3、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
+1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)
+2、[如何部署集成index-tts本地语音](./index-stream-integration.md)
+3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
+4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
## 性能测试教程
1、[各组件速度测试指南](./performance_tester.md)
2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)
diff --git a/docs/FAQ.md b/docs/FAQ.md
index 0904a17c4..844ee3d42 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -62,15 +62,15 @@ VAD:
### 7、部署相关教程
1、[如何进行最简化部署](./Deployment.md)
2、[如何进行全模块部署](./Deployment_all.md)
-2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
-3、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
-4、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
+3、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
+4、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
+5、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
-### 8、编译固件相关教程
+### 9、编译固件相关教程
1、[如何自己编译小智固件](./firmware-build.md)
2、[如何基于虾哥编译好的固件修改OTA地址](./firmware-setting.md)
-### 8、拓展相关教程
+### 10、拓展相关教程
1、[如何开启手机号码注册智控台](./ali-sms-integration.md)
2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)
3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)
@@ -79,13 +79,13 @@ VAD:
6、[如何开启声纹识别](./voiceprint-integration.md)
10、[新闻插件源配置指南](./newsnow_plugin_config.md)
-### 9、语音克隆、本地语音部署相关教程
+### 11、语音克隆、本地语音部署相关教程
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)
2、[如何部署集成index-tts本地语音](./index-stream-integration.md)
3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
-### 10、性能测试教程
+### 12、性能测试教程
1、[各组件速度测试指南](./performance_tester.md)
2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)
From a035ed525a3c72de0db71227ee73f334515a6c56 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Thu, 23 Oct 2025 17:04:33 +0800
Subject: [PATCH 085/182] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=EF=BC=9A=E8=AE=AF?=
=?UTF-8?q?=E9=A3=9Easr=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA=E5=AD=97?=
=?UTF-8?q?=E4=B8=A2=E5=A4=B1=E7=9A=84bug?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../core/providers/asr/xunfei_stream.py | 231 ++++++++++++------
1 file changed, 156 insertions(+), 75 deletions(-)
diff --git a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py
index 7f6964282..e91c8f098 100644
--- a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py
+++ b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py
@@ -22,6 +22,7 @@ STATUS_FIRST_FRAME = 0 # 第一帧的标识
STATUS_CONTINUE_FRAME = 1 # 中间帧标识
STATUS_LAST_FRAME = 2 # 最后一帧的标识
+
class ASRProvider(ASRProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__()
@@ -35,6 +36,7 @@ class ASRProvider(ASRProviderBase):
self.server_ready = False
self.last_frame_sent = False # 标记是否已发送最终帧
self.best_text = "" # 保存最佳识别结果
+ self.has_final_result = False # 标记是否收到最终识别结果
# 讯飞配置
self.app_id = config.get("app_id")
@@ -50,19 +52,15 @@ class ASRProvider(ASRProviderBase):
"language": config.get("language", "zh_cn"),
"accent": config.get("accent", "mandarin"),
"dwa": config.get("dwa", "wpgs"),
- "result": {
- "encoding": "utf8",
- "compress": "raw",
- "format": "plain"
- }
+ "result": {"encoding": "utf8", "compress": "raw", "format": "plain"},
}
self.output_dir = config.get("output_dir", "tmp/")
self.delete_audio_file = delete_audio_file
-
+
def create_url(self) -> str:
"""生成认证URL"""
- url = 'ws://iat.cn-huabei-1.xf-yun.com/v1'
+ url = "ws://iat.cn-huabei-1.xf-yun.com/v1"
# 生成RFC1123格式的时间戳
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
@@ -73,23 +71,30 @@ class ASRProvider(ASRProviderBase):
signature_origin += "GET " + "/v1 " + "HTTP/1.1"
# 进行hmac-sha256进行加密
- signature_sha = hmac.new(self.api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
+ signature_sha = hmac.new(
+ self.api_secret.encode("utf-8"),
+ signature_origin.encode("utf-8"),
+ digestmod=hashlib.sha256,
+ ).digest()
+ signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
- authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
- self.api_key, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
+ authorization_origin = (
+ 'api_key="%s", algorithm="%s", headers="%s", signature="%s"'
+ % (self.api_key, "hmac-sha256", "host date request-line", signature_sha)
+ )
+ authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(
+ encoding="utf-8"
+ )
# 将请求的鉴权参数组合为字典
v = {
"authorization": authorization,
"date": date,
- "host": "iat.cn-huabei-1.xf-yun.com"
+ "host": "iat.cn-huabei-1.xf-yun.com",
}
# 拼接鉴权参数,生成url
- url = url + '?' + urlencode(v)
+ url = url + "?" + urlencode(v)
return url
async def open_audio_channels(self, conn):
@@ -100,7 +105,7 @@ class ASRProvider(ASRProviderBase):
await super().receive_audio(conn, audio, audio_have_voice)
# 存储音频数据用于声纹识别
- if not hasattr(conn, 'asr_audio_for_voiceprint'):
+ if not hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
conn.asr_audio_for_voiceprint.append(audio)
@@ -146,8 +151,10 @@ class ASRProvider(ASRProviderBase):
# 发送首帧音频
if conn.asr_audio and len(conn.asr_audio) > 0:
- first_audio = conn.asr_audio[-1] if conn.asr_audio else b''
- pcm_frame = self.decoder.decode(first_audio, 960) if first_audio else b''
+ first_audio = conn.asr_audio[-1] if conn.asr_audio else b""
+ pcm_frame = (
+ self.decoder.decode(first_audio, 960) if first_audio else b""
+ )
await self._send_audio_frame(pcm_frame, STATUS_FIRST_FRAME)
self.server_ready = True
logger.bind(tag=TAG).info("已发送首帧,开始识别")
@@ -176,23 +183,14 @@ class ASRProvider(ASRProviderBase):
if not self.asr_ws:
return
- audio_b64 = base64.b64encode(audio_data).decode('utf-8')
+ audio_b64 = base64.b64encode(audio_data).decode("utf-8")
frame_data = {
- "header": {
- "status": status,
- "app_id": self.app_id
- },
- "parameter": {
- "iat": self.iat_params
- },
+ "header": {"status": status, "app_id": self.app_id},
+ "parameter": {"iat": self.iat_params},
"payload": {
- "audio": {
- "audio": audio_b64,
- "sample_rate": 16000,
- "encoding": "raw"
- }
- }
+ "audio": {"audio": audio_b64, "sample_rate": 16000, "encoding": "raw"}
+ },
}
await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False))
@@ -207,11 +205,13 @@ class ASRProvider(ASRProviderBase):
try:
while self.asr_ws and not conn.stop_event.is_set():
# 获取当前连接的音频数据
- audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
+ audio_data = getattr(conn, "asr_audio_for_voiceprint", [])
try:
# 如果已发送最终帧,增加超时时间等待完整结果
timeout = 3.0 if self.last_frame_sent else 30.0
- response = await asyncio.wait_for(self.asr_ws.recv(), timeout=timeout)
+ response = await asyncio.wait_for(
+ self.asr_ws.recv(), timeout=timeout
+ )
result = json.loads(response)
logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
@@ -221,7 +221,9 @@ class ASRProvider(ASRProviderBase):
status = header.get("status", 0)
if code != 0:
- logger.bind(tag=TAG).error(f"识别错误,错误码: {code}, 消息: {header.get('message', '')}")
+ logger.bind(tag=TAG).error(
+ f"识别错误,错误码: {code}, 消息: {header.get('message', '')}"
+ )
if code in [10114, 10160]: # 连接问题
break
continue
@@ -231,52 +233,124 @@ class ASRProvider(ASRProviderBase):
text_data = payload["result"]["text"]
if text_data:
# 解码base64文本
- decoded_text = base64.b64decode(text_data).decode('utf-8')
+ decoded_text = base64.b64decode(text_data).decode("utf-8")
text_json = json.loads(decoded_text)
# 提取文本内容
- text_ws = text_json.get('ws', [])
- result_text = ''
+ text_ws = text_json.get("ws", [])
+ result_text = ""
for i in text_ws:
for j in i.get("cw", []):
w = j.get("w", "")
result_text += w
# 更新识别文本 - 实时更新策略
- if result_text and result_text.strip() not in ['', '。', '.', ',', ',']:
+ # 只检查是否为空字符串,不再过滤任何标点符号
+ # 这样可以确保所有识别到的内容,包括标点符号都能被实时更新
+ if result_text and result_text.strip():
# 实时更新:正常情况下都更新,提高响应速度
should_update = True
- # 保存最佳文本(最长的有意义文本)
- if (len(result_text) > len(self.best_text) and
- result_text.strip() not in ['?', '?', '。', '.']):
- self.best_text = result_text
- logger.bind(tag=TAG).debug(f"保存最佳文本: {self.best_text}")
+ # 保存最佳文本
+ # 1. 如果是识别完成状态或最终帧后收到的结果,优先保存
+ # 2. 否则保存最长的有意义文本
+ # 取消对标点符号的过滤,只检查是否为空
+ # 这样可以保留所有识别到的内容,包括各种标点符号
+ is_valid_text = len(result_text.strip()) > 0
- # 如果已发送最终帧,只过滤明显的无效结果
+ if (
+ self.last_frame_sent or status == 2
+ ) and is_valid_text:
+ self.best_text = result_text
+ self.has_final_result = True # 标记已收到最终结果
+ logger.bind(tag=TAG).debug(
+ f"保存最终识别结果: {self.best_text}"
+ )
+ elif (
+ len(result_text) > len(self.best_text)
+ and is_valid_text
+ and not self.has_final_result
+ ):
+ self.best_text = result_text
+ logger.bind(tag=TAG).debug(
+ f"保存中间最佳文本: {self.best_text}"
+ )
+
+ # 如果已发送最终帧,只过滤空文本
if self.last_frame_sent:
- # 最终帧后拒绝问号等明显错误的结果
- if result_text.strip() in ['?', '?', '。', '.']:
+ # 只拒绝完全空的结果
+ if not result_text.strip():
should_update = False
- logger.bind(tag=TAG).warning(f"最终帧后拒绝无效文本: {result_text}")
+ logger.bind(tag=TAG).warning(
+ f"最终帧后拒绝空文本"
+ )
if should_update:
- self.text = result_text
- logger.bind(tag=TAG).info(f"实时更新识别文本: {self.text} (最终帧已发送: {self.last_frame_sent})")
+ # 处理流式识别结果,避免简单替换导致内容丢失
+ # 1. 如果是中间状态(非最终帧后),可能需要替换为更完整的识别
+ # 2. 如果是最终帧后收到的结果,可能是对前面文本的补充
+ if self.last_frame_sent:
+ # 最终帧后收到的结果可能是标点符号等补充内容
+ # 检查是否需要合并文本而不是替换
+ # 如果当前文本是纯标点而前面已有内容,应该追加而不是替换
+ if len(
+ self.text
+ ) > 0 and result_text.strip() in [
+ "。",
+ ".",
+ "?",
+ "?",
+ "!",
+ "!",
+ ",",
+ ",",
+ ";",
+ ";",
+ ]:
+ # 对于标点符号,追加到现有文本后
+ self.text = (
+ self.text.rstrip().rstrip("。.")
+ + result_text
+ )
+ else:
+ # 其他情况保持替换逻辑
+ self.text = result_text
+ else:
+ # 中间状态替换为新的识别结果
+ self.text = result_text
+
+ logger.bind(tag=TAG).info(
+ f"实时更新识别文本: {self.text} (最终帧已发送: {self.last_frame_sent})"
+ )
# 识别完成,但如果还没发送最终帧,继续等待
if status == 2:
- logger.bind(tag=TAG).info(f"识别完成状态已到达,当前识别文本: {self.text}")
+ logger.bind(tag=TAG).info(
+ f"识别完成状态已到达,当前识别文本: {self.text}"
+ )
# 如果还没发送最终帧,继续等待
if not self.last_frame_sent:
- logger.bind(tag=TAG).info("识别完成但最终帧未发送,继续等待...")
+ logger.bind(tag=TAG).info(
+ "识别完成但最终帧未发送,继续等待..."
+ )
continue
- # 已发送最终帧且收到完成状态,使用最佳文本作为最终结果
- if self.best_text and len(self.best_text) > len(self.text):
- logger.bind(tag=TAG).info(f"使用最佳文本作为最终结果: {self.text} -> {self.best_text}")
- self.text = self.best_text
+ # 已发送最终帧且收到完成状态,使用最佳策略选择最终结果
+ # 优先使用识别完成状态下的最新结果,而不是仅仅基于长度
+ if self.best_text:
+ # 如果当前文本是在最终帧发送后或识别完成状态下收到的,优先使用
+ if (
+ self.last_frame_sent or status == 2
+ ) and self.text.strip():
+ logger.bind(tag=TAG).info(
+ f"使用完成状态下的最新识别结果: {self.text}"
+ )
+ elif len(self.best_text) > len(self.text):
+ logger.bind(tag=TAG).info(
+ f"使用更长的最佳文本作为最终结果: {self.text} -> {self.best_text}"
+ )
+ self.text = self.best_text
logger.bind(tag=TAG).info(f"获取到最终完整文本: {self.text}")
conn.reset_vad_states()
@@ -289,9 +363,13 @@ class ASRProvider(ASRProviderBase):
if self.last_frame_sent:
# 超时时也使用最佳文本
if self.best_text and len(self.best_text) > len(self.text):
- logger.bind(tag=TAG).info(f"超时,使用最佳文本: {self.text} -> {self.best_text}")
+ logger.bind(tag=TAG).info(
+ f"超时,使用最佳文本: {self.text} -> {self.best_text}"
+ )
self.text = self.best_text
- logger.bind(tag=TAG).info(f"最终帧后超时,使用结果: {self.text}")
+ logger.bind(tag=TAG).info(
+ f"最终帧后超时,使用结果: {self.text}"
+ )
break
# 如果还没发送最终帧,继续等待
continue
@@ -316,11 +394,11 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None
self.is_processing = False
if conn:
- if hasattr(conn, 'asr_audio_for_voiceprint'):
+ if hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
- if hasattr(conn, 'asr_audio'):
+ if hasattr(conn, "asr_audio"):
conn.asr_audio = []
- if hasattr(conn, 'has_valid_voice'):
+ if hasattr(conn, "has_valid_voice"):
conn.has_valid_voice = False
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
@@ -330,7 +408,7 @@ class ASRProvider(ASRProviderBase):
if self.asr_ws and self.is_processing:
try:
# 取最后一个有效的音频帧作为最后一帧数据
- last_frame = b''
+ last_frame = b""
if asr_audio_task:
last_audio = asr_audio_task[-1]
last_frame = self.decoder.decode(last_audio, 960)
@@ -338,8 +416,7 @@ class ASRProvider(ASRProviderBase):
logger.bind(tag=TAG).info("已发送最后一帧")
# 发送最终帧后,给_forward_results适当时间处理最终结果
- # 减少等待时间,提高响应速度
- await asyncio.sleep(0.1) # 从3秒减少到1秒
+ await asyncio.sleep(0.25)
logger.bind(tag=TAG).info(f"准备处理最终识别结果: {self.text}")
except Exception as e:
@@ -350,8 +427,9 @@ class ASRProvider(ASRProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
import traceback
+
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
-
+
def stop_ws_connection(self):
if self.asr_ws:
asyncio.create_task(self.asr_ws.close())
@@ -360,12 +438,14 @@ class ASRProvider(ASRProviderBase):
async def _cleanup(self, conn):
"""清理资源"""
- logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
+ logger.bind(tag=TAG).info(
+ f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}"
+ )
# 发送最后一帧
if self.asr_ws and self.is_processing:
try:
- await self._send_audio_frame(b'', STATUS_LAST_FRAME)
+ await self._send_audio_frame(b"", STATUS_LAST_FRAME)
await asyncio.sleep(0.1)
logger.bind(tag=TAG).info("已发送最后一帧")
except Exception as e:
@@ -376,6 +456,7 @@ class ASRProvider(ASRProviderBase):
self.server_ready = False
self.last_frame_sent = False
self.best_text = ""
+ self.has_final_result = False
logger.bind(tag=TAG).info("ASR状态已重置")
# 清理任务
@@ -403,11 +484,11 @@ class ASRProvider(ASRProviderBase):
# 清理连接的音频缓存
if conn:
- if hasattr(conn, 'asr_audio_for_voiceprint'):
+ if hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
- if hasattr(conn, 'asr_audio'):
+ if hasattr(conn, "asr_audio"):
conn.asr_audio = []
- if hasattr(conn, 'has_valid_voice'):
+ if hasattr(conn, "has_valid_voice"):
conn.has_valid_voice = False
logger.bind(tag=TAG).info("ASR会话清理完成")
@@ -432,11 +513,11 @@ class ASRProvider(ASRProviderBase):
self.forward_task = None
self.is_processing = False
# 清理所有连接的音频缓冲区
- if hasattr(self, '_connections'):
+ if hasattr(self, "_connections"):
for conn in self._connections.values():
- if hasattr(conn, 'asr_audio_for_voiceprint'):
+ if hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
- if hasattr(conn, 'asr_audio'):
+ if hasattr(conn, "asr_audio"):
conn.asr_audio = []
- if hasattr(conn, 'has_valid_voice'):
- conn.has_valid_voice = False
\ No newline at end of file
+ if hasattr(conn, "has_valid_voice"):
+ conn.has_valid_voice = False
From d6344bde5ea1edf3140e37c4d6ebd11fac0021e2 Mon Sep 17 00:00:00 2001
From: Chingfeng Li
Date: Fri, 24 Oct 2025 10:17:32 +0800
Subject: [PATCH 086/182] =?UTF-8?q?=E6=B7=BB=E5=8A=A0MCP=E6=B5=8B=E8=AF=95?=
=?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=8C=E6=94=AF=E6=8C=81=E8=87=AA=E5=AE=9A?=
=?UTF-8?q?=E4=B9=89=E6=B7=BB=E5=8A=A0=E7=BC=96=E8=BE=91MCP=20Tools?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/test/test_page.css | 6 +-
main/xiaozhi-server/test/test_page.html | 836 ++++++++++++++++++++++--
2 files changed, 774 insertions(+), 68 deletions(-)
diff --git a/main/xiaozhi-server/test/test_page.css b/main/xiaozhi-server/test/test_page.css
index c70c97069..bea049947 100644
--- a/main/xiaozhi-server/test/test_page.css
+++ b/main/xiaozhi-server/test/test_page.css
@@ -21,9 +21,9 @@ h1 {
}
.section {
- margin-bottom: 20px;
- padding: 15px;
- border-radius: 8px;
+ margin-bottom: 5px;
+ padding: 10px;
+ border-radius: 10px;
background-color: #f9f9f9;
}
diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html
index 879d627b3..2cf9a0ff6 100644
--- a/main/xiaozhi-server/test/test_page.html
+++ b/main/xiaozhi-server/test/test_page.html
@@ -56,6 +56,163 @@
#fileProtocolWarning button:hover {
background-color: #45a049;
}
+
+ /* MCP 工具管理样式 */
+ .mcp-tools-container {
+ display: grid;
+ gap: 12px;
+ margin-top: 10px;
+ }
+
+ .mcp-tool-card {
+ background-color: white;
+ border: 1px solid #e0e0e0;
+ border-radius: 8px;
+ padding: 15px;
+ transition: all 0.2s;
+ }
+
+ .mcp-tool-card:hover {
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+ }
+
+ .mcp-tool-card.disabled {
+ opacity: 0.6;
+ pointer-events: none;
+ }
+
+ .mcp-tool-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 10px;
+ }
+
+ .mcp-tool-name {
+ font-size: 15px;
+ font-weight: 600;
+ color: #333;
+ flex: 1;
+ }
+
+ .mcp-tool-actions {
+ display: flex;
+ gap: 6px;
+ }
+
+ .mcp-tool-description {
+ color: #666;
+ font-size: 13px;
+ line-height: 1.5;
+ margin-bottom: 8px;
+ }
+
+ .mcp-tool-info {
+ background-color: #f9f9f9;
+ border: 1px solid #e0e0e0;
+ border-radius: 4px;
+ padding: 8px;
+ font-size: 12px;
+ }
+
+ .mcp-tool-info-row {
+ display: flex;
+ gap: 15px;
+ margin-bottom: 4px;
+ }
+
+ .mcp-tool-info-label {
+ color: #999;
+ min-width: 60px;
+ }
+
+ .mcp-tool-info-value {
+ color: #333;
+ font-family: 'Courier New', monospace;
+ }
+
+ .mcp-property-item {
+ background-color: white;
+ border: 1px solid #e0e0e0;
+ border-radius: 5px;
+ padding: 12px;
+ margin-bottom: 10px;
+ }
+
+ .mcp-property-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 10px;
+ }
+
+ .mcp-property-name {
+ font-weight: 600;
+ color: #333;
+ }
+
+ .mcp-property-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+ margin-bottom: 8px;
+ }
+
+ .mcp-property-row-full {
+ margin-bottom: 8px;
+ }
+
+ .mcp-small-label {
+ display: block;
+ margin-bottom: 4px;
+ font-size: 12px;
+ color: #666;
+ }
+
+ .mcp-small-input {
+ width: 100%;
+ padding: 6px 8px;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ font-size: 13px;
+ }
+
+ .mcp-checkbox-label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ color: #666;
+ cursor: pointer;
+ }
+
+ .mcp-error {
+ background-color: #ffebee;
+ color: #c62828;
+ padding: 10px;
+ border-radius: 5px;
+ margin-bottom: 15px;
+ font-size: 14px;
+ }
+
+ .mcp-badge {
+ display: inline-block;
+ padding: 2px 8px;
+ border-radius: 12px;
+ font-size: 11px;
+ font-weight: 500;
+ margin-left: 8px;
+ }
+
+ .mcp-badge-required {
+ background-color: #ffebee;
+ color: #c62828;
+ }
+
+ .mcp-badge-optional {
+ background-color: #e3f2fd;
+ color: #1976d2;
+ }