api/app/api/v1/tryon.py
2025-04-10 11:38:15 +08:00

90 lines
3.3 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status, Response
from sqlalchemy.ext.asyncio import AsyncSession
import logging
from fastapi.security import OAuth2PasswordRequestForm
from app.api import deps
from app.core import security
from app.core.config import settings
from app.schemas.tryon import TryonRequest
from app.schemas.user import User
from app.services import person_image as person_image_service
from app.services import clothing as clothing_service
from app.api.deps import get_current_user
from app.services.dashscope_service import DashScopeService
from app.schemas.response import StandardResponse
from app.models.tryon import TryonHistory
from app.schemas.tryon import TryonHistoryModel
from sqlalchemy import select
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
router = APIRouter()
@router.post("/tryon", tags=["tryon"])
async def tryon(
tryon_request: TryonRequest,
db: AsyncSession = Depends(deps.get_db),
current_user: User = Depends(get_current_user)
):
"""
试穿请求
"""
# 获取当前用户的默认形象
person_image = await person_image_service.get_default_image(db, current_user.id)
if not person_image:
raise HTTPException(status_code=404, detail="默认形象不存在")
# 获取试穿请求中的衣物ID
top_clothing_id = tryon_request.top_clothing_id
bottom_clothing_id = tryon_request.bottom_clothing_id
# 获取衣物详情
top_clothing_url = tryon_request.top_clothing_url
bottom_clothing_url = tryon_request.bottom_clothing_url
if top_clothing_id:
top_clothing = await clothing_service.get_clothing(db, top_clothing_id)
top_clothing_url = top_clothing.image_url
if bottom_clothing_id:
bottom_clothing = await clothing_service.get_clothing(db, bottom_clothing_id)
bottom_clothing_url = bottom_clothing.image_url
# 调用试穿服务
dashscope_service = DashScopeService()
tryon_result = await dashscope_service.generate_tryon(person_image.image_url,
top_clothing_url,
bottom_clothing_url)
task_id = tryon_result.get("task_id")
if task_id:
tryon_history = TryonHistory(
user_id=current_user.id,
person_image_id=person_image.id,
top_clothing_id=top_clothing_id,
bottom_clothing_id=bottom_clothing_id,
top_clothing_url=top_clothing_url,
bottom_clothing_url=bottom_clothing_url,
task_id=task_id
)
db.add(tryon_history)
await db.commit()
return StandardResponse(code=200, message="试穿任务已提交", data=tryon_history.id)
else:
return StandardResponse(code=500, message="试穿任务提交失败")
@router.get("/tryon/histories", tags=["tryon"])
async def get_tryon_histories(
db: AsyncSession = Depends(deps.get_db),
current_user: User = Depends(get_current_user)
):
"""
获取试穿历史
"""
histories = await db.execute(select(TryonHistory).where(TryonHistory.user_id == current_user.id))
tryon_histories = histories.scalars().all()
return StandardResponse(code=200, message="试穿历史获取成功", data=[TryonHistoryModel.model_validate(history) for history in tryon_histories])