mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Compare commits
4 commits
d1ba851b82
...
1fac05e4a2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1fac05e4a2 | ||
|
|
2dfaf44269 | ||
|
|
e41bc98a25 | ||
|
|
cef2540dc4 |
10 changed files with 412 additions and 108 deletions
43
docs/device-overrides.md
Normal file
43
docs/device-overrides.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# 按设备覆盖配置(单模块部署)
|
||||
|
||||
## 概述
|
||||
|
||||
智控台(manager-api)能给每台设备配不同的模型和提示词;只跑 xiaozhi-server 一个模块时,配置是全局的,所有设备一样。
|
||||
`data/devices.yaml` 补上这一块:连接初始化时按 `device-id` 读这台设备的覆盖项,合并进这条连接的配置。
|
||||
|
||||
## 工作原理
|
||||
|
||||
`core/utils/device_overrides.py` 在 `ConnectionHandler._initialize_components` 最开头被调用(每条连接的 config 都是深拷贝,互不影响)。
|
||||
每次连接都重读文件(几 KB),改完表让设备重连即生效,不用重启服务器。文件不存在、格式错、设备没登记、`enabled: false`、
|
||||
名字在对应配置块里不存在,都只记日志、不改配置、不抛异常。
|
||||
|
||||
## 配置
|
||||
|
||||
`data/.config.yaml`:
|
||||
|
||||
```yaml
|
||||
device_overrides_file: data/devices.yaml # 默认值,可不写
|
||||
```
|
||||
|
||||
`data/devices.yaml`(schema v1):
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
devices:
|
||||
"aa:bb:cc:dd:ee:ff": # device-id(设备 MAC,小写;大小写不敏感)
|
||||
name: 书房
|
||||
enabled: true
|
||||
brain: cascade # cascade = 原版 VAD→ASR→LLM→TTS;填 S2S 配置块里的名字 = 这台设备用语音进语音出模型
|
||||
prompt: 你是书房的语音助手。 # 非空则替换全局 prompt
|
||||
llm: null # 非空且在 LLM 配置块里存在 → 这台设备用它
|
||||
tts: null # 同上
|
||||
```
|
||||
|
||||
同一份文件也可以给前置的准入网关当白名单(`client_id` 字段给网关用,服务器不读)。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
cd main/xiaozhi-server
|
||||
pytest tests/core/utils/test_device_overrides.py -q
|
||||
```
|
||||
|
|
@ -81,6 +81,10 @@ enable_websocket_ping: false
|
|||
# > 0: 使用固定延迟(毫秒)发送,例如: 60
|
||||
tts_audio_send_delay: 0
|
||||
|
||||
# 按设备覆盖配置(单模块部署没有智控台时的差异化配置):按 device-id 从这个文件读该设备的大脑 / 提示词 / LLM / TTS,
|
||||
# 每次连接都重读,改完表设备重连即生效;文件不存在就全部用全局配置。格式见 docs/device-overrides.md
|
||||
device_overrides_file: data/devices.yaml
|
||||
|
||||
exit_commands:
|
||||
- "退出"
|
||||
- "关闭"
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ from core.utils.util import (
|
|||
)
|
||||
from typing import Dict, Any
|
||||
from collections import deque
|
||||
from core.utils.device_overrides import apply_device_overrides
|
||||
from core.utils.modules_initialize import (
|
||||
initialize_modules,
|
||||
initialize_tts,
|
||||
|
|
@ -219,6 +220,9 @@ class ConnectionHandler:
|
|||
)
|
||||
|
||||
self.device_id = self.headers.get("device-id", None)
|
||||
# 按设备覆盖(data/devices.yaml):选大脑 / 提示词 / LLM / TTS,见 docs/device-overrides.md。
|
||||
# 放在拿到 device-id 的第一时间,后面的消息处理(唤醒词、组件初始化)都能看到覆盖后的配置
|
||||
apply_device_overrides(self)
|
||||
|
||||
# 认证通过,继续处理
|
||||
self.websocket = ws
|
||||
|
|
|
|||
|
|
@ -74,7 +74,11 @@ class TTSProvider(TTSProviderBase):
|
|||
"""确保WebSocket连接可用,支持60秒内连接复用"""
|
||||
try:
|
||||
current_time = time.time()
|
||||
if self.ws and current_time - self.last_active_time < 60:
|
||||
if (
|
||||
self.ws
|
||||
and self.ws.close_code is None
|
||||
and current_time - self.last_active_time < 60
|
||||
):
|
||||
# 一分钟内才可以复用链接进行连续对话
|
||||
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
||||
return self.ws
|
||||
|
|
@ -110,10 +114,11 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.conn.client_abort:
|
||||
try:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
if self.activate_session:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
||||
|
|
@ -132,21 +137,27 @@ class TTSProvider(TTSProviderBase):
|
|||
self.reset_stream_state()
|
||||
# 初始化会话
|
||||
try:
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
self.conn.sentence_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
||||
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
# 只建连,会话等文本到达再开启
|
||||
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
|
||||
if self.activate_session:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.close(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.conn.sentence_id),
|
||||
self._ensure_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||
|
||||
elif ContentType.TEXT == message.content_type:
|
||||
if message.content_detail:
|
||||
|
|
@ -174,6 +185,17 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if not self.activate_session:
|
||||
# 本轮无文本,未开启会话,直接收尾
|
||||
self._process_before_stop_play_files()
|
||||
continue
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -194,20 +216,23 @@ class TTSProvider(TTSProviderBase):
|
|||
async def text_to_speak(self, text, _):
|
||||
"""发送文本到TTS服务进行合成"""
|
||||
try:
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning("WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
|
||||
# 过滤Markdown
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.conn.sentence_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
continue_task_message = {
|
||||
"header": {
|
||||
"action": "continue-task",
|
||||
|
|
@ -237,9 +262,6 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
# 确保连接可用
|
||||
await self._ensure_connection()
|
||||
|
||||
|
|
@ -248,6 +270,9 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
# 发送run-task消息启动会话
|
||||
run_task_message = {
|
||||
"header": {
|
||||
|
|
@ -350,9 +375,6 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
# 只处理当前活跃会话的响应
|
||||
if task_id and self.conn.sentence_id != task_id:
|
||||
if event in ["task-finished", "task-failed"]:
|
||||
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
|
||||
self.activate_session = False
|
||||
continue
|
||||
|
||||
if event == "task-started":
|
||||
|
|
@ -376,6 +398,7 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).error(
|
||||
f"TTS任务失败: {error_code} - {error_message}"
|
||||
)
|
||||
self.activate_session = False
|
||||
break
|
||||
except json.JSONDecodeError:
|
||||
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
||||
|
|
@ -392,16 +415,14 @@ class TTSProvider(TTSProviderBase):
|
|||
)
|
||||
break
|
||||
|
||||
# 连接异常时关闭WebSocket
|
||||
# 监听任务退出时关闭连接并清理引用
|
||||
finally:
|
||||
if self.ws:
|
||||
try:
|
||||
await self.ws.close()
|
||||
except:
|
||||
pass
|
||||
self.ws = None
|
||||
# 监听任务退出时清理引用
|
||||
finally:
|
||||
self.activate_session = False
|
||||
self._monitor_task = None
|
||||
|
||||
def audio_to_opus_data_stream(
|
||||
|
|
|
|||
|
|
@ -186,7 +186,11 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
|
||||
self._refresh_token()
|
||||
current_time = time.time()
|
||||
if self.ws and current_time - self.last_active_time < 10:
|
||||
if (
|
||||
self.ws
|
||||
and self.ws.close_code is None
|
||||
and current_time - self.last_active_time < 10
|
||||
):
|
||||
# 10秒内才可以复用链接进行连续对话
|
||||
self.task_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"使用已有链接..., task_id: {self.task_id}")
|
||||
|
|
@ -220,12 +224,17 @@ class TTSProvider(TTSProviderBase):
|
|||
message = self.tts_text_queue.get(timeout=1)
|
||||
|
||||
if self.conn.client_abort:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
continue
|
||||
try:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
if self.activate_session:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.task_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
||||
continue
|
||||
|
||||
# 过滤旧消息:检查sentence_id是否匹配
|
||||
if message.sentence_id != self.conn.sentence_id:
|
||||
|
|
@ -240,18 +249,24 @@ class TTSProvider(TTSProviderBase):
|
|||
self.reset_stream_state()
|
||||
# 初始化参数
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
# 只建连,会话等文本到达再开启
|
||||
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
|
||||
if self.activate_session:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.close(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.task_id),
|
||||
self._ensure_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||
|
||||
elif ContentType.TEXT == message.content_type:
|
||||
if message.content_detail:
|
||||
|
|
@ -278,6 +293,17 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if not self.activate_session:
|
||||
# 本轮无文本,未开启会话,直接收尾
|
||||
self._process_before_stop_play_files()
|
||||
continue
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.task_id),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -296,18 +322,22 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
async def text_to_speak(self, text, _):
|
||||
try:
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.task_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
run_request = {
|
||||
"header": {
|
||||
"message_id": uuid.uuid4().hex,
|
||||
|
|
@ -339,9 +369,6 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
# 建立新连接
|
||||
await self._ensure_connection()
|
||||
|
||||
|
|
@ -350,6 +377,9 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
start_request = {
|
||||
"header": {
|
||||
"message_id": uuid.uuid4().hex,
|
||||
|
|
@ -431,9 +461,6 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
# 只处理当前活跃会话的响应
|
||||
if task_id and self.task_id != task_id:
|
||||
if event_name in ["SynthesisCompleted", "TaskFailed"]:
|
||||
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
|
||||
self.activate_session = False
|
||||
continue
|
||||
|
||||
if event_name == "SynthesisStarted":
|
||||
|
|
@ -469,16 +496,15 @@ class TTSProvider(TTSProviderBase):
|
|||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
||||
)
|
||||
break
|
||||
# 连接异常时关闭WebSocket
|
||||
|
||||
# 监听任务退出时关闭连接并清理引用
|
||||
finally:
|
||||
if self.ws:
|
||||
try:
|
||||
await self.ws.close()
|
||||
except:
|
||||
pass
|
||||
self.ws = None
|
||||
# 监听任务退出时清理引用
|
||||
finally:
|
||||
self.activate_session = False
|
||||
self._monitor_task = None
|
||||
|
||||
def audio_to_opus_data_stream(
|
||||
|
|
|
|||
|
|
@ -704,3 +704,6 @@ class TTSProviderBase(ABC):
|
|||
def reset_stream_state(self):
|
||||
"""重置流式处理状态,用于会话开始时清理残留状态"""
|
||||
self._pending_prefix = ""
|
||||
# 清理编码器中未满一帧的PCM残留
|
||||
if getattr(self, "opus_encoder", None):
|
||||
self.opus_encoder.reset_state()
|
||||
|
|
|
|||
|
|
@ -220,7 +220,7 @@ class TTSProvider(TTSProviderBase):
|
|||
async def _ensure_connection(self):
|
||||
"""建立新的WebSocket连接,并启动监听任务(仅第一次)"""
|
||||
try:
|
||||
if self.ws:
|
||||
if self.ws and self.ws.close_code is None:
|
||||
if self.enable_ws_reuse:
|
||||
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
||||
return self.ws
|
||||
|
|
@ -281,12 +281,12 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.conn.client_abort:
|
||||
try:
|
||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||
if self.enable_ws_reuse:
|
||||
if self.activate_session:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.cancel_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
else:
|
||||
if not self.enable_ws_reuse:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_connection(),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -307,26 +307,29 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.FIRST:
|
||||
# 重置流式处理状态
|
||||
self.reset_stream_state()
|
||||
# 重置 opus 流式编码器跨轮残留
|
||||
if hasattr(self, "opus_encoder") and self.opus_encoder:
|
||||
self.opus_encoder.reset_state()
|
||||
# 初始化参数
|
||||
try:
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
self.conn.sentence_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
||||
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
# 只建连,会话等文本到达再开启
|
||||
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
|
||||
if self.activate_session:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.close(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.conn.sentence_id),
|
||||
self._ensure_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||
|
||||
elif ContentType.TEXT == message.content_type:
|
||||
if message.content_detail:
|
||||
|
|
@ -353,11 +356,29 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if self.activate_session:
|
||||
# 结束会话;LAST 与连接释放由监听任务在 SessionFinished 后处理
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
else:
|
||||
# 未开启会话,没有 SessionFinished 事件,需自行收尾
|
||||
self._process_before_stop_play_files()
|
||||
if not self.enable_ws_reuse:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.finish_connection(),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
||||
continue
|
||||
|
|
@ -373,21 +394,23 @@ class TTSProvider(TTSProviderBase):
|
|||
async def text_to_speak(self, text, _):
|
||||
"""发送文本到TTS服务"""
|
||||
try:
|
||||
# 建立新连接
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
|
||||
# 过滤Markdown
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.conn.sentence_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
await self.send_text(self.voice, txt, self.conn.sentence_id)
|
||||
|
||||
return
|
||||
|
|
@ -407,12 +430,11 @@ class TTSProvider(TTSProviderBase):
|
|||
# 上个会话处于激活状态时关闭上个连接新建链接
|
||||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
|
||||
# 确保连接建立
|
||||
await self._ensure_connection()
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
header = Header(
|
||||
message_type=FULL_CLIENT_REQUEST,
|
||||
|
|
@ -437,9 +459,6 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
|
||||
try:
|
||||
if self.ws:
|
||||
# 句尾替换词滑动窗口残留先发出去
|
||||
if self._pending_prefix:
|
||||
await self.text_to_speak(self._pending_prefix, None)
|
||||
header = Header(
|
||||
message_type=FULL_CLIENT_REQUEST,
|
||||
message_type_specific_flags=MsgTypeFlagWithEvent,
|
||||
|
|
|
|||
|
|
@ -127,7 +127,7 @@ class TTSProvider(TTSProviderBase):
|
|||
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
|
||||
|
||||
async def _ensure_connection(self):
|
||||
"""确保WebSocket连接可用"""
|
||||
"""建立新的WebSocket连接"""
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始建立新连接...")
|
||||
|
||||
|
|
@ -176,24 +176,14 @@ class TTSProvider(TTSProviderBase):
|
|||
self.text_seq += 1
|
||||
|
||||
if message.sentence_type == SentenceType.FIRST:
|
||||
# 初始化参数
|
||||
# 初始化参数,连接在文本到达时建立
|
||||
try:
|
||||
if not getattr(self.conn, "sentence_id", None):
|
||||
self.conn.sentence_id = uuid.uuid4().hex
|
||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
||||
|
||||
logger.bind(tag=TAG).debug("开始启动TTS会话...")
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.start_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
self.before_stop_play_files.clear()
|
||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
||||
continue
|
||||
logger.bind(tag=TAG).error(f"准备TTS状态失败: {str(e)}")
|
||||
|
||||
# 处理文本内容
|
||||
if ContentType.TEXT == message.content_type:
|
||||
|
|
@ -224,6 +214,17 @@ class TTSProvider(TTSProviderBase):
|
|||
if message.sentence_type == SentenceType.LAST:
|
||||
try:
|
||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||
# 句尾替换词滑窗残留补发
|
||||
if self._pending_prefix:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.text_to_speak(self._pending_prefix, None),
|
||||
loop=self.conn.loop,
|
||||
)
|
||||
future.result(timeout=self.tts_timeout)
|
||||
if not self.activate_session:
|
||||
# 本轮无文本,未开启会话,直接收尾
|
||||
self._process_before_stop_play_files()
|
||||
continue
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.finish_session(self.conn.sentence_id),
|
||||
loop=self.conn.loop,
|
||||
|
|
@ -242,19 +243,22 @@ class TTSProvider(TTSProviderBase):
|
|||
async def text_to_speak(self, text, _):
|
||||
"""发送文本到TTS服务进行合成"""
|
||||
try:
|
||||
if self.ws is None:
|
||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||
return
|
||||
|
||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||
|
||||
if filtered_text:
|
||||
# 使用滑动窗口匹配处理跨分片的替换词
|
||||
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
|
||||
confirmed_texts = [txt for txt in confirmed_texts if txt]
|
||||
if not confirmed_texts:
|
||||
return
|
||||
|
||||
# 有文本时才开启会话
|
||||
if not self.activate_session:
|
||||
await self.start_session(self.conn.sentence_id)
|
||||
|
||||
# 发送每个确定的文本片段
|
||||
for txt in confirmed_texts:
|
||||
if txt and self.ws:
|
||||
if self.ws:
|
||||
# 发送文本合成请求
|
||||
run_request = self._build_base_request(status=1, text=txt)
|
||||
await self.ws.send(json.dumps(run_request))
|
||||
|
|
@ -277,9 +281,6 @@ class TTSProvider(TTSProviderBase):
|
|||
if self.activate_session:
|
||||
await self.close()
|
||||
|
||||
# 设置会话激活标志
|
||||
self.activate_session = True
|
||||
|
||||
# 建立新连接
|
||||
await self._ensure_connection()
|
||||
|
||||
|
|
@ -288,10 +289,15 @@ class TTSProvider(TTSProviderBase):
|
|||
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||
|
||||
# 发送会话启动请求
|
||||
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||
self.activate_session = True
|
||||
|
||||
# 启动帧序号从1开始,避免与后续文本帧重复
|
||||
self.text_seq = 1
|
||||
start_request = self._build_base_request(status=0)
|
||||
|
||||
await self.ws.send(json.dumps(start_request))
|
||||
self.text_seq += 1
|
||||
logger.bind(tag=TAG).debug("会话启动请求已发送")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
||||
|
|
@ -412,16 +418,14 @@ class TTSProvider(TTSProviderBase):
|
|||
)
|
||||
break
|
||||
|
||||
# 链接不可复用
|
||||
# 监听任务退出时关闭连接并清理引用
|
||||
finally:
|
||||
if self.ws:
|
||||
try:
|
||||
await self.ws.close()
|
||||
except:
|
||||
pass
|
||||
self.ws = None
|
||||
# 监听任务退出时清理引用
|
||||
finally:
|
||||
self.activate_session = False
|
||||
self._monitor_task = None
|
||||
|
||||
def to_tts(self, text: str) -> list:
|
||||
|
|
|
|||
106
main/xiaozhi-server/core/utils/device_overrides.py
Normal file
106
main/xiaozhi-server/core/utils/device_overrides.py
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
"""按设备覆盖配置:单模块部署(没有智控台)时的"差异化配置"。
|
||||
|
||||
智控台(manager-api)能给每台设备配不同的模型和提示词;只跑 xiaozhi-server 一个模块时配置是全局的。这个模块补上这一块:
|
||||
连接初始化时按请求头里的 device-id 读本地 YAML,把这台设备的覆盖项合并进这条连接的 config(connection.py 每条连接都是
|
||||
深拷贝,互不影响)。每次连接都重读文件(几 KB),改完表让设备重连即生效,不用重启。
|
||||
|
||||
文件路径:config["device_overrides_file"],默认 data/devices.yaml;文件不存在 = 不覆盖。schema v1:
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
devices:
|
||||
"aa:bb:cc:dd:ee:ff": # device-id(设备 MAC,小写)
|
||||
name: 书房
|
||||
enabled: true # false 时这里不处理(准入由 server.auth 或前置网关负责)
|
||||
brain: cascade # cascade = 原版 VAD→ASR→LLM→TTS;填 S2S 配置块里的名字(OpenAIRealtime)或它的 type(openai_realtime)= 用该语音模型
|
||||
prompt: null # 非空则替换 config["prompt"]
|
||||
llm: null # 非空且在 LLM 配置块里存在 → selected_module.LLM
|
||||
tts: null # 同上,TTS
|
||||
```
|
||||
|
||||
任何错误都只记日志、不抛出:配置文件坏了不能让设备连不上。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import yaml
|
||||
|
||||
TAG = __name__
|
||||
DEFAULT_FILE = "data/devices.yaml"
|
||||
|
||||
|
||||
def load_device_overrides(path: str, device_id: str | None) -> dict | None:
|
||||
"""返回这台设备的覆盖项字典;文件不存在、格式错、没登记、被停用都返回 None。"""
|
||||
if not device_id or not path or not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
except (OSError, yaml.YAMLError):
|
||||
return None
|
||||
devices = data.get("devices") if isinstance(data, dict) else None
|
||||
if not isinstance(devices, dict):
|
||||
return None
|
||||
for key, info in devices.items():
|
||||
if str(key).lower() == str(device_id).lower():
|
||||
if not isinstance(info, dict) or info.get("enabled", True) is False:
|
||||
return None
|
||||
return info
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_s2s_name(s2s_block: dict, brain: str) -> str | None:
|
||||
"""brain 既可以写 S2S 配置块里的名字(OpenAIRealtime),也可以写它的 type(openai_realtime)。"""
|
||||
if brain in s2s_block:
|
||||
return brain
|
||||
for name, cfg in s2s_block.items():
|
||||
if isinstance(cfg, dict) and str(cfg.get("type", name)) == brain:
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def apply_device_overrides(conn) -> dict:
|
||||
"""把这台设备的覆盖项合并进 conn.config;返回实际应用了哪些(给日志 / 测试用)。"""
|
||||
applied: dict = {}
|
||||
try:
|
||||
config = conn.config
|
||||
path = config.get("device_overrides_file", DEFAULT_FILE)
|
||||
info = load_device_overrides(path, getattr(conn, "device_id", None))
|
||||
if not info:
|
||||
return applied
|
||||
selected = config.setdefault("selected_module", {})
|
||||
|
||||
brain = info.get("brain")
|
||||
if brain is not None:
|
||||
brain = str(brain).strip()
|
||||
if brain in ("", "cascade"):
|
||||
selected["S2S"] = ""
|
||||
applied["S2S"] = ""
|
||||
else:
|
||||
name = _resolve_s2s_name(config.get("S2S") or {}, brain)
|
||||
if name:
|
||||
selected["S2S"] = name
|
||||
applied["S2S"] = name
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).warning(f"设备覆盖的 brain={brain} 既不是 S2S 配置块的名字也不是其中某项的 type,忽略")
|
||||
|
||||
prompt = info.get("prompt")
|
||||
if isinstance(prompt, str) and prompt.strip():
|
||||
config["prompt"] = prompt
|
||||
applied["prompt"] = True
|
||||
|
||||
for key, section in (("llm", "LLM"), ("tts", "TTS")):
|
||||
name = info.get(key)
|
||||
if isinstance(name, str) and name.strip():
|
||||
if name in (config.get(section) or {}):
|
||||
selected[section] = name
|
||||
applied[section] = name
|
||||
else:
|
||||
conn.logger.bind(tag=TAG).warning(f"设备覆盖的 {key}={name} 不在 {section} 配置块里,忽略")
|
||||
|
||||
if applied:
|
||||
conn.logger.bind(tag=TAG).info(f"已应用设备覆盖: {applied}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
conn.logger.bind(tag=TAG).warning(f"应用设备覆盖失败,按全局配置继续: {type(e).__name__}: {e}")
|
||||
return applied
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
"""按设备覆盖(data/devices.yaml):选大脑、提示词、LLM / TTS;没登记 / 停用 / 文件坏 / 名字不存在都不改配置、不抛异常。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
from config.logger import setup_logging
|
||||
from core.utils.device_overrides import apply_device_overrides, load_device_overrides
|
||||
|
||||
LOGGER = setup_logging()
|
||||
|
||||
REG = """
|
||||
version: 1
|
||||
devices:
|
||||
"AA:BB:CC:DD:EE:01": {name: s3, client_id: "x", brain: OpenAIRealtime, prompt: "你是书房助手"}
|
||||
"aa:bb:cc:dd:ee:02": {name: p, brain: cascade, llm: OtherLLM, tts: NoSuchTTS}
|
||||
"aa:bb:cc:dd:ee:03": {name: paused, enabled: false, brain: OpenAIRealtime}
|
||||
"aa:bb:cc:dd:ee:04": {name: bad-brain, brain: Nope}
|
||||
"aa:bb:cc:dd:ee:05": {name: by-type, brain: openai_realtime}
|
||||
"""
|
||||
|
||||
|
||||
class Conn:
|
||||
def __init__(self, device_id, path):
|
||||
self.device_id = device_id
|
||||
self.logger = LOGGER
|
||||
self.config = {
|
||||
"device_overrides_file": path,
|
||||
"prompt": "全局提示词",
|
||||
"selected_module": {"LLM": "MainLLM", "TTS": "EdgeTTS", "S2S": ""},
|
||||
"S2S": {"OpenAIRealtime": {"type": "openai_realtime"}},
|
||||
"LLM": {"MainLLM": {}, "OtherLLM": {}},
|
||||
"TTS": {"EdgeTTS": {}},
|
||||
}
|
||||
|
||||
|
||||
def test_brain_prompt_and_case_insensitive_mac(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
c = Conn("aa:bb:cc:dd:ee:01", str(p))
|
||||
assert apply_device_overrides(c) == {"S2S": "OpenAIRealtime", "prompt": True}
|
||||
assert c.config["selected_module"]["S2S"] == "OpenAIRealtime" and c.config["prompt"] == "你是书房助手"
|
||||
|
||||
|
||||
def test_brain_accepts_provider_type_name(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
c = Conn("aa:bb:cc:dd:ee:05", str(p))
|
||||
assert apply_device_overrides(c) == {"S2S": "OpenAIRealtime"} # 写 type 也能解析到配置块的名字
|
||||
|
||||
|
||||
def test_cascade_and_llm_override_with_unknown_tts_ignored(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
c = Conn("aa:bb:cc:dd:ee:02", str(p))
|
||||
c.config["selected_module"]["S2S"] = "OpenAIRealtime" # 全局选了 S2S,这台设备要级联
|
||||
assert apply_device_overrides(c) == {"S2S": "", "LLM": "OtherLLM"}
|
||||
assert c.config["selected_module"] == {"LLM": "OtherLLM", "TTS": "EdgeTTS", "S2S": ""}
|
||||
assert c.config["prompt"] == "全局提示词"
|
||||
|
||||
|
||||
def test_no_change_cases(tmp_path):
|
||||
p = tmp_path / "devices.yaml"
|
||||
p.write_text(REG, encoding="utf-8")
|
||||
for dev in ("aa:bb:cc:dd:ee:03", "aa:bb:cc:dd:ee:04", "ff:ff:ff:ff:ff:ff", None):
|
||||
c = Conn(dev, str(p))
|
||||
before = copy.deepcopy(c.config)
|
||||
assert apply_device_overrides(c) == {}
|
||||
assert c.config == before
|
||||
c = Conn("aa:bb:cc:dd:ee:01", str(tmp_path / "missing.yaml"))
|
||||
assert apply_device_overrides(c) == {}
|
||||
p.write_text("{broken", encoding="utf-8")
|
||||
assert load_device_overrides(str(p), "aa:bb:cc:dd:ee:01") is None
|
||||
p.write_text("devices: [1, 2]\n", encoding="utf-8")
|
||||
assert load_device_overrides(str(p), "aa:bb:cc:dd:ee:01") is None
|
||||
Loading…
Reference in a new issue