from __future__ import annotations import asyncio from pathlib import Path TEMP_VIDEOS_DIRECTORY = (Path(__file__).parent.parent / "temp").absolute() if not TEMP_VIDEOS_DIRECTORY.exists(): TEMP_VIDEOS_DIRECTORY.mkdir() async def is_real_video(video: Path) -> bool: cmd = [ "ffprobe", "-v", "error", "-show_entries", "format=format_name,format_long_name", "-of", "default=nw=1", str(video), ] ps = await asyncio.create_subprocess_shell( " ".join(cmd), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) await ps.communicate() return ps.returncode == 0 async def get_video_duration(video: Path) -> float | None: cmd = [ "ffprobe", "-show_entries", "format=duration", "-v", "quiet", "-of", '"csv=p=0"', str(video), ] ps = await asyncio.create_subprocess_shell( " ".join(cmd), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, _ = await ps.communicate() stdout = stdout.decode().strip() return float(stdout) if stdout else None async def take_screenshot(video: Path, path: Path, duration: int | None = None) -> Path: if not isinstance(duration, int | float): duration = await get_video_duration(video) cmd = [ "ffmpeg", "-y", "-v", "error", "-ss", str(int(duration / 2)), "-i", str(video), "-frames:v", "1", "-qscale:v", "2", "-vf", '"scale=min(iw\\,ih)*320/ih:-1"', str(path), ] ps = await asyncio.create_subprocess_shell( " ".join(cmd), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) _, _ = await ps.communicate() return path