Spaces:
Sleeping

frameforge / main.py
kajalan's picture
Update main.py (#7)
c8c7302
Raw History Blame Contribute Delete
7.84 kB
"""
FrameForge β€” FFmpeg as an API
FastAPI + Gradio on Hugging Face Spaces (Docker)
"""
import asyncio
import shutil
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
import aiofiles
import gradio as gr
from fastapi import FastAPI, File, Form, HTTPException, UploadFile, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from ffmpeg_runner import (
get_ffmpeg_version,
run_ffmpeg_from_file,
run_ffmpeg_from_url,
run_ffprobe,
)
from gradio_ui import create_gradio_interface
from models import (
FFmpegCommandRequest,
FFprobeRequest,
HealthResponse,
JobResponse,
)
# ── Config ────────────────────────────────────────────────────────────────────
TEMP_DIR = Path("/tmp/frameforge")
MAX_UPLOAD_BYTES = 500 * 1024 * 1024 # 500 MB
JOB_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 time
while True:
await asyncio.sleep(300)
now = time.time()
expired = [
jid for jid, meta in JOBS.items()
if now - meta.get("created_at", now) > JOB_TTL_SECONDS
]
for jid in expired:
job_dir = TEMP_DIR / jid
if job_dir.exists():
shutil.rmtree(job_dir, ignore_errors=True)
JOBS.pop(jid, None)
@asynccontextmanager
async def lifespan(app: FastAPI):
TEMP_DIR.mkdir(parents=True, exist_ok=True)
cleanup_task = asyncio.create_task(_cleanup_old_jobs())
yield
cleanup_task.cancel()
# ── App ───────────────────────────────────────────────────────────────────────
app = FastAPI(
title="FrameForge API",
description=(
"**FFmpeg as an API** β€” submit any FFmpeg command, get back processed media.\n\n"
"Hosted on Hugging Face Spaces (Docker). Interactive playground at `/ui`.\n\n"
"**Workflow:** `POST /api/run` β†’ poll `GET /api/jobs/{id}` β†’ `GET /api/download/{id}`"
),
version="1.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ── Routes ────────────────────────────────────────────────────────────────────
@app.get("/health", response_model=HealthResponse, tags=["System"])
async def health():
return HealthResponse(
status="ok",
service="FrameForge",
ffmpeg_version=get_ffmpeg_version(),
)
@app.post(
"/api/probe",
tags=["Media"],
summary="Extract media metadata via ffprobe",
response_class=JSONResponse,
)
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 data
except 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 time
job_id = uuid.uuid4().hex[:8]
work_dir = TEMP_DIR / job_id
work_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(...),
ffmpeg_args: str = Form(default=""),
output_format: str = Form(default="mp4"),
output_filename: Optional[str] = Form(default=None),
):
import time
content = 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_id
work_dir.mkdir(parents=True, exist_ok=True)
safe_name = Path(file.filename).name if file.filename else "input"
input_path = work_dir / safe_name
async 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]
return JobResponse(
job_id=job_id,
status=job["status"],
download_url=f"/api/download/{job_id}" if job["status"] == "done" else None,
error=job.get("error"),
)
@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]
if job["status"] != "done":
raise 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):
JOBS[job_id]["status"] = "running"
try:
result_path = await run_ffmpeg_from_url(request, work_dir)
JOBS[job_id]["status"] = "done"
JOBS[job_id]["result"] = str(result_path)
except Exception as e:
JOBS[job_id]["status"] = "failed"
JOBS[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:
JOBS[job_id]["status"] = "failed"
JOBS[job_id]["error"] = str(e)
# ── Mount Gradio at /ui ───────────────────────────────────────────────────────
gradio_demo = create_gradio_interface()
app = gr.mount_gradio_app(app, gradio_demo, path="/ui")