mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #18 from Plaud-AI/feat/demo
feat: optmize and split AIGC API
This commit is contained in:
commit
efcdd1eb74
13 changed files with 2075 additions and 141 deletions
|
|
@ -10,6 +10,9 @@ from services.llm_service import llm_service
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
from api.auth import get_current_user_id
|
from api.auth import get_current_user_id
|
||||||
from schemas.agent import AgentResponse
|
from schemas.agent import AgentResponse
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
@ -140,40 +143,80 @@ async def delete_agent(
|
||||||
return success_response(data={}, message="Agent deleted successfully")
|
return success_response(data={}, message="Agent deleted successfully")
|
||||||
|
|
||||||
|
|
||||||
@router.post("/instructions", summary="Optimize Agent Instruction")
|
@router.post("/persona", summary="Generate or Optimize Agent Persona")
|
||||||
async def optimize_instruction(
|
async def generate_persona(
|
||||||
instruction: str = Form(..., description="Original instruction text"),
|
name: str = Form(..., description="Agent name (required)"),
|
||||||
|
instruction: Optional[str] = Form(None, description="Existing instruction (required for optimize mode)"),
|
||||||
|
avatar: Optional[UploadFile] = File(None, description="Optional avatar image"),
|
||||||
|
mode: str = Form("quick", description="Mode: 'quick' (non-streaming) or 'optimize' (streaming)"),
|
||||||
current_user_id: str = Depends(get_current_user_id),
|
current_user_id: str = Depends(get_current_user_id),
|
||||||
openai_client = Depends(get_openai)
|
openai_client = Depends(get_openai)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Optimize agent instruction using LLM (streaming)
|
Generate or optimize agent persona
|
||||||
|
|
||||||
- **instruction**: Original instruction text from user
|
**Modes:**
|
||||||
- Returns streaming optimized instruction text
|
- `quick`: Fast non-streaming, returns JSON with instruction + voice_opening + voice_closing (for initial creation)
|
||||||
|
- `optimize`: Streaming, returns detailed instruction text (for iterative refinement)
|
||||||
|
|
||||||
The optimization process:
|
**Parameters:**
|
||||||
- Enhances role definition and clarity
|
- **name**: Agent name (required) - e.g., "Dave", "Elon Musk", "Labubu"
|
||||||
- Adds behavior guidelines and tone specification
|
- **instruction**: Existing instruction text (required for optimize mode)
|
||||||
- Structures the instruction professionally
|
- **avatar**: Optional avatar image to inform persona's visual characteristics
|
||||||
- Ensures helpful, focused, and actionable content
|
- **mode**: "quick" (default) or "optimize"
|
||||||
|
|
||||||
|
**Returns:**
|
||||||
|
- quick mode: `{"code": 0, "data": {"instruction": "...", "voice_opening": "...", "voice_closing": "..."}}`
|
||||||
|
- optimize mode: Streaming text with enhanced instruction
|
||||||
"""
|
"""
|
||||||
|
|
||||||
async def instruction_generator():
|
# Process avatar if provided
|
||||||
"""Generate optimized instruction chunks"""
|
avatar_base64 = None
|
||||||
|
avatar_media_type = None
|
||||||
|
|
||||||
|
if avatar:
|
||||||
try:
|
try:
|
||||||
async for chunk in llm_service.optimize_instruction_stream(
|
content = await avatar.read()
|
||||||
openai_client=openai_client,
|
avatar_base64 = base64.b64encode(content).decode("utf-8")
|
||||||
original_instruction=instruction
|
avatar_media_type = avatar.content_type or "image/jpeg"
|
||||||
):
|
|
||||||
yield chunk
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Error already yielded in service, just log
|
logging.warning(f"Failed to process avatar: {e}")
|
||||||
import logging
|
|
||||||
logging.error(f"Instruction optimization failed: {e}")
|
if mode == "optimize":
|
||||||
|
# Optimize mode: streaming with SSE format, requires existing instruction
|
||||||
|
if not instruction:
|
||||||
|
raise HTTPException(status_code=400, detail="instruction is required for optimize mode")
|
||||||
|
|
||||||
|
async def stream_generator():
|
||||||
|
try:
|
||||||
|
async for chunk in llm_service.optimize_persona_stream(
|
||||||
|
openai_client=openai_client,
|
||||||
|
name=name,
|
||||||
|
instruction=instruction,
|
||||||
|
avatar_base64=avatar_base64,
|
||||||
|
avatar_media_type=avatar_media_type
|
||||||
|
):
|
||||||
|
# SSE format: data: <content>\n\n
|
||||||
|
yield f"data: {chunk}\n\n"
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Persona optimization failed: {e}")
|
||||||
|
yield f"data: [ERROR] {str(e)}\n\n"
|
||||||
|
|
||||||
return StreamingResponse(
|
return StreamingResponse(
|
||||||
instruction_generator(),
|
stream_generator(),
|
||||||
media_type="text/plain; charset=utf-8"
|
media_type="text/event-stream"
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
# Quick mode: non-streaming, returns JSON
|
||||||
|
try:
|
||||||
|
result = await llm_service.generate_persona_quick(
|
||||||
|
openai_client=openai_client,
|
||||||
|
name=name,
|
||||||
|
avatar_base64=avatar_base64,
|
||||||
|
avatar_media_type=avatar_media_type
|
||||||
|
)
|
||||||
|
return success_response(data=result)
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Persona generation failed: {e}")
|
||||||
|
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,6 +34,12 @@ class Settings(BaseSettings):
|
||||||
OPENAI_MODEL: str = "gpt-4o-mini"
|
OPENAI_MODEL: str = "gpt-4o-mini"
|
||||||
OPENAI_BASE_URL: str = "https://api.openai.com/v1"
|
OPENAI_BASE_URL: str = "https://api.openai.com/v1"
|
||||||
|
|
||||||
|
# OpenRouter Configuration
|
||||||
|
OPENROUTER_API_KEY: str
|
||||||
|
OPENROUTER_BASE_URL: str = "https://openrouter.ai/api/v1"
|
||||||
|
QUICK_PERSONA_MODEL: str = "google/gemini-2.5-flash"
|
||||||
|
OPTIMIZE_PERSONA_MODEL: str = "google/gemini-3-pro-preview"
|
||||||
|
|
||||||
model_config = SettingsConfigDict(
|
model_config = SettingsConfigDict(
|
||||||
env_file=".env",
|
env_file=".env",
|
||||||
env_file_encoding="utf-8",
|
env_file_encoding="utf-8",
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ async def init_openai():
|
||||||
"""Initialize OpenAI client"""
|
"""Initialize OpenAI client"""
|
||||||
global _openai_client
|
global _openai_client
|
||||||
_openai_client = AsyncOpenAI(
|
_openai_client = AsyncOpenAI(
|
||||||
api_key=settings.OPENAI_API_KEY,
|
api_key=settings.OPENROUTER_API_KEY,
|
||||||
base_url=settings.OPENAI_BASE_URL
|
base_url=settings.OPENROUTER_BASE_URL
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
"""LLM service for text generation"""
|
"""LLM service for text generation"""
|
||||||
from typing import AsyncGenerator
|
import json
|
||||||
|
from typing import AsyncGenerator, Optional
|
||||||
from openai import AsyncOpenAI
|
from openai import AsyncOpenAI
|
||||||
from config import settings
|
from config import settings
|
||||||
|
|
||||||
|
|
@ -22,24 +23,46 @@ Requirements:
|
||||||
|
|
||||||
Output ONLY the text sample, no explanations or metadata."""
|
Output ONLY the text sample, no explanations or metadata."""
|
||||||
|
|
||||||
INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT = """You are an expert AI prompt engineer specializing in agent instruction optimization.
|
# Quick mode: concise persona for initial creation
|
||||||
|
PERSONA_QUICK_SYSTEM_PROMPT = """You are a creative character designer. Create a concise persona based on the name and optional image.
|
||||||
|
|
||||||
Your task: Transform user's basic instruction into a professional, comprehensive agent system prompt.
|
**instruction**: MUST start with "You are [name]..." - a brief role-play instruction (1-2 sentences, 25-40 words)
|
||||||
|
- Describe their personality, vibe, and how they communicate
|
||||||
|
- Write in second person as if instructing an AI to role-play this character
|
||||||
|
|
||||||
Optimization guidelines:
|
**voice_opening**: A characteristic greeting when starting a conversation (5-15 words)
|
||||||
1. **Role Definition**: Clearly define the agent's persona and expertise
|
- How would this character say hello?
|
||||||
2. **Behavior Guidelines**: Specify tone, communication style, and interaction patterns
|
|
||||||
3. **Task Scope**: Define what the agent should and shouldn't do
|
|
||||||
4. **Response Format**: Suggest how responses should be structured
|
|
||||||
5. **Helpful & On-Task**: Keep the agent focused, supportive, and practical
|
|
||||||
|
|
||||||
Output format:
|
**voice_closing**: A characteristic FAREWELL/GOODBYE when ending a conversation (5-15 words)
|
||||||
- Write in second person ("You are...")
|
- How would this character say goodbye? (NOT a catchphrase, but an actual farewell)
|
||||||
- Be clear, specific, and actionable
|
|
||||||
- Length: 100-300 words
|
|
||||||
- Professional yet accessible tone
|
|
||||||
|
|
||||||
Output ONLY the optimized instruction, no explanations or metadata."""
|
Example output:
|
||||||
|
{
|
||||||
|
"instruction": "...",
|
||||||
|
"voice_opening": "...",
|
||||||
|
"voice_closing": "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
Output valid JSON only. Be creative and authentic."""
|
||||||
|
|
||||||
|
# Optimize mode: detailed persona for iterative refinement
|
||||||
|
PERSONA_OPTIMIZE_SYSTEM_PROMPT = """You are a creative character designer who enriches AI agent personas.
|
||||||
|
|
||||||
|
Your task: Take the existing instruction and enhance it into a rich, narrative persona.
|
||||||
|
|
||||||
|
DO NOT write like a typical AI prompt. Write like you're describing a REAL PERSON with soul and character.
|
||||||
|
|
||||||
|
Expand on these dimensions:
|
||||||
|
- Who is this person? What's their vibe, their energy?
|
||||||
|
- How do they talk? Street-smart? Elegant? Nerdy? Chill?
|
||||||
|
- What's their worldview? What do they care about?
|
||||||
|
- How do they connect with people? Warm, sarcastic, mysterious?
|
||||||
|
- Give them a unique angle or perspective on life
|
||||||
|
|
||||||
|
Example style (Dave - The Witty Commentator, a Black stand-up comedian):
|
||||||
|
"You are Dave, a stand-up comedian with a relaxed, soulful vibe and a sharp eye for the absurdities of life. You view the world through a lens of 'real talk' and observational humor, acting as the user's witty friend who loves to chat about pop culture, daily grinds, or random thoughts. Your style is street-smart and medium-sharp—playful enough to roast a situation, but always good-natured and safe, keeping the conversation flowing like a late-night backstage hang."
|
||||||
|
|
||||||
|
Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanations, no metadata."""
|
||||||
|
|
||||||
async def generate_voice_sample_text_stream(
|
async def generate_voice_sample_text_stream(
|
||||||
self,
|
self,
|
||||||
|
|
@ -104,40 +127,106 @@ Output ONLY the optimized instruction, no explanations or metadata."""
|
||||||
yield f"\n\n{error_message}"
|
yield f"\n\n{error_message}"
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def optimize_instruction_stream(
|
async def generate_persona_quick(
|
||||||
self,
|
self,
|
||||||
openai_client: AsyncOpenAI,
|
openai_client: AsyncOpenAI,
|
||||||
original_instruction: str
|
name: str,
|
||||||
) -> AsyncGenerator[str, None]:
|
avatar_base64: Optional[str] = None,
|
||||||
|
avatar_media_type: Optional[str] = None
|
||||||
|
) -> dict:
|
||||||
"""
|
"""
|
||||||
Optimize agent instruction with streaming
|
Quick mode: Non-streaming generation of instruction + voice_opening + voice_closing
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
openai_client: OpenAI client instance
|
openai_client: OpenAI client instance
|
||||||
original_instruction: Original instruction text from user
|
name: Agent name (required)
|
||||||
|
avatar_base64: Optional base64-encoded avatar image
|
||||||
|
avatar_media_type: Optional media type of avatar (e.g., image/jpeg)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict with instruction, voice_opening, voice_closing
|
||||||
|
"""
|
||||||
|
user_prompt = f"Create a persona for: {name}"
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": self.PERSONA_QUICK_SYSTEM_PROMPT}
|
||||||
|
]
|
||||||
|
|
||||||
|
if avatar_base64 and avatar_media_type:
|
||||||
|
messages.append({
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "text": user_prompt + "\n\nUse the image to inform the persona's character and style."},
|
||||||
|
{"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
messages.append({"role": "user", "content": user_prompt})
|
||||||
|
|
||||||
|
response = await openai_client.chat.completions.create(
|
||||||
|
model=settings.QUICK_PERSONA_MODEL,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.6,
|
||||||
|
max_tokens=500
|
||||||
|
)
|
||||||
|
|
||||||
|
content = response.choices[0].message.content.strip()
|
||||||
|
# Handle markdown code blocks if model wraps JSON
|
||||||
|
if content.startswith("```"):
|
||||||
|
lines = content.split("\n")
|
||||||
|
# Remove first line (```json) and last line (```)
|
||||||
|
content = "\n".join(lines[1:-1])
|
||||||
|
|
||||||
|
return json.loads(content)
|
||||||
|
|
||||||
|
async def optimize_persona_stream(
|
||||||
|
self,
|
||||||
|
openai_client: AsyncOpenAI,
|
||||||
|
name: str,
|
||||||
|
instruction: str,
|
||||||
|
avatar_base64: Optional[str] = None,
|
||||||
|
avatar_media_type: Optional[str] = None
|
||||||
|
) -> AsyncGenerator[str, None]:
|
||||||
|
"""
|
||||||
|
Optimize mode: Streaming generation of detailed instruction
|
||||||
|
|
||||||
|
Args:
|
||||||
|
openai_client: OpenAI client instance
|
||||||
|
name: Agent name (required)
|
||||||
|
instruction: Existing instruction to enhance
|
||||||
|
avatar_base64: Optional base64-encoded avatar image
|
||||||
|
avatar_media_type: Optional media type of avatar (e.g., image/jpeg)
|
||||||
|
|
||||||
Yields:
|
Yields:
|
||||||
Optimized instruction chunks as they are generated
|
Enhanced instruction text chunks
|
||||||
|
|
||||||
Raises:
|
|
||||||
Exception: If OpenAI API call fails
|
|
||||||
"""
|
"""
|
||||||
user_prompt = f"""Optimize this agent instruction:
|
user_prompt = f"""Agent name: {name}
|
||||||
|
|
||||||
Original instruction:
|
Current instruction to enhance:
|
||||||
{original_instruction}
|
{instruction}
|
||||||
|
|
||||||
Provide an improved, professional version."""
|
Create a richer, more detailed persona."""
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": self.PERSONA_OPTIMIZE_SYSTEM_PROMPT}
|
||||||
|
]
|
||||||
|
|
||||||
|
if avatar_base64 and avatar_media_type:
|
||||||
|
messages.append({
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "text": user_prompt + "\n\nAlso consider the visual appearance from the image."},
|
||||||
|
{"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
messages.append({"role": "user", "content": user_prompt})
|
||||||
|
|
||||||
try:
|
try:
|
||||||
stream = await openai_client.chat.completions.create(
|
stream = await openai_client.chat.completions.create(
|
||||||
model=settings.OPENAI_MODEL,
|
model=settings.OPTIMIZE_PERSONA_MODEL,
|
||||||
messages=[
|
messages=messages,
|
||||||
{"role": "system", "content": self.INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT},
|
temperature=0.75,
|
||||||
{"role": "user", "content": user_prompt}
|
|
||||||
],
|
|
||||||
temperature=0.7, # Balanced creativity and consistency
|
|
||||||
max_tokens=500,
|
|
||||||
stream=True
|
stream=True
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -146,8 +235,7 @@ Provide an improved, professional version."""
|
||||||
yield chunk.choices[0].delta.content
|
yield chunk.choices[0].delta.content
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# In streaming mode, we yield an error marker
|
error_message = f"[ERROR] Failed to optimize persona: {str(e)}"
|
||||||
error_message = f"[ERROR] Failed to optimize instruction: {str(e)}"
|
|
||||||
yield f"\n\n{error_message}"
|
yield f"\n\n{error_message}"
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -448,6 +448,16 @@ class ConnectionHandler:
|
||||||
|
|
||||||
if self._voice_opening:
|
if self._voice_opening:
|
||||||
self.logger.bind(tag=TAG).info(f"send the opening message: {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(
|
self.tts.tts_text_queue.put(TTSMessageDTO(
|
||||||
sentence_id=str(uuid.uuid4().hex),
|
sentence_id=str(uuid.uuid4().hex),
|
||||||
sentence_type=SentenceType.MIDDLE,
|
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:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
|
self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
|
||||||
|
|
||||||
|
|
@ -833,6 +849,7 @@ class ConnectionHandler:
|
||||||
# self.logger.bind(tag=TAG).info(f"private_config: {private_config}")
|
# self.logger.bind(tag=TAG).info(f"private_config: {private_config}")
|
||||||
# self.logger.bind(tag=TAG).info(f"self.config: {self.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"]["FishSpeech"]["reference_id"] = private_config["voice_id"]
|
||||||
|
self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = private_config["voice_id"]
|
||||||
self._instruction = private_config["instruction"]
|
self._instruction = private_config["instruction"]
|
||||||
self._voice_opening = private_config["voice_opening"]
|
self._voice_opening = private_config["voice_opening"]
|
||||||
self._voice_closing = private_config["voice_closing"]
|
self._voice_closing = private_config["voice_closing"]
|
||||||
|
|
|
||||||
|
|
@ -38,16 +38,16 @@ class AttachmentTextMessageHandler(TextMessageHandler):
|
||||||
if attachment_type == "image":
|
if attachment_type == "image":
|
||||||
content = [
|
content = [
|
||||||
{
|
{
|
||||||
"type": "image",
|
"type": "input_image",
|
||||||
"image_url": {"url": url}
|
"image_url": url
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
else:
|
elif attachment_type == "file":
|
||||||
# File type: store as custom format, LLM layer needs special handling
|
# File type: store as custom format, LLM layer needs special handling
|
||||||
content = [
|
content = [
|
||||||
{
|
{
|
||||||
"type": "file",
|
"type": "input_file",
|
||||||
"file_url": {"url": url}
|
"file_url": url
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
||||||
427
main/xiaozhi-server/core/providers/tts/fish_dual_stream.py
Normal file
427
main/xiaozhi-server/core/providers/tts/fish_dual_stream.py
Normal file
|
|
@ -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
|
||||||
|
|
@ -1,64 +1,13 @@
|
||||||
import base64
|
|
||||||
from pathlib import Path
|
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.utils.util import parse_string_to_list
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from fish_audio_sdk import Session, TTSRequest, ReferenceAudio
|
from fishaudio import FishAudio, TTSConfig
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
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):
|
def audio_to_bytes(file_path):
|
||||||
if not file_path or not Path(file_path).exists():
|
if not file_path or not Path(file_path).exists():
|
||||||
|
|
@ -82,12 +31,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.model = config.get("model", "s1")
|
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"):
|
if config.get("reference_id"):
|
||||||
self.reference_id = config.get("reference_id")
|
self.reference_id = config.get("reference_id")
|
||||||
else:
|
else:
|
||||||
|
|
@ -104,7 +47,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.api_key = config.get("api_key", "YOUR_API_KEY")
|
self.api_key = config.get("api_key", "YOUR_API_KEY")
|
||||||
if self.api_key is None:
|
if self.api_key is None:
|
||||||
raise ValueError("FishSpeech API key is required")
|
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 (
|
self.normalize = str(config.get("normalize", True)).lower() in (
|
||||||
"true",
|
"true",
|
||||||
|
|
@ -143,21 +86,25 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.seed = int(config.get("seed")) if config.get("seed") else None
|
self.seed = int(config.get("seed")) if config.get("seed") else None
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
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}")
|
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,
|
text=text,
|
||||||
reference_id=self.reference_id,
|
reference_id=self.reference_id,
|
||||||
sample_rate=self.sample_rate,
|
model=self.model,
|
||||||
|
config=TTSConfig(
|
||||||
format=self.format,
|
format=self.format,
|
||||||
normalize=True,
|
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:
|
if output_file:
|
||||||
with open(output_file, "wb") as audio_file:
|
with open(output_file, "wb") as audio_file:
|
||||||
|
|
|
||||||
|
|
@ -767,6 +767,7 @@ TTS:
|
||||||
FishSpeech:
|
FishSpeech:
|
||||||
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
|
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
|
||||||
type: fishspeech
|
type: fishspeech
|
||||||
|
model: s1
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
response_format: pcm
|
response_format: pcm
|
||||||
reference_id: null
|
reference_id: null
|
||||||
|
|
@ -783,6 +784,19 @@ TTS:
|
||||||
rate: 44100
|
rate: 44100
|
||||||
sample_rate: 16000
|
sample_rate: 16000
|
||||||
api_key: ${FISH_API_KEY}
|
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:
|
GPT_SOVITS_V2:
|
||||||
# 定义TTS API类型
|
# 定义TTS API类型
|
||||||
#启动tts方法:
|
#启动tts方法:
|
||||||
|
|
@ -1072,6 +1086,8 @@ selected_module:
|
||||||
ASR: GroqASR
|
ASR: GroqASR
|
||||||
LLM: OpenaiLLM
|
LLM: OpenaiLLM
|
||||||
VLLM: ChatGLMVLLM
|
VLLM: ChatGLMVLLM
|
||||||
|
# TTS: FishDualStreamTTS
|
||||||
|
# TODO: temporarily, fish speech doesn't reuse the wesocket connection, need to discuss further.
|
||||||
TTS: FishSpeech
|
TTS: FishSpeech
|
||||||
Memory: memu
|
Memory: memu
|
||||||
Intent: function_call
|
Intent: function_call
|
||||||
|
|
@ -43,6 +43,6 @@ redis>=4.0.0,<5.0.0
|
||||||
elevenlabs>=1.11.0
|
elevenlabs>=1.11.0
|
||||||
cartesia>=1.0.0
|
cartesia>=1.0.0
|
||||||
deepgram-sdk>=3.0.0
|
deepgram-sdk>=3.0.0
|
||||||
fish-audio-sdk==2025.6.3
|
fish-audio-sdk>=1.0.0
|
||||||
|
|
||||||
python-dotenv>=1.0.0
|
python-dotenv>=1.0.0
|
||||||
2
main/xiaozhi-server/test/tts_test/.gitignore
vendored
Normal file
2
main/xiaozhi-server/test/tts_test/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
/reports/
|
||||||
|
/tmp/
|
||||||
787
main/xiaozhi-server/test/tts_test/test_emotion_tag.py
Normal file
787
main/xiaozhi-server/test/tts_test/test_emotion_tag.py
Normal file
|
|
@ -0,0 +1,787 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Fish Speech Emotion Tag Test
|
||||||
|
|
||||||
|
This script tests whether Fish Speech TTS correctly handles emotion tags:
|
||||||
|
- Emotion tags like (happy), (sad) should NOT be read aloud
|
||||||
|
- Only the actual text content should be spoken
|
||||||
|
|
||||||
|
Method:
|
||||||
|
1. Generate TTS audio with emotion-tagged text
|
||||||
|
2. Transcribe the audio using Groq Whisper ASR
|
||||||
|
3. Compare transcript with expected text (without emotion tag)
|
||||||
|
4. Report whether the emotion tag was incorrectly read aloud
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 test_emotion_tag.py
|
||||||
|
|
||||||
|
# With API keys
|
||||||
|
FISH_API_KEY="your-fish-key" GROQ_API_KEY="your-groq-key" python3 test_emotion_tag.py
|
||||||
|
|
||||||
|
# With custom voice
|
||||||
|
FISH_REFERENCE_ID="voice-id" python3 test_emotion_tag.py
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
pip install fish-audio-sdk openai
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import io
|
||||||
|
import wave
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
import argparse
|
||||||
|
from datetime import datetime
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
# Check for required packages
|
||||||
|
try:
|
||||||
|
from fishaudio import AsyncFishAudio
|
||||||
|
from fishaudio.types.tts import TTSConfig
|
||||||
|
except ImportError:
|
||||||
|
print("❌ Missing fish-audio-sdk. Install with:")
|
||||||
|
print(" pip install fish-audio-sdk")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from openai import OpenAI
|
||||||
|
except ImportError:
|
||||||
|
print("❌ Missing openai. Install with:")
|
||||||
|
print(" pip install openai")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
# All emotion tags from role.md
|
||||||
|
EMOTION_TAGS = [
|
||||||
|
"happy", "satisfied", "relaxed", "amused", "sincere", "conciliative",
|
||||||
|
"calm", "confident", "curious", "keen", "confused", "worried",
|
||||||
|
"frustrated", "sad", "unhappy", "impatient", "negative", "disapproving",
|
||||||
|
"disdainful", "scornful", "sarcastic", "surprised"
|
||||||
|
]
|
||||||
|
|
||||||
|
# Voice reference IDs for different languages
|
||||||
|
VOICE_REFERENCES = {
|
||||||
|
"zh": "aebaa2305aa2452fbdc8f41eec852a79",
|
||||||
|
"en": "e58b0d7efca34eb38d5c4985e378abcb",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Test texts in different languages (20 sentences each)
|
||||||
|
TEST_TEXTS = {
|
||||||
|
"zh": [
|
||||||
|
"今天天气真好",
|
||||||
|
"我很高兴认识你",
|
||||||
|
"这个问题有点复杂",
|
||||||
|
"让我想一想",
|
||||||
|
"你说得对",
|
||||||
|
"我明白你的意思了",
|
||||||
|
"这件事情很重要",
|
||||||
|
"我们一起努力吧",
|
||||||
|
"谢谢你的帮助",
|
||||||
|
"请稍等一下",
|
||||||
|
"我有一个想法",
|
||||||
|
"这真是太棒了",
|
||||||
|
"我需要更多时间",
|
||||||
|
"你觉得怎么样",
|
||||||
|
"让我们开始吧",
|
||||||
|
"我不太确定",
|
||||||
|
"这是个好主意",
|
||||||
|
"我会尽力的",
|
||||||
|
"请告诉我更多",
|
||||||
|
"我们来看看",
|
||||||
|
],
|
||||||
|
"en": [
|
||||||
|
"The weather is nice today",
|
||||||
|
"Nice to meet you",
|
||||||
|
"This is a bit complicated",
|
||||||
|
"Let me think about it",
|
||||||
|
"You are right",
|
||||||
|
"I understand what you mean",
|
||||||
|
"This is very important",
|
||||||
|
"Let us work together",
|
||||||
|
"Thank you for your help",
|
||||||
|
"Please wait a moment",
|
||||||
|
"I have an idea",
|
||||||
|
"This is amazing",
|
||||||
|
"I need more time",
|
||||||
|
"What do you think",
|
||||||
|
"Let us get started",
|
||||||
|
"I am not sure",
|
||||||
|
"That is a good idea",
|
||||||
|
"I will do my best",
|
||||||
|
"Please tell me more",
|
||||||
|
"Let us take a look",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
# Default: test all emotion tags
|
||||||
|
DEFAULT_TEST_EMOTIONS = EMOTION_TAGS
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TestCase:
|
||||||
|
"""Single test case configuration"""
|
||||||
|
emotion: str
|
||||||
|
text: str
|
||||||
|
lang: str
|
||||||
|
input_text: str = field(init=False)
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.input_text = f"({self.emotion}) {self.text}"
|
||||||
|
if self.lang == "en":
|
||||||
|
self.input_text += "."
|
||||||
|
else:
|
||||||
|
self.input_text += "。"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TestResult:
|
||||||
|
"""Single test result"""
|
||||||
|
test_case: TestCase
|
||||||
|
transcript: str
|
||||||
|
tag_leaked: bool # True if emotion tag was read aloud
|
||||||
|
text_match: bool # True if transcript matches expected text
|
||||||
|
audio_duration_ms: float
|
||||||
|
success: bool
|
||||||
|
error: str = ""
|
||||||
|
audio_file: str = "" # Path to saved audio file (for failed cases)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class TestConfig:
|
||||||
|
"""Test configuration"""
|
||||||
|
api_key: str
|
||||||
|
groq_api_key: str
|
||||||
|
voice_references: dict # {lang: reference_id}
|
||||||
|
sample_rate: int = 16000
|
||||||
|
format: str = "pcm"
|
||||||
|
whisper_model: str = "whisper-large-v3" # Groq whisper model
|
||||||
|
emotions: list = field(default_factory=lambda: DEFAULT_TEST_EMOTIONS)
|
||||||
|
languages: list = field(default_factory=lambda: ["zh", "en"])
|
||||||
|
|
||||||
|
def get_reference_id(self, lang: str) -> str:
|
||||||
|
"""Get voice reference ID for a specific language"""
|
||||||
|
return self.voice_references.get(lang, "")
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionTagTester:
|
||||||
|
"""Emotion tag testing class"""
|
||||||
|
|
||||||
|
# Groq API base URL (OpenAI compatible)
|
||||||
|
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
||||||
|
|
||||||
|
def __init__(self, config: TestConfig):
|
||||||
|
self.config = config
|
||||||
|
self.client = AsyncFishAudio(api_key=config.api_key)
|
||||||
|
self.groq_client = OpenAI(
|
||||||
|
api_key=config.groq_api_key,
|
||||||
|
base_url=self.GROQ_BASE_URL
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create tmp directory for failed audio files
|
||||||
|
self.tmp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
|
||||||
|
os.makedirs(self.tmp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
|
||||||
|
"""Convert PCM to WAV format for ASR"""
|
||||||
|
wav_buffer = io.BytesIO()
|
||||||
|
with wave.open(wav_buffer, 'wb') as wav_file:
|
||||||
|
wav_file.setnchannels(1)
|
||||||
|
wav_file.setsampwidth(2) # 16-bit
|
||||||
|
wav_file.setframerate(self.config.sample_rate)
|
||||||
|
wav_file.writeframes(pcm_data)
|
||||||
|
return wav_buffer.getvalue()
|
||||||
|
|
||||||
|
def _save_failed_audio(self, test_case: TestCase, audio_data: bytes) -> str:
|
||||||
|
"""Save failed audio to tmp directory"""
|
||||||
|
# Generate filename: {emotion}_{lang}_{text_hash}.wav
|
||||||
|
text_hash = hash(test_case.text) & 0xFFFFFF # 6 hex chars
|
||||||
|
filename = f"{test_case.emotion}_{test_case.lang}_{text_hash:06x}.wav"
|
||||||
|
filepath = os.path.join(self.tmp_dir, filename)
|
||||||
|
|
||||||
|
wav_data = self._pcm_to_wav(audio_data)
|
||||||
|
with open(filepath, "wb") as f:
|
||||||
|
f.write(wav_data)
|
||||||
|
|
||||||
|
return filepath
|
||||||
|
|
||||||
|
def _transcribe(self, audio_data: bytes, lang: str) -> str:
|
||||||
|
"""Transcribe audio using Groq Whisper API"""
|
||||||
|
# Save to temp file (API needs file)
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
|
||||||
|
wav_data = self._pcm_to_wav(audio_data)
|
||||||
|
f.write(wav_data)
|
||||||
|
temp_path = f.name
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(temp_path, "rb") as audio_file:
|
||||||
|
response = self.groq_client.audio.transcriptions.create(
|
||||||
|
model=self.config.whisper_model,
|
||||||
|
file=audio_file,
|
||||||
|
language=lang if lang != "zh" else "zh",
|
||||||
|
)
|
||||||
|
return response.text.strip()
|
||||||
|
finally:
|
||||||
|
os.unlink(temp_path)
|
||||||
|
|
||||||
|
def _normalize_text(self, text: str) -> str:
|
||||||
|
"""Normalize text for comparison"""
|
||||||
|
# Remove punctuation and convert to lowercase
|
||||||
|
import re
|
||||||
|
text = re.sub(r'[^\w\s]', '', text)
|
||||||
|
return text.lower().strip()
|
||||||
|
|
||||||
|
def _check_tag_leaked(self, transcript: str, emotion: str) -> bool:
|
||||||
|
"""Check if emotion tag was read aloud"""
|
||||||
|
normalized = self._normalize_text(transcript)
|
||||||
|
emotion_lower = emotion.lower()
|
||||||
|
|
||||||
|
# Check for exact emotion word
|
||||||
|
if emotion_lower in normalized.split():
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Check for common mispronunciations/variations
|
||||||
|
variations = {
|
||||||
|
"happy": ["happy", "hapi", "happie"],
|
||||||
|
"sad": ["sad", "sæd"],
|
||||||
|
"calm": ["calm", "kam", "come"],
|
||||||
|
"surprised": ["surprised", "surprise"],
|
||||||
|
"curious": ["curious", "curios"],
|
||||||
|
"worried": ["worried", "worry"],
|
||||||
|
"frustrated": ["frustrated", "frustrate"],
|
||||||
|
"confident": ["confident", "confidence"],
|
||||||
|
"sincere": ["sincere", "sincer"],
|
||||||
|
"sarcastic": ["sarcastic", "sarcasm"],
|
||||||
|
}
|
||||||
|
|
||||||
|
for var in variations.get(emotion_lower, [emotion_lower]):
|
||||||
|
if var in normalized:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _check_text_match(self, transcript: str, expected: str) -> bool:
|
||||||
|
"""Check if transcript matches expected text (fuzzy)"""
|
||||||
|
norm_transcript = self._normalize_text(transcript)
|
||||||
|
norm_expected = self._normalize_text(expected)
|
||||||
|
|
||||||
|
# Simple word overlap ratio
|
||||||
|
transcript_words = set(norm_transcript.split())
|
||||||
|
expected_words = set(norm_expected.split())
|
||||||
|
|
||||||
|
if not expected_words:
|
||||||
|
return True
|
||||||
|
|
||||||
|
overlap = len(transcript_words & expected_words)
|
||||||
|
ratio = overlap / len(expected_words)
|
||||||
|
|
||||||
|
return ratio >= 0.5 # At least 50% word match
|
||||||
|
|
||||||
|
async def run_test(self, test_case: TestCase) -> TestResult:
|
||||||
|
"""Run a single test case"""
|
||||||
|
try:
|
||||||
|
tts_config = TTSConfig(
|
||||||
|
format=self.config.format,
|
||||||
|
model="s1",
|
||||||
|
sample_rate=self.config.sample_rate,
|
||||||
|
normalize=True,
|
||||||
|
latency="balanced",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get voice reference ID for this language
|
||||||
|
reference_id = self.config.get_reference_id(test_case.lang)
|
||||||
|
if not reference_id:
|
||||||
|
return TestResult(
|
||||||
|
test_case=test_case,
|
||||||
|
transcript="",
|
||||||
|
tag_leaked=False,
|
||||||
|
text_match=False,
|
||||||
|
audio_duration_ms=0,
|
||||||
|
success=False,
|
||||||
|
error=f"No voice reference ID configured for language: {test_case.lang}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Generate TTS audio
|
||||||
|
audio_data = b''
|
||||||
|
audio_stream = await self.client.tts.stream(
|
||||||
|
text=test_case.input_text,
|
||||||
|
reference_id=reference_id,
|
||||||
|
model="s1",
|
||||||
|
config=tts_config,
|
||||||
|
)
|
||||||
|
|
||||||
|
async for chunk in audio_stream:
|
||||||
|
if chunk:
|
||||||
|
audio_data += chunk
|
||||||
|
|
||||||
|
if not audio_data:
|
||||||
|
return TestResult(
|
||||||
|
test_case=test_case,
|
||||||
|
transcript="",
|
||||||
|
tag_leaked=False,
|
||||||
|
text_match=False,
|
||||||
|
audio_duration_ms=0,
|
||||||
|
success=False,
|
||||||
|
error="No audio data received"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Calculate audio duration
|
||||||
|
audio_duration_ms = len(audio_data) / (self.config.sample_rate * 2) * 1000
|
||||||
|
|
||||||
|
# Transcribe
|
||||||
|
transcript = self._transcribe(audio_data, test_case.lang)
|
||||||
|
|
||||||
|
# Check results
|
||||||
|
tag_leaked = self._check_tag_leaked(transcript, test_case.emotion)
|
||||||
|
text_match = self._check_text_match(transcript, test_case.text)
|
||||||
|
|
||||||
|
# Save audio if tag leaked
|
||||||
|
audio_file = ""
|
||||||
|
if tag_leaked:
|
||||||
|
audio_file = self._save_failed_audio(test_case, audio_data)
|
||||||
|
|
||||||
|
return TestResult(
|
||||||
|
test_case=test_case,
|
||||||
|
transcript=transcript,
|
||||||
|
tag_leaked=tag_leaked,
|
||||||
|
text_match=text_match,
|
||||||
|
audio_duration_ms=audio_duration_ms,
|
||||||
|
success=True,
|
||||||
|
audio_file=audio_file
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return TestResult(
|
||||||
|
test_case=test_case,
|
||||||
|
transcript="",
|
||||||
|
tag_leaked=False,
|
||||||
|
text_match=False,
|
||||||
|
audio_duration_ms=0,
|
||||||
|
success=False,
|
||||||
|
error=str(e)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def run_all_tests(self) -> list[TestResult]:
|
||||||
|
"""Run all test cases"""
|
||||||
|
results = []
|
||||||
|
|
||||||
|
# Generate test cases: organized by language -> emotion -> texts
|
||||||
|
test_cases = []
|
||||||
|
for lang in self.config.languages:
|
||||||
|
texts = TEST_TEXTS.get(lang, [])
|
||||||
|
for emotion in self.config.emotions:
|
||||||
|
for text in texts:
|
||||||
|
test_cases.append(TestCase(emotion=emotion, text=text, lang=lang))
|
||||||
|
|
||||||
|
total = len(test_cases)
|
||||||
|
num_emotions = len(self.config.emotions)
|
||||||
|
num_texts = len(TEST_TEXTS.get(self.config.languages[0], []))
|
||||||
|
|
||||||
|
print(f"\n🧪 Test Plan:")
|
||||||
|
print(f" Languages: {self.config.languages}")
|
||||||
|
print(f" Emotion Tags: {num_emotions}")
|
||||||
|
print(f" Sentences per Tag: {num_texts}")
|
||||||
|
print(f" Total Test Cases: {total}")
|
||||||
|
|
||||||
|
leaked_count = 0
|
||||||
|
current_lang = None
|
||||||
|
current_emotion = None
|
||||||
|
|
||||||
|
for i, tc in enumerate(test_cases, 1):
|
||||||
|
# Print progress header when language or emotion changes
|
||||||
|
if tc.lang != current_lang:
|
||||||
|
current_lang = tc.lang
|
||||||
|
print(f"\n{'='*60}")
|
||||||
|
print(f"📍 Language: {current_lang.upper()}")
|
||||||
|
print(f"{'='*60}")
|
||||||
|
|
||||||
|
if tc.emotion != current_emotion:
|
||||||
|
current_emotion = tc.emotion
|
||||||
|
print(f"\n🏷️ Testing emotion: {current_emotion}")
|
||||||
|
|
||||||
|
# Run test
|
||||||
|
result = await self.run_test(tc)
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
|
# Compact progress output
|
||||||
|
if result.success:
|
||||||
|
if result.tag_leaked:
|
||||||
|
leaked_count += 1
|
||||||
|
print(f" ❌ [{i}/{total}] LEAKED: \"{tc.text[:20]}...\" → \"{result.transcript[:30]}...\"")
|
||||||
|
if result.audio_file:
|
||||||
|
print(f" 📁 Saved: {os.path.basename(result.audio_file)}")
|
||||||
|
else:
|
||||||
|
# Only show dot for success to keep output clean
|
||||||
|
print(f" ✓ [{i}/{total}] OK", end="\r")
|
||||||
|
else:
|
||||||
|
print(f" ⚠️ [{i}/{total}] ERROR: {result.error[:50]}")
|
||||||
|
|
||||||
|
# Small delay between requests
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
|
||||||
|
# Final summary
|
||||||
|
print(f"\n\n{'='*60}")
|
||||||
|
print(f"📊 Test Complete: {total} tests, {leaked_count} leaks")
|
||||||
|
print(f"{'='*60}")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def generate_report(results: list[TestResult], config: TestConfig) -> str:
|
||||||
|
"""Generate markdown report"""
|
||||||
|
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
# Statistics
|
||||||
|
total = len(results)
|
||||||
|
successful = sum(1 for r in results if r.success)
|
||||||
|
leaked = sum(1 for r in results if r.success and r.tag_leaked)
|
||||||
|
matched = sum(1 for r in results if r.success and r.text_match)
|
||||||
|
|
||||||
|
# Build voice references string
|
||||||
|
voice_refs_str = ", ".join([f"{lang.upper()}: `{config.voice_references.get(lang, 'N/A')}`" for lang in config.languages])
|
||||||
|
|
||||||
|
# Calculate sentences per tag
|
||||||
|
num_sentences = len(TEST_TEXTS.get(config.languages[0], []))
|
||||||
|
|
||||||
|
report = f"""# Fish Speech Emotion Tag Test Report
|
||||||
|
|
||||||
|
**Generated:** {now}
|
||||||
|
**Voice References:** {voice_refs_str}
|
||||||
|
**ASR Model:** Groq {config.whisper_model}
|
||||||
|
**Languages:** {', '.join(config.languages)}
|
||||||
|
**Emotion Tags:** {len(config.emotions)}
|
||||||
|
**Sentences per Tag:** {num_sentences}
|
||||||
|
**Total Tests:** {total}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
| Metric | Count | Percentage |
|
||||||
|
|--------|-------|------------|
|
||||||
|
| Total Tests | {total} | 100% |
|
||||||
|
| Successful | {successful} | {successful/total*100:.1f}% |
|
||||||
|
| **Tag Leaked** | **{leaked}** | **{leaked/successful*100:.1f}%** |
|
||||||
|
| Text Matched | {matched} | {matched/successful*100:.1f}% |
|
||||||
|
|
||||||
|
### Interpretation
|
||||||
|
|
||||||
|
- **Tag Leaked = 0**: ✅ Fish Speech correctly handles emotion tags (not read aloud)
|
||||||
|
- **Tag Leaked > 0**: ⚠️ Fish Speech may be reading emotion tags as text
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Leak Rate by Emotion Tag & Language
|
||||||
|
|
||||||
|
This is the main summary table showing leak rate for each emotion tag across languages.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Build main summary table: Emotion x Language
|
||||||
|
report += "| Emotion Tag |"
|
||||||
|
for lang in config.languages:
|
||||||
|
report += f" {lang.upper()} |"
|
||||||
|
report += " Overall |\n"
|
||||||
|
|
||||||
|
report += "|-------------|"
|
||||||
|
for _ in config.languages:
|
||||||
|
report += "--------|"
|
||||||
|
report += "---------|\n"
|
||||||
|
|
||||||
|
for emotion in config.emotions:
|
||||||
|
report += f"| {emotion} |"
|
||||||
|
|
||||||
|
total_leaked = 0
|
||||||
|
total_count = 0
|
||||||
|
|
||||||
|
for lang in config.languages:
|
||||||
|
lang_emo_results = [
|
||||||
|
r for r in results
|
||||||
|
if r.test_case.emotion == emotion
|
||||||
|
and r.test_case.lang == lang
|
||||||
|
and r.success
|
||||||
|
]
|
||||||
|
lang_leaked = sum(1 for r in lang_emo_results if r.tag_leaked)
|
||||||
|
lang_count = len(lang_emo_results)
|
||||||
|
|
||||||
|
total_leaked += lang_leaked
|
||||||
|
total_count += lang_count
|
||||||
|
|
||||||
|
if lang_count > 0:
|
||||||
|
rate = lang_leaked / lang_count * 100
|
||||||
|
status = "✅" if lang_leaked == 0 else "⚠️"
|
||||||
|
report += f" {lang_leaked}/{lang_count} ({rate:.0f}%) {status} |"
|
||||||
|
else:
|
||||||
|
report += " N/A |"
|
||||||
|
|
||||||
|
# Overall for this emotion
|
||||||
|
if total_count > 0:
|
||||||
|
overall_rate = total_leaked / total_count * 100
|
||||||
|
overall_status = "✅" if total_leaked == 0 else "⚠️"
|
||||||
|
report += f" {total_leaked}/{total_count} ({overall_rate:.0f}%) {overall_status} |\n"
|
||||||
|
else:
|
||||||
|
report += " N/A |\n"
|
||||||
|
|
||||||
|
# Language summary row
|
||||||
|
report += "| **Total** |"
|
||||||
|
grand_total_leaked = 0
|
||||||
|
grand_total_count = 0
|
||||||
|
|
||||||
|
for lang in config.languages:
|
||||||
|
lang_results = [r for r in results if r.test_case.lang == lang and r.success]
|
||||||
|
lang_leaked = sum(1 for r in lang_results if r.tag_leaked)
|
||||||
|
lang_count = len(lang_results)
|
||||||
|
|
||||||
|
grand_total_leaked += lang_leaked
|
||||||
|
grand_total_count += lang_count
|
||||||
|
|
||||||
|
if lang_count > 0:
|
||||||
|
rate = lang_leaked / lang_count * 100
|
||||||
|
report += f" **{lang_leaked}/{lang_count} ({rate:.0f}%)** |"
|
||||||
|
else:
|
||||||
|
report += " N/A |"
|
||||||
|
|
||||||
|
if grand_total_count > 0:
|
||||||
|
overall_rate = grand_total_leaked / grand_total_count * 100
|
||||||
|
report += f" **{grand_total_leaked}/{grand_total_count} ({overall_rate:.0f}%)** |\n"
|
||||||
|
else:
|
||||||
|
report += " N/A |\n"
|
||||||
|
|
||||||
|
report += "\n---\n\n"
|
||||||
|
|
||||||
|
# Detailed failures
|
||||||
|
failures = [r for r in results if r.success and r.tag_leaked]
|
||||||
|
if failures:
|
||||||
|
report += "## ⚠️ Failed Cases (Tag Leaked)\n\n"
|
||||||
|
report += "Audio files saved in `tmp/` directory.\n\n"
|
||||||
|
|
||||||
|
# Group by emotion
|
||||||
|
from collections import defaultdict
|
||||||
|
failures_by_emotion = defaultdict(list)
|
||||||
|
for r in failures:
|
||||||
|
failures_by_emotion[r.test_case.emotion].append(r)
|
||||||
|
|
||||||
|
for emotion in sorted(failures_by_emotion.keys()):
|
||||||
|
report += f"### {emotion}\n\n"
|
||||||
|
report += "| Language | Input Text | Transcript | Audio File |\n"
|
||||||
|
report += "|----------|------------|------------|------------|\n"
|
||||||
|
|
||||||
|
for r in failures_by_emotion[emotion]:
|
||||||
|
input_short = r.test_case.input_text[:40] + "..." if len(r.test_case.input_text) > 40 else r.test_case.input_text
|
||||||
|
trans_short = r.transcript[:40] + "..." if len(r.transcript) > 40 else r.transcript
|
||||||
|
audio_name = os.path.basename(r.audio_file) if r.audio_file else "N/A"
|
||||||
|
report += f"| {r.test_case.lang.upper()} | {input_short} | {trans_short} | `{audio_name}` |\n"
|
||||||
|
|
||||||
|
report += "\n"
|
||||||
|
|
||||||
|
# Errors
|
||||||
|
errors = [r for r in results if not r.success]
|
||||||
|
if errors:
|
||||||
|
report += "---\n\n## Errors\n\n"
|
||||||
|
for r in errors:
|
||||||
|
report += f"- [{r.test_case.lang.upper()}] {r.test_case.emotion}: {r.error}\n"
|
||||||
|
report += "\n"
|
||||||
|
|
||||||
|
report += """---
|
||||||
|
|
||||||
|
## Conclusion
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
if leaked == 0:
|
||||||
|
report += "✅ **All emotion tags were correctly handled** - Fish Speech does not read emotion tags aloud.\n"
|
||||||
|
else:
|
||||||
|
leak_rate = leaked / successful * 100 if successful > 0 else 0
|
||||||
|
report += f"⚠️ **{leaked} out of {successful} tests had tag leaks ({leak_rate:.1f}%)**\n\n"
|
||||||
|
|
||||||
|
# Find problematic emotions
|
||||||
|
problematic = []
|
||||||
|
for emotion in config.emotions:
|
||||||
|
emo_results = [r for r in results if r.test_case.emotion == emotion and r.success]
|
||||||
|
emo_leaked = sum(1 for r in emo_results if r.tag_leaked)
|
||||||
|
if emo_leaked > 0:
|
||||||
|
rate = emo_leaked / len(emo_results) * 100
|
||||||
|
problematic.append((emotion, rate))
|
||||||
|
|
||||||
|
if problematic:
|
||||||
|
problematic.sort(key=lambda x: -x[1])
|
||||||
|
report += "**Most problematic emotion tags:**\n"
|
||||||
|
for emotion, rate in problematic[:5]:
|
||||||
|
report += f"- `{emotion}`: {rate:.0f}% leak rate\n"
|
||||||
|
|
||||||
|
report += "\n---\n\n*Generated by Fish Speech Emotion Tag Tester*\n"
|
||||||
|
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args():
|
||||||
|
"""Parse command line arguments"""
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Fish Speech Emotion Tag Test - Test if emotion tags are correctly handled",
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
|
epilog="""
|
||||||
|
Examples:
|
||||||
|
# Test a single emotion tag
|
||||||
|
python test_emotion_tag.py --tag happy
|
||||||
|
|
||||||
|
# Test multiple tags
|
||||||
|
python test_emotion_tag.py --tag happy --tag sad --tag calm
|
||||||
|
|
||||||
|
# Run all tests
|
||||||
|
python test_emotion_tag.py
|
||||||
|
|
||||||
|
# List all available emotion tags
|
||||||
|
python test_emotion_tag.py --list-tags
|
||||||
|
|
||||||
|
Environment Variables:
|
||||||
|
FISH_API_KEY Fish Audio API key (required)
|
||||||
|
GROQ_API_KEY Groq API key for ASR (required)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--tag", "-t",
|
||||||
|
action="append",
|
||||||
|
dest="tags",
|
||||||
|
metavar="EMOTION",
|
||||||
|
help="Emotion tag(s) to test (can be specified multiple times). Default: all tags"
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--list-tags",
|
||||||
|
action="store_true",
|
||||||
|
help="List all available emotion tags and exit"
|
||||||
|
)
|
||||||
|
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
args = parse_args()
|
||||||
|
|
||||||
|
# Handle --list-tags
|
||||||
|
if args.list_tags:
|
||||||
|
print("Available emotion tags:")
|
||||||
|
for i, tag in enumerate(EMOTION_TAGS, 1):
|
||||||
|
print(f" {i:2}. {tag}")
|
||||||
|
print(f"\nTotal: {len(EMOTION_TAGS)} tags")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
print("🏷️ Fish Speech Emotion Tag 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)
|
||||||
|
|
||||||
|
groq_api_key = os.environ.get("GROQ_API_KEY")
|
||||||
|
if not groq_api_key:
|
||||||
|
print("\n❌ Error: GROQ_API_KEY not set")
|
||||||
|
print(" export GROQ_API_KEY='your-key'")
|
||||||
|
print("\n💡 Get your API key from: https://console.groq.com/")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Voice references from fixed config
|
||||||
|
voice_references = VOICE_REFERENCES.copy()
|
||||||
|
whisper_model = "whisper-large-v3"
|
||||||
|
|
||||||
|
# Emotions: CLI --tag or all
|
||||||
|
if args.tags:
|
||||||
|
# Validate tags
|
||||||
|
invalid_tags = [t for t in args.tags if t not in EMOTION_TAGS]
|
||||||
|
if invalid_tags:
|
||||||
|
print(f"\n❌ Invalid emotion tag(s): {invalid_tags}")
|
||||||
|
print(f" Use --list-tags to see available tags")
|
||||||
|
sys.exit(1)
|
||||||
|
emotions = args.tags
|
||||||
|
else:
|
||||||
|
emotions = DEFAULT_TEST_EMOTIONS
|
||||||
|
|
||||||
|
# Languages: always test both
|
||||||
|
languages = ["zh", "en"]
|
||||||
|
|
||||||
|
# Calculate sentence count
|
||||||
|
all_texts = TEST_TEXTS.get(languages[0], [])
|
||||||
|
num_sentences = len(all_texts)
|
||||||
|
|
||||||
|
# Validate voice references for selected languages
|
||||||
|
missing_voices = [lang for lang in languages if not voice_references.get(lang)]
|
||||||
|
if missing_voices:
|
||||||
|
print(f"\n❌ Error: Missing voice reference ID for language(s): {missing_voices}")
|
||||||
|
print(" Please configure VOICE_REFERENCES in test_emotion_tag.py")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
config = TestConfig(
|
||||||
|
api_key=api_key,
|
||||||
|
groq_api_key=groq_api_key,
|
||||||
|
voice_references=voice_references,
|
||||||
|
whisper_model=whisper_model,
|
||||||
|
emotions=emotions,
|
||||||
|
languages=languages,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"\n📋 Configuration:")
|
||||||
|
print(f" Groq ASR Model: {whisper_model}")
|
||||||
|
print(f" Languages & Voices:")
|
||||||
|
for lang in languages:
|
||||||
|
ref_id = voice_references.get(lang, "N/A")
|
||||||
|
print(f" {lang.upper()}: {ref_id}")
|
||||||
|
print(f" Emotion Tags: {len(emotions)} ({', '.join(emotions[:5])}{'...' if len(emotions) > 5 else ''})")
|
||||||
|
print(f" Sentences per Tag: {num_sentences}")
|
||||||
|
print(f" Estimated Tests: {len(emotions) * len(languages) * num_sentences}")
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
tester = EmotionTagTester(config)
|
||||||
|
results = await tester.run_all_tests()
|
||||||
|
|
||||||
|
# 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"emotion_tag_report_{timestamp}.md")
|
||||||
|
|
||||||
|
with open(report_file, "w", encoding="utf-8") as f:
|
||||||
|
f.write(report)
|
||||||
|
|
||||||
|
print(f"\n✅ Report saved to: {report_file}")
|
||||||
|
|
||||||
|
# Print summary
|
||||||
|
print("\n" + "=" * 50)
|
||||||
|
print("📈 Quick Summary")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
total = len(results)
|
||||||
|
successful = sum(1 for r in results if r.success)
|
||||||
|
leaked = sum(1 for r in results if r.success and r.tag_leaked)
|
||||||
|
saved_audio = sum(1 for r in results if r.audio_file)
|
||||||
|
|
||||||
|
print(f"\n Total Tests: {total}")
|
||||||
|
print(f" Successful: {successful}")
|
||||||
|
print(f" Tag Leaked: {leaked}")
|
||||||
|
|
||||||
|
if leaked == 0:
|
||||||
|
print("\n✅ All emotion tags handled correctly!")
|
||||||
|
else:
|
||||||
|
print(f"\n⚠️ {leaked} emotion tags were incorrectly read aloud!")
|
||||||
|
if saved_audio > 0:
|
||||||
|
print(f"📁 {saved_audio} audio files saved to: {tester.tmp_dir}")
|
||||||
|
|
||||||
|
print("\n✅ Test completed!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
601
main/xiaozhi-server/test/tts_test/test_fish_latency.py
Normal file
601
main/xiaozhi-server/test/tts_test/test_fish_latency.py
Normal file
|
|
@ -0,0 +1,601 @@
|
||||||
|
#!/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 ""
|
||||||
|
start_time = time.perf_counter()
|
||||||
|
self.client.tts.stream_websocket(
|
||||||
|
init_websocket(),
|
||||||
|
reference_id=self.config.reference_id,
|
||||||
|
config=tts_config,
|
||||||
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
# yield token
|
||||||
|
# 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())
|
||||||
|
|
||||||
Loading…
Reference in a new issue