#!/usr/bin/env python """Write clean_data/label_same.csv for the segment_same clips that are complete. 16_build_segment_same.py can be stopped part way through, which leaves the clip it was encoding truncated. This probes every clip on disk, keeps only the ones whose length matches the annotation, and deletes the rest so a later re-run of 16 re-cuts them cleanly. Outputs clean_data/label_same.csv video, prompt <- the two-column label clean_data/segment_same/meta.csv annotation_id, video_uid, scene, start_sec, end_sec, duration, split <- what the loader joins for split/scene Splits are assigned per ego video, not per clip, and any video already placed by label_cross.csv keeps that placement -- otherwise the same ego video could land in cross-train and same-val, leaking between the two tasks. python 17_finalize_segment_same.py """ import argparse import hashlib import subprocess from concurrent.futures import ThreadPoolExecutor from pathlib import Path import pandas as pd DATA = Path(__file__).resolve().parent.parent TOL = 0.15 # s; a complete clip matches the annotation to well under this RATIO = (0.70, 0.15) # train, val; rest test 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 -1.0 def assign_split(uid, known): """Deterministic, stable under re-runs, and consistent with label_cross.""" if uid in known: return known[uid] h = int(hashlib.md5(uid.encode()).hexdigest()[:8], 16) / 0xFFFFFFFF return "train" if h < RATIO[0] else "val" if h < sum(RATIO) else "test" def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--clean", type=Path, default=DATA / "clean_data") p.add_argument("--workers", type=int, default=16) p.add_argument("--keep-truncated", action="store_true") a = p.parse_args() ego_dir = a.clean / "segment_same" / "ego" seg = pd.read_parquet(DATA / "index/segments.parquet").set_index("annotation_id") on_disk = sorted(f.stem for f in ego_dir.glob("*.mp4")) print(f"{len(on_disk):,} clips on disk") d = seg.loc[on_disk].reset_index() with ThreadPoolExecutor(a.workers) as ex: d["real_sec"] = list(ex.map(probe_dur, [ego_dir / f"{i}.mp4" for i in d.annotation_id])) d["complete"] = (d.real_sec - d.duration).abs() < TOL bad = d[~d.complete] print(f" complete {int(d.complete.sum()):,} truncated/unreadable {len(bad):,}") for r in bad.itertuples(): print(f" {r.annotation_id}: {r.real_sec:.2f}s vs {r.duration:.2f}s expected") if not a.keep_truncated: (ego_dir / f"{r.annotation_id}.mp4").unlink(missing_ok=True) d = d[d.complete].copy() # splits: inherit from label_cross where the ego video is already placed known = {} lc = a.clean / "label_cross.csv" if lc.exists(): c = pd.read_csv(lc) known = dict(zip(c.ego_video_uid, c.split)) print(f" inheriting split for {len(known)} ego videos from label_cross.csv") vids = sorted(d.video_uid.unique()) smap = {v: assign_split(v, known) for v in vids} d["split"] = d.video_uid.map(smap) lab = pd.DataFrame({"video": "segment_same/ego/" + d.annotation_id + ".mp4", "prompt": d.narration_en.str.strip()}) lab.to_csv(a.clean / "label_same.csv", index=False) meta = d[["annotation_id", "video_uid", "scene", "start_sec", "end_sec", "duration", "split"]].copy() meta.to_csv(a.clean / "segment_same" / "meta.csv", index=False) gb = sum(f.stat().st_size for f in ego_dir.glob("*.mp4")) / 2**30 print(f"\n[write] {len(lab):,} rows -> {a.clean/'label_same.csv'} ({gb:.1f} GB)") print(f"[write] {len(meta):,} rows -> {a.clean/'segment_same'/'meta.csv'}") print(f" videos {d.video_uid.nunique()} scene {dict(d.scene.value_counts())}") print(f" split {dict(meta.split.value_counts())}") print(f" duration median {d.duration.median():.2f}s total {d.duration.sum()/3600:.1f} h") if __name__ == "__main__": main()