router.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from pathlib import Path
  2. from uuid import uuid4
  3. import aiofiles
  4. from fastapi import APIRouter, BackgroundTasks, File, HTTPException, UploadFile
  5. from fastapi.responses import FileResponse
  6. from sorawm.server.schemas import WMRemoveResults
  7. from sorawm.server.worker import worker
  8. router = APIRouter()
  9. async def process_upload_and_queue(
  10. task_id: str, video_content: bytes, video_path: Path
  11. ):
  12. try:
  13. async with aiofiles.open(video_path, "wb") as f:
  14. await f.write(video_content)
  15. await worker.queue_task(task_id, video_path)
  16. except Exception as e:
  17. await worker.mark_task_error(task_id, str(e))
  18. @router.post("/submit_remove_task")
  19. async def submit_remove_task(
  20. background_tasks: BackgroundTasks, video: UploadFile = File(...)
  21. ):
  22. task_id = await worker.create_task()
  23. content = await video.read()
  24. upload_filename = f"{uuid4()}_{video.filename}"
  25. video_path = worker.upload_dir / upload_filename
  26. background_tasks.add_task(process_upload_and_queue, task_id, content, video_path)
  27. return {"task_id": task_id, "message": "Task submitted."}
  28. @router.get("/get_results")
  29. async def get_results(remove_task_id: str) -> WMRemoveResults:
  30. result = await worker.get_task_status(remove_task_id)
  31. if result is None:
  32. raise HTTPException(status_code=404, detail="Task does not exist.")
  33. return result
  34. @router.get("/download/{task_id}")
  35. async def download_video(task_id: str):
  36. result = await worker.get_task_status(task_id)
  37. if result is None:
  38. raise HTTPException(status_code=404, detail="Task does not exist.")
  39. if result.status != "FINISHED":
  40. raise HTTPException(
  41. status_code=400, detail=f"Task not finish yet: {result.status}"
  42. )
  43. output_path = await worker.get_output_path(task_id)
  44. if output_path is None or not output_path.exists():
  45. raise HTTPException(status_code=404, detail="Output file does not exits")
  46. return FileResponse(
  47. path=output_path, filename=output_path.name, media_type="video/mp4"
  48. )