mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: voice clone with sample(s3)
This commit is contained in:
parent
600cba974a
commit
a419b8a607
5 changed files with 112 additions and 40 deletions
|
|
@ -3,7 +3,7 @@ from botocore.args import logger
|
||||||
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
|
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from infra import get_db
|
from infra import get_db, get_s3
|
||||||
from infra.fishaudio import get_fish_audio
|
from infra.fishaudio import get_fish_audio
|
||||||
from services.voice_service import voice_service
|
from services.voice_service import voice_service
|
||||||
from schemas.voice import (
|
from schemas.voice import (
|
||||||
|
|
@ -138,36 +138,36 @@ async def get_my_voices(
|
||||||
async def clone_voice(
|
async def clone_voice(
|
||||||
audio_file: UploadFile = File(..., description="Audio file for cloning"),
|
audio_file: UploadFile = File(..., description="Audio file for cloning"),
|
||||||
text: Optional[str] = Form(None, description="Optional transcription text"),
|
text: Optional[str] = Form(None, description="Optional transcription text"),
|
||||||
fish_client = Depends(get_fish_audio)
|
current_user_id: str = Depends(get_current_user_id),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
fish_client = Depends(get_fish_audio),
|
||||||
|
s3 = Depends(get_s3)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Clone a voice from uploaded audio file
|
Clone a voice from uploaded audio file
|
||||||
- Supports both direct audio upload and recorded audio
|
- Requires authentication
|
||||||
- Text parameter is optional (required for recorded audio)
|
- Stores the original audio in S3
|
||||||
|
- Creates voice record in database with default name
|
||||||
|
- Use PUT /{voice_id} to update name and description later
|
||||||
- Uses Fish Audio's fast training mode (typically 30s-2min)
|
- Uses Fish Audio's fast training mode (typically 30s-2min)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Clone voice
|
# Clone voice, upload to S3, and save to database
|
||||||
voice_id, samples = await voice_service.clone_voice(
|
voice = await voice_service.clone_voice(
|
||||||
|
db=db,
|
||||||
|
s3=s3,
|
||||||
fish_client=fish_client,
|
fish_client=fish_client,
|
||||||
|
owner_id=current_user_id,
|
||||||
audio_file=audio_file,
|
audio_file=audio_file,
|
||||||
text=text
|
text=text
|
||||||
)
|
)
|
||||||
|
|
||||||
# Build response
|
|
||||||
if samples:
|
|
||||||
sample = AudioSample(
|
|
||||||
title=samples[0].title,
|
|
||||||
text=samples[0].text,
|
|
||||||
audio=samples[0].audio
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
sample = None
|
|
||||||
|
|
||||||
return success_response(
|
return success_response(
|
||||||
data={
|
data={
|
||||||
"voice_id": voice_id,
|
"voice_id": voice.voice_id,
|
||||||
"sample": sample,
|
"sample_url": voice.sample_url, # S3 URL of stored audio
|
||||||
|
"sample_text": voice.sample_text # Transcription text
|
||||||
},
|
},
|
||||||
message="Voice cloned successfully"
|
message="Voice cloned successfully"
|
||||||
)
|
)
|
||||||
|
|
@ -185,6 +185,7 @@ async def add_voice(
|
||||||
Add a Fish Audio voice to user's my voices
|
Add a Fish Audio voice to user's my voices
|
||||||
- Creates a reference to the Fish Audio voice
|
- Creates a reference to the Fish Audio voice
|
||||||
- Name is provided by client (from Fish voice title)
|
- Name is provided by client (from Fish voice title)
|
||||||
|
- For cloned voices, can include sample_url and sample_text
|
||||||
"""
|
"""
|
||||||
voice = await voice_service.add_voice(
|
voice = await voice_service.add_voice(
|
||||||
db=db,
|
db=db,
|
||||||
|
|
@ -192,7 +193,9 @@ async def add_voice(
|
||||||
owner_id=current_user_id,
|
owner_id=current_user_id,
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
name=request.name,
|
name=request.name,
|
||||||
desc=request.desc
|
desc=request.desc,
|
||||||
|
sample_url=request.sample_url,
|
||||||
|
sample_text=request.sample_text
|
||||||
)
|
)
|
||||||
|
|
||||||
# Build response
|
# Build response
|
||||||
|
|
@ -200,6 +203,8 @@ async def add_voice(
|
||||||
data=LiveAgentVoice(
|
data=LiveAgentVoice(
|
||||||
voice_id=voice.voice_id,
|
voice_id=voice.voice_id,
|
||||||
name=voice.name,
|
name=voice.name,
|
||||||
|
desc=voice.desc,
|
||||||
|
created_at=voice.created_at,
|
||||||
).model_dump(exclude_none=True),
|
).model_dump(exclude_none=True),
|
||||||
message="Voice added successfully"
|
message="Voice added successfully"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -66,6 +66,8 @@ CREATE TABLE IF NOT EXISTS voices (
|
||||||
owner_id VARCHAR(50) NOT NULL,
|
owner_id VARCHAR(50) NOT NULL,
|
||||||
name VARCHAR(100) NOT NULL,
|
name VARCHAR(100) NOT NULL,
|
||||||
"desc" TEXT NOT NULL DEFAULT '',
|
"desc" TEXT NOT NULL DEFAULT '',
|
||||||
|
sample_url TEXT,
|
||||||
|
sample_text TEXT,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
||||||
CONSTRAINT fk_voices_owner FOREIGN KEY (owner_id)
|
CONSTRAINT fk_voices_owner FOREIGN KEY (owner_id)
|
||||||
|
|
@ -84,6 +86,8 @@ COMMENT ON COLUMN voices.voice_id IS 'Fish Audio voice ID';
|
||||||
COMMENT ON COLUMN voices.owner_id IS 'User ID of voice owner';
|
COMMENT ON COLUMN voices.owner_id IS 'User ID of voice owner';
|
||||||
COMMENT ON COLUMN voices.name IS 'Voice display name';
|
COMMENT ON COLUMN voices.name IS 'Voice display name';
|
||||||
COMMENT ON COLUMN voices."desc" IS 'Voice description';
|
COMMENT ON COLUMN voices."desc" IS 'Voice description';
|
||||||
|
COMMENT ON COLUMN voices.sample_url IS 'S3 URL of the original audio sample (for cloned voices)';
|
||||||
|
COMMENT ON COLUMN voices.sample_text IS 'Transcription text of the audio sample (for cloned voices)';
|
||||||
|
|
||||||
-- ==================== Table: agent_templates ====================
|
-- ==================== Table: agent_templates ====================
|
||||||
-- Pre-configured agent templates
|
-- Pre-configured agent templates
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,10 @@ class VoiceModel(Base):
|
||||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
desc: Mapped[str] = mapped_column(Text, nullable=False)
|
desc: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
|
||||||
|
# Audio sample information (for cloned voices)
|
||||||
|
sample_url: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
sample_text: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
# Timestamps
|
# Timestamps
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
TIMESTAMP(timezone=True),
|
TIMESTAMP(timezone=True),
|
||||||
|
|
@ -161,14 +165,18 @@ class Voice:
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
name: str,
|
name: str,
|
||||||
desc: str
|
desc: str,
|
||||||
|
sample_url: Optional[str] = None,
|
||||||
|
sample_text: Optional[str] = None
|
||||||
) -> VoiceModel:
|
) -> VoiceModel:
|
||||||
"""Create a new voice"""
|
"""Create a new voice"""
|
||||||
voice = VoiceModel(
|
voice = VoiceModel(
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
name=name,
|
name=name,
|
||||||
desc=desc
|
desc=desc,
|
||||||
|
sample_url=sample_url,
|
||||||
|
sample_text=sample_text
|
||||||
)
|
)
|
||||||
db.add(voice)
|
db.add(voice)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
@ -180,18 +188,30 @@ class Voice:
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
name: str,
|
name: Optional[str] = None,
|
||||||
desc: str
|
desc: Optional[str] = None
|
||||||
) -> VoiceModel:
|
) -> VoiceModel:
|
||||||
"""Update a voice"""
|
"""Update a voice (only updates provided fields)"""
|
||||||
|
# Build update values dict with only non-None values
|
||||||
|
update_values = {}
|
||||||
|
if name is not None:
|
||||||
|
update_values['name'] = name
|
||||||
|
if desc is not None:
|
||||||
|
update_values['desc'] = desc
|
||||||
|
|
||||||
|
# If no fields to update, just return the existing voice
|
||||||
|
if not update_values:
|
||||||
|
voice = await Voice.get_by_voice_and_owner(db, voice_id, owner_id)
|
||||||
|
return voice
|
||||||
|
|
||||||
stmt = (
|
stmt = (
|
||||||
update(VoiceModel)
|
update(VoiceModel)
|
||||||
.where(VoiceModel.voice_id == voice_id)
|
.where(VoiceModel.voice_id == voice_id)
|
||||||
.where(VoiceModel.owner_id == owner_id)
|
.where(VoiceModel.owner_id == owner_id)
|
||||||
.values(name=name, desc=desc)
|
.values(**update_values)
|
||||||
.returning(VoiceModel)
|
.returning(VoiceModel)
|
||||||
)
|
)
|
||||||
result =await db.execute(stmt)
|
result = await db.execute(stmt)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
return result.scalar_one()
|
return result.scalar_one()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,8 @@ class VoiceAddRequest(BaseModel):
|
||||||
"""Voice add request"""
|
"""Voice add request"""
|
||||||
name: str = Field(..., min_length=1, max_length=100, description="Voice name")
|
name: str = Field(..., min_length=1, max_length=100, description="Voice name")
|
||||||
desc: str = Field(..., max_length=500, description="Voice description")
|
desc: str = Field(..., max_length=500, description="Voice description")
|
||||||
|
sample_url: Optional[str] = Field(None, description="URL of stored audio sample (for cloned voices)")
|
||||||
|
sample_text: Optional[str] = Field(None, description="Transcription text (for cloned voices)")
|
||||||
|
|
||||||
# ==================== Response Schemas ====================
|
# ==================== Response Schemas ====================
|
||||||
|
|
||||||
|
|
@ -40,7 +42,7 @@ class LiveAgentVoice(BaseModel):
|
||||||
|
|
||||||
samples: Optional[List[AudioSample]] = None
|
samples: Optional[List[AudioSample]] = None
|
||||||
|
|
||||||
created_at: datetime
|
created_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,9 @@ from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as Fis
|
||||||
|
|
||||||
from repositories import VoiceModel, Voice
|
from repositories import VoiceModel, Voice
|
||||||
from utils.ulid import generate_voice_id
|
from utils.ulid import generate_voice_id
|
||||||
|
|
||||||
|
from repositories import FileRepository
|
||||||
|
from datetime import datetime, timezone
|
||||||
class VoiceService:
|
class VoiceService:
|
||||||
"""Voice service layer"""
|
"""Voice service layer"""
|
||||||
|
|
||||||
|
|
@ -90,28 +93,45 @@ class VoiceService:
|
||||||
|
|
||||||
async def clone_voice(
|
async def clone_voice(
|
||||||
self,
|
self,
|
||||||
|
db: AsyncSession,
|
||||||
|
s3, # S3 client for storing audio
|
||||||
fish_client: AsyncFishAudio,
|
fish_client: AsyncFishAudio,
|
||||||
|
owner_id: str,
|
||||||
audio_file: UploadFile,
|
audio_file: UploadFile,
|
||||||
text: Optional[str] = None
|
text: Optional[str] = None
|
||||||
) -> Tuple[str, List[FishSample]]:
|
) -> VoiceModel:
|
||||||
"""
|
"""
|
||||||
Clone a voice using Fish Audio API
|
Clone a voice using Fish Audio API, store audio, and save to database
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
db: Database session
|
db: Database session
|
||||||
|
s3: S3 client for storing audio
|
||||||
fish_client: Fish Audio client
|
fish_client: Fish Audio client
|
||||||
name: Voice name
|
|
||||||
owner_id: User ID
|
owner_id: User ID
|
||||||
name: Voice name
|
|
||||||
audio_file: Audio file to clone
|
audio_file: Audio file to clone
|
||||||
text: Optional transcription text
|
text: Optional transcription text
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Created VoiceModel
|
Created VoiceModel
|
||||||
"""
|
"""
|
||||||
|
# Generate voice_id for our system
|
||||||
|
voice_id = generate_voice_id()
|
||||||
|
|
||||||
# Read audio file content
|
# Read audio file content
|
||||||
audio_content = await audio_file.read()
|
audio_content = await audio_file.read()
|
||||||
voice_id = generate_voice_id()
|
|
||||||
|
# Reset file pointer for S3 upload
|
||||||
|
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
|
# 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_{voice_id}",
|
||||||
|
|
@ -121,7 +141,22 @@ class VoiceService:
|
||||||
visibility="private",
|
visibility="private",
|
||||||
enhance_audio_quality=True
|
enhance_audio_quality=True
|
||||||
)
|
)
|
||||||
return fish_voice.id, fish_voice.samples
|
|
||||||
|
# Create voice record in database
|
||||||
|
|
||||||
|
default_name = f"{owner_id}'s Cloned Voice {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')}"
|
||||||
|
|
||||||
|
voice = await Voice.create(
|
||||||
|
db=db,
|
||||||
|
voice_id=fish_voice.id, # Use Fish Audio voice ID
|
||||||
|
owner_id=owner_id,
|
||||||
|
name=default_name,
|
||||||
|
desc="", # Empty description, to be updated later
|
||||||
|
sample_url=sample_url,
|
||||||
|
sample_text=text
|
||||||
|
)
|
||||||
|
|
||||||
|
return voice
|
||||||
|
|
||||||
async def add_voice(
|
async def add_voice(
|
||||||
self,
|
self,
|
||||||
|
|
@ -131,6 +166,8 @@ class VoiceService:
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
name: str,
|
name: str,
|
||||||
desc: str,
|
desc: str,
|
||||||
|
sample_url: Optional[str] = None,
|
||||||
|
sample_text: Optional[str] = None
|
||||||
) -> VoiceModel:
|
) -> VoiceModel:
|
||||||
"""
|
"""
|
||||||
Add a Fish Audio voice to user's my voices
|
Add a Fish Audio voice to user's my voices
|
||||||
|
|
@ -142,6 +179,8 @@ class VoiceService:
|
||||||
voice_id: Audio voice ID
|
voice_id: Audio voice ID
|
||||||
name: Voice name
|
name: Voice name
|
||||||
desc: Voice description
|
desc: Voice description
|
||||||
|
sample_url: Optional URL of stored audio sample (for cloned voices)
|
||||||
|
sample_text: Optional transcription text (for cloned voices)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Created VoiceModel
|
Created VoiceModel
|
||||||
|
|
@ -158,7 +197,9 @@ class VoiceService:
|
||||||
voice_id=voice_id, # Use Fish Audio voice ID directly
|
voice_id=voice_id, # Use Fish Audio voice ID directly
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
name=name,
|
name=name,
|
||||||
desc=desc
|
desc=desc,
|
||||||
|
sample_url=sample_url,
|
||||||
|
sample_text=sample_text
|
||||||
)
|
)
|
||||||
|
|
||||||
return voice
|
return voice
|
||||||
|
|
@ -193,8 +234,8 @@ class VoiceService:
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
name: str,
|
name: Optional[str] = None,
|
||||||
desc: str
|
desc: Optional[str] = None
|
||||||
) -> VoiceModel:
|
) -> VoiceModel:
|
||||||
"""
|
"""
|
||||||
Update voice name and/or description
|
Update voice name and/or description
|
||||||
|
|
@ -203,13 +244,13 @@ class VoiceService:
|
||||||
db: Database session
|
db: Database session
|
||||||
voice_id: Voice ID
|
voice_id: Voice ID
|
||||||
owner_id: User ID
|
owner_id: User ID
|
||||||
name: New voice name
|
name: New voice name (optional)
|
||||||
desc: New voice description
|
desc: New voice description (optional)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Updated VoiceModel
|
Updated VoiceModel
|
||||||
"""
|
"""
|
||||||
# Get existing voice
|
# Get existing voice to verify ownership
|
||||||
voice = await Voice.get_by_voice_and_owner(
|
voice = await Voice.get_by_voice_and_owner(
|
||||||
db=db,
|
db=db,
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
|
|
@ -221,7 +262,7 @@ class VoiceService:
|
||||||
raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
|
raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
|
||||||
|
|
||||||
# Update only provided fields
|
# Update only provided fields
|
||||||
new_voice = await Voice.update(
|
updated_voice = await Voice.update(
|
||||||
db=db,
|
db=db,
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
|
|
@ -229,7 +270,7 @@ class VoiceService:
|
||||||
desc=desc
|
desc=desc
|
||||||
)
|
)
|
||||||
|
|
||||||
return new_voice
|
return updated_voice
|
||||||
|
|
||||||
|
|
||||||
voice_service = VoiceService()
|
voice_service = VoiceService()
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue