mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
add: tts stream 输出,fishspeech支持,其他还未实现
This commit is contained in:
parent
5597a3e0ef
commit
95ca866a37
5 changed files with 61 additions and 49 deletions
20
config.yaml
20
config.yaml
|
|
@ -121,7 +121,7 @@ LLM:
|
||||||
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
|
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
|
||||||
model_name: glm-4-flash
|
model_name: glm-4-flash
|
||||||
url: https://open.bigmodel.cn/api/paas/v4/
|
url: https://open.bigmodel.cn/api/paas/v4/
|
||||||
api_key: 你的chat-glm api key
|
api_key: 51ff5fdb325c4fc899923d532148c2dd.FFuMryUTTnf9fKRf
|
||||||
OllamaLLM:
|
OllamaLLM:
|
||||||
# 定义LLM API类型
|
# 定义LLM API类型
|
||||||
type: ollama
|
type: ollama
|
||||||
|
|
@ -163,7 +163,7 @@ LLM:
|
||||||
|
|
||||||
TTS_SET:
|
TTS_SET:
|
||||||
TTS_STREAM: false #是否启动流响应 true/false,默认false
|
TTS_STREAM: false #是否启动流响应 true/false,默认false
|
||||||
MAX_WORKERS: 3 #并发请求tts的数量,这个调太大,本地tts会变慢
|
MAX_WORKERS: 4 #并发请求tts的数量,这个调太大,本地tts会变慢
|
||||||
|
|
||||||
TTS:
|
TTS:
|
||||||
# 当前支持的type为edge、doubao,可自行适配
|
# 当前支持的type为edge、doubao,可自行适配
|
||||||
|
|
@ -216,15 +216,23 @@ TTS:
|
||||||
output_file: tmp/
|
output_file: tmp/
|
||||||
response_format: wav
|
response_format: wav
|
||||||
reference_id: null
|
reference_id: null
|
||||||
reference_audio: ["/tmp/test.wav",]
|
reference_audio:
|
||||||
reference_text: ["你弄来这些吟词宴曲来看,还是这些混话来欺负我。",]
|
- "audio_ref/shinchan.wav"
|
||||||
|
- "audio_ref/shinchan2.wav"
|
||||||
|
- "audio_ref/shinchan3.wav"
|
||||||
|
- "audio_ref/shinchan4.wav"
|
||||||
|
reference_text:
|
||||||
|
- "难过的事讨厌的事丢脸的事全都集中起来,在这里,让水冲走所有的烦恼不就好了吗。"
|
||||||
|
- "我还是觉得船到桥头自然直这句话最棒了。"
|
||||||
|
- "我不是小鬼,我是野原新之助,小新这次的目标是成为圆梦之星哦,在努力一下好了,是我的脚自己要走这么快的喔,竞争就是这么激烈。小白,我们走了,成为圆梦之星是不是可以打败怪兽呢。"
|
||||||
|
- "工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。"
|
||||||
normalize: true
|
normalize: true
|
||||||
max_new_tokens: 1024
|
max_new_tokens: 1024
|
||||||
chunk_length: 200
|
chunk_length: 50
|
||||||
top_p: 0.7
|
top_p: 0.7
|
||||||
repetition_penalty: 1.2
|
repetition_penalty: 1.2
|
||||||
temperature: 0.7
|
temperature: 0.7
|
||||||
streaming: false
|
streaming: true
|
||||||
use_memory_cache: "on"
|
use_memory_cache: "on"
|
||||||
seed: null
|
seed: null
|
||||||
channels: 1
|
channels: 1
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,8 @@ class ConnectionHandler:
|
||||||
self.tts_queue = queue.Queue()
|
self.tts_queue = queue.Queue()
|
||||||
self.tts_queue_stream = 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)
|
max_workers = self.config.get("TTS_SET", {}).get("MAX_WORKERS", 10)
|
||||||
|
self.executor = ThreadPoolExecutor(max_workers=max_workers)
|
||||||
|
|
||||||
# 依赖的组件
|
# 依赖的组件
|
||||||
self.vad = _vad
|
self.vad = _vad
|
||||||
|
|
@ -77,6 +78,7 @@ class ConnectionHandler:
|
||||||
# tts相关变量
|
# tts相关变量
|
||||||
self.tts_first_text_index = -1
|
self.tts_first_text_index = -1
|
||||||
self.tts_last_text_index = -1
|
self.tts_last_text_index = -1
|
||||||
|
self.tts_duration = 0
|
||||||
|
|
||||||
# iot相关变量
|
# iot相关变量
|
||||||
self.iot_descriptors = {}
|
self.iot_descriptors = {}
|
||||||
|
|
@ -252,24 +254,22 @@ class ConnectionHandler:
|
||||||
segment_text_raw = current_text[:last_punct_pos + 1]
|
segment_text_raw = current_text[:last_punct_pos + 1]
|
||||||
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)
|
|
||||||
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)
|
|
||||||
self.tts_queue.put(future)
|
|
||||||
# 强制设置空字符,测试TTS出错返回语音的健壮性
|
# 强制设置空字符,测试TTS出错返回语音的健壮性
|
||||||
# if text_index % 2 == 0:
|
# if text_index % 2 == 0:
|
||||||
# segment_text = " "
|
# segment_text = " "
|
||||||
text_index += 1
|
text_index += 1
|
||||||
self.recode_first_last_text(segment_text, text_index)
|
self.recode_first_last_text(segment_text, text_index)
|
||||||
future = self.executor.submit(self.speak_and_play, segment_text, text_index)
|
if self.tts_stream:
|
||||||
self.tts_queue.put(future)
|
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,
|
||||||
|
"text_index": text_index
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
future = self.executor.submit(self.speak_and_play, segment_text, text_index)
|
||||||
|
self.tts_queue.put(future)
|
||||||
processed_chars += len(segment_text_raw) # 更新已处理字符位置
|
processed_chars += len(segment_text_raw) # 更新已处理字符位置
|
||||||
|
|
||||||
# 处理最后剩余的文本
|
# 处理最后剩余的文本
|
||||||
|
|
@ -280,18 +280,16 @@ class ConnectionHandler:
|
||||||
if segment_text:
|
if segment_text:
|
||||||
text_index += 1
|
text_index += 1
|
||||||
self.recode_first_last_text(segment_text, text_index)
|
self.recode_first_last_text(segment_text, text_index)
|
||||||
future = self.executor.submit(self.speak_and_play, segment_text, text_index)
|
|
||||||
self.tts_queue.put(future)
|
|
||||||
self.recode_first_last_text(segment_text)
|
|
||||||
if self.tts_stream:
|
if self.tts_stream:
|
||||||
stream_queue = queue.Queue()
|
stream_queue = queue.Queue()
|
||||||
self.executor.submit(self.speak_and_play_stream, segment_text, stream_queue)
|
self.executor.submit(self.speak_and_play_stream, segment_text, stream_queue, text_index)
|
||||||
self.tts_queue_stream.put({
|
self.tts_queue_stream.put({
|
||||||
"text": segment_text,
|
"text": segment_text,
|
||||||
"chunk_queque": stream_queue
|
"chunk_queque": stream_queue,
|
||||||
|
"text_index": text_index
|
||||||
})
|
})
|
||||||
else:
|
else:
|
||||||
future = self.executor.submit(self.speak_and_play, segment_text)
|
future = self.executor.submit(self.speak_and_play, segment_text, text_index)
|
||||||
self.tts_queue.put(future)
|
self.tts_queue.put(future)
|
||||||
|
|
||||||
self.llm_finish_task = True
|
self.llm_finish_task = True
|
||||||
|
|
@ -353,6 +351,7 @@ class ConnectionHandler:
|
||||||
try:
|
try:
|
||||||
text = tts_stream_queue_msg["text"]
|
text = tts_stream_queue_msg["text"]
|
||||||
chunk_queque = tts_stream_queue_msg["chunk_queque"]
|
chunk_queque = tts_stream_queue_msg["chunk_queque"]
|
||||||
|
text_index = tts_stream_queue_msg["text_index"]
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
self.logger.error("TTS 任务超时")
|
self.logger.error("TTS 任务超时")
|
||||||
continue
|
continue
|
||||||
|
|
@ -361,7 +360,7 @@ class ConnectionHandler:
|
||||||
continue
|
continue
|
||||||
if not self.client_abort:
|
if not self.client_abort:
|
||||||
# 如果没有中途打断就发送语音
|
# 如果没有中途打断就发送语音
|
||||||
self.audio_play_queue.put((chunk_queque, text))
|
self.audio_play_queue.put((chunk_queque, text, text_index))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.clearSpeakStatus()
|
self.clearSpeakStatus()
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
|
|
@ -375,9 +374,10 @@ class ConnectionHandler:
|
||||||
text = None
|
text = None
|
||||||
try:
|
try:
|
||||||
if self.tts_stream:
|
if self.tts_stream:
|
||||||
chunk_queque, text = self.audio_play_queue.get()
|
chunk_queque, text, text_index = self.audio_play_queue.get()
|
||||||
future = asyncio.run_coroutine_threadsafe(sendAudioMessageStream(self, chunk_queque, text),
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.loop)
|
sendAudioMessageStream(self, chunk_queque, text, text_index),
|
||||||
|
self.loop)
|
||||||
future.result()
|
future.result()
|
||||||
else:
|
else:
|
||||||
opus_datas, text, text_index = self.audio_play_queue.get()
|
opus_datas, text, text_index = self.audio_play_queue.get()
|
||||||
|
|
@ -398,17 +398,18 @@ 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, text_index
|
return tts_file, text, text_index
|
||||||
|
|
||||||
def speak_and_play_stream(self, text, queue: queue.Queue):
|
def speak_and_play_stream(self, text, queue: queue.Queue, text_index=0):
|
||||||
if text is None or len(text) <= 0:
|
if text is None or len(text) <= 0:
|
||||||
self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}")
|
self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}")
|
||||||
return None, text
|
return None, text
|
||||||
self.tts.to_tts_stream(text, queue)
|
self.tts.to_tts_stream(text, queue, text_index)
|
||||||
|
|
||||||
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
|
||||||
self.tts_last_text_index = -1
|
self.tts_last_text_index = -1
|
||||||
self.tts_first_text_index = -1
|
self.tts_first_text_index = -1
|
||||||
|
self.tts_duration = 0
|
||||||
|
|
||||||
def recode_first_last_text(self, text, text_index=0):
|
def recode_first_last_text(self, text, text_index=0):
|
||||||
if self.tts_first_text_index == -1:
|
if self.tts_first_text_index == -1:
|
||||||
|
|
|
||||||
|
|
@ -16,11 +16,11 @@ async def isLLMWantToFinish(last_text):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
async def sendAudioMessageStream(conn, audios_queue, text):
|
|
||||||
|
async def sendAudioMessageStream(conn, audios_queue, text, text_index=0):
|
||||||
# 发送句子开始消息
|
# 发送句子开始消息
|
||||||
if text == conn.tts_first_text:
|
if text_index == conn.tts_first_text_index:
|
||||||
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
|
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
|
||||||
conn.tts_start_speak_time = time.perf_counter()
|
|
||||||
await send_tts_message(conn, "sentence_start", text)
|
await send_tts_message(conn, "sentence_start", text)
|
||||||
|
|
||||||
# 初始化流控参数
|
# 初始化流控参数
|
||||||
|
|
@ -37,17 +37,16 @@ async def sendAudioMessageStream(conn, audios_queue, text):
|
||||||
audio_data_chunke = audios_queue.get(timeout=5) # 设置超时为1秒
|
audio_data_chunke = audios_queue.get(timeout=5) # 设置超时为1秒
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 如果超时,继续等待
|
# 如果超时,继续等待
|
||||||
print(f"获取队列超时~{e}")
|
logger.bind(tag=TAG).error(f"获取队列超时~{e}")
|
||||||
|
|
||||||
audio_opus_datas = audio_data_chunke.get('data') if audio_data_chunke else None
|
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
|
duration = audio_data_chunke.get('duration') if audio_data_chunke else 0
|
||||||
|
|
||||||
if audio_data_chunke:
|
if audio_data_chunke:
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
# 检查是否超过 5 秒没有数据
|
# 检查是否超过 5 秒没有数据
|
||||||
if time.time() - start_time > 5:
|
if time.time() - start_time > 15:
|
||||||
logger.bind(tag=TAG).error("超过5秒没有数据,退出。")
|
logger.bind(tag=TAG).error("超过15秒没有数据,退出。")
|
||||||
time_out_stop = True
|
|
||||||
break
|
break
|
||||||
|
|
||||||
if audio_data_chunke and audio_data_chunke.get("end", True):
|
if audio_data_chunke and audio_data_chunke.get("end", True):
|
||||||
|
|
@ -66,14 +65,17 @@ async def sendAudioMessageStream(conn, audios_queue, text):
|
||||||
logger.bind(tag=TAG).error(f"发生错误: {e}")
|
logger.bind(tag=TAG).error(f"发生错误: {e}")
|
||||||
traceback.print_exc() # 打印错误堆栈
|
traceback.print_exc() # 打印错误堆栈
|
||||||
await send_tts_message(conn, "sentence_end", text)
|
await send_tts_message(conn, "sentence_end", text)
|
||||||
|
|
||||||
|
print(f'{text_index}-{conn.tts_last_text_index}')
|
||||||
# 发送结束消息(如果是最后一个文本)
|
# 发送结束消息(如果是最后一个文本)
|
||||||
if (conn.llm_finish_task and text == conn.tts_last_text) or time_out_stop:
|
if conn.llm_finish_task and text_index == conn.tts_last_text_index:
|
||||||
if conn.tts_duration > 0:
|
if conn.tts_duration and conn.tts_duration > 0:
|
||||||
await asyncio.sleep(conn.tts_duration)
|
await asyncio.sleep(conn.tts_duration)
|
||||||
await send_tts_message(conn, 'stop', None)
|
await send_tts_message(conn, 'stop', None)
|
||||||
if await isLLMWantToFinish(text):
|
if await isLLMWantToFinish(text):
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
||||||
|
|
||||||
async def sendAudioMessage(conn, audios, text, text_index=0):
|
async def sendAudioMessage(conn, audios, text, text_index=0):
|
||||||
# 发送句子开始消息
|
# 发送句子开始消息
|
||||||
if text_index == conn.tts_first_text_index:
|
if text_index == conn.tts_first_text_index:
|
||||||
|
|
|
||||||
|
|
@ -38,9 +38,9 @@ class TTSProviderBase(ABC):
|
||||||
logger.bind(tag=TAG).info(f": {e}")
|
logger.bind(tag=TAG).info(f": {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def to_tts_stream(self,text, queue: queue.Queue):
|
def to_tts_stream(self, text, queue: queue.Queue, text_index=0):
|
||||||
try:
|
try:
|
||||||
asyncio.run(self.text_to_speak_stream(text, queue))
|
asyncio.run(self.text_to_speak_stream(text, queue, text_index))
|
||||||
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
|
||||||
|
|
@ -49,7 +49,7 @@ 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):
|
async def text_to_speak_stream(self, text, queue: queue.Queue, text_index=0):
|
||||||
raise Exception("该TTS还没有实现stream模式")
|
raise Exception("该TTS还没有实现stream模式")
|
||||||
|
|
||||||
def wav_to_opus_data(self, wav_file_path):
|
def wav_to_opus_data(self, wav_file_path):
|
||||||
|
|
@ -94,7 +94,7 @@ class TTSProviderBase(ABC):
|
||||||
|
|
||||||
return opus_datas, duration
|
return opus_datas, duration
|
||||||
|
|
||||||
def wav_to_opus_data_audio(self,audio):
|
def wav_to_opus_data_audio(self, audio):
|
||||||
duration = len(audio) / 1000.0
|
duration = len(audio) / 1000.0
|
||||||
# 转换为单声道和16kHz采样率(确保与编码器匹配)
|
# 转换为单声道和16kHz采样率(确保与编码器匹配)
|
||||||
audio = audio.set_channels(1).set_frame_rate(16000)
|
audio = audio.set_channels(1).set_frame_rate(16000)
|
||||||
|
|
@ -126,4 +126,3 @@ class TTSProviderBase(ABC):
|
||||||
opus_datas.append(opus_data)
|
opus_datas.append(opus_data)
|
||||||
|
|
||||||
return opus_datas, duration
|
return opus_datas, duration
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -174,7 +174,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
audio.set_channels(1).set_frame_rate(16000)
|
audio.set_channels(1).set_frame_rate(16000)
|
||||||
return audio
|
return audio
|
||||||
|
|
||||||
async def text_to_speak_stream(self, text, queue: queue.Queue):
|
async def text_to_speak_stream(self, text, queue: queue.Queue,text_index=0):
|
||||||
try:
|
try:
|
||||||
# Prepare reference data
|
# Prepare reference data
|
||||||
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
|
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
|
||||||
|
|
@ -204,6 +204,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
pydantic_data = ServeTTSRequest(**data)
|
pydantic_data = ServeTTSRequest(**data)
|
||||||
audio_buff = None
|
audio_buff = None
|
||||||
chunk_total = b''
|
chunk_total = b''
|
||||||
|
print("请求tts")
|
||||||
with requests.post(
|
with requests.post(
|
||||||
self.api_url,
|
self.api_url,
|
||||||
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
|
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
|
||||||
|
|
@ -228,7 +229,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
queue.put({
|
queue.put({
|
||||||
"data": opus_datas,
|
"data": opus_datas,
|
||||||
"duration": duration,
|
"duration": duration,
|
||||||
"end": False
|
"end": False,
|
||||||
|
"text_index": text_index
|
||||||
})
|
})
|
||||||
audio_buff = None
|
audio_buff = None
|
||||||
chunk_total = b''
|
chunk_total = b''
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue