feat: remove voice

This commit is contained in:
Harold 2025-12-11 00:00:40 +08:00
parent e69edfafd2
commit 6db8e70cf4
4 changed files with 87 additions and 16 deletions

View file

@ -8,6 +8,8 @@ from infra.fishaudio import get_fish_audio
from infra.openai import get_openai from infra.openai import get_openai
from services.voice_service import voice_service from services.voice_service import voice_service
from services.llm_service import llm_service from services.llm_service import llm_service
from services.agent_service import agent_service
from utils.exceptions import ConflictException
from schemas.voice import ( from schemas.voice import (
LiveAgentVoice, LiveAgentVoice,
DiscoverVoiceResponse, DiscoverVoiceResponse,
@ -259,18 +261,31 @@ async def update_voice(
async def remove_voice( async def remove_voice(
voice_id: str, voice_id: str,
current_user_id: str = Depends(get_current_user_id), 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 Remove a voice completely from user's my voices
- Only deletes the database record (reference) - 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 - User must own the voice
""" """
# 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( await voice_service.remove_voice(
db=db, db=db,
s3=s3,
fish_client=fish_client,
voice_id=voice_id, voice_id=voice_id,
owner_id=current_user_id owner_id=current_user_id
) )
except Exception as e:
return error_response(code=500, message=f"Voice removal failed: {e}")
return success_response( return success_response(
data={"voice_id": voice_id}, data={"voice_id": voice_id},

View file

@ -212,6 +212,26 @@ class Agent:
) )
return list(result.scalars().all()) 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 @staticmethod
async def get_agents_with_latest_message( async def get_agents_with_latest_message(
db: AsyncSession, db: AsyncSession,

View file

@ -167,6 +167,19 @@ class AgentService:
""" """
return await Agent.get_bindable_agents(db, owner_id) 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( async def create_agent(
self, self,
db: AsyncSession, db: AsyncSession,

View file

@ -1,15 +1,16 @@
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, save from fishaudio import AsyncFishAudio
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
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 from config.logger import setup_logging
from utils.exceptions import NotFoundException
TAG = __name__ TAG = __name__
logger = setup_logging(TAG) logger = setup_logging(TAG)
@ -256,26 +257,48 @@ class VoiceService:
async def remove_voice( async def remove_voice(
self, self,
db: AsyncSession, db: AsyncSession,
s3,
fish_client: AsyncFishAudio,
voice_id: str, voice_id: str,
owner_id: str owner_id: str
) -> bool: ) -> bool:
""" """
Remove a voice from user's my voices Remove a voice completely: database, S3, and Fish Audio
Args: Args:
db: Database session db: Database session
voice_id: Internal voice ID s3: S3 client
fish_client: Fish Audio client
voice_id: Voice ID
owner_id: User ID owner_id: User ID
Returns: Returns:
True if deleted, False if not found True if deleted successfully
"""
deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id)
if not deleted: Raises:
from utils.exceptions import NotFoundException NotFoundException: If voice not found or not owned by user
"""
# 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") 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 return True
async def update_voice( async def update_voice(