#!/usr/bin/env python3 """ Generate MP4 and GIF preview videos from HuggingFace parquet files. Reads the top_down_preview and volume_preview image columns from each parquet file and stitches them into MP4 and GIF videos. Output structure: previews///top_down.mp4 previews///top_down.gif previews///volume.mp4 previews///volume.gif Already-existing files are skipped automatically. """ import argparse import io import multiprocessing import subprocess import tempfile from pathlib import Path import imageio import pyarrow.parquet as pq from PIL import Image from tqdm import tqdm CONFIGS = [ "temperature", "fraction_of_fluid", "liquid_label", "melt_region", "pressure", "temperature_gradient", "velocity_magnitude", "gradient_magnitude", "vx_vy_vz", "dtdx_dtdy_dtdz", ] FPS = 20 MAX_FRAMES = 200 def frames_to_mp4(frames: list[bytes], mp4_path: Path, fps: int) -> None: """Pipe PNG frames to ffmpeg to produce an MP4.""" mp4_path.parent.mkdir(parents=True, exist_ok=True) # Determine frame dimensions from first frame img = Image.open(io.BytesIO(frames[0])) w, h = img.size # Ensure even dimensions for yuv420p w_pad = w + (w % 2) h_pad = h + (h % 2) proc = subprocess.Popen( [ "ffmpeg", "-y", "-f", "image2pipe", "-framerate", str(fps), "-i", "-", "-vf", f"pad={w_pad}:{h_pad}", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "faststart", "-loglevel", "error", str(mp4_path), ], stdin=subprocess.PIPE, ) for frame_bytes in frames: proc.stdin.write(frame_bytes) proc.stdin.close() proc.wait() if proc.returncode != 0: raise RuntimeError(f"ffmpeg failed for {mp4_path}") def frames_to_gif(frames: list[bytes], gif_path: Path, fps: int) -> None: """Convert PNG frame bytes to an animated GIF.""" gif_path.parent.mkdir(parents=True, exist_ok=True) images = [imageio.v3.imread(io.BytesIO(f)) for f in frames] imageio.mimsave(str(gif_path), images, fps=fps, loop=0) def process_parquet(args: tuple) -> str: """Process one parquet file → MP4s and GIFs (top_down + volume).""" parquet_path, previews_dir, config, case_name, fps, max_frames = args out_dir = previews_dir / config / case_name td_mp4 = out_dir / "top_down.mp4" td_gif = out_dir / "top_down.gif" vol_mp4 = out_dir / "volume.mp4" vol_gif = out_dir / "volume.gif" # Skip if all already exist if td_mp4.exists() and td_gif.exists() and vol_mp4.exists() and vol_gif.exists(): return case_name table = pq.read_table( parquet_path, columns=["top_down_preview", "volume_preview"], ) n_rows = len(table) stride = max(1, n_rows // max_frames) td_frames = [] vol_frames = [] for i in range(0, n_rows, stride): td_data = table.column("top_down_preview")[i].as_py() vol_data = table.column("volume_preview")[i].as_py() td_frames.append(td_data["bytes"]) vol_frames.append(vol_data["bytes"]) if td_frames: if not td_mp4.exists(): frames_to_mp4(td_frames, td_mp4, fps) if not td_gif.exists(): frames_to_gif(td_frames, td_gif, fps) if vol_frames: if not vol_mp4.exists(): frames_to_mp4(vol_frames, vol_mp4, fps) if not vol_gif.exists(): frames_to_gif(vol_frames, vol_gif, fps) return f"{config}/{case_name}" def main() -> None: parser = argparse.ArgumentParser( description="Generate MP4 preview videos from parquet files." ) parser.add_argument( "cases", nargs="*", help="Case names (default: all cases)", ) parser.add_argument( "--config", type=str, default=None, help="Process only this config (default: all configs)", ) parser.add_argument("--fps", type=int, default=FPS) parser.add_argument("--max-frames", type=int, default=MAX_FRAMES) parser.add_argument( "--workers", type=int, default=max(1, multiprocessing.cpu_count() // 4), help="Parallel worker processes (default: cpu_count // 4)", ) args = parser.parse_args() root = Path(__file__).parent.parent data_dir = root / "data" previews_dir = root / "previews" configs = [args.config] if args.config else CONFIGS # Collect all parquet files to process todo = [] for config in configs: config_dir = data_dir / config if not config_dir.exists(): continue parquets = sorted(config_dir.glob("*.parquet")) for pq_path in parquets: case_name = pq_path.stem if args.cases and case_name not in args.cases: continue out_dir = previews_dir / config / case_name td_mp4 = out_dir / "top_down.mp4" td_gif = out_dir / "top_down.gif" vol_mp4 = out_dir / "volume.mp4" vol_gif = out_dir / "volume.gif" if td_mp4.exists() and td_gif.exists() and vol_mp4.exists() and vol_gif.exists(): continue todo.append((pq_path, previews_dir, config, case_name, args.fps, args.max_frames)) if not todo: print("Nothing to do.") return print(f"Generating MP4/GIF previews for {len(todo)} parquet files with {args.workers} workers\n") with multiprocessing.Pool(args.workers) as pool: for done in tqdm( pool.imap_unordered(process_parquet, todo), total=len(todo), desc="Previews", ): pass print(f"\nDone. MP4s written to {previews_dir}/") if __name__ == "__main__": main()