Enxin commited on
Commit
c150001
·
verified ·
1 Parent(s): 7aafcd8

Upload code/exp/analysis/pool/frames_decode.py with huggingface_hub

Browse files
code/exp/analysis/pool/frames_decode.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """frames_decode.py — frame cache for steps 2 and 3.
3
+
4
+ Cache location: bench_exp/work/pool_frames/<video_id>/frame_<k>.jpg + frames.json
5
+ (video_id = content_hash). Decision (2026-09-06): the cluster runs
6
+ job_container/tmpfs (per-job private /tmp, destroyed at job end) and the MIG node
7
+ reports TmpDisk=0, so node-local storage cannot be shared between the CPU decode array
8
+ and the GPU array. /vast is the shared NVMe-backed (VAST) filesystem every node mounts;
9
+ it is the only cache that the decode array and all GPU tasks can read and write, and
10
+ it survives job boundaries for incremental re-runs. GPU tasks decode any video still
11
+ missing from the cache on the fly (same function) so steps 2-3 never block on the array.
12
+
13
+ Frames = the stage_p1_runner v_32 grid: 32 time-uniform targets over meta
14
+ frame_timestamps, nearest frame index each, duplicates (short videos) collapsed to the
15
+ first grid position. frame_<k>.jpg is named by grid position k (0..31); frames.json
16
+ lists the positions that exist (`keys`), the single-frame position `mid_k` (grid
17
+ position 16 = v_1), and the frame size after resizing to a 448 px long side (never
18
+ upscaled), JPEG q85.
19
+
20
+ frames_decode.py [--shard i/k] [--workers 8] [--limit N] [--video-ids FILE]
21
+ [--all-videos] (default: videos of items still in the pool)
22
+ frames_decode.py --stats
23
+ """
24
+ import argparse
25
+ import hashlib
26
+ import io
27
+ import json
28
+ import os
29
+ import shutil
30
+ import sys
31
+ import time
32
+ from concurrent.futures import ProcessPoolExecutor, as_completed
33
+
34
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
35
+ import pool_common as pc # noqa: E402
36
+ from pool_common import log # noqa: E402
37
+
38
+
39
+ def frames_json_path(video_id):
40
+ return os.path.join(pc.FRAMES_DIR, video_id, "frames.json")
41
+
42
+
43
+ def load_frames_json(video_id):
44
+ p = frames_json_path(video_id)
45
+ if not os.path.exists(p):
46
+ return None
47
+ try:
48
+ d = json.load(open(p))
49
+ return d if d.get("ok") else None
50
+ except Exception:
51
+ return None
52
+
53
+
54
+ def grid_positions(meta):
55
+ """-> (grid of 32 frame indices, ordered unique positions k, mid_k)."""
56
+ from stage_p1_runner import _nearest_indices, _uniform_times
57
+ n = int(meta["n_frames"])
58
+ ts = meta.get("frame_timestamps") or []
59
+ if len(ts) != n or n == 0:
60
+ ts = list(range(max(n, 1)))
61
+ grid = _nearest_indices(ts, _uniform_times(ts[0], ts[-1], pc.N_FRAMES_V32))
62
+ first = {}
63
+ keys = []
64
+ for k, idx in enumerate(grid):
65
+ if idx not in first:
66
+ first[idx] = k
67
+ keys.append(k)
68
+ mid_k = first[grid[pc.MID_POS]]
69
+ return grid, keys, mid_k
70
+
71
+
72
+ def ensure_frames(video_id, video_path, meta=None, long_side=pc.FRAME_LONG_SIDE):
73
+ """Decode + cache if missing; returns the frames.json dict (or raises)."""
74
+ d = load_frames_json(video_id)
75
+ if d is not None:
76
+ return d
77
+ from PIL import Image
78
+ from extract_frames import _decode
79
+ if meta is None:
80
+ meta = pc.meta_of(video_id)
81
+ if not meta:
82
+ raise RuntimeError("meta.json missing")
83
+ grid, keys, mid_k = grid_positions(meta)
84
+ idxs = [grid[k] for k in keys]
85
+ decoded = _decode(video_path, idxs) # {idx: PIL}
86
+ avail = max(decoded)
87
+ out_dir = os.path.join(pc.FRAMES_DIR, video_id)
88
+ tmp_dir = f"{out_dir}.tmp{os.getpid()}"
89
+ os.makedirs(tmp_dir, exist_ok=True)
90
+ w = h = None
91
+ for k, idx in zip(keys, idxs):
92
+ im = decoded[min(idx, avail)].convert("RGB")
93
+ W, H = im.size
94
+ s = long_side / max(W, H)
95
+ if s < 1.0:
96
+ im = im.resize((max(1, round(W * s)), max(1, round(H * s))), Image.LANCZOS)
97
+ w, h = im.size
98
+ im.save(os.path.join(tmp_dir, f"frame_{k}.jpg"), format="JPEG", quality=pc.JPEG_QUALITY)
99
+ info = dict(video_id=video_id, n_frames_video=int(meta.get("n_frames", 0)), grid=grid, keys=keys,
100
+ mid_k=mid_k, w=w, h=h, long_side=long_side, jpeg_quality=pc.JPEG_QUALITY,
101
+ too_short=bool(meta.get("too_short")), ok=True, ts=time.strftime("%F %T"))
102
+ json.dump(info, open(os.path.join(tmp_dir, "frames.json"), "w"))
103
+ try:
104
+ os.rename(tmp_dir, out_dir)
105
+ except OSError:
106
+ # another worker finished first: keep theirs
107
+ shutil.rmtree(tmp_dir, ignore_errors=True)
108
+ d = load_frames_json(video_id)
109
+ if d is None:
110
+ raise
111
+ return d
112
+ return info
113
+
114
+
115
+ def frame_bytes(video_id, k):
116
+ with open(os.path.join(pc.FRAMES_DIR, video_id, f"frame_{k}.jpg"), "rb") as f:
117
+ return f.read()
118
+
119
+
120
+ # ------------------------------------------------------------------ selection
121
+ def pool_videos(all_videos=False):
122
+ """(video_id, video_path) of videos whose items are still in the pool: base items
123
+ that are mcq, kept by step 0 (if run) and not removed by step 1 (if run)."""
124
+ import pyarrow.parquet as pq
125
+ df = pq.read_table(pc.BASE_PARQUET, columns=["benchmark", "item_id", "video_key", "video_id",
126
+ "video_path", "format"]).to_pandas()
127
+ hashes = pc.manifest_hashes()
128
+ pend = df["video_id"].str.startswith("k:")
129
+ new = df.loc[pend, "video_key"].map(hashes)
130
+ got = new.notna()
131
+ df.loc[new[got].index, "video_id"] = new[got].values
132
+ df.loc[new[got].index, "video_path"] = [pc.normalized_path(x) for x in new[got].values]
133
+ df = df[df["video_path"].notna()]
134
+ if not all_videos:
135
+ df = df[df["format"] == "mcq"]
136
+ if os.path.exists(pc.STEP0_KEPT):
137
+ kept = pq.read_table(pc.STEP0_KEPT, columns=["item_id", "kept"]).to_pandas()
138
+ keep_ids = set(kept.loc[kept["kept"], "item_id"])
139
+ df = df[df["item_id"].isin(keep_ids)]
140
+ ok1, _ = pc.load_step_rows(1)
141
+ if ok1:
142
+ removed = {i for i, r in ok1.items() if r.get("remove")}
143
+ df = df[~df["item_id"].isin(removed)]
144
+ vids = df.drop_duplicates("video_id")[["video_id", "video_path"]]
145
+ return list(vids.itertuples(index=False, name=None))
146
+
147
+
148
+ def shard_of(video_id, n):
149
+ return int(hashlib.sha1(video_id.encode()).hexdigest()[:8], 16) % n
150
+
151
+
152
+ def work_one(video_id, video_path):
153
+ t0 = time.time()
154
+ try:
155
+ info = ensure_frames(video_id, video_path)
156
+ return video_id, None, len(info["keys"]), round(time.time() - t0, 2)
157
+ except Exception as e:
158
+ return video_id, f"{type(e).__name__}: {str(e)[:200]}", 0, round(time.time() - t0, 2)
159
+
160
+
161
+ def main():
162
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
163
+ ap.add_argument("--shard", default=None, help="i/k (default: Slurm array env or 0/1)")
164
+ ap.add_argument("--workers", type=int, default=max(1, int(os.environ.get("SLURM_CPUS_PER_TASK", 16)) // 2))
165
+ ap.add_argument("--limit", type=int, default=None)
166
+ ap.add_argument("--video-ids", default=None, help="file with one video_id per line (smoke tests)")
167
+ ap.add_argument("--all-videos", action="store_true", help="every normalized video of the base items")
168
+ ap.add_argument("--stats", action="store_true")
169
+ a = ap.parse_args()
170
+ pc.ensure_dirs()
171
+ vids = pool_videos(a.all_videos)
172
+ if a.video_ids:
173
+ want = {l.strip() for l in open(a.video_ids) if l.strip()}
174
+ vids = [v for v in vids if v[0] in want]
175
+ cached = [v for v in vids if load_frames_json(v[0]) is not None]
176
+ if a.stats:
177
+ print(f"pool videos with a normalized file: {len(vids)}; frames cached: {len(cached)}; "
178
+ f"missing: {len(vids) - len(cached)}")
179
+ return
180
+ if a.shard:
181
+ tid, n = (int(x) for x in a.shard.split("/"))
182
+ else:
183
+ tid, n = pc.slurm_task()
184
+ todo = [v for v in vids if load_frames_json(v[0]) is None and shard_of(v[0], n) == tid]
185
+ if a.limit:
186
+ todo = todo[:a.limit]
187
+ log(f"frames shard {tid}/{n}: {len(todo)} video(s) to decode of {len(vids)} "
188
+ f"({len(cached)} already cached); workers={a.workers}", "frames")
189
+ if not todo:
190
+ return
191
+ t0 = time.time()
192
+ n_ok = n_err = n_frames = 0
193
+ errs = []
194
+ with ProcessPoolExecutor(max_workers=a.workers) as ex:
195
+ futs = [ex.submit(work_one, v, p) for v, p in todo]
196
+ for i, f in enumerate(as_completed(futs), 1):
197
+ vid, err, nf, dt = f.result()
198
+ if err:
199
+ n_err += 1
200
+ errs.append(dict(video_id=vid, error=err))
201
+ else:
202
+ n_ok += 1
203
+ n_frames += nf
204
+ if i % 200 == 0 or i == len(todo):
205
+ el = time.time() - t0
206
+ log(f"{i}/{len(todo)} ok={n_ok} err={n_err} {i / el:.2f} videos/s", "frames")
207
+ el = time.time() - t0
208
+ if errs:
209
+ with open(os.path.join(pc.LOG_DIR, "pool_frames_errors.jsonl"), "a") as f:
210
+ for e in errs:
211
+ f.write(json.dumps(dict(ts=time.strftime("%F %T"), **e)) + "\n")
212
+ with open(os.path.join(pc.LOG_DIR, "pool_timing.jsonl"), "a") as f:
213
+ f.write(json.dumps(dict(ts=time.strftime("%F %T"), stage="frames", shard=f"{tid}/{n}", n_videos=len(todo),
214
+ n_ok=n_ok, n_err=n_err, n_frames=n_frames, wall_s=round(el, 1),
215
+ videos_per_s=round(len(todo) / max(el, 1e-9), 3), workers=a.workers)) + "\n")
216
+ log(f"done: ok={n_ok} err={n_err} frames={n_frames} in {el / 60:.1f} min "
217
+ f"({len(todo) / max(el, 1e-9):.2f} videos/s)", "frames")
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()