Compare commits

..

1 commit

Author SHA1 Message Date
Zhengyang Chen
e0e2fa3abb
Merge a47790cddd into 4b1a54a41c 2026-11-11 07:42:44 +02:00
5 changed files with 108 additions and 181 deletions

View file

@ -74,11 +74,7 @@ class TTSProvider(TTSProviderBase):
"""确保WebSocket连接可用,支持60秒内连接复用"""
try:
current_time = time.time()
if (
self.ws
and self.ws.close_code is None
and current_time - self.last_active_time < 60
):
if self.ws and current_time - self.last_active_time < 60:
# 一分钟内才可以复用链接进行连续对话
logger.bind(tag=TAG).debug(f"使用已有链接...")
return self.ws
@ -114,11 +110,10 @@ class TTSProvider(TTSProviderBase):
if self.conn.client_abort:
try:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
if self.activate_session:
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
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)}")
@ -137,27 +132,21 @@ 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连接(暂不开启会话)...")
if self.activate_session:
future = asyncio.run_coroutine_threadsafe(
self.close(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
logger.bind(tag=TAG).debug("开始启动TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self._ensure_connection(),
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连接准备完成")
logger.bind(tag=TAG).debug("TTS会话启动成功")
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:
if message.content_detail:
@ -185,17 +174,6 @@ 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,
@ -216,23 +194,20 @@ 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 self.ws:
if txt and self.ws:
continue_task_message = {
"header": {
"action": "continue-task",
@ -262,6 +237,9 @@ class TTSProvider(TTSProviderBase):
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 确保连接可用
await self._ensure_connection()
@ -270,9 +248,6 @@ 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": {
@ -375,6 +350,9 @@ 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":
@ -398,7 +376,6 @@ 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消息")
@ -415,14 +392,16 @@ class TTSProvider(TTSProviderBase):
)
break
# 监听任务退出时关闭连接并清理引用
finally:
# 连接异常时关闭WebSocket
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,11 +186,7 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
self._refresh_token()
current_time = time.time()
if (
self.ws
and self.ws.close_code is None
and current_time - self.last_active_time < 10
):
if self.ws 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}")
@ -224,17 +220,12 @@ class TTSProvider(TTSProviderBase):
message = self.tts_text_queue.get(timeout=1)
if self.conn.client_abort:
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
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
continue
# 过滤旧消息:检查sentence_id是否匹配
if message.sentence_id != self.conn.sentence_id:
@ -249,24 +240,18 @@ class TTSProvider(TTSProviderBase):
self.reset_stream_state()
# 初始化参数
try:
# 只建连,会话等文本到达再开启
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)
logger.bind(tag=TAG).debug("开始启动TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self._ensure_connection(),
self.start_session(self.task_id),
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)}")
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
continue
elif ContentType.TEXT == message.content_type:
if message.content_detail:
@ -293,17 +278,6 @@ 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,
@ -322,22 +296,18 @@ 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 self.ws:
if txt and self.ws:
run_request = {
"header": {
"message_id": uuid.uuid4().hex,
@ -369,6 +339,9 @@ class TTSProvider(TTSProviderBase):
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 建立新连接
await self._ensure_connection()
@ -377,9 +350,6 @@ 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,
@ -461,6 +431,9 @@ 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":
@ -496,15 +469,16 @@ class TTSProvider(TTSProviderBase):
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
)
break
# 监听任务退出时关闭连接并清理引用
finally:
# 连接异常时关闭WebSocket
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,6 +704,3 @@ 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 and self.ws.close_code is None:
if self.ws:
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.activate_session:
if self.enable_ws_reuse:
asyncio.run_coroutine_threadsafe(
self.cancel_session(self.conn.sentence_id),
loop=self.conn.loop,
)
if not self.enable_ws_reuse:
else:
asyncio.run_coroutine_threadsafe(
self.finish_connection(),
loop=self.conn.loop,
@ -307,29 +307,26 @@ 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连接(暂不开启会话)...")
if self.activate_session:
future = asyncio.run_coroutine_threadsafe(
self.close(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
logger.bind(tag=TAG).debug("开始启动TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self._ensure_connection(),
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连接准备完成")
logger.bind(tag=TAG).debug("TTS会话启动成功")
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:
if message.content_detail:
@ -356,29 +353,11 @@ 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 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)
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
except Exception as e:
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
continue
@ -394,23 +373,21 @@ 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 self.ws:
if txt and self.ws:
await self.send_text(self.voice, txt, self.conn.sentence_id)
return
@ -430,11 +407,12 @@ 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,
@ -459,6 +437,9 @@ 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

@ -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,14 +176,24 @@ 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)}")
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
continue
# 处理文本内容
if ContentType.TEXT == message.content_type:
@ -214,17 +224,6 @@ 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,
@ -243,22 +242,19 @@ 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 self.ws:
if txt and self.ws:
# 发送文本合成请求
run_request = self._build_base_request(status=1, text=txt)
await self.ws.send(json.dumps(run_request))
@ -281,6 +277,9 @@ class TTSProvider(TTSProviderBase):
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 建立新连接
await self._ensure_connection()
@ -289,15 +288,10 @@ 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)}")
@ -418,14 +412,16 @@ 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: