| |
| """Download 360+x panoramic mp4s one-by-one, cut into 15fps/100-frame clips, |
| keep only clips overlapping a 'dynamic' action, delete the rest + the source mp4. |
| |
| Usage: |
| python3 extract_dynamic_clips.py --only <uuid> --max-clips 2 --keep-src # test one |
| python3 extract_dynamic_clips.py # full run (resume-safe) |
| """ |
| import argparse, json, os, subprocess, sys, glob, shutil, traceback |
|
|
| BASE = os.path.dirname(os.path.abspath(__file__)) |
| TAL_DIR = os.path.join(BASE, "TAL_annotations") |
| INDEX = os.path.join(BASE, "index.json") |
| OUT_DIR = os.path.join(BASE, "dynamic_clips") |
| DL_DIR = os.path.join(BASE, "_dl_tmp") |
| DONE_FILE = os.path.join(OUT_DIR, "_done.txt") |
| REPO = "quchenyuan/360x_dataset_HR" |
|
|
| FPS = 15 |
| CLIP_FRAMES = 100 |
| CLIP_SEC = CLIP_FRAMES / FPS |
|
|
| DYNAMIC = { |
| "walking", "running", "dancing", "workout", "driving", "pushing", "clapping", |
| "firework", "moving things", "pouring", "farming", "cleaning", "housekeeping", |
| "playing", "playing instrument", "dressing", "cooking", "preparing food", |
| "opening", "hygiene practices", "eating", "drinking", |
| } |
|
|
|
|
| def log(*a): |
| print(*a, flush=True) |
|
|
|
|
| def dynamic_segments(uuid): |
| """Return list of (start_sec, end_sec, action) for dynamic actions in this uuid.""" |
| f = os.path.join(TAL_DIR, uuid + ".json") |
| if not os.path.exists(f): |
| return [] |
| d = json.load(open(f)) |
| segs = [] |
| for v in d.get("metadata", {}).values(): |
| dur = v.get("duration") |
| if not dur or len(dur) != 2: |
| continue |
| acts = [a for a in v.get("action", {}).values() if a in DYNAMIC] |
| if acts: |
| segs.append((float(dur[0]), float(dur[1]), acts[0])) |
| return segs |
|
|
|
|
| def ffprobe_duration(path): |
| out = subprocess.check_output([ |
| "ffprobe", "-v", "error", "-select_streams", "v:0", |
| "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path, |
| ]).decode().strip() |
| return float(out) |
|
|
|
|
| def planned_clips(duration, segs): |
| """Yield (clip_idx, start_sec, end_sec, matched_actions) for clips kept.""" |
| n_full = int(duration * FPS) // CLIP_FRAMES |
| for i in range(n_full): |
| cs = i * CLIP_SEC |
| ce = (i + 1) * CLIP_SEC |
| matched = sorted({a for (as_, ae, a) in segs if cs < ae and as_ < ce}) |
| if matched: |
| yield i, cs, ce, matched |
|
|
|
|
| def extract_clip(src, cs, out_path): |
| cmd = [ |
| "ffmpeg", "-nostdin", "-y", "-v", "error", |
| "-ss", f"{cs:.5f}", "-i", src, |
| "-vf", f"fps={FPS}", "-frames:v", str(CLIP_FRAMES), |
| "-an", "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", |
| out_path, |
| ] |
| subprocess.run(cmd, check=True) |
|
|
|
|
| def download(uuid): |
| from huggingface_hub import hf_hub_download |
| return hf_hub_download( |
| repo_id=REPO, repo_type="dataset", |
| filename=f"panoramic/{uuid}.mp4", local_dir=DL_DIR, |
| ) |
|
|
|
|
| def process(uuid, max_clips=None, keep_src=False): |
| segs = dynamic_segments(uuid) |
| if not segs: |
| log(f"[{uuid}] no dynamic segments -> skip (no download)") |
| return {"uuid": uuid, "clips": 0, "skipped": "no_dynamic"} |
| log(f"[{uuid}] {len(segs)} dynamic segments; downloading...") |
| src = download(uuid) |
| try: |
| dur = ffprobe_duration(src) |
| plan = list(planned_clips(dur, segs)) |
| if max_clips: |
| plan = plan[:max_clips] |
| outdir = os.path.join(OUT_DIR, uuid) |
| os.makedirs(outdir, exist_ok=True) |
| manifest = {"uuid": uuid, "duration": dur, "fps": FPS, |
| "clip_frames": CLIP_FRAMES, "clips": []} |
| log(f"[{uuid}] dur={dur:.1f}s -> {len(plan)} dynamic clips") |
| for idx, cs, ce, acts in plan: |
| out = os.path.join(outdir, f"clip_{idx:04d}.mp4") |
| extract_clip(src, cs, out) |
| manifest["clips"].append({ |
| "idx": idx, "start": round(cs, 3), "end": round(ce, 3), |
| "actions": acts, "file": os.path.basename(out), |
| }) |
| json.dump(manifest, open(os.path.join(outdir, "manifest.json"), "w"), |
| ensure_ascii=False, indent=1) |
| return {"uuid": uuid, "clips": len(manifest["clips"])} |
| finally: |
| if not keep_src: |
| try: |
| os.remove(src) |
| except OSError: |
| pass |
| |
| for p in glob.glob(os.path.join(DL_DIR, ".cache", "huggingface", "**"), |
| recursive=True): |
| pass |
| shutil.rmtree(os.path.join(DL_DIR, "panoramic"), ignore_errors=True) |
|
|
|
|
| def load_done(): |
| if os.path.exists(DONE_FILE): |
| return set(open(DONE_FILE).read().split()) |
| return set() |
|
|
|
|
| def mark_done(uuid): |
| with open(DONE_FILE, "a") as f: |
| f.write(uuid + "\n") |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--only", help="process a single uuid") |
| ap.add_argument("--max-clips", type=int, default=None) |
| ap.add_argument("--keep-src", action="store_true") |
| args = ap.parse_args() |
|
|
| os.makedirs(OUT_DIR, exist_ok=True) |
| os.makedirs(DL_DIR, exist_ok=True) |
|
|
| if args.only: |
| uuids = [args.only] |
| else: |
| uuids = [e["uuid"] for e in json.load(open(INDEX))] |
|
|
| done = load_done() |
| total = len(uuids) |
| for n, uuid in enumerate(uuids, 1): |
| if uuid in done and not args.only: |
| continue |
| log(f"=== ({n}/{total}) {uuid} ===") |
| try: |
| r = process(uuid, max_clips=args.max_clips, keep_src=args.keep_src) |
| if not args.only: |
| mark_done(uuid) |
| log(f" done: {r}") |
| except Exception: |
| log(f" ERROR on {uuid}:\n{traceback.format_exc()}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|