feat: optmize latency

This commit is contained in:
Harold 2025-12-03 18:04:25 +08:00
parent efcdd1eb74
commit 4ca05c5f2e
7 changed files with 323 additions and 125 deletions

View file

@ -950,11 +950,14 @@ class ConnectionHandler:
try:
# use dialogue with memory (use text for memory query)
memory_str = None
if self.memory is not None:
future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query_text), self.loop
)
memory_str = future.result()
# if self.memory is not None:
# memory_start_time = time.time() * 1000
# future = asyncio.run_coroutine_threadsafe(
# self.memory.query_memory(query_text), self.loop
# )
# memory_str = future.result()
# memory_duration = (time.time() * 1000 - memory_start_time) / 1000
# self.logger.bind(tag=TAG).info(f"[Latency] Memory查询完成, 耗时: {memory_duration:.3f}s")
# 获取对话历史
dialogue_history = self.dialogue.get_llm_dialogue_with_memory(

View file

@ -488,28 +488,31 @@ async def handleAudioMessage(conn, audio):
await _trigger_pseudo_streaming_prefetch(conn, audio, have_voice)
# 只有 TTS 正在播放且非手动监听模式时才检测打断
if conn.client_is_speaking and conn.client_listen_mode != "manual":
# 初始化打断检测状态
_init_interrupt_state(conn)
# if conn.client_is_speaking and conn.client_listen_mode != "manual":
# # 初始化打断检测状态
# _init_interrupt_state(conn)
if have_voice:
# 检测到语音,增加连续语音帧计数
conn._continuous_voice_count += 1
# if have_voice:
# # 检测到语音,增加连续语音帧计数
# conn._continuous_voice_count += 1
# 当连续语音帧达到阈值时,触发打断
# 这样可以过滤短暂噪音、回声、咳嗽等误触发
if conn._continuous_voice_count >= CONTINUOUS_VOICE_THRESHOLD:
logger.bind(tag=TAG).info(
f"持续语音检测触发打断: 连续 {conn._continuous_voice_count} 帧 "
f"(阈值 {CONTINUOUS_VOICE_THRESHOLD} 帧, 约 {CONTINUOUS_VOICE_THRESHOLD * 60}ms)"
)
# 重置计数器
conn._continuous_voice_count = 0
# 触发打断
await handleAbortMessage(conn)
else:
# 没有检测到语音,重置连续语音帧计数
conn._continuous_voice_count = 0
# # 当连续语音帧达到阈值时,触发打断
# # 这样可以过滤短暂噪音、回声、咳嗽等误触发
# if conn._continuous_voice_count >= CONTINUOUS_VOICE_THRESHOLD:
# logger.bind(tag=TAG).info(
# f"持续语音检测触发打断: 连续 {conn._continuous_voice_count} 帧 "
# f"(阈值 {CONTINUOUS_VOICE_THRESHOLD} 帧, 约 {CONTINUOUS_VOICE_THRESHOLD * 60}ms)"
# )
# # 重置计数器
# conn._continuous_voice_count = 0
# # 触发打断
# await handleAbortMessage(conn)
# else:
# # 没有检测到语音,重置连续语音帧计数
# conn._continuous_voice_count = 0
if have_voice:
if conn.client_is_speaking and conn.client_listen_mode != "manual":
await handleAbortMessage(conn)
# 设备长时间空闲检测,用于say goodbye
await no_voice_close_connect(conn, have_voice)

View file

@ -13,6 +13,7 @@ from config.logger import setup_logging
from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase
from types import SimpleNamespace
import time
TAG = __name__

View file

@ -54,6 +54,8 @@ class TTSProviderBase(ABC):
";",
";",
":",
".",
"!"
)
self.first_sentence_punctuations = (
",", # 启用逗号,让首段更快播放
@ -407,8 +409,8 @@ class TTSProviderBase(ABC):
segment_text_raw = current_text[: last_punct_pos + 1]
# 首句长度检查:如果太短,等待更多文本
if self.is_first_sentence and len(segment_text_raw) < MIN_FIRST_SEGMENT_CHARS:
return None # 继续等待更多文本
# if self.is_first_sentence and len(segment_text_raw) < MIN_FIRST_SEGMENT_CHARS:
# return None # 继续等待更多文本
segment_text = textUtils.get_string_no_punctuation_or_emoji(
segment_text_raw

View file

@ -95,38 +95,58 @@ class TTSProvider(TTSProviderBase):
self._ws_connected = False
raise
async def _ensure_connection(self):
"""Ensure WebSocket connection is established"""
async def _ensure_connection(self, max_retries: int = 2):
"""Ensure WebSocket connection is established with retry logic"""
if self.ws and self._ws_connected:
logger.bind(tag=TAG).debug("Using existing WebSocket connection")
return
logger.bind(tag=TAG).info("Establishing new WebSocket connection...")
headers = {
"Authorization": f"Bearer {self.api_key}",
"model": self.model,
}
self.ws = await websockets.connect(
FISH_WS_URL,
additional_headers=headers,
max_size=10 * 1024 * 1024, # 10MB max message size
)
self._ws_connected = True
last_error = None
for attempt in range(max_retries + 1):
try:
logger.bind(tag=TAG).info(f"Establishing WebSocket connection (attempt {attempt + 1}/{max_retries + 1})...")
# Start response monitor task
if self._monitor_task is None or self._monitor_task.done():
logger.bind(tag=TAG).info("Starting WebSocket monitor task...")
self._monitor_task = asyncio.create_task(self._monitor_ws_response())
self.ws = await websockets.connect(
FISH_WS_URL,
additional_headers=headers,
max_size=10 * 1024 * 1024, # 10MB max message size
open_timeout=10, # 10s connection timeout
close_timeout=5, # 5s close timeout
)
self._ws_connected = True
# Start response monitor task
if self._monitor_task is None or self._monitor_task.done():
logger.bind(tag=TAG).info("Starting WebSocket monitor task...")
self._monitor_task = asyncio.create_task(self._monitor_ws_response())
return # Success
except Exception as e:
last_error = e
logger.bind(tag=TAG).warning(f"WebSocket connection attempt {attempt + 1} failed: {e}")
if attempt < max_retries:
await asyncio.sleep(0.5) # Brief delay before retry
# All retries failed
raise last_error
def tts_text_priority_thread(self):
"""
Override: dual stream TTS text processing thread
Manages session lifecycle based on FIRST/LAST signals,
similar to Huoshan's implementation.
Manages session lifecycle based on FIRST/LAST signals.
Key insights from Fish Audio WebSocket API:
1. stop_event triggers WebSocket close, so only use it for interruptions
2. For normal LAST, send flush event to force remaining text generation
3. Fish has no multi-context management, interruption requires reconnection
"""
while not self.conn.stop_event.is_set():
try:
@ -141,16 +161,17 @@ class TTSProvider(TTSProviderBase):
elif self.conn.client_abort:
# ========== Interruption ==========
logger.bind(tag=TAG).info("Received interruption, canceling session")
# Only send stop event on interruption (this will close the connection)
logger.bind(tag=TAG).info("Received interruption, sending stop event")
try:
future = asyncio.run_coroutine_threadsafe(
self._finish_session(self.conn.sentence_id),
self._abort_session(),
self.conn.loop
)
future.result()
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to cancel session: {e}")
continue
logger.bind(tag=TAG).error(f"Failed to abort session: {e}")
continue
# when user doesn't trigger interruption, start new TTS session
if message.sentence_type == SentenceType.FIRST:
@ -168,7 +189,7 @@ class TTSProvider(TTSProviderBase):
elif ContentType.TEXT == message.content_type:
# ========== Text content ==========
if message.content_detail:
# 累积文本用于上报(支持 voice_opening/closing 和 LLM 生成内容)
# Accumulate text for reporting (supports voice_opening/closing and LLM content)
self._session_text_buffer.append(message.content_detail)
try:
@ -195,15 +216,17 @@ class TTSProvider(TTSProviderBase):
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
if message.sentence_type == SentenceType.LAST:
# ========== Dialogue round ends ==========
# ========== Dialogue round ends (normal) ==========
# DO NOT send stop event here! Just send flush to force remaining text.
# The finish event from Fish will trigger LAST in audio queue.
try:
future = asyncio.run_coroutine_threadsafe(
self._finish_session(self.conn.sentence_id),
self._flush_session(),
loop=self.conn.loop,
)
future.result()
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to finish session: {e}")
logger.bind(tag=TAG).error(f"Failed to flush session: {e}")
continue
except queue.Empty:
@ -213,7 +236,6 @@ class TTSProvider(TTSProviderBase):
f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, "
f"stack: {traceback.format_exc()}"
)
continue
async def close(self):
"""Clean up WebSocket resources"""
@ -271,6 +293,7 @@ class TTSProvider(TTSProviderBase):
)
elif event_type == "finish":
logger.bind(tag=TAG).info(f"TTS session finished")
# Session completed
reason = response.get("reason", "unknown")
if reason == "error":
@ -334,18 +357,6 @@ class TTSProvider(TTSProviderBase):
"""
Start a new TTS session
"""
# Wait for previous session to finish
# Avoid the latency of the finish event of the previous session
if self._session_active:
for _ in range(3):
if not self._session_active:
break
logger.bind(tag=TAG).debug("Waiting for previous session to finish...")
await asyncio.sleep(0.1)
else:
logger.bind(tag=TAG).debug("Previous session timeout, clearing connection state...")
await self.close()
# Reset state for new session
self.opus_encoder.reset_state()
self._session_text_buffer = []
@ -376,28 +387,52 @@ class TTSProvider(TTSProviderBase):
await self._send_event(start_event)
self._session_active = True
logger.bind(tag=TAG).info(f"TTS session started, sentence_id: {self.conn.sentence_id}")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to start session: {e}")
raise
async def _finish_session(self, session_id: str = None):
async def _flush_session(self):
"""
Finish current TTS session gracefully
Flush current TTS session - force generation of remaining text
Send flush event to force Fish Audio to generate audio for any buffered text.
This does NOT close the connection - the finish event from Fish will do that.
"""
logger.bind(tag=TAG).info(f"Finishing TTS session: {session_id}")
logger.bind(tag=TAG).debug("Flushing TTS session...")
try:
if self.ws and self._session_active:
# Send flush event to force remaining text generation
flush_event = {"event": "flush"}
await self._send_event(flush_event)
logger.bind(tag=TAG).debug("TTS flush event sent")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to flush session: {e}")
async def _abort_session(self):
"""
Abort current TTS session due to interruption
Send stop event which will close the WebSocket connection.
This is only used when user interrupts the conversation.
"""
logger.bind(tag=TAG).info("Aborting TTS session due to interruption...")
try:
if self.ws and self._session_active:
stop_event = {"event": "stop"}
await self._send_event(stop_event)
logger.bind(tag=TAG).info("TTS session stop sent")
logger.bind(tag=TAG).info("TTS session stop sent (abort)")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to finish session: {e}")
logger.bind(tag=TAG).error(f"Failed to abort session: {e}")
finally:
# Clean up state
self._session_active = False
self.conn.sentence_id = None
self._session_text_buffer = []
self._first_sent = False
# Connection will be closed by Fish Audio after stop event
async def text_to_speak(self, text, output_file):
"""

View file

@ -1,46 +1,31 @@
import os
import queue
import asyncio
import traceback
import time
from pathlib import Path
from core.utils.util import parse_string_to_list
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
from core.utils.tts import MarkdownCleaner
from core.providers.tts.base import TTSProviderBase
from core.utils import opus_encoder_utils, textUtils
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
from fishaudio import FishAudio, TTSConfig
TAG = __name__
logger = setup_logging()
def audio_to_bytes(file_path):
if not file_path or not Path(file_path).exists():
return None
with open(file_path, "rb") as wav_file:
wav = wav_file.read()
return wav
def read_ref_text(ref_text):
path = Path(ref_text)
if path.exists() and path.is_file():
with path.open("r", encoding="utf-8") as file:
return file.read()
return ref_text
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# Mark as streaming interface
self.interface_type = InterfaceType.SINGLE_STREAM
self.model = config.get("model", "s1")
if config.get("reference_id"):
self.reference_id = config.get("reference_id")
else:
self.reference_id = None
self.reference_audio = parse_string_to_list(
config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio")
)
self.reference_text = parse_string_to_list(
config.get('ref_text')if config.get('ref_text') else config.get("reference_text")
)
self.reference_id = config.get("reference_id")
self.format = config.get("response_format", "pcm")
self.sample_rate = config.get("sample_rate", 16000)
self.audio_file_type = config.get("response_format", "pcm")
@ -55,7 +40,7 @@ class TTSProvider(TTSProviderBase):
"yes",
)
# 处理空字符串的情况
# Handle empty string cases
channels = config.get("channels", "1")
rate = config.get("rate", "44100")
max_new_tokens = config.get("max_new_tokens", "1024")
@ -66,7 +51,7 @@ class TTSProvider(TTSProviderBase):
self.max_new_tokens = int(max_new_tokens) if max_new_tokens else 1024
self.chunk_length = int(chunk_length) if chunk_length else 200
# 处理空字符串的情况
# Handle empty string cases
top_p = config.get("top_p", "0.7")
temperature = config.get("temperature", "0.7")
repetition_penalty = config.get("repetition_penalty", "1.2")
@ -85,10 +70,182 @@ class TTSProvider(TTSProviderBase):
self.use_memory_cache = config.get("use_memory_cache", "on")
self.seed = int(config.get("seed")) if config.get("seed") else None
async def text_to_speak(self, text, output_file):
logger.bind(tag=TAG).info(f"fish speech synthesize text: {text}")
# Initialize Opus encoder (sample_rate should match FishSpeech output)
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
)
audio_stream = self._client.tts.stream(
# PCM buffer for accumulating data before encoding
self.pcm_buffer = bytearray()
def tts_text_priority_thread(self):
"""Streaming text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
if message.sentence_type == SentenceType.FIRST:
self.conn.client_abort = False
if self.conn.client_abort:
logger.bind(tag=TAG).info("Received abort signal, stopping TTS text processing")
continue
if message.sentence_type == SentenceType.FIRST:
# Initialize parameters
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.is_first_sentence = True
self.tts_audio_first_sentence = True
self._first_chunk_logged = False
self.before_stop_play_files.clear()
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
if segment_text:
self.to_tts_single_stream(segment_text)
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"Adding audio file to play list: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
self._process_audio_file_stream(
message.content_file,
callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail)
)
if message.sentence_type == SentenceType.LAST:
# Process remaining text
self._process_remaining_text_stream(True)
self._first_chunk_logged = False
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
def _process_remaining_text_stream(self, is_last=False):
"""Process remaining text and generate speech
Returns:
bool: Whether text was successfully processed
"""
full_text = "".join(self.tts_text_buff)
remaining_text = full_text[self.processed_chars:]
if remaining_text:
segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
if segment_text:
self.to_tts_single_stream(segment_text, is_last)
self.processed_chars += len(full_text)
else:
self._process_before_stop_play_files()
else:
self._process_before_stop_play_files()
def to_tts_single_stream(self, text, is_last=False):
try:
max_repeat_time = 5
text = MarkdownCleaner.clean_markdown(text)
try:
asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
logger.bind(tag=TAG).warning(
f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"TTS generation success: {text}, retries: {5 - max_repeat_time}"
)
else:
logger.bind(tag=TAG).error(
f"TTS generation failed: {text}, please check network or service"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS: {e}")
finally:
return None
async def text_to_speak(self, text, is_last):
"""Stream TTS audio processing - encode and send each chunk immediately"""
logger.bind(tag=TAG).info(f"FishSpeech streaming synthesize: {text}")
start_time = time.time() * 1000
# Calculate bytes per frame for Opus encoding
frame_bytes = int(
self.opus_encoder.sample_rate
* self.opus_encoder.channels
* self.opus_encoder.frame_size_ms
/ 1000
* 2 # 16-bit = 2 bytes per sample
)
try:
# Get audio stream from FishSpeech
audio_stream = self._client.tts.stream(
text=text,
reference_id=self.reference_id,
model=self.model,
config=TTSConfig(
format=self.format,
sample_rate=self.sample_rate,
normalize=self.normalize,
latency="balanced",
),
)
self.pcm_buffer.clear()
# Notify that a new sentence is starting
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
first_chunk_logged = False
# Process audio stream - encode and send each chunk immediately
for chunk in audio_stream:
# Log first chunk from TTS API
if not first_chunk_logged:
first_chunk_logged = True
first_chunk_time = time.time() * 1000
self.conn.tts_first_chunk_time = first_chunk_time
api_latency = (first_chunk_time - start_time) / 1000
logger.bind(tag=TAG).info(f"[Latency] TTS API首个chunk, 耗时: {api_latency:.3f}s")
# Add chunk to PCM buffer
self.pcm_buffer.extend(chunk)
# Encode and send complete frames immediately
while len(self.pcm_buffer) >= frame_bytes:
frame = bytes(self.pcm_buffer[:frame_bytes])
del self.pcm_buffer[:frame_bytes]
self.opus_encoder.encode_pcm_to_opus_stream(
frame, end_of_stream=False, callback=self.handle_opus
)
# Flush remaining data that's less than one frame
if self.pcm_buffer:
self.opus_encoder.encode_pcm_to_opus_stream(
bytes(self.pcm_buffer),
end_of_stream=True,
callback=self.handle_opus,
)
self.pcm_buffer.clear()
# If this is the last segment, process any pending files and signal completion
if is_last:
self._process_before_stop_play_files()
except Exception as e:
logger.bind(tag=TAG).error(f"FishSpeech streaming error: {e}")
self.tts_audio_queue.put((SentenceType.LAST, [], None))
def to_tts(self, text):
"""Non-streaming TTS for compatibility - falls back to accumulating all chunks"""
logger.bind(tag=TAG).info(f"FishSpeech synthesize text: {text}")
start_time = time.time()
text = MarkdownCleaner.clean_markdown(text)
audio_bytes = self._client.tts.convert(
text=text,
reference_id=self.reference_id,
model=self.model,
@ -97,17 +254,14 @@ class TTSProvider(TTSProviderBase):
sample_rate=self.sample_rate,
normalize=self.normalize,
latency="balanced",
),
)
)
audio_bytes = b''
logger.bind(tag=TAG).info(f"TTS non-streaming duration: {time.time() - start_time} seconds")
return audio_bytes
for chunk in audio_stream:
if chunk:
audio_bytes += chunk
if output_file:
with open(output_file, "wb") as audio_file:
audio_file.write(audio_bytes)
else:
return audio_bytes
async def close(self):
"""Resource cleanup"""
await super().close()
if hasattr(self, "opus_encoder"):
self.opus_encoder.close()

