add: tts stream 输出,fishspeech支持,其他还未实现

This commit is contained in:
lizhongxiang 2025-03-04 15:41:59 +08:00
parent effd79b465
commit 5e548f6703
5 changed files with 297 additions and 27 deletions

View file

@ -147,7 +147,6 @@ LLM:
type: coze type: coze
bot_id: 你的bot_id bot_id: 你的bot_id
user_id: 你的user_id user_id: 你的user_id
base_url: "https://api.coze.cn/open_api/v2/chat" # 服务地址
personal_access_token: 你的coze个人令牌 personal_access_token: 你的coze个人令牌
LMStudioLLM: LMStudioLLM:
# 定义LLM API类型 # 定义LLM API类型
@ -161,6 +160,11 @@ LLM:
base_url: http://homeassistant.local:8123 base_url: http://homeassistant.local:8123
agent_id: conversation.chatgpt agent_id: conversation.chatgpt
api_key: 你的home assistant api访问令牌 api_key: 你的home assistant api访问令牌
TTS_SET:
TTS_STREAM: false #是否启动流响应 true/false,默认false
MAX_WORKERS: 3 #并发请求tts的数量,这个调太大,本地tts会变慢
TTS: TTS:
# 当前支持的type为edge、doubao,可自行适配 # 当前支持的type为edge、doubao,可自行适配
EdgeTTS: EdgeTTS:

View file

@ -13,7 +13,7 @@ from core.utils.dialogue import Message, Dialogue
from core.handle.textHandle import handleTextMessage from core.handle.textHandle import handleTextMessage
from core.utils.util import get_string_no_punctuation_or_emoji from core.utils.util import get_string_no_punctuation_or_emoji
from concurrent.futures import ThreadPoolExecutor, TimeoutError from concurrent.futures import ThreadPoolExecutor, TimeoutError
from core.handle.sendAudioHandle import sendAudioMessage from core.handle.sendAudioHandle import sendAudioMessage, sendAudioMessageStream
from core.handle.receiveAudioHandle import handleAudioMessage from core.handle.receiveAudioHandle import handleAudioMessage
from config.private_config import PrivateConfig from config.private_config import PrivateConfig
from core.auth import AuthMiddleware, AuthenticationError from core.auth import AuthMiddleware, AuthenticationError
@ -28,6 +28,8 @@ class ConnectionHandler:
self.logger = setup_logging() self.logger = setup_logging()
self.auth = AuthMiddleware(config) self.auth = AuthMiddleware(config)
self.tts_stream = self.config.get("TTS_SET", {}).get("TTS_STREAM", False)
self.websocket = None self.websocket = None
self.headers = None self.headers = None
self.session_id = None self.session_id = None
@ -42,6 +44,7 @@ class ConnectionHandler:
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
self.stop_event = threading.Event() self.stop_event = threading.Event()
self.tts_queue = queue.Queue() self.tts_queue = queue.Queue()
self.tts_queue_stream = queue.Queue()
self.audio_play_queue = queue.Queue() self.audio_play_queue = queue.Queue()
self.executor = ThreadPoolExecutor(max_workers=10) self.executor = ThreadPoolExecutor(max_workers=10)
@ -247,6 +250,14 @@ class ConnectionHandler:
segment_text = get_string_no_punctuation_or_emoji(segment_text_raw) segment_text = get_string_no_punctuation_or_emoji(segment_text_raw)
if segment_text: if segment_text:
self.recode_first_last_text(segment_text) self.recode_first_last_text(segment_text)
if self.tts_stream:
stream_queue = queue.Queue()
self.executor.submit(self.speak_and_play_stream, segment_text, stream_queue)
self.tts_queue_stream.put({
"text": segment_text,
"chunk_queque": stream_queue
})
else:
future = self.executor.submit(self.speak_and_play, segment_text) future = self.executor.submit(self.speak_and_play, segment_text)
self.tts_queue.put(future) self.tts_queue.put(future)
processed_chars += len(segment_text_raw) # 更新已处理字符位置 processed_chars += len(segment_text_raw) # 更新已处理字符位置
@ -258,6 +269,14 @@ class ConnectionHandler:
segment_text = get_string_no_punctuation_or_emoji(remaining_text) segment_text = get_string_no_punctuation_or_emoji(remaining_text)
if segment_text: if segment_text:
self.recode_first_last_text(segment_text) self.recode_first_last_text(segment_text)
if self.tts_stream:
stream_queue = queue.Queue()
self.executor.submit(self.speak_and_play_stream, segment_text, stream_queue)
self.tts_queue_stream.put({
"text": segment_text,
"chunk_queque": stream_queue
})
else:
future = self.executor.submit(self.speak_and_play, segment_text) future = self.executor.submit(self.speak_and_play, segment_text)
self.tts_queue.put(future) self.tts_queue.put(future)
@ -267,6 +286,12 @@ class ConnectionHandler:
return True return True
def _tts_priority_thread(self): def _tts_priority_thread(self):
if self.tts_stream:
self._tts_priority_thread_stream()
else:
self._tts_priority_thread_no_stream()
def _tts_priority_thread_no_stream(self):
while not self.stop_event.is_set(): while not self.stop_event.is_set():
text = None text = None
try: try:
@ -308,10 +333,41 @@ class ConnectionHandler:
) )
self.logger.bind(tag=TAG).error(f"tts_priority priority_thread: {text}{e}") self.logger.bind(tag=TAG).error(f"tts_priority priority_thread: {text}{e}")
def _tts_priority_thread_stream(self):
while not self.stop_event.is_set():
text = None
try:
tts_stream_queue_msg = self.tts_queue_stream.get()
try:
text = tts_stream_queue_msg["text"]
chunk_queque = tts_stream_queue_msg["chunk_queque"]
except TimeoutError:
self.logger.error("TTS 任务超时")
continue
except Exception as e:
self.logger.error(f"TTS 任务出错: {e}")
continue
if not self.client_abort:
# 如果没有中途打断就发送语音
self.audio_play_queue.put((chunk_queque, text))
except Exception as e:
self.clearSpeakStatus()
asyncio.run_coroutine_threadsafe(
self.websocket.send(json.dumps({"type": "tts", "state": "stop", "session_id": self.session_id})),
self.loop
)
self.logger.error(f"tts_priority priority_thread: {text}{e}")
def _audio_play_priority_thread(self): def _audio_play_priority_thread(self):
while not self.stop_event.is_set(): while not self.stop_event.is_set():
text = None text = None
try: try:
if self.tts_stream:
chunk_queque, text = self.audio_play_queue.get()
future = asyncio.run_coroutine_threadsafe(sendAudioMessageStream(self, chunk_queque, text),
self.loop)
future.result()
else:
opus_datas, text = self.audio_play_queue.get() opus_datas, text = self.audio_play_queue.get()
future = asyncio.run_coroutine_threadsafe(sendAudioMessage(self, opus_datas, text), self.loop) future = asyncio.run_coroutine_threadsafe(sendAudioMessage(self, opus_datas, text), self.loop)
future.result() future.result()
@ -329,6 +385,12 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).debug(f"TTS 文件生成完毕: {tts_file}") self.logger.bind(tag=TAG).debug(f"TTS 文件生成完毕: {tts_file}")
return tts_file, text return tts_file, text
def speak_and_play_stream(self, text, queue: queue.Queue):
if text is None or len(text) <= 0:
self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}")
return None, text
self.tts.to_tts_stream(text, queue)
def clearSpeakStatus(self): def clearSpeakStatus(self):
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态") self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
self.asr_server_receive = True self.asr_server_receive = True

