Datasets:
Download extract_frames.py from carpedkm/CustoMDiT: direct link, hf CLI and curl.
- Browser
- Download file 4.78 kB
-
https://huggingface.co/datasets/carpedkm/CustoMDiT/resolve/main/extract_frames.py
- Command line
-
hf download hf://datasets/carpedkm/CustoMDiT/extract_frames.py
-
curl -L -o extract_frames.py https://huggingface.co/datasets/carpedkm/CustoMDiT/resolve/main/extract_frames.py
4.78 kB
| """Extract reference keyframes from videos using annotation metadata. | |
| This script reads annotation JSONs to find the keyframe index for each video, | |
| extracts that frame, and saves it as 'original.png' in the expected directory | |
| structure for CustomDiT training. | |
| Usage: | |
| python extract_frames.py \ | |
| --video_dir ./data/videos \ | |
| --annotation_dir ./data/annotations \ | |
| --output_dir ./data/reference_images \ | |
| --metadata_csv ./data/metadata/train.csv | |
| The output directory structure will match what CustomDiT training expects: | |
| {output_dir}/{videoid}/original.png | |
| For example: | |
| data/reference_images/pexels/videos-popular/10000201/original.png | |
| """ | |
| import os | |
| import json | |
| import argparse | |
| from PIL import Image | |
| try: | |
| import decord | |
| decord.bridge.set_bridge("native") | |
| except ImportError: | |
| print("Error: decord is required. Install with: pip install decord") | |
| exit(1) | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description="Extract reference keyframes from videos") | |
| parser.add_argument("--video_dir", type=str, required=True, | |
| help="Root directory containing videos (e.g., ./data/videos)") | |
| parser.add_argument("--annotation_dir", type=str, required=True, | |
| help="Root directory containing annotation JSONs (e.g., ./data/annotations)") | |
| parser.add_argument("--output_dir", type=str, required=True, | |
| help="Output directory for reference images (e.g., ./data/reference_images)") | |
| parser.add_argument("--metadata_csv", type=str, required=True, | |
| help="Path to train.csv or val.csv to get list of videoids") | |
| parser.add_argument("--num_workers", type=int, default=4, | |
| help="Number of parallel workers") | |
| return parser.parse_args() | |
| def extract_keyframe(videoid, video_dir, annotation_dir, output_dir): | |
| """Extract keyframe for a single video.""" | |
| basename = os.path.basename(videoid) | |
| output_path = os.path.join(output_dir, videoid, "original.png") | |
| # Skip if already extracted | |
| if os.path.exists(output_path): | |
| return "skip" | |
| # Read annotation JSON to get keyframe_index | |
| json_path = os.path.join(annotation_dir, videoid, f"{basename}.json") | |
| if not os.path.exists(json_path): | |
| return "missing_json" | |
| with open(json_path, "r") as f: | |
| data = json.load(f) | |
| keyframe_index = data.get("keyframe_index") | |
| if keyframe_index is None: | |
| return "no_keyframe_index" | |
| # Find video file | |
| video_path = os.path.join(video_dir, f"{videoid}.mp4") | |
| if not os.path.exists(video_path): | |
| # Try without extension (in case videoid already has extension) | |
| video_path = os.path.join(video_dir, videoid) | |
| if not os.path.exists(video_path): | |
| return "missing_video" | |
| # Extract frame | |
| try: | |
| vr = decord.VideoReader(video_path) | |
| # Clamp keyframe_index to valid range | |
| idx = min(keyframe_index, len(vr) - 1) | |
| frame = vr[idx] | |
| img = Image.fromarray(frame.asnumpy()).convert("RGB") | |
| os.makedirs(os.path.dirname(output_path), exist_ok=True) | |
| img.save(output_path) | |
| return "ok" | |
| except Exception as e: | |
| return f"error: {e}" | |
| def main(): | |
| args = parse_args() | |
| # Get unique videoids from metadata CSV | |
| videoids = set() | |
| with open(args.metadata_csv, "r") as f: | |
| header = f.readline() # skip header | |
| for line in f: | |
| parts = line.strip().split(",", 2) | |
| if parts: | |
| videoids.add(parts[0]) | |
| videoids = sorted(videoids) | |
| print(f"Found {len(videoids)} unique videos to process") | |
| stats = {"ok": 0, "skip": 0, "missing_video": 0, "missing_json": 0, "error": 0} | |
| for i, videoid in enumerate(videoids): | |
| result = extract_keyframe(videoid, args.video_dir, args.annotation_dir, args.output_dir) | |
| if result == "ok": | |
| stats["ok"] += 1 | |
| elif result == "skip": | |
| stats["skip"] += 1 | |
| elif result.startswith("missing"): | |
| stats[result] = stats.get(result, 0) + 1 | |
| else: | |
| stats["error"] += 1 | |
| if stats["error"] <= 10: | |
| print(f" Error on {videoid}: {result}") | |
| if (i + 1) % 1000 == 0 or (i + 1) == len(videoids): | |
| print(f"[{i+1}/{len(videoids)}] extracted={stats['ok']} skipped={stats['skip']} " | |
| f"missing_video={stats.get('missing_video', 0)} " | |
| f"missing_json={stats.get('missing_json', 0)} errors={stats['error']}") | |
| print(f"\nDone! Extracted {stats['ok']} keyframes, " | |
| f"skipped {stats['skip']} existing, " | |
| f"{stats.get('missing_video', 0)} videos not found.") | |
| if __name__ == "__main__": | |
| main() | |