File size: 9,428 Bytes
7d31a83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | #!/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()
|