Compare commits

...

4 commits

Author SHA1 Message Date
zhenglieAllen
935f0f1136
Merge b0cc1dc0d1 into 2dfaf44269 2026-11-13 16:29:12 +08:00
wengzh
2dfaf44269
Merge pull request #3559 from xinnan-tech/py-tts-session
Some checks failed
Tests / Java (manager-api) (push) Failing after 41s
Tests / Vue (manager-web) (push) Successful in 11m51s
Tests / Python (xiaozhi-server) (push) Successful in 13m37s
fix(tts): 流式 TTS 会话延迟到首个有效文本开启,修复慢 LLM 场景合成结果为空
2026-11-13 16:13:40 +08:00
Sakura-RanChen
e41bc98a25 fix(tts): 流式 TTS 会话延迟到首个有效文本开启,修复慢 LLM 场景合成结果为空 2026-11-13 10:10:20 +08:00
Allen
b0cc1dc0d1 fix(tts): 恢复 index_stream/minimax 的重试并修正失败日志
现象:
1. TTS 合成失败时不会重试,接口只试一次就放弃;
2. 失败反而打出「语音生成成功」,真正的「语音生成失败」分支永远走不到。

原因:
to_tts_single_stream 里 max_repeat_time 初值 5,只在 except 分支里减 1(5→4),
于是 `if max_repeat_time > 0` 恒为真;而 text_to_speak 内部把异常吃掉、
自己不抛也不返回结果,调用方无从判断成败。

改法:
- text_to_speak 返回 (是否成功, 是否已推送音频帧),失败路径不再自己塞 LAST;
- to_tts_single_stream 改成真正的重试循环(最多 5 次),成功/失败日志按实际
  结果打印;
- 音频一旦推给设备就不再重试,避免同一句播两遍;句首标记用 _tts_first_sent
  保证一句话只发一次;
- LAST 收尾标记改由调用方在重试耗尽后统一发一次,重试成功的音频不会排在
  LAST 后面;
- 去掉 finally 里的 return,异常不再被吞掉。

测试:
新增 tests/core/providers/tts/test_stream_retry.py,覆盖两个 provider 的
重试次数、成功/失败日志、已推音频不重试、LAST 只发一次等场景;
修复前 10 个用例失败,修复后全部通过。
2026-11-07 22:45:25 +08:00
8 changed files with 436 additions and 146 deletions

View file

@ -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(

View file

@ -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(

View file

@ -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()

View file

@ -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,

View file

@ -36,6 +36,9 @@ class TTSProvider(TTSProviderBase):
# PCM缓冲区
self.pcm_buffer = bytearray()
# 一句话只发一次句首标记,重试时不能重复发
self._tts_first_sent = False
def tts_text_priority_thread(self):
"""流式文本处理线程"""
while not self.conn.stop_event.is_set():
@ -90,35 +93,60 @@ class TTSProvider(TTSProviderBase):
self._process_before_stop_play_files()
def to_tts_single_stream(self, text, is_last=False):
original_text = text
try:
max_repeat_time = 5
original_text = text
text = MarkdownCleaner.clean_markdown(text)
if self._correct_words_pattern:
text = self._correct_words_pattern.sub(lambda m: self.correct_words[m.group(0)], text)
try:
asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {original_text},错误: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
# 原来的写法只试一次,而且失败后 max_repeat_time 只减 1(5→4),
# 于是 "max_repeat_time > 0" 恒为真 —— 失败也照样打「语音生成成功」。
max_repeat_time = 5
succeeded = False
attempt = 0
self._tts_first_sent = False
for attempt in range(1, max_repeat_time + 1):
error = None
try:
ok, audio_sent = asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
ok, audio_sent = False, False
error = e
if ok:
succeeded = True
break
if audio_sent:
# 音频已经推给设备了,再试一次同一句会被播两遍
logger.bind(tag=TAG).warning(
f"语音生成失败: {original_text},已推送音频,不再重试"
)
break
suffix = f",错误: {error}" if error else ""
logger.bind(tag=TAG).warning(
f"语音生成失败{attempt}次: {original_text}{suffix}"
)
if succeeded:
logger.bind(tag=TAG).info(
f"语音生成成功: {original_text},重试{5 - max_repeat_time}次"
f"语音生成成功: {original_text},重试{attempt - 1}次"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {original_text},请检查网络或服务是否正常"
)
# 收尾标记只在这里发一次。text_to_speak 失败时不再自己塞 LAST,
# 否则重试成功的音频会排在 LAST 之后,设备根本听不到。
self.tts_audio_queue.put((SentenceType.LAST, [], None))
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
finally:
return None
async def text_to_speak(self, text, is_last):
"""流式处理TTS音频,每句只推送一次音频列表"""
"""流式处理TTS音频,每句只推送一次音频列表
Returns:
tuple[bool, bool]: (是否合成成功, 是否已经推送过音频帧)
音频一旦推给设备就不能重试,否则同一句会被播两遍。
"""
payload = {"text": text, "character": self.voice}
frame_bytes = int(
@ -128,6 +156,7 @@ class TTSProvider(TTSProviderBase):
/ 1000
* 2
) # 16-bit = 2 bytes
audio_sent = False
try:
async with aiohttp.ClientSession() as session:
async with session.post(
@ -138,11 +167,12 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).error(
f"TTS请求失败: {resp.status}, {await resp.text()}"
)
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return
return False, False
self.pcm_buffer.clear()
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
if not self._tts_first_sent:
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
self._tts_first_sent = True
# 处理音频流数据
async for chunk in resp.content.iter_any():
@ -161,6 +191,7 @@ class TTSProvider(TTSProviderBase):
end_of_stream=False,
callback=self.handle_opus
)
audio_sent = True
# flush 剩余不足一帧的数据
if self.pcm_buffer:
@ -170,14 +201,16 @@ class TTSProvider(TTSProviderBase):
callback=self.handle_opus
)
self.pcm_buffer.clear()
audio_sent = True
# 如果是最后一段,输出音频获取完毕
if is_last:
self._process_before_stop_play_files()
return True, audio_sent
except Exception as e:
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return False, audio_sent
def audio_to_pcm_data_stream(
self, audio_file_path, callback=None

View file

@ -85,6 +85,9 @@ class TTSProvider(TTSProviderBase):
# PCM缓冲区
self.pcm_buffer = bytearray()
# 一句话只发一次句首标记,重试时不能重复发
self._tts_first_sent = False
async def open_audio_channels(self, conn):
"""初始化音频通道,并根据conn.sample_rate更新配置"""
# 调用父类方法
@ -146,35 +149,60 @@ class TTSProvider(TTSProviderBase):
self._process_before_stop_play_files()
def to_tts_single_stream(self, text, is_last=False):
original_text = text
try:
max_repeat_time = 5
original_text = text
text = MarkdownCleaner.clean_markdown(text)
if self._correct_words_pattern:
text = self._correct_words_pattern.sub(lambda m: self.correct_words[m.group(0)], text)
try:
asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {original_text},错误: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
# 原来的写法只试一次,而且失败后 max_repeat_time 只减 1(5→4),
# 于是 "max_repeat_time > 0" 恒为真 —— 失败也照样打「语音生成成功」。
max_repeat_time = 5
succeeded = False
attempt = 0
self._tts_first_sent = False
for attempt in range(1, max_repeat_time + 1):
error = None
try:
ok, audio_sent = asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
ok, audio_sent = False, False
error = e
if ok:
succeeded = True
break
if audio_sent:
# 音频已经推给设备了,再试一次同一句会被播两遍
logger.bind(tag=TAG).warning(
f"语音生成失败: {original_text},已推送音频,不再重试"
)
break
suffix = f",错误: {error}" if error else ""
logger.bind(tag=TAG).warning(
f"语音生成失败{attempt}次: {original_text}{suffix}"
)
if succeeded:
logger.bind(tag=TAG).info(
f"语音生成成功: {original_text},重试{5 - max_repeat_time}次"
f"语音生成成功: {original_text},重试{attempt - 1}次"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {original_text},请检查网络或服务是否正常"
)
# 收尾标记只在这里发一次。text_to_speak 失败时不再自己塞 LAST,
# 否则重试成功的音频会排在 LAST 之后,设备根本听不到。
self.tts_audio_queue.put((SentenceType.LAST, [], None))
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
finally:
return None
async def text_to_speak(self, text, is_last):
"""流式处理TTS音频,每句只推送一次音频列表"""
"""流式处理TTS音频,每句只推送一次音频列表
Returns:
tuple[bool, bool]: (是否合成成功, 是否已经推送过音频帧)
音频一旦推给设备就不能重试,否则同一句会被播两遍。
"""
payload = {
"model": self.model,
"text": text,
@ -195,6 +223,7 @@ class TTSProvider(TTSProviderBase):
/ 1000
* 2
) # 16-bit = 2 bytes
audio_sent = False
try:
async with aiohttp.ClientSession() as session:
async with session.post(
@ -208,11 +237,12 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).error(
f"TTS请求失败: {resp.status}, {await resp.text()}"
)
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return
return False, False
self.pcm_buffer.clear()
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
if not self._tts_first_sent:
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
self._tts_first_sent = True
# 处理音频流数据
buffer = b""
@ -246,8 +276,7 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).error(
f"TTS请求失败, 错误码:{status_code}, 错误消息:{status_msg}"
)
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return
return False, audio_sent
status = data.get("data", {}).get("status", 1)
audio_hex = data.get("data", {}).get("audio")
@ -268,6 +297,7 @@ class TTSProvider(TTSProviderBase):
self.opus_encoder.encode_pcm_to_opus_stream(
frame, end_of_stream=False, callback=self.handle_opus
)
audio_sent = True
# flush 剩余不足一帧的数据
if self.pcm_buffer:
@ -277,14 +307,16 @@ class TTSProvider(TTSProviderBase):
callback=self.handle_opus,
)
self.pcm_buffer.clear()
audio_sent = True
# 如果是最后一段,输出音频获取完毕
if is_last:
self._process_before_stop_play_files()
return True, audio_sent
except Exception as e:
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return False, audio_sent
async def close(self):
"""资源清理"""

