mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: remove tts
This commit is contained in:
parent
5e1141064d
commit
b63d3f4e81
18 changed files with 425 additions and 3578 deletions
|
|
@ -925,6 +925,8 @@ class ConnectionHandler:
|
||||||
self.config["TTS"]["FishSpeech"]["reference_id"] = voice_id
|
self.config["TTS"]["FishSpeech"]["reference_id"] = voice_id
|
||||||
if "TTS" in self.config and "FishDualStreamTTS" in self.config.get("TTS", {}):
|
if "TTS" in self.config and "FishDualStreamTTS" in self.config.get("TTS", {}):
|
||||||
self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = voice_id
|
self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = voice_id
|
||||||
|
# if "TTS" in self.config and "FishSingleStreamTTS" in self.config.get("TTS", {}):
|
||||||
|
# self.config["TTS"]["FishSingleStreamTTS"]["reference_id"] = voice_id
|
||||||
self._instruction = private_config.get("instruction", self._instruction)
|
self._instruction = private_config.get("instruction", self._instruction)
|
||||||
# greeting config
|
# greeting config
|
||||||
self._greeting_config["enable_greeting"] = private_config.get("enable_greeting", False)
|
self._greeting_config["enable_greeting"] = private_config.get("enable_greeting", False)
|
||||||
|
|
|
||||||
|
|
@ -1,522 +0,0 @@
|
||||||
import os
|
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
import queue
|
|
||||||
import asyncio
|
|
||||||
import traceback
|
|
||||||
import websockets
|
|
||||||
from asyncio import Task
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.utils import opus_encoder_utils
|
|
||||||
from core.utils.tts import MarkdownCleaner
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
|
|
||||||
self.interface_type = InterfaceType.DUAL_STREAM
|
|
||||||
# 基础配置
|
|
||||||
self.api_key = config.get("api_key")
|
|
||||||
if not self.api_key:
|
|
||||||
raise ValueError("api_key is required for CosyVoice TTS")
|
|
||||||
|
|
||||||
# WebSocket配置
|
|
||||||
self.ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
|
|
||||||
self.ws = None
|
|
||||||
self._monitor_task = None
|
|
||||||
self.last_active_time = None
|
|
||||||
|
|
||||||
# 模型和音色配置
|
|
||||||
self.model = config.get("model", "cosyvoice-v2")
|
|
||||||
self.voice = config.get("voice", "longxiaochun_v2") # 默认音色
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
|
|
||||||
# 音频参数配置
|
|
||||||
self.format = config.get("format", "pcm")
|
|
||||||
sample_rate = config.get("sample_rate", "24000")
|
|
||||||
self.sample_rate = int(sample_rate) if sample_rate else 24000
|
|
||||||
|
|
||||||
volume = config.get("volume", "50")
|
|
||||||
self.volume = int(volume) if volume else 50
|
|
||||||
|
|
||||||
rate = config.get("rate", "1.0")
|
|
||||||
self.rate = float(rate) if rate else 1.0
|
|
||||||
|
|
||||||
pitch = config.get("pitch", "1.0")
|
|
||||||
self.pitch = float(pitch) if pitch else 1.0
|
|
||||||
|
|
||||||
self.header = {
|
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
|
||||||
# "user-agent": "your_platform_info", // 可选
|
|
||||||
# "X-DashScope-WorkSpace": workspace, // 可选,阿里云百炼业务空间ID
|
|
||||||
"X-DashScope-DataInspection": "enable",
|
|
||||||
}
|
|
||||||
|
|
||||||
# 创建Opus编码器
|
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
|
||||||
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
|
|
||||||
)
|
|
||||||
|
|
||||||
async def _ensure_connection(self):
|
|
||||||
"""确保WebSocket连接可用,支持60秒内连接复用"""
|
|
||||||
try:
|
|
||||||
current_time = time.time()
|
|
||||||
if self.ws and current_time - self.last_active_time < 60:
|
|
||||||
# 一分钟内才可以复用链接进行连续对话
|
|
||||||
logger.bind(tag=TAG).info(f"使用已有链接...")
|
|
||||||
return self.ws
|
|
||||||
logger.bind(tag=TAG).info("开始建立新连接...")
|
|
||||||
|
|
||||||
self.ws = await websockets.connect(
|
|
||||||
self.ws_url,
|
|
||||||
additional_headers=self.header,
|
|
||||||
ping_interval=30,
|
|
||||||
ping_timeout=10,
|
|
||||||
close_timeout=10,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.bind(tag=TAG).info("WebSocket连接建立成功")
|
|
||||||
self.last_active_time = current_time
|
|
||||||
return self.ws
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
|
|
||||||
self.ws = None
|
|
||||||
self.last_active_time = None
|
|
||||||
raise
|
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
|
||||||
"""流式TTS文本处理线程"""
|
|
||||||
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 message.sentence_type == SentenceType.FIRST:
|
|
||||||
self.conn.client_abort = False
|
|
||||||
|
|
||||||
if self.conn.client_abort:
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
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).info(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
|
||||||
|
|
||||||
logger.bind(tag=TAG).info("开始启动TTS会话...")
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.start_session(self.conn.sentence_id),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
self.before_stop_play_files.clear()
|
|
||||||
logger.bind(tag=TAG).info("TTS会话启动成功")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
|
||||||
if message.content_detail:
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"开始发送TTS文本: {message.content_detail}"
|
|
||||||
)
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.text_to_speak(message.content_detail, None),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
logger.bind(tag=TAG).debug("TTS文本发送成功")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"添加音频文件到待播放列表: {message.content_file}"
|
|
||||||
)
|
|
||||||
if message.content_file and os.path.exists(message.content_file):
|
|
||||||
# 先处理文件音频数据
|
|
||||||
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
|
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
|
||||||
try:
|
|
||||||
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 Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
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 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)
|
|
||||||
|
|
||||||
# 发送continue-task消息
|
|
||||||
continue_task_message = {
|
|
||||||
"header": {
|
|
||||||
"action": "continue-task",
|
|
||||||
"task_id": self.conn.sentence_id,
|
|
||||||
"streaming": "duplex",
|
|
||||||
},
|
|
||||||
"payload": {"input": {"text": filtered_text}},
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.ws.send(json.dumps(continue_task_message))
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
logger.bind(tag=TAG).debug(f"已发送文本: {filtered_text}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def start_session(self, session_id):
|
|
||||||
"""启动TTS会话"""
|
|
||||||
logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
|
|
||||||
try:
|
|
||||||
# 检查并清理上一个会话的监听任务
|
|
||||||
if (
|
|
||||||
self._monitor_task is not None
|
|
||||||
and isinstance(self._monitor_task, Task)
|
|
||||||
and not self._monitor_task.done()
|
|
||||||
):
|
|
||||||
logger.bind(tag=TAG).info("检测到未完成的上个会话,关闭监听任务...")
|
|
||||||
await self.close()
|
|
||||||
|
|
||||||
# 确保连接可用
|
|
||||||
await self._ensure_connection()
|
|
||||||
|
|
||||||
# 启动监听任务
|
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
|
||||||
|
|
||||||
# 发送run-task消息启动会话
|
|
||||||
run_task_message = {
|
|
||||||
"header": {
|
|
||||||
"action": "run-task",
|
|
||||||
"task_id": session_id,
|
|
||||||
"streaming": "duplex",
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"task_group": "audio",
|
|
||||||
"task": "tts",
|
|
||||||
"function": "SpeechSynthesizer",
|
|
||||||
"model": self.model,
|
|
||||||
"parameters": {
|
|
||||||
"text_type": "PlainText",
|
|
||||||
"voice": self.voice,
|
|
||||||
"format": self.format,
|
|
||||||
"sample_rate": self.sample_rate,
|
|
||||||
"volume": self.volume,
|
|
||||||
"rate": self.rate,
|
|
||||||
"pitch": self.pitch,
|
|
||||||
},
|
|
||||||
"input": {}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.ws.send(json.dumps(run_task_message))
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
logger.bind(tag=TAG).info("会话启动请求已发送")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
|
||||||
await self.close()
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def finish_session(self, session_id):
|
|
||||||
"""结束TTS会话"""
|
|
||||||
logger.bind(tag=TAG).info(f"关闭会话~~{session_id}")
|
|
||||||
try:
|
|
||||||
if self.ws and session_id:
|
|
||||||
# 发送finish-task消息
|
|
||||||
finish_task_message = {
|
|
||||||
"header": {
|
|
||||||
"action": "finish-task",
|
|
||||||
"task_id": session_id,
|
|
||||||
"streaming": "duplex",
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"input": {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.ws.send(json.dumps(finish_task_message))
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
logger.bind(tag=TAG).info("会话结束请求已发送")
|
|
||||||
# 等待监听任务完成
|
|
||||||
if 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
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
|
|
||||||
await self.close()
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""清理资源"""
|
|
||||||
# 取消监听任务
|
|
||||||
if self._monitor_task:
|
|
||||||
try:
|
|
||||||
self._monitor_task.cancel()
|
|
||||||
await self._monitor_task
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
# 关闭WebSocket连接
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
self.last_active_time = None
|
|
||||||
|
|
||||||
async def _start_monitor_tts_response(self):
|
|
||||||
"""监听TTS响应"""
|
|
||||||
try:
|
|
||||||
session_finished = False
|
|
||||||
while not self.conn.stop_event.is_set():
|
|
||||||
try:
|
|
||||||
msg = await self.ws.recv()
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
|
|
||||||
# 检查客户端是否中止
|
|
||||||
if self.conn.client_abort:
|
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
|
|
||||||
break
|
|
||||||
|
|
||||||
if isinstance(msg, str): # JSON控制消息
|
|
||||||
try:
|
|
||||||
data = json.loads(msg)
|
|
||||||
event = data["header"].get("event")
|
|
||||||
|
|
||||||
if event == "task-started":
|
|
||||||
logger.bind(tag=TAG).debug("TTS任务启动成功~")
|
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], None))
|
|
||||||
elif event == "result-generated":
|
|
||||||
# 发送缓存的数据
|
|
||||||
if self.conn.tts_MessageText:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"句子语音生成成功: {self.conn.tts_MessageText}"
|
|
||||||
)
|
|
||||||
self.tts_audio_queue.put(
|
|
||||||
(SentenceType.FIRST, [], self.conn.tts_MessageText)
|
|
||||||
)
|
|
||||||
self.conn.tts_MessageText = None
|
|
||||||
elif event == "task-finished":
|
|
||||||
logger.bind(tag=TAG).debug("TTS任务完成~")
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
session_finished = True
|
|
||||||
break
|
|
||||||
elif event == "task-failed":
|
|
||||||
error_code = data["header"].get("error_code", "unknown")
|
|
||||||
error_message = data["header"].get("error_message", "未知错误")
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"TTS任务失败: {error_code} - {error_message}"
|
|
||||||
)
|
|
||||||
break
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
|
||||||
elif isinstance(msg, (bytes, bytearray)):
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
msg, False, callback=self.handle_opus
|
|
||||||
)
|
|
||||||
except websockets.ConnectionClosed:
|
|
||||||
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
break
|
|
||||||
|
|
||||||
# 仅在连接异常且非正常结束时才关闭连接
|
|
||||||
if not session_finished and self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
# 监听任务退出时清理引用
|
|
||||||
finally:
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
|
||||||
"""非流式生成音频数据,用于生成音频及测试场景"""
|
|
||||||
try:
|
|
||||||
# 创建事件循环
|
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(loop)
|
|
||||||
|
|
||||||
# 生成会话ID
|
|
||||||
session_id = uuid.uuid4().hex
|
|
||||||
# 存储音频数据
|
|
||||||
audio_data = []
|
|
||||||
|
|
||||||
async def _generate_audio():
|
|
||||||
ws = await websockets.connect(
|
|
||||||
self.ws_url,
|
|
||||||
additional_headers=self.header,
|
|
||||||
ping_interval=30,
|
|
||||||
ping_timeout=10,
|
|
||||||
close_timeout=10,
|
|
||||||
max_size=10 * 1024 * 1024,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 发送run-task消息启动会话
|
|
||||||
run_task_message = {
|
|
||||||
"header": {
|
|
||||||
"action": "run-task",
|
|
||||||
"task_id": session_id,
|
|
||||||
"streaming": "duplex",
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"task_group": "audio",
|
|
||||||
"task": "tts",
|
|
||||||
"function": "SpeechSynthesizer",
|
|
||||||
"model": self.model,
|
|
||||||
"parameters": {
|
|
||||||
"text_type": "PlainText",
|
|
||||||
"voice": self.voice,
|
|
||||||
"format": self.format,
|
|
||||||
"sample_rate": self.sample_rate,
|
|
||||||
"volume": self.volume,
|
|
||||||
"rate": self.rate,
|
|
||||||
"pitch": self.pitch,
|
|
||||||
},
|
|
||||||
"input": {}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(run_task_message))
|
|
||||||
|
|
||||||
# 等待任务启动
|
|
||||||
task_started = False
|
|
||||||
while not task_started:
|
|
||||||
msg = await ws.recv()
|
|
||||||
if isinstance(msg, str):
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
if header.get("event") == "task-started":
|
|
||||||
task_started = True
|
|
||||||
logger.bind(tag=TAG).debug("TTS任务已启动")
|
|
||||||
elif header.get("event") == "task-failed":
|
|
||||||
error_code = header.get("error_code", "unknown")
|
|
||||||
error_message = header.get("error_message", "未知错误")
|
|
||||||
raise Exception(
|
|
||||||
f"启动任务失败: {error_code} - {error_message}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 发送文本
|
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
|
||||||
# 发送continue-task消息
|
|
||||||
continue_task_message = {
|
|
||||||
"header": {
|
|
||||||
"action": "continue-task",
|
|
||||||
"task_id": session_id,
|
|
||||||
"streaming": "duplex",
|
|
||||||
},
|
|
||||||
"payload": {"input": {"text": filtered_text}},
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(continue_task_message))
|
|
||||||
|
|
||||||
# 发送finish-task消息
|
|
||||||
finish_task_message = {
|
|
||||||
"header": {
|
|
||||||
"action": "finish-task",
|
|
||||||
"task_id": session_id,
|
|
||||||
"streaming": "duplex",
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"input": {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(finish_task_message))
|
|
||||||
|
|
||||||
# 接收音频数据
|
|
||||||
task_finished = False
|
|
||||||
while not task_finished:
|
|
||||||
msg = await ws.recv()
|
|
||||||
if isinstance(msg, (bytes, bytearray)):
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
msg,
|
|
||||||
end_of_stream=False,
|
|
||||||
callback=lambda opus: audio_data.append(opus)
|
|
||||||
)
|
|
||||||
elif isinstance(msg, str):
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
if header.get("event") == "task-finished":
|
|
||||||
task_finished = True
|
|
||||||
logger.bind(tag=TAG).debug("TTS任务完成")
|
|
||||||
elif header.get("event") == "task-failed":
|
|
||||||
error_code = header.get("error_code", "unknown")
|
|
||||||
error_message = header.get("error_message", "未知错误")
|
|
||||||
raise Exception(
|
|
||||||
f"合成失败: {error_code} - {error_message}"
|
|
||||||
)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
# 清理资源
|
|
||||||
try:
|
|
||||||
await ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 运行异步任务
|
|
||||||
loop.run_until_complete(_generate_audio())
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
return audio_data
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
|
|
||||||
return []
|
|
||||||
|
|
@ -1,205 +0,0 @@
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import hmac
|
|
||||||
import hashlib
|
|
||||||
import base64
|
|
||||||
import requests
|
|
||||||
from datetime import datetime
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from config.logger import setup_logging
|
|
||||||
import time
|
|
||||||
import uuid
|
|
||||||
from urllib import parse
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class AccessToken:
|
|
||||||
@staticmethod
|
|
||||||
def _encode_text(text):
|
|
||||||
encoded_text = parse.quote_plus(text)
|
|
||||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _encode_dict(dic):
|
|
||||||
keys = dic.keys()
|
|
||||||
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
|
|
||||||
encoded_text = parse.urlencode(dic_sorted)
|
|
||||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def create_token(access_key_id, access_key_secret):
|
|
||||||
parameters = {
|
|
||||||
"AccessKeyId": access_key_id,
|
|
||||||
"Action": "CreateToken",
|
|
||||||
"Format": "JSON",
|
|
||||||
"RegionId": "cn-shanghai",
|
|
||||||
"SignatureMethod": "HMAC-SHA1",
|
|
||||||
"SignatureNonce": str(uuid.uuid1()),
|
|
||||||
"SignatureVersion": "1.0",
|
|
||||||
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
||||||
"Version": "2019-02-28",
|
|
||||||
}
|
|
||||||
# 构造规范化的请求字符串
|
|
||||||
query_string = AccessToken._encode_dict(parameters)
|
|
||||||
# print('规范化的请求字符串: %s' % query_string)
|
|
||||||
# 构造待签名字符串
|
|
||||||
string_to_sign = (
|
|
||||||
"GET"
|
|
||||||
+ "&"
|
|
||||||
+ AccessToken._encode_text("/")
|
|
||||||
+ "&"
|
|
||||||
+ AccessToken._encode_text(query_string)
|
|
||||||
)
|
|
||||||
# print('待签名的字符串: %s' % string_to_sign)
|
|
||||||
# 计算签名
|
|
||||||
secreted_string = hmac.new(
|
|
||||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
|
||||||
bytes(string_to_sign, encoding="utf-8"),
|
|
||||||
hashlib.sha1,
|
|
||||||
).digest()
|
|
||||||
signature = base64.b64encode(secreted_string)
|
|
||||||
# print('签名: %s' % signature)
|
|
||||||
# 进行URL编码
|
|
||||||
signature = AccessToken._encode_text(signature)
|
|
||||||
# print('URL编码后的签名: %s' % signature)
|
|
||||||
# 调用服务
|
|
||||||
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
|
|
||||||
signature,
|
|
||||||
query_string,
|
|
||||||
)
|
|
||||||
# print('url: %s' % full_url)
|
|
||||||
# 提交HTTP GET请求
|
|
||||||
response = requests.get(full_url)
|
|
||||||
if response.ok:
|
|
||||||
root_obj = response.json()
|
|
||||||
key = "Token"
|
|
||||||
if key in root_obj:
|
|
||||||
token = root_obj[key]["Id"]
|
|
||||||
expire_time = root_obj[key]["ExpireTime"]
|
|
||||||
return token, expire_time
|
|
||||||
# print(response.text)
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
|
|
||||||
# 新增空值判断逻辑
|
|
||||||
self.access_key_id = config.get("access_key_id")
|
|
||||||
self.access_key_secret = config.get("access_key_secret")
|
|
||||||
|
|
||||||
self.appkey = config.get("appkey")
|
|
||||||
self.format = config.get("format", "wav")
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
|
||||||
sample_rate = config.get("sample_rate", "16000")
|
|
||||||
self.sample_rate = int(sample_rate) if sample_rate else 16000
|
|
||||||
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice", "xiaoyun")
|
|
||||||
|
|
||||||
volume = config.get("volume", "50")
|
|
||||||
self.volume = int(volume) if volume else 50
|
|
||||||
|
|
||||||
speech_rate = config.get("speech_rate", "0")
|
|
||||||
self.speech_rate = int(speech_rate) if speech_rate else 0
|
|
||||||
|
|
||||||
pitch_rate = config.get("pitch_rate", "0")
|
|
||||||
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
|
|
||||||
|
|
||||||
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
|
|
||||||
self.api_url = f"https://{self.host}/stream/v1/tts"
|
|
||||||
self.header = {"Content-Type": "application/json"}
|
|
||||||
|
|
||||||
if self.access_key_id and self.access_key_secret:
|
|
||||||
# 使用密钥对生成临时token
|
|
||||||
self._refresh_token()
|
|
||||||
else:
|
|
||||||
# 直接使用预生成的长期token
|
|
||||||
self.token = config.get("token")
|
|
||||||
self.expire_time = None
|
|
||||||
|
|
||||||
def _refresh_token(self):
|
|
||||||
"""刷新Token并记录过期时间"""
|
|
||||||
if self.access_key_id and self.access_key_secret:
|
|
||||||
self.token, expire_time_str = AccessToken.create_token(
|
|
||||||
self.access_key_id, self.access_key_secret
|
|
||||||
)
|
|
||||||
if not expire_time_str:
|
|
||||||
raise ValueError("无法获取有效的Token过期时间")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 统一转换为字符串处理
|
|
||||||
expire_str = str(expire_time_str).strip()
|
|
||||||
|
|
||||||
if expire_str.isdigit():
|
|
||||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
|
||||||
else:
|
|
||||||
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
|
|
||||||
self.expire_time = expire_time.timestamp() - 60
|
|
||||||
except Exception as e:
|
|
||||||
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
|
|
||||||
|
|
||||||
else:
|
|
||||||
self.expire_time = None
|
|
||||||
|
|
||||||
if not self.token:
|
|
||||||
raise ValueError("无法获取有效的访问Token")
|
|
||||||
|
|
||||||
def _is_token_expired(self):
|
|
||||||
"""检查Token是否过期"""
|
|
||||||
if not self.expire_time:
|
|
||||||
return False # 长期Token不过期
|
|
||||||
# 新增调试日志
|
|
||||||
# current_time = time.time()
|
|
||||||
# remaining = self.expire_time - current_time
|
|
||||||
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
|
|
||||||
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
|
|
||||||
# f"剩余 {remaining:.2f}秒")
|
|
||||||
return time.time() > self.expire_time
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
if self._is_token_expired():
|
|
||||||
logger.warning("Token已过期,正在自动刷新...")
|
|
||||||
self._refresh_token()
|
|
||||||
request_json = {
|
|
||||||
"appkey": self.appkey,
|
|
||||||
"token": self.token,
|
|
||||||
"text": text,
|
|
||||||
"format": self.format,
|
|
||||||
"sample_rate": self.sample_rate,
|
|
||||||
"voice": self.voice,
|
|
||||||
"volume": self.volume,
|
|
||||||
"speech_rate": self.speech_rate,
|
|
||||||
"pitch_rate": self.pitch_rate,
|
|
||||||
}
|
|
||||||
|
|
||||||
# print(self.api_url, json.dumps(request_json, ensure_ascii=False))
|
|
||||||
try:
|
|
||||||
resp = requests.post(
|
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
|
||||||
)
|
|
||||||
if resp.status_code == 401: # Token过期特殊处理
|
|
||||||
self._refresh_token()
|
|
||||||
resp = requests.post(
|
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
|
||||||
)
|
|
||||||
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
|
|
||||||
if resp.headers["Content-Type"].startswith("audio/"):
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as f:
|
|
||||||
f.write(resp.content)
|
|
||||||
return output_file
|
|
||||||
else:
|
|
||||||
return resp.content
|
|
||||||
else:
|
|
||||||
raise Exception(
|
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
|
||||||
|
|
@ -1,607 +0,0 @@
|
||||||
import random
|
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import hmac
|
|
||||||
import hashlib
|
|
||||||
import base64
|
|
||||||
import time
|
|
||||||
import queue
|
|
||||||
import asyncio
|
|
||||||
import traceback
|
|
||||||
from asyncio import Task
|
|
||||||
import websockets
|
|
||||||
import os
|
|
||||||
from datetime import datetime
|
|
||||||
from urllib import parse
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
|
||||||
from core.utils.tts import MarkdownCleaner
|
|
||||||
from core.utils import opus_encoder_utils, textUtils
|
|
||||||
from config.logger import setup_logging
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class AccessToken:
|
|
||||||
@staticmethod
|
|
||||||
def _encode_text(text):
|
|
||||||
encoded_text = parse.quote_plus(text)
|
|
||||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _encode_dict(dic):
|
|
||||||
keys = dic.keys()
|
|
||||||
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
|
|
||||||
encoded_text = parse.urlencode(dic_sorted)
|
|
||||||
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def create_token(access_key_id, access_key_secret):
|
|
||||||
parameters = {
|
|
||||||
"AccessKeyId": access_key_id,
|
|
||||||
"Action": "CreateToken",
|
|
||||||
"Format": "JSON",
|
|
||||||
"RegionId": "cn-shanghai", # 使用上海地域进行Token获取
|
|
||||||
"SignatureMethod": "HMAC-SHA1",
|
|
||||||
"SignatureNonce": str(uuid.uuid1()),
|
|
||||||
"SignatureVersion": "1.0",
|
|
||||||
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
||||||
"Version": "2019-02-28",
|
|
||||||
}
|
|
||||||
|
|
||||||
query_string = AccessToken._encode_dict(parameters)
|
|
||||||
string_to_sign = (
|
|
||||||
"GET"
|
|
||||||
+ "&"
|
|
||||||
+ AccessToken._encode_text("/")
|
|
||||||
+ "&"
|
|
||||||
+ AccessToken._encode_text(query_string)
|
|
||||||
)
|
|
||||||
|
|
||||||
secreted_string = hmac.new(
|
|
||||||
bytes(access_key_secret + "&", encoding="utf-8"),
|
|
||||||
bytes(string_to_sign, encoding="utf-8"),
|
|
||||||
hashlib.sha1,
|
|
||||||
).digest()
|
|
||||||
signature = base64.b64encode(secreted_string)
|
|
||||||
signature = AccessToken._encode_text(signature)
|
|
||||||
|
|
||||||
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
|
|
||||||
signature,
|
|
||||||
query_string,
|
|
||||||
)
|
|
||||||
|
|
||||||
import requests
|
|
||||||
|
|
||||||
response = requests.get(full_url)
|
|
||||||
if response.ok:
|
|
||||||
root_obj = response.json()
|
|
||||||
key = "Token"
|
|
||||||
if key in root_obj:
|
|
||||||
token = root_obj[key]["Id"]
|
|
||||||
expire_time = root_obj[key]["ExpireTime"]
|
|
||||||
return token, expire_time
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
|
|
||||||
# 设置为流式接口类型
|
|
||||||
self.interface_type = InterfaceType.DUAL_STREAM
|
|
||||||
|
|
||||||
# 基础配置
|
|
||||||
self.access_key_id = config.get("access_key_id")
|
|
||||||
self.access_key_secret = config.get("access_key_secret")
|
|
||||||
self.appkey = config.get("appkey")
|
|
||||||
self.format = config.get("format", "pcm")
|
|
||||||
self.audio_file_type = config.get("format", "pcm")
|
|
||||||
|
|
||||||
# 采样率配置
|
|
||||||
sample_rate = config.get("sample_rate", "16000")
|
|
||||||
self.sample_rate = int(sample_rate) if sample_rate else 16000
|
|
||||||
|
|
||||||
# 音色配置 - CosyVoice大模型音色
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice", "longxiaochun") # CosyVoice默认音色
|
|
||||||
|
|
||||||
# 音频参数配置
|
|
||||||
volume = config.get("volume", "50")
|
|
||||||
self.volume = int(volume) if volume else 50
|
|
||||||
|
|
||||||
speech_rate = config.get("speech_rate", "0")
|
|
||||||
self.speech_rate = int(speech_rate) if speech_rate else 0
|
|
||||||
|
|
||||||
pitch_rate = config.get("pitch_rate", "0")
|
|
||||||
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
|
|
||||||
|
|
||||||
# WebSocket配置
|
|
||||||
self.host = config.get("host", "nls-gateway-cn-beijing.aliyuncs.com")
|
|
||||||
# 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议
|
|
||||||
if "-internal." in self.host:
|
|
||||||
self.ws_url = f"ws://{self.host}/ws/v1"
|
|
||||||
else:
|
|
||||||
# 默认使用wss协议
|
|
||||||
self.ws_url = f"wss://{self.host}/ws/v1"
|
|
||||||
self.ws = None
|
|
||||||
self._monitor_task = None
|
|
||||||
self.last_active_time = None
|
|
||||||
|
|
||||||
# 专属tts设置
|
|
||||||
self.task_id = uuid.uuid4().hex
|
|
||||||
|
|
||||||
# 创建Opus编码器
|
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
|
||||||
sample_rate=16000, channels=1, frame_size_ms=60
|
|
||||||
)
|
|
||||||
|
|
||||||
# Token管理
|
|
||||||
if self.access_key_id and self.access_key_secret:
|
|
||||||
self._refresh_token()
|
|
||||||
else:
|
|
||||||
self.token = config.get("token")
|
|
||||||
self.expire_time = None
|
|
||||||
|
|
||||||
def _refresh_token(self):
|
|
||||||
"""刷新Token并记录过期时间"""
|
|
||||||
if self.access_key_id and self.access_key_secret:
|
|
||||||
self.token, expire_time_str = AccessToken.create_token(
|
|
||||||
self.access_key_id, self.access_key_secret
|
|
||||||
)
|
|
||||||
if not expire_time_str:
|
|
||||||
raise ValueError("无法获取有效的Token过期时间")
|
|
||||||
|
|
||||||
expire_str = str(expire_time_str).strip()
|
|
||||||
|
|
||||||
try:
|
|
||||||
if expire_str.isdigit():
|
|
||||||
expire_time = datetime.fromtimestamp(int(expire_str))
|
|
||||||
else:
|
|
||||||
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
|
|
||||||
self.expire_time = expire_time.timestamp() - 60
|
|
||||||
except Exception as e:
|
|
||||||
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
|
|
||||||
else:
|
|
||||||
self.expire_time = None
|
|
||||||
|
|
||||||
if not self.token:
|
|
||||||
raise ValueError("无法获取有效的访问Token")
|
|
||||||
|
|
||||||
def _is_token_expired(self):
|
|
||||||
"""检查Token是否过期"""
|
|
||||||
if not self.expire_time:
|
|
||||||
return False
|
|
||||||
return time.time() > self.expire_time
|
|
||||||
|
|
||||||
async def _ensure_connection(self):
|
|
||||||
"""确保WebSocket连接可用"""
|
|
||||||
try:
|
|
||||||
if self._is_token_expired():
|
|
||||||
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
|
|
||||||
self._refresh_token()
|
|
||||||
current_time = time.time()
|
|
||||||
if self.ws and current_time - self.last_active_time < 10:
|
|
||||||
# 10秒内才可以复用链接进行连续对话
|
|
||||||
self.task_id = uuid.uuid4().hex
|
|
||||||
logger.bind(tag=TAG).info(f"使用已有链接..., task_id: {self.task_id}")
|
|
||||||
return self.ws
|
|
||||||
logger.bind(tag=TAG).info("开始建立新连接...")
|
|
||||||
|
|
||||||
self.ws = await websockets.connect(
|
|
||||||
self.ws_url,
|
|
||||||
additional_headers={"X-NLS-Token": self.token},
|
|
||||||
ping_interval=30,
|
|
||||||
ping_timeout=10,
|
|
||||||
close_timeout=10,
|
|
||||||
)
|
|
||||||
self.task_id = uuid.uuid4().hex
|
|
||||||
logger.bind(tag=TAG).info(f"WebSocket连接建立成功, task_id: {self.task_id}")
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
return self.ws
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
|
|
||||||
self.ws = None
|
|
||||||
self.last_active_time = None
|
|
||||||
raise
|
|
||||||
|
|
||||||
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 message.sentence_type == SentenceType.FIRST:
|
|
||||||
self.conn.client_abort = False
|
|
||||||
|
|
||||||
if self.conn.client_abort:
|
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
|
||||||
continue
|
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
|
||||||
# 初始化参数
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).info("开始启动TTS会话...")
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.start_session(self.task_id),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
self.before_stop_play_files.clear()
|
|
||||||
logger.bind(tag=TAG).info("TTS会话启动成功")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
|
||||||
if message.content_detail:
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"开始发送TTS文本: {message.content_detail}"
|
|
||||||
)
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.text_to_speak(message.content_detail, None),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
logger.bind(tag=TAG).debug("TTS文本发送成功")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"添加音频文件到待播放列表: {message.content_file}"
|
|
||||||
)
|
|
||||||
if message.content_file and os.path.exists(message.content_file):
|
|
||||||
# 先处理文件音频数据
|
|
||||||
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).info("开始结束TTS会话...")
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.finish_session(self.task_id),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
except queue.Empty:
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
|
|
||||||
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)
|
|
||||||
run_request = {
|
|
||||||
"header": {
|
|
||||||
"message_id": uuid.uuid4().hex,
|
|
||||||
"task_id": self.task_id,
|
|
||||||
"namespace": "FlowingSpeechSynthesizer",
|
|
||||||
"name": "RunSynthesis",
|
|
||||||
"appkey": self.appkey,
|
|
||||||
},
|
|
||||||
"payload": {"text": filtered_text},
|
|
||||||
}
|
|
||||||
await self.ws.send(json.dumps(run_request))
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
return
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def start_session(self, task_id):
|
|
||||||
logger.bind(tag=TAG).info("开始会话~~")
|
|
||||||
try:
|
|
||||||
# 会话开始时检测上个会话的监听状态
|
|
||||||
if (
|
|
||||||
self._monitor_task is not None
|
|
||||||
and isinstance(self._monitor_task, Task)
|
|
||||||
and not self._monitor_task.done()
|
|
||||||
):
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
"检测到未完成的上个会话,关闭监听任务和连接..."
|
|
||||||
)
|
|
||||||
await self.close()
|
|
||||||
|
|
||||||
# 建立新连接
|
|
||||||
await self._ensure_connection()
|
|
||||||
|
|
||||||
# 启动监听任务
|
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
|
||||||
|
|
||||||
start_request = {
|
|
||||||
"header": {
|
|
||||||
"message_id": uuid.uuid4().hex,
|
|
||||||
"task_id": self.task_id,
|
|
||||||
"namespace": "FlowingSpeechSynthesizer",
|
|
||||||
"name": "StartSynthesis",
|
|
||||||
"appkey": self.appkey,
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"voice": self.voice,
|
|
||||||
"format": self.format,
|
|
||||||
"sample_rate": self.sample_rate,
|
|
||||||
"volume": self.volume,
|
|
||||||
"speech_rate": self.speech_rate,
|
|
||||||
"pitch_rate": self.pitch_rate,
|
|
||||||
"enable_subtitle": True,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
await self.ws.send(json.dumps(start_request))
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
logger.bind(tag=TAG).info("会话启动请求已发送")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
|
||||||
# 确保清理资源
|
|
||||||
await self.close()
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def finish_session(self, task_id):
|
|
||||||
logger.bind(tag=TAG).info(f"关闭会话~~{task_id}")
|
|
||||||
try:
|
|
||||||
if self.ws:
|
|
||||||
stop_request = {
|
|
||||||
"header": {
|
|
||||||
"message_id": uuid.uuid4().hex,
|
|
||||||
"task_id": self.task_id,
|
|
||||||
"namespace": "FlowingSpeechSynthesizer",
|
|
||||||
"name": "StopSynthesis",
|
|
||||||
"appkey": self.appkey,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await self.ws.send(json.dumps(stop_request))
|
|
||||||
logger.bind(tag=TAG).info("会话结束请求已发送")
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
if 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
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
|
|
||||||
# 确保清理资源
|
|
||||||
await self.close()
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""资源清理"""
|
|
||||||
if self._monitor_task:
|
|
||||||
try:
|
|
||||||
self._monitor_task.cancel()
|
|
||||||
await self._monitor_task
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
self.last_active_time = None
|
|
||||||
|
|
||||||
async def _start_monitor_tts_response(self):
|
|
||||||
"""监听TTS响应"""
|
|
||||||
try:
|
|
||||||
session_finished = False # 标记会话是否正常结束
|
|
||||||
while not self.conn.stop_event.is_set():
|
|
||||||
try:
|
|
||||||
msg = await self.ws.recv()
|
|
||||||
self.last_active_time = time.time()
|
|
||||||
# 检查客户端是否中止
|
|
||||||
if self.conn.client_abort:
|
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
|
|
||||||
break
|
|
||||||
if isinstance(msg, str): # 文本控制消息
|
|
||||||
try:
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
event_name = header.get("name")
|
|
||||||
if event_name == "SynthesisStarted":
|
|
||||||
logger.bind(tag=TAG).debug("TTS合成已启动")
|
|
||||||
self.tts_audio_queue.put(
|
|
||||||
(SentenceType.FIRST, [], None)
|
|
||||||
)
|
|
||||||
elif event_name == "SentenceEnd":
|
|
||||||
# 发送缓存的数据
|
|
||||||
if self.conn.tts_MessageText:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"句子语音生成成功: {self.conn.tts_MessageText}"
|
|
||||||
)
|
|
||||||
self.tts_audio_queue.put(
|
|
||||||
(SentenceType.FIRST, [], self.conn.tts_MessageText)
|
|
||||||
)
|
|
||||||
self.conn.tts_MessageText = None
|
|
||||||
elif event_name == "SynthesisCompleted":
|
|
||||||
logger.bind(tag=TAG).debug(f"会话结束~~")
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
session_finished = True
|
|
||||||
break
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
|
||||||
# 二进制消息(音频数据)
|
|
||||||
elif isinstance(msg, (bytes, bytearray)):
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(msg, False, self.handle_opus)
|
|
||||||
except websockets.ConnectionClosed:
|
|
||||||
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
break
|
|
||||||
# 仅在连接异常时才关闭
|
|
||||||
if not session_finished and self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
# 监听任务退出时清理引用
|
|
||||||
finally:
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景"""
|
|
||||||
try:
|
|
||||||
# 创建新的事件循环
|
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(loop)
|
|
||||||
|
|
||||||
# 存储音频数据
|
|
||||||
audio_data = []
|
|
||||||
|
|
||||||
async def _generate_audio():
|
|
||||||
# 刷新Token(如果需要)
|
|
||||||
if self._is_token_expired():
|
|
||||||
self._refresh_token()
|
|
||||||
|
|
||||||
# 建立WebSocket连接
|
|
||||||
ws = await websockets.connect(
|
|
||||||
self.ws_url,
|
|
||||||
additional_headers={"X-NLS-Token": self.token},
|
|
||||||
ping_interval=30,
|
|
||||||
ping_timeout=10,
|
|
||||||
close_timeout=10,
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
# 发送StartSynthesis请求
|
|
||||||
start_request = {
|
|
||||||
"header": {
|
|
||||||
"message_id": uuid.uuid4().hex,
|
|
||||||
"task_id": self.task_id,
|
|
||||||
"namespace": "FlowingSpeechSynthesizer",
|
|
||||||
"name": "StartSynthesis",
|
|
||||||
"appkey": self.appkey,
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"voice": self.voice,
|
|
||||||
"format": self.format,
|
|
||||||
"sample_rate": self.sample_rate,
|
|
||||||
"volume": self.volume,
|
|
||||||
"speech_rate": self.speech_rate,
|
|
||||||
"pitch_rate": self.pitch_rate,
|
|
||||||
"enable_subtitle": True,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(start_request))
|
|
||||||
|
|
||||||
# 等待SynthesisStarted响应
|
|
||||||
synthesis_started = False
|
|
||||||
while not synthesis_started:
|
|
||||||
msg = await ws.recv()
|
|
||||||
if isinstance(msg, str):
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
if header.get("name") == "SynthesisStarted":
|
|
||||||
synthesis_started = True
|
|
||||||
logger.bind(tag=TAG).debug("TTS合成已启动")
|
|
||||||
elif header.get("name") == "TaskFailed":
|
|
||||||
error_info = data.get("payload", {}).get(
|
|
||||||
"error_info", {}
|
|
||||||
)
|
|
||||||
error_code = error_info.get("error_code")
|
|
||||||
error_message = error_info.get(
|
|
||||||
"error_message", "未知错误"
|
|
||||||
)
|
|
||||||
raise Exception(
|
|
||||||
f"启动合成失败: {error_code} - {error_message}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 发送文本合成请求
|
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
|
||||||
run_request = {
|
|
||||||
"header": {
|
|
||||||
"message_id": uuid.uuid4().hex,
|
|
||||||
"task_id": self.task_id,
|
|
||||||
"namespace": "FlowingSpeechSynthesizer",
|
|
||||||
"name": "RunSynthesis",
|
|
||||||
"appkey": self.appkey,
|
|
||||||
},
|
|
||||||
"payload": {"text": filtered_text},
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(run_request))
|
|
||||||
|
|
||||||
# 发送停止合成请求
|
|
||||||
stop_request = {
|
|
||||||
"header": {
|
|
||||||
"message_id": uuid.uuid4().hex,
|
|
||||||
"task_id": self.task_id,
|
|
||||||
"namespace": "FlowingSpeechSynthesizer",
|
|
||||||
"name": "StopSynthesis",
|
|
||||||
"appkey": self.appkey,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(stop_request))
|
|
||||||
|
|
||||||
# 接收音频数据
|
|
||||||
synthesis_completed = False
|
|
||||||
while not synthesis_completed:
|
|
||||||
msg = await ws.recv()
|
|
||||||
if isinstance(msg, (bytes, bytearray)):
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
msg,
|
|
||||||
end_of_stream=False,
|
|
||||||
callback=lambda opus: audio_data.append(opus)
|
|
||||||
)
|
|
||||||
elif isinstance(msg, str):
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
event_name = header.get("name")
|
|
||||||
if event_name == "SynthesisCompleted":
|
|
||||||
synthesis_completed = True
|
|
||||||
logger.bind(tag=TAG).debug("TTS合成完成")
|
|
||||||
elif event_name == "TaskFailed":
|
|
||||||
error_info = data.get("payload", {}).get(
|
|
||||||
"error_info", {}
|
|
||||||
)
|
|
||||||
error_code = error_info.get("error_code")
|
|
||||||
error_message = error_info.get(
|
|
||||||
"error_message", "未知错误"
|
|
||||||
)
|
|
||||||
raise Exception(
|
|
||||||
f"合成失败: {error_code} - {error_message}"
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
await ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
loop.run_until_complete(_generate_audio())
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
return audio_data
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
|
|
||||||
return []
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
import requests
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.model = config.get("model")
|
|
||||||
self.access_token = config.get("access_token")
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
|
||||||
self.response_format = config.get("response_format", "wav")
|
|
||||||
self.audio_file_type = config.get("response_format", "wav")
|
|
||||||
self.host = "api.coze.cn"
|
|
||||||
self.api_url = f"https://{self.host}/v1/audio/speech"
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
request_json = {
|
|
||||||
"model": self.model,
|
|
||||||
"input": text,
|
|
||||||
"voice_id": self.voice,
|
|
||||||
"response_format": self.response_format,
|
|
||||||
}
|
|
||||||
headers = {
|
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
response = requests.request(
|
|
||||||
"POST", self.api_url, json=request_json, headers=headers
|
|
||||||
)
|
|
||||||
data = response.content
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as file_to_save:
|
|
||||||
file_to_save.write(data)
|
|
||||||
else:
|
|
||||||
return data
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import base64
|
|
||||||
import requests
|
|
||||||
from core.utils.util import check_model_key
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from config.logger import setup_logging
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
if config.get("appid"):
|
|
||||||
self.appid = int(config.get("appid"))
|
|
||||||
else:
|
|
||||||
self.appid = ""
|
|
||||||
self.access_token = config.get("access_token")
|
|
||||||
self.cluster = config.get("cluster")
|
|
||||||
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
|
||||||
|
|
||||||
# 处理空字符串的情况
|
|
||||||
speed_ratio = config.get("speed_ratio", "1.0")
|
|
||||||
volume_ratio = config.get("volume_ratio", "1.0")
|
|
||||||
pitch_ratio = config.get("pitch_ratio", "1.0")
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
|
||||||
self.speed_ratio = float(speed_ratio) if speed_ratio else 1.0
|
|
||||||
self.volume_ratio = float(volume_ratio) if volume_ratio else 1.0
|
|
||||||
self.pitch_ratio = float(pitch_ratio) if pitch_ratio else 1.0
|
|
||||||
|
|
||||||
self.api_url = config.get("api_url")
|
|
||||||
self.authorization = config.get("authorization")
|
|
||||||
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
|
|
||||||
model_key_msg = check_model_key("TTS", self.access_token)
|
|
||||||
if model_key_msg:
|
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
request_json = {
|
|
||||||
"app": {
|
|
||||||
"appid": f"{self.appid}",
|
|
||||||
"token": self.access_token,
|
|
||||||
"cluster": self.cluster,
|
|
||||||
},
|
|
||||||
"user": {"uid": "1"},
|
|
||||||
"audio": {
|
|
||||||
"voice_type": self.voice,
|
|
||||||
"encoding": self.audio_file_type,
|
|
||||||
"speed_ratio": self.speed_ratio,
|
|
||||||
"volume_ratio": self.volume_ratio,
|
|
||||||
"pitch_ratio": self.pitch_ratio,
|
|
||||||
},
|
|
||||||
"request": {
|
|
||||||
"reqid": str(uuid.uuid4()),
|
|
||||||
"text": text,
|
|
||||||
"text_type": "plain",
|
|
||||||
"operation": "query",
|
|
||||||
"with_frontend": 1,
|
|
||||||
"frontend_type": "unitTson",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp = requests.post(
|
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
|
||||||
)
|
|
||||||
if "data" in resp.json():
|
|
||||||
data = resp.json()["data"]
|
|
||||||
audio_bytes = base64.b64decode(data)
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as file_to_save:
|
|
||||||
file_to_save.write(audio_bytes)
|
|
||||||
else:
|
|
||||||
return audio_bytes
|
|
||||||
else:
|
|
||||||
raise Exception(
|
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
import os
|
|
||||||
import uuid
|
|
||||||
import edge_tts
|
|
||||||
from datetime import datetime
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
|
||||||
self.audio_file_type = config.get("format", "mp3")
|
|
||||||
|
|
||||||
def generate_filename(self, extension=".mp3"):
|
|
||||||
return os.path.join(
|
|
||||||
self.output_file,
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
try:
|
|
||||||
communicate = edge_tts.Communicate(text, voice=self.voice)
|
|
||||||
if output_file:
|
|
||||||
# 确保目录存在并创建空文件
|
|
||||||
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
|
||||||
with open(output_file, "wb") as f:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# 流式写入音频数据
|
|
||||||
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
|
|
||||||
async for chunk in communicate.stream():
|
|
||||||
if chunk["type"] == "audio": # 只处理音频数据块
|
|
||||||
f.write(chunk["data"])
|
|
||||||
else:
|
|
||||||
# 返回音频二进制数据
|
|
||||||
audio_bytes = b""
|
|
||||||
async for chunk in communicate.stream():
|
|
||||||
if chunk["type"] == "audio":
|
|
||||||
audio_bytes += chunk["data"]
|
|
||||||
return audio_bytes
|
|
||||||
except Exception as e:
|
|
||||||
error_msg = f"Edge TTS请求失败: {e}"
|
|
||||||
raise Exception(error_msg) # 抛出异常,让调用方捕获
|
|
||||||
410
main/xiaozhi-server/core/providers/tts/fish_single_stream.py
Normal file
410
main/xiaozhi-server/core/providers/tts/fish_single_stream.py
Normal file
|
|
@ -0,0 +1,410 @@
|
||||||
|
import os
|
||||||
|
import queue
|
||||||
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from core.utils.tts import MarkdownCleaner
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
from core.utils import opus_encoder_utils, textUtils
|
||||||
|
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType, TTSAudioDTO, MessageTag
|
||||||
|
from fishaudio import FishAudio, TTSConfig
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
|
# Mark as streaming interface
|
||||||
|
self.interface_type = InterfaceType.SINGLE_STREAM
|
||||||
|
|
||||||
|
self.model = config.get("model", "speech-1.6")
|
||||||
|
self.reference_id = config.get("reference_id")
|
||||||
|
|
||||||
|
self.format = config.get("response_format", "pcm")
|
||||||
|
self.sample_rate = config.get("sample_rate", 16000)
|
||||||
|
self.audio_file_type = config.get("response_format", "pcm")
|
||||||
|
self.api_key = config.get("api_key", "YOUR_API_KEY")
|
||||||
|
if self.api_key is None:
|
||||||
|
raise ValueError("FishSpeech API key is required")
|
||||||
|
self._client = FishAudio(api_key=self.api_key)
|
||||||
|
|
||||||
|
self.normalize = str(config.get("normalize", True)).lower() in (
|
||||||
|
"true",
|
||||||
|
"1",
|
||||||
|
"yes",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Handle empty string cases
|
||||||
|
channels = config.get("channels", "1")
|
||||||
|
rate = config.get("rate", "44100")
|
||||||
|
max_new_tokens = config.get("max_new_tokens", "1024")
|
||||||
|
chunk_length = config.get("chunk_length", "200")
|
||||||
|
|
||||||
|
self.channels = int(channels) if channels else 1
|
||||||
|
self.rate = int(rate) if rate else 44100
|
||||||
|
self.max_new_tokens = int(max_new_tokens) if max_new_tokens else 1024
|
||||||
|
self.chunk_length = int(chunk_length) if chunk_length else 200
|
||||||
|
|
||||||
|
# Handle empty string cases
|
||||||
|
top_p = config.get("top_p", "0.7")
|
||||||
|
temperature = config.get("temperature", "0.7")
|
||||||
|
repetition_penalty = config.get("repetition_penalty", "1.2")
|
||||||
|
|
||||||
|
self.top_p = float(top_p) if top_p else 0.7
|
||||||
|
self.temperature = float(temperature) if temperature else 0.7
|
||||||
|
self.repetition_penalty = (
|
||||||
|
float(repetition_penalty) if repetition_penalty else 1.2
|
||||||
|
)
|
||||||
|
|
||||||
|
self.streaming = str(config.get("streaming", False)).lower() in (
|
||||||
|
"true",
|
||||||
|
"1",
|
||||||
|
"yes",
|
||||||
|
)
|
||||||
|
self.use_memory_cache = config.get("use_memory_cache", "on")
|
||||||
|
self.seed = int(config.get("seed")) if config.get("seed") else None
|
||||||
|
|
||||||
|
# Initialize Opus encoder (sample_rate should match FishSpeech output)
|
||||||
|
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
||||||
|
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
|
||||||
|
)
|
||||||
|
|
||||||
|
# PCM buffer for accumulating data before encoding
|
||||||
|
self.pcm_buffer = bytearray()
|
||||||
|
|
||||||
|
# Track if we've sent FIRST for this session
|
||||||
|
self._session_started = False
|
||||||
|
# Track first chunk time for latency measurement
|
||||||
|
self._first_chunk_logged = False
|
||||||
|
|
||||||
|
def tts_text_priority_thread(self):
|
||||||
|
"""Streaming text processing thread with lifecycle alignment:
|
||||||
|
- tts_text_queue FIRST -> tts_audio_queue FIRST (session start)
|
||||||
|
- tts_text_queue TEXT (MIDDLE) -> tts_audio_queue MIDDLE (audio chunks)
|
||||||
|
- tts_text_queue LAST -> tts_audio_queue LAST (session end)
|
||||||
|
"""
|
||||||
|
while not self.conn.stop_event.is_set():
|
||||||
|
try:
|
||||||
|
message = self.tts_text_queue.get(timeout=1)
|
||||||
|
|
||||||
|
# Handle FIRST - session start
|
||||||
|
if message.sentence_type == SentenceType.FIRST:
|
||||||
|
self.conn.client_abort = False
|
||||||
|
# Initialize session parameters
|
||||||
|
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._first_chunk_logged = False
|
||||||
|
self._session_started = False
|
||||||
|
self.before_stop_play_files.clear()
|
||||||
|
self.pcm_buffer.clear()
|
||||||
|
self.conn._latency_tts_first_text_time = None
|
||||||
|
logger.bind(tag=TAG).debug("TTS session initialized, waiting for text")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Check for abort
|
||||||
|
if self.conn.client_abort:
|
||||||
|
logger.bind(tag=TAG).info("Received abort signal, skipping TTS processing")
|
||||||
|
# If session was started, send LAST to close it
|
||||||
|
if self._session_started:
|
||||||
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.LAST,
|
||||||
|
audio_data=None,
|
||||||
|
text=None,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
|
self._session_started = False
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Handle TEXT content
|
||||||
|
if ContentType.TEXT == message.content_type:
|
||||||
|
self.tts_text_buff.append(message.content_detail)
|
||||||
|
segment_text = self._get_segment_text()
|
||||||
|
if segment_text:
|
||||||
|
# Record TTS first text input time (for latency tracking)
|
||||||
|
if self.conn._latency_tts_first_text_time is None:
|
||||||
|
self.conn._latency_tts_first_text_time = time.time() * 1000
|
||||||
|
logger.bind(tag=TAG).debug("📝 [Latency] TTS received first text")
|
||||||
|
|
||||||
|
# Process text with streaming TTS
|
||||||
|
self._stream_tts_segment(segment_text)
|
||||||
|
|
||||||
|
# Handle FILE content
|
||||||
|
elif ContentType.FILE == message.content_type:
|
||||||
|
logger.bind(tag=TAG).info(f"Adding audio file: {message.content_file}")
|
||||||
|
if message.content_file and os.path.exists(message.content_file):
|
||||||
|
self._process_audio_file_stream(
|
||||||
|
message.content_file,
|
||||||
|
callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Handle LAST - session end
|
||||||
|
if message.sentence_type == SentenceType.LAST:
|
||||||
|
# Process remaining text
|
||||||
|
self._process_remaining_text()
|
||||||
|
|
||||||
|
# Process any pending audio files and send LAST
|
||||||
|
self._process_before_stop_play_files()
|
||||||
|
|
||||||
|
self._session_started = False
|
||||||
|
self._first_chunk_logged = False
|
||||||
|
logger.bind(tag=TAG).debug("TTS session ended")
|
||||||
|
|
||||||
|
except queue.Empty:
|
||||||
|
continue
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(
|
||||||
|
f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _stream_tts_segment(self, text: str):
|
||||||
|
"""Process a text segment with streaming TTS, sending audio chunks as MIDDLE messages"""
|
||||||
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
if not text.strip():
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).info(f"FishSpeech streaming: {text}")
|
||||||
|
start_time = time.time() * 1000
|
||||||
|
|
||||||
|
# Calculate bytes per frame for Opus encoding
|
||||||
|
frame_bytes = int(
|
||||||
|
self.opus_encoder.sample_rate
|
||||||
|
* self.opus_encoder.channels
|
||||||
|
* self.opus_encoder.frame_size_ms
|
||||||
|
/ 1000
|
||||||
|
* 2 # 16-bit = 2 bytes per sample
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Get audio stream from FishSpeech
|
||||||
|
audio_stream = self._client.tts.stream(
|
||||||
|
text=text,
|
||||||
|
reference_id=self.reference_id,
|
||||||
|
model=self.model,
|
||||||
|
config=TTSConfig(
|
||||||
|
format=self.format,
|
||||||
|
sample_rate=self.sample_rate,
|
||||||
|
normalize=self.normalize,
|
||||||
|
latency="balanced",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Send FIRST for each text segment (triggers sentence_start on client)
|
||||||
|
# This ensures client receives all text segments, not just the first one
|
||||||
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.FIRST,
|
||||||
|
audio_data=None,
|
||||||
|
text=text,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
|
self._session_started = True
|
||||||
|
|
||||||
|
# Process audio stream chunks
|
||||||
|
for chunk in audio_stream:
|
||||||
|
# Check for abort during streaming
|
||||||
|
if self.conn.client_abort:
|
||||||
|
logger.bind(tag=TAG).info("Abort during TTS streaming, stopping")
|
||||||
|
break
|
||||||
|
|
||||||
|
# Log first chunk latency
|
||||||
|
if not self._first_chunk_logged:
|
||||||
|
self._first_chunk_logged = True
|
||||||
|
first_chunk_time = time.time() * 1000
|
||||||
|
self.conn.tts_first_chunk_time = first_chunk_time
|
||||||
|
api_latency = (first_chunk_time - start_time) / 1000
|
||||||
|
logger.bind(tag=TAG).info(f"[Latency] TTS API first chunk: {api_latency:.3f}s")
|
||||||
|
|
||||||
|
# Add chunk to PCM buffer
|
||||||
|
self.pcm_buffer.extend(chunk)
|
||||||
|
|
||||||
|
# Encode and send complete frames as MIDDLE messages
|
||||||
|
while len(self.pcm_buffer) >= frame_bytes:
|
||||||
|
# Check abort again before processing
|
||||||
|
if self.conn.client_abort:
|
||||||
|
break
|
||||||
|
|
||||||
|
frame = bytes(self.pcm_buffer[:frame_bytes])
|
||||||
|
del self.pcm_buffer[:frame_bytes]
|
||||||
|
|
||||||
|
self.opus_encoder.encode_pcm_to_opus_stream(
|
||||||
|
frame, end_of_stream=False, callback=self._handle_opus_middle
|
||||||
|
)
|
||||||
|
|
||||||
|
# Flush remaining data (less than one frame)
|
||||||
|
if self.pcm_buffer and not self.conn.client_abort:
|
||||||
|
self.opus_encoder.encode_pcm_to_opus_stream(
|
||||||
|
bytes(self.pcm_buffer),
|
||||||
|
end_of_stream=True,
|
||||||
|
callback=self._handle_opus_middle,
|
||||||
|
)
|
||||||
|
self.pcm_buffer.clear()
|
||||||
|
|
||||||
|
elapsed = (time.time() * 1000 - start_time) / 1000
|
||||||
|
logger.bind(tag=TAG).debug(f"TTS segment completed in {elapsed:.3f}s: {text[:30]}...")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"FishSpeech streaming error: {e}")
|
||||||
|
# On error, clear buffer to avoid corrupted audio
|
||||||
|
self.pcm_buffer.clear()
|
||||||
|
|
||||||
|
def _handle_opus_middle(self, opus_data: bytes):
|
||||||
|
"""Handle encoded Opus data, send as MIDDLE message"""
|
||||||
|
if self.conn.client_abort:
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).debug(f"Sending opus frame: {len(opus_data)} bytes")
|
||||||
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.MIDDLE,
|
||||||
|
audio_data=opus_data,
|
||||||
|
text=None,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
|
|
||||||
|
def _audio_play_priority_thread(self):
|
||||||
|
"""Override base class to accumulate all segments into one report.
|
||||||
|
|
||||||
|
- Each FIRST still triggers sentence_start on client (for real-time display)
|
||||||
|
- But report accumulates all text segments and audio, only reports on LAST
|
||||||
|
"""
|
||||||
|
from core.utils.output_counter import add_device_output
|
||||||
|
from core.handle.reportHandle import enqueue_tts_report
|
||||||
|
from core.handle.sendAudioHandle import sendAudioMessage
|
||||||
|
from core.utils.opus import pack_opus_with_header
|
||||||
|
|
||||||
|
# Accumulated text and audio for the entire session (one LLM response)
|
||||||
|
session_text_parts = []
|
||||||
|
session_audio = []
|
||||||
|
session_message_tag = MessageTag.NORMAL
|
||||||
|
|
||||||
|
# Track last send future for ordering
|
||||||
|
last_send_future = None
|
||||||
|
|
||||||
|
while not self.conn.stop_event.is_set():
|
||||||
|
text = None
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
tts_audio_message = self.tts_audio_queue.get(timeout=0.1)
|
||||||
|
if isinstance(tts_audio_message, TTSAudioDTO):
|
||||||
|
sentence_type = tts_audio_message.sentence_type
|
||||||
|
audio_datas = tts_audio_message.audio_data
|
||||||
|
text = tts_audio_message.text
|
||||||
|
message_tag = tts_audio_message.message_tag
|
||||||
|
elif isinstance(tts_audio_message, tuple):
|
||||||
|
sentence_type = tts_audio_message[0]
|
||||||
|
audio_datas = tts_audio_message[1]
|
||||||
|
text = tts_audio_message[2]
|
||||||
|
message_tag = MessageTag.NORMAL
|
||||||
|
else:
|
||||||
|
logger.bind(tag=TAG).warning(f"Unknown tts_audio_message type: {type(tts_audio_message)}")
|
||||||
|
continue
|
||||||
|
except queue.Empty:
|
||||||
|
if self.conn.stop_event.is_set():
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
|
||||||
|
if self.conn.client_abort:
|
||||||
|
logger.bind(tag=TAG).debug("Received abort, reporting accumulated content")
|
||||||
|
# Report accumulated content on abort
|
||||||
|
if session_text_parts and session_audio:
|
||||||
|
full_text = "".join(session_text_parts)
|
||||||
|
enqueue_tts_report(self.conn, full_text, session_audio, session_message_tag)
|
||||||
|
logger.bind(tag=TAG).info(f"Abort report: {full_text[:50]}...")
|
||||||
|
session_text_parts, session_audio = [], []
|
||||||
|
last_send_future = None
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Handle FIRST: accumulate text, don't report yet
|
||||||
|
if sentence_type == SentenceType.FIRST:
|
||||||
|
if text:
|
||||||
|
session_text_parts.append(text)
|
||||||
|
session_message_tag = message_tag
|
||||||
|
|
||||||
|
# Handle MIDDLE: accumulate audio
|
||||||
|
if isinstance(audio_datas, bytes):
|
||||||
|
audio_with_header = pack_opus_with_header(audio_datas, message_tag)
|
||||||
|
session_audio.append(audio_with_header)
|
||||||
|
|
||||||
|
# Handle LAST: report the entire accumulated session
|
||||||
|
if sentence_type == SentenceType.LAST:
|
||||||
|
if session_text_parts or session_audio:
|
||||||
|
full_text = "".join(session_text_parts)
|
||||||
|
if full_text and session_audio:
|
||||||
|
enqueue_tts_report(self.conn, full_text, session_audio, session_message_tag)
|
||||||
|
logger.bind(tag=TAG).info(f"Session report: {full_text[:80]}...")
|
||||||
|
session_text_parts, session_audio = [], []
|
||||||
|
|
||||||
|
# Wait for previous send to complete (maintain order)
|
||||||
|
if last_send_future is not None:
|
||||||
|
try:
|
||||||
|
last_send_future.result(timeout=5.0)
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"Previous audio send timeout: {e}")
|
||||||
|
|
||||||
|
# Send audio to client (async, non-blocking)
|
||||||
|
last_send_future = asyncio.run_coroutine_threadsafe(
|
||||||
|
sendAudioMessage(self.conn, sentence_type, audio_datas, text, message_tag),
|
||||||
|
self.conn.loop,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Track output
|
||||||
|
if self.conn.max_output_size > 0 and text:
|
||||||
|
add_device_output(self.conn.headers.get("device-id"), len(text))
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"_audio_play_priority_thread error: {text} {e}")
|
||||||
|
|
||||||
|
# On connection close, report remaining accumulated data
|
||||||
|
if session_text_parts and session_audio:
|
||||||
|
try:
|
||||||
|
full_text = "".join(session_text_parts)
|
||||||
|
enqueue_tts_report(self.conn, full_text, session_audio, session_message_tag)
|
||||||
|
logger.bind(tag=TAG).info(f"Connection close report: {full_text}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"Connection close report failed: {e}")
|
||||||
|
|
||||||
|
def _process_remaining_text(self):
|
||||||
|
"""Process any remaining text in buffer"""
|
||||||
|
full_text = "".join(self.tts_text_buff)
|
||||||
|
remaining_text = full_text[self.processed_chars:]
|
||||||
|
if remaining_text:
|
||||||
|
segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
|
||||||
|
if segment_text:
|
||||||
|
self._stream_tts_segment(segment_text)
|
||||||
|
self.processed_chars = len(full_text)
|
||||||
|
|
||||||
|
async def text_to_speak(self, text, output_file):
|
||||||
|
"""Non-streaming TTS interface (required by base class)
|
||||||
|
|
||||||
|
This provider primarily uses streaming, but this method is needed
|
||||||
|
for compatibility with base class abstract method.
|
||||||
|
"""
|
||||||
|
text = MarkdownCleaner.clean_markdown(text)
|
||||||
|
audio_bytes = self._client.tts.convert(
|
||||||
|
text=text,
|
||||||
|
reference_id=self.reference_id,
|
||||||
|
model=self.model,
|
||||||
|
config=TTSConfig(
|
||||||
|
format=self.format,
|
||||||
|
sample_rate=self.sample_rate,
|
||||||
|
normalize=self.normalize,
|
||||||
|
latency="balanced",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if output_file:
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
f.write(audio_bytes)
|
||||||
|
return audio_bytes
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
"""Resource cleanup"""
|
||||||
|
await super().close()
|
||||||
|
if hasattr(self, "opus_encoder"):
|
||||||
|
self.opus_encoder.close()
|
||||||
|
|
@ -1,103 +0,0 @@
|
||||||
import requests
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.utils.util import parse_string_to_list
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.url = config.get("url")
|
|
||||||
self.text_lang = config.get("text_lang", "zh")
|
|
||||||
self.ref_audio_path = config.get('ref_audio') if config.get('ref_audio') else config.get("ref_audio_path")
|
|
||||||
self.prompt_text = config.get('ref_text') if config.get('ref_text') else config.get("prompt_text")
|
|
||||||
self.prompt_lang = config.get("prompt_lang", "zh")
|
|
||||||
|
|
||||||
# 处理空字符串的情况
|
|
||||||
top_k = config.get("top_k", "5")
|
|
||||||
top_p = config.get("top_p", "1")
|
|
||||||
temperature = config.get("temperature", "1")
|
|
||||||
batch_threshold = config.get("batch_threshold", "0.75")
|
|
||||||
batch_size = config.get("batch_size", "1")
|
|
||||||
speed_factor = config.get("speed_factor", "1.0")
|
|
||||||
seed = config.get("seed", "-1")
|
|
||||||
repetition_penalty = config.get("repetition_penalty", "1.35")
|
|
||||||
|
|
||||||
self.top_k = int(top_k) if top_k else 5
|
|
||||||
self.top_p = float(top_p) if top_p else 1
|
|
||||||
self.temperature = float(temperature) if temperature else 1
|
|
||||||
self.batch_threshold = float(batch_threshold) if batch_threshold else 0.75
|
|
||||||
self.batch_size = int(batch_size) if batch_size else 1
|
|
||||||
self.speed_factor = float(speed_factor) if speed_factor else 1.0
|
|
||||||
self.seed = int(seed) if seed else -1
|
|
||||||
self.repetition_penalty = (
|
|
||||||
float(repetition_penalty) if repetition_penalty else 1.35
|
|
||||||
)
|
|
||||||
|
|
||||||
self.text_split_method = config.get("text_split_method", "cut0")
|
|
||||||
|
|
||||||
self.split_bucket = str(config.get("split_bucket", True)).lower() in (
|
|
||||||
"true",
|
|
||||||
"1",
|
|
||||||
"yes",
|
|
||||||
)
|
|
||||||
self.return_fragment = str(config.get("return_fragment", False)).lower() in (
|
|
||||||
"true",
|
|
||||||
"1",
|
|
||||||
"yes",
|
|
||||||
)
|
|
||||||
|
|
||||||
self.streaming_mode = str(config.get("streaming_mode", False)).lower() in (
|
|
||||||
"true",
|
|
||||||
"1",
|
|
||||||
"yes",
|
|
||||||
)
|
|
||||||
|
|
||||||
self.parallel_infer = str(config.get("parallel_infer", True)).lower() in (
|
|
||||||
"true",
|
|
||||||
"1",
|
|
||||||
"yes",
|
|
||||||
)
|
|
||||||
|
|
||||||
self.aux_ref_audio_paths = parse_string_to_list(
|
|
||||||
config.get("aux_ref_audio_paths")
|
|
||||||
)
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
request_json = {
|
|
||||||
"text": text,
|
|
||||||
"text_lang": self.text_lang,
|
|
||||||
"ref_audio_path": self.ref_audio_path,
|
|
||||||
"aux_ref_audio_paths": self.aux_ref_audio_paths,
|
|
||||||
"prompt_text": self.prompt_text,
|
|
||||||
"prompt_lang": self.prompt_lang,
|
|
||||||
"top_k": self.top_k,
|
|
||||||
"top_p": self.top_p,
|
|
||||||
"temperature": self.temperature,
|
|
||||||
"text_split_method": self.text_split_method,
|
|
||||||
"batch_size": self.batch_size,
|
|
||||||
"batch_threshold": self.batch_threshold,
|
|
||||||
"split_bucket": self.split_bucket,
|
|
||||||
"return_fragment": self.return_fragment,
|
|
||||||
"speed_factor": self.speed_factor,
|
|
||||||
"streaming_mode": self.streaming_mode,
|
|
||||||
"seed": self.seed,
|
|
||||||
"parallel_infer": self.parallel_infer,
|
|
||||||
"repetition_penalty": self.repetition_penalty,
|
|
||||||
}
|
|
||||||
|
|
||||||
resp = requests.post(self.url, json=request_json)
|
|
||||||
if resp.status_code == 200:
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as file:
|
|
||||||
file.write(resp.content)
|
|
||||||
else:
|
|
||||||
return resp.content
|
|
||||||
else:
|
|
||||||
error_msg = f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}"
|
|
||||||
logger.bind(tag=TAG).error(error_msg)
|
|
||||||
raise Exception(error_msg)
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
import requests
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.utils.util import parse_string_to_list
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.url = config.get("url")
|
|
||||||
self.refer_wav_path = config.get('ref_audio')if config.get('ref_audio') else config.get("refer_wav_path")
|
|
||||||
self.prompt_text = config.get('ref_text')if config.get('ref_text') else config.get("prompt_text")
|
|
||||||
self.prompt_language = config.get("prompt_language")
|
|
||||||
self.text_language = config.get("text_language", "audo")
|
|
||||||
|
|
||||||
# 处理空字符串的情况
|
|
||||||
top_k = config.get("top_k", "15")
|
|
||||||
top_p = config.get("top_p", "1.0")
|
|
||||||
temperature = config.get("temperature", "1.0")
|
|
||||||
sample_steps = config.get("sample_steps", "32")
|
|
||||||
speed = config.get("speed", "1.0")
|
|
||||||
|
|
||||||
self.top_k = int(top_k) if top_k else 15
|
|
||||||
self.top_p = float(top_p) if top_p else 1.0
|
|
||||||
self.temperature = float(temperature) if temperature else 1.0
|
|
||||||
self.sample_steps = int(sample_steps) if sample_steps else 32
|
|
||||||
self.speed = float(speed) if speed else 1.0
|
|
||||||
|
|
||||||
self.cut_punc = config.get("cut_punc", "")
|
|
||||||
self.inp_refs = parse_string_to_list(config.get("inp_refs"))
|
|
||||||
self.if_sr = str(config.get("if_sr", False)).lower() in ("true", "1", "yes")
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
request_params = {
|
|
||||||
"refer_wav_path": self.refer_wav_path,
|
|
||||||
"prompt_text": self.prompt_text,
|
|
||||||
"prompt_language": self.prompt_language,
|
|
||||||
"text": text,
|
|
||||||
"text_language": self.text_language,
|
|
||||||
"top_k": self.top_k,
|
|
||||||
"top_p": self.top_p,
|
|
||||||
"temperature": self.temperature,
|
|
||||||
"cut_punc": self.cut_punc,
|
|
||||||
"speed": self.speed,
|
|
||||||
"inp_refs": self.inp_refs,
|
|
||||||
"sample_steps": self.sample_steps,
|
|
||||||
"if_sr": self.if_sr,
|
|
||||||
}
|
|
||||||
|
|
||||||
resp = requests.get(self.url, params=request_params)
|
|
||||||
if resp.status_code == 200:
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as file:
|
|
||||||
file.write(resp.content)
|
|
||||||
else:
|
|
||||||
return resp.content
|
|
||||||
else:
|
|
||||||
error_msg = f"GPT_SoVITS_V3 TTS请求失败: {resp.status_code} - {resp.text}"
|
|
||||||
logger.bind(tag=TAG).error(error_msg)
|
|
||||||
raise Exception(error_msg)
|
|
||||||
|
|
@ -1,235 +0,0 @@
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import queue
|
|
||||||
import aiohttp
|
|
||||||
import asyncio
|
|
||||||
import requests
|
|
||||||
import traceback
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.utils.tts import MarkdownCleaner
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.utils import opus_encoder_utils, textUtils
|
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.interface_type = InterfaceType.SINGLE_STREAM
|
|
||||||
self.voice = config.get("voice", "xiao_he")
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice", "xiao_he")
|
|
||||||
self.api_url = config.get("api_url", "http://8.138.114.124:11996/tts")
|
|
||||||
self.audio_format = "pcm"
|
|
||||||
self.before_stop_play_files = []
|
|
||||||
|
|
||||||
# 创建Opus编码器 需注意接口返回的采样率为24000
|
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
|
||||||
sample_rate=24000, channels=1, frame_size_ms=60
|
|
||||||
)
|
|
||||||
|
|
||||||
# PCM缓冲区
|
|
||||||
self.pcm_buffer = bytearray()
|
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
|
||||||
"""流式文本处理线程"""
|
|
||||||
while not self.conn.stop_event.is_set():
|
|
||||||
try:
|
|
||||||
message = self.tts_text_queue.get(timeout=1)
|
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
|
||||||
# 初始化参数
|
|
||||||
self.tts_stop_request = False
|
|
||||||
self.processed_chars = 0
|
|
||||||
self.tts_text_buff = []
|
|
||||||
self.before_stop_play_files.clear()
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
|
||||||
self.tts_text_buff.append(message.content_detail)
|
|
||||||
segment_text = self._get_segment_text()
|
|
||||||
if segment_text:
|
|
||||||
self.to_tts_single_stream(segment_text)
|
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"添加音频文件到待播放列表: {message.content_file}"
|
|
||||||
)
|
|
||||||
if message.content_file and os.path.exists(message.content_file):
|
|
||||||
# 先处理文件音频数据
|
|
||||||
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
|
|
||||||
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
|
||||||
# 处理剩余的文本
|
|
||||||
self._process_remaining_text_stream(True)
|
|
||||||
|
|
||||||
except queue.Empty:
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def _process_remaining_text_stream(self, is_last=False):
|
|
||||||
"""处理剩余的文本并生成语音
|
|
||||||
Returns:
|
|
||||||
bool: 是否成功处理了文本
|
|
||||||
"""
|
|
||||||
full_text = "".join(self.tts_text_buff)
|
|
||||||
remaining_text = full_text[self.processed_chars :]
|
|
||||||
if remaining_text:
|
|
||||||
segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
|
|
||||||
if segment_text:
|
|
||||||
self.to_tts_single_stream(segment_text, is_last)
|
|
||||||
self.processed_chars += len(full_text)
|
|
||||||
else:
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
else:
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
|
|
||||||
def to_tts_single_stream(self, text, is_last=False):
|
|
||||||
try:
|
|
||||||
max_repeat_time = 5
|
|
||||||
text = MarkdownCleaner.clean_markdown(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}次: {text},错误: {e}"
|
|
||||||
)
|
|
||||||
max_repeat_time -= 1
|
|
||||||
|
|
||||||
if max_repeat_time > 0:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
|
||||||
)
|
|
||||||
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音频,每句只推送一次音频列表"""
|
|
||||||
payload = {"text": text, "character": self.voice}
|
|
||||||
|
|
||||||
frame_bytes = int(
|
|
||||||
self.opus_encoder.sample_rate
|
|
||||||
* self.opus_encoder.channels # 1
|
|
||||||
* self.opus_encoder.frame_size_ms
|
|
||||||
/ 1000
|
|
||||||
* 2
|
|
||||||
) # 16-bit = 2 bytes
|
|
||||||
try:
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.post(self.api_url, json=payload, timeout=10) as resp:
|
|
||||||
|
|
||||||
if resp.status != 200:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"TTS请求失败: {resp.status}, {await resp.text()}"
|
|
||||||
)
|
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
|
||||||
return
|
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
|
||||||
|
|
||||||
# 处理音频流数据
|
|
||||||
async for chunk in resp.content.iter_any():
|
|
||||||
data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk
|
|
||||||
if not data:
|
|
||||||
continue
|
|
||||||
|
|
||||||
self.pcm_buffer.extend(data)
|
|
||||||
|
|
||||||
while len(self.pcm_buffer) >= frame_bytes:
|
|
||||||
frame = bytes(self.pcm_buffer[:frame_bytes])
|
|
||||||
del self.pcm_buffer[:frame_bytes]
|
|
||||||
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
frame,
|
|
||||||
end_of_stream=False,
|
|
||||||
callback=self.handle_opus
|
|
||||||
)
|
|
||||||
|
|
||||||
# flush 剩余不足一帧的数据
|
|
||||||
if self.pcm_buffer:
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
bytes(self.pcm_buffer),
|
|
||||||
end_of_stream=True,
|
|
||||||
callback=self.handle_opus
|
|
||||||
)
|
|
||||||
self.pcm_buffer.clear()
|
|
||||||
|
|
||||||
# 如果是最后一段,输出音频获取完毕
|
|
||||||
if is_last:
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""资源清理"""
|
|
||||||
await super().close()
|
|
||||||
if hasattr(self, "opus_encoder"):
|
|
||||||
self.opus_encoder.close()
|
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景
|
|
||||||
Args:
|
|
||||||
text: 要转换的文本
|
|
||||||
Returns:
|
|
||||||
list: 返回opus编码后的音频数据列表
|
|
||||||
"""
|
|
||||||
start_time = time.time()
|
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
|
||||||
|
|
||||||
payload = {"text": text, "character": self.voice}
|
|
||||||
|
|
||||||
try:
|
|
||||||
with requests.post(self.api_url, json=payload, timeout=5) as response:
|
|
||||||
if response.status_code != 200:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"TTS请求失败: {response.status_code}, {response.text}"
|
|
||||||
)
|
|
||||||
return []
|
|
||||||
|
|
||||||
logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒")
|
|
||||||
|
|
||||||
# 使用opus编码器处理PCM数据
|
|
||||||
opus_datas = []
|
|
||||||
pcm_data = response.content
|
|
||||||
|
|
||||||
# 计算每帧的字节数
|
|
||||||
frame_bytes = int(
|
|
||||||
self.opus_encoder.sample_rate
|
|
||||||
* self.opus_encoder.channels
|
|
||||||
* self.opus_encoder.frame_size_ms
|
|
||||||
/ 1000
|
|
||||||
* 2
|
|
||||||
)
|
|
||||||
|
|
||||||
# 分帧处理PCM数据
|
|
||||||
for i in range(0, len(pcm_data), frame_bytes):
|
|
||||||
frame = pcm_data[i : i + frame_bytes]
|
|
||||||
if len(frame) < frame_bytes:
|
|
||||||
# 最后一帧可能不足,用0填充
|
|
||||||
frame = frame + b"\x00" * (frame_bytes - len(frame))
|
|
||||||
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
frame,
|
|
||||||
end_of_stream=(i + frame_bytes >= len(pcm_data)),
|
|
||||||
callback=lambda opus: opus_datas.append(opus)
|
|
||||||
)
|
|
||||||
|
|
||||||
return opus_datas
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
|
||||||
return []
|
|
||||||
|
|
@ -1,267 +0,0 @@
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import queue
|
|
||||||
import aiohttp
|
|
||||||
import asyncio
|
|
||||||
import requests
|
|
||||||
import traceback
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.utils.tts import MarkdownCleaner
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.utils import opus_encoder_utils, textUtils
|
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.interface_type = InterfaceType.SINGLE_STREAM
|
|
||||||
self.access_token = config.get("access_token")
|
|
||||||
self.voice = config.get("voice")
|
|
||||||
self.api_url = config.get("api_url")
|
|
||||||
self.audio_format = "pcm"
|
|
||||||
self.before_stop_play_files = []
|
|
||||||
|
|
||||||
# 创建Opus编码器
|
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
|
||||||
sample_rate=16000, channels=1, frame_size_ms=60
|
|
||||||
)
|
|
||||||
|
|
||||||
# PCM缓冲区
|
|
||||||
self.pcm_buffer = bytearray()
|
|
||||||
|
|
||||||
def tts_text_priority_thread(self):
|
|
||||||
"""流式文本处理线程"""
|
|
||||||
while not self.conn.stop_event.is_set():
|
|
||||||
try:
|
|
||||||
message = self.tts_text_queue.get(timeout=1)
|
|
||||||
if message.sentence_type == SentenceType.FIRST:
|
|
||||||
# 初始化参数
|
|
||||||
self.tts_stop_request = False
|
|
||||||
self.processed_chars = 0
|
|
||||||
self.tts_text_buff = []
|
|
||||||
self.before_stop_play_files.clear()
|
|
||||||
elif ContentType.TEXT == message.content_type:
|
|
||||||
self.tts_text_buff.append(message.content_detail)
|
|
||||||
segment_text = self._get_segment_text()
|
|
||||||
if segment_text:
|
|
||||||
self.to_tts_single_stream(segment_text)
|
|
||||||
|
|
||||||
elif ContentType.FILE == message.content_type:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"添加音频文件到待播放列表: {message.content_file}"
|
|
||||||
)
|
|
||||||
if message.content_file and os.path.exists(message.content_file):
|
|
||||||
# 先处理文件音频数据
|
|
||||||
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
|
||||||
# 处理剩余的文本
|
|
||||||
self._process_remaining_text_stream(True)
|
|
||||||
|
|
||||||
except queue.Empty:
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def _process_remaining_text_stream(self, is_last=False):
|
|
||||||
"""处理剩余的文本并生成语音
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: 是否成功处理了文本
|
|
||||||
"""
|
|
||||||
full_text = "".join(self.tts_text_buff)
|
|
||||||
remaining_text = full_text[self.processed_chars :]
|
|
||||||
if remaining_text:
|
|
||||||
segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
|
|
||||||
if segment_text:
|
|
||||||
self.to_tts_single_stream(segment_text, is_last)
|
|
||||||
self.processed_chars += len(full_text)
|
|
||||||
else:
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
else:
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
|
|
||||||
def to_tts_single_stream(self, text, is_last=False):
|
|
||||||
try:
|
|
||||||
max_repeat_time = 5
|
|
||||||
text = MarkdownCleaner.clean_markdown(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}次: {text},错误: {e}"
|
|
||||||
)
|
|
||||||
max_repeat_time -= 1
|
|
||||||
|
|
||||||
if max_repeat_time > 0:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
|
||||||
)
|
|
||||||
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音频,每句只推送一次音频列表"""
|
|
||||||
await self._tts_request(text, is_last)
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""资源清理"""
|
|
||||||
await super().close()
|
|
||||||
if hasattr(self, "opus_encoder"):
|
|
||||||
self.opus_encoder.close()
|
|
||||||
|
|
||||||
async def _tts_request(self, text: str, is_last: bool) -> None:
|
|
||||||
params = {
|
|
||||||
"tts_text": text,
|
|
||||||
"spk_id": self.voice,
|
|
||||||
"frame_durition": 60,
|
|
||||||
"stream": "true",
|
|
||||||
"target_sr": 16000,
|
|
||||||
"audio_format": "pcm",
|
|
||||||
"instruct_text": "请生成一段自然流畅的语音",
|
|
||||||
}
|
|
||||||
headers = {
|
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
|
|
||||||
# 一帧 PCM 所需字节数:60 ms × 16 kHz × 1 ch × 2 B = 1 920
|
|
||||||
frame_bytes = int(
|
|
||||||
self.opus_encoder.sample_rate
|
|
||||||
* self.opus_encoder.channels # 1
|
|
||||||
* self.opus_encoder.frame_size_ms
|
|
||||||
/ 1000
|
|
||||||
* 2
|
|
||||||
) # 16-bit = 2 bytes
|
|
||||||
|
|
||||||
try:
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.get(
|
|
||||||
self.api_url, params=params, headers=headers, timeout=10
|
|
||||||
) as resp:
|
|
||||||
|
|
||||||
if resp.status != 200:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"TTS请求失败: {resp.status}, {await resp.text()}"
|
|
||||||
)
|
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
|
||||||
return
|
|
||||||
|
|
||||||
self.pcm_buffer.clear()
|
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
|
|
||||||
|
|
||||||
# 兼容 iter_chunked / iter_chunks / iter_any
|
|
||||||
async for chunk in resp.content.iter_any():
|
|
||||||
data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk
|
|
||||||
if not data:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 拼到 buffer
|
|
||||||
self.pcm_buffer.extend(data)
|
|
||||||
|
|
||||||
# 够一帧就编码
|
|
||||||
while len(self.pcm_buffer) >= frame_bytes:
|
|
||||||
frame = bytes(self.pcm_buffer[:frame_bytes])
|
|
||||||
del self.pcm_buffer[:frame_bytes]
|
|
||||||
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
frame,
|
|
||||||
end_of_stream=False,
|
|
||||||
callback=self.handle_opus
|
|
||||||
)
|
|
||||||
|
|
||||||
# flush 剩余不足一帧的数据
|
|
||||||
if self.pcm_buffer:
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
bytes(self.pcm_buffer),
|
|
||||||
end_of_stream=True,
|
|
||||||
callback=self.handle_opus
|
|
||||||
)
|
|
||||||
self.pcm_buffer.clear()
|
|
||||||
|
|
||||||
# 如果是最后一段,输出音频获取完毕
|
|
||||||
if is_last:
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景
|
|
||||||
Args:
|
|
||||||
text: 要转换的文本
|
|
||||||
Returns:
|
|
||||||
list: 返回opus编码后的音频数据列表
|
|
||||||
"""
|
|
||||||
start_time = time.time()
|
|
||||||
text = MarkdownCleaner.clean_markdown(text)
|
|
||||||
|
|
||||||
params = {
|
|
||||||
"tts_text": text,
|
|
||||||
"spk_id": self.voice,
|
|
||||||
"frame_duration": 60,
|
|
||||||
"stream": False,
|
|
||||||
"target_sr": 16000,
|
|
||||||
"audio_format": self.audio_format,
|
|
||||||
"instruct_text": "请生成一段自然流畅的语音",
|
|
||||||
}
|
|
||||||
headers = {
|
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
with requests.get(
|
|
||||||
self.api_url, params=params, headers=headers, timeout=5
|
|
||||||
) as response:
|
|
||||||
if response.status_code != 200:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"TTS请求失败: {response.status_code}, {response.text}"
|
|
||||||
)
|
|
||||||
return []
|
|
||||||
|
|
||||||
logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒")
|
|
||||||
|
|
||||||
# 使用opus编码器处理PCM数据
|
|
||||||
opus_datas = []
|
|
||||||
pcm_data = response.content
|
|
||||||
|
|
||||||
# 计算每帧的字节数
|
|
||||||
frame_bytes = int(
|
|
||||||
self.opus_encoder.sample_rate
|
|
||||||
* self.opus_encoder.channels
|
|
||||||
* self.opus_encoder.frame_size_ms
|
|
||||||
/ 1000
|
|
||||||
* 2
|
|
||||||
)
|
|
||||||
|
|
||||||
# 分帧处理PCM数据
|
|
||||||
for i in range(0, len(pcm_data), frame_bytes):
|
|
||||||
frame = pcm_data[i : i + frame_bytes]
|
|
||||||
if len(frame) < frame_bytes:
|
|
||||||
# 最后一帧可能不足,用0填充
|
|
||||||
frame = frame + b"\x00" * (frame_bytes - len(frame))
|
|
||||||
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
frame,
|
|
||||||
end_of_stream=(i + frame_bytes >= len(pcm_data)),
|
|
||||||
callback=lambda opus: opus_datas.append(opus)
|
|
||||||
)
|
|
||||||
|
|
||||||
return opus_datas
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
|
|
||||||
return []
|
|
||||||
|
|
@ -1,151 +0,0 @@
|
||||||
import io
|
|
||||||
import wave
|
|
||||||
import json
|
|
||||||
import base64
|
|
||||||
import asyncio
|
|
||||||
import websockets
|
|
||||||
import numpy as np
|
|
||||||
from datetime import datetime
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.url = config.get("url", "ws://192.168.1.10:8092/paddlespeech/tts/streaming")
|
|
||||||
self.protocol = config.get("protocol", "websocket")
|
|
||||||
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.spk_id = int(config.get("private_voice"))
|
|
||||||
else:
|
|
||||||
self.spk_id = int(config.get("spk_id", "0"))
|
|
||||||
|
|
||||||
sample_rate = config.get("sample_rate", 24000)
|
|
||||||
self.sample_rate = float(sample_rate) if sample_rate else 24000
|
|
||||||
|
|
||||||
speed = config.get("speed", 1.0)
|
|
||||||
self.speed = float(speed) if speed else 1.0
|
|
||||||
|
|
||||||
volume = config.get("volume", 1.0)
|
|
||||||
self.volume = float(volume) if volume else 1.0
|
|
||||||
|
|
||||||
self.delete_audio_file = config.get("delete_audio", True)
|
|
||||||
if not self.delete_audio_file:
|
|
||||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
||||||
save_path = config.get("save_path")
|
|
||||||
if save_path:
|
|
||||||
if not save_path.endswith('.wav'):
|
|
||||||
save_path = f"{save_path}_{timestamp}.wav"
|
|
||||||
else:
|
|
||||||
other_path = save_path[:-4]
|
|
||||||
save_path = f"{other_path}_{timestamp}.wav"
|
|
||||||
self.save_path = save_path
|
|
||||||
else:
|
|
||||||
self.save_path = f"./streaming_tts_{timestamp}.wav"
|
|
||||||
else:
|
|
||||||
self.save_path = None
|
|
||||||
|
|
||||||
async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1,
|
|
||||||
bits_per_sample: int = 16) -> bytes:
|
|
||||||
"""
|
|
||||||
将 PCM 数据转换为 WAV 文件并返回字节数据
|
|
||||||
:param pcm_data: PCM 数据(原始字节流)
|
|
||||||
:param sample_rate: 音频采样率,默认为24000
|
|
||||||
:param num_channels: 声道数,默认为单声道
|
|
||||||
:param bits_per_sample: 每个样本的位数,默认为16
|
|
||||||
:return: WAV 格式的字节数据
|
|
||||||
"""
|
|
||||||
byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16位PCM
|
|
||||||
wav_io = io.BytesIO()
|
|
||||||
|
|
||||||
with wave.open(wav_io, "wb") as wav_file:
|
|
||||||
wav_file.setnchannels(num_channels)
|
|
||||||
wav_file.setsampwidth(bits_per_sample // 8)
|
|
||||||
wav_file.setframerate(sample_rate)
|
|
||||||
wav_file.writeframes(byte_data.tobytes())
|
|
||||||
|
|
||||||
return wav_io.getvalue()
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
if self.protocol == "websocket":
|
|
||||||
return await self.text_streaming(text, output_file)
|
|
||||||
else:
|
|
||||||
raise ValueError("Unsupported protocol. Please use 'websocket' or 'http'.")
|
|
||||||
|
|
||||||
async def text_streaming(self, text, output_file):
|
|
||||||
try:
|
|
||||||
# 使用 websockets 异步连接到 WebSocket 服务器
|
|
||||||
async with websockets.connect(self.url) as ws:
|
|
||||||
# 发送开始请求
|
|
||||||
start_request = {
|
|
||||||
"task": "tts",
|
|
||||||
"signal": "start"
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(start_request))
|
|
||||||
|
|
||||||
# 接收开始响应并提取 session_id
|
|
||||||
start_response = await ws.recv()
|
|
||||||
start_response = json.loads(start_response) # 解析 JSON 响应
|
|
||||||
if start_response.get("status") != 0:
|
|
||||||
raise Exception(f"连接失败: {start_response.get('signal')}")
|
|
||||||
|
|
||||||
session_id = start_response.get("session")
|
|
||||||
|
|
||||||
# 发送待合成的文本数据
|
|
||||||
data_request = {
|
|
||||||
"text": text,
|
|
||||||
"spk_id": self.spk_id,
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(data_request))
|
|
||||||
|
|
||||||
audio_chunks = b""
|
|
||||||
timeout_seconds = 60 # 设置超时
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
response = await asyncio.wait_for(ws.recv(), timeout=timeout_seconds)
|
|
||||||
response = json.loads(response) # 解析 JSON 响应
|
|
||||||
status = response.get("status")
|
|
||||||
|
|
||||||
if status == 2: # 最后一个数据包
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
# 拼接音频数据(base64 编码的 PCM 数据)
|
|
||||||
audio_chunks += base64.b64decode(response.get("audio"))
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
raise Exception(f"WebSocket 超时:等待音频数据超过 {timeout_seconds} 秒")
|
|
||||||
|
|
||||||
# 将拼接后的 PCM 数据转换为 WAV 格式
|
|
||||||
wav_data = await self.pcm_to_wav(audio_chunks)
|
|
||||||
|
|
||||||
# 结束请求
|
|
||||||
end_request = {
|
|
||||||
"task": "tts",
|
|
||||||
"signal": "end",
|
|
||||||
"session": session_id # 会话 ID 必须与开始请求中的一致
|
|
||||||
}
|
|
||||||
await ws.send(json.dumps(end_request))
|
|
||||||
|
|
||||||
# 接收结束响应避免服务抛出异常
|
|
||||||
await ws.recv()
|
|
||||||
|
|
||||||
# 根据配置决定是否保存文件
|
|
||||||
if not self.delete_audio_file and self.save_path:
|
|
||||||
with open(self.save_path, "wb") as f:
|
|
||||||
f.write(wav_data)
|
|
||||||
logger.bind(tag=TAG).info(f"音频文件已保存到: {self.save_path}")
|
|
||||||
|
|
||||||
# 返回或保存音频数据
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as file_to_save:
|
|
||||||
file_to_save.write(wav_data)
|
|
||||||
else:
|
|
||||||
return wav_data
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"Error during TTS WebSocket request: {e} while processing text: {text}")
|
|
||||||
|
|
@ -1,45 +0,0 @@
|
||||||
import requests
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.model = config.get("model")
|
|
||||||
self.access_token = config.get("access_token")
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
|
||||||
self.response_format = config.get("response_format", "mp3")
|
|
||||||
self.audio_file_type = config.get("response_format", "mp3")
|
|
||||||
self.sample_rate = config.get("sample_rate")
|
|
||||||
self.speed = float(config.get("speed", 1.0))
|
|
||||||
self.gain = config.get("gain")
|
|
||||||
|
|
||||||
self.host = "api.siliconflow.cn"
|
|
||||||
self.api_url = f"https://{self.host}/v1/audio/speech"
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
request_json = {
|
|
||||||
"model": self.model,
|
|
||||||
"input": text,
|
|
||||||
"voice": self.voice,
|
|
||||||
"response_format": self.response_format,
|
|
||||||
}
|
|
||||||
headers = {
|
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
response = requests.request(
|
|
||||||
"POST", self.api_url, json=request_json, headers=headers
|
|
||||||
)
|
|
||||||
data = response.content
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as file_to_save:
|
|
||||||
file_to_save.write(data)
|
|
||||||
else:
|
|
||||||
return data
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
|
||||||
|
|
@ -1,167 +0,0 @@
|
||||||
import hashlib
|
|
||||||
import hmac
|
|
||||||
import time
|
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import base64
|
|
||||||
import requests
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.appid = config.get("appid")
|
|
||||||
self.secret_id = config.get("secret_id")
|
|
||||||
self.secret_key = config.get("secret_key")
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = int(config.get("voice"))
|
|
||||||
self.api_url = "https://tts.tencentcloudapi.com" # 正确的API端点
|
|
||||||
self.region = config.get("region")
|
|
||||||
self.output_file = config.get("output_dir")
|
|
||||||
self.audio_file_type = config.get("format", "wav")
|
|
||||||
|
|
||||||
def _get_auth_headers(self, request_body):
|
|
||||||
"""生成鉴权请求头"""
|
|
||||||
# 获取当前UTC时间戳
|
|
||||||
timestamp = int(time.time())
|
|
||||||
|
|
||||||
# 使用UTC时间计算日期
|
|
||||||
utc_date = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime(
|
|
||||||
"%Y-%m-%d"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 服务名称必须是 "tts"
|
|
||||||
service = "tts"
|
|
||||||
|
|
||||||
# 拼接凭证范围
|
|
||||||
credential_scope = f"{utc_date}/{service}/tc3_request"
|
|
||||||
|
|
||||||
# 使用TC3-HMAC-SHA256签名方法
|
|
||||||
algorithm = "TC3-HMAC-SHA256"
|
|
||||||
|
|
||||||
# 构建规范请求字符串
|
|
||||||
http_request_method = "POST"
|
|
||||||
canonical_uri = "/"
|
|
||||||
canonical_querystring = ""
|
|
||||||
|
|
||||||
# 请求头必须包含host和content-type,且按字典序排列
|
|
||||||
canonical_headers = (
|
|
||||||
f"content-type:application/json\n" f"host:tts.tencentcloudapi.com\n"
|
|
||||||
)
|
|
||||||
signed_headers = "content-type;host"
|
|
||||||
|
|
||||||
# 请求体哈希值
|
|
||||||
payload = json.dumps(request_body)
|
|
||||||
payload_hash = hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
|
||||||
|
|
||||||
# 构建规范请求字符串
|
|
||||||
canonical_request = (
|
|
||||||
f"{http_request_method}\n"
|
|
||||||
f"{canonical_uri}\n"
|
|
||||||
f"{canonical_querystring}\n"
|
|
||||||
f"{canonical_headers}\n"
|
|
||||||
f"{signed_headers}\n"
|
|
||||||
f"{payload_hash}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 计算规范请求的哈希值
|
|
||||||
hashed_canonical_request = hashlib.sha256(
|
|
||||||
canonical_request.encode("utf-8")
|
|
||||||
).hexdigest()
|
|
||||||
|
|
||||||
# 构建待签名字符串
|
|
||||||
string_to_sign = (
|
|
||||||
f"{algorithm}\n"
|
|
||||||
f"{timestamp}\n"
|
|
||||||
f"{credential_scope}\n"
|
|
||||||
f"{hashed_canonical_request}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 计算签名密钥
|
|
||||||
secret_date = self._hmac_sha256(
|
|
||||||
f"TC3{self.secret_key}".encode("utf-8"), utc_date
|
|
||||||
)
|
|
||||||
secret_service = self._hmac_sha256(secret_date, service)
|
|
||||||
secret_signing = self._hmac_sha256(secret_service, "tc3_request")
|
|
||||||
|
|
||||||
# 计算签名
|
|
||||||
signature = hmac.new(
|
|
||||||
secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256
|
|
||||||
).hexdigest()
|
|
||||||
|
|
||||||
# 构建授权头
|
|
||||||
authorization = (
|
|
||||||
f"{algorithm} "
|
|
||||||
f"Credential={self.secret_id}/{credential_scope}, "
|
|
||||||
f"SignedHeaders={signed_headers}, "
|
|
||||||
f"Signature={signature}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 构建请求头
|
|
||||||
headers = {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Host": "tts.tencentcloudapi.com",
|
|
||||||
"Authorization": authorization,
|
|
||||||
"X-TC-Action": "TextToVoice",
|
|
||||||
"X-TC-Timestamp": str(timestamp),
|
|
||||||
"X-TC-Version": "2019-08-23",
|
|
||||||
"X-TC-Region": self.region,
|
|
||||||
"X-TC-Language": "zh-CN",
|
|
||||||
}
|
|
||||||
|
|
||||||
return headers
|
|
||||||
|
|
||||||
def _hmac_sha256(self, key, msg):
|
|
||||||
"""HMAC-SHA256加密"""
|
|
||||||
if isinstance(msg, str):
|
|
||||||
msg = msg.encode("utf-8")
|
|
||||||
return hmac.new(key, msg, hashlib.sha256).digest()
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
# 构建请求体
|
|
||||||
request_json = {
|
|
||||||
"Text": text, # 合成语音的源文本
|
|
||||||
"SessionId": str(uuid.uuid4()), # 会话ID,随机生成
|
|
||||||
"VoiceType": int(self.voice), # 音色
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 获取请求头(每次请求都重新生成,以确保时间戳和签名是最新的)
|
|
||||||
headers = self._get_auth_headers(request_json)
|
|
||||||
|
|
||||||
# 发送请求
|
|
||||||
resp = requests.post(
|
|
||||||
self.api_url, json.dumps(request_json), headers=headers
|
|
||||||
)
|
|
||||||
|
|
||||||
# 检查响应
|
|
||||||
if resp.status_code == 200:
|
|
||||||
response_data = resp.json()
|
|
||||||
|
|
||||||
# 检查是否成功
|
|
||||||
if response_data.get("Response", {}).get("Error") is not None:
|
|
||||||
error_info = response_data["Response"]["Error"]
|
|
||||||
raise Exception(
|
|
||||||
f"API返回错误: {error_info['Code']}: {error_info['Message']}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 解码Base64音频数据
|
|
||||||
audio_bytes = base64.b64decode(response_data["Response"].get("Audio"))
|
|
||||||
if audio_bytes:
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as f:
|
|
||||||
f.write(audio_bytes)
|
|
||||||
else:
|
|
||||||
return audio_bytes
|
|
||||||
else:
|
|
||||||
raise Exception(f"{__name__}: 没有返回音频数据: {response_data}")
|
|
||||||
else:
|
|
||||||
raise Exception(
|
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
raise Exception(f"{__name__} error: {e}")
|
|
||||||
|
|
@ -1,88 +0,0 @@
|
||||||
import os
|
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import requests
|
|
||||||
import shutil
|
|
||||||
from datetime import datetime
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from config.logger import setup_logging
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
self.url = config.get(
|
|
||||||
"url",
|
|
||||||
"https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=",
|
|
||||||
)
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = int(config.get("private_voice"))
|
|
||||||
else:
|
|
||||||
self.voice = int(config.get("voice_id", 1695))
|
|
||||||
self.token = config.get("token")
|
|
||||||
self.to_lang = config.get("to_lang")
|
|
||||||
self.volume_change_dB = int(config.get("volume_change_dB", 0))
|
|
||||||
self.speed_factor = int(config.get("speed_factor", 1))
|
|
||||||
self.stream = str(config.get("stream", False)).lower() in ("true", "1", "yes")
|
|
||||||
self.output_file = config.get("output_dir")
|
|
||||||
self.pitch_factor = int(config.get("pitch_factor", 0))
|
|
||||||
self.format = config.get("format", "mp3")
|
|
||||||
self.audio_file_type = config.get("format", "mp3")
|
|
||||||
self.emotion = int(config.get("emotion", 1))
|
|
||||||
self.header = {"Content-Type": "application/json"}
|
|
||||||
|
|
||||||
def generate_filename(self, extension=".mp3"):
|
|
||||||
return os.path.join(
|
|
||||||
self.output_file,
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
|
||||||
url = f"{self.url}{self.token}"
|
|
||||||
result = "firefly"
|
|
||||||
payload = json.dumps(
|
|
||||||
{
|
|
||||||
"to_lang": self.to_lang,
|
|
||||||
"text": text,
|
|
||||||
"emotion": self.emotion,
|
|
||||||
"format": self.format,
|
|
||||||
"volume_change_dB": self.volume_change_dB,
|
|
||||||
"voice_id": self.voice,
|
|
||||||
"pitch_factor": self.pitch_factor,
|
|
||||||
"speed_factor": self.speed_factor,
|
|
||||||
"token": self.token,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
resp = requests.request("POST", url, data=payload)
|
|
||||||
if resp.status_code != 200:
|
|
||||||
logger.bind(tag=TAG).error(f"TTSON 请求失败: {resp.text}")
|
|
||||||
raise Exception(f"{__name__}: TTS请求失败")
|
|
||||||
resp_json = resp.json()
|
|
||||||
try:
|
|
||||||
result = (
|
|
||||||
resp_json["url"]
|
|
||||||
+ ":"
|
|
||||||
+ str(resp_json["port"])
|
|
||||||
+ "/flashsummary/retrieveFileData?stream=True&token="
|
|
||||||
+ self.token
|
|
||||||
+ "&voice_audio_path="
|
|
||||||
+ resp_json["voice_path"]
|
|
||||||
)
|
|
||||||
|
|
||||||
audio_content = requests.get(result)
|
|
||||||
if output_file:
|
|
||||||
with open(output_file, "wb") as f:
|
|
||||||
f.write(audio_content.content)
|
|
||||||
else:
|
|
||||||
return audio_content.content
|
|
||||||
voice_path = resp_json.get("voice_path")
|
|
||||||
des_path = output_file
|
|
||||||
shutil.move(voice_path, des_path)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print("error:", e)
|
|
||||||
raise Exception(f"{__name__}: TTS请求失败")
|
|
||||||
|
|
@ -1,527 +0,0 @@
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import uuid
|
|
||||||
import json
|
|
||||||
import hmac
|
|
||||||
import queue
|
|
||||||
import base64
|
|
||||||
import hashlib
|
|
||||||
import asyncio
|
|
||||||
import traceback
|
|
||||||
import websockets
|
|
||||||
from asyncio import Task
|
|
||||||
from config.logger import setup_logging
|
|
||||||
from core.utils import opus_encoder_utils
|
|
||||||
from core.utils.tts import MarkdownCleaner
|
|
||||||
from urllib.parse import urlencode, urlparse
|
|
||||||
from core.providers.tts.base import TTSProviderBase
|
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class XunfeiWSAuth:
|
|
||||||
@staticmethod
|
|
||||||
def create_auth_url(api_key, api_secret, api_url):
|
|
||||||
"""生成讯飞WebSocket认证URL"""
|
|
||||||
parsed_url = urlparse(api_url)
|
|
||||||
host = parsed_url.netloc
|
|
||||||
path = parsed_url.path
|
|
||||||
|
|
||||||
# 获取UTC时间,讯飞要求使用RFC1123格式
|
|
||||||
now = time.gmtime()
|
|
||||||
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', now)
|
|
||||||
|
|
||||||
# 构造签名字符串
|
|
||||||
signature_origin = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
|
|
||||||
|
|
||||||
# 计算签名
|
|
||||||
signature_sha = hmac.new(
|
|
||||||
api_secret.encode('utf-8'),
|
|
||||||
signature_origin.encode('utf-8'),
|
|
||||||
digestmod=hashlib.sha256
|
|
||||||
).digest()
|
|
||||||
signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
|
|
||||||
|
|
||||||
# 构造authorization
|
|
||||||
authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
|
|
||||||
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
|
|
||||||
|
|
||||||
# 构造最终的WebSocket URL
|
|
||||||
v = {
|
|
||||||
"authorization": authorization,
|
|
||||||
"date": date,
|
|
||||||
"host": host
|
|
||||||
}
|
|
||||||
url = api_url + '?' + urlencode(v)
|
|
||||||
return url
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
|
||||||
def __init__(self, config, delete_audio_file):
|
|
||||||
super().__init__(config, delete_audio_file)
|
|
||||||
|
|
||||||
# 设置为流式接口类型
|
|
||||||
self.interface_type = InterfaceType.DUAL_STREAM
|
|
||||||
|
|
||||||
# 基础配置
|
|
||||||
self.app_id = config.get("app_id")
|
|
||||||
self.api_key = config.get("api_key")
|
|
||||||
self.api_secret = config.get("api_secret")
|
|
||||||
|
|
||||||
# 接口地址
|
|
||||||
self.api_url = config.get("api_url", "wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6")
|
|
||||||
|
|
||||||
# 音色配置
|
|
||||||
self.voice = config.get("voice", "x5_lingxiaoxuan_flow")
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
|
|
||||||
# 音频参数配置
|
|
||||||
speed = config.get("speed", "50")
|
|
||||||
self.speed = int(speed) if speed else 50
|
|
||||||
|
|
||||||
volume = config.get("volume", "50")
|
|
||||||
self.volume = int(volume) if volume else 50
|
|
||||||
|
|
||||||
pitch = config.get("pitch", "50")
|
|
||||||
self.pitch = int(pitch) if pitch else 50
|
|
||||||
|
|
||||||
# 音频编码配置
|
|
||||||
self.format = config.get("format", "raw")
|
|
||||||
|
|
||||||
sample_rate = config.get("sample_rate", "24000")
|
|
||||||
self.sample_rate = int(sample_rate) if sample_rate else 24000
|
|
||||||
|
|
||||||
# 口语化配置
|
|
||||||
self.oral_level = config.get("oral_level", "mid")
|
|
||||||
|
|
||||||
spark_assist = config.get("spark_assist", "1")
|
|
||||||
self.spark_assist = int(spark_assist) if spark_assist else 1
|
|
||||||
|
|
||||||
stop_split = config.get("stop_split", "0")
|
|
||||||
self.stop_split = int(stop_split) if stop_split else 0
|
|
||||||
|
|
||||||
remain = config.get("remain", "0")
|
|
||||||
self.remain = int(remain) if remain else 0
|
|
||||||
|
|
||||||
# WebSocket配置
|
|
||||||
self.ws = None
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
# 序列号管理
|
|
||||||
self.text_seq = 0
|
|
||||||
|
|
||||||
# 创建Opus编码器
|
|
||||||
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
|
|
||||||
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
|
|
||||||
)
|
|
||||||
|
|
||||||
# 验证必需参数
|
|
||||||
if not all([self.app_id, self.api_key, self.api_secret]):
|
|
||||||
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
|
|
||||||
|
|
||||||
async def _ensure_connection(self):
|
|
||||||
"""确保WebSocket连接可用"""
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).info("开始建立新连接...")
|
|
||||||
|
|
||||||
# 生成认证URL
|
|
||||||
auth_url = XunfeiWSAuth.create_auth_url(
|
|
||||||
self.api_key, self.api_secret, self.api_url
|
|
||||||
)
|
|
||||||
|
|
||||||
self.ws = await websockets.connect(
|
|
||||||
auth_url,
|
|
||||||
ping_interval=30,
|
|
||||||
ping_timeout=10,
|
|
||||||
close_timeout=10,
|
|
||||||
)
|
|
||||||
logger.bind(tag=TAG).info("WebSocket连接建立成功")
|
|
||||||
return self.ws
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
|
|
||||||
self.ws = None
|
|
||||||
raise
|
|
||||||
|
|
||||||
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 message.sentence_type == SentenceType.FIRST:
|
|
||||||
# 重置序列号
|
|
||||||
self.text_seq = 0
|
|
||||||
self.conn.client_abort = False
|
|
||||||
# 增加序列号
|
|
||||||
self.text_seq += 1
|
|
||||||
if self.conn.client_abort:
|
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
|
|
||||||
continue
|
|
||||||
|
|
||||||
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).info(f"自动生成新的 会话ID: {self.conn.sentence_id}")
|
|
||||||
|
|
||||||
logger.bind(tag=TAG).info("开始启动TTS会话...")
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.start_session(self.conn.sentence_id),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
self.before_stop_play_files.clear()
|
|
||||||
logger.bind(tag=TAG).info("TTS会话启动成功")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 处理文本内容
|
|
||||||
if ContentType.TEXT == message.content_type:
|
|
||||||
if message.content_detail:
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"开始发送TTS文本: {message.content_detail}"
|
|
||||||
)
|
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
|
||||||
self.text_to_speak(message.content_detail, None),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
future.result()
|
|
||||||
logger.bind(tag=TAG).debug("TTS文本发送成功")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
|
|
||||||
# 不使用continue,确保后续处理不被中断
|
|
||||||
|
|
||||||
# 处理文件内容
|
|
||||||
if ContentType.FILE == message.content_type:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"添加音频文件到待播放列表: {message.content_file}"
|
|
||||||
)
|
|
||||||
if message.content_file and os.path.exists(message.content_file):
|
|
||||||
# 先处理文件音频数据
|
|
||||||
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
|
|
||||||
|
|
||||||
# 处理会话结束
|
|
||||||
if message.sentence_type == SentenceType.LAST:
|
|
||||||
try:
|
|
||||||
logger.bind(tag=TAG).info("开始结束TTS会话...")
|
|
||||||
asyncio.run_coroutine_threadsafe(
|
|
||||||
self.finish_session(self.conn.sentence_id),
|
|
||||||
loop=self.conn.loop,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
except queue.Empty:
|
|
||||||
continue
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
# 发送文本合成请求
|
|
||||||
run_request = self._build_base_request(status=1,text=filtered_text)
|
|
||||||
await self.ws.send(json.dumps(run_request))
|
|
||||||
return
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def start_session(self, session_id):
|
|
||||||
logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
|
|
||||||
try:
|
|
||||||
# 会话开始时检测上个会话的监听状态
|
|
||||||
if (
|
|
||||||
self._monitor_task is not None
|
|
||||||
and isinstance(self._monitor_task, Task)
|
|
||||||
and not self._monitor_task.done()
|
|
||||||
):
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
"检测到未完成的上个会话,关闭监听任务和连接..."
|
|
||||||
)
|
|
||||||
await self.close()
|
|
||||||
|
|
||||||
# 建立新连接
|
|
||||||
await self._ensure_connection()
|
|
||||||
|
|
||||||
# 启动监听任务
|
|
||||||
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
|
|
||||||
|
|
||||||
# 发送会话启动请求
|
|
||||||
start_request = self._build_base_request(status=0)
|
|
||||||
|
|
||||||
await self.ws.send(json.dumps(start_request))
|
|
||||||
logger.bind(tag=TAG).info("会话启动请求已发送")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
|
|
||||||
# 确保清理资源
|
|
||||||
await self.close()
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def finish_session(self, session_id):
|
|
||||||
logger.bind(tag=TAG).info(f"关闭会话~~{session_id}")
|
|
||||||
try:
|
|
||||||
if self.ws:
|
|
||||||
# 发送会话结束请求
|
|
||||||
stop_request = self._build_base_request(status=2)
|
|
||||||
await self.ws.send(json.dumps(stop_request))
|
|
||||||
logger.bind(tag=TAG).info("会话结束请求已发送")
|
|
||||||
|
|
||||||
if 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
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
|
|
||||||
await self.close()
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""资源清理"""
|
|
||||||
if self._monitor_task:
|
|
||||||
try:
|
|
||||||
self._monitor_task.cancel()
|
|
||||||
await self._monitor_task
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
|
|
||||||
async def _start_monitor_tts_response(self):
|
|
||||||
"""监听TTS响应"""
|
|
||||||
try:
|
|
||||||
while not self.conn.stop_event.is_set():
|
|
||||||
try:
|
|
||||||
msg = await self.ws.recv()
|
|
||||||
|
|
||||||
# 检查客户端是否中止
|
|
||||||
if self.conn.client_abort:
|
|
||||||
logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
|
|
||||||
break
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
code = header.get("code")
|
|
||||||
|
|
||||||
if code == 0:
|
|
||||||
payload = data.get("payload", {})
|
|
||||||
audio_payload = payload.get("audio", {})
|
|
||||||
|
|
||||||
if audio_payload:
|
|
||||||
status = audio_payload.get("status", 0)
|
|
||||||
audio_data = audio_payload.get("audio", "")
|
|
||||||
if status == 0:
|
|
||||||
logger.bind(tag=TAG).debug("TTS合成已启动")
|
|
||||||
self.tts_audio_queue.put(
|
|
||||||
(SentenceType.FIRST, [], None)
|
|
||||||
)
|
|
||||||
elif status == 2:
|
|
||||||
logger.bind(tag=TAG).debug("收到结束状态的音频数据,TTS合成完成")
|
|
||||||
self._process_before_stop_play_files()
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
if self.conn.tts_MessageText:
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"句子语音生成成功: {self.conn.tts_MessageText}"
|
|
||||||
)
|
|
||||||
self.tts_audio_queue.put(
|
|
||||||
(SentenceType.FIRST, [], self.conn.tts_MessageText)
|
|
||||||
)
|
|
||||||
self.conn.tts_MessageText = None
|
|
||||||
try:
|
|
||||||
audio_bytes = base64.b64decode(audio_data)
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
audio_bytes, False, self.handle_opus
|
|
||||||
)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"处理音频数据失败: {e}")
|
|
||||||
|
|
||||||
else:
|
|
||||||
message = header.get("message", "未知错误")
|
|
||||||
logger.bind(tag=TAG).error(f"TTS合成错误: {code} - {message}")
|
|
||||||
break
|
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
logger.bind(tag=TAG).warning("收到无效的JSON消息")
|
|
||||||
|
|
||||||
except websockets.ConnectionClosed:
|
|
||||||
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
|
|
||||||
break
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
|
|
||||||
)
|
|
||||||
break
|
|
||||||
|
|
||||||
# 链接不可复用
|
|
||||||
if self.ws:
|
|
||||||
try:
|
|
||||||
await self.ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.ws = None
|
|
||||||
# 监听任务退出时清理引用
|
|
||||||
finally:
|
|
||||||
self._monitor_task = None
|
|
||||||
|
|
||||||
def to_tts(self, text: str) -> list:
|
|
||||||
"""非流式TTS处理,用于测试及保存音频文件的场景"""
|
|
||||||
try:
|
|
||||||
# 创建新的事件循环
|
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(loop)
|
|
||||||
|
|
||||||
# 存储音频数据
|
|
||||||
audio_data = []
|
|
||||||
|
|
||||||
async def _generate_audio():
|
|
||||||
# 生成认证URL
|
|
||||||
auth_url = XunfeiWSAuth.create_auth_url(
|
|
||||||
self.api_key, self.api_secret, self.api_url
|
|
||||||
)
|
|
||||||
|
|
||||||
# 建立WebSocket连接
|
|
||||||
ws = await websockets.connect(
|
|
||||||
auth_url,
|
|
||||||
ping_interval=30,
|
|
||||||
ping_timeout=10,
|
|
||||||
close_timeout=10,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
filtered_text = MarkdownCleaner.clean_markdown(text)
|
|
||||||
|
|
||||||
text_request = self._build_base_request(status=2,text=filtered_text)
|
|
||||||
|
|
||||||
await ws.send(json.dumps(text_request))
|
|
||||||
|
|
||||||
task_finished = False
|
|
||||||
while not task_finished:
|
|
||||||
msg = await ws.recv()
|
|
||||||
|
|
||||||
data = json.loads(msg)
|
|
||||||
header = data.get("header", {})
|
|
||||||
code = header.get("code")
|
|
||||||
|
|
||||||
if code == 0:
|
|
||||||
payload = data.get("payload", {})
|
|
||||||
audio_payload = payload.get("audio", {})
|
|
||||||
if audio_payload:
|
|
||||||
status = audio_payload.get("status", 0)
|
|
||||||
audio_base64 = audio_payload.get("audio", "")
|
|
||||||
if status == 1:
|
|
||||||
try:
|
|
||||||
audio_bytes = base64.b64decode(audio_base64)
|
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
|
||||||
audio_bytes,
|
|
||||||
end_of_stream=False,
|
|
||||||
callback=lambda opus: audio_data.append(opus)
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"处理音频数据失败: {e}")
|
|
||||||
elif status == 2:
|
|
||||||
task_finished = True
|
|
||||||
logger.bind(tag=TAG).debug("TTS任务完成")
|
|
||||||
|
|
||||||
else:
|
|
||||||
message = header.get("message", "未知错误")
|
|
||||||
raise Exception(f"合成失败: {code} - {message}")
|
|
||||||
|
|
||||||
finally:
|
|
||||||
# 清理资源
|
|
||||||
try:
|
|
||||||
await ws.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
loop.run_until_complete(_generate_audio())
|
|
||||||
loop.close()
|
|
||||||
|
|
||||||
return audio_data
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
|
|
||||||
return []
|
|
||||||
|
|
||||||
def _build_base_request(self, status,text=" "):
|
|
||||||
"""构建基础请求结构"""
|
|
||||||
return {
|
|
||||||
"header": {
|
|
||||||
"app_id": self.app_id,
|
|
||||||
"status": status,
|
|
||||||
},
|
|
||||||
"parameter": {
|
|
||||||
"oral": {
|
|
||||||
"oral_level": self.oral_level,
|
|
||||||
"spark_assist": self.spark_assist,
|
|
||||||
"stop_split": self.stop_split,
|
|
||||||
"remain": self.remain
|
|
||||||
},
|
|
||||||
"tts": {
|
|
||||||
"vcn": self.voice,
|
|
||||||
"speed": self.speed,
|
|
||||||
"volume": self.volume,
|
|
||||||
"pitch": self.pitch,
|
|
||||||
"bgs": 0,
|
|
||||||
"reg": 0,
|
|
||||||
"rdn": 0,
|
|
||||||
"rhy": 0,
|
|
||||||
"audio": {
|
|
||||||
"encoding": self.format,
|
|
||||||
"sample_rate": self.sample_rate,
|
|
||||||
"channels": 1,
|
|
||||||
"bit_depth": 16,
|
|
||||||
"frame_size": 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"text": {
|
|
||||||
"encoding": "utf8",
|
|
||||||
"compress": "raw",
|
|
||||||
"format": "plain",
|
|
||||||
"status": status,
|
|
||||||
"seq": self.text_seq,
|
|
||||||
"text": base64.b64encode(text.encode('utf-8')).decode('utf-8')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -320,7 +320,7 @@ ASR:
|
||||||
base_url: https://api.groq.com/openai/v1
|
base_url: https://api.groq.com/openai/v1
|
||||||
model_name: whisper-large-v3-turbo
|
model_name: whisper-large-v3-turbo
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
prompt: "Hello there. 好的,没问题。"
|
prompt: "Hello, 这是一个测试。We discuss the plan, 请加上标点符号。"
|
||||||
ByteplusStreamASR:
|
ByteplusStreamASR:
|
||||||
type: byteplus_stream
|
type: byteplus_stream
|
||||||
appid: ${BYTEPLUS_APPID}
|
appid: ${BYTEPLUS_APPID}
|
||||||
|
|
@ -367,57 +367,6 @@ TurnDetection:
|
||||||
max_endpoint_delay: 2000 # Max time to wait after last speech before forcing end of turn (milliseconds)
|
max_endpoint_delay: 2000 # Max time to wait after last speech before forcing end of turn (milliseconds)
|
||||||
|
|
||||||
LLM:
|
LLM:
|
||||||
# 所有openai类型均可以修改超参,以AliLLM为例
|
|
||||||
# 当前支持的type为openai、dify、ollama,可自行适配
|
|
||||||
AliLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: openai
|
|
||||||
# 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
|
|
||||||
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
|
||||||
model_name: qwen-turbo
|
|
||||||
api_key: 你的deepseek web key
|
|
||||||
temperature: 0.7 # 温度值
|
|
||||||
max_tokens: 500 # 最大生成token数
|
|
||||||
top_p: 1
|
|
||||||
top_k: 50
|
|
||||||
frequency_penalty: 0 # 频率惩罚
|
|
||||||
AliAppLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: AliBL
|
|
||||||
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
|
||||||
app_id: 你的app_id
|
|
||||||
# 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
|
|
||||||
api_key: 你的api_key
|
|
||||||
# 是否不使用本地prompt:true|false (默不用请在百练应用中设置prompt)
|
|
||||||
is_no_prompt: true
|
|
||||||
# Ali_memory_id:false(不使用)|你的memory_id(请在百练应用中设置中获取)
|
|
||||||
# Tips!:Ali_memory未实现多用户存储记忆(记忆按id调用)
|
|
||||||
ali_memory_id: false
|
|
||||||
DoubaoLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: openai
|
|
||||||
# 先开通服务,打开以下网址,开通的服务搜索Doubao-1.5-pro,开通它
|
|
||||||
# 开通地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false
|
|
||||||
# 免费额度500000token
|
|
||||||
# 开通后,进入这里获取密钥:https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D
|
|
||||||
base_url: https://ark.cn-beijing.volces.com/api/v3
|
|
||||||
model_name: doubao-1-5-pro-32k-250115
|
|
||||||
api_key: 你的doubao web key
|
|
||||||
DeepSeekLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: openai
|
|
||||||
# 可在这里找到你的api key https://platform.deepseek.com/
|
|
||||||
model_name: deepseek-chat
|
|
||||||
url: https://api.deepseek.com
|
|
||||||
api_key: 你的deepseek web key
|
|
||||||
ChatGLMLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: openai
|
|
||||||
# glm-4-flash 是免费的,但是还是需要注册填写api_key的
|
|
||||||
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
|
|
||||||
model_name: glm-4-flash
|
|
||||||
url: https://open.bigmodel.cn/api/paas/v4/
|
|
||||||
api_key: 你的chat-glm web key
|
|
||||||
GroqLLM:
|
GroqLLM:
|
||||||
type: openai
|
type: openai
|
||||||
model_name: meta-llama/llama-4-scout-17b-16e-instruct
|
model_name: meta-llama/llama-4-scout-17b-16e-instruct
|
||||||
|
|
@ -438,87 +387,6 @@ LLM:
|
||||||
allow_fallbacks: true
|
allow_fallbacks: true
|
||||||
reasoning_effort: none
|
reasoning_effort: none
|
||||||
max_tokens: 2000
|
max_tokens: 2000
|
||||||
OllamaLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: ollama
|
|
||||||
model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载
|
|
||||||
base_url: http://localhost:11434 # Ollama服务地址
|
|
||||||
DifyLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: dify
|
|
||||||
# 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限
|
|
||||||
# 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词
|
|
||||||
base_url: https://api.dify.ai/v1
|
|
||||||
api_key: 你的DifyLLM web key
|
|
||||||
# 使用的对话模式 可以选择工作流 workflows/run 对话模式 chat-messages 文本生成 completion-messages
|
|
||||||
# 使用workflows进行返回的时候输入参数为 query 返回参数的名字要设置为 answer
|
|
||||||
# 文本生成的默认输入参数也是query
|
|
||||||
mode: chat-messages
|
|
||||||
GeminiLLM:
|
|
||||||
type: gemini
|
|
||||||
# 谷歌Gemini API,需要先在Google Cloud控制台创建API密钥并获取api_key
|
|
||||||
# 若在中国境内使用,请遵守《生成式人工智能服务管理暂行办法》
|
|
||||||
# token申请地址: https://aistudio.google.com/apikey
|
|
||||||
# 若部署地无法访问接口,需要开启科学上网
|
|
||||||
api_key: 你的gemini web key
|
|
||||||
model_name: "gemini-2.0-flash"
|
|
||||||
http_proxy: "" #"http://127.0.0.1:10808"
|
|
||||||
https_proxy: "" #http://127.0.0.1:10808"
|
|
||||||
CozeLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: coze
|
|
||||||
# 你可以在这里找到个人令牌
|
|
||||||
# https://www.coze.cn/open/oauth/pats
|
|
||||||
# bot_id和user_id的内容写在引号之内
|
|
||||||
bot_id: "你的bot_id"
|
|
||||||
user_id: "你的user_id"
|
|
||||||
personal_access_token: 你的coze个人令牌
|
|
||||||
VolcesAiGatewayLLM:
|
|
||||||
# 火山引擎 - 边缘大模型网关
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: openai
|
|
||||||
# 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-pro-32k-functioncall ,开通
|
|
||||||
# 如果需要使用边缘大模型网关提供的语音合成,一并勾选 Doubao-语音合成 ,另见 TTS.VolcesAiGatewayTTS 配置
|
|
||||||
# https://console.volcengine.com/vei/aigateway/
|
|
||||||
# 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list
|
|
||||||
base_url: https://ai-gateway.vei.volces.com/v1
|
|
||||||
model_name: doubao-pro-32k-functioncall
|
|
||||||
api_key: 你的网关访问密钥
|
|
||||||
LMStudioLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: openai
|
|
||||||
model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载
|
|
||||||
url: http://localhost:1234/v1 # LM Studio服务地址
|
|
||||||
api_key: lm-studio # LM Studio服务的固定API Key
|
|
||||||
HomeAssistant:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: homeassistant
|
|
||||||
base_url: http://homeassistant.local:8123
|
|
||||||
agent_id: conversation.chatgpt
|
|
||||||
api_key: 你的home assistant api访问令牌
|
|
||||||
FastgptLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: fastgpt
|
|
||||||
# 如果使用fastgpt,配置文件里prompt(提示词)是无效的,需要在fastgpt控制台设置提示词
|
|
||||||
base_url: https://host/api/v1
|
|
||||||
# 你可以在这里找到你的api_key
|
|
||||||
# https://cloud.tryfastgpt.ai/account/apikey
|
|
||||||
api_key: 你的fastgpt密钥
|
|
||||||
variables:
|
|
||||||
k: "v"
|
|
||||||
k2: "v2"
|
|
||||||
XinferenceLLM:
|
|
||||||
# 定义LLM API类型
|
|
||||||
type: xinference
|
|
||||||
# Xinference服务地址和模型名称
|
|
||||||
model_name: qwen2.5:72b-AWQ # 使用的模型名称,需要预先在Xinference启动对应模型
|
|
||||||
base_url: http://localhost:9997 # Xinference服务地址
|
|
||||||
XinferenceSmallLLM:
|
|
||||||
# 定义轻量级LLM API类型,用于意图识别
|
|
||||||
type: xinference
|
|
||||||
# Xinference服务地址和模型名称
|
|
||||||
model_name: qwen2.5:3b-AWQ # 使用的小模型名称,用于意图识别
|
|
||||||
base_url: http://localhost:9997 # Xinference服务地址
|
|
||||||
# VLLM配置(视觉语言大模型)
|
# VLLM配置(视觉语言大模型)
|
||||||
VLLM:
|
VLLM:
|
||||||
ChatGLMVLLM:
|
ChatGLMVLLM:
|
||||||
|
|
@ -545,14 +413,6 @@ VLLM:
|
||||||
model_name: lite
|
model_name: lite
|
||||||
api_key: 你的api_password
|
api_key: 你的api_password
|
||||||
TTS:
|
TTS:
|
||||||
# 当前支持的type为edge、doubao,可自行适配
|
|
||||||
EdgeTTS:
|
|
||||||
# 定义TTS API类型
|
|
||||||
type: edge
|
|
||||||
voice: zh-CN-XiaoxiaoNeural
|
|
||||||
output_dir: tmp/
|
|
||||||
# ============== SDK 版本TTS(推荐)==============
|
|
||||||
# 使用官方SDK,代码更简洁、性能更好、维护成本更低
|
|
||||||
Cartesia:
|
Cartesia:
|
||||||
# Cartesia TTS - SDK版本(推荐)
|
# Cartesia TTS - SDK版本(推荐)
|
||||||
# 官方SDK实现,低延迟,支持流式合成
|
# 官方SDK实现,低延迟,支持流式合成
|
||||||
|
|
@ -594,24 +454,6 @@ TTS:
|
||||||
# 启用说话人增强
|
# 启用说话人增强
|
||||||
use_speaker_boost: true
|
use_speaker_boost: true
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
DoubaoTTS:
|
|
||||||
# 定义TTS API类型
|
|
||||||
type: doubao
|
|
||||||
# 火山引擎语音合成服务,需要先在火山引擎控制台创建应用并获取appid和access_token
|
|
||||||
# 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误
|
|
||||||
# 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。
|
|
||||||
# 普通音色在这里开通:https://console.volcengine.com/speech/service/8
|
|
||||||
# 湾湾小何音色在这里开通:https://console.volcengine.com/speech/service/10007,开通后将下面的voice设置成zh_female_wanwanxiaohe_moon_bigtts
|
|
||||||
api_url: https://openspeech.bytedance.com/api/v1/tts
|
|
||||||
voice: BV001_streaming
|
|
||||||
output_dir: tmp/
|
|
||||||
authorization: "Bearer;"
|
|
||||||
appid: 你的火山引擎语音合成服务appid
|
|
||||||
access_token: 你的火山引擎语音合成服务access_token
|
|
||||||
cluster: volcano_tts
|
|
||||||
speed_ratio: 1.0
|
|
||||||
volume_ratio: 1.0
|
|
||||||
pitch_ratio: 1.0
|
|
||||||
#火山tts,支持双向流式tts
|
#火山tts,支持双向流式tts
|
||||||
HuoshanDoubleStreamTTS:
|
HuoshanDoubleStreamTTS:
|
||||||
type: huoshan_double_stream
|
type: huoshan_double_stream
|
||||||
|
|
@ -628,37 +470,6 @@ TTS:
|
||||||
speech_rate: 0
|
speech_rate: 0
|
||||||
loudness_rate: 0
|
loudness_rate: 0
|
||||||
pitch: 0
|
pitch: 0
|
||||||
CosyVoiceSiliconflow:
|
|
||||||
type: siliconflow
|
|
||||||
# 硅基流动TTS
|
|
||||||
# token申请地址 https://cloud.siliconflow.cn/account/ak
|
|
||||||
model: FunAudioLLM/CosyVoice2-0.5B
|
|
||||||
voice: FunAudioLLM/CosyVoice2-0.5B:alex
|
|
||||||
output_dir: tmp/
|
|
||||||
access_token: 你的硅基流动API密钥
|
|
||||||
response_format: wav
|
|
||||||
CozeCnTTS:
|
|
||||||
type: cozecn
|
|
||||||
# COZECN TTS
|
|
||||||
# token申请地址 https://www.coze.cn/open/oauth/pats
|
|
||||||
voice: 7426720361733046281
|
|
||||||
output_dir: tmp/
|
|
||||||
access_token: 你的coze web key
|
|
||||||
response_format: wav
|
|
||||||
VolcesAiGatewayTTS:
|
|
||||||
type: openai
|
|
||||||
# 火山引擎 - 边缘大模型网关
|
|
||||||
# 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-语音合成 ,开通
|
|
||||||
# 如果需要使用边缘大模型网关提供的 LLM,一并勾选 Doubao-pro-32k-functioncall ,另见 LLM.VolcesAiGatewayLLM 配置
|
|
||||||
# https://console.volcengine.com/vei/aigateway/
|
|
||||||
# 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list
|
|
||||||
api_key: 你的网关访问密钥
|
|
||||||
api_url: https://ai-gateway.vei.volces.com/v1/audio/speech
|
|
||||||
model: doubao-tts
|
|
||||||
# 音色列表见 https://www.volcengine.com/docs/6561/1257544
|
|
||||||
voice: zh_male_shaonianzixin_moon_bigtts
|
|
||||||
speed: 1
|
|
||||||
output_dir: tmp/
|
|
||||||
FishSpeech:
|
FishSpeech:
|
||||||
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
|
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
|
||||||
type: fishspeech
|
type: fishspeech
|
||||||
|
|
@ -692,50 +503,19 @@ TTS:
|
||||||
rate: 44100
|
rate: 44100
|
||||||
sample_rate: 16000
|
sample_rate: 16000
|
||||||
api_key: ${FISH_API_KEY}
|
api_key: ${FISH_API_KEY}
|
||||||
GPT_SOVITS_V2:
|
FishSingleStreamTTS:
|
||||||
# 定义TTS API类型
|
type: fish_single_stream
|
||||||
#启动tts方法:
|
model: speech-1.6
|
||||||
#python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/demo.yaml
|
|
||||||
type: gpt_sovits_v2
|
|
||||||
url: "http://127.0.0.1:9880/tts"
|
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
text_lang: "auto"
|
response_format: pcm
|
||||||
ref_audio_path: "demo.wav"
|
normalize: true
|
||||||
prompt_text: ""
|
chunk_length: 200
|
||||||
prompt_lang: "zh"
|
top_p: 0.7
|
||||||
top_k: 5
|
temperature: 0.7
|
||||||
top_p: 1
|
channels: 1
|
||||||
temperature: 1
|
rate: 44100
|
||||||
text_split_method: "cut0"
|
sample_rate: 16000
|
||||||
batch_size: 1
|
api_key: ${FISH_API_KEY}
|
||||||
batch_threshold: 0.75
|
|
||||||
split_bucket: true
|
|
||||||
return_fragment: false
|
|
||||||
speed_factor: 1.0
|
|
||||||
streaming_mode: false
|
|
||||||
seed: -1
|
|
||||||
parallel_infer: true
|
|
||||||
repetition_penalty: 1.35
|
|
||||||
aux_ref_audio_paths: []
|
|
||||||
GPT_SOVITS_V3:
|
|
||||||
# 定义TTS API类型 GPT-SoVITS-v3lora-20250228
|
|
||||||
#启动tts方法:
|
|
||||||
#python api.py
|
|
||||||
type: gpt_sovits_v3
|
|
||||||
url: "http://127.0.0.1:9880"
|
|
||||||
output_dir: tmp/
|
|
||||||
text_language: "auto"
|
|
||||||
refer_wav_path: "caixukun.wav"
|
|
||||||
prompt_language: "zh"
|
|
||||||
prompt_text: ""
|
|
||||||
top_k: 15
|
|
||||||
top_p: 1.0
|
|
||||||
temperature: 1.0
|
|
||||||
cut_punc: ""
|
|
||||||
speed: 1.0
|
|
||||||
inp_refs: []
|
|
||||||
sample_steps: 32
|
|
||||||
if_sr: false
|
|
||||||
MinimaxTTSHTTPStream:
|
MinimaxTTSHTTPStream:
|
||||||
# Minimax流式语音合成服务
|
# Minimax流式语音合成服务
|
||||||
type: minimax_httpstream
|
type: minimax_httpstream
|
||||||
|
|
@ -768,103 +548,6 @@ TTS:
|
||||||
# voice_id: female-shaonv
|
# voice_id: female-shaonv
|
||||||
# weight: 1
|
# weight: 1
|
||||||
# language_boost: auto
|
# language_boost: auto
|
||||||
AliyunTTS:
|
|
||||||
# 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
|
|
||||||
# 平台地址:https://nls-portal.console.aliyun.com/
|
|
||||||
# appkey地址:https://nls-portal.console.aliyun.com/applist
|
|
||||||
# token地址:https://nls-portal.console.aliyun.com/overview
|
|
||||||
# 定义TTS API类型
|
|
||||||
type: aliyun
|
|
||||||
output_dir: tmp/
|
|
||||||
appkey: 你的阿里云智能语音交互服务项目Appkey
|
|
||||||
token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
|
|
||||||
voice: xiaoyun
|
|
||||||
access_key_id: 你的阿里云账号access_key_id
|
|
||||||
access_key_secret: 你的阿里云账号access_key_secret
|
|
||||||
|
|
||||||
# 以下可不用设置,使用默认设置
|
|
||||||
# format: wav
|
|
||||||
# sample_rate: 16000
|
|
||||||
# volume: 50
|
|
||||||
# speech_rate: 0
|
|
||||||
# pitch_rate: 0
|
|
||||||
AliyunStreamTTS:
|
|
||||||
# 阿里云CosyVoice大模型流式文本语音合成
|
|
||||||
# 采用FlowingSpeechSynthesizer接口,支持更低延迟和更自然的语音质量
|
|
||||||
# 流式文本语音合成仅提供商用版,不支持试用,详情请参见试用版和商用版。要使用该功能,请开通商用版。
|
|
||||||
# 支持龙系列专用音色:longxiaochun、longyu、longchen等
|
|
||||||
# 平台地址:https://nls-portal.console.aliyun.com/
|
|
||||||
# appkey地址:https://nls-portal.console.aliyun.com/applist
|
|
||||||
# token地址:https://nls-portal.console.aliyun.com/overview
|
|
||||||
# 使用三阶段流式交互:StartSynthesis -> RunSynthesis -> StopSynthesis
|
|
||||||
type: aliyun_stream
|
|
||||||
output_dir: tmp/
|
|
||||||
appkey: 你的阿里云智能语音交互服务项目Appkey
|
|
||||||
token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
|
|
||||||
voice: longxiaochun
|
|
||||||
access_key_id: 你的阿里云账号access_key_id
|
|
||||||
access_key_secret: 你的阿里云账号access_key_secret
|
|
||||||
# 截至2025年7月21日大模型音色只有北京节点采用,其他节点暂不支持
|
|
||||||
host: nls-gateway-cn-beijing.aliyuncs.com
|
|
||||||
# 以下可不用设置,使用默认设置
|
|
||||||
# format: pcm # 音频格式:pcm、wav、mp3
|
|
||||||
# sample_rate: 16000 # 采样率:8000、16000、24000
|
|
||||||
# volume: 50 # 音量:0-100
|
|
||||||
# speech_rate: 0 # 语速:-500到500
|
|
||||||
# pitch_rate: 0 # 语调:-500到500
|
|
||||||
TencentTTS:
|
|
||||||
# 腾讯云智能语音交互服务,需要先在腾讯云平台开通服务
|
|
||||||
# appid、secret_id、secret_key申请地址:https://console.cloud.tencent.com/cam/capi
|
|
||||||
# 免费领取资源:https://console.cloud.tencent.com/tts/resourcebundle
|
|
||||||
type: tencent
|
|
||||||
output_dir: tmp/
|
|
||||||
appid: 你的腾讯云AppId
|
|
||||||
secret_id: 你的腾讯云SecretID
|
|
||||||
secret_key: 你的腾讯云SecretKey
|
|
||||||
region: ap-guangzhou
|
|
||||||
voice: 101001
|
|
||||||
|
|
||||||
TTS302AI:
|
|
||||||
# 302AI语音合成服务,需要先在302平台创建账户充值,并获取密钥信息
|
|
||||||
# 添加 302.ai TTS 配置
|
|
||||||
# token申请地址:https://dash.302.ai/
|
|
||||||
# 获取api_keyn路径:https://dash.302.ai/apis/list
|
|
||||||
# 价格,$35/百万字符。火山原版¥450元/百万字符
|
|
||||||
type: doubao
|
|
||||||
api_url: https://api.302ai.cn/doubao/tts_hd
|
|
||||||
authorization: "Bearer "
|
|
||||||
# 湾湾小何音色
|
|
||||||
voice: "zh_female_wanwanxiaohe_moon_bigtts"
|
|
||||||
output_dir: tmp/
|
|
||||||
access_token: "你的302API密钥"
|
|
||||||
GizwitsTTS:
|
|
||||||
type: doubao
|
|
||||||
# 火山引擎作为基座,可以完全使用企业级火山引擎语音合成服务
|
|
||||||
# 前一万名注册的用户,将送5元体验金额
|
|
||||||
# 获取API Key地址:https://agentrouter.gizwitsapi.com/panel/token
|
|
||||||
api_url: https://bytedance.gizwitsapi.com/api/v1/tts
|
|
||||||
authorization: "Bearer "
|
|
||||||
# 湾湾小何音色
|
|
||||||
voice: "zh_female_wanwanxiaohe_moon_bigtts"
|
|
||||||
output_dir: tmp/
|
|
||||||
access_token: "你的机智云API key"
|
|
||||||
ACGNTTS:
|
|
||||||
#在线网址:https://acgn.ttson.cn/
|
|
||||||
#token购买:www.ttson.cn
|
|
||||||
#开发相关疑问请提交至网站上的qq
|
|
||||||
#角色id获取地址:ctrl+f快速检索角色——网站管理者不允许发布,可询问网站管理者
|
|
||||||
#各参数意义见开发文档:https://www.yuque.com/alexuh/skmti9/wm6taqislegb02gd?singleDoc#
|
|
||||||
type: ttson
|
|
||||||
token: your_token
|
|
||||||
voice_id: 1695
|
|
||||||
speed_factor: 1
|
|
||||||
pitch_factor: 0
|
|
||||||
volume_change_dB: 0
|
|
||||||
to_lang: ZH
|
|
||||||
url: https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=
|
|
||||||
format: mp3
|
|
||||||
output_dir: tmp/
|
|
||||||
emotion: 1
|
|
||||||
OpenAITTS:
|
OpenAITTS:
|
||||||
# openai官方文本转语音服务,可支持全球大多数语种
|
# openai官方文本转语音服务,可支持全球大多数语种
|
||||||
type: openai
|
type: openai
|
||||||
|
|
@ -880,99 +563,6 @@ TTS:
|
||||||
# 语速范围0.25-4.0
|
# 语速范围0.25-4.0
|
||||||
speed: 1
|
speed: 1
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
CustomTTS:
|
|
||||||
# 自定义的TTS接口服务,请求参数可自定义,可接入众多TTS服务
|
|
||||||
# 以本地部署的KokoroTTS为例
|
|
||||||
# 如果只有cpu运行:docker run -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-cpu:latest
|
|
||||||
# 如果只有gpu运行:docker run --gpus all -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-gpu:latest
|
|
||||||
# 要求接口使用POST方式请求,并返回音频文件
|
|
||||||
type: custom
|
|
||||||
method: POST
|
|
||||||
url: "http://127.0.0.1:8880/v1/audio/speech"
|
|
||||||
params: # 自定义请求参数
|
|
||||||
input: "{prompt_text}"
|
|
||||||
response_format: "mp3"
|
|
||||||
download_format: "mp3"
|
|
||||||
voice: "zf_xiaoxiao"
|
|
||||||
lang_code: "z"
|
|
||||||
return_download_link: true
|
|
||||||
speed: 1
|
|
||||||
stream: false
|
|
||||||
headers: # 自定义请求头
|
|
||||||
# Authorization: Bearer xxxx
|
|
||||||
format: mp3 # 接口返回的音频格式
|
|
||||||
output_dir: tmp/
|
|
||||||
LinkeraiTTS:
|
|
||||||
type: linkerai
|
|
||||||
api_url: https://tts.linkerai.cn/tts
|
|
||||||
audio_format: "pcm"
|
|
||||||
# 默认的access_token供大家测试时免费使用的,此access_token请勿用于商业用途
|
|
||||||
# 如果效果不错,可自行申请token,申请地址:https://linkerai.cn
|
|
||||||
# 各参数意义见开发文档:https://tts.linkerai.cn/docs
|
|
||||||
# 支持声音克隆,可自行上传音频,填入voice参数,voice参数为空时,使用默认声音
|
|
||||||
access_token: "U4YdYXVfpwWnk2t5Gp822zWPCuORyeJL"
|
|
||||||
voice: "OUeAo1mhq6IBExi"
|
|
||||||
output_dir: tmp/
|
|
||||||
PaddleSpeechTTS:
|
|
||||||
#百度飞浆 PaddleSpeech 支持本地离线部署 支持模型训练
|
|
||||||
#框架地址 https://www.paddlepaddle.org.cn/
|
|
||||||
#项目地址 https://github.com/PaddlePaddle/PaddleSpeech
|
|
||||||
#SpeechServerDemo https://github.com/PaddlePaddle/PaddleSpeech/tree/develop/demos/speech_server
|
|
||||||
#流式传输请参考 https://github.com/PaddlePaddle/PaddleSpeech/wiki/PaddleSpeech-Server-WebSocket-API
|
|
||||||
type: paddle_speech
|
|
||||||
protocol: websocket # protocol choices = ['websocket', 'http']
|
|
||||||
url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming,http默认http://127.0.0.1:8090/paddlespeech/tts]
|
|
||||||
spk_id: 0 # 发音人 ID,0 通常表示默认的发音人
|
|
||||||
sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择]
|
|
||||||
speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢
|
|
||||||
volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
|
|
||||||
save_path: # 保存路径
|
|
||||||
IndexStreamTTS:
|
|
||||||
# 基于Index-TTS-vLLM项目的TTS接口服务
|
|
||||||
# 参照教程:https://github.com/Ksuriuri/index-tts-vllm/blob/master/README.md
|
|
||||||
type: index_stream
|
|
||||||
api_url: http://127.0.0.1:11996/tts
|
|
||||||
audio_format: "pcm"
|
|
||||||
# 默认音色,如需其他音色可到项目assets文件夹下注册
|
|
||||||
voice: "jay_klee"
|
|
||||||
output_dir: tmp/
|
|
||||||
AliBLTTS:
|
|
||||||
# 阿里百炼CosyVoice大模型流式文本语音合成
|
|
||||||
# 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
|
|
||||||
# cosyvoice-v3和部分音色需要申请开通
|
|
||||||
type: alibl_stream
|
|
||||||
api_key: 你的api_key
|
|
||||||
model: "cosyvoice-v2"
|
|
||||||
voice: "longcheng_v2"
|
|
||||||
output_dir: tmp/
|
|
||||||
# 以下可不用设置,使用默认设置
|
|
||||||
# format: pcm # 音频格式:pcm、wav、mp3、opus
|
|
||||||
# sample_rate: 24000 # 采样率:16000, 24000, 48000
|
|
||||||
# volume: 50 # 音量:0-100
|
|
||||||
# rate: 1 # 语速:0.5~2
|
|
||||||
# pitch: 1 # 语调:0.5~2
|
|
||||||
XunFeiTTS:
|
|
||||||
# 讯飞TTS服务 官方网站:https://www.xfyun.cn/
|
|
||||||
# 登录讯飞语音技术平台 https://console.xfyun.cn/app/myapp 创建相关应用
|
|
||||||
# 选择需要的服务获取api相关配置 https://console.xfyun.cn/services/uts
|
|
||||||
# 为需要使用的应用(APPID)购买相关服务 例如:超拟人合成 https://console.xfyun.cn/services/uts
|
|
||||||
type: xunfei_stream
|
|
||||||
api_url: wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6
|
|
||||||
app_id: 你的app_id
|
|
||||||
api_secret: 你的api_secret
|
|
||||||
api_key: 你的api_key
|
|
||||||
voice: x5_lingxiaoxuan_flow
|
|
||||||
output_dir: tmp/
|
|
||||||
# 以下可不用设置,使用默认设置,注意V5音色不支持口语化配置
|
|
||||||
# oral_level: mid # 口语化等级:high, mid, low
|
|
||||||
# spark_assist: 1 # 是否通过大模型进行口语化 开启:1, 关闭:0
|
|
||||||
# stop_split: 0 # 关闭服务端拆句 不关闭:0,关闭:1
|
|
||||||
# remain: 0 # 是否保留原书面语的样子 保留:1, 不保留:0
|
|
||||||
# format: raw # 音频格式:raw(PCM), lame(MP3), speex, opus, opus-wb, opus-swb, speex-wb
|
|
||||||
# sample_rate: 24000 # 采样率:16000, 8000, 24000
|
|
||||||
# volume: 50 # 音量:0-100
|
|
||||||
# speed: 50 # 语速:0-100
|
|
||||||
# pitch: 50 # 语调:0-100
|
|
||||||
# ===============================================================================
|
# ===============================================================================
|
||||||
# ============================= Module Selection ================================
|
# ============================= Module Selection ================================
|
||||||
# ===============================================================================
|
# ===============================================================================
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue