mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
60 lines
2 KiB
Python
60 lines
2 KiB
Python
import asyncio
|
||
from config.logger import setup_logging
|
||
import os
|
||
from abc import ABC, abstractmethod
|
||
from core.utils.util import audio_to_opus_data
|
||
from core.utils.tts import TextFormater
|
||
|
||
TAG = __name__
|
||
logger = setup_logging()
|
||
|
||
|
||
class TTSProviderBase(ABC):
|
||
def __init__(self, config, delete_audio_file):
|
||
self.delete_audio_file = delete_audio_file
|
||
self.output_file = config.get("output_dir")
|
||
|
||
@abstractmethod
|
||
def generate_filename(self):
|
||
pass
|
||
|
||
def to_tts(self, text):
|
||
tmp_file = self.generate_filename()
|
||
try:
|
||
max_repeat_time = 5
|
||
# 判断清理markdown标记并且判断文本是否是关键字,否则不生成tts
|
||
text = TextFormater.format_text(text)
|
||
if text is None or text == "":
|
||
return None
|
||
while not os.path.exists(tmp_file) and max_repeat_time > 0:
|
||
try:
|
||
asyncio.run(self.text_to_speak(text, tmp_file))
|
||
except Exception as e:
|
||
logger.bind(tag=TAG).warning(
|
||
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
|
||
)
|
||
# 未执行成功,删除文件
|
||
if os.path.exists(tmp_file):
|
||
os.remove(tmp_file)
|
||
max_repeat_time -= 1
|
||
|
||
if max_repeat_time > 0:
|
||
logger.bind(tag=TAG).info(
|
||
f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
|
||
)
|
||
else:
|
||
logger.bind(tag=TAG).error(
|
||
f"语音生成失败: {text},请检查网络或服务是否正常"
|
||
)
|
||
|
||
return tmp_file
|
||
except Exception as e:
|
||
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
|
||
return None
|
||
|
||
@abstractmethod
|
||
async def text_to_speak(self, text, output_file):
|
||
pass
|
||
|
||
def audio_to_opus_data(self, audio_file_path):
|
||
return audio_to_opus_data(audio_file_path)
|