mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
save
This commit is contained in:
parent
bc81bcf899
commit
8d7cc1f740
4 changed files with 93 additions and 17 deletions
Binary file not shown.
|
|
@ -484,6 +484,14 @@ class ConnectionHandler:
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
self.tts.open_audio_channels(self), self.loop
|
self.tts.open_audio_channels(self), self.loop
|
||||||
)
|
)
|
||||||
|
# 预生成唤醒词回复缓存(mimo_v25 优先)
|
||||||
|
try:
|
||||||
|
from core.handle.helloHandle import wakeupWordsResponse
|
||||||
|
asyncio.run_coroutine_threadsafe(
|
||||||
|
wakeupWordsResponse(self), self.loop
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).warning(f"预生成唤醒词回复失败: {e}")
|
||||||
if self.need_bind:
|
if self.need_bind:
|
||||||
self.bind_completed_event.set()
|
self.bind_completed_event.set()
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import json
|
||||||
import uuid
|
import uuid
|
||||||
import random
|
import random
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import hashlib
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
|
@ -13,6 +14,7 @@ from core.providers.tts.dto.dto import SentenceType
|
||||||
from core.utils.wakeup_word import WakeupWordsConfig
|
from core.utils.wakeup_word import WakeupWordsConfig
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
|
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
|
||||||
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
|
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
|
||||||
|
from core.utils.tts import create_instance
|
||||||
from core.providers.tools.device_mcp import MCPClient, send_mcp_initialize_message
|
from core.providers.tools.device_mcp import MCPClient, send_mcp_initialize_message
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -39,6 +41,33 @@ wakeup_words_config = WakeupWordsConfig()
|
||||||
_wakeup_response_lock = asyncio.Lock()
|
_wakeup_response_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_wakeup_cache_voice(conn: "ConnectionHandler"):
|
||||||
|
"""获取唤醒词缓存 key。
|
||||||
|
注意:此 key 表示"唤醒词目标缓存槽",不代表实际生成 provider。
|
||||||
|
当 mimo_v25 生成失败时,回退音频也会写入同一 key 下。
|
||||||
|
"""
|
||||||
|
mimo_config = conn.config.get("TTS", {}).get("mimo_v25")
|
||||||
|
if mimo_config:
|
||||||
|
model = mimo_config.get("model", "mimo-v2.5-tts")
|
||||||
|
voice = mimo_config.get("voice", "default")
|
||||||
|
fmt = mimo_config.get("response_format", "wav")
|
||||||
|
style = mimo_config.get("style_instruction", "")
|
||||||
|
style_hash = hashlib.md5(style.encode()).hexdigest()[:6]
|
||||||
|
clone_file = mimo_config.get("clone_audio_file", "")
|
||||||
|
clone_hash = hashlib.md5(clone_file.encode()).hexdigest()[:6] if clone_file else "none"
|
||||||
|
opt_preview = "1" if mimo_config.get("optimize_text_preview", False) else "0"
|
||||||
|
return f"mimo_v25_{model}_{voice}_{fmt}_{style_hash}_{clone_hash}_{opt_preview}"
|
||||||
|
voice = getattr(conn.tts, "voice", "default")
|
||||||
|
return voice or "default"
|
||||||
|
|
||||||
|
|
||||||
|
def _save_wakeup_response(wav_bytes, voice_key, text):
|
||||||
|
file_path = wakeup_words_config.generate_file_path(voice_key)
|
||||||
|
with open(file_path, "wb") as f:
|
||||||
|
f.write(wav_bytes)
|
||||||
|
wakeup_words_config.update_wakeup_response(voice_key, file_path, text)
|
||||||
|
|
||||||
|
|
||||||
async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
|
async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
|
||||||
"""处理hello消息"""
|
"""处理hello消息"""
|
||||||
audio_params = msg_json.get("audio_params")
|
audio_params = msg_json.get("audio_params")
|
||||||
|
|
@ -84,13 +113,15 @@ async def checkWakeupWords(conn: "ConnectionHandler", text):
|
||||||
conn.just_woken_up = True
|
conn.just_woken_up = True
|
||||||
await send_tts_message(conn, "start")
|
await send_tts_message(conn, "start")
|
||||||
|
|
||||||
# 获取当前音色
|
# 获取唤醒词缓存 key
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
voice_key = _get_wakeup_cache_voice(conn)
|
||||||
if not voice:
|
conn.logger.bind(tag=TAG).info(f"checkWakeupWords voice_key={voice_key}")
|
||||||
voice = "default"
|
|
||||||
|
|
||||||
# 获取唤醒词回复配置
|
# 获取唤醒词回复配置
|
||||||
response = wakeup_words_config.get_wakeup_response(voice)
|
response = wakeup_words_config.get_wakeup_response(voice_key)
|
||||||
|
conn.logger.bind(tag=TAG).info(
|
||||||
|
f"checkWakeupWords response={'命中' if response else '未命中'}"
|
||||||
|
)
|
||||||
if not response or not response.get("file_path"):
|
if not response or not response.get("file_path"):
|
||||||
response = {
|
response = {
|
||||||
"voice": "default",
|
"voice": "default",
|
||||||
|
|
@ -117,17 +148,26 @@ async def checkWakeupWords(conn: "ConnectionHandler", text):
|
||||||
# 检查是否需要更新唤醒词回复
|
# 检查是否需要更新唤醒词回复
|
||||||
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
|
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
|
||||||
if not _wakeup_response_lock.locked():
|
if not _wakeup_response_lock.locked():
|
||||||
asyncio.create_task(wakeupWordsResponse(conn))
|
async def _safe_wakeup_response():
|
||||||
|
try:
|
||||||
|
await wakeupWordsResponse(conn)
|
||||||
|
except Exception as e:
|
||||||
|
conn.logger.bind(tag=TAG).exception(
|
||||||
|
f"wakeupWordsResponse 执行失败: {e}"
|
||||||
|
)
|
||||||
|
asyncio.create_task(_safe_wakeup_response())
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
||||||
if not conn.tts:
|
if not conn.tts:
|
||||||
|
conn.logger.bind(tag=TAG).debug("wakeupWordsResponse: conn.tts 为 None,跳过")
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 尝试获取锁,如果获取不到就返回
|
# 尝试获取锁,如果获取不到就返回
|
||||||
if not await _wakeup_response_lock.acquire():
|
if not await _wakeup_response_lock.acquire():
|
||||||
|
conn.logger.bind(tag=TAG).debug("wakeupWordsResponse: 获取锁失败,跳过")
|
||||||
return
|
return
|
||||||
|
|
||||||
# 从预定义回复列表中随机选择一个回复
|
# 从预定义回复列表中随机选择一个回复
|
||||||
|
|
@ -135,21 +175,47 @@ async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
||||||
if not result or len(result) == 0:
|
if not result or len(result) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
# 生成TTS音频
|
voice_key = _get_wakeup_cache_voice(conn)
|
||||||
|
conn.logger.bind(tag=TAG).info(
|
||||||
|
f"开始生成唤醒词回复: voice_key={voice_key}, text={result}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 优先使用 mimo_v25 生成唤醒词回复
|
||||||
|
mimo_config = conn.config.get("TTS", {}).get("mimo_v25")
|
||||||
|
if mimo_config:
|
||||||
|
try:
|
||||||
|
mimo_tts = create_instance("mimo_v25", mimo_config, delete_audio_file=True)
|
||||||
|
mimo_tts.conn = conn
|
||||||
|
tts_result = await asyncio.to_thread(mimo_tts.to_tts, result)
|
||||||
|
if not tts_result:
|
||||||
|
conn.logger.bind(tag=TAG).warning(
|
||||||
|
"mimo_v25 生成唤醒词回复返回空,回退到当前 TTS"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
wav_bytes = opus_datas_to_wav_bytes(
|
||||||
|
tts_result, sample_rate=conn.sample_rate
|
||||||
|
)
|
||||||
|
_save_wakeup_response(wav_bytes, voice_key, result)
|
||||||
|
conn.logger.bind(tag=TAG).info(
|
||||||
|
f"mimo_v25 唤醒词回复生成成功: voice_key={voice_key}"
|
||||||
|
)
|
||||||
|
await mimo_tts.close()
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
conn.logger.bind(tag=TAG).warning(
|
||||||
|
f"mimo_v25 生成唤醒词回复失败,回退到当前 TTS: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 回退到当前 TTS
|
||||||
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
|
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
|
||||||
if not tts_result:
|
if not tts_result:
|
||||||
|
conn.logger.bind(tag=TAG).warning("当前 TTS 生成唤醒词回复返回空")
|
||||||
return
|
return
|
||||||
|
|
||||||
# 获取当前音色
|
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
|
||||||
|
|
||||||
# 使用链接的sample_rate
|
|
||||||
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=conn.sample_rate)
|
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=conn.sample_rate)
|
||||||
file_path = wakeup_words_config.generate_file_path(voice)
|
_save_wakeup_response(wav_bytes, voice_key, result)
|
||||||
with open(file_path, "wb") as f:
|
conn.logger.bind(tag=TAG).info(
|
||||||
f.write(wav_bytes)
|
f"当前 TTS 唤醒词回复生成成功: voice_key={voice_key}"
|
||||||
# 更新配置
|
)
|
||||||
wakeup_words_config.update_wakeup_response(voice, file_path, result)
|
|
||||||
finally:
|
finally:
|
||||||
# 确保在任何情况下都释放锁
|
# 确保在任何情况下都释放锁
|
||||||
if _wakeup_response_lock.locked():
|
if _wakeup_response_lock.locked():
|
||||||
|
|
|
||||||
|
|
@ -125,6 +125,8 @@ class WakeupWordsConfig:
|
||||||
# 生成voice的哈希值
|
# 生成voice的哈希值
|
||||||
voice_hash = hashlib.md5(voice.encode()).hexdigest()
|
voice_hash = hashlib.md5(voice.encode()).hexdigest()
|
||||||
file_path = os.path.join(self.assets_dir, f"{voice_hash}.wav")
|
file_path = os.path.join(self.assets_dir, f"{voice_hash}.wav")
|
||||||
|
# 统一使用正斜杠,避免跨平台路径问题
|
||||||
|
file_path = file_path.replace("\\", "/")
|
||||||
|
|
||||||
# 如果文件已存在,先删除
|
# 如果文件已存在,先删除
|
||||||
if os.path.exists(file_path):
|
if os.path.exists(file_path):
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue