ego4d-hand-mano / extract_clips.py
bochen123's picture
Add remaining annotation shards, clip index, extractor and dataset card
9f52b0a verified
Raw History Blame Contribute Delete
7.36 kB
#!/usr/bin/env python3
"""Rebuild the clips of this dataset from your own copy of the Ego4D `video_540ss` videos.
Each clip is exactly frames [start_frame, start_frame + 120] (121 frames, 0-based, decode
order) of <ego4d_dir>/<video_uid>.mp4 -- no spatial crop, no resize, no frame resampling.
python3 extract_clips.py --clips metadata/clips.parquet \
--ego4d-dir /path/to/ego4d/v2/video_540ss --out ./clips --workers 32
Needs: python3, pyarrow, and an `ffmpeg` on PATH (any build; `--ffmpeg` to point elsewhere).
Re-runnable: existing outputs are skipped, so an interrupted run just continues.
"""
import os, sys, csv, json, time, hashlib, argparse, subprocess, collections
from concurrent.futures import ProcessPoolExecutor, as_completed
FRAMES = 121
def read_clips(path):
if path.endswith(".parquet"):
import pyarrow.parquet as pq
t = pq.read_table(path)
cols = [c for c in ("clip_id", "video_uid", "start_frame", "fps", "frame_sha256")
if c in t.column_names]
return t.select(cols).to_pylist()
with open(path) as fh:
if path.endswith(".jsonl"):
return [json.loads(l) for l in fh if l.strip()]
return list(csv.DictReader(fh))
def decode_luma(ffmpeg, src, start, fps, frames=FRAMES):
"""Frame-accurate: input seeking decodes to the exact timestamp, verified bit-identical
to decoding the whole file and selecting by frame number."""
cmd = [ffmpeg, "-v", "error", "-ss", "%.6f" % (start / fps), "-i", src,
"-frames:v", str(frames), "-fps_mode", "passthrough",
"-f", "rawvideo", "-pix_fmt", "gray", "-"]
return subprocess.run(cmd, capture_output=True, check=True).stdout
def one(job):
(a, rows, src) = job
out_dir = os.path.join(a.out, rows[0]["video_uid"])
os.makedirs(out_dir, exist_ok=True)
res = {"video_uid": rows[0]["video_uid"], "ok": 0, "skipped": 0, "failed": [],
"hash_ok": 0, "hash_bad": []}
for r in rows:
cid, start = r["clip_id"], int(r["start_frame"])
fps = float(r.get("fps") or 30.0)
dst = os.path.join(out_dir, cid + (".mp4" if a.format == "mp4" else ""))
if a.format == "mp4" and os.path.exists(dst) and not a.verify:
res["skipped"] += 1
continue
try:
if a.verify:
got = hashlib.sha256(decode_luma(a.ffmpeg, src, start, fps)).hexdigest()
want = r.get("frame_sha256")
if want and got != want:
res["hash_bad"].append(cid)
else:
res["hash_ok"] += 1
if a.format == "mp4" and os.path.exists(dst):
res["skipped"] += 1
continue
if a.format == "mp4":
cmd = [a.ffmpeg, "-v", "error", "-y", "-ss", "%.6f" % (start / fps), "-i", src,
"-frames:v", str(FRAMES), "-fps_mode", "passthrough",
"-c:v", "libx264", "-crf", str(a.crf), "-preset", a.preset,
"-pix_fmt", "yuv420p", "-an", "-movflags", "+faststart",
"-f", "mp4", dst + ".tmp"]
else:
os.makedirs(dst, exist_ok=True)
cmd = [a.ffmpeg, "-v", "error", "-y", "-ss", "%.6f" % (start / fps), "-i", src,
"-frames:v", str(FRAMES), "-fps_mode", "passthrough",
os.path.join(dst, "%03d.jpg")]
subprocess.run(cmd, check=True, capture_output=True)
if a.format == "mp4":
os.replace(dst + ".tmp", dst)
res["ok"] += 1
except subprocess.CalledProcessError as e:
res["failed"].append([cid, e.stderr.decode()[:120]])
return res
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--clips", required=True, help="metadata/clips.parquet (or .csv/.jsonl)")
ap.add_argument("--ego4d-dir", required=True, help="directory of <video_uid>.mp4 (video_540ss)")
ap.add_argument("--out", default="./clips")
ap.add_argument("--format", choices=["mp4", "frames"], default="mp4")
ap.add_argument("--crf", default="23")
ap.add_argument("--preset", default="medium")
ap.add_argument("--workers", type=int, default=os.cpu_count() or 8)
ap.add_argument("--ffmpeg", default="ffmpeg")
ap.add_argument("--split", default=None, help="only this split, if the table has a split column")
ap.add_argument("--videos", default=None, help="file with video_uids to restrict to")
ap.add_argument("--limit-videos", type=int, default=0)
ap.add_argument("--verify", action="store_true",
help="also check the decoded frames against frame_sha256 in the table")
a = ap.parse_args()
rows = read_clips(a.clips)
if a.split:
rows = [r for r in rows if r.get("split") == a.split]
if a.videos:
keep = {l.strip() for l in open(a.videos) if l.strip()}
rows = [r for r in rows if r["video_uid"] in keep]
by_vid = collections.defaultdict(list)
for r in rows:
by_vid[r["video_uid"]].append(r)
vids = sorted(by_vid)
if a.limit_videos:
vids = vids[:a.limit_videos]
jobs, missing = [], []
for v in vids:
src = os.path.join(a.ego4d_dir, v + ".mp4")
if not os.path.exists(src):
missing.append(v)
continue
jobs.append((a, sorted(by_vid[v], key=lambda r: int(r["start_frame"])), src))
print("%d clips over %d source videos; %d source videos not found"
% (sum(len(j[1]) for j in jobs), len(jobs), len(missing)), flush=True)
if missing:
with open(os.path.join(a.out or ".", "missing_videos.txt"), "w") as fh:
fh.write("\n".join(missing) + "\n")
print(" -> missing video_uids written to missing_videos.txt", flush=True)
os.makedirs(a.out, exist_ok=True)
tot = collections.Counter()
bad, failed = [], []
t0 = time.time()
with ProcessPoolExecutor(a.workers) as ex:
futs = [ex.submit(one, j) for j in jobs]
for i, f in enumerate(as_completed(futs), 1):
r = f.result()
for k in ("ok", "skipped", "hash_ok"):
tot[k] += r[k]
bad += r["hash_bad"]; failed += r["failed"]
if i % 25 == 0 or i == len(futs):
el = time.time() - t0
print(" %d/%d videos | %d extracted, %d skipped, %d failed | %.0f clips/s"
% (i, len(futs), tot["ok"], tot["skipped"], len(failed),
(tot["ok"] + tot["skipped"]) / max(el, 1e-9)), flush=True)
print("done: %d extracted, %d skipped, %d failed in %.0fs"
% (tot["ok"], tot["skipped"], len(failed), time.time() - t0))
if a.verify:
print("frame-hash: %d verified, %d MISMATCHED" % (tot["hash_ok"], len(bad)))
if bad:
print(" first mismatches:", bad[:5])
print(" a mismatch means your source video differs from the one the dataset was "
"built from (wrong Ego4D version/variant), not that your ffmpeg is wrong")
if failed:
json.dump(failed, open(os.path.join(a.out, "failures.json"), "w"), indent=1)
print(" failures written to failures.json")
sys.exit(1 if (failed or bad) else 0)
if __name__ == "__main__":
main()