From 6db8e70cf47dc6d5e2451c8e66b8cd31f895bfad Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 11 Dec 2025 00:00:40 +0800 Subject: [PATCH] feat: remove voice --- main/live-agent-api/api/v1/voices.py | 31 +++++++++++---- main/live-agent-api/repositories/agent.py | 20 ++++++++++ main/live-agent-api/services/agent_service.py | 13 +++++++ main/live-agent-api/services/voice_service.py | 39 +++++++++++++++---- 4 files changed, 87 insertions(+), 16 deletions(-) diff --git a/main/live-agent-api/api/v1/voices.py b/main/live-agent-api/api/v1/voices.py index 0aa049fec..75413fa49 100644 --- a/main/live-agent-api/api/v1/voices.py +++ b/main/live-agent-api/api/v1/voices.py @@ -8,6 +8,8 @@ from infra.fishaudio import get_fish_audio from infra.openai import get_openai from services.voice_service import voice_service from services.llm_service import llm_service +from services.agent_service import agent_service +from utils.exceptions import ConflictException from schemas.voice import ( LiveAgentVoice, DiscoverVoiceResponse, @@ -259,19 +261,32 @@ async def update_voice( async def remove_voice( voice_id: str, current_user_id: str = Depends(get_current_user_id), - db: AsyncSession = Depends(get_db) + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3), + fish_client = Depends(get_fish_audio) ): """ - Remove a voice from user's my voices - - Only deletes the database record (reference) + Remove a voice completely from user's my voices + - Checks if voice is bound to any agent (returns 409 Conflict if bound) + - Deletes from database, S3, and Fish Audio - User must own the voice """ - await voice_service.remove_voice( - db=db, - voice_id=voice_id, - owner_id=current_user_id - ) + # Check if voice is bound to any agent + is_bound = await agent_service.is_voice_bound(db=db, voice_id=voice_id) + if is_bound: + raise ConflictException("Cannot remove voice: it is currently bound to one or more agents") + try: + await voice_service.remove_voice( + db=db, + s3=s3, + fish_client=fish_client, + voice_id=voice_id, + owner_id=current_user_id + ) + except Exception as e: + return error_response(code=500, message=f"Voice removal failed: {e}") + return success_response( data={"voice_id": voice_id}, message="Voice removed successfully" diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index c4a4d5a91..f13abeb58 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -211,6 +211,26 @@ class Agent: .order_by(AgentModel.created_at.desc()) ) return list(result.scalars().all()) + + @staticmethod + async def is_voice_bound(db: AsyncSession, voice_id: str) -> bool: + """ + Check if a voice is bound to any agent + + Args: + db: Database session + voice_id: Voice ID to check + + Returns: + True if voice is bound to at least one agent + """ + result = await db.execute( + select(func.count()) + .select_from(AgentModel) + .where(AgentModel.voice_id == voice_id) + ) + count = result.scalar_one() + return count > 0 @staticmethod async def get_agents_with_latest_message( diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 65298db3d..c6567a581 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -166,6 +166,19 @@ class AgentService: List of agents with wake_word configured """ return await Agent.get_bindable_agents(db, owner_id) + + async def is_voice_bound(self, db: AsyncSession, voice_id: str) -> bool: + """ + Check if a voice is bound to any agent + + Args: + db: Database session + voice_id: Voice ID to check + + Returns: + True if voice is bound to at least one agent + """ + return await Agent.is_voice_bound(db, voice_id) async def create_agent( self, diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 10591ab8b..478a7ca0e 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -1,15 +1,16 @@ from typing import Optional, List, Tuple from sqlalchemy.ext.asyncio import AsyncSession from fastapi import UploadFile -from fishaudio import AsyncFishAudio, save +from fishaudio import AsyncFishAudio from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample from repositories import VoiceModel, Voice -from utils.ulid import generate_voice_id from repositories import FileRepository from datetime import datetime, timezone from config.logger import setup_logging +from utils.exceptions import NotFoundException + TAG = __name__ logger = setup_logging(TAG) @@ -256,26 +257,48 @@ class VoiceService: async def remove_voice( self, db: AsyncSession, + s3, + fish_client: AsyncFishAudio, voice_id: str, owner_id: str ) -> bool: """ - Remove a voice from user's my voices + Remove a voice completely: database, S3, and Fish Audio Args: db: Database session - voice_id: Internal voice ID + s3: S3 client + fish_client: Fish Audio client + voice_id: Voice ID owner_id: User ID Returns: - True if deleted, False if not found + True if deleted successfully + + Raises: + NotFoundException: If voice not found or not owned by user """ - deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id) - if not deleted: - from utils.exceptions import NotFoundException + # Get voice record first to get sample_url for S3 cleanup + voice = await Voice.get_by_voice_and_owner(db=db, voice_id=voice_id, owner_id=owner_id) + if not voice: raise NotFoundException(f"Voice {voice_id} not found or not owned by user") + sample_url = voice.sample_url + + # Delete from database first + deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id) + if not deleted: + raise NotFoundException(f"Voice {voice_id} not found or not owned by user") + + # Cleanup S3 file (best effort, don't fail if cleanup fails) + try: + if sample_url: + await self._cleanup_s3_file(s3, sample_url) + await self._cleanup_fish_voice(fish_client, voice_id) + except Exception as e: + logger.bind(tag=TAG).warning(f"Cleanup failed: {e}") + return False return True async def update_voice(