Spaces:
Runtime error
Runtime error
feat: add remote input file downloading and placeholder replacement for FFmpeg commands (#3)
Browse files- feat: add remote input file downloading and placeholder replacement for FFmpeg commands (3034138b7cb640c193e4be2d8b2bc06c9a535f3d)
Files changed (3)
- ffmpeg_runner.py+111
- main.py+68-4
- models.py+6
4 unmodified lines5678910254 unmodified lines2652662672682692704 unmodified linesimport subprocessfrom pathlib import Pathfrom typing import Callable, Optionalfrom models import FFmpegCommandRequestfrom progress import ProgressSnapshot254 unmodified linesreturn await _ffmpeg_progress(cmd, work_dir, progress_cb)async def run_from_file(ffmpeg_args: str,input_path: Path,4 unmodified lines567891011121314254 unmodified lines2692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803814 unmodified linesimport subprocessfrom pathlib import Pathfrom typing import Callable, Optionalimport httpximport aiofilesfrom urllib.parse import urlparseimport osfrom models import FFmpegCommandRequestfrom progress import ProgressSnapshot254 unmodified linesreturn await _ffmpeg_progress(cmd, work_dir, progress_cb)async def download_input_files(input_files: dict[str, str], work_dir: Path) -> dict[str, Path]:"""Downloads all input files in parallel to the work directory.Returns a mapping of reference key to local Path."""downloaded_paths = {}async def download_one(key: str, url: str):# Extract extension from URLparsed = urlparse(url)_, ext = os.path.splitext(parsed.path)if not ext:ext = ".bin" # default extension# Local filename is key + extension (e.g. in_img_1.png)local_filename = f"{key}{ext}"dest_path = work_dir / local_filenameasync with httpx.AsyncClient(follow_redirects=True, timeout=60.0) as client:async with client.stream("GET", url) as response:if response.status_code != 200:raise RuntimeError(f"Failed to download {key} from {url}: HTTP {response.status_code}")async with aiofiles.open(dest_path, "wb") as f:async for chunk in response.aiter_bytes(chunk_size=8192):await f.write(chunk)downloaded_paths[key] = dest_path# Run downloads in paralleltasks = [download_one(key, url) for key, url in input_files.items()]await asyncio.gather(*tasks)return downloaded_pathsdef prepare_rendi_command(ffmpeg_command: str,downloaded_inputs: dict[str, Path],output_files: dict[str, str],work_dir: Path) -> tuple[list[str], dict[str, Path]]:"""Replaces placeholders in ffmpeg_command and returns the command list and output paths."""cmd_str = ffmpeg_command# Replace inputsfor key, local_path in downloaded_inputs.items():placeholder = f"{{{{{key}}}}}"# Use forward slashes for FFmpeg compatibility on Windowscmd_str = cmd_str.replace(placeholder, str(local_path).replace("\\", "/"))# Replace outputsresolved_outputs = {}for key, filename in output_files.items():placeholder = f"{{{{{key}}}}}"out_path = work_dir / filename# Use forward slashes for FFmpeg compatibility on Windowscmd_str = cmd_str.replace(placeholder, str(out_path).replace("\\", "/"))resolved_outputs[key] = out_path# Split the command string into a list of argumentsargs = shlex.split(cmd_str)if args and args[0] == "ffmpeg":cmd = args# Ensure -y is presentif "-y" not in cmd:cmd.insert(1, "-y")else:cmd = ["ffmpeg", "-y"] + argsreturn cmd, resolved_outputsasync def run_rendi_command(input_files: dict[str, str],output_files: dict[str, str],ffmpeg_command: str,work_dir: Path,job_id: str = "",progress_cb: Optional[Callable[[ProgressSnapshot], None]] = None,) -> dict[str, str]:"""Downloads input files, replaces placeholders, runs FFmpeg with progress tracking,and returns a dictionary of output reference keys to their local file paths."""# 1. Sanitize commandsanitize_ffmpeg_args(ffmpeg_command)# 2. Download input files in paralleldownloaded_inputs = await download_input_files(input_files, work_dir)# 3. Prepare command and resolve outputscmd, resolved_outputs = prepare_rendi_command(ffmpeg_command, downloaded_inputs, output_files, work_dir)# 4. Run FFmpeg with progressawait _ffmpeg_progress(cmd, work_dir, progress_cb)# 5. Verify all outputs existfor key, out_path in resolved_outputs.items():if not out_path.exists():raise RuntimeError(f"FFmpeg completed but output file '{key}' ({out_path.name}) was not created.")# Return mapping of output keys to their filenamesreturn {key: out_path.name for key, out_path in resolved_outputs.items()}async def run_from_file(ffmpeg_args: str,input_path: Path,
16 unmodified lines17181920212223205 unmodified lines22923023123223323471 unmodified lines30630730830931031131231331431531631716 unmodified linesimport config, ffmpeg_runner as runnerfrom gradio_ui import create_gradio_interfacefrom job_queue import JobQueuefrom models import (FFmpegCommandRequest, FFprobeRequest,HealthResponse, JobResponse, ProgressInfo, ResourceInfo)from operations import DUAL_INPUT_FIELDS, REGISTRYfrom progress import ProgressSnapshot205 unmodified linesawait queue.submit(job_id, _run())return _job_resp(job_id)# ββ structured ops β upload βββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/api/ops/{operation}/upload", response_model=JobResponse, tags=["Operations"],summary="Submit a structured operation (file upload)",71 unmodified lines@app.get("/api/download/{job_id}", tags=["Jobs"],summary="Download the processed output file",description="Streams the file in chunks. Available for 1 hour after completion.")async def download(job_id: str):rec = queue.get(job_id)if not rec: raise HTTPException(404, "Job not found.")if rec.status != "done": raise HTTPException(400, f"Job status: '{rec.status}'.")out = Path(rec.result)if not out.exists(): raise HTTPException(404, "Output file expired or was cleaned up.")return StreamingResponse(_iter_file(out), media_type="application/octet-stream",headers={"Content-Disposition": f'attachment; filename="{out.name}"',16 unmodified lines17181920212223205 unmodified lines22923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428571 unmodified lines35735835936036136236336436536636736836937037137237337437537637737837938038116 unmodified linesimport config, ffmpeg_runner as runnerfrom gradio_ui import create_gradio_interfacefrom job_queue import JobQueuefrom models import (FFmpegCommandRequest, FFprobeRequest, RendiFFmpegRequest,HealthResponse, JobResponse, ProgressInfo, ResourceInfo)from operations import DUAL_INPUT_FIELDS, REGISTRYfrom progress import ProgressSnapshot205 unmodified linesawait queue.submit(job_id, _run())return _job_resp(job_id)# ββ Rendi Compatibility βββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/v1/run-ffmpeg-command", tags=["Rendi Compatibility"], summary="Rendi-style FFmpeg Command")@app.post("/api/run-ffmpeg-command", tags=["Rendi Compatibility"], summary="Rendi-style FFmpeg Command")async def run_rendi_api(req: RendiFFmpegRequest):job_id, work_dir = _new_job()queue.create(job_id, work_dir)async def _run():outputs = await runner.run_rendi_command(req.input_files, req.output_files, req.ffmpeg_command,work_dir, job_id, _progress_cb(job_id))return _json.dumps(outputs)await queue.submit(job_id, _run())return {"command_id": job_id,"job_id": job_id,"status": "pending","download_url": f"/api/download/{job_id}"}@app.get("/v1/commands/{job_id}", tags=["Rendi Compatibility"], summary="Poll Rendi-style Command Status")@app.get("/api/commands/{job_id}", tags=["Rendi Compatibility"], summary="Poll Rendi-style Command Status")async def get_rendi_command(job_id: str):rec = queue.get(job_id)if not rec:raise HTTPException(404, "Command not found.")output_files = {}if rec.status == "done" and rec.result:try:outputs = _json.loads(rec.result)if isinstance(outputs, dict):for key, filename in outputs.items():output_files[key] = f"/api/download/{job_id}?file={filename}"except Exception:passreturn {"command_id": rec.job_id,"job_id": rec.job_id,"status": rec.status,"progress": rec.progress.to_dict(),"output_files": output_files,"error": rec.error}# ββ structured ops β upload βββββββββββββββββββββββββββββββββββββββββββββββββββ@app.post("/api/ops/{operation}/upload", response_model=JobResponse, tags=["Operations"],summary="Submit a structured operation (file upload)",71 unmodified lines@app.get("/api/download/{job_id}", tags=["Jobs"],summary="Download the processed output file",description="Streams the file in chunks. Available for 1 hour after completion.")async def download(job_id: str, file: Optional[str] = None):rec = queue.get(job_id)if not rec: raise HTTPException(404, "Job not found.")if rec.status != "done": raise HTTPException(400, f"Job status: '{rec.status}'.")if file:out = rec.work_dir / fileelse:try:outputs = _json.loads(rec.result)if isinstance(outputs, dict) and outputs:first_file = list(outputs.values())[0]out = rec.work_dir / first_fileelse:out = Path(rec.result)except Exception:out = Path(rec.result) if rec.result else Noneif not out or not out.exists(): raise HTTPException(404, "Output file expired or was cleaned up.")return StreamingResponse(_iter_file(out), media_type="application/octet-stream",headers={"Content-Disposition": f'attachment; filename="{out.name}"',
24 unmodified lines25262728293024 unmodified linesinput_url: strclass ProgressInfo(BaseModel):percent: float = 0.0speed: str = ""24 unmodified lines25262728293031323334353624 unmodified linesinput_url: strclass RendiFFmpegRequest(BaseModel):input_files: dict[str, str]output_files: dict[str, str]ffmpeg_command: strclass ProgressInfo(BaseModel):percent: float = 0.0speed: str = ""
ffmpeg_runner.py+111
main.py+68-4
models.py+6