from fastapi import APIRouter, UploadFile, File, HTTPException from fastapi.responses import JSONResponse import uuid, shutil, time from pathlib import Path from config import UPLOADS_DIR, EPT_DIR, SUPPORTED_FORMATS from services.converter import run_entwine, ENTWINE_AVAILABLE router = APIRouter() @router.post("/upload") async def upload(file: UploadFile = File(...)): suffix = Path(file.filename).suffix.lower() if suffix not in SUPPORTED_FORMATS: raise HTTPException(400, f"Format non supporté: {suffix}") if not ENTWINE_AVAILABLE: raise HTTPException(500, "entwine non disponible sur ce serveur") pc_id = str(uuid.uuid4())[:8] upload_path = UPLOADS_DIR / f"{pc_id}{suffix}" out_dir = EPT_DIR / pc_id file_size = 0 with open(upload_path, "wb") as f: while chunk := await file.read(1024 * 1024): f.write(chunk) file_size += len(chunk) if file_size == 0: upload_path.unlink() raise HTTPException(400, "Fichier vide") if out_dir.exists(): shutil.rmtree(out_dir, ignore_errors=True) out_dir.mkdir(parents=True, exist_ok=True) start = time.time() result = run_entwine(upload_path, out_dir) return JSONResponse({ "id": pc_id, "filename": file.filename, "size_mb": round(file_size / (1024 * 1024), 2), "viewer_path": f"/viewer/{pc_id}", "embed_path": f"/viewer-embed/{pc_id}", "ept_dir": result.get("ept_dir"), "conversion_time_seconds": round(time.time() - start, 2), })