Files
tts-plus/backend.py
T
2026-05-24 16:42:11 +08:00

125 lines
3.9 KiB
Python

from abc import ABC, abstractmethod
from loguru import logger
import re
# 自动切分函数,避免TOKEN耗尽
def smart_split(text: str, max_length: int = 300) -> list[str]:
if len(text) <= max_length:
return [text]
text = re.sub(r"\s+", " ", text).strip()
chunks = []
while len(text) > max_length:
# 1. 截取前 max_length 个字作为候选区
candidate = text[:max_length]
# 2. 优先找一句话结束的绝对标点(句号、问号、感叹号、省略号、换行)
# [。!?…\n] 后面可能跟着引号,所以用 [」”]? 容错
end_punc_match = list(re.finditer(r"[。!?…\n][」”]?", candidate))
if end_punc_match:
# 取候选区里最后一个句号的位置
split_idx = end_punc_match[-1].end()
else:
# 3. 没找到句号,则退而求其次寻找停顿标点(逗号、分号、冒号、顿号)
pause_punc_match = list(re.finditer(r"[,;:、,;:][」”]?", candidate))
if pause_punc_match:
split_idx = pause_punc_match[-1].end()
else:
# 4. 如果 600 字内极其奇葩地连一个标点都没有,则在空格处切分
space_match = list(re.finditer(r"\s", candidate))
if space_match:
split_idx = space_match[-1].end()
else:
# 5. 实在啥都没有,无情强行按字数切断(保底机制)
split_idx = max_length
# 提取切分出来的段落
chunk = text[:split_idx].strip()
if chunk:
chunks.append(chunk)
# 剩下的文本继续循环
text = text[split_idx:].strip()
if text:
chunks.append(text)
return chunks
class TTSBackend(ABC):
@abstractmethod
def say(self, voice: str, text: str, instruct: str = "", output_file: str = ""):
pass
# 自动分块的说话接口,适用于长文本,是默认实现
def smart_say(
self,
voice: str,
text: str,
instruct: str = "",
output_file_prefix: str = "./output",
):
chunks = smart_split(text)
for i, chunk in enumerate(chunks):
output_file = (
f"{output_file_prefix}_{i}.wav"
if len(chunks) > 1
else f"{output_file_prefix}.wav"
)
logger.debug(f"正在合成 chunk {i+1}/{len(chunks)}: {chunk}")
self.say(
voice=voice, text=chunk, instruct=instruct, output_file=output_file
)
class CrispASRCLIBackend(TTSBackend):
def __init__(
self,
model: str,
codec_model: str,
executable: str = "./crispasr",
gpu_backend: str = "auto",
):
self.executable = executable
self.model = model
self.gpu_backend = gpu_backend
self.codec_model = codec_model
def say(
self,
voice: str,
text: str,
instruct: str = "",
output_file: str = "./output.wav",
):
import subprocess
cmd = [
self.executable,
"--voice",
voice,
"--tts",
text,
"--model",
self.model,
"--gpu-backend",
self.gpu_backend,
"--codec-model",
self.codec_model,
]
if instruct:
cmd.extend(["--instruct", instruct])
if output_file:
cmd.extend(["--tts-output", output_file])
logger.debug(f"命令: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True)
logger.debug(f"stdout: {result.stdout.decode()}")
logger.debug(f"stderr: {result.stderr.decode()}")
if result.returncode != 0:
raise RuntimeError(f"Command failed: {result.stderr.decode()}")