EgoExoLearn-processed / restructure /16_build_segment_same.py
KienNguyen1233's picture
Upload processed EgoExoLearn (resume) (part 11)
07b266f verified
Raw History Blame Contribute Delete
5.09 kB
#!/usr/bin/env python
"""Build clean_data/segment_same/ : one clip per valid ego action segment.
The same-segment task cuts *inside* a single action: the prefix is the first
part of action k, the target is the rest of it. So each clip here is exactly
one annotated ego segment, start to end, with no padding -- t=0 is the action
start and t=duration is the action end. A loader can therefore pick any cut
point inside the clip without consulting the index.
clean_data/segment_same/
ego/<annotation_id>.mp4 the action segment at native resolution, crf 18
clean_data/label_same.csv video, prompt (video is relative to clean_data/,
the same convention as label_cross.csv)
"Valid" means all of:
view == ego
target_ok source short side >= 480 (we train at 832x480, so a
smaller source would be upscaled)
not overruns_video annotation end is inside the file
duration >= 2.31s 21-frame prefix (1.31s @16fps) + >= 1.0s of target
narration_en non-empty
Filenames are the annotation_id, so every row joins straight back to
index/segments.parquet for hands, verbs, nouns, dish, scene, overlap flags.
python 16_build_segment_same.py
"""
import argparse
import subprocess
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pandas as pd
DATA = Path(__file__).resolve().parent.parent
SRC = DATA / "videos"
MIN_DUR = 2.31 # 21-frame prefix @16fps + >= 1.0s target
def probe_dur(p):
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "csv=p=0", str(p)], capture_output=True, text=True)
try:
return float(r.stdout.strip())
except ValueError:
return 0.0
def cut(job):
uid, t0, dur, dst, threads = job
if dst.exists() and abs(probe_dur(dst) - dur) < 0.5:
return True # already complete
r = subprocess.run(
["ffmpeg", "-nostdin", "-v", "error", "-y", "-ss", f"{t0:.3f}",
"-i", str(SRC / f"{uid}.mp4"), "-t", f"{dur:.3f}",
"-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "18",
"-pix_fmt", "yuv420p", "-threads", str(threads), str(dst)],
capture_output=True)
return r.returncode == 0 and dst.exists() and dst.stat().st_size > 0
def select(seg):
e = seg[seg.view == "ego"]
return e[(e.duration >= MIN_DUR) & e.target_ok & ~e.overruns_video
& (e.narration_en.fillna("").str.strip().str.len() > 0)].copy()
def main():
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("-o", "--out", type=Path, default=DATA / "clean_data/segment_same")
p.add_argument("--workers", type=int, default=16)
p.add_argument("--threads", type=int, default=2, help="x264 threads per worker")
p.add_argument("--limit", type=int, default=0, help="debug: only N clips")
a = p.parse_args()
d = select(pd.read_parquet(DATA / "index/segments.parquet"))
if a.limit:
d = d.head(a.limit)
print(f"{len(d):,} valid ego action segments | {d.video_uid.nunique()} videos "
f"| {d.duration.sum()/3600:.1f} h | scene {dict(d.scene.value_counts())}")
assert d.annotation_id.is_unique, "annotation_id collision"
(a.out / "ego").mkdir(parents=True, exist_ok=True)
jobs = [(r.video_uid, r.start_sec, r.duration,
a.out / "ego" / f"{r.annotation_id}.mp4", a.threads) for r in d.itertuples()]
print(f"cutting {len(jobs):,} clips ({a.workers} workers x {a.threads} threads) ...",
flush=True)
t0, done, ok = time.time(), 0, []
with ThreadPoolExecutor(a.workers) as ex:
for res in ex.map(cut, jobs):
ok.append(res)
done += 1
if done % 500 == 0:
el = time.time() - t0
print(f" {done:>6,}/{len(jobs):,} {el/60:6.1f} min elapsed, "
f"eta {el/done*(len(jobs)-done)/60:6.1f} min, "
f"{sum(ok)} ok / {done-sum(ok)} failed", flush=True)
print(f" {sum(ok):,} ok, {len(ok)-sum(ok):,} failed "
f"({(time.time()-t0)/60:.1f} min)")
d["ok"] = ok
bad = d[~d.ok]
if len(bad):
bad[["annotation_id", "video_uid", "start_sec", "duration"]].to_csv(
a.out / "failed.csv", index=False)
print(f" [warn] {len(bad)} failures -> {a.out/'failed.csv'}")
g = d[d.ok]
# paths are relative to clean_data/, matching label_cross.csv, so both
# loaders take the same root
lab = pd.DataFrame({"video": f"{a.out.name}/ego/" + g.annotation_id + ".mp4",
"prompt": g.narration_en.str.strip()})
out_csv = a.out.parent / "label_same.csv"
lab.to_csv(out_csv, index=False)
gb = sum(f.stat().st_size for f in (a.out / "ego").glob("*.mp4")) / 2**30
print(f"\n[write] {len(lab):,} rows -> {out_csv} ({gb:.1f} GB of clips)")
if __name__ == "__main__":
main()