mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: minimax && deepgram && elevenlabs && cartesia
This commit is contained in:
parent
5d9e63f89b
commit
e24490880a
13 changed files with 704 additions and 47 deletions
|
|
@ -0,0 +1,43 @@
|
||||||
|
-- Add Deepgram TTS Provider and Model Configuration
|
||||||
|
|
||||||
|
-- ==================== Deepgram TTS ====================
|
||||||
|
|
||||||
|
-- Add Deepgram TTS Provider
|
||||||
|
DELETE FROM `ai_model_provider` WHERE id = 'TTS_Deepgram';
|
||||||
|
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
|
||||||
|
('TTS_Deepgram', 'TTS', 'deepgram', 'Deepgram TTS', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"model","label":"Model","type":"string"}]', 20, 1, NOW(), 1, NOW());
|
||||||
|
|
||||||
|
-- Add Deepgram TTS Model Configuration
|
||||||
|
DELETE FROM `ai_model_config` WHERE id = 'TTS_Deepgram';
|
||||||
|
INSERT INTO `ai_model_config` (
|
||||||
|
`id`,
|
||||||
|
`model_type`,
|
||||||
|
`model_code`,
|
||||||
|
`model_name`,
|
||||||
|
`is_default`,
|
||||||
|
`is_enabled`,
|
||||||
|
`config_json`,
|
||||||
|
`doc_link`,
|
||||||
|
`remark`,
|
||||||
|
`sort`,
|
||||||
|
`creator`,
|
||||||
|
`create_date`,
|
||||||
|
`updater`,
|
||||||
|
`update_date`
|
||||||
|
) VALUES (
|
||||||
|
'TTS_Deepgram',
|
||||||
|
'TTS',
|
||||||
|
'Deepgram',
|
||||||
|
'Deepgram TTS',
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
'{"type": "deepgram", "api_key": "", "model": "aura-2-thalia-en"}',
|
||||||
|
'https://developers.deepgram.com/docs/text-to-speech',
|
||||||
|
'Deepgram TTS Configuration:\n1. Deepgram provides high-quality, low-latency AI text-to-speech service\n2. Uses official Deepgram Python SDK (deepgram-sdk)\n3. Supports multiple languages and Aura 2 voice models\n4. API Key: Register at https://console.deepgram.com/ to get your API key\n5. Model: Deepgram voice models directly specify the voice (e.g., aura-2-thalia-en, aura-2-stella-en, aura-2-orion-en)\n6. Available Models:\n - Female: aura-2-asteria-en, aura-2-luna-en, aura-2-stella-en, aura-2-athena-en\n - Male: aura-2-orion-en, aura-2-arcas-en, aura-2-perseus-en, aura-2-zeus-en\n7. Features: Natural voices, multi-language support, low latency\n8. Perfect for real-time voice applications and conversational AI',
|
||||||
|
22,
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
|
@ -409,3 +409,10 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202511051120.sql
|
path: classpath:db/changelog/202511051120.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202511071245
|
||||||
|
author: harold
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202511071245.sql
|
||||||
|
|
|
||||||
|
|
@ -12,13 +12,7 @@ from typing import Optional, Callable, Dict, Any
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from core.providers.tts.dto.dto import InterfaceType
|
from core.providers.tts.dto.dto import InterfaceType
|
||||||
|
import cartesia
|
||||||
try:
|
|
||||||
import cartesia
|
|
||||||
except ImportError:
|
|
||||||
raise ImportError(
|
|
||||||
"Cartesia SDK not installed. Install with: pip install cartesia"
|
|
||||||
)
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -51,7 +45,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 标记为单流式接口
|
# 标记为单流式接口
|
||||||
self.interface_type = InterfaceType.SINGLE_STREAM
|
self.interface_type = InterfaceType.SINGLE_STREAM
|
||||||
# 设置音频文件类型为 WAV
|
# 设置音频文件类型为 WAV
|
||||||
self.audio_file_type = "wav"
|
self.audio_file_type = "pcm"
|
||||||
|
|
||||||
# 获取 API Key
|
# 获取 API Key
|
||||||
self.api_key = config.get("api_key") or os.environ.get("CARTESIA_API_KEY")
|
self.api_key = config.get("api_key") or os.environ.get("CARTESIA_API_KEY")
|
||||||
|
|
@ -81,7 +75,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 音频配置
|
# 音频配置
|
||||||
self.encoding = config.get("encoding", "pcm_s16le")
|
self.encoding = config.get("encoding", "pcm_s16le")
|
||||||
# 确保 sample_rate 是整数类型(配置文件可能返回字符串)
|
# 确保 sample_rate 是整数类型(配置文件可能返回字符串)
|
||||||
sample_rate_value = config.get("sample_rate", 24000)
|
sample_rate_value = config.get("sample_rate", 16000)
|
||||||
self.sample_rate = int(sample_rate_value) if isinstance(sample_rate_value, str) else sample_rate_value
|
self.sample_rate = int(sample_rate_value) if isinstance(sample_rate_value, str) else sample_rate_value
|
||||||
|
|
||||||
# 验证至少有一个 voice 配置
|
# 验证至少有一个 voice 配置
|
||||||
|
|
@ -102,7 +96,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
f"encoding={self.encoding}, sample_rate={self.sample_rate}"
|
f"encoding={self.encoding}, sample_rate={self.sample_rate}"
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _get_ws_client(self):
|
def _get_ws_client(self):
|
||||||
"""获取或创建 WebSocket 客户端(复用连接)"""
|
"""获取或创建 WebSocket 客户端(复用连接)"""
|
||||||
if self._ws_client is None:
|
if self._ws_client is None:
|
||||||
self._ws_client = self.client.tts.websocket()
|
self._ws_client = self.client.tts.websocket()
|
||||||
|
|
@ -134,11 +128,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
Returns:
|
Returns:
|
||||||
WAV 格式的完整音频字节数据
|
WAV 格式的完整音频字节数据
|
||||||
"""
|
"""
|
||||||
import io
|
|
||||||
import wave
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ws = await self._get_ws_client()
|
ws = self._get_ws_client()
|
||||||
|
|
||||||
pcm_chunks = []
|
pcm_chunks = []
|
||||||
voice = self._prepare_voice_param()
|
voice = self._prepare_voice_param()
|
||||||
|
|
@ -162,19 +153,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
# 合并所有 PCM 音频块
|
# 合并所有 PCM 音频块
|
||||||
pcm_data = b''.join(pcm_chunks)
|
pcm_data = b''.join(pcm_chunks)
|
||||||
|
return pcm_data
|
||||||
# 将 PCM 转换为 WAV 格式
|
|
||||||
wav_buffer = io.BytesIO()
|
|
||||||
with wave.open(wav_buffer, 'wb') as wav_file:
|
|
||||||
wav_file.setnchannels(1) # 单声道
|
|
||||||
wav_file.setsampwidth(2) # 16-bit = 2 bytes
|
|
||||||
wav_file.setframerate(self.sample_rate) # 使用配置的采样率
|
|
||||||
wav_file.writeframes(pcm_data)
|
|
||||||
|
|
||||||
wav_bytes = wav_buffer.getvalue()
|
|
||||||
|
|
||||||
# 返回完整的 WAV 字节数据
|
|
||||||
return wav_bytes
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Cartesia TTS failed: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"Cartesia TTS failed: {e}", exc_info=True)
|
||||||
|
|
|
||||||
66
main/xiaozhi-server/core/providers/tts/deepgram.py
Normal file
66
main/xiaozhi-server/core/providers/tts/deepgram.py
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import os
|
||||||
|
from typing import Optional
|
||||||
|
from deepgram import DeepgramClient
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
from core.providers.tts.dto.dto import InterfaceType
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
self.interface_type = InterfaceType.SINGLE_STREAM
|
||||||
|
|
||||||
|
# Deepgram configuration
|
||||||
|
self.api_key = config.get("api_key") or os.environ.get("DEEPGRAM_API_KEY")
|
||||||
|
if not self.api_key:
|
||||||
|
raise ValueError(
|
||||||
|
"Deepgram API key is required. "
|
||||||
|
"Provide via api_key in config or set DEEPGRAM_API_KEY environment variable"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.model = config.get("model", "aura-2-thalia-en") or os.environ.get("DEEPGRAM_MODEL") # Default voice model
|
||||||
|
self.encoding = config.get("encoding", "linear16") # PCM format
|
||||||
|
self.sample_rate = config.get("sample_rate", 16000) # Match client sample rate
|
||||||
|
self.container = config.get("container", "none") # Raw audio
|
||||||
|
self.audio_file_type = "pcm"
|
||||||
|
|
||||||
|
# Initialize Deepgram client
|
||||||
|
self.client = DeepgramClient(api_key=self.api_key)
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).info(
|
||||||
|
f"Deepgram TTS initialized: model={self.model}, "
|
||||||
|
f"sample_rate={self.sample_rate}, encoding={self.encoding}"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def text_to_speech(self, text: str, output_file: Optional[str] = None) -> Optional[bytes]:
|
||||||
|
try:
|
||||||
|
audio_stream = self.client.speak.v1.audio.generate(
|
||||||
|
text=text,
|
||||||
|
model=self.model,
|
||||||
|
encoding = self.encoding,
|
||||||
|
sample_rate = self.sample_rate,
|
||||||
|
container = self.container,
|
||||||
|
)
|
||||||
|
|
||||||
|
if output_file:
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
for chunk in audio_stream:
|
||||||
|
f.write(chunk)
|
||||||
|
else:
|
||||||
|
audio_bytes = b""
|
||||||
|
for chunk in audio_stream:
|
||||||
|
audio_bytes += chunk["data"]
|
||||||
|
return audio_bytes
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Deepgram TTS failed: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
"""Resource cleanup"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
@ -53,7 +53,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 标记为单流式接口
|
# 标记为单流式接口
|
||||||
self.interface_type = InterfaceType.SINGLE_STREAM
|
self.interface_type = InterfaceType.SINGLE_STREAM
|
||||||
# 设置音频文件类型为 MP3
|
# 设置音频文件类型为 MP3
|
||||||
self.audio_file_type = "mp3"
|
self.audio_file_type = "pcm"
|
||||||
|
|
||||||
# 获取 API Key
|
# 获取 API Key
|
||||||
self.api_key = config.get("api_key") or os.environ.get("ELEVEN_API_KEY")
|
self.api_key = config.get("api_key") or os.environ.get("ELEVEN_API_KEY")
|
||||||
|
|
@ -113,28 +113,24 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 使用 SDK 的 convert 方法生成完整音频(返回 generator)
|
# 使用 SDK 的 convert 方法生成完整音频(返回 generator)
|
||||||
# 强制使用 mp3_44100 格式(忽略配置中的 output_format)
|
# 强制使用 mp3_44100 格式(忽略配置中的 output_format)
|
||||||
# 因为 base.py 需要完整的音频文件格式(MP3/WAV),而不是原始 PCM
|
# 因为 base.py 需要完整的音频文件格式(MP3/WAV),而不是原始 PCM
|
||||||
audio_result = self.client.text_to_speech.convert(
|
audio_stream = self.client.text_to_speech.convert(
|
||||||
voice_id=self.voice_id,
|
voice_id=self.voice_id,
|
||||||
text=text,
|
text=text,
|
||||||
model_id=self.model,
|
model_id=self.model,
|
||||||
output_format="mp3_44100", # 强制 MP3 格式,44.1kHz
|
output_format=self.output_format,
|
||||||
voice_settings=self.voice_settings
|
voice_settings=self.voice_settings
|
||||||
)
|
)
|
||||||
|
|
||||||
# 检查返回类型
|
# 检查返回类型
|
||||||
if isinstance(audio_result, bytes):
|
if output_file:
|
||||||
# 直接返回 bytes
|
with open(output_file, 'wb') as f:
|
||||||
return audio_result
|
for chunk in audio_stream:
|
||||||
|
f.write(chunk)
|
||||||
else:
|
else:
|
||||||
# 是 generator,需要收集所有音频块
|
audio_bytes = b""
|
||||||
audio_chunks = []
|
for chunk in audio_stream:
|
||||||
for chunk in audio_result:
|
audio_bytes += chunk["data"]
|
||||||
if chunk:
|
return audio_bytes
|
||||||
audio_chunks.append(chunk)
|
|
||||||
|
|
||||||
# 合并为完整的 MP3 数据
|
|
||||||
mp3_data = b''.join(audio_chunks)
|
|
||||||
return mp3_data
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"ElevenLabs TTS failed: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"ElevenLabs TTS failed: {e}", exc_info=True)
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
|
||||||
defult_audio_setting = {
|
defult_audio_setting = {
|
||||||
"sample_rate": 24000,
|
"sample_rate": 16000,
|
||||||
"bitrate": 128000,
|
|
||||||
"format": "pcm",
|
"format": "pcm",
|
||||||
"channel": 1,
|
"channel": 1,
|
||||||
}
|
}
|
||||||
|
|
@ -56,8 +55,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
if self.voice:
|
if self.voice:
|
||||||
self.voice_setting["voice_id"] = self.voice
|
self.voice_setting["voice_id"] = self.voice
|
||||||
|
|
||||||
self.host = "api.minimaxi.com" # 备用地址:api-bj.minimaxi.com
|
self.host = "api.minimax.io"
|
||||||
self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}"
|
self.api_url = f"https://{self.host}/v1/t2a_v2"
|
||||||
self.header = {
|
self.header = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
|
|
|
||||||
68
main/xiaozhi-server/core/providers/tts/test/QUICKSTART.txt
Normal file
68
main/xiaozhi-server/core/providers/tts/test/QUICKSTART.txt
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
TTS Test Quick Start Guide
|
||||||
|
==========================
|
||||||
|
|
||||||
|
1. Set API Keys (one-time setup)
|
||||||
|
---------------------------------
|
||||||
|
|
||||||
|
Add to ~/.zshrc for permanent access:
|
||||||
|
|
||||||
|
echo 'export DEEPGRAM_API_KEY="sk-your-key"' >> ~/.zshrc
|
||||||
|
echo 'export ELEVENLABS_API_KEY="sk-your-key"' >> ~/.zshrc
|
||||||
|
echo 'export CARTESIA_API_KEY="your-key"' >> ~/.zshrc
|
||||||
|
echo 'export MINIMAX_API_KEY="your-key"' >> ~/.zshrc
|
||||||
|
echo 'export MINIMAX_GROUP_ID="your-group-id"' >> ~/.zshrc
|
||||||
|
source ~/.zshrc
|
||||||
|
|
||||||
|
|
||||||
|
2. Run Tests
|
||||||
|
------------
|
||||||
|
|
||||||
|
cd /Users/harold/Projects/live-agent/main/xiaozhi-server/
|
||||||
|
|
||||||
|
# Test Deepgram
|
||||||
|
python3 -m core.providers.tts.test.test_deepgram
|
||||||
|
|
||||||
|
# Test ElevenLabs
|
||||||
|
python3 -m core.providers.tts.test.test_elevenlabs
|
||||||
|
|
||||||
|
# Test Cartesia
|
||||||
|
python3 -m core.providers.tts.test.test_cartesia
|
||||||
|
|
||||||
|
# Test Minimax
|
||||||
|
python3 -m core.providers.tts.test.test_minimax
|
||||||
|
|
||||||
|
# Custom text
|
||||||
|
python3 -m core.providers.tts.test.test_deepgram "你好世界"
|
||||||
|
python3 -m core.providers.tts.test.test_minimax "你好世界"
|
||||||
|
|
||||||
|
|
||||||
|
3. Check Output
|
||||||
|
---------------
|
||||||
|
|
||||||
|
Generated audio files are in:
|
||||||
|
core/providers/tts/test/tmp/
|
||||||
|
- deepgram_test.wav
|
||||||
|
- elevenlabs_test.wav
|
||||||
|
- cartesia_test.wav
|
||||||
|
- minimax_test.wav
|
||||||
|
|
||||||
|
|
||||||
|
4. Troubleshooting
|
||||||
|
------------------
|
||||||
|
|
||||||
|
If SDK not installed:
|
||||||
|
pip install deepgram-sdk elevenlabs cartesia aiohttp
|
||||||
|
|
||||||
|
If API key error:
|
||||||
|
echo $DEEPGRAM_API_KEY # Check if set
|
||||||
|
echo $MINIMAX_API_KEY # Check Minimax key
|
||||||
|
echo $MINIMAX_GROUP_ID # Check Minimax group ID
|
||||||
|
source ~/.zshrc # Reload config
|
||||||
|
|
||||||
|
If module not found:
|
||||||
|
cd /Users/harold/Projects/live-agent/main/xiaozhi-server/
|
||||||
|
# Make sure you're in the right directory!
|
||||||
|
|
||||||
|
|
||||||
|
That's it! 🎉
|
||||||
|
|
||||||
0
main/xiaozhi-server/core/providers/tts/test/__init__.py
Normal file
0
main/xiaozhi-server/core/providers/tts/test/__init__.py
Normal file
112
main/xiaozhi-server/core/providers/tts/test/test_cartesia.py
Normal file
112
main/xiaozhi-server/core/providers/tts/test/test_cartesia.py
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
from io import BytesIO
|
||||||
|
import wave
|
||||||
|
import os
|
||||||
|
import cartesia
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
"""
|
||||||
|
Test for Cartesia TTS
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 -m core.providers.tts.test_cartesia
|
||||||
|
python3 -m core.providers.tts.test_cartesia "Custom text"
|
||||||
|
|
||||||
|
Environment:
|
||||||
|
CARTESIA_API_KEY - Your API key (required)
|
||||||
|
CARTESIA_VOICE_ID - Voice ID (optional, default: a0e99841-438c-4a64-b679-ae501e7d6091)
|
||||||
|
CARTESIA_MODEL - Model (optional, default: sonic-english)
|
||||||
|
"""
|
||||||
|
|
||||||
|
text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of Cartesia text to speech."
|
||||||
|
|
||||||
|
api_key = os.environ.get("CARTESIA_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
print("❌ Error: CARTESIA_API_KEY not set")
|
||||||
|
print(" export CARTESIA_API_KEY='your-key'")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Get configuration from environment
|
||||||
|
voice_id = os.environ.get("CARTESIA_VOICE_ID", "f9a4b3a6-b44b-469f-90e3-c8e19bd30e99")
|
||||||
|
model = os.environ.get("CARTESIA_MODEL", "sonic-3")
|
||||||
|
|
||||||
|
print(f"🎙️ Testing Cartesia TTS")
|
||||||
|
print(f" Model: {model}")
|
||||||
|
print(f" Voice ID: {voice_id[:16]}...")
|
||||||
|
print(f" Text: {text}\n")
|
||||||
|
|
||||||
|
# Create Cartesia client
|
||||||
|
client = cartesia.Cartesia(api_key=api_key)
|
||||||
|
|
||||||
|
try:
|
||||||
|
print("⏳ Generating audio...")
|
||||||
|
start = asyncio.get_event_loop().time()
|
||||||
|
|
||||||
|
# Create WebSocket connection
|
||||||
|
ws = client.tts.websocket()
|
||||||
|
|
||||||
|
# Collect audio chunks
|
||||||
|
pcm_chunks = []
|
||||||
|
|
||||||
|
# Send request and receive audio stream
|
||||||
|
for output in ws.send(
|
||||||
|
model_id=model,
|
||||||
|
transcript=text,
|
||||||
|
voice={
|
||||||
|
"mode": "id",
|
||||||
|
"id": voice_id
|
||||||
|
},
|
||||||
|
stream=True,
|
||||||
|
output_format={
|
||||||
|
"container": "raw",
|
||||||
|
"encoding": "pcm_s16le", # 16-bit PCM
|
||||||
|
"sample_rate": 16000
|
||||||
|
},
|
||||||
|
language="zh"
|
||||||
|
):
|
||||||
|
# Collect PCM audio data
|
||||||
|
if output and hasattr(output, 'audio') and output.audio:
|
||||||
|
pcm_chunks.append(output.audio)
|
||||||
|
|
||||||
|
# Merge all PCM chunks
|
||||||
|
audio_bytes = b''.join(pcm_chunks)
|
||||||
|
duration = (asyncio.get_event_loop().time() - start) * 1000
|
||||||
|
|
||||||
|
print(f"✅ Audio generated")
|
||||||
|
print(f" Duration: {duration:.0f}ms")
|
||||||
|
print(f" Size: {len(audio_bytes):,} bytes\n")
|
||||||
|
|
||||||
|
# Convert PCM to WAV format
|
||||||
|
wav_buffer = BytesIO()
|
||||||
|
|
||||||
|
# Open wave file in write mode
|
||||||
|
with wave.open(wav_buffer, 'wb') as wf:
|
||||||
|
wf.setnchannels(1) # Mono
|
||||||
|
wf.setsampwidth(2) # 16-bit (2 bytes) per sample
|
||||||
|
wf.setframerate(16000) # Sample rate
|
||||||
|
wf.writeframes(audio_bytes)
|
||||||
|
|
||||||
|
# Save to file
|
||||||
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
output_file = os.path.join(script_dir, "tmp", "cartesia_test.wav")
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
f.write(wav_buffer.getvalue())
|
||||||
|
|
||||||
|
print(f"💾 Saved to: {output_file}")
|
||||||
|
print("🔊 Playing audio...")
|
||||||
|
|
||||||
|
# Play audio file
|
||||||
|
os.system(f"afplay '{output_file}'")
|
||||||
|
|
||||||
|
print("\n✅ Test completed successfully!")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n❌ Test failed: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
sys.exit(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n\n👋 Test interrupted")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
95
main/xiaozhi-server/core/providers/tts/test/test_deepgram.py
Normal file
95
main/xiaozhi-server/core/providers/tts/test/test_deepgram.py
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
from io import BytesIO
|
||||||
|
import wave
|
||||||
|
import os
|
||||||
|
from deepgram import DeepgramClient
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
"""
|
||||||
|
Test for Deepgram TTS
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 -m core.providers.tts.test_deepgram
|
||||||
|
python3 -m core.providers.tts.test_deepgram "Custom text"
|
||||||
|
|
||||||
|
Environment:
|
||||||
|
DEEPGRAM_API_KEY - Your API key (required)
|
||||||
|
DEEPGRAM_MODEL - Voice model (optional, default: aura-2-thalia-en)
|
||||||
|
"""
|
||||||
|
|
||||||
|
text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of Deepgram text to speech."
|
||||||
|
|
||||||
|
api_key = os.environ.get("DEEPGRAM_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
print("❌ Error: DEEPGRAM_API_KEY not set")
|
||||||
|
print(" export DEEPGRAM_API_KEY='your-key'")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Get configuration from environment
|
||||||
|
model = os.environ.get("DEEPGRAM_MODEL", "aura-2-thalia-en")
|
||||||
|
|
||||||
|
print(f"🎙️ Testing Deepgram TTS")
|
||||||
|
print(f" Model: {model}")
|
||||||
|
print(f" Text: {text}\n")
|
||||||
|
|
||||||
|
# Create Deepgram client
|
||||||
|
client = DeepgramClient(api_key=api_key)
|
||||||
|
|
||||||
|
try:
|
||||||
|
print("⏳ Generating audio...")
|
||||||
|
start = asyncio.get_event_loop().time()
|
||||||
|
|
||||||
|
# Generate audio using Deepgram SDK
|
||||||
|
audio_stream = client.speak.v1.audio.generate(
|
||||||
|
text=text,
|
||||||
|
model=model,
|
||||||
|
encoding="linear16", # PCM format
|
||||||
|
sample_rate=16000,
|
||||||
|
container="none" # Raw audio
|
||||||
|
)
|
||||||
|
|
||||||
|
# Collect audio chunks
|
||||||
|
audio_bytes = b""
|
||||||
|
for chunk in audio_stream:
|
||||||
|
audio_bytes += chunk
|
||||||
|
|
||||||
|
duration = (asyncio.get_event_loop().time() - start) * 1000
|
||||||
|
|
||||||
|
print(f"✅ Audio generated")
|
||||||
|
print(f" Duration: {duration:.0f}ms")
|
||||||
|
print(f" Size: {len(audio_bytes):,} bytes\n")
|
||||||
|
|
||||||
|
# Convert PCM to WAV format
|
||||||
|
wav_buffer = BytesIO()
|
||||||
|
|
||||||
|
# Open wave file in write mode
|
||||||
|
with wave.open(wav_buffer, 'wb') as wf:
|
||||||
|
wf.setnchannels(1) # Mono
|
||||||
|
wf.setsampwidth(2) # 16-bit (2 bytes) per sample
|
||||||
|
wf.setframerate(16000) # Sample rate
|
||||||
|
wf.writeframes(audio_bytes)
|
||||||
|
|
||||||
|
# Save to file
|
||||||
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
output_file = os.path.join(script_dir, "tmp", "deepgram_test.wav")
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
f.write(wav_buffer.getvalue())
|
||||||
|
|
||||||
|
print(f"💾 Saved to: {output_file}")
|
||||||
|
print("🔊 Playing audio...")
|
||||||
|
|
||||||
|
# Play audio file
|
||||||
|
os.system(f"afplay '{output_file}'")
|
||||||
|
|
||||||
|
print("\n✅ Test completed successfully!")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n❌ Test failed: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
sys.exit(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n\n👋 Test interrupted")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
from io import BytesIO
|
||||||
|
import wave
|
||||||
|
import os
|
||||||
|
from elevenlabs.client import ElevenLabs
|
||||||
|
from elevenlabs import VoiceSettings
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
"""
|
||||||
|
Test for ElevenLabs TTS
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 -m core.providers.tts.elevenlabs
|
||||||
|
python3 -m core.providers.tts.elevenlabs "Custom text"
|
||||||
|
|
||||||
|
Environment:
|
||||||
|
ELEVENLABS_API_KEY - Your API key (required)
|
||||||
|
ELEVENLABS_VOICE_ID - Voice ID (optional)
|
||||||
|
"""
|
||||||
|
|
||||||
|
text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of ElevenLabs text to speech."
|
||||||
|
|
||||||
|
api_key = os.environ.get("ELEVENLABS_API_KEY")
|
||||||
|
if not api_key:
|
||||||
|
print("❌ Error: ELEVENLABS_API_KEY not set")
|
||||||
|
print(" export ELEVENLABS_API_KEY='your-key'")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Create minimal provider instance
|
||||||
|
client = ElevenLabs(api_key=api_key)
|
||||||
|
voice_id = os.environ.get("ELEVENLABS_VOICE_ID", "EXAVITQu4vr4xnSDxMaL")
|
||||||
|
voice_settings = VoiceSettings(
|
||||||
|
stability=0.5,
|
||||||
|
similarity_boost=0.75,
|
||||||
|
style=0.0,
|
||||||
|
use_speaker_boost=True
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
print("⏳ Generating audio...")
|
||||||
|
start = asyncio.get_event_loop().time()
|
||||||
|
|
||||||
|
# Generate audio
|
||||||
|
audio_stream = client.text_to_speech.convert(
|
||||||
|
voice_id=voice_id,
|
||||||
|
text=text,
|
||||||
|
model_id="eleven_multilingual_v2",
|
||||||
|
output_format="pcm_16000",
|
||||||
|
voice_settings=voice_settings
|
||||||
|
)
|
||||||
|
|
||||||
|
# Collect chunks
|
||||||
|
audio_bytes = b''.join(chunk for chunk in audio_stream if chunk)
|
||||||
|
duration = (asyncio.get_event_loop().time() - start) * 1000
|
||||||
|
|
||||||
|
print(f"✅ Audio generated")
|
||||||
|
print(f" Duration: {duration:.0f}ms")
|
||||||
|
print(f" Size: {len(audio_bytes):,} bytes\n")
|
||||||
|
|
||||||
|
# Convert to WAV format
|
||||||
|
wav_buffer = BytesIO()
|
||||||
|
|
||||||
|
# Open wave file in write mode
|
||||||
|
with wave.open(wav_buffer, 'wb') as wf:
|
||||||
|
wf.setnchannels(1) # Mono or stereo
|
||||||
|
wf.setsampwidth(2) # 16-bit (2 bytes) per sample
|
||||||
|
wf.setframerate(16000) # Sample rate (e.g., 16000 Hz)
|
||||||
|
wf.writeframes(audio_bytes)
|
||||||
|
wav_buffer.getvalue()
|
||||||
|
|
||||||
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
output_file = os.path.join(script_dir, "tmp", "elevenlabs_test.wav")
|
||||||
|
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
f.write(wav_buffer.getvalue())
|
||||||
|
# here,I want to get a .wav file to play the audio file
|
||||||
|
os.system(f"afplay '{output_file}'")
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n\n👋 Test interrupted")
|
||||||
|
sys.exit(1)
|
||||||
208
main/xiaozhi-server/core/providers/tts/test/test_minimax.py
Normal file
208
main/xiaozhi-server/core/providers/tts/test/test_minimax.py
Normal file
|
|
@ -0,0 +1,208 @@
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from io import BytesIO
|
||||||
|
import wave
|
||||||
|
import os
|
||||||
|
import platform
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
"""
|
||||||
|
Test for Minimax TTS
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 -m core.providers.tts.test.test_minimax
|
||||||
|
python3 -m core.providers.tts.test.test_minimax "Custom text"
|
||||||
|
|
||||||
|
Environment:
|
||||||
|
MINIMAX_API_KEY - Your API key (required)
|
||||||
|
MINIMAX_GROUP_ID - Your Group ID (required)
|
||||||
|
MINIMAX_MODEL - Model name (optional, default: speech-01-turbo)
|
||||||
|
MINIMAX_VOICE_ID - Voice ID (optional, default: female-shaonv)
|
||||||
|
"""
|
||||||
|
|
||||||
|
text = sys.argv[1] if len(sys.argv) > 1 else "Hello, this is a test of Minimax text to speech."
|
||||||
|
|
||||||
|
# Check required environment variables
|
||||||
|
api_key = os.environ.get("MINIMAX_API_KEY")
|
||||||
|
group_id = os.environ.get("MINIMAX_GROUP_ID")
|
||||||
|
|
||||||
|
if not api_key:
|
||||||
|
print("❌ Error: MINIMAX_API_KEY not set")
|
||||||
|
print(" export MINIMAX_API_KEY='your-key'")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if not group_id:
|
||||||
|
print("❌ Error: MINIMAX_GROUP_ID not set")
|
||||||
|
print(" export MINIMAX_GROUP_ID='your-group-id'")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Optional parameters
|
||||||
|
model = os.environ.get("MINIMAX_MODEL", "speech-2.6-hd")
|
||||||
|
voice_id = os.environ.get("MINIMAX_VOICE_ID", "English_Graceful_Lady")
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
host = "api.minimax.io"
|
||||||
|
api_url = f"https://{host}/v1/t2a_v2"
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"model": model,
|
||||||
|
"text": text,
|
||||||
|
"stream": True,
|
||||||
|
"voice_setting": {
|
||||||
|
"voice_id": voice_id,
|
||||||
|
"speed": 1.0,
|
||||||
|
"vol": 1.0,
|
||||||
|
"pitch": 0,
|
||||||
|
"emotion": "happy",
|
||||||
|
},
|
||||||
|
"pronunciation_dict": {
|
||||||
|
"tone": []
|
||||||
|
},
|
||||||
|
"audio_setting": {
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"format": "pcm",
|
||||||
|
"channel": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async def test():
|
||||||
|
try:
|
||||||
|
print(f"⏳ Generating audio with Minimax TTS...")
|
||||||
|
print(f" Model: {model}")
|
||||||
|
print(f" Voice: {voice_id}")
|
||||||
|
print(f" Text: {text[:50]}{'...' if len(text) > 50 else ''}\n")
|
||||||
|
|
||||||
|
start_time = asyncio.get_event_loop().time()
|
||||||
|
pcm_chunks = []
|
||||||
|
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.post(
|
||||||
|
api_url,
|
||||||
|
headers=headers,
|
||||||
|
data=json.dumps(payload),
|
||||||
|
timeout=aiohttp.ClientTimeout(total=30),
|
||||||
|
) as resp:
|
||||||
|
|
||||||
|
if resp.status != 200:
|
||||||
|
error_text = await resp.text()
|
||||||
|
print(f"❌ API Error: {resp.status}")
|
||||||
|
print(f" Response: {error_text}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Process streaming audio data
|
||||||
|
buffer = b""
|
||||||
|
async for chunk in resp.content.iter_any():
|
||||||
|
if not chunk:
|
||||||
|
continue
|
||||||
|
|
||||||
|
buffer += chunk
|
||||||
|
|
||||||
|
# Parse SSE (Server-Sent Events) format
|
||||||
|
while True:
|
||||||
|
# Find data chunk separator
|
||||||
|
header_pos = buffer.find(b"data: ")
|
||||||
|
if header_pos == -1:
|
||||||
|
break
|
||||||
|
|
||||||
|
end_pos = buffer.find(b"\n\n", header_pos)
|
||||||
|
if end_pos == -1:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Extract single complete JSON block
|
||||||
|
json_str = buffer[header_pos + 6 : end_pos].decode("utf-8")
|
||||||
|
buffer = buffer[end_pos + 2 :]
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = json.loads(json_str)
|
||||||
|
status = data.get("data", {}).get("status", 1)
|
||||||
|
audio_hex = data.get("data", {}).get("audio")
|
||||||
|
|
||||||
|
# Only process status=1 valid audio chunks
|
||||||
|
# Ignore status=2 end summary chunks
|
||||||
|
if status == 1 and audio_hex:
|
||||||
|
# Decode hex string to PCM bytes
|
||||||
|
audio_bytes = bytes.fromhex(audio_hex)
|
||||||
|
pcm_chunks.append(audio_bytes)
|
||||||
|
elif status == 2:
|
||||||
|
# End of stream
|
||||||
|
break
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
print(f"⚠️ Warning: Failed to parse JSON: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
duration = (asyncio.get_event_loop().time() - start_time) * 1000
|
||||||
|
|
||||||
|
# Combine all PCM chunks
|
||||||
|
pcm_data = b''.join(pcm_chunks)
|
||||||
|
|
||||||
|
if not pcm_data:
|
||||||
|
print("❌ Error: No audio data received")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"✅ Audio generated")
|
||||||
|
print(f" Duration: {duration:.0f}ms")
|
||||||
|
print(f" Size: {len(pcm_data):,} bytes")
|
||||||
|
print(f" Chunks: {len(pcm_chunks)}\n")
|
||||||
|
|
||||||
|
# Convert PCM to WAV format
|
||||||
|
wav_buffer = BytesIO()
|
||||||
|
with wave.open(wav_buffer, 'wb') as wf:
|
||||||
|
wf.setnchannels(1) # Mono
|
||||||
|
wf.setsampwidth(2) # 16-bit (2 bytes) per sample
|
||||||
|
wf.setframerate(24000) # Sample rate: 24000 Hz
|
||||||
|
wf.writeframes(pcm_data)
|
||||||
|
|
||||||
|
# Save to file
|
||||||
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
output_file = os.path.join(script_dir, "tmp", "minimax_test.wav")
|
||||||
|
|
||||||
|
# Create tmp directory if not exists
|
||||||
|
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
||||||
|
|
||||||
|
with open(output_file, 'wb') as f:
|
||||||
|
f.write(wav_buffer.getvalue())
|
||||||
|
|
||||||
|
print(f"💾 Saved to: {output_file}\n")
|
||||||
|
print("🔊 Playing audio...")
|
||||||
|
|
||||||
|
# Play audio (platform-specific)
|
||||||
|
system = platform.system()
|
||||||
|
if system == "Darwin": # macOS
|
||||||
|
os.system(f"afplay '{output_file}'")
|
||||||
|
elif system == "Linux":
|
||||||
|
# Try common Linux audio players
|
||||||
|
if os.system("which aplay > /dev/null 2>&1") == 0:
|
||||||
|
os.system(f"aplay '{output_file}'")
|
||||||
|
elif os.system("which ffplay > /dev/null 2>&1") == 0:
|
||||||
|
os.system(f"ffplay -nodisp -autoexit '{output_file}' 2>/dev/null")
|
||||||
|
else:
|
||||||
|
print("⚠️ No audio player found (aplay/ffplay)")
|
||||||
|
elif system == "Windows":
|
||||||
|
os.system(f'start {output_file}')
|
||||||
|
else:
|
||||||
|
print(f"⚠️ Unsupported platform: {system}")
|
||||||
|
|
||||||
|
print("\n✅ Test completed successfully!")
|
||||||
|
|
||||||
|
except aiohttp.ClientError as e:
|
||||||
|
print(f"❌ Network error: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n\n👋 Test interrupted")
|
||||||
|
sys.exit(1)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Unexpected error: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Run the async test
|
||||||
|
asyncio.run(test())
|
||||||
|
|
||||||
|
|
@ -40,3 +40,4 @@ vosk==0.3.44
|
||||||
# TTS SDKs
|
# TTS SDKs
|
||||||
elevenlabs>=1.11.0
|
elevenlabs>=1.11.0
|
||||||
cartesia>=1.0.0
|
cartesia>=1.0.0
|
||||||
|
deepgram-sdk>=3.0.0
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue