mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Compare commits
4 commits
e0e2fa3abb
...
cc72a9b3f8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc72a9b3f8 | ||
|
|
2dfaf44269 | ||
|
|
e41bc98a25 | ||
|
|
a47790cddd |
9 changed files with 344 additions and 122 deletions
|
|
@ -7,8 +7,6 @@ from config.manage_api_client import (
|
||||||
get_server_config,
|
get_server_config,
|
||||||
get_agent_models,
|
get_agent_models,
|
||||||
get_correct_words,
|
get_correct_words,
|
||||||
DeviceNotFoundException,
|
|
||||||
DeviceBindException,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -94,13 +92,11 @@ async def get_private_config_from_api(config, device_id, client_id):
|
||||||
agent_result = results[0]
|
agent_result = results[0]
|
||||||
correct_words = results[1] if not isinstance(results[1], Exception) else None
|
correct_words = results[1] if not isinstance(results[1], Exception) else None
|
||||||
|
|
||||||
# 抛出业务异常
|
# 设备配置是必需的,不能将请求失败当成空配置继续使用公共模型。
|
||||||
if isinstance(agent_result, DeviceNotFoundException):
|
if isinstance(agent_result, Exception):
|
||||||
raise agent_result
|
|
||||||
if isinstance(agent_result, DeviceBindException):
|
|
||||||
raise agent_result
|
raise agent_result
|
||||||
|
|
||||||
private_config = agent_result if not isinstance(agent_result, Exception) else {}
|
private_config = agent_result
|
||||||
if correct_words:
|
if correct_words:
|
||||||
private_config["correct_words"] = correct_words
|
private_config["correct_words"] = correct_words
|
||||||
return private_config
|
return private_config
|
||||||
|
|
|
||||||
|
|
@ -795,7 +795,8 @@ class ConnectionHandler:
|
||||||
# 在线程池中初始化组件
|
# 在线程池中初始化组件
|
||||||
self.executor.submit(self._initialize_components)
|
self.executor.submit(self._initialize_components)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"后台初始化失败: {e}")
|
self.logger.bind(tag=TAG).error(f"后台初始化失败,关闭连接: {e}")
|
||||||
|
await self.close()
|
||||||
|
|
||||||
async def _initialize_private_config_async(self):
|
async def _initialize_private_config_async(self):
|
||||||
"""从接口异步获取差异化配置(异步版本,不阻塞主循环)"""
|
"""从接口异步获取差异化配置(异步版本,不阻塞主循环)"""
|
||||||
|
|
@ -824,10 +825,6 @@ class ConnectionHandler:
|
||||||
self.need_bind = True
|
self.need_bind = True
|
||||||
self.bind_code = e.bind_code
|
self.bind_code = e.bind_code
|
||||||
private_config = {}
|
private_config = {}
|
||||||
except Exception as e:
|
|
||||||
self.need_bind = True
|
|
||||||
self.logger.bind(tag=TAG).error(f"异步获取差异化配置失败: {e}")
|
|
||||||
private_config = {}
|
|
||||||
|
|
||||||
init_llm, init_tts, init_memory, init_intent = (
|
init_llm, init_tts, init_memory, init_intent = (
|
||||||
False,
|
False,
|
||||||
|
|
|
||||||
|
|
@ -74,7 +74,11 @@ class TTSProvider(TTSProviderBase):
|
||||||
"""确保WebSocket连接可用,支持60秒内连接复用"""
|
"""确保WebSocket连接可用,支持60秒内连接复用"""
|
||||||
try:
|
try:
|
||||||
current_time = time.time()
|
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"使用已有链接...")
|
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
||||||
return self.ws
|
return self.ws
|
||||||
|
|
@ -110,10 +114,11 @@ class TTSProvider(TTSProviderBase):
|
||||||
if self.conn.client_abort:
|
if self.conn.client_abort:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||||
asyncio.run_coroutine_threadsafe(
|
if self.activate_session:
|
||||||
self.finish_session(self.conn.sentence_id),
|
asyncio.run_coroutine_threadsafe(
|
||||||
loop=self.conn.loop,
|
self.finish_session(self.conn.sentence_id),
|
||||||
)
|
loop=self.conn.loop,
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
||||||
|
|
@ -132,21 +137,27 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.reset_stream_state()
|
self.reset_stream_state()
|
||||||
# 初始化会话
|
# 初始化会话
|
||||||
try:
|
try:
|
||||||
if not getattr(self.conn, "sentence_id", None):
|
if not getattr(self.conn, "sentence_id", None):
|
||||||
self.conn.sentence_id = uuid.uuid4().hex
|
self.conn.sentence_id = uuid.uuid4().hex
|
||||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
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(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.start_session(self.conn.sentence_id),
|
self._ensure_connection(),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result(timeout=self.tts_timeout)
|
future.result(timeout=self.tts_timeout)
|
||||||
self.before_stop_play_files.clear()
|
self.before_stop_play_files.clear()
|
||||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
if message.content_detail:
|
if message.content_detail:
|
||||||
|
|
@ -174,6 +185,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
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(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.finish_session(self.conn.sentence_id),
|
self.finish_session(self.conn.sentence_id),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
|
|
@ -194,20 +216,23 @@ class TTSProvider(TTSProviderBase):
|
||||||
async def text_to_speak(self, text, _):
|
async def text_to_speak(self, text, _):
|
||||||
"""发送文本到TTS服务进行合成"""
|
"""发送文本到TTS服务进行合成"""
|
||||||
try:
|
try:
|
||||||
if self.ws is None:
|
|
||||||
logger.bind(tag=TAG).warning("WebSocket连接不存在,终止发送文本")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 过滤Markdown
|
# 过滤Markdown
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
|
||||||
if filtered_text:
|
if filtered_text:
|
||||||
# 使用滑动窗口匹配处理跨分片的替换词
|
# 使用滑动窗口匹配处理跨分片的替换词
|
||||||
confirmed_texts, self._pending_prefix = self._match_stream_text(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:
|
for txt in confirmed_texts:
|
||||||
if txt and self.ws:
|
if self.ws:
|
||||||
continue_task_message = {
|
continue_task_message = {
|
||||||
"header": {
|
"header": {
|
||||||
"action": "continue-task",
|
"action": "continue-task",
|
||||||
|
|
@ -237,9 +262,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
if self.activate_session:
|
if self.activate_session:
|
||||||
await self.close()
|
await self.close()
|
||||||
|
|
||||||
# 设置会话激活标志
|
|
||||||
self.activate_session = True
|
|
||||||
|
|
||||||
# 确保连接可用
|
# 确保连接可用
|
||||||
await self._ensure_connection()
|
await self._ensure_connection()
|
||||||
|
|
||||||
|
|
@ -248,6 +270,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).debug("启动监听任务...")
|
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||||
|
|
||||||
|
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||||
|
self.activate_session = True
|
||||||
|
|
||||||
# 发送run-task消息启动会话
|
# 发送run-task消息启动会话
|
||||||
run_task_message = {
|
run_task_message = {
|
||||||
"header": {
|
"header": {
|
||||||
|
|
@ -350,9 +375,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
# 只处理当前活跃会话的响应
|
# 只处理当前活跃会话的响应
|
||||||
if task_id and self.conn.sentence_id != task_id:
|
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
|
continue
|
||||||
|
|
||||||
if event == "task-started":
|
if event == "task-started":
|
||||||
|
|
@ -376,6 +398,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"TTS任务失败: {error_code} - {error_message}"
|
f"TTS任务失败: {error_code} - {error_message}"
|
||||||
)
|
)
|
||||||
|
self.activate_session = False
|
||||||
break
|
break
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
||||||
|
|
@ -392,16 +415,14 @@ class TTSProvider(TTSProviderBase):
|
||||||
)
|
)
|
||||||
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
|
||||||
|
|
||||||
def audio_to_opus_data_stream(
|
def audio_to_opus_data_stream(
|
||||||
|
|
|
||||||
|
|
@ -186,7 +186,11 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
|
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
current_time = time.time()
|
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秒内才可以复用链接进行连续对话
|
# 10秒内才可以复用链接进行连续对话
|
||||||
self.task_id = uuid.uuid4().hex
|
self.task_id = uuid.uuid4().hex
|
||||||
logger.bind(tag=TAG).debug(f"使用已有链接..., task_id: {self.task_id}")
|
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)
|
message = self.tts_text_queue.get(timeout=1)
|
||||||
|
|
||||||
if self.conn.client_abort:
|
if self.conn.client_abort:
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
try:
|
||||||
asyncio.run_coroutine_threadsafe(
|
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||||
self.finish_session(self.conn.sentence_id),
|
if self.activate_session:
|
||||||
loop=self.conn.loop,
|
asyncio.run_coroutine_threadsafe(
|
||||||
)
|
self.finish_session(self.task_id),
|
||||||
continue
|
loop=self.conn.loop,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
||||||
|
continue
|
||||||
|
|
||||||
# 过滤旧消息:检查sentence_id是否匹配
|
# 过滤旧消息:检查sentence_id是否匹配
|
||||||
if message.sentence_id != self.conn.sentence_id:
|
if message.sentence_id != self.conn.sentence_id:
|
||||||
|
|
@ -240,18 +249,24 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.reset_stream_state()
|
self.reset_stream_state()
|
||||||
# 初始化参数
|
# 初始化参数
|
||||||
try:
|
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(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.start_session(self.task_id),
|
self._ensure_connection(),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result(timeout=self.tts_timeout)
|
future.result(timeout=self.tts_timeout)
|
||||||
self.before_stop_play_files.clear()
|
self.before_stop_play_files.clear()
|
||||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
if message.content_detail:
|
if message.content_detail:
|
||||||
|
|
@ -278,6 +293,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
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(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.finish_session(self.task_id),
|
self.finish_session(self.task_id),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
|
|
@ -296,18 +322,22 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
async def text_to_speak(self, text, _):
|
async def text_to_speak(self, text, _):
|
||||||
try:
|
try:
|
||||||
if self.ws is None:
|
|
||||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
|
||||||
return
|
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
|
||||||
if filtered_text:
|
if filtered_text:
|
||||||
# 使用滑动窗口匹配处理跨分片的替换词
|
# 使用滑动窗口匹配处理跨分片的替换词
|
||||||
confirmed_texts, self._pending_prefix = self._match_stream_text(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:
|
for txt in confirmed_texts:
|
||||||
if txt and self.ws:
|
if self.ws:
|
||||||
run_request = {
|
run_request = {
|
||||||
"header": {
|
"header": {
|
||||||
"message_id": uuid.uuid4().hex,
|
"message_id": uuid.uuid4().hex,
|
||||||
|
|
@ -339,9 +369,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
if self.activate_session:
|
if self.activate_session:
|
||||||
await self.close()
|
await self.close()
|
||||||
|
|
||||||
# 设置会话激活标志
|
|
||||||
self.activate_session = True
|
|
||||||
|
|
||||||
# 建立新连接
|
# 建立新连接
|
||||||
await self._ensure_connection()
|
await self._ensure_connection()
|
||||||
|
|
||||||
|
|
@ -350,6 +377,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).debug("启动监听任务...")
|
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
||||||
|
|
||||||
|
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||||
|
self.activate_session = True
|
||||||
|
|
||||||
start_request = {
|
start_request = {
|
||||||
"header": {
|
"header": {
|
||||||
"message_id": uuid.uuid4().hex,
|
"message_id": uuid.uuid4().hex,
|
||||||
|
|
@ -431,9 +461,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
# 只处理当前活跃会话的响应
|
# 只处理当前活跃会话的响应
|
||||||
if task_id and self.task_id != task_id:
|
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
|
continue
|
||||||
|
|
||||||
if event_name == "SynthesisStarted":
|
if event_name == "SynthesisStarted":
|
||||||
|
|
@ -469,16 +496,15 @@ class TTSProvider(TTSProviderBase):
|
||||||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
f"处理TTS响应时出错: {e}\n{traceback.format_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
|
||||||
|
|
||||||
def audio_to_opus_data_stream(
|
def audio_to_opus_data_stream(
|
||||||
|
|
|
||||||
|
|
@ -704,3 +704,6 @@ class TTSProviderBase(ABC):
|
||||||
def reset_stream_state(self):
|
def reset_stream_state(self):
|
||||||
"""重置流式处理状态,用于会话开始时清理残留状态"""
|
"""重置流式处理状态,用于会话开始时清理残留状态"""
|
||||||
self._pending_prefix = ""
|
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):
|
async def _ensure_connection(self):
|
||||||
"""建立新的WebSocket连接,并启动监听任务(仅第一次)"""
|
"""建立新的WebSocket连接,并启动监听任务(仅第一次)"""
|
||||||
try:
|
try:
|
||||||
if self.ws:
|
if self.ws and self.ws.close_code is None:
|
||||||
if self.enable_ws_reuse:
|
if self.enable_ws_reuse:
|
||||||
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
logger.bind(tag=TAG).debug(f"使用已有链接...")
|
||||||
return self.ws
|
return self.ws
|
||||||
|
|
@ -281,12 +281,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
if self.conn.client_abort:
|
if self.conn.client_abort:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
||||||
if self.enable_ws_reuse:
|
if self.activate_session:
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self.cancel_session(self.conn.sentence_id),
|
self.cancel_session(self.conn.sentence_id),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
else:
|
if not self.enable_ws_reuse:
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self.finish_connection(),
|
self.finish_connection(),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
|
|
@ -307,26 +307,29 @@ 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):
|
||||||
self.conn.sentence_id = uuid.uuid4().hex
|
self.conn.sentence_id = uuid.uuid4().hex
|
||||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
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(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.start_session(self.conn.sentence_id),
|
self._ensure_connection(),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result(timeout=self.tts_timeout)
|
future.result(timeout=self.tts_timeout)
|
||||||
self.before_stop_play_files.clear()
|
self.before_stop_play_files.clear()
|
||||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
logger.bind(tag=TAG).debug("TTS连接准备完成")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
elif ContentType.TEXT == message.content_type:
|
||||||
if message.content_detail:
|
if message.content_detail:
|
||||||
|
|
@ -353,11 +356,29 @@ class TTSProvider(TTSProviderBase):
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
# 句尾替换词滑窗残留补发
|
||||||
self.finish_session(self.conn.sentence_id),
|
if self._pending_prefix:
|
||||||
loop=self.conn.loop,
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
)
|
self.text_to_speak(self._pending_prefix, None),
|
||||||
future.result(timeout=self.tts_timeout)
|
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:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
||||||
continue
|
continue
|
||||||
|
|
@ -373,21 +394,23 @@ class TTSProvider(TTSProviderBase):
|
||||||
async def text_to_speak(self, text, _):
|
async def text_to_speak(self, text, _):
|
||||||
"""发送文本到TTS服务"""
|
"""发送文本到TTS服务"""
|
||||||
try:
|
try:
|
||||||
# 建立新连接
|
|
||||||
if self.ws is None:
|
|
||||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
|
||||||
return
|
|
||||||
|
|
||||||
# 过滤Markdown
|
# 过滤Markdown
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
|
||||||
if filtered_text:
|
if filtered_text:
|
||||||
# 使用滑动窗口匹配处理跨分片的替换词
|
# 使用滑动窗口匹配处理跨分片的替换词
|
||||||
confirmed_texts, self._pending_prefix = self._match_stream_text(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:
|
for txt in confirmed_texts:
|
||||||
if txt and self.ws:
|
if self.ws:
|
||||||
await self.send_text(self.voice, txt, self.conn.sentence_id)
|
await self.send_text(self.voice, txt, self.conn.sentence_id)
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|
@ -407,12 +430,11 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 上个会话处于激活状态时关闭上个连接新建链接
|
# 上个会话处于激活状态时关闭上个连接新建链接
|
||||||
if self.activate_session:
|
if self.activate_session:
|
||||||
await self.close()
|
await self.close()
|
||||||
|
|
||||||
# 设置会话激活标志
|
|
||||||
self.activate_session = True
|
|
||||||
|
|
||||||
# 确保连接建立
|
# 确保连接建立
|
||||||
await self._ensure_connection()
|
await self._ensure_connection()
|
||||||
|
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
|
||||||
|
self.activate_session = True
|
||||||
|
|
||||||
header = Header(
|
header = Header(
|
||||||
message_type=FULL_CLIENT_REQUEST,
|
message_type=FULL_CLIENT_REQUEST,
|
||||||
|
|
@ -437,9 +459,6 @@ 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,
|
||||||
|
|
|
||||||
|
|
@ -127,7 +127,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
|
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
|
||||||
|
|
||||||
async def _ensure_connection(self):
|
async def _ensure_connection(self):
|
||||||
"""确保WebSocket连接可用"""
|
"""建立新的WebSocket连接"""
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).debug("开始建立新连接...")
|
logger.bind(tag=TAG).debug("开始建立新连接...")
|
||||||
|
|
||||||
|
|
@ -176,24 +176,14 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.text_seq += 1
|
self.text_seq += 1
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
# 初始化参数
|
# 初始化参数,连接在文本到达时建立
|
||||||
try:
|
try:
|
||||||
if not getattr(self.conn, "sentence_id", None):
|
if not getattr(self.conn, "sentence_id", None):
|
||||||
self.conn.sentence_id = uuid.uuid4().hex
|
self.conn.sentence_id = uuid.uuid4().hex
|
||||||
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
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()
|
self.before_stop_play_files.clear()
|
||||||
logger.bind(tag=TAG).debug("TTS会话启动成功")
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"准备TTS状态失败: {str(e)}")
|
||||||
continue
|
|
||||||
|
|
||||||
# 处理文本内容
|
# 处理文本内容
|
||||||
if ContentType.TEXT == message.content_type:
|
if ContentType.TEXT == message.content_type:
|
||||||
|
|
@ -224,6 +214,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).debug("开始结束TTS会话...")
|
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(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self.finish_session(self.conn.sentence_id),
|
self.finish_session(self.conn.sentence_id),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
|
|
@ -242,19 +243,22 @@ class TTSProvider(TTSProviderBase):
|
||||||
async def text_to_speak(self, text, _):
|
async def text_to_speak(self, text, _):
|
||||||
"""发送文本到TTS服务进行合成"""
|
"""发送文本到TTS服务进行合成"""
|
||||||
try:
|
try:
|
||||||
if self.ws is None:
|
|
||||||
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
|
||||||
return
|
|
||||||
|
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
filtered_text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
|
||||||
if filtered_text:
|
if filtered_text:
|
||||||
# 使用滑动窗口匹配处理跨分片的替换词
|
# 使用滑动窗口匹配处理跨分片的替换词
|
||||||
confirmed_texts, self._pending_prefix = self._match_stream_text(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:
|
for txt in confirmed_texts:
|
||||||
if txt and self.ws:
|
if self.ws:
|
||||||
# 发送文本合成请求
|
# 发送文本合成请求
|
||||||
run_request = self._build_base_request(status=1, text=txt)
|
run_request = self._build_base_request(status=1, text=txt)
|
||||||
await self.ws.send(json.dumps(run_request))
|
await self.ws.send(json.dumps(run_request))
|
||||||
|
|
@ -277,9 +281,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
if self.activate_session:
|
if self.activate_session:
|
||||||
await self.close()
|
await self.close()
|
||||||
|
|
||||||
# 设置会话激活标志
|
|
||||||
self.activate_session = True
|
|
||||||
|
|
||||||
# 建立新连接
|
# 建立新连接
|
||||||
await self._ensure_connection()
|
await self._ensure_connection()
|
||||||
|
|
||||||
|
|
@ -288,10 +289,15 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).debug("启动监听任务...")
|
logger.bind(tag=TAG).debug("启动监听任务...")
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
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)
|
start_request = self._build_base_request(status=0)
|
||||||
|
|
||||||
await self.ws.send(json.dumps(start_request))
|
await self.ws.send(json.dumps(start_request))
|
||||||
|
self.text_seq += 1
|
||||||
logger.bind(tag=TAG).debug("会话启动请求已发送")
|
logger.bind(tag=TAG).debug("会话启动请求已发送")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
||||||
|
|
@ -412,16 +418,14 @@ class TTSProvider(TTSProviderBase):
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
|
|
||||||
# 链接不可复用
|
# 监听任务退出时关闭连接并清理引用
|
||||||
|
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
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
def to_tts(self, text: str) -> list:
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,12 @@
|
||||||
"""Tests for the recursive config merge in config/config_loader.py."""
|
"""Tests for configuration merging and device configuration failures."""
|
||||||
|
from unittest.mock import AsyncMock
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from config import config_loader
|
||||||
from config.config_loader import merge_configs
|
from config.config_loader import merge_configs
|
||||||
|
from config.manage_api_client import DeviceBindException, DeviceNotFoundException
|
||||||
|
|
||||||
|
|
||||||
def test_merge_simple_override():
|
def test_merge_simple_override():
|
||||||
|
|
@ -42,4 +49,53 @@ def test_merge_does_not_mutate_defaults():
|
||||||
default = {"a": {"b": 1}}
|
default = {"a": {"b": 1}}
|
||||||
custom = {"a": {"c": 2}}
|
custom = {"a": {"c": 2}}
|
||||||
merge_configs(default, custom)
|
merge_configs(default, custom)
|
||||||
assert default == {"a": {"b": 1}} # unchanged
|
assert default == {"a": {"b": 1}} # unchanged
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("error", [
|
||||||
|
httpx.ReadTimeout("agent config timed out"),
|
||||||
|
httpx.ConnectError("manager API unavailable"),
|
||||||
|
RuntimeError("API returned an error"),
|
||||||
|
DeviceNotFoundException("unknown device"),
|
||||||
|
DeviceBindException("123456"),
|
||||||
|
])
|
||||||
|
async def test_private_config_propagates_agent_errors(monkeypatch, error):
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(side_effect=error))
|
||||||
|
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(return_value=None))
|
||||||
|
|
||||||
|
with pytest.raises(type(error)) as raised:
|
||||||
|
await config_loader.get_private_config_from_api(
|
||||||
|
{"selected_module": {"ASR": "FunASR"}}, "device", "client"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert raised.value is error
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("correct_words", [None, {"小志": "小智"}])
|
||||||
|
async def test_private_config_keeps_agent_selection(monkeypatch, correct_words):
|
||||||
|
agent_config = {"selected_module": {"ASR": "DoubaoStreamASR"}}
|
||||||
|
get_models = AsyncMock(return_value=agent_config)
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", get_models)
|
||||||
|
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(return_value=correct_words))
|
||||||
|
selected = {"ASR": "FunASR"}
|
||||||
|
|
||||||
|
result = await config_loader.get_private_config_from_api(
|
||||||
|
{"selected_module": selected}, "device", "client"
|
||||||
|
)
|
||||||
|
|
||||||
|
get_models.assert_awaited_once_with("device", "client", selected)
|
||||||
|
assert result["selected_module"]["ASR"] == "DoubaoStreamASR"
|
||||||
|
assert result.get("correct_words") == correct_words
|
||||||
|
|
||||||
|
|
||||||
|
async def test_private_config_tolerates_optional_correct_words_failure(monkeypatch):
|
||||||
|
agent_config = {"selected_module": {"ASR": "DoubaoStreamASR"}}
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(return_value=agent_config))
|
||||||
|
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(side_effect=RuntimeError("unavailable")))
|
||||||
|
|
||||||
|
result = await config_loader.get_private_config_from_api(
|
||||||
|
{"selected_module": {}}, "device", "client"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result == agent_config
|
||||||
|
assert "correct_words" not in result
|
||||||
|
|
|
||||||
100
main/xiaozhi-server/tests/core/test_connection_config.py
Normal file
100
main/xiaozhi-server/tests/core/test_connection_config.py
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
"""Device config errors must not start a session with public model settings."""
|
||||||
|
import asyncio
|
||||||
|
import copy
|
||||||
|
from unittest.mock import AsyncMock, Mock
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from config import config_loader
|
||||||
|
from config.manage_api_client import DeviceBindException, DeviceNotFoundException
|
||||||
|
from core import connection
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def conn(monkeypatch):
|
||||||
|
# Exercise the real initialization methods without loading models or hardware.
|
||||||
|
conn = object.__new__(connection.ConnectionHandler)
|
||||||
|
conn.read_config_from_api = True
|
||||||
|
conn.common_config = {
|
||||||
|
"selected_module": {"ASR": "FunASR"},
|
||||||
|
"ASR": {"FunASR": {"type": "fun_local"}},
|
||||||
|
}
|
||||||
|
conn.config = copy.deepcopy(conn.common_config)
|
||||||
|
conn.headers = {"device-id": "device", "client-id": "client"}
|
||||||
|
conn.need_bind = False
|
||||||
|
conn.bind_code = None
|
||||||
|
conn.bind_completed_event = asyncio.Event()
|
||||||
|
conn.logger = Mock()
|
||||||
|
conn.logger.bind.return_value = conn.logger
|
||||||
|
conn.executor = Mock()
|
||||||
|
conn._initialize_components = Mock()
|
||||||
|
conn.close = AsyncMock()
|
||||||
|
monkeypatch.setattr(connection, "initialize_modules", Mock(return_value={}))
|
||||||
|
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(return_value=None))
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("error", [
|
||||||
|
httpx.ReadTimeout("agent config timed out"),
|
||||||
|
RuntimeError("API returned an error"),
|
||||||
|
])
|
||||||
|
async def test_config_failure_closes_without_starting_or_requesting_binding(conn, monkeypatch, error):
|
||||||
|
conn.loop = asyncio.get_running_loop()
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(side_effect=error))
|
||||||
|
|
||||||
|
await conn._background_initialize()
|
||||||
|
|
||||||
|
conn.close.assert_awaited_once_with()
|
||||||
|
conn.executor.submit.assert_not_called()
|
||||||
|
connection.initialize_modules.assert_not_called()
|
||||||
|
assert conn.need_bind is False
|
||||||
|
assert not conn.bind_completed_event.is_set()
|
||||||
|
conn.logger.info.assert_not_called()
|
||||||
|
assert any(str(error) in call.args[0] for call in conn.logger.error.call_args_list)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("error", [
|
||||||
|
DeviceNotFoundException("unknown device"), DeviceBindException("123456"),
|
||||||
|
])
|
||||||
|
async def test_binding_errors_keep_existing_binding_flow(conn, monkeypatch, error):
|
||||||
|
conn.loop = asyncio.get_running_loop()
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(side_effect=error))
|
||||||
|
|
||||||
|
await conn._background_initialize()
|
||||||
|
|
||||||
|
assert conn.need_bind is True
|
||||||
|
assert conn.bind_code == getattr(error, "bind_code", None)
|
||||||
|
conn.executor.submit.assert_called_once_with(conn._initialize_components)
|
||||||
|
conn.close.assert_not_awaited()
|
||||||
|
conn.logger.info.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_success_applies_agent_config_before_initializing(conn, monkeypatch):
|
||||||
|
conn.loop = asyncio.get_running_loop()
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(return_value={
|
||||||
|
"selected_module": {"ASR": "DoubaoStreamASR"},
|
||||||
|
"ASR": {"DoubaoStreamASR": {"type": "doubao_stream"}},
|
||||||
|
}))
|
||||||
|
|
||||||
|
await conn._background_initialize()
|
||||||
|
|
||||||
|
assert conn.config["selected_module"]["ASR"] == "DoubaoStreamASR"
|
||||||
|
assert conn.need_bind is False
|
||||||
|
assert conn.bind_completed_event.is_set()
|
||||||
|
conn.executor.submit.assert_called_once_with(conn._initialize_components)
|
||||||
|
conn.close.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_local_config_does_not_request_agent_config(conn, monkeypatch):
|
||||||
|
conn.read_config_from_api = False
|
||||||
|
get_models = AsyncMock()
|
||||||
|
monkeypatch.setattr(config_loader, "get_agent_models", get_models)
|
||||||
|
|
||||||
|
await conn._background_initialize()
|
||||||
|
|
||||||
|
get_models.assert_not_awaited()
|
||||||
|
assert conn.config == conn.common_config
|
||||||
|
assert conn.bind_completed_event.is_set()
|
||||||
|
conn.executor.submit.assert_called_once_with(conn._initialize_components)
|
||||||
|
conn.close.assert_not_awaited()
|
||||||
Loading…
Reference in a new issue