File size: 9,336 Bytes
c150001
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python3
"""frames_decode.py — frame cache for steps 2 and 3.

Cache location: bench_exp/work/pool_frames/<video_id>/frame_<k>.jpg + frames.json
(video_id = content_hash). Decision (2026-09-06): the cluster runs
job_container/tmpfs (per-job private /tmp, destroyed at job end) and the MIG node
reports TmpDisk=0, so node-local storage cannot be shared between the CPU decode array
and the GPU array. /vast is the shared NVMe-backed (VAST) filesystem every node mounts;
it is the only cache that the decode array and all GPU tasks can read and write, and
it survives job boundaries for incremental re-runs. GPU tasks decode any video still
missing from the cache on the fly (same function) so steps 2-3 never block on the array.

Frames = the stage_p1_runner v_32 grid: 32 time-uniform targets over meta
frame_timestamps, nearest frame index each, duplicates (short videos) collapsed to the
first grid position. frame_<k>.jpg is named by grid position k (0..31); frames.json
lists the positions that exist (`keys`), the single-frame position `mid_k` (grid
position 16 = v_1), and the frame size after resizing to a 448 px long side (never
upscaled), JPEG q85.

  frames_decode.py [--shard i/k] [--workers 8] [--limit N] [--video-ids FILE]
                   [--all-videos]   (default: videos of items still in the pool)
  frames_decode.py --stats
"""
import argparse
import hashlib
import io
import json
import os
import shutil
import sys
import time
from concurrent.futures import ProcessPoolExecutor, as_completed

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pool_common as pc  # noqa: E402
from pool_common import log  # noqa: E402


def frames_json_path(video_id):
    return os.path.join(pc.FRAMES_DIR, video_id, "frames.json")


def load_frames_json(video_id):
    p = frames_json_path(video_id)
    if not os.path.exists(p):
        return None
    try:
        d = json.load(open(p))
        return d if d.get("ok") else None
    except Exception:
        return None


def grid_positions(meta):
    """-> (grid of 32 frame indices, ordered unique positions k, mid_k)."""
    from stage_p1_runner import _nearest_indices, _uniform_times
    n = int(meta["n_frames"])
    ts = meta.get("frame_timestamps") or []
    if len(ts) != n or n == 0:
        ts = list(range(max(n, 1)))
    grid = _nearest_indices(ts, _uniform_times(ts[0], ts[-1], pc.N_FRAMES_V32))
    first = {}
    keys = []
    for k, idx in enumerate(grid):
        if idx not in first:
            first[idx] = k
            keys.append(k)
    mid_k = first[grid[pc.MID_POS]]
    return grid, keys, mid_k


def ensure_frames(video_id, video_path, meta=None, long_side=pc.FRAME_LONG_SIDE):
    """Decode + cache if missing; returns the frames.json dict (or raises)."""
    d = load_frames_json(video_id)
    if d is not None:
        return d
    from PIL import Image
    from extract_frames import _decode
    if meta is None:
        meta = pc.meta_of(video_id)
    if not meta:
        raise RuntimeError("meta.json missing")
    grid, keys, mid_k = grid_positions(meta)
    idxs = [grid[k] for k in keys]
    decoded = _decode(video_path, idxs)                 # {idx: PIL}
    avail = max(decoded)
    out_dir = os.path.join(pc.FRAMES_DIR, video_id)
    tmp_dir = f"{out_dir}.tmp{os.getpid()}"
    os.makedirs(tmp_dir, exist_ok=True)
    w = h = None
    for k, idx in zip(keys, idxs):
        im = decoded[min(idx, avail)].convert("RGB")
        W, H = im.size
        s = long_side / max(W, H)
        if s < 1.0:
            im = im.resize((max(1, round(W * s)), max(1, round(H * s))), Image.LANCZOS)
        w, h = im.size
        im.save(os.path.join(tmp_dir, f"frame_{k}.jpg"), format="JPEG", quality=pc.JPEG_QUALITY)
    info = dict(video_id=video_id, n_frames_video=int(meta.get("n_frames", 0)), grid=grid, keys=keys,
                mid_k=mid_k, w=w, h=h, long_side=long_side, jpeg_quality=pc.JPEG_QUALITY,
                too_short=bool(meta.get("too_short")), ok=True, ts=time.strftime("%F %T"))
    json.dump(info, open(os.path.join(tmp_dir, "frames.json"), "w"))
    try:
        os.rename(tmp_dir, out_dir)
    except OSError:
        # another worker finished first: keep theirs
        shutil.rmtree(tmp_dir, ignore_errors=True)
        d = load_frames_json(video_id)
        if d is None:
            raise
        return d
    return info


def frame_bytes(video_id, k):
    with open(os.path.join(pc.FRAMES_DIR, video_id, f"frame_{k}.jpg"), "rb") as f:
        return f.read()


# ------------------------------------------------------------------ selection
def pool_videos(all_videos=False):
    """(video_id, video_path) of videos whose items are still in the pool: base items
    that are mcq, kept by step 0 (if run) and not removed by step 1 (if run)."""
    import pyarrow.parquet as pq
    df = pq.read_table(pc.BASE_PARQUET, columns=["benchmark", "item_id", "video_key", "video_id",
                                                 "video_path", "format"]).to_pandas()
    hashes = pc.manifest_hashes()
    pend = df["video_id"].str.startswith("k:")
    new = df.loc[pend, "video_key"].map(hashes)
    got = new.notna()
    df.loc[new[got].index, "video_id"] = new[got].values
    df.loc[new[got].index, "video_path"] = [pc.normalized_path(x) for x in new[got].values]
    df = df[df["video_path"].notna()]
    if not all_videos:
        df = df[df["format"] == "mcq"]
        if os.path.exists(pc.STEP0_KEPT):
            kept = pq.read_table(pc.STEP0_KEPT, columns=["item_id", "kept"]).to_pandas()
            keep_ids = set(kept.loc[kept["kept"], "item_id"])
            df = df[df["item_id"].isin(keep_ids)]
        ok1, _ = pc.load_step_rows(1)
        if ok1:
            removed = {i for i, r in ok1.items() if r.get("remove")}
            df = df[~df["item_id"].isin(removed)]
    vids = df.drop_duplicates("video_id")[["video_id", "video_path"]]
    return list(vids.itertuples(index=False, name=None))


def shard_of(video_id, n):
    return int(hashlib.sha1(video_id.encode()).hexdigest()[:8], 16) % n


def work_one(video_id, video_path):
    t0 = time.time()
    try:
        info = ensure_frames(video_id, video_path)
        return video_id, None, len(info["keys"]), round(time.time() - t0, 2)
    except Exception as e:
        return video_id, f"{type(e).__name__}: {str(e)[:200]}", 0, round(time.time() - t0, 2)


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--shard", default=None, help="i/k (default: Slurm array env or 0/1)")
    ap.add_argument("--workers", type=int, default=max(1, int(os.environ.get("SLURM_CPUS_PER_TASK", 16)) // 2))
    ap.add_argument("--limit", type=int, default=None)
    ap.add_argument("--video-ids", default=None, help="file with one video_id per line (smoke tests)")
    ap.add_argument("--all-videos", action="store_true", help="every normalized video of the base items")
    ap.add_argument("--stats", action="store_true")
    a = ap.parse_args()
    pc.ensure_dirs()
    vids = pool_videos(a.all_videos)
    if a.video_ids:
        want = {l.strip() for l in open(a.video_ids) if l.strip()}
        vids = [v for v in vids if v[0] in want]
    cached = [v for v in vids if load_frames_json(v[0]) is not None]
    if a.stats:
        print(f"pool videos with a normalized file: {len(vids)}; frames cached: {len(cached)}; "
              f"missing: {len(vids) - len(cached)}")
        return
    if a.shard:
        tid, n = (int(x) for x in a.shard.split("/"))
    else:
        tid, n = pc.slurm_task()
    todo = [v for v in vids if load_frames_json(v[0]) is None and shard_of(v[0], n) == tid]
    if a.limit:
        todo = todo[:a.limit]
    log(f"frames shard {tid}/{n}: {len(todo)} video(s) to decode of {len(vids)} "
        f"({len(cached)} already cached); workers={a.workers}", "frames")
    if not todo:
        return
    t0 = time.time()
    n_ok = n_err = n_frames = 0
    errs = []
    with ProcessPoolExecutor(max_workers=a.workers) as ex:
        futs = [ex.submit(work_one, v, p) for v, p in todo]
        for i, f in enumerate(as_completed(futs), 1):
            vid, err, nf, dt = f.result()
            if err:
                n_err += 1
                errs.append(dict(video_id=vid, error=err))
            else:
                n_ok += 1
                n_frames += nf
            if i % 200 == 0 or i == len(todo):
                el = time.time() - t0
                log(f"{i}/{len(todo)} ok={n_ok} err={n_err} {i / el:.2f} videos/s", "frames")
    el = time.time() - t0
    if errs:
        with open(os.path.join(pc.LOG_DIR, "pool_frames_errors.jsonl"), "a") as f:
            for e in errs:
                f.write(json.dumps(dict(ts=time.strftime("%F %T"), **e)) + "\n")
    with open(os.path.join(pc.LOG_DIR, "pool_timing.jsonl"), "a") as f:
        f.write(json.dumps(dict(ts=time.strftime("%F %T"), stage="frames", shard=f"{tid}/{n}", n_videos=len(todo),
                                n_ok=n_ok, n_err=n_err, n_frames=n_frames, wall_s=round(el, 1),
                                videos_per_s=round(len(todo) / max(el, 1e-9), 3), workers=a.workers)) + "\n")
    log(f"done: ok={n_ok} err={n_err} frames={n_frames} in {el / 60:.1f} min "
        f"({len(todo) / max(el, 1e-9):.2f} videos/s)", "frames")


if __name__ == "__main__":
    main()