View file

@ -1,3 +1,5 @@
import traceback
from config.logger import setup_logging from config.logger import setup_logging
import json import json
import asyncio import asyncio
@ -15,6 +17,64 @@ async def isLLMWantToFinish(last_text):
return False return False
async def sendAudioMessageStream(conn, audios_queue, text):
# 发送句子开始消息
if text == conn.tts_first_text:
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
conn.tts_start_speak_time = time.perf_counter()
await send_tts_message(conn, "sentence_start", text)
# 初始化流控参数
frame_duration = 60 # 毫秒
start_time = time.perf_counter() # 使用高精度计时器
play_position = 0 # 已播放的时长(毫秒)
time_out_stop = False
while True:
try:
start_get_queue = time.time()
# 尝试获取数据,如果没有数据,则等待一小段时间再试
audio_data_chunke = None
try:
audio_data_chunke = audios_queue.get(timeout=5) # 设置超时为1秒
except Exception as e:
# 如果超时,继续等待
print(f"获取队列超时~{e}")
audio_opus_datas = audio_data_chunke.get('data') if audio_data_chunke else None
duration = audio_data_chunke.get('duration') if audio_data_chunke else 0
if audio_data_chunke:
start_time = time.time()
# 检查是否超过 5 秒没有数据
if time.time() - start_time > 5:
logger.bind(tag=TAG).error("超过5秒没有数据,退出。")
time_out_stop = True
break
if audio_data_chunke and audio_data_chunke.get("end", True):
break
if audio_opus_datas:
queue_duration = time.time() - start_get_queue
last_duration = conn.tts_duration - queue_duration
if last_duration <= 0:
last_duration = 0
conn.tts_duration = duration + last_duration + 0.5
for opus_packet in audio_opus_datas:
await conn.websocket.send(opus_packet)
start_time = time.time() # 更新获取数据的时间
except Exception as e:
logger.bind(tag=TAG).error(f"发生错误: {e}")
traceback.print_exc() # 打印错误堆栈
await send_tts_message(conn, "sentence_end", text)
# 发送结束消息(如果是最后一个文本)
if (conn.llm_finish_task and text == conn.tts_last_text) or time_out_stop:
if conn.tts_duration > 0:
await asyncio.sleep(conn.tts_duration)
await send_tts_message(conn, 'stop', None)
if await isLLMWantToFinish(text):
await conn.close()
async def sendAudioMessage(conn, audios, text): async def sendAudioMessage(conn, audios, text):
# 发送句子开始消息 # 发送句子开始消息
if text == conn.tts_first_text: if text == conn.tts_first_text:

View file

@ -5,6 +5,7 @@ import numpy as np
import opuslib_next import opuslib_next
from pydub import AudioSegment from pydub import AudioSegment
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import queue
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
@ -33,6 +34,13 @@ class TTSProviderBase(ABC):
logger.bind(tag=TAG).info(f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次") logger.bind(tag=TAG).info(f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次")
return tmp_file return tmp_file
except Exception as e:
logger.bind(tag=TAG).info(f": {e}")
return None
def to_tts_stream(self,text, queue: queue.Queue):
try:
asyncio.run(self.text_to_speak_stream(text, queue))
except Exception as e: except Exception as e:
logger.bind(tag=TAG).info(f"Failed to generate TTS file: {e}") logger.bind(tag=TAG).info(f"Failed to generate TTS file: {e}")
return None return None
@ -41,6 +49,9 @@ class TTSProviderBase(ABC):
async def text_to_speak(self, text, output_file): async def text_to_speak(self, text, output_file):
pass pass
async def text_to_speak_stream(self,text,queue: queue.Queue):
raise Exception("该TTS还没有实现stream模式")
def wav_to_opus_data(self, wav_file_path): def wav_to_opus_data(self, wav_file_path):
# 使用pydub加载PCM文件 # 使用pydub加载PCM文件
# 获取文件后缀名 # 获取文件后缀名
@ -82,3 +93,37 @@ class TTSProviderBase(ABC):
opus_datas.append(opus_data) opus_datas.append(opus_data)
return opus_datas, duration return opus_datas, duration
def wav_to_opus_data_audio(self,audio):
duration = len(audio) / 1000.0
# 转换为单声道和16kHz采样率(确保与编码器匹配)
audio = audio.set_channels(1).set_frame_rate(16000)
# 获取原始PCM数据(16位小端)
raw_data = audio.raw_data
# 初始化Opus编码器
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
# 编码参数
frame_duration = 60 # 60ms per frame
frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame
opus_datas = []
# 按帧处理所有音频数据(包括最后一帧可能补零)
for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample
# 获取当前帧的二进制数据
chunk = raw_data[i:i + frame_size * 2]
# 如果最后一帧不足,补零
if len(chunk) < frame_size * 2:
chunk += b'\x00' * (frame_size * 2 - len(chunk))
# 转换为numpy数组处理
np_frame = np.frombuffer(chunk, dtype=np.int16)
# 编码Opus数据
opus_data = encoder.encode(np_frame.tobytes(), frame_size)
opus_datas.append(opus_data)
return opus_datas, duration

View file

