Spaces:
Running
Running
axeronis commited on
Commit ·
5339570
1
Parent(s): d6efaed
feat(voice): add custom voice cloning support with 3 universal voices
Browse files
backend/alembic/versions/2025_12_23_voice_settings.py
CHANGED
|
@@ -18,10 +18,12 @@ depends_on = None
|
|
| 18 |
|
| 19 |
def upgrade() -> None:
|
| 20 |
# Add voice settings columns to tenants table
|
| 21 |
-
op.add_column('tenants', sa.Column('voice_id', sa.String(), nullable=True, server_default='
|
| 22 |
op.add_column('tenants', sa.Column('voice_enabled', sa.Boolean(), nullable=True, server_default='true'))
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
def downgrade() -> None:
|
|
|
|
| 26 |
op.drop_column('tenants', 'voice_enabled')
|
| 27 |
op.drop_column('tenants', 'voice_id')
|
|
|
|
| 18 |
|
| 19 |
def upgrade() -> None:
|
| 20 |
# Add voice settings columns to tenants table
|
| 21 |
+
op.add_column('tenants', sa.Column('voice_id', sa.String(), nullable=True, server_default='professional_male'))
|
| 22 |
op.add_column('tenants', sa.Column('voice_enabled', sa.Boolean(), nullable=True, server_default='true'))
|
| 23 |
+
op.add_column('tenants', sa.Column('voice_reference_url', sa.String(), nullable=True))
|
| 24 |
|
| 25 |
|
| 26 |
def downgrade() -> None:
|
| 27 |
+
op.drop_column('tenants', 'voice_reference_url')
|
| 28 |
op.drop_column('tenants', 'voice_enabled')
|
| 29 |
op.drop_column('tenants', 'voice_id')
|
backend/app/api/webhook.py
CHANGED
|
@@ -1010,11 +1010,13 @@ async def process_ai_response_background(
|
|
| 1010 |
from app.services.telegram_service import telegram_service
|
| 1011 |
|
| 1012 |
# Generate speech using tenant's selected voice
|
| 1013 |
-
voice_id = getattr(tenant, 'voice_id', '
|
|
|
|
| 1014 |
logger.info(f"🎙️ Generating voice response (voice={voice_id})...")
|
| 1015 |
audio_bytes = await voice_service.generate_audio(
|
| 1016 |
text=ai_response["text"],
|
| 1017 |
-
voice=voice_id
|
|
|
|
| 1018 |
)
|
| 1019 |
|
| 1020 |
# Send voice message
|
|
|
|
| 1010 |
from app.services.telegram_service import telegram_service
|
| 1011 |
|
| 1012 |
# Generate speech using tenant's selected voice
|
| 1013 |
+
voice_id = getattr(tenant, 'voice_id', 'professional_male')
|
| 1014 |
+
custom_voice_url = getattr(tenant, 'voice_reference_url', None)
|
| 1015 |
logger.info(f"🎙️ Generating voice response (voice={voice_id})...")
|
| 1016 |
audio_bytes = await voice_service.generate_audio(
|
| 1017 |
text=ai_response["text"],
|
| 1018 |
+
voice=voice_id,
|
| 1019 |
+
custom_voice_url=custom_voice_url
|
| 1020 |
)
|
| 1021 |
|
| 1022 |
# Send voice message
|
backend/app/models/tenant.py
CHANGED
|
@@ -106,8 +106,9 @@ class Tenant(SQLModel, table=True):
|
|
| 106 |
notification_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
| 107 |
|
| 108 |
# Voice Settings (Chatterbox TTS)
|
| 109 |
-
voice_id: str = Field(default="
|
| 110 |
voice_enabled: bool = Field(default=True) # Enable/disable AI voice responses
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
# Status
|
|
|
|
| 106 |
notification_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
| 107 |
|
| 108 |
# Voice Settings (Chatterbox TTS)
|
| 109 |
+
voice_id: str = Field(default="professional_male") # professional_male, friendly_male, professional_female, or custom
|
| 110 |
voice_enabled: bool = Field(default=True) # Enable/disable AI voice responses
|
| 111 |
+
voice_reference_url: Optional[str] = Field(default=None) # URL to custom voice audio (for voice cloning)
|
| 112 |
|
| 113 |
|
| 114 |
# Status
|
backend/app/services/voice_service.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
Voice Service - Chatterbox TTS Integration
|
| 3 |
|
| 4 |
-
Uses Chatterbox TTS (free, emotional voices)
|
| 5 |
Falls back to Edge TTS if Chatterbox is unavailable.
|
| 6 |
"""
|
| 7 |
|
|
@@ -13,37 +13,34 @@ from app.core.config import settings
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
|
| 16 |
-
# Available
|
| 17 |
AVAILABLE_VOICES = {
|
| 18 |
-
"
|
| 19 |
-
"name": "
|
| 20 |
-
"
|
| 21 |
-
"description": "Уверенный мужской голос, командный стиль"
|
| 22 |
},
|
| 23 |
-
"
|
| 24 |
-
"name": "
|
| 25 |
-
"
|
| 26 |
-
"description": "Дружелюбный мужской голос, располагающий к общению"
|
| 27 |
},
|
| 28 |
-
"
|
| 29 |
-
"name": "
|
| 30 |
-
"
|
| 31 |
-
"description": "Тёплый женский голос, вызывающий доверие"
|
| 32 |
}
|
| 33 |
}
|
| 34 |
|
| 35 |
|
| 36 |
class VoiceService:
|
| 37 |
"""
|
| 38 |
-
Voice Service using Chatterbox TTS.
|
| 39 |
|
| 40 |
-
Primary: Chatterbox (free, emotional)
|
| 41 |
Fallback: Edge TTS (free, basic)
|
| 42 |
"""
|
| 43 |
|
| 44 |
def __init__(self):
|
| 45 |
self.chatterbox_url = getattr(settings, 'CHATTERBOX_API_URL', None)
|
| 46 |
-
self.default_voice = "
|
| 47 |
|
| 48 |
if self.chatterbox_url:
|
| 49 |
logger.info(f"✅ Chatterbox Voice Service initialized ({self.chatterbox_url})")
|
|
@@ -54,6 +51,7 @@ class VoiceService:
|
|
| 54 |
self,
|
| 55 |
text: str,
|
| 56 |
voice: str = None,
|
|
|
|
| 57 |
exaggeration: float = 0.5
|
| 58 |
) -> bytes:
|
| 59 |
"""
|
|
@@ -61,7 +59,8 @@ class VoiceService:
|
|
| 61 |
|
| 62 |
Args:
|
| 63 |
text: Text to synthesize
|
| 64 |
-
voice: Voice ID (
|
|
|
|
| 65 |
exaggeration: Emotion intensity (0.0 - 1.0)
|
| 66 |
|
| 67 |
Returns:
|
|
@@ -75,7 +74,9 @@ class VoiceService:
|
|
| 75 |
# Try Chatterbox first
|
| 76 |
if self.chatterbox_url:
|
| 77 |
try:
|
| 78 |
-
audio = await self._chatterbox_generate(
|
|
|
|
|
|
|
| 79 |
if audio:
|
| 80 |
return audio
|
| 81 |
except Exception as e:
|
|
@@ -88,17 +89,24 @@ class VoiceService:
|
|
| 88 |
self,
|
| 89 |
text: str,
|
| 90 |
voice: str,
|
| 91 |
-
exaggeration: float
|
|
|
|
| 92 |
) -> bytes:
|
| 93 |
-
"""Generate audio using Chatterbox API."""
|
| 94 |
-
async with httpx.AsyncClient(timeout=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
response = await client.post(
|
| 96 |
f"{self.chatterbox_url}/synthesize",
|
| 97 |
-
json=
|
| 98 |
-
"text": text,
|
| 99 |
-
"voice": voice,
|
| 100 |
-
"exaggeration": exaggeration
|
| 101 |
-
}
|
| 102 |
)
|
| 103 |
response.raise_for_status()
|
| 104 |
|
|
@@ -113,9 +121,9 @@ class VoiceService:
|
|
| 113 |
|
| 114 |
# Map our voices to Edge TTS voices
|
| 115 |
EDGE_VOICE_MAP = {
|
| 116 |
-
"
|
| 117 |
-
"
|
| 118 |
-
"
|
| 119 |
}
|
| 120 |
|
| 121 |
edge_voice = EDGE_VOICE_MAP.get(voice, "ru-RU-DmitryNeural")
|
|
|
|
| 1 |
"""
|
| 2 |
Voice Service - Chatterbox TTS Integration
|
| 3 |
|
| 4 |
+
Uses Chatterbox TTS (free, emotional voices) with voice cloning support.
|
| 5 |
Falls back to Edge TTS if Chatterbox is unavailable.
|
| 6 |
"""
|
| 7 |
|
|
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
|
| 16 |
+
# Available built-in voices
|
| 17 |
AVAILABLE_VOICES = {
|
| 18 |
+
"professional_male": {
|
| 19 |
+
"name": "Professional (Male)",
|
| 20 |
+
"description": "Confident business voice, works in Russian/English"
|
|
|
|
| 21 |
},
|
| 22 |
+
"friendly_male": {
|
| 23 |
+
"name": "Friendly (Male)",
|
| 24 |
+
"description": "Warm, approachable voice for building rapport"
|
|
|
|
| 25 |
},
|
| 26 |
+
"professional_female": {
|
| 27 |
+
"name": "Professional (Female)",
|
| 28 |
+
"description": "Clear, trustworthy female voice"
|
|
|
|
| 29 |
}
|
| 30 |
}
|
| 31 |
|
| 32 |
|
| 33 |
class VoiceService:
|
| 34 |
"""
|
| 35 |
+
Voice Service using Chatterbox TTS with voice cloning.
|
| 36 |
|
| 37 |
+
Primary: Chatterbox (free, emotional, cloning)
|
| 38 |
Fallback: Edge TTS (free, basic)
|
| 39 |
"""
|
| 40 |
|
| 41 |
def __init__(self):
|
| 42 |
self.chatterbox_url = getattr(settings, 'CHATTERBOX_API_URL', None)
|
| 43 |
+
self.default_voice = "professional_male"
|
| 44 |
|
| 45 |
if self.chatterbox_url:
|
| 46 |
logger.info(f"✅ Chatterbox Voice Service initialized ({self.chatterbox_url})")
|
|
|
|
| 51 |
self,
|
| 52 |
text: str,
|
| 53 |
voice: str = None,
|
| 54 |
+
custom_voice_url: str = None,
|
| 55 |
exaggeration: float = 0.5
|
| 56 |
) -> bytes:
|
| 57 |
"""
|
|
|
|
| 59 |
|
| 60 |
Args:
|
| 61 |
text: Text to synthesize
|
| 62 |
+
voice: Voice ID (professional_male, friendly_male, professional_female, or custom)
|
| 63 |
+
custom_voice_url: URL to custom voice audio for cloning
|
| 64 |
exaggeration: Emotion intensity (0.0 - 1.0)
|
| 65 |
|
| 66 |
Returns:
|
|
|
|
| 74 |
# Try Chatterbox first
|
| 75 |
if self.chatterbox_url:
|
| 76 |
try:
|
| 77 |
+
audio = await self._chatterbox_generate(
|
| 78 |
+
text, selected_voice, exaggeration, custom_voice_url
|
| 79 |
+
)
|
| 80 |
if audio:
|
| 81 |
return audio
|
| 82 |
except Exception as e:
|
|
|
|
| 89 |
self,
|
| 90 |
text: str,
|
| 91 |
voice: str,
|
| 92 |
+
exaggeration: float,
|
| 93 |
+
custom_voice_url: str = None
|
| 94 |
) -> bytes:
|
| 95 |
+
"""Generate audio using Chatterbox API with optional voice cloning."""
|
| 96 |
+
async with httpx.AsyncClient(timeout=120.0) as client: # Longer timeout for CPU
|
| 97 |
+
payload = {
|
| 98 |
+
"text": text,
|
| 99 |
+
"voice": voice,
|
| 100 |
+
"exaggeration": exaggeration
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
# Add custom voice URL for cloning
|
| 104 |
+
if custom_voice_url:
|
| 105 |
+
payload["custom_voice_url"] = custom_voice_url
|
| 106 |
+
|
| 107 |
response = await client.post(
|
| 108 |
f"{self.chatterbox_url}/synthesize",
|
| 109 |
+
json=payload
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
)
|
| 111 |
response.raise_for_status()
|
| 112 |
|
|
|
|
| 121 |
|
| 122 |
# Map our voices to Edge TTS voices
|
| 123 |
EDGE_VOICE_MAP = {
|
| 124 |
+
"professional_male": "ru-RU-DmitryNeural",
|
| 125 |
+
"friendly_male": "ru-RU-DmitryNeural",
|
| 126 |
+
"professional_female": "ru-RU-SvetlanaNeural"
|
| 127 |
}
|
| 128 |
|
| 129 |
edge_voice = EDGE_VOICE_MAP.get(voice, "ru-RU-DmitryNeural")
|
chatterbox-service/server.py
CHANGED
|
@@ -2,13 +2,14 @@
|
|
| 2 |
Chatterbox TTS API Server
|
| 3 |
|
| 4 |
Free, emotional text-to-speech service using Resemble AI's Chatterbox.
|
| 5 |
-
|
| 6 |
"""
|
| 7 |
|
| 8 |
import io
|
|
|
|
| 9 |
import logging
|
| 10 |
from typing import Optional
|
| 11 |
-
from fastapi import FastAPI, HTTPException
|
| 12 |
from fastapi.responses import StreamingResponse
|
| 13 |
from pydantic import BaseModel
|
| 14 |
|
|
@@ -17,36 +18,40 @@ logger = logging.getLogger(__name__)
|
|
| 17 |
|
| 18 |
app = FastAPI(
|
| 19 |
title="Chatterbox TTS API",
|
| 20 |
-
description="Free emotional TTS with
|
| 21 |
-
version="1.
|
| 22 |
)
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
"
|
| 27 |
-
"name": "
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
},
|
| 31 |
-
"
|
| 32 |
-
"name": "
|
| 33 |
-
"
|
| 34 |
-
"
|
| 35 |
},
|
| 36 |
-
"
|
| 37 |
-
"name": "
|
| 38 |
-
"
|
| 39 |
-
"
|
| 40 |
}
|
| 41 |
}
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# Lazy load model
|
| 44 |
_model = None
|
| 45 |
|
| 46 |
def get_model():
|
| 47 |
global _model
|
| 48 |
if _model is None:
|
| 49 |
-
logger.info("🔄 Loading Chatterbox model (first time, may take
|
| 50 |
try:
|
| 51 |
from chatterbox.tts import ChatterboxTTS
|
| 52 |
_model = ChatterboxTTS.from_pretrained(device="cpu")
|
|
@@ -60,16 +65,17 @@ def get_model():
|
|
| 60 |
class TTSRequest(BaseModel):
|
| 61 |
"""TTS synthesis request."""
|
| 62 |
text: str
|
| 63 |
-
voice: str = "
|
| 64 |
exaggeration: float = 0.5 # Emotion intensity (0.0 - 1.0)
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
class VoiceInfo(BaseModel):
|
| 68 |
"""Voice information."""
|
| 69 |
id: str
|
| 70 |
name: str
|
| 71 |
-
gender: str
|
| 72 |
description: str
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
@app.get("/health")
|
|
@@ -80,10 +86,10 @@ async def health_check():
|
|
| 80 |
|
| 81 |
@app.get("/voices", response_model=list[VoiceInfo])
|
| 82 |
async def list_voices():
|
| 83 |
-
"""List available voices."""
|
| 84 |
return [
|
| 85 |
-
VoiceInfo(id=vid,
|
| 86 |
-
for vid, vinfo in
|
| 87 |
]
|
| 88 |
|
| 89 |
|
|
@@ -92,29 +98,69 @@ async def synthesize(request: TTSRequest):
|
|
| 92 |
"""
|
| 93 |
Synthesize speech from text.
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
Returns MP3 audio stream.
|
| 96 |
"""
|
| 97 |
if not request.text or not request.text.strip():
|
| 98 |
raise HTTPException(status_code=400, detail="Text cannot be empty")
|
| 99 |
|
| 100 |
-
if request.voice not in VOICES:
|
| 101 |
-
raise HTTPException(
|
| 102 |
-
status_code=400,
|
| 103 |
-
detail=f"Unknown voice: {request.voice}. Available: {list(VOICES.keys())}"
|
| 104 |
-
)
|
| 105 |
-
|
| 106 |
try:
|
| 107 |
model = get_model()
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
logger.info(f"🎙️ Generating speech: voice={request.voice}, text={request.text[:50]}...")
|
| 110 |
|
| 111 |
-
# Generate audio
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
# Convert to MP3
|
| 120 |
import torchaudio
|
|
@@ -135,6 +181,45 @@ async def synthesize(request: TTSRequest):
|
|
| 135 |
raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
|
| 136 |
|
| 137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
# OpenAI-compatible endpoint
|
| 139 |
@app.post("/v1/audio/speech")
|
| 140 |
async def openai_compatible_speech(request: TTSRequest):
|
|
|
|
| 2 |
Chatterbox TTS API Server
|
| 3 |
|
| 4 |
Free, emotional text-to-speech service using Resemble AI's Chatterbox.
|
| 5 |
+
Supports voice cloning with custom audio references.
|
| 6 |
"""
|
| 7 |
|
| 8 |
import io
|
| 9 |
+
import os
|
| 10 |
import logging
|
| 11 |
from typing import Optional
|
| 12 |
+
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
|
| 13 |
from fastapi.responses import StreamingResponse
|
| 14 |
from pydantic import BaseModel
|
| 15 |
|
|
|
|
| 18 |
|
| 19 |
app = FastAPI(
|
| 20 |
title="Chatterbox TTS API",
|
| 21 |
+
description="Free emotional TTS with voice cloning",
|
| 22 |
+
version="1.1.0"
|
| 23 |
)
|
| 24 |
|
| 25 |
+
# Built-in voices (multilingual)
|
| 26 |
+
BUILTIN_VOICES = {
|
| 27 |
+
"professional_male": {
|
| 28 |
+
"name": "Professional (Male)",
|
| 29 |
+
"description": "Confident business voice, works well in Russian/English",
|
| 30 |
+
"reference_path": "voices/professional_male.wav"
|
| 31 |
},
|
| 32 |
+
"friendly_male": {
|
| 33 |
+
"name": "Friendly (Male)",
|
| 34 |
+
"description": "Warm, approachable voice for building rapport",
|
| 35 |
+
"reference_path": "voices/friendly_male.wav"
|
| 36 |
},
|
| 37 |
+
"professional_female": {
|
| 38 |
+
"name": "Professional (Female)",
|
| 39 |
+
"description": "Clear, trustworthy female voice",
|
| 40 |
+
"reference_path": "voices/professional_female.wav"
|
| 41 |
}
|
| 42 |
}
|
| 43 |
|
| 44 |
+
# Custom voices storage
|
| 45 |
+
CUSTOM_VOICES_DIR = "custom_voices"
|
| 46 |
+
os.makedirs(CUSTOM_VOICES_DIR, exist_ok=True)
|
| 47 |
+
|
| 48 |
# Lazy load model
|
| 49 |
_model = None
|
| 50 |
|
| 51 |
def get_model():
|
| 52 |
global _model
|
| 53 |
if _model is None:
|
| 54 |
+
logger.info("🔄 Loading Chatterbox model (first time, may take 1-2 minutes)...")
|
| 55 |
try:
|
| 56 |
from chatterbox.tts import ChatterboxTTS
|
| 57 |
_model = ChatterboxTTS.from_pretrained(device="cpu")
|
|
|
|
| 65 |
class TTSRequest(BaseModel):
|
| 66 |
"""TTS synthesis request."""
|
| 67 |
text: str
|
| 68 |
+
voice: str = "professional_male" # Built-in or custom voice ID
|
| 69 |
exaggeration: float = 0.5 # Emotion intensity (0.0 - 1.0)
|
| 70 |
+
custom_voice_url: Optional[str] = None # URL to custom voice audio
|
| 71 |
|
| 72 |
|
| 73 |
class VoiceInfo(BaseModel):
|
| 74 |
"""Voice information."""
|
| 75 |
id: str
|
| 76 |
name: str
|
|
|
|
| 77 |
description: str
|
| 78 |
+
is_custom: bool = False
|
| 79 |
|
| 80 |
|
| 81 |
@app.get("/health")
|
|
|
|
| 86 |
|
| 87 |
@app.get("/voices", response_model=list[VoiceInfo])
|
| 88 |
async def list_voices():
|
| 89 |
+
"""List available built-in voices."""
|
| 90 |
return [
|
| 91 |
+
VoiceInfo(id=vid, name=vinfo["name"], description=vinfo["description"], is_custom=False)
|
| 92 |
+
for vid, vinfo in BUILTIN_VOICES.items()
|
| 93 |
]
|
| 94 |
|
| 95 |
|
|
|
|
| 98 |
"""
|
| 99 |
Synthesize speech from text.
|
| 100 |
|
| 101 |
+
Supports:
|
| 102 |
+
- Built-in voices (professional_male, friendly_male, professional_female)
|
| 103 |
+
- Custom voice via custom_voice_url (URL to audio file)
|
| 104 |
+
|
| 105 |
Returns MP3 audio stream.
|
| 106 |
"""
|
| 107 |
if not request.text or not request.text.strip():
|
| 108 |
raise HTTPException(status_code=400, detail="Text cannot be empty")
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
try:
|
| 111 |
model = get_model()
|
| 112 |
|
| 113 |
+
# Determine voice reference audio
|
| 114 |
+
voice_audio = None
|
| 115 |
+
|
| 116 |
+
if request.custom_voice_url:
|
| 117 |
+
# Download custom voice reference
|
| 118 |
+
import httpx
|
| 119 |
+
async with httpx.AsyncClient() as client:
|
| 120 |
+
resp = await client.get(request.custom_voice_url)
|
| 121 |
+
resp.raise_for_status()
|
| 122 |
+
voice_audio = resp.content
|
| 123 |
+
logger.info(f"🎤 Using custom voice from URL ({len(voice_audio)} bytes)")
|
| 124 |
+
|
| 125 |
+
elif request.voice in BUILTIN_VOICES:
|
| 126 |
+
# Use built-in voice
|
| 127 |
+
ref_path = BUILTIN_VOICES[request.voice]["reference_path"]
|
| 128 |
+
if os.path.exists(ref_path):
|
| 129 |
+
with open(ref_path, "rb") as f:
|
| 130 |
+
voice_audio = f.read()
|
| 131 |
+
logger.info(f"���� Using built-in voice: {request.voice}")
|
| 132 |
+
else:
|
| 133 |
+
logger.warning(f"⚠️ Voice reference not found: {ref_path}, using default")
|
| 134 |
+
|
| 135 |
+
# Check custom voice file
|
| 136 |
+
custom_path = f"{CUSTOM_VOICES_DIR}/{request.voice}.wav"
|
| 137 |
+
if voice_audio is None and os.path.exists(custom_path):
|
| 138 |
+
with open(custom_path, "rb") as f:
|
| 139 |
+
voice_audio = f.read()
|
| 140 |
+
logger.info(f"🎤 Using custom voice file: {request.voice}")
|
| 141 |
+
|
| 142 |
logger.info(f"🎙️ Generating speech: voice={request.voice}, text={request.text[:50]}...")
|
| 143 |
|
| 144 |
+
# Generate audio with or without reference
|
| 145 |
+
if voice_audio:
|
| 146 |
+
# Save temp file for reference
|
| 147 |
+
import tempfile
|
| 148 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
| 149 |
+
tmp.write(voice_audio)
|
| 150 |
+
tmp_path = tmp.name
|
| 151 |
+
|
| 152 |
+
wav = model.generate(
|
| 153 |
+
text=request.text,
|
| 154 |
+
audio_prompt_path=tmp_path,
|
| 155 |
+
exaggeration=request.exaggeration
|
| 156 |
+
)
|
| 157 |
+
os.unlink(tmp_path) # Clean up temp file
|
| 158 |
+
else:
|
| 159 |
+
# No reference - use default voice
|
| 160 |
+
wav = model.generate(
|
| 161 |
+
text=request.text,
|
| 162 |
+
exaggeration=request.exaggeration
|
| 163 |
+
)
|
| 164 |
|
| 165 |
# Convert to MP3
|
| 166 |
import torchaudio
|
|
|
|
| 181 |
raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
|
| 182 |
|
| 183 |
|
| 184 |
+
@app.post("/voices/upload")
|
| 185 |
+
async def upload_custom_voice(
|
| 186 |
+
voice_id: str = Form(...),
|
| 187 |
+
audio: UploadFile = File(...)
|
| 188 |
+
):
|
| 189 |
+
"""
|
| 190 |
+
Upload custom voice reference audio.
|
| 191 |
+
|
| 192 |
+
Requires 10-30 seconds of clear speech audio.
|
| 193 |
+
Supported formats: WAV, MP3, OGG.
|
| 194 |
+
"""
|
| 195 |
+
if not voice_id or not voice_id.strip():
|
| 196 |
+
raise HTTPException(status_code=400, detail="voice_id is required")
|
| 197 |
+
|
| 198 |
+
# Validate file size (max 10MB)
|
| 199 |
+
content = await audio.read()
|
| 200 |
+
if len(content) > 10 * 1024 * 1024:
|
| 201 |
+
raise HTTPException(status_code=400, detail="File too large (max 10MB)")
|
| 202 |
+
|
| 203 |
+
# Save file
|
| 204 |
+
save_path = f"{CUSTOM_VOICES_DIR}/{voice_id}.wav"
|
| 205 |
+
|
| 206 |
+
# Convert to WAV if needed
|
| 207 |
+
try:
|
| 208 |
+
from pydub import AudioSegment
|
| 209 |
+
audio_segment = AudioSegment.from_file(io.BytesIO(content))
|
| 210 |
+
audio_segment.export(save_path, format="wav")
|
| 211 |
+
logger.info(f"✅ Custom voice saved: {voice_id} ({len(content)} bytes)")
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.error(f"❌ Failed to process audio: {e}")
|
| 214 |
+
raise HTTPException(status_code=400, detail=f"Invalid audio format: {str(e)}")
|
| 215 |
+
|
| 216 |
+
return {
|
| 217 |
+
"status": "success",
|
| 218 |
+
"voice_id": voice_id,
|
| 219 |
+
"message": f"Voice '{voice_id}' uploaded successfully"
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
# OpenAI-compatible endpoint
|
| 224 |
@app.post("/v1/audio/speech")
|
| 225 |
async def openai_compatible_speech(request: TTSRequest):
|