Compare commits

...

2 commits

Author SHA1 Message Date
zhenglieAllen
bdcf68feb9
Merge b0cc1dc0d1 into 61a8c04477 2026-11-16 14:56:27 +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
3 changed files with 255 additions and 38 deletions

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

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