From ca7553b6074bf0e8d1577006d0b23ee55ff43433 Mon Sep 17 00:00:00 2001 From: Harold Date: Mon, 15 Dec 2025 18:13:59 +0800 Subject: [PATCH 1/2] feat: turn detection --- main/xiaozhi-server/core/connection.py | 54 +++++++++ .../xiaozhi-server/core/providers/asr/base.py | 16 ++- .../core/providers/tts/fish_dual_stream.py | 37 ++++--- .../core/providers/turn_detection/__init__.py | 2 + .../core/providers/turn_detection/base.py | 73 ++++++++++++ .../core/providers/turn_detection/noop.py | 31 ++++++ .../core/providers/turn_detection/ten.py | 104 ++++++++++++++++++ .../core/utils/turn_detection.py | 27 +++++ main/xiaozhi-server/custom_config.yaml | 14 +++ 9 files changed, 343 insertions(+), 15 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/turn_detection/__init__.py create mode 100644 main/xiaozhi-server/core/providers/turn_detection/base.py create mode 100644 main/xiaozhi-server/core/providers/turn_detection/noop.py create mode 100644 main/xiaozhi-server/core/providers/turn_detection/ten.py create mode 100644 main/xiaozhi-server/core/utils/turn_detection.py diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index f4597c0a2..6b6d89e46 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -24,6 +24,7 @@ from core.utils.modules_initialize import ( initialize_tts, initialize_asr, ) +from core.utils import turn_detection as turn_detection_factory from core.handle.reportHandle import report from core.providers.tts.default import DefaultTTS from concurrent.futures import ThreadPoolExecutor @@ -114,6 +115,7 @@ class ConnectionHandler: self.vad: VADProviderBase = None self.asr = None self.tts = None + self.turn_detection = None # Turn Detection provider (optional) self._asr = _asr self._vad = _vad self.llm = _llm @@ -469,6 +471,9 @@ class ConnectionHandler: # 初始化声纹识别 self._initialize_voiceprint() + # Initialize Turn Detection (optional) + self._initialize_turn_detection() + # 打开语音识别通道 asyncio.run_coroutine_threadsafe( self.asr.open_audio_channels(self), self.loop @@ -712,6 +717,39 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"Failed to create VAD stream: {e}") self.vad_stream = None + def _initialize_turn_detection(self): + """Initialize Turn Detection provider (optional) + + If TurnDetection is configured as "noop" type, turn_detection will be set to None + to skip turn detection entirely. Otherwise, creates the configured provider. + """ + try: + selected_module = self.config.get("selected_module", {}) + turn_detection_module = selected_module.get("TurnDetection") + + if not turn_detection_module: + self.logger.bind(tag=TAG).debug("TurnDetection not configured, skipping") + self.turn_detection = None + return + + turn_detection_config = self.config.get("TurnDetection", {}).get(turn_detection_module, {}) + turn_detection_type = turn_detection_config.get("type", "noop") + + # Create the turn detection provider (noop implementation handles disabled case) + self.turn_detection = turn_detection_factory.create_instance( + turn_detection_type, + turn_detection_config + ) + self.logger.bind(tag=TAG).info( + f"TurnDetection initialized: {turn_detection_module} (type={turn_detection_type})" + ) + + except Exception as e: + self.logger.bind(tag=TAG).warning( + f"TurnDetection initialization failed: {e}, disabled" + ) + self.turn_detection = None + def _initialize_voiceprint(self): """为当前连接初始化声纹识别""" try: @@ -1406,6 +1444,22 @@ class ConnectionHandler: self.vad_stream = None except Exception as e: self.logger.bind(tag=TAG).error(f"Error closing VAD stream: {e}") + + if self._vad_event_task and not self._vad_event_task.done(): + self._vad_event_task.cancel() + try: + await self._vad_event_task + except asyncio.CancelledError: + pass + self._vad_event_task = None + + # Close Turn Detection provider (also clears its internal buffer) + if self.turn_detection: + try: + await self.turn_detection.close() + self.turn_detection = None + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error closing Turn Detection: {e}") # 取消超时任务 if self.timeout_task and not self.timeout_task.done(): diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 9f5e25791..2a7b14a5d 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -252,7 +252,21 @@ class ASRProviderBase(ABC): self.stop_ws_connection() if text_len > 0: - enhanced_text = self._build_enhanced_text(raw_text, speaker_name) + # Turn Detection: check if user finished speaking + if conn.turn_detection: + end_of_turn, full_text = await conn.turn_detection.check_end_of_turn(raw_text) + + if not end_of_turn: + # User hasn't finished, continue waiting for more speech + logger.bind(tag=TAG).info(f"User hasn't finished, continue waiting for more speech") + return + + # Use accumulated text from turn detection + enhanced_text = self._build_enhanced_text(full_text, speaker_name) + else: + # No Turn Detection: use single segment text + enhanced_text = self._build_enhanced_text(raw_text, speaker_name) + asr_report_time = int(time.time()) await startToChat(conn, enhanced_text) diff --git a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py index 06644a3ef..4cbb95f45 100644 --- a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py +++ b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py @@ -408,12 +408,7 @@ class TTSProvider(TTSProviderBase): await super().close() - def _cleanup_session_state(self, flush_opus: bool = True): - """Clean up session state after finish or abnormal exit - - Args: - flush_opus: Whether to flush remaining opus buffer (skip on abnormal exit) - """ + async def _cleanup_session_state(self, flush_opus: bool = True, skip_cancel_monitor_task: bool = False): if flush_opus: # Flush remaining opus buffer self.opus_encoder.encode_pcm_to_opus_stream( @@ -435,6 +430,24 @@ class TTSProvider(TTSProviderBase): self._process_before_stop_play_files() self._first_sent = False + if self.ws: + try: + await self.ws.close() + except websockets.ConnectionClosed: + logger.bind(tag=TAG).debug("WebSocket connection has already been closed") + finally: + self.ws = None + + if self._monitor_task and not self._monitor_task.done(): + try: + await self._monitor_task + except asyncio.CancelledError: + pass + except Exception as e: + logger.bind(tag=TAG).warning(f"Error canceling monitor task: {e}") + finally: + self._monitor_task = None + async def _monitor_ws_response(self): """Monitor WebSocket responses - long running task (MessagePack serialization)""" try: @@ -482,14 +495,12 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug(f"TTS session finished") # Normal finish: flush opus and clean up state - self._cleanup_session_state(flush_opus=True) + await self._cleanup_session_state(flush_opus=True, skip_cancel_monitor_task=True) except Exception as e: if isinstance(e, websockets.ConnectionClosed): logger.bind(tag=TAG).warning("WebSocket connection closed unexpectedly") - logger.bind(tag=TAG).error(f"Error in monitor task: {e}") - # Abnormal exit: clean up state without flushing opus - if self._session_active: - self._cleanup_session_state(flush_opus=False) + else: + logger.bind(tag=TAG).error(f"Error in monitor task: {e}") break # Clean up WebSocket on exit (regardless of exit reason) @@ -591,9 +602,7 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).error(f"Failed to abort session: {e}") finally: # Clean up state immediately (don't wait for monitor task) - self._session_active = False - self._session_text_buffer = [] - self._first_sent = False + await self._cleanup_session_state(flush_opus=True) async def text_to_speak(self, text, output_file): diff --git a/main/xiaozhi-server/core/providers/turn_detection/__init__.py b/main/xiaozhi-server/core/providers/turn_detection/__init__.py new file mode 100644 index 000000000..37f3ef594 --- /dev/null +++ b/main/xiaozhi-server/core/providers/turn_detection/__init__.py @@ -0,0 +1,2 @@ +# Turn Detection Provider Module + diff --git a/main/xiaozhi-server/core/providers/turn_detection/base.py b/main/xiaozhi-server/core/providers/turn_detection/base.py new file mode 100644 index 000000000..7f958d3b6 --- /dev/null +++ b/main/xiaozhi-server/core/providers/turn_detection/base.py @@ -0,0 +1,73 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass +from enum import Enum +import time +from typing import List, Optional, Tuple + +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +class TurnDetectionState(Enum): + FINISHED = "finished" + WAITING = "wait" + UNFINISHED = "unfinished" + + +@dataclass +class TurnDetectionResult: + """Result from Turn Detection service""" + text: str # Full accumulated text + result: TurnDetectionState # Detection result + + +class TurnDetectionProviderBase(ABC): + """Base class for Turn Detection providers + + Turn Detection determines whether the user has finished speaking + and it's time for the system to respond. + + Manages text buffer internally - subclasses can override buffer behavior. + """ + + def __init__(self, config: dict): + self._text_buffer: List[str] = [] + self._buffer_start_time: float = 0.0 + self._buffer_timeout: float = float(config.get("buffer_timeout", 10.0)) + + def _append_text(self, text: str) -> str: + if not self._text_buffer: + self._buffer_start_time = time.time() + self._text_buffer.append(text) + return " ".join(self._text_buffer) + + def _clear_buffer(self) -> None: + """Clear the text buffer""" + self._text_buffer.clear() + self._buffer_start_time = 0.0 + + def _is_buffer_timeout(self) -> bool: + """Check if buffer has timed out (to avoid infinite accumulation)""" + if not self._text_buffer: + return False + return (time.time() - self._buffer_start_time) > self._buffer_timeout + + @abstractmethod + async def check_end_of_turn(self, text: str) -> Tuple[bool, str]: + """Check if the user has finished their turn + + Args: + text: New ASR text segment + + Returns: + Tuple of (end_of_turn: bool, full_text: str) + - end_of_turn: True if user finished speaking, False to continue buffering + - full_text: Accumulated text from buffer + """ + ... + + async def close(self) -> None: + """Clean up resources - clears buffer""" + self._clear_buffer() diff --git a/main/xiaozhi-server/core/providers/turn_detection/noop.py b/main/xiaozhi-server/core/providers/turn_detection/noop.py new file mode 100644 index 000000000..708415e4b --- /dev/null +++ b/main/xiaozhi-server/core/providers/turn_detection/noop.py @@ -0,0 +1,31 @@ +from typing import Tuple + +from config.logger import setup_logging +from .base import TurnDetectionProviderBase + +TAG = __name__ +logger = setup_logging() + + +class TurnDetectionProvider(TurnDetectionProviderBase): + """No-op Turn Detection provider (disabled mode) + + Always returns end_of_turn=True immediately without any network calls. + Use this when Turn Detection is disabled. + """ + + def __init__(self, config: dict): + super().__init__(config) + logger.bind(tag=TAG).info("NoopTurnDetection initialized (Turn Detection disabled)") + + async def check_end_of_turn(self, text: str) -> Tuple[bool, str]: + """Always return end_of_turn=True immediately + + Args: + text: The ASR text + + Returns: + Tuple of (True, text) - always signals turn finished + """ + # No buffering needed for noop - just return the text as-is + return True, text diff --git a/main/xiaozhi-server/core/providers/turn_detection/ten.py b/main/xiaozhi-server/core/providers/turn_detection/ten.py new file mode 100644 index 000000000..dcc22a7f4 --- /dev/null +++ b/main/xiaozhi-server/core/providers/turn_detection/ten.py @@ -0,0 +1,104 @@ +from typing import Tuple +import httpx + +from config.logger import setup_logging +from .base import TurnDetectionProviderBase, TurnDetectionState + +TAG = __name__ +logger = setup_logging() + + +class TurnDetectionProvider(TurnDetectionProviderBase): + """HTTP-based Turn Detection provider using httpx async client + + Calls an external Turn Detection service via HTTP POST. + Gracefully degrades to end_of_turn=True on timeout or errors. + """ + + def __init__(self, config: dict): + super().__init__(config) + + host = config.get("host", "127.0.0.1") + port = config.get("port", 8080) + endpoint = config.get("endpoint", "/") + + self.url = f"http://{host}:{port}{endpoint}" + self.timeout = float(config.get("timeout", 0.5)) + self._client = httpx.AsyncClient(timeout=self.timeout) + + logger.bind(tag=TAG).info( + f"TenTurnDetection initialized: url={self.url}, timeout={self.timeout}s" + ) + + async def check_end_of_turn(self, text: str) -> Tuple[bool, str]: + """Check if the user has finished their turn via HTTP call + + Args: + text: New ASR text segment + + Returns: + Tuple of (end_of_turn: bool, full_text: str) + On timeout/error, returns (True, full_text) to avoid blocking + """ + # Append to buffer + full_text = self._append_text(text) + + # Check buffer timeout + if self._is_buffer_timeout(): + logger.bind(tag=TAG).warning( + f"Turn buffer timeout, forcing send: '{full_text[:50]}...'" + ) + self._clear_buffer() + return True, full_text + + # Call Turn Detection service + try: + response = await self._client.post( + self.url, + json={"text": full_text} + ) + response.raise_for_status() + data = response.json() + logger.bind(tag=TAG).info(f"TD raw response: {data}") + # Parse result string + result_str = data.get("result", "finished") + + if result_str == TurnDetectionState.FINISHED.value: + logger.bind(tag=TAG).info( + f"Turn finished, buffering: '{full_text[:50]}'" + ) + self._clear_buffer() + return True, full_text + + # UNFINISHED or WAITING: continue buffering + logger.bind(tag=TAG).info( + f"Turn unfinished, buffering: '{full_text[:50]}'" + ) + return False, full_text + + except httpx.TimeoutException: + logger.bind(tag=TAG).warning( + f"TurnDetection timeout ({self.timeout}s), defaulting to finished" + ) + self._clear_buffer() + return True, full_text + + except httpx.HTTPStatusError as e: + logger.bind(tag=TAG).error( + f"TurnDetection HTTP error: {e.response.status_code}, defaulting to finished" + ) + self._clear_buffer() + return True, full_text + + except Exception as e: + logger.bind(tag=TAG).error( + f"TurnDetection error: {e}, defaulting to finished" + ) + self._clear_buffer() + return True, full_text + + async def close(self) -> None: + """Close the httpx client and clear buffer""" + await super().close() + await self._client.aclose() + logger.bind(tag=TAG).debug("TenTurnDetection client closed") diff --git a/main/xiaozhi-server/core/utils/turn_detection.py b/main/xiaozhi-server/core/utils/turn_detection.py new file mode 100644 index 000000000..73ddee63f --- /dev/null +++ b/main/xiaozhi-server/core/utils/turn_detection.py @@ -0,0 +1,27 @@ +import importlib +import os +import sys +from core.providers.turn_detection.base import TurnDetectionProviderBase +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +def create_instance(class_name: str, *args, **kwargs) -> TurnDetectionProviderBase: + """Factory method to create Turn Detection provider instance + + Args: + class_name: The type name from config (e.g., "http", "noop") + *args, **kwargs: Arguments to pass to the provider constructor + + Returns: + TurnDetectionProvider instance + """ + if os.path.exists(os.path.join("core", "providers", "turn_detection", f"{class_name}.py")): + lib_name = f"core.providers.turn_detection.{class_name}" + if lib_name not in sys.modules: + sys.modules[lib_name] = importlib.import_module(lib_name) + return sys.modules[lib_name].TurnDetectionProvider(*args, **kwargs) + + raise ValueError(f"Unsupported Turn Detection type: {class_name}") diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index 4079d177a..192caeaee 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -492,6 +492,19 @@ VAD: min_silence_duration_ms: 400 # silence detection duration (ms) frame_window_threshold: 3 # sliding window threshold +# Turn Detection: Determines if user has finished speaking +# Use NoopTurnDetection to disable, HTTPTurnDetection to enable +TurnDetection: + NoopTurnDetection: + type: noop + TenTurnDetection: + type: ten + host: 115.190.161.149 + port: 8002 + timeout: 0.5 # HTTP request timeout (seconds) + endpoint: /turn-detect # API endpoint path + buffer_timeout: 10.0 # Max time to accumulate text (seconds) + LLM: # 所有openai类型均可以修改超参,以AliLLM为例 # 当前支持的type为openai、dify、ollama,可自行适配 @@ -1104,6 +1117,7 @@ TTS: # =============================================================================== selected_module: VAD: SileroVAD + TurnDetection: NoopTurnDetection # Set to TenTurnDetection to enable ASR: GroqASR # ASR: ByteplusStreamASR # LLM: GroqLLM From 91d33083da06ecf759c77abc0a73d9132273c137 Mon Sep 17 00:00:00 2001 From: Harold Date: Mon, 15 Dec 2025 18:16:45 +0800 Subject: [PATCH 2/2] feat: skip cancel monitor task --- .../core/providers/tts/fish_dual_stream.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py index 4cbb95f45..2fe0642a4 100644 --- a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py +++ b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py @@ -438,15 +438,16 @@ class TTSProvider(TTSProviderBase): finally: self.ws = None - if self._monitor_task and not self._monitor_task.done(): - try: - await self._monitor_task - except asyncio.CancelledError: - pass - except Exception as e: - logger.bind(tag=TAG).warning(f"Error canceling monitor task: {e}") - finally: - self._monitor_task = None + if not skip_cancel_monitor_task: + if self._monitor_task and not self._monitor_task.done(): + try: + await self._monitor_task + except asyncio.CancelledError: + pass + except Exception as e: + logger.bind(tag=TAG).warning(f"Error canceling monitor task: {e}") + finally: + self._monitor_task = None async def _monitor_ws_response(self): """Monitor WebSocket responses - long running task (MessagePack serialization)"""