Merge pull request #59 from Plaud-AI/feat/demo

feat: vad onnx && turn detection
This commit is contained in:
Harold-Guo 2025-12-19 18:13:42 +08:00 committed by GitHub
commit 94ce8404c7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 5847 additions and 3919 deletions

View file

@ -65,6 +65,7 @@ services:
# Model files (important!) # Model files (important!)
- /home/ubuntu/live-agent/main/xiaozhi-server/models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall - /home/ubuntu/live-agent/main/xiaozhi-server/models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall
- /home/ubuntu/live-agent/main/xiaozhi-server/models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad - /home/ubuntu/live-agent/main/xiaozhi-server/models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad
- /home/ubuntu/live-agent/main/xiaozhi-server/models/fsmn_vad_onnx:/opt/xiaozhi-esp32-server/models/fsmn_vad_onnx
# Temporary files # Temporary files
- /home/ubuntu/live-agent/main/xiaozhi-server/tmp:/opt/xiaozhi-esp32-server/tmp - /home/ubuntu/live-agent/main/xiaozhi-server/tmp:/opt/xiaozhi-esp32-server/tmp
# Music files (optional) # Music files (optional)

View file

@ -38,6 +38,7 @@ services:
# Model files (important!) # Model files (important!)
- ./xiaozhi-server/models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall - ./xiaozhi-server/models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall
- ./xiaozhi-server/models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad - ./xiaozhi-server/models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad
- ./xiaozhi-server/models/fsmn_vad_onnx:/opt/xiaozhi-esp32-server/models/fsmn_vad_onnx
# Temporary files # Temporary files
- ./xiaozhi-server/tmp:/opt/xiaozhi-esp32-server/tmp - ./xiaozhi-server/tmp:/opt/xiaozhi-esp32-server/tmp
# Music files (optional) # Music files (optional)

View file

