diff --git a/main/live-agent-api/api/v1/voices.py b/main/live-agent-api/api/v1/voices.py index cd27c3d74..6c3f3043d 100644 --- a/main/live-agent-api/api/v1/voices.py +++ b/main/live-agent-api/api/v1/voices.py @@ -3,7 +3,7 @@ from botocore.args import logger from fastapi import APIRouter, Depends, Query, Form, File, UploadFile 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 services.voice_service import voice_service from schemas.voice import ( @@ -138,36 +138,36 @@ async def get_my_voices( async def clone_voice( audio_file: UploadFile = File(..., description="Audio file for cloning"), 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 - - Supports both direct audio upload and recorded audio - - Text parameter is optional (required for recorded audio) + - Requires authentication + - 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) """ - # Clone voice - voice_id, samples = await voice_service.clone_voice( + # Clone voice, upload to S3, and save to database + voice = await voice_service.clone_voice( + db=db, + s3=s3, fish_client=fish_client, + owner_id=current_user_id, audio_file=audio_file, 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( data={ - "voice_id": voice_id, - "sample": sample, + "voice_id": voice.voice_id, + "sample_url": voice.sample_url, # S3 URL of stored audio + "sample_text": voice.sample_text # Transcription text }, message="Voice cloned successfully" ) @@ -185,6 +185,7 @@ async def add_voice( Add a Fish Audio voice to user's my voices - Creates a reference to the Fish Audio voice - 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( db=db, @@ -192,7 +193,9 @@ async def add_voice( owner_id=current_user_id, voice_id=voice_id, name=request.name, - desc=request.desc + desc=request.desc, + sample_url=request.sample_url, + sample_text=request.sample_text ) # Build response @@ -200,6 +203,8 @@ async def add_voice( data=LiveAgentVoice( voice_id=voice.voice_id, name=voice.name, + desc=voice.desc, + created_at=voice.created_at, ).model_dump(exclude_none=True), message="Voice added successfully" ) diff --git a/main/live-agent-api/init_db.sql b/main/live-agent-api/init_db.sql index e81c24d2f..db4e9c61a 100644 --- a/main/live-agent-api/init_db.sql +++ b/main/live-agent-api/init_db.sql @@ -66,6 +66,8 @@ CREATE TABLE IF NOT EXISTS voices ( owner_id VARCHAR(50) NOT NULL, name VARCHAR(100) NOT NULL, "desc" TEXT NOT NULL DEFAULT '', + sample_url TEXT, + sample_text TEXT, created_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) @@ -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.name IS 'Voice display name'; 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 ==================== -- Pre-configured agent templates diff --git a/main/live-agent-api/repositories/voice.py b/main/live-agent-api/repositories/voice.py index 0af5bc715..6f83fb84d 100644 --- a/main/live-agent-api/repositories/voice.py +++ b/main/live-agent-api/repositories/voice.py @@ -29,6 +29,10 @@ class VoiceModel(Base): name: Mapped[str] = mapped_column(String(100), 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 created_at: Mapped[datetime] = mapped_column( TIMESTAMP(timezone=True), @@ -161,14 +165,18 @@ class Voice: voice_id: str, owner_id: str, name: str, - desc: str + desc: str, + sample_url: Optional[str] = None, + sample_text: Optional[str] = None ) -> VoiceModel: """Create a new voice""" voice = VoiceModel( voice_id=voice_id, owner_id=owner_id, name=name, - desc=desc + desc=desc, + sample_url=sample_url, + sample_text=sample_text ) db.add(voice) await db.commit() @@ -180,18 +188,30 @@ class Voice: db: AsyncSession, voice_id: str, owner_id: str, - name: str, - desc: str + name: Optional[str] = None, + desc: Optional[str] = None ) -> 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 = ( update(VoiceModel) .where(VoiceModel.voice_id == voice_id) .where(VoiceModel.owner_id == owner_id) - .values(name=name, desc=desc) + .values(**update_values) .returning(VoiceModel) ) - result =await db.execute(stmt) + result = await db.execute(stmt) await db.commit() return result.scalar_one() diff --git a/main/live-agent-api/schemas/voice.py b/main/live-agent-api/schemas/voice.py index 1c70d79ab..85f15be68 100644 --- a/main/live-agent-api/schemas/voice.py +++ b/main/live-agent-api/schemas/voice.py @@ -23,6 +23,8 @@ class VoiceAddRequest(BaseModel): """Voice add request""" name: str = Field(..., min_length=1, max_length=100, description="Voice name") 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 ==================== @@ -40,7 +42,7 @@ class LiveAgentVoice(BaseModel): samples: Optional[List[AudioSample]] = None - created_at: datetime + created_at: Optional[datetime] = None diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 9c0be14e9..3a9c02073 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -6,6 +6,9 @@ from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as Fis from repositories import VoiceModel, Voice from utils.ulid import generate_voice_id + +from repositories import FileRepository +from datetime import datetime, timezone class VoiceService: """Voice service layer""" @@ -90,28 +93,45 @@ class VoiceService: async def clone_voice( self, + db: AsyncSession, + s3, # S3 client for storing audio fish_client: AsyncFishAudio, + owner_id: str, audio_file: UploadFile, 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: db: Database session + s3: S3 client for storing audio fish_client: Fish Audio client - name: Voice name owner_id: User ID - name: Voice name audio_file: Audio file to clone text: Optional transcription text Returns: Created VoiceModel """ + # Generate voice_id for our system + voice_id = generate_voice_id() + # Read audio file content 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 fish_voice: FishVoice = await fish_client.voices.create( title=f"live_agent_{voice_id}", @@ -121,7 +141,22 @@ class VoiceService: visibility="private", 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( self, @@ -131,6 +166,8 @@ class VoiceService: voice_id: str, name: str, desc: str, + sample_url: Optional[str] = None, + sample_text: Optional[str] = None ) -> VoiceModel: """ Add a Fish Audio voice to user's my voices @@ -142,6 +179,8 @@ class VoiceService: voice_id: Audio voice ID name: Voice name desc: Voice description + sample_url: Optional URL of stored audio sample (for cloned voices) + sample_text: Optional transcription text (for cloned voices) Returns: Created VoiceModel @@ -158,7 +197,9 @@ class VoiceService: voice_id=voice_id, # Use Fish Audio voice ID directly owner_id=owner_id, name=name, - desc=desc + desc=desc, + sample_url=sample_url, + sample_text=sample_text ) return voice @@ -193,8 +234,8 @@ class VoiceService: db: AsyncSession, voice_id: str, owner_id: str, - name: str, - desc: str + name: Optional[str] = None, + desc: Optional[str] = None ) -> VoiceModel: """ Update voice name and/or description @@ -203,13 +244,13 @@ class VoiceService: db: Database session voice_id: Voice ID owner_id: User ID - name: New voice name - desc: New voice description + name: New voice name (optional) + desc: New voice description (optional) Returns: Updated VoiceModel """ - # Get existing voice + # Get existing voice to verify ownership voice = await Voice.get_by_voice_and_owner( db=db, voice_id=voice_id, @@ -221,7 +262,7 @@ class VoiceService: raise NotFoundException(f"Voice {voice_id} not found or not owned by user") # Update only provided fields - new_voice = await Voice.update( + updated_voice = await Voice.update( db=db, voice_id=voice_id, owner_id=owner_id, @@ -229,7 +270,7 @@ class VoiceService: desc=desc ) - return new_voice + return updated_voice voice_service = VoiceService()