"""本地语音播报(仅本地 Windows 模式使用,容器内自动禁用)。 原来 speak() 是同步调用:IndexTTS2 首次加载模型要 1-2 分钟,合成每次几秒, 直接卡在轮询主循环里,导致监控间隔完全失真。这里改为后台线程 + 队列。 服务器(Linux/容器)没有声卡也不装 torch,所以此模块在非 Windows 上直接降级为 no-op。 """ from __future__ import annotations import logging import queue import sys import threading from typing import Optional log = logging.getLogger("fengxiang.tts") class Speaker: def __init__(self, voice_prompt: str = "", enabled: bool = True): self.enabled = bool(enabled) and sys.platform == "win32" self.voice_prompt = voice_prompt or None self._queue: "queue.Queue[Optional[str]]" = queue.Queue(maxsize=20) self._thread: Optional[threading.Thread] = None self._impl = None if enabled and not self.enabled: log.info("当前平台 %s 不支持本地播报,已自动禁用 TTS", sys.platform) def start(self) -> None: if not self.enabled or self._thread: return self._thread = threading.Thread(target=self._worker, name="tts", daemon=True) self._thread.start() def say(self, text: str) -> None: """非阻塞投递,队列满则丢弃并告警(绝不阻塞监控)。""" if not self.enabled: return try: self._queue.put_nowait(text) except queue.Full: log.warning("TTS 队列已满,丢弃本次播报") def _worker(self) -> None: while True: text = self._queue.get() if text is None: return try: if self._impl is None: from local_tts import speak as local_speak # 延迟导入,避免无依赖时启动失败 self._impl = local_speak self._impl(text, voice_prompt=self.voice_prompt) log.info("语音播报完成: %s", text) except Exception as exc: # noqa: BLE001 log.error("语音播报失败: %s", exc) def stop(self) -> None: if not self.enabled: return try: self._queue.put_nowait(None) except queue.Full: pass