Spaces:
Sleeping
Sleeping
Update main.py
#5
by kajalan - opened
3 unmodified lines4567891 unmodified line11121314151623 unmodified lines40414243444517 unmodified lines6364656667686941 unmodified lines11111211311411511611711811912012112213 unmodified lines13613713813914014114214314414514614732 unmodified lines180181182183184185186187188189101 unmodified lines2912922932943 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, JSONResponse23 unmodified linesJOBS: dict[str, dict] = {}async def _cleanup_old_jobs():"""Periodically remove jobs older than JOB_TTL_SECONDS."""import time17 unmodified linescleanup_task = asyncio.create_task(_cleanup_old_jobs())yieldcleanup_task.cancel()# Leave /tmp as-is (HF Spaces resets on restart anyway)# ── App ───────────────────────────────────────────────────────────────────────41 unmodified lines"""Run **ffprobe** on any publicly accessible URL and return full JSONmetadata (streams, format, codec, bitrate, duration, etc.)."""try:data = await run_ffprobe(request.input_url)return dataexcept RuntimeError as e:raise HTTPException(status_code=422, detail=str(e))@app.post(13 unmodified lines1. POST here → get `job_id`2. Poll `GET /api/jobs/{job_id}` until `status == "done"`3. Download result from `GET /api/download/{job_id}`**Example `ffmpeg_args`:**- Resize: `-vf scale=1280:720 -c:v libx264 -preset fast`- Extract audio: `-vn -acodec libmp3lame -q:a 2`- Screenshot: `-ss 00:00:05 -vframes 1`- GIF: `-vf fps=10,scale=480:-1 -loop 0`"""import timejob_id = uuid.uuid4().hex[:8]32 unmodified lines"""import time# Size guardcontent = await file.read()if len(content) > MAX_UPLOAD_BYTES:raise HTTPException(413, detail=f"File exceeds 500 MB limit.")job_id = uuid.uuid4().hex[:8]work_dir = TEMP_DIR / job_id101 unmodified lines# ── Mount Gradio playground at /ui ────────────────────────────────────────────gradio_demo = create_gradio_interface()app = gr.mount_gradio_app(app, gradio_demo, path="/ui")3 unmodified lines456789101 unmodified line1213141516171823 unmodified lines4243444546474849505152535455565758596061626364656667686970717273747517 unmodified lines93949596979841 unmodified lines14014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517613 unmodified lines19019119219319419532 unmodified lines228229230231232233234235236101 unmodified lines3383393403413 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, JSONResponse23 unmodified linesJOBS: 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 time17 unmodified linescleanup_task = asyncio.create_task(_cleanup_old_jobs())yieldcleanup_task.cancel()# ── App ───────────────────────────────────────────────────────────────────────41 unmodified lines"""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)}")data = await run_ffprobe(probe_target)return dataexcept HTTPException:raiseexcept RuntimeError as e:raise HTTPException(status_code=422, detail=str(e))finally:# Clean up temp file if we created oneif tmp_path:try:Path(tmp_path).unlink(missing_ok=True)except Exception:pass@app.post(13 unmodified lines1. 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]32 unmodified lines"""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_id101 unmodified lines# ── Mount Gradio playground at /ui ────────────────────────────────────────────gradio_demo = create_gradio_interface()app = gr.mount_gradio_app(app, gradio_demo, path="/ui")
main.py+58-11