View file

@ -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:

View file

@ -0,0 +1,152 @@
"""流式 TTS 的重试:失败要真的重试,日志也不能把失败写成成功。
index_stream / minimax_httpstream 原来的 to_tts_single_stream 只试一次;
失败后 max_repeat_time 只减 1(5→4),于是 `if max_repeat_time > 0` 恒为真,
失败也照样打「语音生成成功」,真正的「语音生成失败」分支永远走不到。
"""
import queue
from contextlib import contextmanager
import pytest
from loguru import logger
from core.providers.tts import index_stream, minimax_httpstream
from core.providers.tts.dto.dto import SentenceType
PROVIDERS = [index_stream.TTSProvider, minimax_httpstream.TTSProvider]
# 日志里区分成功/失败的固定文案
SUCCESS_LOG = "语音生成成功"
FAILURE_LOG = "请检查网络或服务是否正常"
def _make_provider(cls):
"""只填 to_tts_single_stream 用得到的字段。
绕开 __init__:它会去建 opus 编码器,而编解码依赖系统里的 libopus,
单测里根本用不上。
"""
provider = object.__new__(cls)
provider.tts_audio_queue = queue.Queue()
provider.correct_words = {}
provider._correct_words_pattern = None
provider._tts_first_sent = False
return provider
@contextmanager
def _capture_logs():
"""抓 loguru 的输出。"""
messages = []
handler_id = logger.add(
lambda msg: messages.append(str(msg)), level="DEBUG", format="{message}"
)
try:
yield messages
finally:
logger.remove(handler_id)
def _drain(provider):
items = []
while not provider.tts_audio_queue.empty():
items.append(provider.tts_audio_queue.get())
return items
def _stub(provider, results):
"""把 text_to_speak 换成按 results 依次返回的桩,并记录调用次数。
results 里的每一项要么是 (ok, audio_sent),要么是 Exception(直接抛出)。
"""
calls = []
async def fake_text_to_speak(text, is_last):
calls.append(text)
result = results[min(len(calls) - 1, len(results) - 1)]
if isinstance(result, Exception):
raise result
return result
provider.text_to_speak = fake_text_to_speak
return calls
@pytest.mark.parametrize("cls", PROVIDERS)
def test_transient_failure_is_retried(cls):
"""前两次失败、第三次成功:必须真的重试到成功。"""
provider = _make_provider(cls)
calls = _stub(provider, [(False, False), (False, False), (True, True)])
with _capture_logs() as messages:
provider.to_tts_single_stream("今天天气怎么样")
assert len(calls) == 3, "失败后应该重试,而不是只试一次"
assert any(SUCCESS_LOG in m for m in messages), "重试成功后应该打「语音生成成功」"
assert not any(FAILURE_LOG in m for m in messages), "最终成功了不该再打「语音生成失败」"
@pytest.mark.parametrize("cls", PROVIDERS)
def test_failure_is_logged_as_failure(cls):
"""一直失败:日志必须是失败,不能反着写成成功。"""
provider = _make_provider(cls)
calls = _stub(provider, [(False, False)])
with _capture_logs() as messages:
provider.to_tts_single_stream("今天天气怎么样")
assert len(calls) == 5, "最多重试 5 次"
assert any(FAILURE_LOG in m for m in messages), "失败必须打「语音生成失败」"
assert not any(SUCCESS_LOG in m for m in messages), "失败不能打「语音生成成功」"
@pytest.mark.parametrize("cls", PROVIDERS)
def test_exception_is_retried_and_logged_as_failure(cls):
"""text_to_speak 抛异常时同样要重试,并且按失败记账。"""
provider = _make_provider(cls)
calls = _stub(provider, [RuntimeError("连接超时")])
with _capture_logs() as messages:
provider.to_tts_single_stream("今天天气怎么样")
assert len(calls) == 5
assert any(FAILURE_LOG in m for m in messages)
assert not any(SUCCESS_LOG in m for m in messages)
@pytest.mark.parametrize("cls", PROVIDERS)
def test_no_retry_once_audio_was_pushed(cls):
"""音频已经推给设备就不能再试,否则同一句会被播两遍。"""
provider = _make_provider(cls)
calls = _stub(provider, [(False, True)])
with _capture_logs() as messages:
provider.to_tts_single_stream("今天天气怎么样")
assert len(calls) == 1, "音频已经推出去就不该重试"
assert any(FAILURE_LOG in m for m in messages)
@pytest.mark.parametrize("cls", PROVIDERS)
def test_last_marker_sent_once_after_retries_exhausted(cls):
"""失败收尾的 LAST 标记只发一次,不能每次重试都发。"""
provider = _make_provider(cls)
_stub(provider, [(False, False)])
provider.to_tts_single_stream("今天天气怎么样")
items = _drain(provider)
lasts = [i for i in items if i[0] is SentenceType.LAST]
assert len(lasts) == 1, f"LAST 标记应该只发一次,实际 {len(lasts)} 次"
@pytest.mark.parametrize("cls", PROVIDERS)
def test_no_last_marker_when_retry_succeeds(cls):
"""重试成功时不能发 LAST,否则成功的音频会排在 LAST 后面听不到。"""
provider = _make_provider(cls)
_stub(provider, [(False, False), (True, True)])
provider.to_tts_single_stream("今天天气怎么样")
items = _drain(provider)
assert not [i for i in items if i[0] is SentenceType.LAST]