@ -1,11 +1,19 @@
import base64 import base64
import os import os
import traceback
import uuid import uuid
import queue
import io
import numpy as np
import requests import requests
import ormsgpack import ormsgpack
from pathlib import Path from pathlib import Path
import torch
import torchaudio
from pydantic import BaseModel, Field, conint, model_validator from pydantic import BaseModel, Field, conint, model_validator
from pydub import AudioSegment
from typing_extensions import Annotated from typing_extensions import Annotated
from datetime import datetime from datetime import datetime
from typing import Literal from typing import Literal
@ -36,6 +44,7 @@ class ServeReferenceAudio(BaseModel):
def __repr__(self) -> str: def __repr__(self) -> str:
return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})" return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})"
class ServeTTSRequest(BaseModel): class ServeTTSRequest(BaseModel):
text: str text: str
chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200 chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
@ -70,6 +79,7 @@ def audio_to_bytes(file_path):
wav = wav_file.read() wav = wav_file.read()
return wav return wav
def read_ref_text(ref_text): def read_ref_text(ref_text):
path = Path(ref_text) path = Path(ref_text)
if path.exists() and path.is_file(): if path.exists() and path.is_file():
@ -77,31 +87,32 @@ def read_ref_text(ref_text):
return file.read() return file.read()
return ref_text return ref_text
class TTSProvider(TTSProviderBase): class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file): def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file) super().__init__(config, delete_audio_file)
self.reference_id = config.get("reference_id") self.reference_id = config.get("reference_id")
self.reference_audio = config.get("reference_audio",[]) self.reference_audio = config.get("reference_audio", [])
self.reference_text = config.get("reference_text",[]) self.reference_text = config.get("reference_text", [])
self.format = config.get("format","wav") self.format = config.get("format", "wav")
self.channels = config.get("channels",1) self.channels = config.get("channels", 1)
self.rate = config.get("rate",44100) self.rate = config.get("rate", 44100)
self.api_key = config.get("api_key","YOUR_API_KEY") self.api_key = config.get("api_key", "YOUR_API_KEY")
if "你" in self.api_key: if "你" in self.api_key:
logger.bind(tag=TAG).error("你还没配置FishSpeech TTS的密钥,请在配置文件中配置密钥,否则无法正常工作") logger.bind(tag=TAG).error("你还没配置FishSpeech TTS的密钥,请在配置文件中配置密钥,否则无法正常工作")
return return
self.normalize = config.get("normalize",True) self.normalize = config.get("normalize", True)
self.max_new_tokens = config.get("max_new_tokens",1024) self.max_new_tokens = config.get("max_new_tokens", 1024)
self.chunk_length = config.get("chunk_length",200) self.chunk_length = config.get("chunk_length", 200)
self.top_p = config.get("top_p",0.7) self.top_p = config.get("top_p", 0.7)
self.repetition_penalty = config.get("repetition_penalty",1.2) self.repetition_penalty = config.get("repetition_penalty", 1.2)
self.temperature = config.get("temperature",0.7) self.temperature = config.get("temperature", 0.7)
self.streaming = config.get("streaming",False) self.streaming = config.get("streaming", False)
self.use_memory_cache = config.get("use_memory_cache","on") self.use_memory_cache = config.get("use_memory_cache", "on")
self.seed = config.get("seed") self.seed = config.get("seed")
self.api_url = config.get("api_url","http://127.0.0.1:8080/v1/tts") self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
def generate_filename(self, extension=".wav"): def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
@ -155,4 +166,92 @@ class TTSProvider(TTSProviderBase):
print(f"Request failed with status code {response.status_code}") print(f"Request failed with status code {response.status_code}")
print(response.json()) print(response.json())
def _get_audio_from_tts(self, data_bytes):
tts_speech = torch.from_numpy(np.array(np.frombuffer(data_bytes, dtype=np.int16))).unsqueeze(dim=0)
with io.BytesIO() as bf:
torchaudio.save(bf, tts_speech, 44100, format="wav")
audio = AudioSegment.from_file(bf, format="wav")
audio.set_channels(1).set_frame_rate(16000)
return audio
async def text_to_speak_stream(self, text, queue: queue.Queue):
try:
# Prepare reference data
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text]
data = {
"text": text,
"references": [
ServeReferenceAudio(
audio=audio if audio else b"", text=text
)
for text, audio in zip(ref_texts, byte_audios)
],
"reference_id": self.reference_id,
"normalize": self.normalize,
"format": self.format,
"max_new_tokens": self.max_new_tokens,
"chunk_length": self.chunk_length,
"top_p": self.top_p,
"repetition_penalty": self.repetition_penalty,
"temperature": self.temperature,
"streaming": self.streaming,
"use_memory_cache": self.use_memory_cache,
"seed": self.seed,
}
pydantic_data = ServeTTSRequest(**data)
audio_buff = None
chunk_total = b''
with requests.post(
self.api_url,
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/msgpack",
},
) as response:
if response.status_code == 200:
for chunk in response.iter_content():
# 拼接当前块和上一块数据
chunk_total += chunk
if len(chunk_total) >= 86400 and len(chunk_total) % 86400 == 0:
audio = self._get_audio_from_tts(chunk_total)
if not audio_buff:
audio_buff = audio
else:
audio_buff += audio
if len(audio_buff.raw_data) % 1920 == 0:
# 把 audio 转成 opus
opus_datas, duration = self.wav_to_opus_data_audio(audio_buff)
queue.put({
"data": opus_datas,
"duration": duration,
"end": False
})
audio_buff = None
chunk_total = b''
if len(chunk_total) > 0:
if not audio_buff:
audio_buff = self._get_audio_from_tts(chunk_total)
else:
audio_buff += self._get_audio_from_tts(chunk_total)
# 把 audio 转成 opus
opus_datas, duration = self.wav_to_opus_data_audio(audio_buff)
queue.put({
"data": opus_datas,
"duration": duration,
"end": False
})
else:
print('请求失败:', response.status_code, response.text)
queue.put({
"data": None,
"end": True
})
except Exception as e:
logger.bind(tag=TAG).error("tts发生错误")
traceback.print_exc()
raise e