mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: cursor pagination
This commit is contained in:
parent
f835bb0774
commit
9620b9f1df
8 changed files with 178 additions and 54 deletions
|
|
@ -12,16 +12,25 @@ router = APIRouter()
|
||||||
|
|
||||||
@router.get("", summary="Get user's agent list")
|
@router.get("", summary="Get user's agent list")
|
||||||
async def get_agent_list(
|
async def get_agent_list(
|
||||||
page: int = Query(1, ge=1),
|
cursor: Optional[str] = Query(None, description="Pagination cursor"),
|
||||||
page_size: int = Query(10, ge=1, le=20),
|
page_size: int = Query(10, ge=1, le=20, description="Number of items per page"),
|
||||||
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)
|
||||||
):
|
):
|
||||||
"""Get user's agent list"""
|
"""
|
||||||
|
Get user's agent list with cursor-based pagination
|
||||||
|
|
||||||
|
Cursor-based pagination prevents data drift when creating/deleting agents:
|
||||||
|
- **First request**: No cursor parameter needed
|
||||||
|
- **Subsequent requests**: Use `next_cursor` from previous response
|
||||||
|
- **Returns**: List of agents with `next_cursor` and `has_more` flag
|
||||||
|
|
||||||
|
Agents are ordered by creation time (newest first).
|
||||||
|
"""
|
||||||
agent_list = await agent_service.get_agent_list(
|
agent_list = await agent_service.get_agent_list(
|
||||||
db=db,
|
db=db,
|
||||||
owner_id=current_user_id,
|
owner_id=current_user_id,
|
||||||
page=page,
|
cursor=cursor,
|
||||||
page_size=page_size
|
page_size=page_size
|
||||||
)
|
)
|
||||||
return success_response(data=agent_list.model_dump())
|
return success_response(data=agent_list.model_dump())
|
||||||
|
|
|
||||||
|
|
@ -91,20 +91,27 @@ async def get_default_voices(
|
||||||
|
|
||||||
@router.get("/", summary="Get My Voices")
|
@router.get("/", summary="Get My Voices")
|
||||||
async def get_my_voices(
|
async def get_my_voices(
|
||||||
page: int = Query(1, ge=1),
|
cursor: Optional[str] = Query(None, description="Pagination cursor (ISO datetime from previous response)"),
|
||||||
page_size: int = Query(20, ge=1, le=100),
|
page_size: int = Query(10, ge=1, le=50, description="Number of items per page"),
|
||||||
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)
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Get user's custom voices (my_voices tab)
|
Get user's custom voices with cursor-based pagination
|
||||||
Returns voices created/cloned by the current user
|
|
||||||
|
Cursor-based pagination prevents data drift when adding/removing voices:
|
||||||
|
- **First request**: No cursor parameter needed
|
||||||
|
- **Subsequent requests**: Use `next_cursor` from previous response
|
||||||
|
- **Returns**: List of voices with `next_cursor` and `has_more` flag
|
||||||
|
|
||||||
|
Voices are ordered by creation time (newest first).
|
||||||
|
Returns voices created/cloned/added by the current user.
|
||||||
"""
|
"""
|
||||||
# Get raw data from service layer
|
# Get raw data from service layer
|
||||||
voices, count = await voice_service.get_my_voices(
|
voices, next_cursor, has_more = await voice_service.get_my_voices(
|
||||||
db=db,
|
db=db,
|
||||||
owner_id=current_user_id,
|
owner_id=current_user_id,
|
||||||
page=page,
|
cursor=cursor,
|
||||||
page_size=page_size
|
page_size=page_size
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -114,13 +121,15 @@ async def get_my_voices(
|
||||||
voice_responses.append(LiveAgentVoice(
|
voice_responses.append(LiveAgentVoice(
|
||||||
voice_id=voice.voice_id,
|
voice_id=voice.voice_id,
|
||||||
name=voice.name,
|
name=voice.name,
|
||||||
tags=voice.tags or [],
|
desc=voice.desc,
|
||||||
|
created_at=voice.created_at,
|
||||||
))
|
))
|
||||||
|
|
||||||
# Build response
|
# Build response
|
||||||
voice_list = MyVoiceResponse(
|
voice_list = MyVoiceResponse(
|
||||||
voices=voice_responses,
|
voices=voice_responses,
|
||||||
has_more=count > page * page_size
|
next_cursor=next_cursor,
|
||||||
|
has_more=has_more
|
||||||
)
|
)
|
||||||
|
|
||||||
return success_response(data=voice_list.model_dump())
|
return success_response(data=voice_list.model_dump())
|
||||||
|
|
@ -140,16 +149,26 @@ async def clone_voice(
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Clone voice
|
# Clone voice
|
||||||
voice_id = await voice_service.clone_voice(
|
voice_id, samples = await voice_service.clone_voice(
|
||||||
fish_client=fish_client,
|
fish_client=fish_client,
|
||||||
audio_file=audio_file,
|
audio_file=audio_file,
|
||||||
text=text
|
text=text
|
||||||
)
|
)
|
||||||
|
|
||||||
# Build response
|
# 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_id,
|
||||||
|
"sample": sample,
|
||||||
},
|
},
|
||||||
message="Voice cloned successfully"
|
message="Voice cloned successfully"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional, List
|
from typing import Optional, List, Tuple
|
||||||
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete
|
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
@ -75,18 +75,54 @@ class Agent:
|
||||||
async def get_agents_by_owner(
|
async def get_agents_by_owner(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
skip: int = 0,
|
cursor: Optional[str] = None,
|
||||||
limit: int = 20
|
limit: int = 20
|
||||||
) -> List[AgentModel]:
|
) -> Tuple[List[AgentModel], Optional[str], bool]:
|
||||||
"""Get all agents owned by a user"""
|
"""
|
||||||
result = await db.execute(
|
Get agents owned by a user with cursor-based pagination
|
||||||
select(AgentModel)
|
|
||||||
.where(AgentModel.owner_id == owner_id)
|
Args:
|
||||||
.offset(skip)
|
db: Database session
|
||||||
.limit(limit)
|
owner_id: User ID
|
||||||
.order_by(AgentModel.created_at.desc())
|
cursor: ISO datetime string of last item's created_at
|
||||||
)
|
limit: Number of items to return
|
||||||
return result.scalars().all()
|
|
||||||
|
Returns:
|
||||||
|
(agents, next_cursor, has_more)
|
||||||
|
"""
|
||||||
|
query = select(AgentModel).where(AgentModel.owner_id == owner_id)
|
||||||
|
|
||||||
|
# Apply cursor filter if provided
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
cursor_time = datetime.fromisoformat(cursor)
|
||||||
|
# Get records created before cursor time
|
||||||
|
query = query.where(AgentModel.created_at < cursor_time)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
# Invalid cursor, ignore and start from beginning
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Order by created_at DESC, agent_id DESC for stable sorting
|
||||||
|
# Fetch limit + 1 to check if there are more records
|
||||||
|
query = query.order_by(
|
||||||
|
AgentModel.created_at.desc(),
|
||||||
|
AgentModel.agent_id.desc()
|
||||||
|
).limit(limit + 1)
|
||||||
|
|
||||||
|
result = await db.execute(query)
|
||||||
|
agents: List[AgentModel] = result.scalars().all()
|
||||||
|
|
||||||
|
# Check if there are more records
|
||||||
|
has_more = len(agents) > limit
|
||||||
|
if has_more:
|
||||||
|
agents = agents[:limit]
|
||||||
|
|
||||||
|
# Generate next cursor from last item
|
||||||
|
next_cursor = None
|
||||||
|
if has_more and agents:
|
||||||
|
next_cursor = agents[-1].created_at.isoformat()
|
||||||
|
|
||||||
|
return agents, next_cursor, has_more
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def create(
|
async def create(
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional, List
|
from typing import Optional, List, Tuple
|
||||||
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, func, update
|
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, func, update
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
@ -71,10 +71,21 @@ class Voice:
|
||||||
async def get_list(
|
async def get_list(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
owner_id: Optional[str] = None,
|
owner_id: Optional[str] = None,
|
||||||
skip: int = 0,
|
cursor: Optional[str] = None,
|
||||||
limit: int = 100
|
limit: int = 100
|
||||||
) -> List[VoiceModel]:
|
) -> Tuple[List[VoiceModel], Optional[str], bool]:
|
||||||
"""Get voices with filters"""
|
"""
|
||||||
|
Get voices with cursor-based pagination
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
owner_id: Filter by owner ID
|
||||||
|
cursor: ISO datetime string of last item's created_at
|
||||||
|
limit: Number of items to return
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(voices, next_cursor, has_more)
|
||||||
|
"""
|
||||||
query = select(VoiceModel)
|
query = select(VoiceModel)
|
||||||
|
|
||||||
if owner_id:
|
if owner_id:
|
||||||
|
|
@ -83,10 +94,37 @@ class Voice:
|
||||||
VoiceModel.owner_id == owner_id
|
VoiceModel.owner_id == owner_id
|
||||||
)
|
)
|
||||||
|
|
||||||
query = query.offset(skip).limit(limit).order_by(VoiceModel.created_at.desc())
|
# Apply cursor filter if provided
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
cursor_time = datetime.fromisoformat(cursor)
|
||||||
|
# Get records created before cursor time
|
||||||
|
query = query.where(VoiceModel.created_at < cursor_time)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
# Invalid cursor, ignore and start from beginning
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Order by created_at DESC, voice_id DESC for stable sorting
|
||||||
|
# Fetch limit + 1 to check if there are more records
|
||||||
|
query = query.order_by(
|
||||||
|
VoiceModel.created_at.desc(),
|
||||||
|
VoiceModel.voice_id.desc()
|
||||||
|
).limit(limit + 1)
|
||||||
|
|
||||||
result = await db.execute(query)
|
result = await db.execute(query)
|
||||||
return result.scalars().all()
|
voices = list(result.scalars().all())
|
||||||
|
|
||||||
|
# Check if there are more records
|
||||||
|
has_more = len(voices) > limit
|
||||||
|
if has_more:
|
||||||
|
voices = voices[:limit]
|
||||||
|
|
||||||
|
# Generate next cursor from last item
|
||||||
|
next_cursor = None
|
||||||
|
if has_more and voices:
|
||||||
|
next_cursor = voices[-1].created_at.isoformat()
|
||||||
|
|
||||||
|
return voices, next_cursor, has_more
|
||||||
|
|
||||||
async def count(
|
async def count(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
|
|
|
||||||
|
|
@ -42,8 +42,10 @@ class AgentResponse(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
class AgentListResponse(BaseModel):
|
class AgentListResponse(BaseModel):
|
||||||
"""Agent list response"""
|
"""Agent list response with cursor-based pagination"""
|
||||||
agents: list[AgentResponse]
|
agents: list[AgentResponse]
|
||||||
|
next_cursor: Optional[str] = None
|
||||||
|
has_more: bool = False
|
||||||
|
|
||||||
|
|
||||||
class AgentConfigResponse(BaseModel):
|
class AgentConfigResponse(BaseModel):
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,8 @@ class LiveAgentVoice(BaseModel):
|
||||||
|
|
||||||
samples: Optional[List[AudioSample]] = None
|
samples: Optional[List[AudioSample]] = None
|
||||||
|
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class FishAudioVoiceResponse(BaseModel):
|
class FishAudioVoiceResponse(BaseModel):
|
||||||
|
|
@ -65,9 +67,10 @@ class DiscoverVoiceResponse(BaseModel):
|
||||||
has_more: bool
|
has_more: bool
|
||||||
|
|
||||||
class MyVoiceResponse(BaseModel):
|
class MyVoiceResponse(BaseModel):
|
||||||
"""My voice response"""
|
"""My voice response with cursor-based pagination"""
|
||||||
voices: List[LiveAgentVoice]
|
voices: List[LiveAgentVoice]
|
||||||
has_more: bool
|
next_cursor: Optional[str] = None
|
||||||
|
has_more: bool = False
|
||||||
|
|
||||||
|
|
||||||
class VoiceCloneStatusResponse(BaseModel):
|
class VoiceCloneStatusResponse(BaseModel):
|
||||||
|
|
|
||||||
|
|
@ -23,20 +23,34 @@ class AgentService:
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
page: int = 1,
|
cursor: Optional[str] = None,
|
||||||
page_size: int = 10
|
page_size: int = 10
|
||||||
) -> AgentListResponse:
|
) -> AgentListResponse:
|
||||||
"""Get user's agent list"""
|
"""
|
||||||
skip = (page - 1) * page_size
|
Get user's agent list with cursor-based pagination
|
||||||
agents = await Agent.get_agents_by_owner(
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
owner_id: User ID
|
||||||
|
cursor: Pagination cursor (ISO datetime string)
|
||||||
|
page_size: Number of items per page
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
AgentListResponse with agents, next_cursor, and has_more
|
||||||
|
"""
|
||||||
|
agents, next_cursor, has_more = await Agent.get_agents_by_owner(
|
||||||
db,
|
db,
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
skip=skip,
|
cursor=cursor,
|
||||||
limit=page_size
|
limit=page_size
|
||||||
)
|
)
|
||||||
|
|
||||||
agent_responses = [AgentResponse.model_validate(a) for a in agents]
|
agent_responses = [AgentResponse.model_validate(a) for a in agents]
|
||||||
return AgentListResponse(agents=agent_responses)
|
return AgentListResponse(
|
||||||
|
agents=agent_responses,
|
||||||
|
next_cursor=next_cursor,
|
||||||
|
has_more=has_more
|
||||||
|
)
|
||||||
|
|
||||||
async def get_agent_detail(
|
async def get_agent_detail(
|
||||||
self,
|
self,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ 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
|
||||||
from fishaudio.types import PaginatedResponse, Voice as FishVoice
|
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 utils.ulid import generate_voice_id
|
||||||
|
|
@ -64,32 +64,36 @@ class VoiceService:
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
page: int = 1,
|
cursor: Optional[str] = None,
|
||||||
page_size: int = 20
|
page_size: int = 20
|
||||||
) -> Tuple[List[VoiceModel], int]:
|
) -> Tuple[List[VoiceModel], Optional[str], bool]:
|
||||||
"""
|
"""
|
||||||
Get user's custom voices (my_voices tab)
|
Get user's custom voices with cursor-based pagination
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
owner_id: User ID
|
||||||
|
cursor: Pagination cursor (ISO datetime string)
|
||||||
|
page_size: Number of items per page
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List of VoiceModel objects
|
Tuple of (voices, next_cursor, has_more)
|
||||||
"""
|
"""
|
||||||
skip = (page - 1) * page_size
|
voices, next_cursor, has_more = await Voice.get_list(
|
||||||
voices = await Voice.get_list(
|
|
||||||
db,
|
db,
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
skip=skip,
|
cursor=cursor,
|
||||||
limit=page_size
|
limit=page_size
|
||||||
)
|
)
|
||||||
|
|
||||||
count = await Voice.count(db, owner_id=owner_id)
|
return voices, next_cursor, has_more
|
||||||
return voices, count
|
|
||||||
|
|
||||||
async def clone_voice(
|
async def clone_voice(
|
||||||
self,
|
self,
|
||||||
fish_client: AsyncFishAudio,
|
fish_client: AsyncFishAudio,
|
||||||
audio_file: UploadFile,
|
audio_file: UploadFile,
|
||||||
text: Optional[str] = None
|
text: Optional[str] = None
|
||||||
) -> VoiceModel:
|
) -> Tuple[str, List[FishSample]]:
|
||||||
"""
|
"""
|
||||||
Clone a voice using Fish Audio API
|
Clone a voice using Fish Audio API
|
||||||
|
|
||||||
|
|
@ -117,8 +121,7 @@ class VoiceService:
|
||||||
visibility="private",
|
visibility="private",
|
||||||
enhance_audio_quality=True
|
enhance_audio_quality=True
|
||||||
)
|
)
|
||||||
|
return fish_voice.id, fish_voice.samples
|
||||||
return fish_voice.id
|
|
||||||
|
|
||||||
async def add_voice(
|
async def add_voice(
|
||||||
self,
|
self,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue