diff --git a/main/xiaozhi-server/config/assets/wakeup_words/d9db46916c443e4aea6c55c6488913cd.wav b/main/xiaozhi-server/config/assets/wakeup_words/d9db46916c443e4aea6c55c6488913cd.wav deleted file mode 100644 index 7d527e0a7..000000000 Binary files a/main/xiaozhi-server/config/assets/wakeup_words/d9db46916c443e4aea6c55c6488913cd.wav and /dev/null differ diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 2d933811f..41b1c3c0c 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -484,6 +484,14 @@ class ConnectionHandler: asyncio.run_coroutine_threadsafe( 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: self.bind_completed_event.set() return diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 6bad8380a..8d7ec89cd 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -3,6 +3,7 @@ import json import uuid import random import asyncio +import hashlib from typing import 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.handle.sendAudioHandle import sendAudioMessage, send_tts_message 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 TAG = __name__ @@ -39,6 +41,33 @@ wakeup_words_config = WakeupWordsConfig() _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): """处理hello消息""" audio_params = msg_json.get("audio_params") @@ -84,13 +113,15 @@ async def checkWakeupWords(conn: "ConnectionHandler", text): conn.just_woken_up = True await send_tts_message(conn, "start") - # 获取当前音色 - voice = getattr(conn.tts, "voice", "default") - if not voice: - voice = "default" + # 获取唤醒词缓存 key + voice_key = _get_wakeup_cache_voice(conn) + conn.logger.bind(tag=TAG).info(f"checkWakeupWords voice_key={voice_key}") # 获取唤醒词回复配置 - 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"): response = { "voice": "default", @@ -117,17 +148,26 @@ async def checkWakeupWords(conn: "ConnectionHandler", text): # 检查是否需要更新唤醒词回复 if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: 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 async def wakeupWordsResponse(conn: "ConnectionHandler"): if not conn.tts: + conn.logger.bind(tag=TAG).debug("wakeupWordsResponse: conn.tts 为 None,跳过") return try: # 尝试获取锁,如果获取不到就返回 if not await _wakeup_response_lock.acquire(): + conn.logger.bind(tag=TAG).debug("wakeupWordsResponse: 获取锁失败,跳过") return # 从预定义回复列表中随机选择一个回复 @@ -135,21 +175,47 @@ async def wakeupWordsResponse(conn: "ConnectionHandler"): if not result or len(result) == 0: 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) if not tts_result: + conn.logger.bind(tag=TAG).warning("当前 TTS 生成唤醒词回复返回空") return - - # 获取当前音色 - voice = getattr(conn.tts, "voice", "default") - - # 使用链接的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) - with open(file_path, "wb") as f: - f.write(wav_bytes) - # 更新配置 - wakeup_words_config.update_wakeup_response(voice, file_path, result) + _save_wakeup_response(wav_bytes, voice_key, result) + conn.logger.bind(tag=TAG).info( + f"当前 TTS 唤醒词回复生成成功: voice_key={voice_key}" + ) finally: # 确保在任何情况下都释放锁 if _wakeup_response_lock.locked(): diff --git a/main/xiaozhi-server/core/utils/wakeup_word.py b/main/xiaozhi-server/core/utils/wakeup_word.py index 93d4e6b84..54bd2ddbe 100644 --- a/main/xiaozhi-server/core/utils/wakeup_word.py +++ b/main/xiaozhi-server/core/utils/wakeup_word.py @@ -125,6 +125,8 @@ class WakeupWordsConfig: # 生成voice的哈希值 voice_hash = hashlib.md5(voice.encode()).hexdigest() file_path = os.path.join(self.assets_dir, f"{voice_hash}.wav") + # 统一使用正斜杠,避免跨平台路径问题 + file_path = file_path.replace("\\", "/") # 如果文件已存在,先删除 if os.path.exists(file_path):