Download api_server/app/api/v1/endpoints/tasks.py from MoYoYoTech/MoYoYo.tts: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/MoYoYoTech/MoYoYo.tts/resolve/main/api_server/app/api/v1/endpoints/tasks.py
- Command line
-
hf download hf://MoYoYoTech/MoYoYo.tts/api_server/app/api/v1/endpoints/tasks.py
-
curl -L -o tasks.py https://huggingface.co/MoYoYoTech/MoYoYo.tts/resolve/main/api_server/app/api/v1/endpoints/tasks.py
10.9 kB
| """ | |
| Quick Mode 任务 API | |
| 小白用户一键训练 API 端点 | |
| API 列表: | |
| - POST /tasks 创建一键训练任务 | |
| - GET /tasks 获取任务列表 | |
| - GET /tasks/{task_id} 获取任务详情 | |
| - DELETE /tasks/{task_id} 取消任务 | |
| - GET /tasks/{task_id}/progress SSE 进度订阅 | |
| - GET /tasks/{task_id}/outputs 获取推理输出列表 | |
| - GET /tasks/{task_id}/outputs/{file_type}/{filename} 下载任务相关文件 | |
| """ | |
| import json | |
| from typing import Literal, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, Path, Query | |
| from fastapi.responses import StreamingResponse, Response | |
| from ....models.schemas.task import ( | |
| QuickModeRequest, | |
| TaskResponse, | |
| TaskListResponse, | |
| InferenceOutputsResponse, | |
| ) | |
| from ....models.schemas.common import SuccessResponse, ErrorResponse | |
| from ....services.task_service import TaskService | |
| from ...deps import get_task_service | |
| router = APIRouter() | |
| async def create_task( | |
| request: QuickModeRequest, | |
| service: TaskService = Depends(get_task_service), | |
| ) -> TaskResponse: | |
| """ | |
| 创建一键训练任务 | |
| """ | |
| # 验证 exp_name 是否已存在 | |
| if await service.check_exp_name_exists(request.exp_name): | |
| raise HTTPException( | |
| status_code=409, | |
| detail=f"实验名称 '{request.exp_name}' 已存在,请使用不同的名称" | |
| ) | |
| # 验证音频文件是否存在 | |
| file_exists, audio_path = await service.validate_audio_file(request.audio_file_id) | |
| if not file_exists: | |
| raise HTTPException( | |
| status_code=404, | |
| detail=f"音频文件不存在: {request.audio_file_id}" | |
| ) | |
| return await service.create_quick_task(request) | |
| async def list_tasks( | |
| status: Optional[str] = Query( | |
| None, | |
| description="按状态筛选: queued, running, completed, failed, cancelled, interrupted" | |
| ), | |
| limit: int = Query(50, ge=1, le=100, description="每页数量"), | |
| offset: int = Query(0, ge=0, description="偏移量"), | |
| service: TaskService = Depends(get_task_service), | |
| ) -> TaskListResponse: | |
| """ | |
| 获取任务列表 | |
| """ | |
| return await service.list_tasks(status=status, limit=limit, offset=offset) | |
| async def get_task( | |
| task_id: str, | |
| service: TaskService = Depends(get_task_service), | |
| ) -> TaskResponse: | |
| """ | |
| 获取任务详情 | |
| """ | |
| task = await service.get_task(task_id) | |
| if not task: | |
| raise HTTPException(status_code=404, detail="任务不存在") | |
| return task | |
| async def cancel_task( | |
| task_id: str, | |
| service: TaskService = Depends(get_task_service), | |
| ) -> SuccessResponse: | |
| """ | |
| 取消任务 | |
| """ | |
| # 先检查任务是否存在 | |
| task = await service.get_task(task_id) | |
| if not task: | |
| raise HTTPException(status_code=404, detail="任务不存在") | |
| success = await service.cancel_task(task_id) | |
| if not success: | |
| raise HTTPException(status_code=400, detail="任务无法取消(可能已完成或已取消)") | |
| return SuccessResponse(message="任务已取消") | |
| async def subscribe_progress( | |
| task_id: str, | |
| service: TaskService = Depends(get_task_service), | |
| ) -> StreamingResponse: | |
| """ | |
| SSE 进度订阅 | |
| """ | |
| # 先检查任务是否存在 | |
| task = await service.get_task(task_id) | |
| if not task: | |
| raise HTTPException(status_code=404, detail="任务不存在") | |
| async def event_generator(): | |
| """生成 SSE 事件流""" | |
| async for progress in service.subscribe_progress(task_id): | |
| # 确定事件类型 | |
| event_type = progress.get("type", "progress") | |
| status = progress.get("status") | |
| if status == "completed": | |
| event_type = "completed" | |
| elif status == "failed": | |
| event_type = "failed" | |
| elif status == "cancelled": | |
| event_type = "cancelled" | |
| elif event_type == "heartbeat": | |
| event_type = "heartbeat" | |
| # 构建 SSE 格式 | |
| data = json.dumps(progress, ensure_ascii=False) | |
| yield f"event: {event_type}\ndata: {data}\n\n" | |
| # 如果是终态,结束流 | |
| if status in ("completed", "failed", "cancelled"): | |
| break | |
| return StreamingResponse( | |
| event_generator(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "Connection": "keep-alive", | |
| "X-Accel-Buffering": "no", # Nginx 禁用缓冲 | |
| }, | |
| ) | |
| async def get_task_outputs( | |
| task_id: str, | |
| service: TaskService = Depends(get_task_service), | |
| ) -> InferenceOutputsResponse: | |
| """ | |
| 获取任务的推理输出列表 | |
| """ | |
| result = await service.get_inference_outputs(task_id) | |
| if result is None: | |
| raise HTTPException(status_code=404, detail="任务不存在") | |
| return result | |
| # 文件类型定义 | |
| FileType = Literal["output", "ref_audio", "gpt_model", "sovits_model"] | |
| async def download_task_file( | |
| task_id: str, | |
| file_type: FileType = Path(..., description="文件类型: output/ref_audio/gpt_model/sovits_model"), | |
| filename: str = Path(..., description="文件名或路径"), | |
| service: TaskService = Depends(get_task_service), | |
| ) -> Response: | |
| """ | |
| 下载任务相关文件(推理输出、参考音频、模型文件) | |
| """ | |
| result = await service.download_file(task_id, file_type, filename) | |
| if result is None: | |
| raise HTTPException(status_code=404, detail="任务或文件不存在") | |
| file_data, file_name, content_type = result | |
| return Response( | |
| content=file_data, | |
| media_type=content_type, | |
| headers={ | |
| "Content-Disposition": f'attachment; filename="{file_name}"', | |
| "Content-Length": str(len(file_data)), | |
| }, | |
| ) | |