From 4dd8bb583ed5ef05b2f08edc74095a10fd8491b6 Mon Sep 17 00:00:00 2001 From: Harold Date: Tue, 2 Dec 2025 01:04:44 +0800 Subject: [PATCH] feat: fish dual stream --- main/xiaozhi-server/core/connection.py | 17 + .../textHandler/attachmentMessageHandler.py | 10 +- .../core/providers/tts/fish_dual_stream.py | 427 +++++++++++++ .../core/providers/tts/fishspeech.py | 85 +-- main/xiaozhi-server/custom_config.yaml | 16 + main/xiaozhi-server/requirements.txt | 2 +- .../test/tts_latency/.gitignore | 1 + .../test/tts_latency/test_fish_latency.py | 602 ++++++++++++++++++ 8 files changed, 1085 insertions(+), 75 deletions(-) create mode 100644 main/xiaozhi-server/core/providers/tts/fish_dual_stream.py create mode 100644 main/xiaozhi-server/test/tts_latency/.gitignore create mode 100644 main/xiaozhi-server/test/tts_latency/test_fish_latency.py diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 8b16130e2..0d0f6f0f9 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -448,6 +448,16 @@ class ConnectionHandler: if self._voice_opening: self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}") + + opening_sentence_id = str(uuid.uuid4().hex) + + # FIRST: Start session + self.tts.tts_text_queue.put(TTSMessageDTO( + sentence_id=opening_sentence_id, + sentence_type=SentenceType.FIRST, + content_type=ContentType.ACTION, + )) + self.tts.tts_text_queue.put(TTSMessageDTO( sentence_id=str(uuid.uuid4().hex), sentence_type=SentenceType.MIDDLE, @@ -456,6 +466,12 @@ class ConnectionHandler: ) ) + self.tts.tts_text_queue.put(TTSMessageDTO( + sentence_id=opening_sentence_id, + sentence_type=SentenceType.LAST, + content_type=ContentType.ACTION, + )) + except Exception as e: self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") @@ -829,6 +845,7 @@ class ConnectionHandler: # self.logger.bind(tag=TAG).info(f"private_config: {private_config}") # self.logger.bind(tag=TAG).info(f"self.config: {self.config}") self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"] + self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = private_config["voice_id"] self._instruction = private_config["instruction"] self._voice_opening = private_config["voice_opening"] self._voice_closing = private_config["voice_closing"] diff --git a/main/xiaozhi-server/core/handle/textHandler/attachmentMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/attachmentMessageHandler.py index 1b170c88d..6a17cbfc2 100644 --- a/main/xiaozhi-server/core/handle/textHandler/attachmentMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/attachmentMessageHandler.py @@ -38,16 +38,16 @@ class AttachmentTextMessageHandler(TextMessageHandler): if attachment_type == "image": content = [ { - "type": "image", - "image_url": {"url": url} + "type": "input_image", + "image_url": url } ] - else: + elif attachment_type == "file": # File type: store as custom format, LLM layer needs special handling content = [ { - "type": "file", - "file_url": {"url": url} + "type": "input_file", + "file_url": url } ] diff --git a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py new file mode 100644 index 000000000..8e17fb5c9 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py @@ -0,0 +1,427 @@ +""" +Fish Audio Dual Stream TTS Implementation + +Based on native WebSocket API (wss://api.fish.audio/v1/tts/live), supporting: +1. Pre-connection optimization: establish WebSocket connection before LLM output +2. Session lifecycle management: start/stop events for each dialogue round +3. FlushEvent + Chunk strategy: force audio generation at punctuation marks +4. Lightweight interruption: send stop event without closing connection + +Reference: https://docs.fish.audio/api-reference/endpoint/websocket/tts-live +""" + +import os +import uuid +import queue +import asyncio +import traceback +import ormsgpack +import websockets + +from core.utils.tts import MarkdownCleaner +from core.utils import opus_encoder_utils +from core.utils.util import check_model_key +from core.providers.tts.base import TTSProviderBase +from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +# Fish Audio WebSocket API endpoint +FISH_WS_URL = "wss://api.fish.audio/v1/tts/live" + + +class TTSProvider(TTSProviderBase): + """Fish Audio Dual Stream TTS Implementation using native WebSocket API""" + + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + + # Mark as dual stream interface + self.interface_type = InterfaceType.DUAL_STREAM + + # Fish Audio configuration + self.api_key = config.get("api_key") + if not self.api_key: + raise ValueError("Fish Audio API key is required") + + self.model = config.get("model", "s1") + self.reference_id = config.get("reference_id") + self.format = config.get("response_format", "pcm") + self.sample_rate = int(config.get("sample_rate", 16000)) + self.audio_file_type = self.format + self.latency_mode = config.get("latency_mode", "balanced") + self.chunk_length = int(config.get("chunk_length", 200)) + self.top_p = float(config.get("top_p", 0.7)) + self.temperature = float(config.get("temperature", 0.7)) + + self.normalize = str(config.get("normalize", True)).lower() in ( + "true", "1", "yes" + ) + + # WebSocket connection state + self.ws = None + self._ws_connected = False + self._session_active = False + self._monitor_task = None + + # Opus encoder (PCM -> Opus) + self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( + sample_rate=self.sample_rate, channels=1, frame_size_ms=60 + ) + + # Text buffer for current session (supports both LLM and voice_opening/closing) + self._session_text_buffer = [] + self._first_sent = False + + # Check API Key + model_key_msg = check_model_key("TTS", self.api_key) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) + + async def open_audio_channels(self, conn): + """ + Override: establish WebSocket pre-connection + + Connect to Fish Audio WebSocket before LLM starts generating, + reducing connection delay for the first TTS request. + """ + try: + await super().open_audio_channels(conn) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to open audio channels: {str(e)}") + self.ws = None + self._ws_connected = False + raise + + async def _ensure_connection(self): + """Ensure WebSocket connection is established""" + 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 + + # 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()) + + + 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. + """ + while not self.conn.stop_event.is_set(): + try: + message = self.tts_text_queue.get(timeout=1) + logger.bind(tag=TAG).debug( + f"Received TTS task | {message.sentence_type.name} | {message.content_type.name}" + ) + + if message.sentence_type == SentenceType.FIRST: + # ========== New dialogue round starts ========== + self.conn.client_abort = False + + elif self.conn.client_abort: + # ========== Interruption ========== + logger.bind(tag=TAG).info("Received interruption, canceling session") + try: + future = asyncio.run_coroutine_threadsafe( + self._finish_session(self.conn.sentence_id), + self.conn.loop + ) + future.result() + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to cancel session: {e}") + continue + + # when user doesn't trigger interruption, start new TTS session + if message.sentence_type == SentenceType.FIRST: + # Start new TTS session + try: + future = asyncio.run_coroutine_threadsafe( + self._start_session(), + self.conn.loop + ) + future.result() + self.before_stop_play_files.clear() + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to start session: {e}") + continue + elif ContentType.TEXT == message.content_type: + # ========== Text content ========== + if message.content_detail: + # 累积文本用于上报(支持 voice_opening/closing 和 LLM 生成内容) + self._session_text_buffer.append(message.content_detail) + + try: + logger.bind(tag=TAG).debug( + f"Sending TTS text: {message.content_detail}" + ) + future = asyncio.run_coroutine_threadsafe( + self.text_to_speak(message.content_detail, None), + loop=self.conn.loop, + ) + future.result() + logger.bind(tag=TAG).debug("TTS text sent successfully") + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to send TTS text: {e}") + continue + + elif ContentType.FILE == message.content_type: + # ========== File content ========== + logger.bind(tag=TAG).info( + f"Adding audio file to playback list: {message.content_file}" + ) + if message.content_file and os.path.exists(message.content_file): + # Process file audio data first + 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 ========== + try: + future = asyncio.run_coroutine_threadsafe( + self._finish_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + future.result() + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to finish session: {e}") + continue + + except queue.Empty: + continue + except Exception as e: + logger.bind(tag=TAG).error( + 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""" + self._session_active = False + self._ws_connected = False + + # Cancel monitor task + if self._monitor_task: + try: + self._monitor_task.cancel() + await self._monitor_task + except asyncio.CancelledError: + pass + except Exception as e: + logger.bind(tag=TAG).warning(f"Error canceling monitor task: {e}") + self._monitor_task = None + + # Close WebSocket + if self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None + self._ws_connected = False + + await super().close() + + async def _monitor_ws_response(self): + """Monitor WebSocket responses - long running task (MessagePack serialization)""" + try: + while not self.conn.stop_event.is_set(): + try: + if not self.ws: + break + + msg = await self.ws.recv() + response = ormsgpack.unpackb(msg) + event_type = response.get("event") + + if event_type == "audio": + # Received audio chunk (binary data) + audio_data = response.get("audio") + if audio_data and not self.conn.client_abort: + # 在第一个音频之前发送 FIRST(带当前累积的文本) + # 这样后续音频通过 MIDDLE 累积时,enqueue_audio 不会被清空 + if not self._first_sent: + self._first_sent = True + report_text = ''.join(self._session_text_buffer) if self._session_text_buffer else None + self.tts_audio_queue.put((SentenceType.FIRST, None, report_text)) + + # PCM -> Opus conversion + self.opus_encoder.encode_pcm_to_opus_stream( + audio_data, end_of_stream=False, callback=self.handle_opus + ) + + elif event_type == "finish": + # Session completed + reason = response.get("reason", "unknown") + if reason == "error": + logger.bind(tag=TAG).error(f"TTS session error") + else: + logger.bind(tag=TAG).debug(f"TTS session finished") + + # Flush remaining opus buffer + self.opus_encoder.encode_pcm_to_opus_stream( + b'', end_of_stream=True, callback=self.handle_opus + ) + + # 发送 LAST 触发客户端 stop 和最终上报 + # 不再发送 FIRST,避免清空之前累积的音频 + self.tts_audio_queue.put((SentenceType.LAST, None, None)) + + # 清理状态 + self._session_text_buffer = [] + self.conn.tts_MessageText = None + + self._session_active = False + self._process_before_stop_play_files() + self.ws = None + self._ws_connected = False + self._first_sent = False + + except websockets.ConnectionClosed: + logger.bind(tag=TAG).warning("WebSocket connection closed") + break + except Exception as e: + logger.bind(tag=TAG).error(f"Error in monitor task: {e}") + traceback.print_exc() + break + + # Clean up on exit + if self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None + self._ws_connected = False + + finally: + self._monitor_task = None + + async def _send_event(self, event: dict): + """Send event to Fish Audio WebSocket using MessagePack serialization""" + if not self.ws or not self._ws_connected: + logger.bind(tag=TAG).warning("WebSocket not connected, cannot send event") + return + + try: + bytes_event = ormsgpack.packb(event) + await self.ws.send(bytes_event) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to send event: {e}") + raise + + async def _start_session(self): + """ + 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 = [] + self._first_sent = False + self.conn.sentence_id = uuid.uuid4().hex + + try: + # Ensure connection + await self._ensure_connection() + + # Send start event + start_event = { + "event": "start", + "request": { + "text": "", + "format": self.format, + "sample_rate": self.sample_rate, + "chunk_length": self.chunk_length, + "latency": self.latency_mode, + "normalize": self.normalize, + "top_p": self.top_p, + "temperature": self.temperature, + } + } + + if self.reference_id: + start_event["request"]["reference_id"] = self.reference_id + + 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): + """ + Finish current TTS session gracefully + """ + logger.bind(tag=TAG).info(f"Finishing TTS session: {session_id}") + + 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") + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to finish session: {e}") + finally: + self._session_active = False + self.conn.sentence_id = None + + async def text_to_speak(self, text, output_file): + """ + streaming TTS text to Fish Audio WebSocket + + """ + logger.bind(tag=TAG).debug(f"Fish Audio TTS: {text}") + try: + if self.ws is None: + logger.bind(tag=TAG).warning("WebSocket not connected, cannot send text") + return + + filtered_text = MarkdownCleaner.clean_markdown(text) + + # Send text + text_event = {"event": "text", "text": filtered_text} + await self._send_event(text_event) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to send text: {e}") + if self.ws: + try: + await self.ws.close() + except: + pass + self.ws = None + self._ws_connected = False + raise \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py index 25930265a..c7fabb9a7 100644 --- a/main/xiaozhi-server/core/providers/tts/fishspeech.py +++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py @@ -1,64 +1,13 @@ -import base64 from pathlib import Path -from pydantic import BaseModel, Field, conint, model_validator -from typing_extensions import Annotated -from typing import Literal from core.utils.util import parse_string_to_list from core.providers.tts.base import TTSProviderBase from config.logger import setup_logging -from fish_audio_sdk import Session, TTSRequest, ReferenceAudio +from fishaudio import FishAudio, TTSConfig TAG = __name__ logger = setup_logging() -class ServeReferenceAudio(BaseModel): - audio: bytes - text: str - - @model_validator(mode="before") - def decode_audio(cls, values): - audio = values.get("audio") - if ( - isinstance(audio, str) and len(audio) > 255 - ): # Check if audio is a string (Base64) - try: - values["audio"] = base64.b64decode(audio) - except Exception as e: - # If the audio is not a valid base64 string, we will just ignore it and let the server handle it - pass - return values - - def __repr__(self) -> str: - return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})" - - -class ServeTTSRequest(BaseModel): - text: str - chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200 - # Audio format - format: Literal["wav", "pcm", "mp3"] = "wav" - # References audios for in-context learning - references: list[ServeReferenceAudio] = [] - # Reference id - # For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/ - # Just pass 7f92f8afb8ec43bf81429cc1c9199cb1 - reference_id: str | None = None - seed: int | None = None - use_memory_cache: Literal["on", "off"] = "off" - # Normalize text for en & zh, this increase stability for numbers - normalize: bool = True - # not usually used below - streaming: bool = False - max_new_tokens: int = 1024 - top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7 - repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.2 - temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7 - - class Config: - # Allow arbitrary types for pytorch related types - arbitrary_types_allowed = True - def audio_to_bytes(file_path): if not file_path or not Path(file_path).exists(): @@ -82,12 +31,6 @@ class TTSProvider(TTSProviderBase): super().__init__(config, delete_audio_file) self.model = config.get("model", "s1") - # if config.get("private_voice"): - # self.reference_id = config.get("private_voice") - # else: - # self.reference_id = ( - # None if not config.get("reference_id") else config.get("reference_id") - # ) if config.get("reference_id"): self.reference_id = config.get("reference_id") else: @@ -104,7 +47,7 @@ class TTSProvider(TTSProviderBase): self.api_key = config.get("api_key", "YOUR_API_KEY") if self.api_key is None: raise ValueError("FishSpeech API key is required") - self.session = Session(self.api_key) + self._client = FishAudio(api_key=self.api_key) self.normalize = str(config.get("normalize", True)).lower() in ( "true", @@ -143,22 +86,26 @@ class TTSProvider(TTSProviderBase): 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"[DEBUG] 原始文本: {repr(text)}") logger.bind(tag=TAG).info(f"fish speech synthesize text: {text}") - # Prepare reference data - byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio] - ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text] - request = TTSRequest( + audio_stream = self._client.tts.stream( text=text, reference_id=self.reference_id, - sample_rate=self.sample_rate, - format=self.format, - normalize=True, + model=self.model, + config=TTSConfig( + format=self.format, + sample_rate=self.sample_rate, + normalize=self.normalize, + latency="balanced", + ), ) - audio_stream = self.session.tts(request, backend="s1") - audio_bytes = b''.join(chunk for chunk in audio_stream if chunk) + audio_bytes = b'' + + 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) diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index 9e63bfb7e..c8724acb9 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -767,6 +767,7 @@ TTS: FishSpeech: # 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md type: fishspeech + model: s1 output_dir: tmp/ response_format: pcm reference_id: null @@ -783,6 +784,19 @@ TTS: rate: 44100 sample_rate: 16000 api_key: ${FISH_API_KEY} + FishDualStreamTTS: + type: fish_dual_stream + model: s1 + output_dir: tmp/ + response_format: pcm + normalize: true + chunk_length: 200 + top_p: 0.7 + temperature: 0.7 + channels: 1 + rate: 44100 + sample_rate: 16000 + api_key: ${FISH_API_KEY} GPT_SOVITS_V2: # 定义TTS API类型 #启动tts方法: @@ -1072,6 +1086,8 @@ selected_module: ASR: GroqASR LLM: OpenaiLLM VLLM: ChatGLMVLLM + # TTS: FishDualStreamTTS + # TODO: temporarily, fish speech doesn't reuse the wesocket connection, need to discuss further. TTS: FishSpeech Memory: memu Intent: function_call \ No newline at end of file diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index 96f3e2678..8019ac732 100644 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -43,6 +43,6 @@ redis>=4.0.0,<5.0.0 elevenlabs>=1.11.0 cartesia>=1.0.0 deepgram-sdk>=3.0.0 -fish-audio-sdk==2025.6.3 +fish-audio-sdk>=1.0.0 python-dotenv>=1.0.0 \ No newline at end of file diff --git a/main/xiaozhi-server/test/tts_latency/.gitignore b/main/xiaozhi-server/test/tts_latency/.gitignore new file mode 100644 index 000000000..7d0d59449 --- /dev/null +++ b/main/xiaozhi-server/test/tts_latency/.gitignore @@ -0,0 +1 @@ +/reports/ \ No newline at end of file diff --git a/main/xiaozhi-server/test/tts_latency/test_fish_latency.py b/main/xiaozhi-server/test/tts_latency/test_fish_latency.py new file mode 100644 index 000000000..f3fe08e27 --- /dev/null +++ b/main/xiaozhi-server/test/tts_latency/test_fish_latency.py @@ -0,0 +1,602 @@ +#!/usr/bin/env python3 +""" +Fish Speech TTS Latency Comparison: HTTP vs WebSocket + +This script compares the latency of Fish Speech TTS using: +1. HTTP streaming (session.tts) +2. WebSocket streaming (client.tts.stream_websocket) + +Usage: + python3 test_fish_latency.py + + # With custom API key + FISH_API_KEY="your-key" python3 test_fish_latency.py + + # With custom voice + FISH_REFERENCE_ID="voice-id" python3 test_fish_latency.py + +Output: + - Generates a markdown report in ./reports/ + - Prints summary to console + +Requirements: + pip install fish-audio-sdk +""" + +import os +import sys +import time +import asyncio +import statistics +from datetime import datetime +from dataclasses import dataclass + +# Check for required package +try: + from fishaudio import AsyncFishAudio + from fishaudio.types.tts import TTSConfig, FlushEvent +except ImportError: + print("❌ Missing required packages. Install with:") + print(" pip install fish-audio-sdk") + sys.exit(1) + + +@dataclass +class LatencyResult: + """Single test result""" + method: str + test_name: str + text_length: int + ttfb_ms: float # Time to first byte + total_ms: float # Total time + audio_bytes: int + success: bool + error: str = "" + + +@dataclass +class TestConfig: + """Test configuration""" + api_key: str + reference_id: str + sample_rate: int = 16000 + format: str = "pcm" + latency_mode: str = "balanced" # "balanced" or "normal" + runs_per_test: int = 3 + + +# LLM simulation - tokens arrive with delays +# Realistic LLM output with punctuation for sentence segmentation +LLM_SIMULATION = { + "tokens": [ + "好", "的", ",", "今", "天", "天", "气", "非", "常", "不", "错", "。", + "阳", "光", "明", "媚", ",", "温", "度", "适", "宜", ",", "非", "常", + "适", "合", "户", "外", "活", "动", "!", "你", "想", "去", "哪", "里", "玩", "呢", "?" + ], + "delay_ms": 30, # Simulate ~30ms per token (typical LLM speed for Chinese) +} + +# Punctuation sets for sentence segmentation (from base.py) +FIRST_SENTENCE_PUNCTUATIONS = [",", ","] # First sentence ends at comma +SENTENCE_PUNCTUATIONS = ["。", "!", "?", ";", ".", "!", "?", ";", "\n"] # Full sentence ends +MIN_FIRST_SEGMENT_CHARS = 8 # Minimum chars for first segment + + +class TextSegmenter: + """ + Simulates the text segmentation logic from base.py _get_segment_text() + Collects tokens and yields segments when punctuation is encountered. + """ + + def __init__(self): + self.buffer = "" + self.is_first_sentence = True + + def reset(self): + self.buffer = "" + self.is_first_sentence = True + + def add_token(self, token: str) -> str | None: + """ + Add a token and return a segment if ready, otherwise None. + Mirrors the logic in base.py _get_segment_text() + """ + self.buffer += token + + # Choose punctuation set based on whether it's the first sentence + punctuations = FIRST_SENTENCE_PUNCTUATIONS if self.is_first_sentence else SENTENCE_PUNCTUATIONS + + # Find the last punctuation position + last_punct_pos = -1 + for punct in punctuations: + pos = self.buffer.rfind(punct) + if pos != -1 and (last_punct_pos == -1 or pos < last_punct_pos): + last_punct_pos = pos + + if last_punct_pos != -1: + segment = self.buffer[:last_punct_pos + 1] + + # First segment minimum length check + if self.is_first_sentence and len(segment) < MIN_FIRST_SEGMENT_CHARS: + return None # Wait for more text + + # Extract segment and update buffer + self.buffer = self.buffer[last_punct_pos + 1:] + + if self.is_first_sentence: + self.is_first_sentence = False + + return segment + + return None + + def flush(self) -> str | None: + """Return any remaining text in buffer""" + if self.buffer: + remaining = self.buffer + self.buffer = "" + self.is_first_sentence = True + return remaining + return None + + +class HTTPTester: + """HTTP streaming TTS tester""" + + def __init__(self, config: TestConfig): + self.config = config + self.client = AsyncFishAudio(api_key=config.api_key) + + async def test_llm_stream(self, test_name: str) -> LatencyResult: + """ + Test TTS with simulated LLM streaming output via HTTP. + + Flow (matches current implementation): + 1. LLM outputs tokens with delays + 2. TextSegmenter collects tokens and waits for punctuation + 3. When a segment is ready, immediately call HTTP TTS for that segment + 4. Continue receiving LLM tokens while TTS processes + + Key limitation: HTTP cannot start TTS until a complete segment is available. + """ + tokens = LLM_SIMULATION["tokens"] + delay_ms = LLM_SIMULATION["delay_ms"] + + # Start timing from when LLM starts generating + start_time = time.perf_counter() + first_chunk_time = None + audio_bytes = b'' + full_text = "".join(tokens) + + try: + segmenter = TextSegmenter() + tts_config = TTSConfig( + format=self.config.format, + model="s1", + sample_rate=self.config.sample_rate, + normalize=True, + latency=self.config.latency_mode, + ) + + # Process tokens and immediately send segments to TTS when ready + for token in tokens: + await asyncio.sleep(delay_ms / 1000) # Simulate LLM generation delay + segment = segmenter.add_token(token) + + # When a segment is ready, immediately call HTTP TTS + if segment: + audio_stream = await self.client.tts.stream( + text=segment, + reference_id=self.config.reference_id, + model="s1", + config=tts_config, + ) + + async for chunk in audio_stream: + if chunk: + if first_chunk_time is None: + first_chunk_time = time.perf_counter() + audio_bytes += chunk + + # Flush any remaining text + remaining = segmenter.flush() + if remaining: + audio_stream = await self.client.tts.stream( + text=remaining, + reference_id=self.config.reference_id, + model="s1", + config=tts_config, + ) + + async for chunk in audio_stream: + if chunk: + if first_chunk_time is None: + first_chunk_time = time.perf_counter() + audio_bytes += chunk + + end_time = time.perf_counter() + + if first_chunk_time is None: + first_chunk_time = end_time + + return LatencyResult( + method="HTTP-LLM", + test_name=test_name, + text_length=len(full_text), + ttfb_ms=(first_chunk_time - start_time) * 1000, # From LLM start to first audio + total_ms=(end_time - start_time) * 1000, + audio_bytes=len(audio_bytes), + success=True, + ) + except Exception as e: + return LatencyResult( + method="HTTP-LLM", + test_name=test_name, + text_length=len(full_text), + ttfb_ms=0, + total_ms=0, + audio_bytes=0, + success=False, + error=str(e), + ) + + +class WebSocketTester: + """WebSocket streaming TTS tester using fishaudio SDK""" + + def __init__(self, config: TestConfig): + self.config = config + self.client = AsyncFishAudio(api_key=config.api_key) + + async def test_llm_stream(self, test_name: str) -> LatencyResult: + """ + Test TTS with simulated LLM streaming output via WebSocket. + + Optimizations: + 1. Pre-connect: Yield empty string before LLM delay to establish connection early + 2. FlushEvent: Use TextSegmenter + FlushEvent to force audio generation at sentence boundaries + + This mirrors HTTP's chunking strategy but with WebSocket's streaming advantage. + """ + tokens = LLM_SIMULATION["tokens"] + delay_ms = LLM_SIMULATION["delay_ms"] + full_text = "".join(tokens) + + tts_config = TTSConfig( + format=self.config.format, + sample_rate=self.config.sample_rate, + normalize=True, + latency=self.config.latency_mode, + ) + + # Optimization 1: Pre-connect - yield empty string to establish connection + # before the first LLM token delay + + async def init_websocket(): + yield "" + + self.client.tts.stream_websocket( + init_websocket(), + reference_id=self.config.reference_id, + config=tts_config, + ) + + start_time = time.perf_counter() + first_chunk_time = None + audio_bytes = b'' + + try: + + async def llm_token_gen(): + """ + Simulate LLM streaming with FlushEvent optimization. + - Pre-connect by yielding empty string immediately + - Use TextSegmenter to detect sentence boundaries + - Yield FlushEvent after each complete segment to force immediate audio generation + """ + segmenter = TextSegmenter() + + for token in tokens: + await asyncio.sleep(delay_ms / 1000) # Simulate LLM generation delay + + # Accumulate token and check for segment completion + segment = segmenter.add_token(token) + + if segment: + # Optimization 2: When segment is complete, yield it + FlushEvent + # to force immediate audio generation + yield segment + yield FlushEvent() + # Note: Don't yield individual tokens - TextSegmenter handles buffering + # The segment already contains all accumulated tokens + + # Flush any remaining text + remaining = segmenter.flush() + if remaining: + yield remaining + yield FlushEvent() + + audio_stream = self.client.tts.stream_websocket( + llm_token_gen(), + reference_id=self.config.reference_id, + config=tts_config, + ) + + async for chunk in audio_stream: + if chunk: + if first_chunk_time is None: + first_chunk_time = time.perf_counter() + audio_bytes += chunk + + end_time = time.perf_counter() + + if first_chunk_time is None: + first_chunk_time = end_time + + return LatencyResult( + method="WebSocket-LLM", + test_name=test_name, + text_length=len(full_text), + ttfb_ms=(first_chunk_time - start_time) * 1000, + total_ms=(end_time - start_time) * 1000, + audio_bytes=len(audio_bytes), + success=True, + ) + except Exception as e: + return LatencyResult( + method="WebSocket-LLM", + test_name=test_name, + text_length=len(full_text), + ttfb_ms=0, + total_ms=0, + audio_bytes=0, + success=False, + error=str(e), + ) + + +def generate_report(results: list[LatencyResult], config: TestConfig) -> str: + """Generate markdown report""" + now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + report = f"""# Fish Speech TTS Latency Comparison Report + +**Generated:** {now} +**Reference ID:** {config.reference_id} +**Sample Rate:** {config.sample_rate} Hz +**Format:** {config.format} +**WebSocket Latency Mode:** {config.latency_mode} +**Runs per Test:** {config.runs_per_test} + +--- + +## Summary + +| Method | Test | Avg TTFB (ms) | Avg Total (ms) | Avg Audio (bytes) | +|--------|------|---------------|----------------|-------------------| +""" + + # Group results by method and test + grouped = {} + for r in results: + if not r.success: + continue + key = (r.method, r.test_name) + if key not in grouped: + grouped[key] = [] + grouped[key].append(r) + + for (method, test_name), runs in sorted(grouped.items()): + avg_ttfb = statistics.mean(r.ttfb_ms for r in runs) + avg_total = statistics.mean(r.total_ms for r in runs) + avg_audio = statistics.mean(r.audio_bytes for r in runs) + report += f"| {method} | {test_name} | {avg_ttfb:.1f} | {avg_total:.1f} | {avg_audio:.0f} |\n" + + report += """ +--- + +## Detailed Results + +""" + + for (method, test_name), runs in sorted(grouped.items()): + report += f"### {method} - {test_name}\n\n" + report += "| Run | TTFB (ms) | Total (ms) | Audio (bytes) | Text Length |\n" + report += "|-----|-----------|------------|---------------|-------------|\n" + + for i, r in enumerate(runs, 1): + report += f"| {i} | {r.ttfb_ms:.1f} | {r.total_ms:.1f} | {r.audio_bytes} | {r.text_length} |\n" + + if len(runs) > 1: + ttfb_std = statistics.stdev(r.ttfb_ms for r in runs) + total_std = statistics.stdev(r.total_ms for r in runs) + report += f"\n**TTFB Std Dev:** {ttfb_std:.1f} ms | **Total Std Dev:** {total_std:.1f} ms\n" + + report += "\n" + + # Error summary + errors = [r for r in results if not r.success] + if errors: + report += "## Errors\n\n" + for r in errors: + report += f"- **{r.method}** - {r.test_name}: {r.error}\n" + report += "\n" + + # Analysis + report += """--- + +## Analysis + +### Key Findings: LLM Streaming Simulation + +This is the critical comparison for multi-turn conversations. + +**Test Setup:** +- Simulated LLM output: {} tokens, {}ms per token +- Full text: "{}" + +**HTTP-LLM Flow (Current Implementation):** +1. LLM outputs tokens → TextSegmenter collects +2. Wait for punctuation (e.g., comma for first sentence) +3. Segment ready → HTTP TTS request +4. Repeat for each segment + +**WebSocket-LLM Flow (Proposed):** +1. LLM outputs tokens → Stream directly to WebSocket +2. Fish Audio server buffers and generates audio +3. Audio chunks return as soon as server is ready +4. No client-side segmentation needed! + +""".format(len(LLM_SIMULATION["tokens"]), LLM_SIMULATION["delay_ms"], "".join(LLM_SIMULATION["tokens"])[:50] + "...") + + http_llm_runs = grouped.get(("HTTP-LLM", "llm_simulation"), []) + ws_llm_runs = grouped.get(("WebSocket-LLM", "llm_simulation"), []) + + if http_llm_runs and ws_llm_runs: + http_ttfb = statistics.mean(r.ttfb_ms for r in http_llm_runs) + ws_ttfb = statistics.mean(r.ttfb_ms for r in ws_llm_runs) + http_total = statistics.mean(r.total_ms for r in http_llm_runs) + ws_total = statistics.mean(r.total_ms for r in ws_llm_runs) + + ttfb_diff = http_ttfb - ws_ttfb + total_diff = http_total - ws_total + ttfb_pct = (ttfb_diff / http_ttfb * 100) if http_ttfb > 0 else 0 + total_pct = (total_diff / http_total * 100) if http_total > 0 else 0 + + report += f"| Metric | HTTP-LLM | WebSocket-LLM | Difference |\n" + report += f"|--------|----------|---------------|------------|\n" + report += f"| TTFB | {http_ttfb:.0f}ms | {ws_ttfb:.0f}ms | **{ttfb_diff:.0f}ms** ({ttfb_pct:.1f}%) |\n" + report += f"| Total | {http_total:.0f}ms | {ws_total:.0f}ms | **{total_diff:.0f}ms** ({total_pct:.1f}%) |\n" + + if ttfb_diff > 100: + report += f"\n🎯 **WebSocket provides {ttfb_diff:.0f}ms faster first audio** in LLM streaming scenarios!\n" + + report += """ +### Recommendations + +1. **For single requests:** Compare TTFB values above to determine the best method +2. **For LLM streaming:** WebSocket allows sending tokens as they arrive, reducing perceived latency +3. **Consider `latency="balanced"` for real-time applications** +4. **For multi-turn conversations:** WebSocket streaming is recommended for lower latency + +--- + +*Generated by Fish Speech TTS Latency Tester* +""" + + return report + + +async def main(): + print("🐟 Fish Speech TTS Latency Comparison Test") + print("=" * 50) + + # Get configuration from environment + api_key = os.environ.get("FISH_API_KEY") + if not api_key: + print("\n❌ Error: FISH_API_KEY not set") + print(" export FISH_API_KEY='your-key'") + print("\n💡 Get your API key from: https://fish.audio/") + sys.exit(1) + + reference_id = os.environ.get("FISH_REFERENCE_ID", "5196af35f6ff4a0dbf541793fc9f2157") + runs = int(os.environ.get("TEST_RUNS", "3")) + + config = TestConfig( + api_key=api_key, + reference_id=reference_id, + runs_per_test=runs, + ) + + print(f"\n📋 Configuration:") + print(f" Reference ID: {reference_id}") + print(f" Sample Rate: {config.sample_rate} Hz") + print(f" Format: {config.format}") + print(f" Runs per test: {runs}") + + # Initialize testers + http_tester = HTTPTester(config) + ws_tester = WebSocketTester(config) + + results: list[LatencyResult] = [] + + # Run HTTP LLM simulation test + print("\n" + "=" * 50) + print("🔄 Testing HTTP with LLM Simulation...") + print(" (HTTP must wait for segment completion before starting TTS)") + print("=" * 50) + + print(f"\n📝 Simulating LLM output ({len(LLM_SIMULATION['tokens'])} tokens, {LLM_SIMULATION['delay_ms']}ms/token)") + for run in range(runs): + result = await http_tester.test_llm_stream("llm_simulation") + results.append(result) + if result.success: + print(f" Run {run + 1}: TTFB={result.ttfb_ms:.0f}ms, Total={result.total_ms:.0f}ms") + else: + print(f" Run {run + 1}: ❌ {result.error}") + await asyncio.sleep(0.5) + + # Run WebSocket LLM simulation test + print("\n" + "=" * 50) + print("🔄 Testing WebSocket with LLM Simulation...") + print("=" * 50) + + print(f"\n📝 Simulating LLM output ({len(LLM_SIMULATION['tokens'])} tokens, {LLM_SIMULATION['delay_ms']}ms/token)") + for run in range(runs): + result = await ws_tester.test_llm_stream("llm_simulation") + results.append(result) + if result.success: + print(f" Run {run + 1}: TTFB={result.ttfb_ms:.0f}ms, Total={result.total_ms:.0f}ms") + else: + print(f" Run {run + 1}: ❌ {result.error}") + await asyncio.sleep(0.5) + + # Generate report + print("\n" + "=" * 50) + print("📊 Generating Report...") + print("=" * 50) + + report = generate_report(results, config) + + # Save report + script_dir = os.path.dirname(os.path.abspath(__file__)) + reports_dir = os.path.join(script_dir, "reports") + os.makedirs(reports_dir, exist_ok=True) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + report_file = os.path.join(reports_dir, f"latency_report_{timestamp}.md") + + with open(report_file, "w") as f: + f.write(report) + + print(f"\n✅ Report saved to: {report_file}") + + # Print summary + print("\n" + "=" * 50) + print("📈 Quick Summary") + print("=" * 50) + + # Group and average results + grouped = {} + for r in results: + if not r.success: + continue + key = (r.method, r.test_name) + if key not in grouped: + grouped[key] = [] + grouped[key].append(r) + + print(f"\n{'Method':<15} {'Test':<20} {'Avg TTFB (ms)':<15} {'Avg Total (ms)':<15}") + print("-" * 65) + + for (method, test_name), runs_list in sorted(grouped.items()): + avg_ttfb = statistics.mean(r.ttfb_ms for r in runs_list) + avg_total = statistics.mean(r.total_ms for r in runs_list) + print(f"{method:<15} {test_name:<20} {avg_ttfb:<15.0f} {avg_total:<15.0f}") + + print("\n✅ Test completed!") + + +if __name__ == "__main__": + asyncio.run(main()) +