Download scripts/prepare_spatialvid_csv.py from zzhang2816/new_share_long_live_100: direct link, hf CLI and curl.
- Browser
- Download file 9.43 kB
-
https://huggingface.co/datasets/zzhang2816/new_share_long_live_100/resolve/main/scripts/prepare_spatialvid_csv.py
- Command line
-
hf download hf://datasets/zzhang2816/new_share_long_live_100/scripts/prepare_spatialvid_csv.py
-
curl -L -o prepare_spatialvid_csv.py https://huggingface.co/datasets/zzhang2816/new_share_long_live_100/resolve/main/scripts/prepare_spatialvid_csv.py
9.43 kB
| #!/usr/bin/env python3 | |
| """Build a LiveWorld four-field CSV from SpatialVID_preped. | |
| SpatialVID / LongLive i2v assets: | |
| - sampled_clippath.csv -> prompt + clipPath | |
| - <video_root>/<clipPath> -> first-frame image | |
| - clip_annotation/<stem>/longlive/scene_projection_input.mp4 (81 frames) | |
| - clip_annotation/<stem>/longlive/fg_projection_input.mp4 (81 frames) | |
| LiveWorld ``condition_source=mp4`` with ``num_frames=81`` indexes projection | |
| videos at global indices ``1..81`` (first_frame is separate at index 0). | |
| So an 81-frame LongLive control must be padded to 82 frames: | |
| lw_proj = [pad_frame] + longlive_proj[0..80] | |
| then LiveWorld targets ``1..81`` consume the original 81 LongLive frames. | |
| Pad policy: | |
| - bg: first frame of the source clip (same as input_image) | |
| - fg: black frame (FG at t=0 lives in the RGB image) | |
| Writes per stem under ``--output-root/<stem>/``: | |
| first_frame.png, bg_projection.mp4, fg_projection.mp4 | |
| and a CSV (paths relative to the CSV file location): | |
| name,input_image,text,bg_projection,fg_projection | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import sys | |
| from pathlib import Path | |
| from typing import Optional, Tuple | |
| import cv2 | |
| import numpy as np | |
| from tqdm import tqdm | |
| def parse_args() -> argparse.Namespace: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument( | |
| "--csv", | |
| type=Path, | |
| default=Path( | |
| "/home/zhangzhiyuan/VAM_projs/realbench_comp/" | |
| "SpatialVID_preped/sampled_clippath.csv" | |
| ), | |
| ) | |
| p.add_argument( | |
| "--video-root", | |
| type=Path, | |
| default=Path( | |
| "/home/zhangzhiyuan/VAM_projs/realbench_comp/SpatialVID_preped" | |
| ), | |
| help="Directory containing <clipPath> mp4s", | |
| ) | |
| p.add_argument( | |
| "--annotation-root", | |
| type=Path, | |
| default=Path( | |
| "/home/zhangzhiyuan/VAM_projs/realbench_comp/" | |
| "SpatialVID_preped/clip_annotation" | |
| ), | |
| ) | |
| p.add_argument( | |
| "--output-root", | |
| type=Path, | |
| default=Path(__file__).resolve().parents[1] / "liveworld_i2v_inputs", | |
| help="Per-case first_frame + padded 82-frame projections " | |
| "(default: LiveWorld_comp/liveworld_i2v_inputs)", | |
| ) | |
| p.add_argument( | |
| "--out-csv", | |
| type=Path, | |
| default=Path(__file__).resolve().parents[1] / "liveworld_i2v_cases.csv", | |
| help="Output CSV path (default: LiveWorld_comp/liveworld_i2v_cases.csv)", | |
| ) | |
| p.add_argument("--fps", type=float, default=16.0, | |
| help="FPS for written projection mp4s (LiveWorld default 16)") | |
| p.add_argument("--target-hw", type=int, nargs=2, default=[480, 832], | |
| metavar=("H", "W"), | |
| help="Resize first_frame / projections to this HxW") | |
| p.add_argument("--overwrite", action="store_true") | |
| p.add_argument("--limit", type=int, default=None) | |
| p.add_argument("--stems", nargs="*", default=None, | |
| help="Only process these stems (default: all csv rows)") | |
| return p.parse_args() | |
| def read_video_bgr(path: Path) -> list: | |
| cap = cv2.VideoCapture(str(path)) | |
| if not cap.isOpened(): | |
| raise FileNotFoundError(f"cannot open video: {path}") | |
| frames = [] | |
| while True: | |
| ok, frame = cap.read() | |
| if not ok: | |
| break | |
| frames.append(frame) | |
| cap.release() | |
| if not frames: | |
| raise RuntimeError(f"empty video: {path}") | |
| return frames | |
| def write_video_bgr(path: Path, frames: list, fps: float) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| h, w = frames[0].shape[:2] | |
| writer = cv2.VideoWriter( | |
| str(path), | |
| cv2.VideoWriter_fourcc(*"mp4v"), | |
| float(fps), | |
| (w, h), | |
| ) | |
| if not writer.isOpened(): | |
| raise RuntimeError(f"failed to open VideoWriter: {path}") | |
| for f in frames: | |
| writer.write(f) | |
| writer.release() | |
| def resize_bgr(frame: np.ndarray, target_hw: Tuple[int, int]) -> np.ndarray: | |
| H, W = target_hw | |
| if frame.shape[0] == H and frame.shape[1] == W: | |
| return frame | |
| return cv2.resize(frame, (W, H), interpolation=cv2.INTER_LINEAR) | |
| def pad_projection_to_82( | |
| frames_81: list, | |
| pad_frame: np.ndarray, | |
| target_hw: Tuple[int, int], | |
| ) -> list: | |
| """Prepend pad_frame so LiveWorld indices 1..81 map to original 0..80.""" | |
| if len(frames_81) != 81: | |
| raise ValueError(f"expected 81 frames, got {len(frames_81)}") | |
| pad = resize_bgr(pad_frame, target_hw) | |
| body = [resize_bgr(f, target_hw) for f in frames_81] | |
| return [pad] + body | |
| def process_one( | |
| stem: str, | |
| prompt: str, | |
| video_path: Path, | |
| annotation_root: Path, | |
| output_root: Path, | |
| fps: float, | |
| target_hw: Tuple[int, int], | |
| overwrite: bool, | |
| ) -> Optional[dict]: | |
| ll_dir = annotation_root / stem / "longlive" | |
| bg_src = ll_dir / "scene_projection_input.mp4" | |
| fg_src = ll_dir / "fg_projection_input.mp4" | |
| if not bg_src.exists() or not fg_src.exists(): | |
| print(f"[skip] missing projections: {stem}", file=sys.stderr) | |
| return None | |
| if not video_path.exists(): | |
| print(f"[skip] missing video: {video_path}", file=sys.stderr) | |
| return None | |
| out_dir = output_root / stem | |
| first_path = out_dir / "first_frame.png" | |
| bg_out = out_dir / "bg_projection.mp4" | |
| fg_out = out_dir / "fg_projection.mp4" | |
| if ( | |
| not overwrite | |
| and first_path.exists() | |
| and bg_out.exists() | |
| and fg_out.exists() | |
| ): | |
| return { | |
| "name": stem, | |
| "input_image": first_path, | |
| "text": prompt, | |
| "bg_projection": bg_out, | |
| "fg_projection": fg_out, | |
| } | |
| src_frames = read_video_bgr(video_path) | |
| first_bgr = resize_bgr(src_frames[0], target_hw) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| cv2.imwrite(str(first_path), first_bgr) | |
| bg_81 = read_video_bgr(bg_src) | |
| fg_81 = read_video_bgr(fg_src) | |
| if len(bg_81) != 81 or len(fg_81) != 81: | |
| print( | |
| f"[skip] {stem}: expected 81-frame projections, " | |
| f"got bg={len(bg_81)} fg={len(fg_81)}", | |
| file=sys.stderr, | |
| ) | |
| return None | |
| H, W = target_hw | |
| black = np.zeros((H, W, 3), dtype=np.uint8) | |
| bg_82 = pad_projection_to_82(bg_81, first_bgr, target_hw) | |
| fg_82 = pad_projection_to_82(fg_81, black, target_hw) | |
| write_video_bgr(bg_out, bg_82, fps) | |
| write_video_bgr(fg_out, fg_82, fps) | |
| return { | |
| "name": stem, | |
| "input_image": first_path, | |
| "text": prompt, | |
| "bg_projection": bg_out, | |
| "fg_projection": fg_out, | |
| } | |
| def main() -> None: | |
| args = parse_args() | |
| target_hw = (int(args.target_hw[0]), int(args.target_hw[1])) | |
| wanted = set(args.stems) if args.stems else None | |
| with args.csv.open("r", encoding="utf-8-sig", newline="") as f: | |
| rows = list(csv.DictReader(f)) | |
| if not rows: | |
| raise SystemExit(f"empty csv: {args.csv}") | |
| selected = [] | |
| for r in rows: | |
| clip = (r.get("clipPath") or "").strip() | |
| if not clip: | |
| continue | |
| stem = Path(clip).stem | |
| if wanted is not None and stem not in wanted: | |
| continue | |
| selected.append((stem, (r.get("prompt") or "").strip(), clip)) | |
| if args.limit is not None: | |
| selected = selected[: args.limit] | |
| args.output_root.mkdir(parents=True, exist_ok=True) | |
| out_rows = [] | |
| n_fail = 0 | |
| for stem, prompt, clip in tqdm(selected, desc="prepare liveworld i2v"): | |
| if not prompt: | |
| print(f"[skip] empty prompt: {stem}", file=sys.stderr) | |
| n_fail += 1 | |
| continue | |
| video_path = args.video_root / clip | |
| try: | |
| row = process_one( | |
| stem=stem, | |
| prompt=prompt, | |
| video_path=video_path, | |
| annotation_root=args.annotation_root, | |
| output_root=args.output_root, | |
| fps=args.fps, | |
| target_hw=target_hw, | |
| overwrite=args.overwrite, | |
| ) | |
| except Exception as e: # noqa: BLE001 | |
| n_fail += 1 | |
| print(f"[FAIL] {stem}: {e}", file=sys.stderr) | |
| continue | |
| if row is None: | |
| n_fail += 1 | |
| continue | |
| out_rows.append(row) | |
| args.out_csv.parent.mkdir(parents=True, exist_ok=True) | |
| csv_base = args.out_csv.resolve().parent | |
| def _rel(p: Path) -> str: | |
| try: | |
| return str(p.resolve().relative_to(csv_base)) | |
| except ValueError: | |
| return str(p.resolve()) | |
| csv_rows = [ | |
| { | |
| "name": r["name"], | |
| "input_image": _rel(Path(r["input_image"])), | |
| "text": r["text"], | |
| "bg_projection": _rel(Path(r["bg_projection"])), | |
| "fg_projection": _rel(Path(r["fg_projection"])), | |
| } | |
| for r in out_rows | |
| ] | |
| with args.out_csv.open("w", encoding="utf-8", newline="") as f: | |
| writer = csv.DictWriter( | |
| f, | |
| fieldnames=[ | |
| "name", "input_image", "text", "bg_projection", "fg_projection", | |
| ], | |
| quoting=csv.QUOTE_MINIMAL, | |
| ) | |
| writer.writeheader() | |
| writer.writerows(csv_rows) | |
| print( | |
| f"[done] wrote {len(csv_rows)} rows -> {args.out_csv} " | |
| f"(fail/skip={n_fail}, inputs={args.output_root})" | |
| ) | |
| if __name__ == "__main__": | |
| main() | |