mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: clone voice with new sample url
This commit is contained in:
parent
f39547f082
commit
e69edfafd2
3 changed files with 134 additions and 56 deletions
|
|
@ -16,11 +16,13 @@ from schemas.voice import (
|
||||||
VoiceUpdateRequest,
|
VoiceUpdateRequest,
|
||||||
VoiceAddRequest
|
VoiceAddRequest
|
||||||
)
|
)
|
||||||
from utils.response import success_response
|
from utils.response import success_response, error_response
|
||||||
from api.auth import get_current_user_id
|
from api.auth import get_current_user_id
|
||||||
from config import get_logger
|
from config.logger import setup_logging
|
||||||
|
from utils.exceptions import InternalServerException
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
TAG = __name__
|
||||||
|
logger = setup_logging(TAG)
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@router.get("/discover", summary="Get Discover Voices")
|
@router.get("/discover", summary="Get Discover Voices")
|
||||||
|
|
@ -157,6 +159,7 @@ async def clone_voice(
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Clone voice, upload to S3, and save to database
|
# Clone voice, upload to S3, and save to database
|
||||||
|
try:
|
||||||
voice = await voice_service.clone_voice(
|
voice = await voice_service.clone_voice(
|
||||||
db=db,
|
db=db,
|
||||||
s3=s3,
|
s3=s3,
|
||||||
|
|
@ -166,6 +169,9 @@ async def clone_voice(
|
||||||
text=text
|
text=text
|
||||||
)
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return error_response(code=500, message=f"Voice cloning failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
return success_response(
|
return success_response(
|
||||||
data={
|
data={
|
||||||
|
|
|
||||||
|
|
@ -256,3 +256,26 @@ class FileRepository:
|
||||||
|
|
||||||
return total_deleted
|
return total_deleted
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def upload_voice_sample(
|
||||||
|
s3,
|
||||||
|
audio_data: bytes,
|
||||||
|
voice_id: str,
|
||||||
|
file_ext: str = "mp3"
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Upload TTS-generated voice sample to S3
|
||||||
|
...
|
||||||
|
"""
|
||||||
|
filename = f"{voice_id}.{file_ext}"
|
||||||
|
s3_key = f"voice_samples/{filename}"
|
||||||
|
|
||||||
|
await s3.put_object(
|
||||||
|
Bucket=settings.S3_BUCKET_NAME,
|
||||||
|
Key=s3_key,
|
||||||
|
Body=audio_data,
|
||||||
|
ContentType=f"audio/{file_ext}",
|
||||||
|
)
|
||||||
|
|
||||||
|
url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}"
|
||||||
|
return url
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
from typing import Optional, List, Tuple
|
from typing import Optional, List, Tuple
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from fastapi import UploadFile
|
from fastapi import UploadFile
|
||||||
from fishaudio import AsyncFishAudio
|
from fishaudio import AsyncFishAudio, save
|
||||||
from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample
|
from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample
|
||||||
|
|
||||||
from repositories import VoiceModel, Voice
|
from repositories import VoiceModel, Voice
|
||||||
|
|
@ -9,6 +9,13 @@ from utils.ulid import generate_voice_id
|
||||||
|
|
||||||
from repositories import FileRepository
|
from repositories import FileRepository
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging(TAG)
|
||||||
|
|
||||||
|
# Default sample text for TTS preview when user doesn't provide text
|
||||||
|
DEFAULT_SAMPLE_TEXT = "The only way to do great work is to love what you do."
|
||||||
class VoiceService:
|
class VoiceService:
|
||||||
"""Voice service layer"""
|
"""Voice service layer"""
|
||||||
|
|
||||||
|
|
@ -101,7 +108,13 @@ class VoiceService:
|
||||||
text: Optional[str] = None
|
text: Optional[str] = None
|
||||||
) -> VoiceModel:
|
) -> VoiceModel:
|
||||||
"""
|
"""
|
||||||
Clone a voice using Fish Audio API, store audio, and save to database
|
Clone a voice using Fish Audio API, generate TTS preview, and save to database
|
||||||
|
|
||||||
|
Flow:
|
||||||
|
1. Clone voice from uploaded audio + optional text
|
||||||
|
2. Generate TTS preview audio using the new voice (with provided or default text)
|
||||||
|
3. Upload TTS preview to S3 as sample_url
|
||||||
|
4. Create voice record in database
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
db: Database session
|
db: Database session
|
||||||
|
|
@ -109,55 +122,91 @@ class VoiceService:
|
||||||
fish_client: Fish Audio client
|
fish_client: Fish Audio client
|
||||||
owner_id: User ID
|
owner_id: User ID
|
||||||
audio_file: Audio file to clone
|
audio_file: Audio file to clone
|
||||||
text: Optional transcription text
|
text: Optional transcription text (also used for TTS preview)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Created VoiceModel
|
Created VoiceModel
|
||||||
"""
|
|
||||||
# Generate voice_id for our system
|
|
||||||
voice_id = generate_voice_id()
|
|
||||||
|
|
||||||
# Read audio file content
|
Raises:
|
||||||
|
InternalServerException: When any downstream service fails
|
||||||
|
"""
|
||||||
|
from utils.exceptions import InternalServerException
|
||||||
|
|
||||||
|
fish_voice_id: Optional[str] = None
|
||||||
|
sample_url: Optional[str] = None
|
||||||
|
sample_text = text if text else DEFAULT_SAMPLE_TEXT
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Read audio file content for cloning
|
||||||
audio_content = await audio_file.read()
|
audio_content = await audio_file.read()
|
||||||
|
|
||||||
# Reset file pointer for S3 upload
|
# Step 1: Clone voice using Fish Audio API
|
||||||
await audio_file.seek(0)
|
|
||||||
|
|
||||||
# Upload audio to S3 for storage (using voice_id as filename)
|
|
||||||
|
|
||||||
sample_url = await FileRepository.upload(
|
|
||||||
s3=s3,
|
|
||||||
file=audio_file,
|
|
||||||
folder="voice_samples",
|
|
||||||
custom_filename=voice_id
|
|
||||||
)
|
|
||||||
|
|
||||||
# Call Fish Audio API to clone voice
|
|
||||||
fish_voice: FishVoice = await fish_client.voices.create(
|
fish_voice: FishVoice = await fish_client.voices.create(
|
||||||
title=f"live_agent_{voice_id}",
|
title=f"live_agent_{owner_id}_{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}",
|
||||||
voices=[audio_content],
|
voices=[audio_content],
|
||||||
texts=[text] if text else None,
|
texts=[text] if text else None,
|
||||||
train_mode="fast",
|
train_mode="fast",
|
||||||
visibility="private",
|
visibility="private",
|
||||||
enhance_audio_quality=True
|
enhance_audio_quality=True
|
||||||
)
|
)
|
||||||
|
fish_voice_id = fish_voice.id
|
||||||
|
|
||||||
# Create voice record in database
|
# Step 2: Generate TTS preview using the new voice
|
||||||
|
logger.bind(tag=TAG).info(f"Generating TTS preview with voice {fish_voice_id}")
|
||||||
|
audio_bytes = await fish_client.tts.convert(
|
||||||
|
text=sample_text,
|
||||||
|
reference_id=fish_voice_id,
|
||||||
|
format="mp3"
|
||||||
|
)
|
||||||
|
logger.bind(tag=TAG).info(f"TTS preview generated, size: {len(audio_bytes)} bytes")
|
||||||
|
|
||||||
default_name = f"{owner_id}'s Cloned Voice {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')}"
|
# Step 3: Upload TTS preview audio to S3
|
||||||
|
sample_url = await FileRepository.upload_voice_sample(
|
||||||
|
s3=s3,
|
||||||
|
audio_data=audio_bytes,
|
||||||
|
voice_id=fish_voice_id,
|
||||||
|
file_ext="mp3"
|
||||||
|
)
|
||||||
|
logger.bind(tag=TAG).info(f"TTS preview uploaded to S3: {sample_url}")
|
||||||
|
|
||||||
|
# Step 4: Create voice record in database
|
||||||
voice = await Voice.create(
|
voice = await Voice.create(
|
||||||
db=db,
|
db=db,
|
||||||
voice_id=fish_voice.id, # Use Fish Audio voice ID
|
voice_id=fish_voice_id,
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
name=default_name,
|
name="Cloned Voice",
|
||||||
desc="", # Empty description, to be updated later
|
desc="",
|
||||||
sample_url=sample_url,
|
sample_url=sample_url,
|
||||||
sample_text=text
|
sample_text=sample_text
|
||||||
)
|
)
|
||||||
|
|
||||||
return voice
|
return voice
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Clone voice failed: {e}")
|
||||||
|
# Cleanup created resources based on what was successfully created
|
||||||
|
if sample_url:
|
||||||
|
await self._cleanup_s3_file(s3, sample_url)
|
||||||
|
if fish_voice_id:
|
||||||
|
await self._cleanup_fish_voice(fish_client, fish_voice_id)
|
||||||
|
raise InternalServerException(f"Voice cloning failed: {str(e)}")
|
||||||
|
|
||||||
|
async def _cleanup_fish_voice(self, fish_client: AsyncFishAudio, voice_id: str) -> None:
|
||||||
|
"""Cleanup helper: delete voice from Fish Audio"""
|
||||||
|
try:
|
||||||
|
await fish_client.voices.delete(voice_id)
|
||||||
|
logger.bind(tag=TAG).info(f"Cleanup: deleted Fish Audio voice {voice_id}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"Cleanup failed: could not delete Fish Audio voice {voice_id}: {e}")
|
||||||
|
|
||||||
|
async def _cleanup_s3_file(self, s3, url: str) -> None:
|
||||||
|
"""Cleanup helper: delete file from S3"""
|
||||||
|
try:
|
||||||
|
await FileRepository.delete(s3, url)
|
||||||
|
logger.bind(tag=TAG).info(f"Cleanup: deleted S3 file {url}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"Cleanup failed: could not delete S3 file {url}: {e}")
|
||||||
|
|
||||||
async def add_voice(
|
async def add_voice(
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue