File size: 4,504 Bytes
7f97480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
"""Extract representative frames from MP4 demonstrations for manual inspection."""

import argparse
import json
import os
from pathlib import Path
from typing import List, Optional

import mediapy as media
import numpy as np


def parse_fractions(fractions):
    values = []
    for f in fractions:
        value = float(f)
        if not 0.0 <= value <= 1.0:
            raise ValueError(f"Fraction {value} must be in [0, 1].")
        values.append(value)
    return values


def extract_frames(video_path: Path, fractions, output_dir: Path, video_root: Optional[Path]):
    frames = media.read_video(video_path)
    if len(frames) == 0:
        print(f"[WARN] {video_path}: empty video")
        return 0
    frame_indices = sorted(set(int(round(frac * (len(frames) - 1))) for frac in fractions))
    base = video_path.stem
    if video_root is not None:
        try:
            rel_dir = video_path.parent.relative_to(video_root)
        except ValueError:
            rel_dir = Path()
    else:
        rel_dir = Path()
    save_dir = output_dir / rel_dir / base
    save_dir.mkdir(parents=True, exist_ok=True)
    saved = 0
    for idx in frame_indices:
        frame = frames[idx]
        out_path = save_dir / f"frame_{idx:04d}.png"
        media.write_image(out_path, frame)
        saved += 1
    return saved


def iter_videos_from_preview(preview_path: Path) -> List[Path]:
    videos: List[Path] = []
    with preview_path.open("r", encoding="utf-8") as fh:
        for line in fh:
            if not line.strip():
                continue
            record = json.loads(line)
            if record.get("instruction") is not None:
                continue
            h5_path = Path(record["path"])
            video_name = h5_path.name.replace("data_", "demo_").replace(".hdf5", ".mp4")
            video_path = h5_path.with_name(video_name)
            videos.append(video_path)
    return videos


def main():
    parser = argparse.ArgumentParser(description="Sample frames from MP4 videos.")
    parser.add_argument("--video-dir", help="Directory containing demo_*.mp4 files.")
    parser.add_argument(
        "--pattern",
        default="demo_*.mp4",
        help="Glob relative to --video-dir for selecting videos (default: demo_*.mp4).",
    )
    parser.add_argument(
        "--frames",
        nargs="+",
        default=["0.1", "0.5", "0.9"],
        help="Normalized positions (0-1) from which to sample frames.",
    )
    parser.add_argument("--output", required=True, help="Directory to store extracted frame images.")
    parser.add_argument("--max-videos", type=int, help="Optional cap on number of videos to process.")
    parser.add_argument(
        "--preview-json",
        type=Path,
        help="JSONL preview file (from update_instructions script). Only videos with null instruction will be processed.",
    )
    parser.add_argument(
        "--dataset-root",
        help="Root directory containing the dataset (used to preserve relative structure when --preview-json is set).",
    )
    args = parser.parse_args()

    output_dir = Path(args.output).expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    fractions = parse_fractions(args.frames)

    videos: List[Path]
    video_root: Optional[Path]
    if args.preview_json:
        preview_path = Path(args.preview_json).expanduser().resolve()
        videos = iter_videos_from_preview(preview_path)
        if args.dataset_root:
            video_root = Path(args.dataset_root).expanduser().resolve()
        else:
            # try to guess common ancestor
            parents = {vp.parent for vp in videos}
            parent_paths = [str(p) for p in parents]
            video_root = Path(os.path.commonpath(parent_paths)) if parent_paths else None
    else:
        if not args.video_dir:
            raise ValueError("--video-dir is required when --preview-json is not provided.")
        video_root = Path(args.video_dir).expanduser().resolve()
        videos = sorted(video_root.glob(args.pattern))

    if args.max_videos is not None:
        videos = videos[: args.max_videos]
    print(f"Found {len(videos)} videos to process.")
    total_frames = 0
    for vp in videos:
        if not vp.exists():
            print(f"[WARN] Missing video {vp}")
            continue
        total_frames += extract_frames(vp, fractions, output_dir, video_root)
    print(f"Saved {total_frames} frames into {output_dir}.")


if __name__ == "__main__":
    main()