feat: turn detection

This commit is contained in:
Harold 2025-12-15 18:13:59 +08:00
parent c658b2ba12
commit ca7553b607
9 changed files with 343 additions and 15 deletions

View file

@ -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:
@ -1407,6 +1445,22 @@ class ConnectionHandler:
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():
self.timeout_task.cancel()

View file

@ -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)

View file

@ -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):

View file

@ -0,0 +1,2 @@
# Turn Detection Provider Module

View file

@ -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()

View file

@ -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

View file

@ -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")

View file

@ -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}")

View file

@ -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