@ -0,0 +1,35 @@
FROM nvidia/cuda:12.3.2-devel-ubuntu22.04
ENV DEBIAN_FRONTEND=noninteractive
# Install system dependencies
RUN apt update && apt install -y \
software-properties-common \
curl \
git \
&& add-apt-repository -y ppa:deadsnakes/ppa \
&& apt update -y \
&& apt install -y python3.12 python3.12-venv python3.12-dev \
&& apt clean && rm -rf /var/lib/apt/lists/*
# Install uv
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"
WORKDIR /workspace/
EXPOSE 18000
# Set timezone
ENV TimeZone=Etc/UTC
RUN ln -snf /usr/share/zoneinfo/$TimeZone /etc/localtime && echo $TimeZone > /etc/timezone
# Copy project files
COPY pyproject.toml uv.lock* /workspace/
# Install dependencies
RUN uv sync --frozen --no-dev
# Copy source code
COPY . /workspace/
CMD ["uv", "run", "python", "main.py"]

View file

@ -0,0 +1,60 @@
from fastapi import FastAPI, BackgroundTasks
import uvicorn
from pydantic import BaseModel
import time
import logging
from turn_det import analyze_text
# ---------------------
# 日志初始化
# ---------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)
# ---------------------
# FastAPI 实例
# ---------------------
app = FastAPI(title="My HTTP Service")
# ---------------------
# 请求体
# ---------------------
class Item(BaseModel):
text: str
# ---------------------
# 路由
# ---------------------
@app.get("/health")
def health():
"""健康检查接口"""
return {
"status": "ok",
"timestamp": int(time.time())
}
@app.get("/")
def root():
return {"message": "Hello from FastAPI!"}
@app.post("/turn-detect")
def process(item: Item):
"""接收 JSON 请求并处理"""
logger.info(f"Received: {item}")
res = analyze_text(item.text)
logger.info(f"result: {res}")
result = {
"text": item.text,
"result":res
}
return result
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=18000)

View file

@ -0,0 +1,17 @@
[project]
name = "turn-detection"
version = "0.1.0"
description = "Turn Detection Service based on TEN-framework"
requires-python = ">=3.10"
dependencies = [
"torch>=2.0.0",
"transformers>=4.40.0",
"fastapi>=0.100.0",
"uvicorn>=0.20.0",
]
[dependency-groups]
dev = [
"pytest>=8.0.0",
]

View file

@ -0,0 +1,8 @@
docker run --restart=on-failure:3 \
--gpus all \
-d \
-p 18000:18000 \
-v /home/ubuntu/.cache/huggingface:/root/.cache/huggingface \
--name turn_detect \
turn_det:latest

View file

@ -0,0 +1,74 @@
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import os
def get_device():
"""Auto-detect the best available device: CUDA > MPS > CPU"""
if torch.cuda.is_available():
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
return torch.device("cuda")
elif torch.backends.mps.is_available():
return torch.device("mps")
else:
return torch.device("cpu")
def get_dtype(device):
"""Get appropriate dtype for the device"""
if device.type == "cuda":
return torch.bfloat16
elif device.type == "mps":
return torch.float16 # MPS works better with float16
else:
return torch.float32 # CPU needs float32 for bfloat16 models
# Auto-detect device
DEVICE = get_device()
DTYPE = get_dtype(DEVICE)
print(f"Using device: {DEVICE}, dtype: {DTYPE}")
# Load model and tokenizer
model_id = 'TEN-framework/TEN_Turn_Detection'
model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=True,
torch_dtype=DTYPE
)
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
# Move model to device
model = model.to(DEVICE)
model.eval()
def analyze_text(text, system_prompt=""):
"""Function for inference"""
inf_messages = [{"role": "system", "content": system_prompt}] + [{"role": "user", "content": text}]
input_ids = tokenizer.apply_chat_template(
inf_messages,
add_generation_prompt=True,
return_tensors="pt"
).to(DEVICE)
with torch.no_grad():
outputs = model.generate(
input_ids,
max_new_tokens=1,
do_sample=True,
top_p=0.1,
temperature=0.1,
pad_token_id=tokenizer.eos_token_id
)
response = outputs[0][input_ids.shape[-1]:]
return tokenizer.decode(response, skip_special_tokens=True)
if __name__=="__main__":
# Example usage
text = "Hello I have a question about"
result = analyze_text(text)
print(f"Input: '{text}'")
print(f"Turn Detection Result: '{result}'")

1372
main/turn_detection/uv.lock Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
3.11

View file

@ -1,7 +1,7 @@
# Dockerfile for local development and testing # Dockerfile for local development and testing
# Build xiaozhi-server image from local source code # Build xiaozhi-server image from local source code
FROM python:3.10-slim FROM python:3.11-slim
# Install system dependencies # Install system dependencies
RUN apt-get update && \ RUN apt-get update && \
@ -9,31 +9,29 @@ RUN apt-get update && \
libopus0 \ libopus0 \
ffmpeg \ ffmpeg \
build-essential \ build-essential \
curl \
git && \ git && \
apt-get clean && \ apt-get clean && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
# Configure pip to use Aliyun mirror for faster downloads in China # Install uv
RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \ COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
pip config set global.trusted-host mirrors.aliyun.com && \
pip config set global.timeout 120 && \
pip config set install.retries 5
# Set working directory # Set working directory
WORKDIR /opt/xiaozhi-esp32-server WORKDIR /opt/xiaozhi-esp32-server
# Copy requirements file # Copy dependency files first (for better layer caching)
COPY requirements.txt . COPY pyproject.toml uv.lock ./
# Install Python dependencies # Install Python dependencies with uv
RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \ RUN uv sync --frozen --no-dev
pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5
# Copy application code # Copy application code
COPY . . COPY . .
# Set timezone # Set timezone and Python path
ENV TZ=Asia/Shanghai ENV TZ=Asia/Shanghai
ENV PATH="/opt/xiaozhi-esp32-server/.venv/bin:$PATH"
# Expose ports # Expose ports
# 8000: WebSocket server # 8000: WebSocket server

View file

@ -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)

View file

@ -555,38 +555,6 @@ async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]]
await max_out_size(conn) await max_out_size(conn)
return return
# 提取用于检测的纯文本(去除JSON包装)
check_text = actual_text
try:
if actual_text.strip().startswith("{"):
parsed = json.loads(actual_text)
if "content" in parsed:
check_text = parsed["content"]
except (json.JSONDecodeError, KeyError):
pass
# 强制停止检测:即使 TTS 未播放,如果有正在进行的 LLM 任务也要停止
if _is_force_stop_intent(check_text):
# 检查是否有正在进行的 LLM 任务
if not conn.llm_finish_task:
conn.logger.bind(tag=TAG).info(f"强制停止意图检测到: '{check_text}',取消当前任务")
await handleAbortMessage(conn)
# 不继续处理,直接返回
return
# 如果 TTS 正在播放也要停止
if conn.client_is_speaking:
conn.logger.bind(tag=TAG).info(f"强制停止 TTS 播放: '{check_text}'")
await handleAbortMessage(conn)
return
# 智能打断处理(TTS 正在播放时)
if conn.client_is_speaking and conn.client_listen_mode != "manual":
should_continue = await _smart_interrupt_handler(conn, actual_text)
if not should_continue:
# 反馈信号(嗯、好的等),不打断也不处理
conn.logger.bind(tag=TAG).debug(f"跳过反馈信号: {actual_text}")
return
# 首先进行意图分析,使用实际文本内容 # 首先进行意图分析,使用实际文本内容
intent_handled = await handle_user_intent(conn, actual_text) intent_handled = await handle_user_intent(conn, actual_text)
@ -600,36 +568,9 @@ async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]]
# 确定聊天内容:multimodal 优先 # 确定聊天内容:multimodal 优先
chat_content = multimodal_content if multimodal_content else actual_text chat_content = multimodal_content if multimodal_content else actual_text
# 尝试使用并行优化的聊天处理器
parallel_handler = _get_parallel_chat_handler(conn)
if parallel_handler is not None:
# 使用并行优化的异步 chat 方法
conn.logger.bind(tag=TAG).debug("使用 ParallelChatHandler 处理消息")
asyncio.create_task(_run_parallel_chat(conn, parallel_handler, chat_content))
else:
# 降级到原始的同步 chat 方法
conn.executor.submit(conn.chat, chat_content) conn.executor.submit(conn.chat, chat_content)
async def _run_parallel_chat(conn, handler, content):
"""
运行并行聊天处理
包装 ParallelChatHandler.chat() 的异步调用,处理异常并降级
Args:
conn: 连接对象
handler: ParallelChatHandler 实例
content: 文本或 multimodal 内容
"""
try:
await handler.chat(content)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"并行聊天处理失败: {e},降级到原始方法")
# 降级到原始方法
conn.executor.submit(conn.chat, content)
async def no_voice_close_connect(conn, have_voice): async def no_voice_close_connect(conn, have_voice):
if have_voice: if have_voice:
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000

View file

@ -259,10 +259,10 @@ class ASRProviderBase(ABC):
conn.asr_text_buffer = raw_text conn.asr_text_buffer = raw_text
# Turn Detection: let turn detection handle end of turn # Turn Detection: let turn detection handle end of turn
# if conn.turn_detection: if conn.turn_detection:
# # Turn detection will wait for endpoint delay, then call on_end_of_turn # Turn detection will wait for endpoint delay, then call on_end_of_turn
# conn.turn_detection.check_end_of_turn(conn) conn.turn_detection.check_end_of_turn(conn)
# return return
# # No Turn Detection: process immediately # # No Turn Detection: process immediately
# await conn.on_end_of_turn() # await conn.on_end_of_turn()

View file

@ -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 []

View file

@ -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}")

View file

@ -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 []

View file

@ -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}")

View file

@ -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}")

View file

@ -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) # 抛出异常,让调用方捕获

View 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()

View file

@ -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)

View file

@ -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)

View file

@ -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 []

View file

@ -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 &times; 16 kHz &times; 1 ch &times; 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 []

View file

@ -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}")

View file

@ -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}")

View file

@ -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}")

View file

@ -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请求失败")

View file

@ -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')
}
}
}

View file

@ -147,6 +147,17 @@ class TurnDetectionProvider(TurnDetectionProviderBase):
self._turn_detection_task = asyncio.create_task( self._turn_detection_task = asyncio.create_task(
self._delayed_turn_detection_task(conn) self._delayed_turn_detection_task(conn)
) )
# Add callback to log exceptions (task may be cancelled, which is expected)
self._turn_detection_task.add_done_callback(self._on_task_done)
def _on_task_done(self, task: asyncio.Task):
"""Callback when turn detection task completes"""
if task.cancelled():
logger.bind(tag=TAG).debug("Turn detection task was cancelled")
return
exc = task.exception()
if exc:
logger.bind(tag=TAG).error(f"Turn detection task failed: {exc}")
async def close(self) -> None: async def close(self) -> None:
"""Close the httpx client""" """Close the httpx client"""

View file

@ -2,7 +2,7 @@ import asyncio
import time import time
import numpy as np import numpy as np
from dataclasses import dataclass from dataclasses import dataclass
from funasr import AutoModel from funasr_onnx import Fsmn_vad_online
from config.logger import setup_logging from config.logger import setup_logging
from .base import VADProviderBase, VADStream from .base import VADProviderBase, VADStream
@ -21,20 +21,20 @@ class FsmnVADOptions:
sample_rate: int = 16000 # 16kHz sample_rate: int = 16000 # 16kHz
chunk_size_ms: int = 100 # streaming chunk size in ms chunk_size_ms: int = 100 # streaming chunk size in ms
# FSMN model parameters (passed to AutoModel) # FSMN model parameters (can override models/fsmn_vad_onnx/config.yaml defaults)
min_silence_duration_ms: int = 500 # silence detection duration (ms) min_silence_duration_ms: int = 500 # silence detection duration (ms)
speech_noise_threshold: float = 0.6 # speech/noise threshold, higher = stricter speech_noise_threshold: float = 0.6 # speech/noise threshold, higher = stricter
sil_to_speech_time_thres: int = 150 # silence→speech transition time (ms), higher = less noise sensitive sil_to_speech_time_thres: int = 150 # silence→speech transition time (ms)
class VADProvider(VADProviderBase): class VADProvider(VADProviderBase):
"""FSMN VAD provider using FunASR""" """FSMN VAD provider using ONNX Runtime for fast CPU inference"""
def __init__(self, config: dict): def __init__(self, config: dict):
super().__init__() super().__init__()
model_name = config.get("model", "fsmn-vad") model_dir = config.get("model_dir", "models/fsmn_vad_onnx")
model_revision = config.get("model_revision", "v2.0.4") quantize = config.get("quantize", True)
# Parse config # Parse config
self._opts = FsmnVADOptions( self._opts = FsmnVADOptions(
@ -46,14 +46,24 @@ class VADProvider(VADProviderBase):
sil_to_speech_time_thres=int(config.get("sil_to_speech_time_thres", 150)), sil_to_speech_time_thres=int(config.get("sil_to_speech_time_thres", 150)),
) )
# Pass FSMN model parameters to AutoModel # Load ONNX model with ONNX Runtime
self._model = AutoModel( self._model = Fsmn_vad_online(
model=model_name, model_dir=model_dir,
model_revision=model_revision, quantize=quantize,
max_end_silence_time=self._opts.min_silence_duration_ms, max_end_sil=self._opts.min_silence_duration_ms,
speech_noise_thres=self._opts.speech_noise_threshold, )
sil_to_speech_time_thres=self._opts.sil_to_speech_time_thres,
disable_pbar=True, # disable progress bar # Override VAD parameters at runtime (these override config.yaml defaults)
vad_opts = self._model.vad_scorer.vad_opts
vad_opts.max_end_silence_time = self._opts.min_silence_duration_ms
vad_opts.speech_noise_thres = self._opts.speech_noise_threshold
vad_opts.sil_to_speech_time_thres = self._opts.sil_to_speech_time_thres
logger.bind(tag=TAG).info(
f"Loaded FSMN VAD ONNX model from {model_dir} (quantize={quantize}, "
f"max_end_sil={self._opts.min_silence_duration_ms}ms, "
f"speech_noise_thres={self._opts.speech_noise_threshold}, "
f"sil_to_speech_time={self._opts.sil_to_speech_time_thres}ms)"
) )
@ -107,8 +117,8 @@ class FsmnVADStream(VADStream):
input_audios: bytearray = bytearray() input_audios: bytearray = bytearray()
inference_audios: bytearray = bytearray() inference_audios: bytearray = bytearray()
# FSMN cache for streaming (reset on speech end) # FSMN ONNX cache for streaming (reset on speech end)
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
while not self._is_closed: while not self._is_closed:
try: try:
@ -130,13 +140,8 @@ class FsmnVADStream(VADStream):
) )
chunk_float32 = chunk_int16.astype(np.float32) / 32768.0 chunk_float32 = chunk_int16.astype(np.float32) / 32768.0
# Run FSMN inference # Run FSMN ONNX inference
res = self._model.generate( res = self._model(chunk_float32, param_dict=fsmn_param_dict)
input=chunk_float32,
cache=fsmn_cache,
is_final=False,
chunk_size=self._opts.chunk_size_ms
)
inference_duration = time.perf_counter() - inference_start inference_duration = time.perf_counter() - inference_start
@ -168,10 +173,10 @@ class FsmnVADStream(VADStream):
def _copy_speech_buffer() -> bytes: def _copy_speech_buffer() -> bytes:
return bytes(self._speech_buffer[:speech_buffer_index]) return bytes(self._speech_buffer[:speech_buffer_index])
# Parse FSMN result # Parse FSMN ONNX result
# res format: [{"key": "xxx", "value": [[start_ms, end_ms], ...]}] # res format: [[[start_ms, end_ms], ...]] or []
if res and len(res) > 0 and res[0].get("value"): if res and len(res) > 0 and len(res[0]) > 0:
seg = res[0]["value"][0] # Take first segment seg = res[0][0] # Take first segment from first batch
seg_start, seg_end = seg[0], seg[1] seg_start, seg_end = seg[0], seg[1]
if seg_start >= 0 and seg_end == -1: if seg_start >= 0 and seg_end == -1:
@ -216,7 +221,7 @@ class FsmnVADStream(VADStream):
# Reset for next utterance # Reset for next utterance
speech_duration = 0.0 speech_duration = 0.0
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
_reset_write_cursor() _reset_write_cursor()
elif seg_start > 0 and seg_end > 0: elif seg_start > 0 and seg_end > 0:

View file

@ -282,52 +282,6 @@ Memory:
llm: ChatGLMLLM llm: ChatGLMLLM
ASR: ASR:
FunASR:
type: fun_local
model_dir: models/SenseVoiceSmall
output_dir: tmp/
FunASRServer:
# 独立部署FunASR,使用FunASR的API服务,只需要五句话
# 第一句:mkdir -p ./funasr-runtime-resources/models
# 第二句:sudo docker run -p 10096:10095 -it --privileged=true -v $PWD/funasr-runtime-resources/models:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-online-cpu-0.1.12
# 上一句话执行后会进入到容器,继续第三句:cd FunASR/runtime
# 不要退出容器,继续在容器中执行第四句:nohup bash run_server_2pass.sh --download-model-dir /workspace/models --vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx --model-dir damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx --online-model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online-onnx --punc-dir damo/punc_ct-transformer_zh-cn-common-vad_realtime-vocab272727-onnx --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst --itn-dir thuduj12/fst_itn_zh --hotword /workspace/models/hotwords.txt > log.txt 2>&1 &
# 上一句话执行后会进入到容器,继续第五句:tail -f log.txt
# 第五句话执行完后,会看到模型下载日志,下载完后就可以连接使用了
# 以上是使用CPU推理,如果有GPU,详细参考:https://github.com/modelscope/FunASR/blob/main/runtime/docs/SDK_advanced_guide_online_zh.md
type: fun_server
host: 127.0.0.1
port: 10096
is_ssl: true
api_key: none
output_dir: tmp/
SherpaASR:
# Sherpa-ONNX 本地语音识别(需手动下载模型)
type: sherpa_onnx_local
model_dir: models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17
output_dir: tmp/
# 模型类型:sense_voice (多语言) 或 paraformer (中文专用)
model_type: sense_voice
SherpaParaformerASR:
# 中文语音识别模型,可以运行在低性能设备(需手动下载模型,例如RK3566-2g)
# 详细配置说明请参考:docs/sherpa-paraformer-guide.md
type: sherpa_onnx_local
model_dir: models/sherpa-onnx-paraformer-zh-small-2024-03-09
output_dir: tmp/
model_type: paraformer
DoubaoASR:
# 可以在这里申请相关Key等信息
# https://console.volcengine.com/speech/app
# DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费
# 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
type: doubao
appid: 你的火山引擎语音合成服务appid
access_token: 你的火山引擎语音合成服务access_token
cluster: volcengine_input_common
# 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
boosting_table_name: (选填)你的热词文件名称
correct_table_name: (选填)你的替换词文件名称
output_dir: tmp/
DoubaoStreamASR: DoubaoStreamASR:
# 可以在这里申请相关Key等信息 # 可以在这里申请相关Key等信息
# https://console.volcengine.com/speech/app # https://console.volcengine.com/speech/app
@ -342,60 +296,6 @@ ASR:
boosting_table_name: (选填)你的热词文件名称 boosting_table_name: (选填)你的热词文件名称
correct_table_name: (选填)你的替换词文件名称 correct_table_name: (选填)你的替换词文件名称
output_dir: tmp/ output_dir: tmp/
TencentASR:
# token申请地址:https://console.cloud.tencent.com/cam/capi
# 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle
type: tencent
appid: 你的腾讯语音合成服务appid
secret_id: 你的腾讯语音合成服务secret_id
secret_key: 你的腾讯语音合成服务secret_key
output_dir: tmp/
AliyunASR:
# 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
# HTTP POST请求,一次性处理完整音频
# 平台地址:https://nls-portal.console.aliyun.com/
# appkey地址:https://nls-portal.console.aliyun.com/applist
# token地址:https://nls-portal.console.aliyun.com/overview
# AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景
# 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟)
# 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟)
# 定义ASR API类型
type: aliyun
appkey: 你的阿里云智能语音交互服务项目Appkey
token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
access_key_id: 你的阿里云账号access_key_id
access_key_secret: 你的阿里云账号access_key_secret
output_dir: tmp/
AliyunStreamASR:
# 阿里云智能语音交互服务 - 实时流式语音识别
# WebSocket连接,实时处理音频流
# 平台地址:https://nls-portal.console.aliyun.com/
# appkey地址:https://nls-portal.console.aliyun.com/applist
# token地址:https://nls-portal.console.aliyun.com/overview
# AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景
# 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟)
# 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟)
# 定义ASR API类型
type: aliyun_stream
appkey: 你的阿里云智能语音交互服务项目Appkey
token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
access_key_id: 你的阿里云账号access_key_id
access_key_secret: 你的阿里云账号access_key_secret
# 服务器地域选择,可选择距离更近的服务器以减少延迟,如nls-gateway-cn-hangzhou.aliyuncs.com(杭州)等
host: nls-gateway-cn-shanghai.aliyuncs.com
# 断句检测时间(毫秒),控制静音多长时间后进行断句,默认800毫秒
max_sentence_silence: 800
output_dir: tmp/
BaiduASR:
# 获取AppID、API Key、Secret Key:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/app/list
# 查看资源额度:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/overview/resource/list
type: baidu
app_id: 你的百度语音技术AppID
api_key: 你的百度语音技术APIKey
secret_key: 你的百度语音技术SecretKey
# 语言参数,1537为普通话,具体参考:https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b
dev_pid: 1537
output_dir: tmp/
OpenaiASR: OpenaiASR:
# OpenAI语音识别服务,需要先在OpenAI平台创建组织并获取api_key # OpenAI语音识别服务,需要先在OpenAI平台创建组织并获取api_key
# 支持中、英、日、韩等多种语音识别,具体参考文档https://platform.openai.com/docs/guides/speech-to-text # 支持中、英、日、韩等多种语音识别,具体参考文档https://platform.openai.com/docs/guides/speech-to-text
@ -421,58 +321,6 @@ ASR:
model_name: whisper-large-v3-turbo model_name: whisper-large-v3-turbo
output_dir: tmp/ output_dir: tmp/
prompt: "Hello, 这是一个测试。We discuss the plan, 请加上标点符号。" prompt: "Hello, 这是一个测试。We discuss the plan, 请加上标点符号。"
VoskASR:
# 官方网站:https://alphacephei.com/vosk/
# 配置说明:
# 1. VOSK是一个离线语音识别库,支持多种语言
# 2. 需要先下载模型文件:https://alphacephei.com/vosk/models
# 3. 中文模型推荐使用vosk-model-small-cn-0.22或vosk-model-cn-0.22
# 4. 完全离线运行,无需网络连接
# 5. 输出文件保存在tmp/目录
# 使用步骤:
# 1. 访问 https://alphacephei.com/vosk/models 下载对应的模型
# 2. 解压模型文件到项目目录下的models/vosk/文件夹
# 3. 在配置中指定正确的模型路径
# 4. 注意:VOSK中文模型输出不带标点符号,词与词之间会有空格
type: vosk
model_path: 你的模型路径,如:models/vosk/vosk-model-small-cn-0.22
output_dir: tmp/
Qwen3ASRFlash:
# 通义千问Qwen3-ASR-Flash语音识别服务,需要先在阿里云百炼平台创建API密钥
# 申请步骤:
# 1.登录阿里云百炼平台。https://bailian.console.aliyun.com/
# 2.创建API-KEY https://bailian.console.aliyun.com/#/api-key
# 3.Qwen3-ASR-Flash基于通义千问多模态基座,支持多语言识别、歌唱识别、噪声拒识等功能
type: qwen3_asr_flash
api_key: 你的阿里云百炼API密钥
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
model_name: qwen3-asr-flash
output_dir: tmp/
# ASR选项配置
enable_lid: true # 自动语种检测
enable_itn: true # 逆文本归一化
#language: "zh" # 语种,支持zh、en、ja、ko等
context: "" # 上下文信息,用于提高识别准确率,不超过10000 Token
XunfeiStreamASR:
# 讯飞流式语音识别服务
# 需要先在讯飞开放平台创建应用,获取以下认证信息
# 讯飞开放平台地址:https://www.xfyun.cn/
# 创建应用后,在"我的应用"中获取:
# - APPID
# - APISecret
# - APIKey
type: xunfei_stream
# 必填参数 - 讯飞开放平台应用信息
app_id: 你的APPID
api_key: 你的APIKey
api_secret: 你的APISecret
# 识别参数配置
domain: slm # 识别领域,iat:日常用语,medical:医疗,finance:金融等
language: zh_cn # 语言,zh_cn:中文,en_us:英文
accent: mandarin # 方言,mandarin:普通话
dwa: wpgs # 动态修正,wpgs:实时返回中间结果
# 调整音频处理参数以提高长语音识别质量
output_dir: tmp/
ByteplusStreamASR: ByteplusStreamASR:
type: byteplus_stream type: byteplus_stream
appid: ${BYTEPLUS_APPID} appid: ${BYTEPLUS_APPID}
@ -493,8 +341,8 @@ VAD:
# Reference: https://huggingface.co/funasr/fsmn-vad # Reference: https://huggingface.co/funasr/fsmn-vad
FsmnVAD: FsmnVAD:
type: fsmn type: fsmn
model: fsmn-vad model_dir: models/fsmn_vad_onnx # ONNX model directory
model_revision: v2.0.4 quantize: true # use INT8 quantized model (faster)
chunk_size_ms: 100 # streaming chunk size in ms chunk_size_ms: 100 # streaming chunk size in ms
min_silence_duration_ms: 400 # silence detection duration (ms) min_silence_duration_ms: 400 # silence detection duration (ms)
speech_noise_threshold: 0.6 # speech/noise threshold (0.6-0.9), higher = stricter speech_noise_threshold: 0.6 # speech/noise threshold (0.6-0.9), higher = stricter
@ -511,65 +359,14 @@ TurnDetection:
type: noop type: noop
TenTurnDetection: TenTurnDetection:
type: ten type: ten
host: 115.190.161.149 host: 13.212.248.80
port: 8002 port: 18000
timeout: 0.5 # HTTP request timeout (seconds) timeout: 1 # HTTP request timeout (seconds)
endpoint: /turn-detect # API endpoint path endpoint: /turn-detect # API endpoint path
min_endpoint_delay: 500 # Min time to wait after last speech before forcing end of turn (milliseconds) min_endpoint_delay: 500 # Min 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) 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
@ -590,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:
@ -697,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实现,低延迟,支持流式合成
@ -746,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
@ -780,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
@ -844,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
@ -920,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
@ -1032,105 +563,12 @@ 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 ================================
# =============================================================================== # ===============================================================================
selected_module: selected_module:
# VAD: FsmnVAD VAD: FsmnVAD
VAD: SileroVAD # VAD: SileroVAD
TurnDetection: TenTurnDetection # Set to TenTurnDetection to enable TurnDetection: TenTurnDetection # Set to TenTurnDetection to enable
ASR: GroqASR ASR: GroqASR
# ASR: ByteplusStreamASR # ASR: ByteplusStreamASR

View file

@ -0,0 +1,8 @@
<Nnet>
<Splice> 400 400
[ 0 ]
<AddShift> 400 400
<LearnRateCoef> 0 [ -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 ]
<Rescale> 400 400
<LearnRateCoef> 0 [ 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 ]
</Nnet>

View file

@ -0,0 +1,56 @@
frontend: WavFrontendOnline
frontend_conf:
fs: 16000
window: hamming
n_mels: 80
frame_length: 25
frame_shift: 10
dither: 0.0
lfr_m: 5
lfr_n: 1
model: FsmnVADStreaming
model_conf:
sample_rate: 16000
detect_mode: 1
snr_mode: 0
max_end_silence_time: 800
max_start_silence_time: 3000
do_start_point_detection: True
do_end_point_detection: True
window_size_ms: 200
sil_to_speech_time_thres: 150
speech_to_sil_time_thres: 150
speech_2_noise_ratio: 1.0
do_extend: 1
lookback_time_start_point: 200
lookahead_time_end_point: 100
max_single_segment_time: 60000
snr_thres: -100.0
noise_frame_num_used_for_snr: 100
decibel_thres: -100.0
speech_noise_thres: 0.6
fe_prior_thres: 0.0001
silence_pdf_num: 1
sil_pdf_ids: [0]
speech_noise_thresh_low: -0.1
speech_noise_thresh_high: 0.3
output_frame_probs: False
frame_in_ms: 10
frame_length_ms: 25
encoder: FSMN
encoder_conf:
input_dim: 400
input_affine_dim: 140
fsmn_layers: 4
linear_dim: 250
proj_dim: 128
lorder: 20
rorder: 0
lstride: 1
rstride: 0
output_affine_dim: 140
output_dim: 248

Binary file not shown.

View file

@ -0,0 +1,91 @@
[project]
name = "xiaozhi-server"
version = "1.0.0"
description = "Xiaozhi AI Voice Assistant Server"
requires-python = ">=3.11,<3.12"
dependencies = [
# Core
"pyyml==0.0.2",
"numpy==1.26.4",
"websockets==14.2",
"httpx==0.27.2",
"aiohttp==3.12.15",
"aiohttp_cors==0.7.0",
"requests==2.32.5",
"ruamel.yaml==0.18.15",
"loguru==0.7.3",
"python-dotenv>=1.0.0",
"aioconsole==0.8.1",
"chardet==5.2.0",
"psutil==7.0.0",
"portalocker==3.2.0",
"Jinja2==3.1.6",
"PyJWT==2.8.0",
"PySocks==1.7.1",
"bs4==0.0.2",
"ormsgpack==1.11.0",
# Audio processing
"opuslib_next==1.1.2",
"pydub==0.25.1",
# ML/DL frameworks
"torch==2.2.2",
"torchaudio==2.2.2",
# VAD
"silero_vad==6.0.0",
"funasr==1.2.3",
"funasr_onnx==0.4.1",
# ASR
"sherpa_onnx==1.12.11",
"vosk==0.3.44",
"modelscope==1.23.2",
"deepgram-sdk>=3.0.0",
# LLM
"openai==2.5.0",
"google-generativeai==0.8.5",
"cozepy==0.19.0",
"dashscope==1.24.6",
# TTS
"edge_tts==7.0.0",
"elevenlabs>=1.11.0",
"cartesia>=1.0.0",
"fish-audio-sdk>=1.0.0",
"baidu-aip==4.16.13",
# Memory
"mem0ai==1.0.0",
"memu-py",
"redis>=4.0.0,<5.0.0",
# MCP
"mcp==1.13.1",
"mcp-proxy==0.8.2",
# Utilities
"cnlunar==0.2.0",
"markitdown==0.1.3",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0.0",
"pytest-asyncio>=0.21.0",
"librosa>=0.10.0",
"soundfile>=0.12.0",
]
# No build-system needed - this is an application, not a library
[dependency-groups]
dev = [
"pytest>=7.0.0",
"pytest-asyncio>=0.21.0",
"librosa>=0.10.0",
"soundfile>=0.12.0",
]

View file

@ -1,48 +0,0 @@
pyyml==0.0.2
torch==2.2.2
silero_vad==6.0.0
websockets==14.2
opuslib_next==1.1.2
numpy==1.26.4
pydub==0.25.1
funasr==1.2.3
torchaudio==2.2.2
openai==2.5.0
google-generativeai==0.8.5
edge_tts==7.0.0
httpx==0.27.2
aiohttp==3.12.15
aiohttp_cors==0.7.0
ormsgpack==1.11.0
ruamel.yaml==0.18.15
loguru==0.7.3
requests==2.32.5
cozepy==0.19.0
mem0ai==1.0.0
memu-py
bs4==0.0.2
modelscope==1.23.2
sherpa_onnx==1.12.11
mcp==1.13.1
cnlunar==0.2.0
PySocks==1.7.1
dashscope==1.24.6
baidu-aip==4.16.13
chardet==5.2.0
aioconsole==0.8.1
markitdown==0.1.3
mcp-proxy==0.8.2
PyJWT==2.8.0
psutil==7.0.0
portalocker==3.2.0
Jinja2==3.1.6
vosk==0.3.44
redis>=4.0.0,<5.0.0
elevenlabs>=1.11.0
cartesia>=1.0.0
deepgram-sdk>=3.0.0
fish-audio-sdk>=1.0.0
python-dotenv>=1.0.0

View file

@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""
Export FSMN VAD model to ONNX format for faster inference on CPU.
Usage:
python scripts/export_fsmn_onnx.py
Output:
./models/fsmn_vad_onnx/ - ONNX model files
"""
import os
import sys
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def export_fsmn_to_onnx(
model_name: str = "iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
model_revision: str = "v2.0.4",
output_dir: str = "./models/fsmn_vad_onnx",
quantize: bool = True,
device: str = "cpu",
):
"""
Export FSMN VAD model to ONNX format.
Args:
model_name: ModelScope model name
model_revision: Model revision/version
output_dir: Output directory for ONNX files
quantize: Whether to quantize to INT8 (smaller, faster on CPU)
device: Device for loading PyTorch model
"""
from funasr import AutoModel
print(f"Loading FSMN VAD model: {model_name} (revision: {model_revision})")
print(f"Device: {device}")
# Load PyTorch model
model = AutoModel(
model=model_name,
model_revision=model_revision,
device=device,
disable_pbar=False,
)
# Create output directory
os.makedirs(output_dir, exist_ok=True)
print(f"\nExporting to ONNX...")
print(f" Output directory: {output_dir}")
print(f" Quantize (INT8): {quantize}")
# Export to ONNX
res = model.export(
quantize=quantize,
output_dir=output_dir,
)
print(f"\n✅ Export success!")
print(f" ONNX files saved to: {output_dir}")
# List exported files
print(f"\nExported files:")
for f in Path(output_dir).glob("*"):
size_mb = f.stat().st_size / (1024 * 1024)
print(f" - {f.name} ({size_mb:.2f} MB)")
return res
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Export FSMN VAD to ONNX")
parser.add_argument(
"--model",
default="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch",
help="ModelScope model name"
)
parser.add_argument(
"--revision",
default="v2.0.4",
help="Model revision"
)
parser.add_argument(
"--output-dir",
default="./models/fsmn_vad_onnx",
help="Output directory"
)
parser.add_argument(
"--no-quantize",
action="store_true",
help="Disable INT8 quantization (use FP32)"
)
parser.add_argument(
"--device",
default="cpu",
choices=["cpu", "cuda"],
help="Device for loading model"
)
args = parser.parse_args()
export_fsmn_to_onnx(
model_name=args.model,
model_revision=args.revision,
output_dir=args.output_dir,
quantize=not args.no_quantize,
device=args.device,
)

View file

@ -1,12 +1,12 @@
""" """
FSMN VAD Stream Test Script FSMN VAD Stream Test Script (ONNX Version)
This script tests FSMN VAD with audio files, simulating the streaming behavior: This script tests FSMN VAD ONNX with audio files, simulating the streaming behavior:
1. Load an audio file 1. Load an audio file
2. Convert to 16kHz mono PCM 2. Convert to 16kHz mono PCM
3. Split into 60ms chunks (simulating WebSocket protocol) 3. Split into 60ms chunks (simulating WebSocket protocol)
4. Feed chunks to FSMN VAD stream 4. Feed chunks to FSMN VAD ONNX stream
5. Print VAD events (START_OF_SPEECH, END_OF_SPEECH) 5. Print VAD events (START_OF_SPEECH, END_OF_SPEECH)
Usage: Usage:
@ -136,41 +136,55 @@ class VADEvent:
# ============================================================================ # ============================================================================
class FsmnVADTester: class FsmnVADTester:
"""Test FSMN VAD with audio file input""" """Test FSMN VAD ONNX with audio file input"""
def __init__( def __init__(
self, self,
model_dir: str = "models/fsmn_vad_onnx",
quantize: bool = True,
chunk_size_ms: int = 100, chunk_size_ms: int = 100,
min_silence_duration_ms: int = 500, min_silence_duration_ms: int = 500,
speech_noise_threshold: float = 0.6, speech_noise_threshold: float = 0.6,
sil_to_speech_time_thres: int = 150,
prefix_padding_duration: float = 0.3, prefix_padding_duration: float = 0.3,
): ):
self.model_dir = model_dir
self.quantize = quantize
self.chunk_size_ms = chunk_size_ms self.chunk_size_ms = chunk_size_ms
self.min_silence_duration_ms = min_silence_duration_ms self.min_silence_duration_ms = min_silence_duration_ms
self.speech_noise_threshold = speech_noise_threshold self.speech_noise_threshold = speech_noise_threshold
self.sil_to_speech_time_thres = sil_to_speech_time_thres
self.prefix_padding_duration = prefix_padding_duration self.prefix_padding_duration = prefix_padding_duration
self.sample_rate = 16000 self.sample_rate = 16000
# Initialize FSMN model # Initialize FSMN ONNX model
self._init_model() self._init_model()
def _init_model(self): def _init_model(self):
"""Initialize FSMN VAD model""" """Initialize FSMN VAD ONNX model"""
try: try:
from funasr import AutoModel from funasr_onnx import Fsmn_vad_online
except ImportError: except ImportError:
print("Error: funasr is required. Install with: pip install funasr") print("Error: funasr_onnx is required. Install with: pip install funasr-onnx")
sys.exit(1) sys.exit(1)
print("\nInitializing FSMN VAD model...") print(f"\nInitializing FSMN VAD ONNX model from {self.model_dir}...")
self.model = AutoModel( self.model = Fsmn_vad_online(
model="fsmn-vad", model_dir=self.model_dir,
model_revision="v2.0.4", quantize=self.quantize,
disable_pbar=True, # disable progress bar max_end_sil=self.min_silence_duration_ms,
max_end_silence_time=self.min_silence_duration_ms,
speech_noise_thres=self.speech_noise_threshold,
) )
print("Model initialized.")
# Override VAD parameters at runtime
vad_opts = self.model.vad_scorer.vad_opts
vad_opts.max_end_silence_time = self.min_silence_duration_ms
vad_opts.speech_noise_thres = self.speech_noise_threshold
vad_opts.sil_to_speech_time_thres = self.sil_to_speech_time_thres
print(f"Model initialized (quantize={self.quantize}).")
print(f" max_end_silence_time: {vad_opts.max_end_silence_time}ms")
print(f" speech_noise_thres: {vad_opts.speech_noise_thres}")
print(f" sil_to_speech_time_thres: {vad_opts.sil_to_speech_time_thres}ms")
def process_audio_file(self, file_path: str, input_chunk_ms: int = 60, verbose: bool = False) -> List[dict]: def process_audio_file(self, file_path: str, input_chunk_ms: int = 60, verbose: bool = False) -> List[dict]:
""" """
@ -202,7 +216,7 @@ class FsmnVADTester:
speech_buffer_index = 0 speech_buffer_index = 0
# State # State
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
speaking = False speaking = False
speech_start_ms = 0 speech_start_ms = 0
speech_duration = 0.0 speech_duration = 0.0
@ -247,13 +261,8 @@ class FsmnVADTester:
chunk_int16 = np.frombuffer(inference_buffer[:chunk_bytes], dtype=np.int16) chunk_int16 = np.frombuffer(inference_buffer[:chunk_bytes], dtype=np.int16)
chunk_float32 = chunk_int16.astype(np.float32) / 32768.0 chunk_float32 = chunk_int16.astype(np.float32) / 32768.0
# Run FSMN inference (is_final=False for streaming scenario) # Run FSMN ONNX inference
res = self.model.generate( res = self.model(chunk_float32, param_dict=fsmn_param_dict)
input=chunk_float32,
cache=fsmn_cache,
is_final=False,
chunk_size=self.chunk_size_ms,
)
inference_duration = time.perf_counter() - inference_start inference_duration = time.perf_counter() - inference_start
total_inference_time += inference_duration total_inference_time += inference_duration
@ -261,9 +270,8 @@ class FsmnVADTester:
# Verbose output: show raw FSMN result # Verbose output: show raw FSMN result
if verbose: if verbose:
value = res[0].get("value", []) if res and len(res) > 0 else []
print(f" [{current_time_ms:6.0f}ms] inference #{inference_count:3d} | " print(f" [{current_time_ms:6.0f}ms] inference #{inference_count:3d} | "
f"result={value} | " f"result={res} | "
f"time={inference_duration*1000:.2f}ms") f"time={inference_duration*1000:.2f}ms")
# Copy to speech buffer # Copy to speech buffer
@ -273,9 +281,9 @@ class FsmnVADTester:
speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_buffer[:to_copy] speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_buffer[:to_copy]
speech_buffer_index += to_copy speech_buffer_index += to_copy
# Parse FSMN result # Parse FSMN ONNX result: [[[start, end], ...]]
if res and len(res) > 0 and res[0].get("value"): if res and len(res) > 0 and len(res[0]) > 0:
seg = res[0]["value"][0] seg = res[0][0] # First segment from first batch
seg_start, seg_end = seg[0], seg[1] seg_start, seg_end = seg[0], seg[1]
if seg_start >= 0 and seg_end == -1: if seg_start >= 0 and seg_end == -1:
@ -320,7 +328,7 @@ class FsmnVADTester:
# Reset state # Reset state
speech_duration = 0.0 speech_duration = 0.0
fsmn_cache = {} fsmn_param_dict = {"in_cache": [], "is_final": False}
reset_write_cursor() reset_write_cursor()
elif seg_start > 0 and seg_end > 0: elif seg_start > 0 and seg_end > 0:
@ -353,13 +361,14 @@ class FsmnVADTester:
def main(): def main():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Test FSMN VAD with audio file", description="Test FSMN VAD ONNX with audio file",
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=""" epilog="""
Examples: Examples:
python test_fsmn_vad_stream.py test_audio.wav python test_fsmn_vad_stream.py test_audio.wav
python test_fsmn_vad_stream.py test_audio.mp3 --input-chunk-ms 100 python test_fsmn_vad_stream.py test_audio.mp3 --input-chunk-ms 100
python test_fsmn_vad_stream.py test_audio.wav --min-silence-ms 800 python test_fsmn_vad_stream.py test_audio.wav --min-silence-ms 800
python test_fsmn_vad_stream.py test_audio.wav --no-quantize
""" """
) )
@ -369,6 +378,19 @@ Examples:
help="Path to audio file (wav, mp3, etc.)" help="Path to audio file (wav, mp3, etc.)"
) )
parser.add_argument(
"--model-dir",
type=str,
default="models/fsmn_vad_onnx",
help="ONNX model directory (default: models/fsmn_vad_onnx)"
)
parser.add_argument(
"--no-quantize",
action="store_true",
help="Use FP32 model instead of INT8 quantized model"
)
parser.add_argument( parser.add_argument(
"--input-chunk-ms", "--input-chunk-ms",
type=int, type=int,
@ -397,6 +419,13 @@ Examples:
help="Speech noise threshold (default: 0.6)" help="Speech noise threshold (default: 0.6)"
) )
parser.add_argument(
"--sil-to-speech-time",
type=int,
default=150,
help="Silence to speech transition time in ms (default: 150)"
)
parser.add_argument( parser.add_argument(
"--prefix-padding", "--prefix-padding",
type=float, type=float,
@ -419,9 +448,12 @@ Examples:
# Create tester and run # Create tester and run
tester = FsmnVADTester( tester = FsmnVADTester(
model_dir=args.model_dir,
quantize=not args.no_quantize,
chunk_size_ms=args.fsmn_chunk_ms, chunk_size_ms=args.fsmn_chunk_ms,
min_silence_duration_ms=args.min_silence_ms, min_silence_duration_ms=args.min_silence_ms,
speech_noise_threshold=args.speech_noise_threshold, speech_noise_threshold=args.speech_noise_threshold,
sil_to_speech_time_thres=args.sil_to_speech_time,
prefix_padding_duration=args.prefix_padding, prefix_padding_duration=args.prefix_padding,
) )

3454
main/xiaozhi-server/uv.lock Normal file

File diff suppressed because it is too large Load diff