Spaces:
Sleeping
Sleeping
Update main.py
#7
by kajalan - opened
3 unmodified lines456789101 unmodified line1213141516171819 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707172737475767778798041 unmodified lines1221231241251261271281 unmodified line1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611622 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482491 unmodified line2512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033045 unmodified lines3103113123133143153163173183193203213221 unmodified line3243253263273283293303313323333343353363373387 unmodified lines3463473483493503513523533543553563573583593603613623633641 unmodified line3663673683693703713723 unmodified lines"""import asyncioimport shutilimport tempfileimport uuidfrom contextlib import asynccontextmanagerfrom pathlib import Path1 unmodified lineimport aiofilesimport gradio as grimport requests as reqfrom fastapi import FastAPI, File, Form, HTTPException, UploadFile, BackgroundTasksfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponse19 unmodified linesJOB_TTL_SECONDS = 1800 # 30 min# ── In-memory job store ───────────────────────────────────────────────────────# { job_id: { status, result, error, created_at } }JOBS: dict[str, dict] = {}def _is_gdrive_url(url: str) -> bool:return "drive.google.com" in url or "drive.usercontent.google.com" in urldef _download_gdrive_to_tmp(url: str) -> str:"""Download a GDrive URL to a temp file, return path."""r = req.get(url,stream=True,timeout=60,headers={"User-Agent": "Mozilla/5.0"},)r.raise_for_status()suffix = ".mp4"# Try to detect extension from content-dispositioncd = r.headers.get("content-disposition", "")if "filename=" in cd:fname = cd.split("filename=")[-1].strip().strip('"')suffix = Path(fname).suffix or suffixtmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=str(TEMP_DIR))for chunk in r.iter_content(chunk_size=65536):tmp.write(chunk)tmp.flush()tmp.close()return tmp.nameasync def _cleanup_old_jobs():"""Periodically remove jobs older than JOB_TTL_SECONDS."""import timewhile True:await asyncio.sleep(300) # run every 5 minnow = time.time()expired = [jid for jid, meta in JOBS.items()41 unmodified lines@app.get("/health", response_model=HealthResponse, tags=["System"])async def health():"""Service health + FFmpeg version."""return HealthResponse(status="ok",service="FrameForge",1 unmodified line)def _run_ffprobe_direct(target: str) -> dict:"""Run ffprobe directly on a local path or URL, return parsed JSON."""import jsonimport subprocesscmd = ["ffprobe","-v", "quiet","-print_format", "json","-show_streams","-show_format","-show_error",target,]result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)stdout = result.stdout.strip()stderr = result.stderr.strip()if result.returncode != 0 or not stdout:raise RuntimeError(f"ffprobe failed (code {result.returncode}): {stderr or 'no output'}")try:return json.loads(stdout)except Exception:raise RuntimeError(f"ffprobe returned invalid JSON. stderr: {stderr}")@app.post("/api/probe",tags=["Media"],2 unmodified lines)async def probe_media(request: FFprobeRequest):"""Run **ffprobe** on any publicly accessible URL and return full JSONmetadata (streams, format, codec, bitrate, duration, etc.).Google Drive URLs are automatically pre-downloaded to avoid redirect issues."""tmp_path: Optional[str] = Nonetry:probe_target = request.input_urlif _is_gdrive_url(request.input_url):try:tmp_path = _download_gdrive_to_tmp(request.input_url)probe_target = tmp_pathexcept Exception as e:raise HTTPException(status_code=422,detail=f"Failed to download Google Drive file: {str(e)}")# Run ffprobe directly (bypasses ffmpeg_runner to get full error detail)data = await asyncio.get_event_loop().run_in_executor(None, _run_ffprobe_direct, probe_target)return dataexcept HTTPException:raiseexcept RuntimeError as e:raise HTTPException(status_code=422, detail=str(e))except Exception as e:raise HTTPException(status_code=422, detail=f"Unexpected error: {str(e)}")finally:if tmp_path:try:Path(tmp_path).unlink(missing_ok=True)except Exception:pass@app.post("/api/run",response_model=JobResponse,tags=["Jobs"],summary="Submit an FFmpeg job (URL input)",)async def run_ffmpeg_url(request: FFmpegCommandRequest,background_tasks: BackgroundTasks,):"""Submit a background FFmpeg job using a public input URL.**Steps:**1. POST here → get `job_id`2. Poll `GET /api/jobs/{job_id}` until `status == "done"`3. Download result from `GET /api/download/{job_id}`"""import timejob_id = uuid.uuid4().hex[:8]work_dir = TEMP_DIR / job_idwork_dir.mkdir(parents=True, exist_ok=True)JOBS[job_id] = {"status": "pending","result": None,"error": None,"created_at": time.time(),}background_tasks.add_task(_run_url_job, job_id, request, work_dir)return JobResponse(job_id=job_id, status="pending")@app.post("/api/run/upload",response_model=JobResponse,tags=["Jobs"],summary="Submit an FFmpeg job (file upload)",)async def run_ffmpeg_upload(background_tasks: BackgroundTasks,file: UploadFile = File(...),1 unmodified lineoutput_format: str = Form(default="mp4"),output_filename: Optional[str] = Form(default=None),):"""Upload a local file and submit an FFmpeg job.Same polling flow as `/api/run`.Max upload size: **500 MB**."""import timecontent = await file.read()if len(content) > MAX_UPLOAD_BYTES:raise HTTPException(413, detail="File exceeds 500 MB limit.")job_id = uuid.uuid4().hex[:8]work_dir = TEMP_DIR / job_idwork_dir.mkdir(parents=True, exist_ok=True)safe_name = Path(file.filename).name if file.filename else "input"input_path = work_dir / safe_nameasync with aiofiles.open(input_path, "wb") as f:await f.write(content)JOBS[job_id] = {"status": "pending","result": None,"error": None,"created_at": time.time(),}background_tasks.add_task(_run_upload_job, job_id, ffmpeg_args, input_path,output_format, work_dir, output_filename)return JobResponse(job_id=job_id, status="pending")@app.get("/api/jobs/{job_id}",response_model=JobResponse,tags=["Jobs"],summary="Poll job status",)async def get_job_status(job_id: str):"""Poll a job. Status values: `pending` → `running` → `done` | `failed`.When `status == "done"`, use `download_url` to fetch the result."""if job_id not in JOBS:raise HTTPException(404, detail="Job not found.")job = JOBS[job_id]5 unmodified lines)@app.get("/api/download/{job_id}",tags=["Jobs"],summary="Download processed output",)async def download_output(job_id: str):"""Download the output file for a completed job."""if job_id not in JOBS:raise HTTPException(404, detail="Job not found.")job = JOBS[job_id]1 unmodified lineraise HTTPException(400, detail=f"Job status is '{job['status']}', not 'done'.")result_path = Path(job["result"])if not result_path.exists():raise HTTPException(404, detail="Output file no longer exists (may have been cleaned up).")return FileResponse(path=str(result_path),filename=result_path.name,media_type="application/octet-stream",)# ── Background task helpers ───────────────────────────────────────────────────async def _run_url_job(job_id: str, request: FFmpegCommandRequest, work_dir: Path):7 unmodified linesJOBS[job_id]["error"] = str(e)async def _run_upload_job(job_id: str,ffmpeg_args: str,input_path: Path,output_format: str,work_dir: Path,output_filename: Optional[str],):JOBS[job_id]["status"] = "running"try:result_path = await run_ffmpeg_from_file(ffmpeg_args, input_path, output_format, work_dir, output_filename)JOBS[job_id]["status"] = "done"JOBS[job_id]["result"] = str(result_path)except Exception as e:1 unmodified lineJOBS[job_id]["error"] = str(e)# ── Mount Gradio playground at /ui ────────────────────────────────────────────gradio_demo = create_gradio_interface()app = gr.mount_gradio_app(app, gradio_demo, path="/ui")3 unmodified lines4567891 unmodified line11121314151619 unmodified lines363738394041424344454647484941 unmodified lines9192939495961 unmodified line98991001011021032 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381 unmodified line1401411421431441451461471481491501511521531541551561571581591601611621635 unmodified lines1691701711721731741751761 unmodified line1781791801811821831841851861871887 unmodified lines1961971981992002012022032042051 unmodified line2072082092102112122133 unmodified lines"""import asyncioimport shutilimport uuidfrom contextlib import asynccontextmanagerfrom pathlib import Path1 unmodified lineimport aiofilesimport gradio as grfrom fastapi import FastAPI, File, Form, HTTPException, UploadFile, BackgroundTasksfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponse19 unmodified linesJOB_TTL_SECONDS = 1800 # 30 min# ── In-memory job store ───────────────────────────────────────────────────────JOBS: dict[str, dict] = {}async def _cleanup_old_jobs():"""Periodically remove jobs older than JOB_TTL_SECONDS."""import timewhile True:await asyncio.sleep(300)now = time.time()expired = [jid for jid, meta in JOBS.items()41 unmodified lines@app.get("/health", response_model=HealthResponse, tags=["System"])async def health():return HealthResponse(status="ok",service="FrameForge",1 unmodified line)@app.post("/api/probe",tags=["Media"],2 unmodified lines)async def probe_media(request: FFprobeRequest):"""Run ffprobe on any URL. Google Drive URLs are pre-downloaded automatically.Returns full JSON: streams, format, codec, bitrate, duration, etc."""try:data = await run_ffprobe(request.input_url, temp_dir=TEMP_DIR)return dataexcept RuntimeError as e:raise HTTPException(status_code=422, detail=str(e))except Exception as e:raise HTTPException(status_code=422, detail=f"Unexpected error: {str(e)}")@app.post("/api/run", response_model=JobResponse, tags=["Jobs"])async def run_ffmpeg_url(request: FFmpegCommandRequest,background_tasks: BackgroundTasks,):import timejob_id = uuid.uuid4().hex[:8]work_dir = TEMP_DIR / job_idwork_dir.mkdir(parents=True, exist_ok=True)JOBS[job_id] = {"status": "pending", "result": None, "error": None, "created_at": time.time()}background_tasks.add_task(_run_url_job, job_id, request, work_dir)return JobResponse(job_id=job_id, status="pending")@app.post("/api/run/upload", response_model=JobResponse, tags=["Jobs"])async def run_ffmpeg_upload(background_tasks: BackgroundTasks,file: UploadFile = File(...),1 unmodified lineoutput_format: str = Form(default="mp4"),output_filename: Optional[str] = Form(default=None),):import timecontent = await file.read()if len(content) > MAX_UPLOAD_BYTES:raise HTTPException(413, detail="File exceeds 500 MB limit.")job_id = uuid.uuid4().hex[:8]work_dir = TEMP_DIR / job_idwork_dir.mkdir(parents=True, exist_ok=True)safe_name = Path(file.filename).name if file.filename else "input"input_path = work_dir / safe_nameasync with aiofiles.open(input_path, "wb") as f:await f.write(content)JOBS[job_id] = {"status": "pending", "result": None, "error": None, "created_at": time.time()}background_tasks.add_task(_run_upload_job, job_id, ffmpeg_args, input_path, output_format, work_dir, output_filename)return JobResponse(job_id=job_id, status="pending")@app.get("/api/jobs/{job_id}", response_model=JobResponse, tags=["Jobs"])async def get_job_status(job_id: str):if job_id not in JOBS:raise HTTPException(404, detail="Job not found.")job = JOBS[job_id]5 unmodified lines)@app.get("/api/download/{job_id}", tags=["Jobs"])async def download_output(job_id: str):if job_id not in JOBS:raise HTTPException(404, detail="Job not found.")job = JOBS[job_id]1 unmodified lineraise HTTPException(400, detail=f"Job status is '{job['status']}', not 'done'.")result_path = Path(job["result"])if not result_path.exists():raise HTTPException(404, detail="Output file no longer exists.")return FileResponse(path=str(result_path), filename=result_path.name, media_type="application/octet-stream")# ── Background helpers ────────────────────────────────────────────────────────async def _run_url_job(job_id: str, request: FFmpegCommandRequest, work_dir: Path):7 unmodified linesJOBS[job_id]["error"] = str(e)async def _run_upload_job(job_id, ffmpeg_args, input_path, output_format, work_dir, output_filename):JOBS[job_id]["status"] = "running"try:result_path = await run_ffmpeg_from_file(ffmpeg_args, input_path, output_format, work_dir, output_filename)JOBS[job_id]["status"] = "done"JOBS[job_id]["result"] = str(result_path)except Exception as e:1 unmodified lineJOBS[job_id]["error"] = str(e)# ── Mount Gradio at /ui ───────────────────────────────────────────────────────gradio_demo = create_gradio_interface()app = gr.mount_gradio_app(app, gradio_demo, path="/ui")
main.py+17-176