File size: 6,806 Bytes
4a735cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python3
"""Rebuild `obs_frame.png` for the Ego4D-derived samples of AFUN_pool.

AFUN_pool ships every annotation for these samples (affordance mask, 3D motion,
camera intrinsics, instruction) but NOT the RGB frame or the depth map: the
Ego4D license permits distributing annotations, not the imagery itself. Each
sample's `provenance.json` therefore points at the exact Ego4D video frame the
annotation was made on. This script decodes that frame from your own Ego4D
download and writes it next to the annotations, so the sample folder ends up in
the same 3-file layout as the rest of the release
(`obs_frame.png`, `sam_mask.png`, `trajectory.json`).

Steps
-----
1. Get Ego4D access (sign the license at https://ego4d-data.org) and download
   the full-scale videos for the UIDs used here:

       python reconstruct_ego4d_frames.py --pool-root AFUN_pool/ego4d --list-uids > uids.txt
       ego4d --output_directory ~/ego4d --datasets full_scale --version v2 \
             --video_uid_file uids.txt

   which yields `~/ego4d/v2/full_scale/<uid>.mp4`.

2. Decode the frames (PyAV required: `pip install av`):

       python reconstruct_ego4d_frames.py --pool-root AFUN_pool/ego4d --ego4d-root ~/ego4d

   `--verify` additionally checks every decoded frame against the pixel hash
   recorded in `provenance.json`, so you know the reconstruction is exact.

Decoding is done exactly the way the frames were extracted originally: PyAV,
seek to the keyframe before the target, decode forward, frame index =
round(pts * time_base * fps), `to_ndarray(format="rgb24")`, no resizing.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys
from collections import defaultdict
from pathlib import Path

import numpy as np

PROV_NAME = "provenance.json"


def pixel_sha256(rgb: np.ndarray) -> str:
    """Hash of the raw H×W×3 uint8 pixels — independent of PNG encoder settings."""
    return hashlib.sha256(np.ascontiguousarray(rgb, dtype=np.uint8).tobytes()).hexdigest()


def iter_samples(pool_root: Path):
    """Yield (sample_dir, provenance) for every sample under pool_root."""
    for prov_path in sorted(pool_root.rglob(PROV_NAME)):
        yield prov_path.parent, json.loads(prov_path.read_text())


def open_video(path: Path):
    import av  # noqa: WPS433  (imported lazily so --list-uids works without PyAV)

    container = av.open(str(path))
    stream = container.streams.video[0]
    fps = float(stream.average_rate) if stream.average_rate else 30.0
    return container, stream, fps


def decode_frame(container, stream, fps: float, frame_idx: int, last_frame: int) -> tuple[np.ndarray, int]:
    """Decode `frame_idx`, reusing the open stream when reading forward.

    Mirrors the original extraction code: seek only when moving backwards (or on
    the first read), then decode forward until the target index is reached.
    Returns (rgb, last_decoded_frame_index).
    """
    if frame_idx <= last_frame or last_frame < 0:
        seek_pts = int((frame_idx / fps) / stream.time_base)
        container.seek(seek_pts, stream=stream, any_frame=False, backward=True)
        last_frame = -1
    for frame in container.decode(stream):
        if frame.pts is None:
            continue
        cur = int(float(frame.pts * stream.time_base) * fps + 0.5)
        last_frame = cur
        if cur >= frame_idx:
            rgb = frame.to_ndarray(format="rgb24")
            if rgb.ndim == 2:
                rgb = np.stack([rgb] * 3, axis=-1)
            elif rgb.shape[2] == 4:
                rgb = rgb[:, :, :3]
            return rgb.astype(np.uint8), last_frame
    raise IndexError(f"frame {frame_idx} not reachable (last decoded {last_frame})")


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--pool-root", type=Path, required=True,
                    help="Directory holding the Ego4D-derived AFUN_pool samples (contains provenance.json files)")
    ap.add_argument("--ego4d-root", type=Path,
                    help="Your Ego4D download root; videos are expected at <root>/v2/full_scale/<uid>.mp4")
    ap.add_argument("--list-uids", action="store_true",
                    help="Print the Ego4D video UIDs needed (one per line) and exit")
    ap.add_argument("--verify", action="store_true",
                    help="Compare each decoded frame's pixel hash with provenance.json")
    ap.add_argument("--overwrite", action="store_true", help="Re-decode even if obs_frame.png exists")
    args = ap.parse_args()

    samples = list(iter_samples(args.pool_root))
    if not samples:
        sys.exit(f"no {PROV_NAME} found under {args.pool_root}")

    if args.list_uids:
        for uid in sorted({p["ego4d_video_uid"] for _, p in samples}):
            print(uid)
        return 0
    if args.ego4d_root is None:
        sys.exit("--ego4d-root is required unless --list-uids is given")

    from PIL import Image  # noqa: WPS433

    # Group by video so each file is opened once and read mostly forward.
    by_video: dict[str, list] = defaultdict(list)
    for d, p in samples:
        by_video[p["ego4d_video_uid"]].append((p["ego4d_frame_index"], d, p))

    n_ok = n_skip = n_bad = n_missing_video = 0
    for uid, items in sorted(by_video.items()):
        video = args.ego4d_root / "v2" / "full_scale" / f"{uid}.mp4"
        if not video.is_file():
            n_missing_video += 1
            print(f"[missing video] {video}  ({len(items)} samples)", file=sys.stderr)
            continue
        container, stream, fps = open_video(video)
        last = -1
        for frame_idx, sample_dir, prov in sorted(items):
            out = sample_dir / "obs_frame.png"
            if out.exists() and not args.overwrite and not args.verify:
                n_skip += 1
                continue
            try:
                rgb, last = decode_frame(container, stream, fps, frame_idx, last)
            except Exception as e:  # keep going; report at the end
                n_bad += 1
                print(f"[decode failed] {sample_dir}: {e}", file=sys.stderr)
                continue
            if args.verify and prov.get("rgb_sha256") and pixel_sha256(rgb) != prov["rgb_sha256"]:
                n_bad += 1
                print(f"[hash mismatch] {sample_dir} frame {frame_idx}", file=sys.stderr)
                continue
            if not out.exists() or args.overwrite:
                Image.fromarray(rgb).save(out)
            n_ok += 1
        container.close()

    print(f"done: {n_ok} frames written/verified, {n_skip} skipped (already present), "
          f"{n_bad} failed, {n_missing_video} videos missing")
    return 1 if (n_bad or n_missing_video) else 0


if __name__ == "__main__":
    sys.exit(main())