mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fix gateway tts
This commit is contained in:
commit
9a9ff82470
11 changed files with 223 additions and 40 deletions
|
|
@ -227,7 +227,7 @@ public interface Constant {
|
||||||
/**
|
/**
|
||||||
* 版本号
|
* 版本号
|
||||||
*/
|
*/
|
||||||
public static final String VERSION = "0.5.7";
|
public static final String VERSION = "0.5.8";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无效固件URL
|
* 无效固件URL
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
-- LLM意图识别配置说明
|
||||||
|
UPDATE `ai_model_config` SET
|
||||||
|
`doc_link` = NULL,
|
||||||
|
`remark` = 'LLM意图识别配置说明:
|
||||||
|
1. 使用独立的LLM进行意图识别
|
||||||
|
2. 默认使用selected_module.LLM的模型
|
||||||
|
3. 可以配置使用独立的LLM(如免费的ChatGLMLLM)
|
||||||
|
4. 通用性强,但会增加处理时间
|
||||||
|
配置说明:
|
||||||
|
1. 在llm字段中指定使用的LLM模型
|
||||||
|
2. 如果不指定,则使用selected_module.LLM的模型' WHERE `id` = 'Intent_intent_llm';
|
||||||
|
|
||||||
|
-- 函数调用意图识别配置说明
|
||||||
|
UPDATE `ai_model_config` SET
|
||||||
|
`doc_link` = NULL,
|
||||||
|
`remark` = '函数调用意图识别配置说明:
|
||||||
|
1. 使用LLM的function_call功能进行意图识别
|
||||||
|
2. 需要所选择的LLM支持function_call
|
||||||
|
3. 按需调用工具,处理速度快' WHERE `id` = 'Intent_function_call';
|
||||||
|
|
@ -226,4 +226,10 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202506161101.sql
|
path: classpath:db/changelog/202506161101.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202506191643
|
||||||
|
author: hrz
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202506191643.sql
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from config.config_loader import load_config
|
||||||
from config.settings import check_config_file
|
from config.settings import check_config_file
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
SERVER_VERSION = "0.5.7"
|
SERVER_VERSION = "0.5.8"
|
||||||
_logger_initialized = False
|
_logger_initialized = False
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -115,6 +115,7 @@ class ConnectionHandler:
|
||||||
self.client_have_voice_last_time = 0.0
|
self.client_have_voice_last_time = 0.0
|
||||||
self.client_no_voice_last_time = 0.0
|
self.client_no_voice_last_time = 0.0
|
||||||
self.client_voice_stop = False
|
self.client_voice_stop = False
|
||||||
|
self.client_voice_frame_count = 0
|
||||||
|
|
||||||
# asr相关变量
|
# asr相关变量
|
||||||
# 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
|
# 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
|
||||||
|
|
@ -627,8 +628,8 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
memory_str = future.result()
|
memory_str = future.result()
|
||||||
|
|
||||||
uuid_str = str(uuid.uuid4()).replace("-", "")
|
self.sentence_id = str(uuid.uuid4().hex)
|
||||||
self.sentence_id = uuid_str
|
|
||||||
|
|
||||||
if self.intent_type == "function_call" and functions is not None:
|
if self.intent_type == "function_call" and functions is not None:
|
||||||
# 使用支持functions的streaming接口
|
# 使用支持functions的streaming接口
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,27 @@ class MCPClient:
|
||||||
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop)
|
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop)
|
||||||
return await asyncio.wrap_future(fut)
|
return await asyncio.wrap_future(fut)
|
||||||
|
|
||||||
|
def is_connected(self) -> bool:
|
||||||
|
"""检查MCP客户端是否连接正常
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 如果客户端已连接并正常工作,返回True,否则返回False
|
||||||
|
"""
|
||||||
|
# 检查工作任务是否存在
|
||||||
|
if self._worker_task is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 检查工作任务是否已经完成或取消
|
||||||
|
if self._worker_task.done():
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 检查会话是否存在
|
||||||
|
if self.session is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 所有检查都通过,连接正常
|
||||||
|
return True
|
||||||
|
|
||||||
async def _worker(self):
|
async def _worker(self):
|
||||||
async with AsyncExitStack() as stack:
|
async with AsyncExitStack() as stack:
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -100,7 +100,7 @@ class MCPManager:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
||||||
"""执行工具调用
|
"""执行工具调用,失败时会尝试重新连接
|
||||||
Args:
|
Args:
|
||||||
tool_name: 工具名称
|
tool_name: 工具名称
|
||||||
arguments: 工具参数
|
arguments: 工具参数
|
||||||
|
|
@ -112,11 +112,64 @@ class MCPManager:
|
||||||
self.conn.logger.bind(tag=TAG).info(
|
self.conn.logger.bind(tag=TAG).info(
|
||||||
f"Executing tool {tool_name} with arguments: {arguments}"
|
f"Executing tool {tool_name} with arguments: {arguments}"
|
||||||
)
|
)
|
||||||
for client in self.client.values():
|
|
||||||
if client.has_tool(tool_name):
|
|
||||||
return await client.call_tool(tool_name, arguments)
|
|
||||||
|
|
||||||
raise ValueError(f"Tool {tool_name} not found in any MCP server")
|
max_retries = 3 # 最大重试次数
|
||||||
|
retry_interval = 2 # 重试间隔(秒)
|
||||||
|
|
||||||
|
# 找到对应的客户端
|
||||||
|
client_name = None
|
||||||
|
target_client = None
|
||||||
|
for name, client in self.client.items():
|
||||||
|
if client.has_tool(tool_name):
|
||||||
|
client_name = name
|
||||||
|
target_client = client
|
||||||
|
break
|
||||||
|
|
||||||
|
if not target_client:
|
||||||
|
raise ValueError(f"Tool {tool_name} not found in any MCP server")
|
||||||
|
|
||||||
|
# 带重试机制的工具调用
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
try:
|
||||||
|
return await target_client.call_tool(tool_name, arguments)
|
||||||
|
except Exception as e:
|
||||||
|
# 最后一次尝试失败时直接抛出异常
|
||||||
|
if attempt == max_retries - 1:
|
||||||
|
raise
|
||||||
|
|
||||||
|
self.conn.logger.bind(tag=TAG).warning(
|
||||||
|
f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 尝试重新连接
|
||||||
|
self.conn.logger.bind(tag=TAG).info(
|
||||||
|
f"重试前尝试重新连接 MCP 客户端 {client_name}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
# 关闭旧的连接
|
||||||
|
await target_client.cleanup()
|
||||||
|
|
||||||
|
# 重新初始化客户端
|
||||||
|
config = self.load_config()
|
||||||
|
if client_name in config:
|
||||||
|
client = MCPClient(config[client_name])
|
||||||
|
await client.initialize()
|
||||||
|
self.client[client_name] = client
|
||||||
|
target_client = client
|
||||||
|
self.conn.logger.bind(tag=TAG).info(
|
||||||
|
f"成功重新连接 MCP 客户端: {client_name}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.conn.logger.bind(tag=TAG).error(
|
||||||
|
f"Cannot reconnect MCP client {client_name}: config not found"
|
||||||
|
)
|
||||||
|
except Exception as reconnect_error:
|
||||||
|
self.conn.logger.bind(tag=TAG).error(
|
||||||
|
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 等待一段时间再重试
|
||||||
|
await asyncio.sleep(retry_interval)
|
||||||
|
|
||||||
async def cleanup_all(self) -> None:
|
async def cleanup_all(self) -> None:
|
||||||
"""依次关闭所有 MCPClient,不让异常阻断整体流程。"""
|
"""依次关闭所有 MCPClient,不让异常阻断整体流程。"""
|
||||||
|
|
|
||||||
|
|
@ -254,7 +254,6 @@ class ASRProvider(ASRProviderBase):
|
||||||
"X-Api-Access-Key": self.access_token,
|
"X-Api-Access-Key": self.access_token,
|
||||||
"X-Api-Resource-Id": "volc.bigasr.sauc.duration",
|
"X-Api-Resource-Id": "volc.bigasr.sauc.duration",
|
||||||
"X-Api-Connect-Id": str(uuid.uuid4()),
|
"X-Api-Connect-Id": str(uuid.uuid4()),
|
||||||
"Host": "openspeech.bytedance.com",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def generate_header(
|
def generate_header(
|
||||||
|
|
@ -310,7 +309,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
code = int.from_bytes(res[4:8], "big", signed=False)
|
code = int.from_bytes(res[4:8], "big", signed=False)
|
||||||
msg_length = int.from_bytes(res[8:12], "big", signed=False)
|
msg_length = int.from_bytes(res[8:12], "big", signed=False)
|
||||||
error_msg = json.loads(res[12:].decode("utf-8"))
|
error_msg = json.loads(res[12:].decode("utf-8"))
|
||||||
return {"code": code, "msg_length": msg_length, "payload_msg": error_msg}
|
return {
|
||||||
|
"code": code,
|
||||||
|
"msg_length": msg_length,
|
||||||
|
"payload_msg": error_msg,
|
||||||
|
}
|
||||||
|
|
||||||
# 获取JSON数据(跳过12字节头部)
|
# 获取JSON数据(跳过12字节头部)
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ from core.utils.util import check_model_key
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from core.handle.abortHandle import handleAbortMessage
|
from core.handle.abortHandle import handleAbortMessage
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
||||||
|
from asyncio import Task
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -141,6 +143,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
self.ws = None
|
self.ws = None
|
||||||
self.interface_type = InterfaceType.DUAL_STREAM
|
self.interface_type = InterfaceType.DUAL_STREAM
|
||||||
|
self._monitor_task = None # 监听任务引用
|
||||||
self.appId = config.get("appid")
|
self.appId = config.get("appid")
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
self.cluster = config.get("cluster")
|
self.cluster = config.get("cluster")
|
||||||
|
|
@ -270,8 +273,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
try:
|
try:
|
||||||
# 建立新连接
|
# 建立新连接
|
||||||
if self.ws is None:
|
if self.ws is None:
|
||||||
await handleAbortMessage(self.conn)
|
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
|
||||||
logger.bind(tag=TAG).error(f"WebSocket连接不存在,终止发送文本")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# 过滤Markdown
|
# 过滤Markdown
|
||||||
|
|
@ -293,6 +295,25 @@ class TTSProvider(TTSProviderBase):
|
||||||
async def start_session(self, session_id):
|
async def start_session(self, session_id):
|
||||||
logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
|
logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
|
||||||
try:
|
try:
|
||||||
|
task = self._monitor_task
|
||||||
|
if (
|
||||||
|
task is not None
|
||||||
|
and isinstance(task, Task)
|
||||||
|
and not task.done()
|
||||||
|
):
|
||||||
|
logger.bind(tag=TAG).info("等待上一个监听任务结束...")
|
||||||
|
if self.ws is not None:
|
||||||
|
logger.bind(tag=TAG).info("强制关闭上一个WebSocket连接以唤醒监听任务...")
|
||||||
|
try:
|
||||||
|
await self.ws.close()
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"关闭上一个ws异常: {e}")
|
||||||
|
self.ws = None
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(task, timeout=8)
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"等待监听任务异常: {e}")
|
||||||
|
self._monitor_task = None
|
||||||
# 建立新连接
|
# 建立新连接
|
||||||
await self._ensure_connection()
|
await self._ensure_connection()
|
||||||
|
|
||||||
|
|
@ -463,6 +484,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
self.ws = None
|
self.ws = None
|
||||||
|
# 监听任务退出时清理引用
|
||||||
|
self._monitor_task = None
|
||||||
|
|
||||||
async def send_event(
|
async def send_event(
|
||||||
self,
|
self,
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,21 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
import base64
|
import base64
|
||||||
|
import pydub
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
import queue
|
import queue
|
||||||
import websockets
|
import websockets
|
||||||
|
import requests
|
||||||
|
import io
|
||||||
|
import openai
|
||||||
|
|
||||||
|
|
||||||
from core.utils import opus_encoder_utils
|
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 core.utils.tts import MarkdownCleaner
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from core.utils.util import audio_to_data, audio_bytes_to_data, opus_datas_to_wav_bytes
|
||||||
from core.handle.abortHandle import handleAbortMessage
|
from core.handle.abortHandle import handleAbortMessage
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
||||||
|
|
||||||
|
|
@ -28,12 +34,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.host = "ai-gateway.vei.volces.com"
|
self.host = "ai-gateway.vei.volces.com"
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
self.ws_url = f"wss://{self.host}/v1/realtime?model={self.model_name}"
|
self.ws_url = f"wss://{self.host}/v1/realtime?model={self.model_name}"
|
||||||
|
self.base_url = f"https://{self.host}/v1"
|
||||||
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", "pcm") # 流式接口通常使用 pcm
|
self.audio_file_type = config.get("format", "wav") # 流式接口通常使用 pcm
|
||||||
self.sample_rate = config.get("sample_rate", 16000)
|
self.sample_rate = config.get("sample_rate", 16000)
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
||||||
sample_rate=16000, channels=1, frame_size_ms=60
|
sample_rate=16000, channels=1, frame_size_ms=60
|
||||||
|
|
@ -46,7 +52,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
check_model_key("TTS", self.api_key)
|
check_model_key("TTS", self.api_key)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
try:
|
try:
|
||||||
await super().open_audio_channels(conn)
|
await super().open_audio_channels(conn)
|
||||||
|
|
@ -70,7 +75,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
event_type = data.get("type")
|
event_type = data.get("type")
|
||||||
logger.bind(tag=TAG).debug(f"Received data: {data}")
|
logger.bind(tag=TAG).debug(f"Received data: {data}")
|
||||||
if event_type == "tts_session.updated":
|
if event_type == "tts_session.updated":
|
||||||
logger.bind(tag=TAG).info(f"TTS session updated: {data}")
|
logger.bind(tag=TAG).info(f"Session: {self.conn.sentence_id}, 完成会话初始化")
|
||||||
opus_datas_cache = []
|
opus_datas_cache = []
|
||||||
is_first_sentence = True
|
is_first_sentence = True
|
||||||
first_sentence_segment_count = 0
|
first_sentence_segment_count = 0
|
||||||
|
|
@ -80,7 +85,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
if len(opus_data_list) == 0:
|
if len(opus_data_list) == 0:
|
||||||
continue
|
continue
|
||||||
if is_first_sentence:
|
if is_first_sentence:
|
||||||
logger.bind(tag=TAG).info(f"Received first audio data")
|
logger.bind(tag=TAG).debug(f"Session: {self.conn.sentence_id}, Received first audio data")
|
||||||
is_first_sentence = False
|
is_first_sentence = False
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.FIRST, opus_data_list, None)
|
(SentenceType.FIRST, opus_data_list, None)
|
||||||
|
|
@ -92,14 +97,14 @@ class TTSProvider(TTSProviderBase):
|
||||||
)
|
)
|
||||||
first_sentence_segment_count += 1
|
first_sentence_segment_count += 1
|
||||||
elif event_type == "response.audio_subtitle.delta":
|
elif event_type == "response.audio_subtitle.delta":
|
||||||
logger.bind(tag=TAG).info(f"Received subtitles delata data: {data}")
|
logger.bind(tag=TAG).debug(f"Session: {self.conn.sentence_id},Received subtitles delata data: {data}")
|
||||||
subtitles = data.get("subtitles").get("text")
|
subtitles = data.get("subtitles").get("text")
|
||||||
if subtitles:
|
if subtitles:
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.MIDDLE, [], subtitles)
|
(SentenceType.MIDDLE, [], subtitles)
|
||||||
)
|
)
|
||||||
elif event_type == "response.audio.done":
|
elif event_type == "response.audio.done":
|
||||||
logger.bind(tag=TAG).info("完成语音生成.")
|
logger.bind(tag=TAG).debug(f"Session: {self.conn.sentence_id},完成语音生成.")
|
||||||
if self.tts_audio_queue:
|
if self.tts_audio_queue:
|
||||||
self.tts_audio_queue.put(
|
self.tts_audio_queue.put(
|
||||||
(SentenceType.LAST, opus_datas_cache, None)
|
(SentenceType.LAST, opus_datas_cache, None)
|
||||||
|
|
@ -116,11 +121,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.ws = None
|
self.ws = None
|
||||||
break
|
break
|
||||||
except websockets.exceptions.ConnectionClosed as e:
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
|
self.stop_ws_connection()
|
||||||
logger.bind(tag=TAG).warning(f"WebSocket connection closed: {e}")
|
logger.bind(tag=TAG).warning(f"WebSocket connection closed: {e}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error receiving audio: {e}")
|
logger.bind(tag=TAG).error(f"Error receiving audio: {e}")
|
||||||
finally:
|
finally:
|
||||||
logger.bind(tag=TAG).info(f"退出音频接收任务")
|
logger.bind(tag=TAG).debug(f"Session: {self.conn.sentence_id}, 退出音频接收任务")
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
def tts_text_priority_thread(self):
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
|
|
@ -154,10 +160,10 @@ class TTSProvider(TTSProviderBase):
|
||||||
segment_text = self._get_segment_text()
|
segment_text = self._get_segment_text()
|
||||||
if segment_text:
|
if segment_text:
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"开始发送TTS文本: {message.content_detail}"
|
f"session: {self.conn.sentence_id} 发送TTS文本: {segment_text}"
|
||||||
)
|
)
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.text_to_speak(segment_text, None),
|
self._send_text(segment_text),
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
|
|
@ -170,7 +176,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
)
|
)
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
if message.sentence_type == SentenceType.LAST:
|
||||||
logger.bind(tag=TAG).info("结束TTS会话")
|
logger.bind(tag=TAG).info(f"session: {self.conn.sentence_id} 结束TTS会话")
|
||||||
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,
|
||||||
|
|
@ -203,7 +209,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await self.ws.send(json.dumps(session_update_payload))
|
await self.ws.send(json.dumps(session_update_payload))
|
||||||
logger.bind(tag=TAG).info(f"会话启动请求已发送, Send Event: {session_update_payload}")
|
logger.bind(tag=TAG).debug(f"会话启动请求已发送, Send Event: {session_update_payload}")
|
||||||
# 启动监听任务
|
# 启动监听任务
|
||||||
if self._monitor_task is None:
|
if self._monitor_task is None:
|
||||||
self._monitor_task = asyncio.create_task(self._receive_audio())
|
self._monitor_task = asyncio.create_task(self._receive_audio())
|
||||||
|
|
@ -218,29 +224,27 @@ class TTSProvider(TTSProviderBase):
|
||||||
pass
|
pass
|
||||||
self._monitor_task = None
|
self._monitor_task = None
|
||||||
if self.ws:
|
if self.ws:
|
||||||
try:
|
await self.stop_ws_connection()
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def finish_session(self, session_id):
|
async def finish_session(self, session_id):
|
||||||
try:
|
try:
|
||||||
if self.ws:
|
if self.ws:
|
||||||
done_payload = {
|
done_payload = {
|
||||||
"type": "input_text.done"
|
"type": "input_text.done"
|
||||||
}
|
}
|
||||||
await self.ws.send(json.dumps(done_payload))
|
await self.ws.send(json.dumps(done_payload))
|
||||||
logger.bind(tag=TAG).info(f"会话结束请求已发送,Send Event: {done_payload}")
|
logger.bind(tag=TAG).debug(f"会话结束请求已发送,Send Event: {done_payload}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
await self.stop_ws_connection()
|
||||||
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
|
||||||
|
|
||||||
# 等待监听任务完成
|
# 等待监听任务完成
|
||||||
if hasattr(self, "_monitor_task"):
|
if hasattr(self, "_monitor_task"):
|
||||||
try:
|
try:
|
||||||
await self._monitor_task
|
await self._monitor_task
|
||||||
|
logger.bind(tag=TAG).debug(f"退出monitor task")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"等待监听任务完成时发生错误: {str(e)}"
|
f"等待监听任务完成时发生错误: {str(e)}"
|
||||||
|
|
@ -249,11 +253,14 @@ class TTSProvider(TTSProviderBase):
|
||||||
self._monitor_task = None
|
self._monitor_task = None
|
||||||
|
|
||||||
async def _ensure_connection(self):
|
async def _ensure_connection(self):
|
||||||
|
# TODO: 建立健康检查机制,实现连接复用
|
||||||
|
#await self.stop_ws_connection()
|
||||||
if self.ws is None:
|
if self.ws is None:
|
||||||
try:
|
try:
|
||||||
logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}")
|
logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}")
|
||||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||||
self.ws = await websockets.connect(self.ws_url, additional_headers=headers)
|
self.ws = await websockets.connect(self.ws_url, additional_headers=headers)
|
||||||
|
#self._health_check_task = asyncio.create_task(self._websocket_health_check())
|
||||||
logger.bind(tag=TAG).info("WebSocket connection established.")
|
logger.bind(tag=TAG).info("WebSocket connection established.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}")
|
logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}")
|
||||||
|
|
@ -271,7 +278,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
finally:
|
finally:
|
||||||
self.ws = None
|
self.ws = None
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def _send_text(self, text):
|
||||||
"""发送文本到TTS服务"""
|
"""发送文本到TTS服务"""
|
||||||
try:
|
try:
|
||||||
# 建立新连接
|
# 建立新连接
|
||||||
|
|
@ -291,13 +298,51 @@ class TTSProvider(TTSProviderBase):
|
||||||
"delta": filtered_text
|
"delta": filtered_text
|
||||||
}
|
}
|
||||||
await self.ws.send(json.dumps(text_append_payload))
|
await self.ws.send(json.dumps(text_append_payload))
|
||||||
logger.bind(tag=TAG).info(f"发送文本, Send Event: {text_append_payload}")
|
logger.bind(tag=TAG).debug(f"发送文本, Send Event: {text_append_payload}")
|
||||||
return
|
return
|
||||||
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)}")
|
||||||
await self.stop_ws_connection()
|
await self.stop_ws_connection()
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
"""采用http方式发送文本到TTS服务"""
|
||||||
|
logger.bind(tag=TAG).info(f"采用http方式发送文本: {text}")
|
||||||
|
client = openai.OpenAI(
|
||||||
|
base_url = self.base_url,
|
||||||
|
api_key = self.api_key
|
||||||
|
)
|
||||||
|
|
||||||
|
response = client.audio.speech.create(
|
||||||
|
model = self.model_name,
|
||||||
|
voice = self.voice,
|
||||||
|
input = text
|
||||||
|
)
|
||||||
|
# 其他格式用pydub
|
||||||
|
audio = pydub.AudioSegment.from_file(
|
||||||
|
io.BytesIO(response.content), format="mp3", parameters=["-nostdin"]
|
||||||
|
)
|
||||||
|
wav_buffer = io.BytesIO()
|
||||||
|
audio.export(wav_buffer, format="wav")
|
||||||
|
wav_bytes = wav_buffer.getvalue()
|
||||||
|
output_file = "/tmp/a.wav"
|
||||||
|
if output_file:
|
||||||
|
with open(output_file, "wb") as audio_file:
|
||||||
|
audio_file.write(wav_bytes)
|
||||||
|
return wav_bytes
|
||||||
|
|
||||||
|
async def _websocket_health_check(self):
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
if self.ws is None:
|
||||||
|
continue
|
||||||
|
await self.ws.send("Ping")
|
||||||
|
response = await self.ws.recv()
|
||||||
|
logger.bind(tag=TAG).info(f"健康检测收到: {response}")
|
||||||
|
await asyncio.sleep(10)
|
||||||
|
except websockets.exceptions.ConnectionClosedOK:
|
||||||
|
logger.bind(tag=TAG).info("连接正常关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"发生错误,关闭连接: {e}")
|
||||||
|
await self.stop_ws_connection()
|
||||||
|
|
||||||
|
|
@ -35,6 +35,10 @@ class VADProvider(VADProviderBase):
|
||||||
pcm_frame = self.decoder.decode(opus_packet, 960)
|
pcm_frame = self.decoder.decode(opus_packet, 960)
|
||||||
conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区
|
conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区
|
||||||
|
|
||||||
|
# 初始化帧计数器
|
||||||
|
if not hasattr(conn, "client_voice_frame_count"):
|
||||||
|
conn.client_voice_frame_count = 0
|
||||||
|
|
||||||
# 处理缓冲区中的完整帧(每次处理512采样点)
|
# 处理缓冲区中的完整帧(每次处理512采样点)
|
||||||
client_have_voice = False
|
client_have_voice = False
|
||||||
while len(conn.client_audio_buffer) >= 512 * 2:
|
while len(conn.client_audio_buffer) >= 512 * 2:
|
||||||
|
|
@ -50,7 +54,15 @@ class VADProvider(VADProviderBase):
|
||||||
# 检测语音活动
|
# 检测语音活动
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
speech_prob = self.model(audio_tensor, 16000).item()
|
speech_prob = self.model(audio_tensor, 16000).item()
|
||||||
client_have_voice = speech_prob >= self.vad_threshold
|
is_voice = speech_prob >= self.vad_threshold
|
||||||
|
|
||||||
|
if is_voice:
|
||||||
|
conn.client_voice_frame_count += 1
|
||||||
|
else:
|
||||||
|
conn.client_voice_frame_count = 0
|
||||||
|
|
||||||
|
# 只有连续4帧检测到语音才认为有语音
|
||||||
|
client_have_voice = conn.client_voice_frame_count >= 4
|
||||||
|
|
||||||
# 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
|
# 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
|
||||||
if conn.client_have_voice and not client_have_voice:
|
if conn.client_have_voice and not client_have_voice:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue