mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
silicon flow is added
This commit is contained in:
parent
a68b8ffa18
commit
65be4a18ae
4 changed files with 242 additions and 21 deletions
|
|
@ -1,50 +1,131 @@
|
|||
import requests
|
||||
import json
|
||||
from core.utils.util import check_model_key
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
from config.logger import setup_logging
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
class TTSProvider(TTSProviderBase):
|
||||
"""
|
||||
SiliconFlow CosyVoice TTS Provider
|
||||
Supports high-quality voice synthesis with CosyVoice models
|
||||
"""
|
||||
|
||||
def __init__(self, config, delete_audio_file):
|
||||
super().__init__(config, delete_audio_file)
|
||||
self.model = config.get("model")
|
||||
self.access_token = config.get("access_token")
|
||||
|
||||
# API configuration
|
||||
self.access_token = config.get("access_token")
|
||||
if not self.access_token:
|
||||
raise ValueError("SiliconFlow access token is required")
|
||||
|
||||
# Model configuration - default to CosyVoice2-0.5B
|
||||
self.model = config.get("model", "FunAudioLLM/CosyVoice2-0.5B")
|
||||
|
||||
# Voice configuration - default to diana with model prefix
|
||||
if config.get("private_voice"):
|
||||
self.voice = config.get("private_voice")
|
||||
else:
|
||||
self.voice = config.get("voice")
|
||||
voice_name = config.get("voice", "diana")
|
||||
# If voice doesn't already contain model prefix, add it
|
||||
if ":" not in voice_name:
|
||||
self.voice = f"{self.model}:{voice_name}"
|
||||
else:
|
||||
self.voice = voice_name
|
||||
|
||||
# Audio format configuration
|
||||
self.response_format = config.get("response_format", "mp3")
|
||||
self.audio_file_type = config.get("response_format", "mp3")
|
||||
self.sample_rate = config.get("sample_rate")
|
||||
self.audio_file_type = self.response_format
|
||||
|
||||
# Audio parameters
|
||||
self.speed = float(config.get("speed", 1.0))
|
||||
self.gain = config.get("gain")
|
||||
self.host = "api.siliconflow.cn"
|
||||
self.api_url = f"https://{self.host}/v1/audio/speech"
|
||||
self.gain = config.get("gain", 0)
|
||||
|
||||
# API endpoint
|
||||
self.api_url = "https://api.siliconflow.com/v1/audio/speech"
|
||||
|
||||
# Validate API key
|
||||
model_key_msg = check_model_key("SiliconFlow TTS", self.access_token)
|
||||
if model_key_msg:
|
||||
logger.bind(tag=TAG).error(model_key_msg)
|
||||
|
||||
if self.access_token and len(self.access_token) < 32:
|
||||
logger.bind(tag=TAG).warning(
|
||||
"SiliconFlow access token appears to be too short. Please check your token.")
|
||||
|
||||
logger.bind(tag=TAG).info(f"SiliconFlow TTS initialized with model: {self.model}, voice: {self.voice}")
|
||||
|
||||
async def text_to_speak(self, text, output_file):
|
||||
request_json = {
|
||||
"model": self.model,
|
||||
"""
|
||||
Convert text to speech using SiliconFlow CosyVoice API
|
||||
"""
|
||||
# Prepare request payload - based on your original API example
|
||||
payload = {
|
||||
"input": text,
|
||||
"voice": self.voice,
|
||||
"response_format": self.response_format,
|
||||
"stream": True, # Enable streaming as in your example
|
||||
"speed": self.speed,
|
||||
"gain": self.gain,
|
||||
"model": self.model
|
||||
}
|
||||
|
||||
# Add voice parameter with model prefix (e.g., FunAudioLLM/CosyVoice2-0.5B:diana)
|
||||
if self.voice:
|
||||
payload["voice"] = self.voice
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.access_token}",
|
||||
"Content-Type": "application/json",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.request(
|
||||
"POST", self.api_url, json=request_json, headers=headers
|
||||
logger.bind(tag=TAG).debug(f"SiliconFlow TTS request: {text[:50]}...")
|
||||
|
||||
response = requests.post(
|
||||
self.api_url,
|
||||
json=payload,
|
||||
headers=headers,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
data = response.content
|
||||
|
||||
if output_file:
|
||||
with open(output_file, "wb") as file_to_save:
|
||||
file_to_save.write(data)
|
||||
if response.status_code == 200:
|
||||
if output_file:
|
||||
with open(output_file, "wb") as audio_file:
|
||||
audio_file.write(response.content)
|
||||
logger.bind(tag=TAG).debug(f"SiliconFlow TTS saved to: {output_file}")
|
||||
else:
|
||||
return response.content
|
||||
else:
|
||||
return data
|
||||
# Try to parse error response
|
||||
try:
|
||||
error_data = response.json()
|
||||
except:
|
||||
error_data = response.text
|
||||
|
||||
raise Exception(
|
||||
f"SiliconFlow TTS request failed: {response.status_code} - {error_data}"
|
||||
)
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
raise Exception("SiliconFlow TTS request timed out")
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise Exception(f"SiliconFlow TTS network error: {str(e)}")
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"{__name__} error: {e}")
|
||||
logger.bind(tag=TAG).error(f"SiliconFlow TTS error: {str(e)}")
|
||||
raise
|
||||
|
||||
def get_available_voices(self):
|
||||
"""
|
||||
Helper method to get available voices for CosyVoice
|
||||
Returns voices with model prefix format
|
||||
"""
|
||||
model_prefix = self.model
|
||||
return [
|
||||
(f"{model_prefix}:diana", "Diana (Female)"),
|
||||
(f"{model_prefix}:alex", "Alex (Male)"),
|
||||
(f"{model_prefix}:bella", "Bella (Female)"),
|
||||
]
|
||||
|
|
|
|||
BIN
main/xiaozhi-server/test_diana_voice.mp3
Normal file
BIN
main/xiaozhi-server/test_diana_voice.mp3
Normal file
Binary file not shown.
85
main/xiaozhi-server/test_siliconflow_tts.py
Normal file
85
main/xiaozhi-server/test_siliconflow_tts.py
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script for SiliconFlow CosyVoice TTS Provider
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import asyncio
|
||||
import yaml
|
||||
|
||||
# Add the main directory to Python path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), 'main', 'xiaozhi-server'))
|
||||
|
||||
from core.providers.tts.siliconflow import TTSProvider
|
||||
|
||||
def load_config():
|
||||
"""Load configuration from .config.yaml"""
|
||||
# Try different possible paths
|
||||
possible_paths = [
|
||||
os.path.join(os.path.dirname(__file__), 'data', '.config.yaml'),
|
||||
os.path.join(os.path.dirname(__file__), 'main', 'xiaozhi-server', 'data', '.config.yaml'),
|
||||
'data/.config.yaml'
|
||||
]
|
||||
|
||||
for config_path in possible_paths:
|
||||
try:
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = yaml.safe_load(f)
|
||||
print(f"✅ Loaded config from: {config_path}")
|
||||
return config.get('TTS', {}).get('siliconflow', {})
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
print("Warning: Could not load config from any expected location")
|
||||
return {}
|
||||
|
||||
async def test_siliconflow_tts():
|
||||
"""Test SiliconFlow TTS with diana voice"""
|
||||
|
||||
# Load configuration from .config.yaml
|
||||
config = load_config()
|
||||
|
||||
# Fallback configuration if config file not found
|
||||
if not config:
|
||||
config = {
|
||||
"model": "FunAudioLLM/CosyVoice2-0.5B",
|
||||
"access_token": "sk-kuyamprtzyvtetbnsyoysbbxuwqzyraldecobjetvdeowzte", # Replace with actual token
|
||||
"response_format": "mp3",
|
||||
"speed": 1,
|
||||
"gain": 0,
|
||||
"output_dir": "tmp/"
|
||||
}
|
||||
|
||||
try:
|
||||
# Initialize TTS provider
|
||||
tts_provider = TTSProvider(config, delete_audio_file=False)
|
||||
|
||||
# Test text
|
||||
test_text = "Hello, this is a test of SiliconFlow CosyVoice TTS with Diana voice."
|
||||
|
||||
# Generate speech
|
||||
output_file = "test_diana_voice.mp3"
|
||||
print(f"Generating speech for: {test_text}")
|
||||
print(f"Using voice: {tts_provider.voice or 'Default (model-based)'}")
|
||||
print(f"Using model: {tts_provider.model}")
|
||||
|
||||
await tts_provider.text_to_speak(test_text, output_file)
|
||||
|
||||
if os.path.exists(output_file):
|
||||
print(f"✅ Success! Audio file generated: {output_file}")
|
||||
print(f"File size: {os.path.getsize(output_file)} bytes")
|
||||
else:
|
||||
print("❌ Failed to generate audio file")
|
||||
|
||||
# Test available voices
|
||||
voices = tts_provider.get_available_voices()
|
||||
print(f"\nAvailable voices: {voices}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Testing SiliconFlow CosyVoice TTS Provider...")
|
||||
print("Note: You need to set a valid SiliconFlow access token in the config")
|
||||
asyncio.run(test_siliconflow_tts())
|
||||
55
main/xiaozhi-server/test_voice_format.py
Normal file
55
main/xiaozhi-server/test_voice_format.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify voice format handling
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the main directory to Python path
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), 'main', 'xiaozhi-server'))
|
||||
|
||||
from core.providers.tts.siliconflow import TTSProvider
|
||||
|
||||
def test_voice_format():
|
||||
"""Test that voice names are correctly formatted with model prefix"""
|
||||
|
||||
# Test configurations
|
||||
test_configs = [
|
||||
{
|
||||
"access_token": "test_token",
|
||||
"model": "FunAudioLLM/CosyVoice2-0.5B",
|
||||
"voice": "diana", # Should become FunAudioLLM/CosyVoice2-0.5B:diana
|
||||
},
|
||||
{
|
||||
"access_token": "test_token",
|
||||
"model": "FunAudioLLM/CosyVoice2-0.5B",
|
||||
"voice": "FunAudioLLM/CosyVoice2-0.5B:alex", # Should stay as is
|
||||
},
|
||||
{
|
||||
"access_token": "test_token",
|
||||
"model": "FunAudioLLM/CosyVoice2-0.5B",
|
||||
# No voice specified - should default to diana with prefix
|
||||
}
|
||||
]
|
||||
|
||||
for i, config in enumerate(test_configs):
|
||||
try:
|
||||
provider = TTSProvider(config, delete_audio_file=True)
|
||||
print(f"Test {i+1}:")
|
||||
print(f" Input voice: {config.get('voice', 'None (default)')}")
|
||||
print(f" Final voice: {provider.voice}")
|
||||
print(f" Model: {provider.model}")
|
||||
|
||||
# Test available voices
|
||||
voices = provider.get_available_voices()
|
||||
print(f" Available voices: {voices}")
|
||||
print()
|
||||
|
||||
except Exception as e:
|
||||
print(f"Test {i+1} failed: {e}")
|
||||
print()
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Testing SiliconFlow voice format handling...")
|
||||
test_voice_format()
|
||||
Loading…
Reference in a new issue