Download supplement_20260910/code/exp/analysis/pool/frames_decode.py from GMLRVigil/BenchCheck-Pool-Frames: direct link, hf CLI and curl.
- Browser
- Download file 9.34 kB
-
https://huggingface.co/datasets/GMLRVigil/BenchCheck-Pool-Frames/resolve/main/supplement_20260910/code/exp/analysis/pool/frames_decode.py
- Command line
-
hf download hf://datasets/GMLRVigil/BenchCheck-Pool-Frames/supplement_20260910/code/exp/analysis/pool/frames_decode.py
-
curl -L -o frames_decode.py https://huggingface.co/datasets/GMLRVigil/BenchCheck-Pool-Frames/resolve/main/supplement_20260910/code/exp/analysis/pool/frames_decode.py
9.34 kB
| #!/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() | |