View file

@ -68,8 +68,8 @@ log:
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
delete_audio: true
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
close_connection_no_voice_time: 120
# 没有语音输入多久后断开连接(秒),默认15分钟,即900秒
close_connection_no_voice_time: 900
# TTS请求超时时间(秒)
tts_timeout: 10
# 开启唤醒词加速
@ -535,12 +535,12 @@ LLM:
api_key: 你的chat-glm web key
GroqLLM:
type: openai
model_name: openai/gpt-oss-20b
model_name: meta-llama/llama-4-scout-17b-16e-instruct
base_url: https://api.groq.com/openai/v1
api_key: your groq api key
api_key: ${GROQ_API_KEY}
OpenaiLLM:
type: openai
model_name: gpt-4o
model_name: gpt-4o-mini
base_url: https://api.openai.com/v1
api_key: ${OPENAI_API_KEY}
OllamaLLM:
@ -1084,10 +1084,10 @@ TTS:
selected_module:
VAD: SileroVAD
ASR: GroqASR
LLM: OpenaiLLM
LLM: GroqLLM
VLLM: ChatGLMVLLM
# TTS: FishDualStreamTTS
TTS: FishDualStreamTTS
# TODO: temporarily, fish speech doesn't reuse the wesocket connection, need to discuss further.
TTS: FishSpeech
# TTS: FishSpeech
Memory: memu
Intent: function_call