enable streamable tts

This commit is contained in:
xiehao.0527 2025-06-20 17:14:30 +08:00
parent 0795b5de35
commit 8cc41d9547
4 changed files with 296 additions and 117 deletions

View file

@ -49,7 +49,7 @@ async def check_direct_exit(conn, text):
async def analyze_intent_with_llm(conn, text): async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图""" """使用LLM分析用户意图"""
if not hasattr(conn, "intent") or not conn.intent: if not hasattr(conn, "intent") or not conn.intent:
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化") conn.logger.bind(tag=TAG).error("意图识别服务未初始化")
return None return None
# 对话历史记录 # 对话历史记录

View file

@ -34,7 +34,8 @@ emoji_map = {
async def sendAudioMessage(conn, sentenceType, audios, text): async def sendAudioMessage(conn, sentenceType, audios, text):
# 发送句子开始消息 # 发送句子开始消息
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") audio_len = len(audios)
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {audio_len}, {text}")
if text is not None: if text is not None:
emotion = analyze_emotion(text) emotion = analyze_emotion(text)
emoji = emoji_map.get(emotion, "🙂") # 默认使用笑脸 emoji = emoji_map.get(emotion, "🙂") # 默认使用笑脸

View file

@ -101,7 +101,7 @@ class ASRProvider(ASRProviderBase):
# 发送当前音频数据 # 发送当前音频数据
if self.asr_ws and self.is_processing: if self.asr_ws and self.is_processing:
try: try:
logger.bind(tag=TAG).info(f"Append audio data") logger.bind(tag=TAG).debug(f"Append audio data")
pcm_frame = self.decode_opus(conn.asr_audio) pcm_frame = self.decode_opus(conn.asr_audio)
await self._send_audio_chunk(b''.join(pcm_frame),False if have_voice else True) await self._send_audio_chunk(b''.join(pcm_frame),False if have_voice else True)
conn.asr_audio.clear() conn.asr_audio.clear()
@ -121,7 +121,7 @@ class ASRProvider(ASRProviderBase):
} }
audio_event["type"] = "input_audio_buffer.commit" if completed else "input_audio_buffer.append" audio_event["type"] = "input_audio_buffer.commit" if completed else "input_audio_buffer.append"
await self.asr_ws.send(json.dumps(audio_event)) await self.asr_ws.send(json.dumps(audio_event))
logger.bind(tag=TAG).info(f"Sent audio chunk, size: {len(pcm_data)} , completed: {completed}") logger.bind(tag=TAG).debug(f"Sent audio chunk, size: {len(pcm_data)} , completed: {completed}")
def _create_stream_start_msg(self) -> dict: def _create_stream_start_msg(self) -> dict:
"""创建流式识别开始的请求消息,具体格式需参考火山引擎文档""" """创建流式识别开始的请求消息,具体格式需参考火山引擎文档"""
@ -150,7 +150,7 @@ class ASRProvider(ASRProviderBase):
try: try:
message = await self.asr_ws.recv() message = await self.asr_ws.recv()
event = json.loads(message) event = json.loads(message)
logger.bind(tag=TAG).info(f"Received ASR result: {event}") logger.bind(tag=TAG).debug(f"Received ASR result: {event}")
# 解析火山引擎流式 ASR 的响应格式 # 解析火山引擎流式 ASR 的响应格式
# 以下为示例,具体字段需要参考文档 # 以下为示例,具体字段需要参考文档
@ -171,7 +171,7 @@ class ASRProvider(ASRProviderBase):
self.text = final_transcript # 确保使用最终结果 self.text = final_transcript # 确保使用最终结果
conn.reset_vad_states() conn.reset_vad_states()
await self.handle_voice_stop(conn, None) await self.handle_voice_stop(conn, None)
# self.text = "" # 清空 self.text = "" # 清空
# await self.stop_ws_connection() # 收到完成后可以考虑关闭连接 # await self.stop_ws_connection() # 收到完成后可以考虑关闭连接
break # 结束接收任务 break # 结束接收任务
elif message_type == 'error': # 假设的错误类型 elif message_type == 'error': # 假设的错误类型
@ -196,23 +196,11 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False self.is_processing = False
# self.text = "" # 确保文本清空 # self.text = "" # 确保文本清空
async def stop_ws_connection(self): def stop_ws_connection(self):
logger.bind(tag=TAG).info("Stopping ASR WebSocket connection...") logger.bind(tag=TAG).info("Stopping ASR WebSocket connection...")
self.is_processing = False # 停止处理标志
if self.forward_task:
self.forward_task.cancel()
try:
await self.forward_task
except asyncio.CancelledError:
logger.bind(tag=TAG).info("ASR forward task cancelled.")
self.forward_task = None
if self.asr_ws: if self.asr_ws:
try: try:
# 发送结束流的信令,如果火山引擎需要 asyncio.create_task(self.asr_ws.close())
end_event = {"type": "input_audio_buffer.commit"}
await self.asr_ws.send(json.dumps(end_event))
await self.asr_ws.close()
logger.bind(tag=TAG).info("ASR WebSocket connection closed successfully.") logger.bind(tag=TAG).info("ASR WebSocket connection closed successfully.")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"Error closing ASR WebSocket: {e}") logger.bind(tag=TAG).error(f"Error closing ASR WebSocket: {e}")
@ -221,70 +209,6 @@ class ASRProvider(ASRProviderBase):
self.audio_buffer.clear() self.audio_buffer.clear()
# self.text = "" # 确保文本清空 # self.text = "" # 确保文本清空
async def _receive_messages(self, client) -> Optional[str]:
resp_msg = ""
while True:
message = await client.recv()
event = json.loads(message)
logger.bind(tag=TAG).debug(f"received raw message: {message}")
message_type = event.get("type")
if message_type == 'conversation.item.input_audio_transcription.completed':
logger.bind(tag=TAG).debug(f"responsed message: {resp_msg}")
return resp_msg
elif message_type == 'conversation.item.input_audio_transcription.result':
resp_msg += event.get("transcript")
async def _send_request(
self, audio_data: List[bytes], segment_size: int
) -> Optional[str]:
"""Send request to Volc LLM gateway ASR service."""
try:
auth_header = {"Authorization": f"Bearer {self.api_key}"}
logger.bind(tag=TAG).debug(f"ASR 参数: {self.ws_url} {auth_header} ")
async with websockets.connect(
self.ws_url, additional_headers=auth_header
) as websocket:
# Prepare request data
create_session_msg = self._create_session_msg()
# Send header and metadata
# full_client_request
await websocket.send(create_session_msg)
for _, (chunk, last) in enumerate(
self.slice_data(audio_data, segment_size), 1
):
base64_audio = base64.b64encode(chunk).decode("utf-8")
if last:
# 最后一个包,支持commit
ws_event = {
"audio": base64_audio,
"type": "input_audio_buffer.append"
}
else:
ws_event = {
"type": "input_audio_buffer.append",
"audio": base64_audio
}
# Send audio data
await websocket.send(json.dumps(ws_event))
# Send commit event
ws_event = {
"type": "input_audio_buffer.commit"
}
await websocket.send(json.dumps(ws_event))
# Receive response
return await self._receive_messages(websocket)
except Exception as e:
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
return None
@staticmethod @staticmethod
def slice_data(data: bytes, chunk_size: int) -> (list, bool): def slice_data(data: bytes, chunk_size: int) -> (list, bool):
""" """
@ -321,5 +245,14 @@ class ASRProvider(ASRProviderBase):
async def close(self): async def close(self):
"""资源清理方法""" """资源清理方法"""
await self.stop_ws_connection() if self.asr_ws:
logger.bind(tag=TAG).info("ASRProvider closed.") await self.asr_ws.close()
self.asr_ws = None
if self.forward_task:
self.forward_task.cancel()
try:
await self.forward_task
except asyncio.CancelledError:
pass
self.forward_task = None
self.is_processing = False

View file

@ -1,7 +1,17 @@
import requests import asyncio
import base64
import json
import uuid
import queue
import websockets
from core.utils import opus_encoder_utils
from core.utils.util import check_model_key from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase from core.providers.tts.base import TTSProviderBase
from core.utils.tts import MarkdownCleaner
from config.logger import setup_logging from config.logger import setup_logging
from core.handle.abortHandle import handleAbortMessage
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -10,49 +20,284 @@ logger = setup_logging()
class TTSProvider(TTSProviderBase): class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file): def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file) super().__init__(config, delete_audio_file)
self.interface_type = InterfaceType.DUAL_STREAM
self.api_key = config.get("api_key") self.api_key = config.get("api_key")
self.model_name = config.get("model_name") self.model_name = config.get("model_name")
self.output_dir = config.get("output_dir")
self.host = config.get("host") self.host = config.get("host")
if self.host is None: if self.host is None:
self.host = "ai-gateway.vei.volces.com" self.host = "ai-gateway.vei.volces.com"
if self.output_dir is None:
self.output_dir = "tmp/"
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.base_url = f"https://{self.host}/v1/audio/speech" self.ws_url = f"wss://{self.host}/v1/realtime?model={self.model_name}"
if config.get("private_voice"): if config.get("private_voice"):
self.voice = config.get("private_voice") self.voice = config.get("private_voice")
else: else:
self.voice = config.get("voice", "alloy") self.voice = config.get("voice", "alloy")
self.audio_file_type = config.get("format", "wav") self.audio_file_type = config.get("format", "pcm") # 流式接口通常使用 pcm
self.sample_rate = config.get("sample_rate", 16000)
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=16000, channels=1, frame_size_ms=60
)
# 处理空字符串的情况 # 处理空字符串的情况
speed = config.get("speed", "1.0") speed = config.get("speed", "1.0")
self.speed = float(speed) if speed else 1.0 self.speed = float(speed) if speed else 1.0
self.ws = None
self._monitor_task = None
check_model_key("TTS", self.api_key) check_model_key("TTS", self.api_key)
async def open_audio_channels(self, conn):
try:
await super().open_audio_channels(conn)
await self._ensure_connection()
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to open audio channels: {str(e)}")
self.ws = None
raise
async def _receive_audio(self):
"""监听TTS响应"""
opus_datas_cache = []
is_first_sentence = True
is_audio_done = False
first_sentence_segment_count = 0 # 添加计数器
try:
while not self.conn.stop_event.is_set():
message = await self.ws.recv()
data = json.loads(message)
event_type = data.get("type")
logger.bind(tag=TAG).debug(f"Received data: {data}")
if event_type == "tts_session.updated":
logger.bind(tag=TAG).info(f"TTS session updated: {data}")
opus_datas_cache = []
is_first_sentence = True
first_sentence_segment_count = 0
elif event_type == "response.audio.delta":
pcm_data = base64.b64decode(data.get("delta"))
opus_data_list = self.opus_encoder.encode_pcm_to_opus(pcm_data, False)
if len(opus_data_list) == 0:
continue
if is_first_sentence:
logger.bind(tag=TAG).info(f"Received first audio data")
is_first_sentence = False
self.tts_audio_queue.put(
(SentenceType.FIRST, opus_data_list, None)
)
else:
logger.bind(tag=TAG).debug(f"Received delta audio data")
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus_data_list, None)
)
first_sentence_segment_count += 1
elif event_type == "response.audio_subtitle.delta":
logger.bind(tag=TAG).info(f"Received subtitles delata data: {data}")
subtitles = data.get("subtitles").get("text")
if subtitles:
self.tts_audio_queue.put(
(SentenceType.MIDDLE, [], subtitles)
)
elif event_type == "response.audio.done":
logger.bind(tag=TAG).info("完成语音生成.")
if self.tts_audio_queue:
self.tts_audio_queue.put(
(SentenceType.LAST, opus_datas_cache, None)
)
self._process_before_stop_play_files()
break # End of stream for this request
elif event_type == "error":
logger.bind(tag=TAG).error(f"Received error from server: {data}")
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
break
except websockets.exceptions.ConnectionClosed as e:
logger.bind(tag=TAG).warning(f"WebSocket connection closed: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error receiving audio: {e}")
finally:
logger.bind(tag=TAG).info(f"退出音频接收任务")
def tts_text_priority_thread(self):
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
)
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
continue
if message.sentence_type == SentenceType.FIRST:
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).info(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()
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.is_first_sentence = True
self.tts_audio_first_sentence = True
self.before_stop_play_files.clear()
logger.bind(tag=TAG).debug("TTS会话启动成功")
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
if segment_text:
logger.bind(tag=TAG).info(
f"开始发送TTS文本: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(segment_text, None),
loop=self.conn.loop,
)
future.result()
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"添加音频文件到待播放列表: {message.content_file}"
)
self.before_stop_play_files.append(
(message.content_file, message.content_detail)
)
if message.sentence_type == SentenceType.LAST:
logger.bind(tag=TAG).info("结束TTS会话")
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
)
continue
async def start_session(self, session_id):
logger.bind(tag=TAG).info(f"开始会话 {session_id}")
try:
# 建立新连接
await self._ensure_connection()
# 发送会话启动请求
session_update_payload = {
"event_id": str(uuid.uuid4()),
"type": "tts_session.update",
"session": {
"voice": self.voice,
"output_audio_format": self.audio_file_type,
"output_audio_sample_rate": self.sample_rate,
"text_to_speech": {
"model": self.model_name
}
}
}
await self.ws.send(json.dumps(session_update_payload))
logger.bind(tag=TAG).info(f"会话启动请求已发送, Send Event: {session_update_payload}")
# 启动监听任务
if self._monitor_task is None:
self._monitor_task = asyncio.create_task(self._receive_audio())
except Exception as e:
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
# 确保清理资源
if hasattr(self, "_monitor_task"):
try:
self._monitor_task.cancel()
await self._monitor_task
except:
pass
self._monitor_task = None
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
raise
async def finish_session(self, session_id):
try:
if self.ws:
done_payload = {
"type": "input_text.done"
}
await self.ws.send(json.dumps(done_payload))
logger.bind(tag=TAG).info(f"会话结束请求已发送,Send Event: {done_payload}")
except Exception as e:
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
# 等待监听任务完成
if hasattr(self, "_monitor_task"):
try:
await self._monitor_task
except Exception as e:
logger.bind(tag=TAG).error(
f"等待监听任务完成时发生错误: {str(e)}"
)
finally:
self._monitor_task = None
async def _ensure_connection(self):
if self.ws is None:
try:
logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}")
headers = {"Authorization": f"Bearer {self.api_key}"}
self.ws = await websockets.connect(self.ws_url, additional_headers=headers)
logger.bind(tag=TAG).info("WebSocket connection established.")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}")
self.ws = None
raise
async def stop_ws_connection(self):
# 关闭WebSocket连接
if self.ws:
try:
await self.ws.close()
logger.bind(tag=TAG).info("WebSocket connection closed.")
except Exception as e:
logger.bind(tag=TAG).error(f"Error closing WebSocket: {e}")
finally:
self.ws = None
async def text_to_speak(self, text, output_file): async def text_to_speak(self, text, output_file):
headers = { """发送文本到TTS服务"""
"Authorization": f"Bearer {self.api_key}", try:
"Content-Type": "application/json", # 建立新连接
} if self.ws is None:
data = { await handleAbortMessage(self.conn)
"model": self.model_name, logger.bind(tag=TAG).error(f"WebSocket连接不存在,终止发送文本")
"input": text, return
"voice": self.voice,
"response_format": "wav", # 过滤Markdown
"speed": self.speed, filtered_text = MarkdownCleaner.clean_markdown(text)
}
response = requests.post(self.base_url, json=data, headers=headers) # 发送文本
if response.status_code == 200: if len(filtered_text) > 0:
if output_file: text_append_payload = {
with open(output_file, "wb") as audio_file: "event_id": str(uuid.uuid4()),
audio_file.write(response.content) "type": "input_text.append",
else: "delta": filtered_text
return response.content }
else: await self.ws.send(json.dumps(text_append_payload))
raise Exception( logger.bind(tag=TAG).info(f"发送文本, Send Event: {text_append_payload}")
f"OpenAI TTS请求失败: {response.status_code} - {response.text}" return
) except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
await self.stop_ws_connection()
raise