Spaces:
Sleeping
Sleeping
Update ffmpeg_runner.py (#8)
Browse files- Update ffmpeg_runner.py (57855e9a1c072240f4c89a5eaed569e2ee35234a)
116 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491506 unmodified lines157158159160116 unmodified linesreturn output_pathasync def run_ffprobe(input_url: str) -> dict:"""Return full ffprobe JSON for a URL."""cmd = ["ffprobe","-v", "quiet","-print_format", "json","-show_streams","-show_format",input_url,]proc = await asyncio.create_subprocess_exec(*cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)try:stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=60)except asyncio.TimeoutError:proc.kill()raise RuntimeError("ffprobe timed out.")if proc.returncode != 0:err = stderr.decode(errors="replace")raise RuntimeError(f"ffprobe failed:\n{err}")return json.loads(stdout.decode())def get_ffmpeg_version() -> str:6 unmodified linesfirst_line = result.stdout.splitlines()[0]return first_line # e.g. "ffmpeg version 6.0 ..."except Exception:return "unknown"116 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632646 unmodified lines271272273274116 unmodified linesreturn output_pathdef _is_redirect_url(url: str) -> bool:"""Returns True for URLs that need pre-downloading (GDrive, etc.)."""return ("drive.google.com" in urlor "drive.usercontent.google.com" in urlor "docs.google.com" in url)def _download_to_tempfile(url: str, dest_dir: Path) -> Path:"""Download URL to a temp file in dest_dir.Handles GDrive confirmation pages automatically.Returns the temp file path."""import requestsimport tempfilesession = requests.Session()headers = {"User-Agent": "Mozilla/5.0 (compatible; ffprobe/1.0)"}resp = session.get(url, headers=headers, stream=True, timeout=120, allow_redirects=True)resp.raise_for_status()# If GDrive returned HTML (virus-scan warning), grab the confirm token and retrycontent_type = resp.headers.get("content-type", "")if "text/html" in content_type:# Try to extract download warning form action / confirm param from HTMLhtml = resp.content.decode(errors="replace")# Modern GDrive uses a "confirm" query param approachimport re as _rematch = _re.search(r'confirm=([0-9A-Za-z_\-]+)', html)if match:confirm = match.group(1)# Re-request with confirm tokenresp = session.get(url,headers=headers,params={"confirm": confirm},stream=True,timeout=120,allow_redirects=True,)resp.raise_for_status()content_type = resp.headers.get("content-type", "")if "text/html" in content_type:raise RuntimeError(f"URL returned HTML instead of media "f"(content-type: {content_type}). "f"Ensure the file is publicly shared and use a direct download URL.")# Detect extension from content-disposition or URLsuffix = ".mp4"cd = resp.headers.get("content-disposition", "")if "filename=" in cd:fname = cd.split("filename=")[-1].strip().strip('"').split(";")[0].strip()ext = Path(fname).suffixif ext:suffix = extelif "." in url.split("?")[0].split("/")[-1]:suffix = "." + url.split("?")[0].split("/")[-1].rsplit(".", 1)[-1]tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=str(dest_dir))for chunk in resp.iter_content(chunk_size=65536):if chunk:tmp.write(chunk)tmp.flush()tmp.close()tmp_path = Path(tmp.name)if tmp_path.stat().st_size == 0:tmp_path.unlink(missing_ok=True)raise RuntimeError("Downloaded file is 0 bytes — check file permissions/sharing settings.")return tmp_pathasync def run_ffprobe(input_url: str, temp_dir: Optional[Path] = None) -> dict:"""Return full ffprobe JSON for a URL or local path.GDrive and other redirect-heavy URLs are pre-downloaded first."""tmp_path: Optional[Path] = Noneprobe_target = input_urltry:if _is_redirect_url(input_url):td = temp_dir or Path("/tmp/frameforge")td.mkdir(parents=True, exist_ok=True)loop = asyncio.get_event_loop()tmp_path = await loop.run_in_executor(None, _download_to_tempfile, input_url, td)probe_target = str(tmp_path)cmd = ["ffprobe","-v", "error", # show errors (not quiet) so we get real messages"-print_format", "json","-show_streams","-show_format","-show_error",probe_target,]proc = await asyncio.create_subprocess_exec(*cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,)try:stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=120)except asyncio.TimeoutError:proc.kill()raise RuntimeError("ffprobe timed out after 120s.")stdout_str = stdout.decode(errors="replace").strip()stderr_str = stderr.decode(errors="replace").strip()if proc.returncode != 0 or not stdout_str:raise RuntimeError(f"ffprobe failed (exit {proc.returncode}): "f"{stderr_str or 'no stderr output'}")try:return json.loads(stdout_str)except json.JSONDecodeError as e:raise RuntimeError(f"ffprobe returned invalid JSON (exit {proc.returncode}): "f"{stderr_str}. JSON error: {e}")finally:if tmp_path and tmp_path.exists():try:tmp_path.unlink()except Exception:passdef get_ffmpeg_version() -> str:6 unmodified linesfirst_line = result.stdout.splitlines()[0]return first_line # e.g. "ffmpeg version 6.0 ..."except Exception:return "unknown"
ffmpeg_runner.py+137-23