import os import json from pathlib import Path from PIL import Image data_dir = Path("data/animations") output_dir = Path("data/shots") # create output directory if it doesn't exist output_dir.mkdir(parents=True, exist_ok=True) # Find all .webp files in data/animations webp_files = sorted(data_dir.glob("sample-*.webp")) for webp_file in webp_files: # Extract NNN from filename base_name = webp_file.stem # sample-NNN nnn = base_name.split("-")[1] hf_json_path = data_dir / f"sample-{nnn}.hf.json" if not hf_json_path.exists(): print(f"Missing {hf_json_path}, skipping {webp_file}") continue # Load human feedback json with open(hf_json_path, "r") as f: hf_data = json.load(f) # Open the .webp image img = Image.open(webp_file) # Get scene change indices indices = hf_data.get("scene_change_indices", []) if not indices: print(f"No scene_change_indices in {hf_json_path}, skipping.") continue # Build split frame ranges ranges = [] prev = 0 for idx in indices: ranges.append((prev, idx)) prev = idx + 1 # Add final range to end of frames total_frames = getattr(img, 'n_frames', 1) ranges.append((prev, total_frames - 1)) for i, (start, end) in enumerate(ranges): frames = [] durations = [] for frame_idx in range(start, end + 1): img.seek(frame_idx) frames.append(img.copy()) # Get duration for each frame duration = img.info.get('duration', 40) # default to 40ms if missing durations.append(duration) if frames: out_path = output_dir / f"sample-{nnn}-{i}.webp" if len(frames) == 1: frames[0].save(out_path, format="WEBP", duration=durations[0]) else: frames[0].save(out_path, format="WEBP", save_all=True, append_images=frames[1:], duration=durations) print(f"Saved {out_path} ({len(frames)} frames)")