Simple web backend added with upload/status/process/download API
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""API route handlers."""
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Download endpoint for split results."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from zipfile import ZipFile
|
||||
import os
|
||||
|
||||
from backend.config import settings
|
||||
from backend.services.task_manager import task_manager
|
||||
from backend.models.response import TaskStatus
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["download"])
|
||||
|
||||
|
||||
def _prepare_download(task_id: str):
|
||||
"""Common logic to prepare and return the ZIP file."""
|
||||
if not task_manager.has_task(task_id):
|
||||
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
|
||||
|
||||
status = task_manager.get_status(task_id)
|
||||
if status["status"] != TaskStatus.DONE:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Task {task_id} is not complete. Current status: {status['status']}"
|
||||
)
|
||||
|
||||
output_dir = settings.temp_dir / task_id / "output"
|
||||
if not output_dir.exists() or not any(output_dir.iterdir()):
|
||||
raise HTTPException(status_code=404, detail="No output files found")
|
||||
|
||||
zip_path = settings.temp_dir / task_id / "splits.zip"
|
||||
# Create ZIP if not already exists (or overwrite)
|
||||
with ZipFile(zip_path, "w") as zipf:
|
||||
for file_path in output_dir.iterdir():
|
||||
if file_path.is_file():
|
||||
zipf.write(file_path, arcname=file_path.name)
|
||||
|
||||
return zip_path
|
||||
|
||||
|
||||
@router.get("/download/{task_id}")
|
||||
async def download_results(task_id: str):
|
||||
zip_path = _prepare_download(task_id)
|
||||
return FileResponse(
|
||||
path=zip_path,
|
||||
media_type="application/zip",
|
||||
filename=f"{task_id}_splits.zip",
|
||||
headers={"Content-Disposition": f"attachment; filename={task_id}_splits.zip"}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/download/{task_id}/splits.zip")
|
||||
async def download_results_as_zip(task_id: str):
|
||||
"""Alias endpoint that provides a .zip suffix for easier curl usage."""
|
||||
zip_path = _prepare_download(task_id)
|
||||
return FileResponse(
|
||||
path=zip_path,
|
||||
media_type="application/zip",
|
||||
filename="splits.zip",
|
||||
headers={"Content-Disposition": "attachment; filename=splits.zip"}
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Split task endpoint."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
|
||||
from backend.models.request import SplitRequest
|
||||
from backend.models.response import SplitResponse, TaskStatus
|
||||
from backend.services.splitter import run_split_task
|
||||
from backend.services.task_manager import task_manager
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["split"])
|
||||
|
||||
|
||||
@router.post("/split", response_model=SplitResponse)
|
||||
async def start_split(request: SplitRequest, background_tasks: BackgroundTasks):
|
||||
task_id = request.task_id
|
||||
|
||||
if not task_manager.has_task(task_id):
|
||||
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
|
||||
|
||||
status = task_manager.get_status(task_id)
|
||||
if status and status["status"] in (TaskStatus.PROCESSING, TaskStatus.DONE):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"Task {task_id} is already {status['status']}"
|
||||
)
|
||||
|
||||
task_manager.update_task(
|
||||
task_id,
|
||||
status=TaskStatus.PROCESSING,
|
||||
progress=0,
|
||||
message="Preparing to split..."
|
||||
)
|
||||
|
||||
background_tasks.add_task(run_split_task, task_id, request.tracklist, request.options)
|
||||
|
||||
return SplitResponse(
|
||||
task_id=task_id,
|
||||
status=TaskStatus.PROCESSING
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Status query endpoint."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from backend.models.response import StatusResponse
|
||||
from backend.services.task_manager import task_manager
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["status"])
|
||||
|
||||
|
||||
@router.get("/status/{task_id}", response_model=StatusResponse)
|
||||
async def get_status(task_id: str):
|
||||
if not task_manager.has_task(task_id):
|
||||
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
|
||||
|
||||
status = task_manager.get_status(task_id)
|
||||
|
||||
return StatusResponse(
|
||||
task_id=task_id,
|
||||
status=status["status"],
|
||||
progress=status["progress"],
|
||||
message=status["message"],
|
||||
error=status.get("error"),
|
||||
tracks=status.get("tracks", [])
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""File upload endpoint."""
|
||||
|
||||
import uuid
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, UploadFile, File, HTTPException
|
||||
|
||||
from backend.config import settings
|
||||
from backend.models.response import UploadResponse
|
||||
from backend.services.task_manager import task_manager
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["upload"])
|
||||
|
||||
ALLOWED_EXTENSIONS = {
|
||||
".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus",
|
||||
".aac", ".wma", ".aiff", ".alac", ".ac3"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/upload", response_model=UploadResponse)
|
||||
async def upload_file(file: UploadFile = File(...)):
|
||||
extension = Path(file.filename).suffix.lower()
|
||||
if extension not in ALLOWED_EXTENSIONS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unsupported file format. Allowed: {', '.join(sorted(ALLOWED_EXTENSIONS))}"
|
||||
)
|
||||
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
task_dir = settings.temp_dir / task_id
|
||||
task_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
input_path = task_dir / f"input{extension}"
|
||||
try:
|
||||
with open(input_path, "wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
except Exception as e:
|
||||
shutil.rmtree(task_dir, ignore_errors=True)
|
||||
raise HTTPException(status_code=500, detail=f"Failed to save file: {str(e)}")
|
||||
|
||||
file_size = input_path.stat().st_size
|
||||
max_size_bytes = settings.max_upload_size_mb * 1024 * 1024
|
||||
if file_size > max_size_bytes:
|
||||
shutil.rmtree(task_dir, ignore_errors=True)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File too large. Maximum size: {settings.max_upload_size_mb} MB"
|
||||
)
|
||||
|
||||
# Create task entry in the task manager
|
||||
task_manager.create_task(task_id, file.filename, file_size)
|
||||
|
||||
return UploadResponse(
|
||||
task_id=task_id,
|
||||
filename=file.filename,
|
||||
size=file_size
|
||||
)
|
||||
Reference in New Issue
Block a user