File size: 11,804 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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | """Run LiveWorld_comp from a CSV of the four essential fields.
CSV columns (header required; extra columns ignored):
name,input_image,text,bg_projection,fg_projection
- name : optional; output folder name (default: row_{i:04d})
- input_image : path to first-frame RGB image
- text : inline prompt, OR path to a .txt prompt file
- bg_projection : path to bg / scene projection mp4
- fg_projection : path to fg projection mp4 (optional; leave empty to skip)
Uses ``condition_source=mp4`` + dummy identity poses (geometry not needed).
Default config ``configs/csv_mp4_81.yaml`` generates a single 81-frame chunk
(final video = first frame + 81 generated = 82 frames).
Example:
python run_from_csv.py \\
--csv cases.csv \\
--output-root outputs_csv \\
--config configs/csv_mp4_81.yaml
# subset / resume
python run_from_csv.py --csv cases.csv --indices 0 1 2 --skip_existing
"""
from __future__ import annotations
import argparse
import csv
import os
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import torch
from omegaconf import OmegaConf
_HERE = Path(__file__).resolve().parent
_LIVEWORLD_ROOT_CANDIDATES = [
_HERE.parent / "LiveWorld",
Path(os.environ.get("LIVEWORLD_ROOT", "")),
]
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
for _root in _LIVEWORLD_ROOT_CANDIDATES:
if _root and _root.is_dir():
if str(_root) in sys.path:
sys.path.remove(str(_root))
sys.path.insert(0, str(_root))
break
from core.inputs import load_user_inputs_from_paths # noqa: E402
from core.model_loader import build_pipeline # noqa: E402
from core.pipeline import RunOptions, run_iterative_inference_user_pc # noqa: E402
REQUIRED_COLS = ("input_image", "text", "bg_projection")
OPTIONAL_COLS = ("name", "fg_projection")
def _ensure_ffmpeg_on_path() -> None:
import shutil
import tempfile
if shutil.which("ffmpeg") is not None:
return
try:
import imageio_ffmpeg
exe = imageio_ffmpeg.get_ffmpeg_exe()
except Exception as e: # noqa: BLE001
print(f"[warn] no system ffmpeg and imageio_ffmpeg unavailable ({e}); "
f"H.264 video saving will fail.", file=sys.stderr)
return
bin_dir = Path(tempfile.gettempdir()) / "lw_comp_ffmpeg_bin"
bin_dir.mkdir(parents=True, exist_ok=True)
link = bin_dir / "ffmpeg"
if not link.exists():
try:
link.symlink_to(exe)
except OSError:
import shutil as _sh
_sh.copy(exe, link)
link.chmod(0o755)
os.environ["PATH"] = str(bin_dir) + os.pathsep + os.environ.get("PATH", "")
print(f"[boot] using bundled ffmpeg: {exe} (linked as {link})")
def _slugify(name: str, fallback: str) -> str:
s = re.sub(r"[^\w.\-]+", "_", str(name).strip())
s = s.strip("._")
return s or fallback
def _normalize_header(fieldnames: Optional[List[str]]) -> Dict[str, str]:
"""Map lowercased stripped header -> original header."""
if not fieldnames:
raise SystemExit("CSV has no header row")
mapping: Dict[str, str] = {}
for h in fieldnames:
if h is None:
continue
key = h.strip().lower()
mapping[key] = h
# Aliases
aliases = {
"input_image": ("input_image", "image", "first_frame", "first_frame.png"),
"text": ("text", "prompt", "caption"),
"bg_projection": ("bg_projection", "bg", "scene_projection", "bg_projection.mp4"),
"fg_projection": ("fg_projection", "fg", "fg_projection.mp4"),
"name": ("name", "id", "case", "case_name"),
}
resolved: Dict[str, str] = {}
for canonical, cands in aliases.items():
for c in cands:
if c in mapping:
resolved[canonical] = mapping[c]
break
missing = [c for c in REQUIRED_COLS if c not in resolved]
if missing:
raise SystemExit(
f"CSV missing required columns {missing}. "
f"Need at least: {list(REQUIRED_COLS)}. "
f"Got headers: {fieldnames}"
)
return resolved
def _resolve_path(value: str, base_dir: Path) -> str:
"""Resolve a CSV path: absolute stays as-is; relative is vs ``base_dir``."""
raw = (value or "").strip()
if not raw:
return raw
p = Path(raw)
if not p.is_absolute():
p = (base_dir / p).resolve()
return str(p)
def _read_csv_rows(csv_path: Path) -> List[Dict[str, str]]:
base_dir = csv_path.resolve().parent
path_keys = {"input_image", "bg_projection", "fg_projection"}
with csv_path.open("r", encoding="utf-8-sig", newline="") as f:
reader = csv.DictReader(f)
colmap = _normalize_header(list(reader.fieldnames or []))
rows: List[Dict[str, str]] = []
for i, raw in enumerate(reader):
row = {
k: (raw.get(src) or "").strip()
for k, src in colmap.items()
}
if not any(row.get(c) for c in REQUIRED_COLS):
continue # skip blank lines
if not row.get("name"):
row["name"] = f"row_{i:04d}"
else:
row["name"] = _slugify(row["name"], f"row_{i:04d}")
for k in path_keys:
if row.get(k):
row[k] = _resolve_path(row[k], base_dir)
rows.append(row)
if not rows:
raise SystemExit(f"no data rows in {csv_path}")
return rows
def _parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="LiveWorld_comp inference from a 4-field CSV")
p.add_argument("--csv", required=True,
help="CSV with columns: name,input_image,text,"
"bg_projection,fg_projection")
p.add_argument("--output-root", default=str(_HERE / "outputs_csv"),
help="Root for results; each case -> <output-root>/<name>")
p.add_argument("--config",
default=str(_HERE / "configs" / "csv_mp4_81.yaml"),
help="System YAML (default: configs/csv_mp4_81.yaml)")
p.add_argument("--indices", type=int, nargs="*", default=None,
help="Only run these 0-based row indices")
p.add_argument("--limit", type=int, default=None,
help="Run only the first N selected rows")
p.add_argument("--device", default=None, help="Override runtime.device")
p.add_argument("--skip_existing", action="store_true",
help="Skip when <output>/final_video.mp4 already exists")
p.add_argument("--num_frames", type=int, default=None,
help="Override run.num_frames (must be multiple of "
"frames_per_iter; default 81 from config)")
return p.parse_args()
def _options_from_cfg(run_cfg: dict, seed: int) -> RunOptions:
opts = RunOptions()
if run_cfg is None:
run_cfg = {}
for key, value in run_cfg.items():
if hasattr(opts, key):
setattr(opts, key, value)
opts.seed = seed
if opts.target_hw is not None:
opts.target_hw = tuple(int(v) for v in opts.target_hw)
if opts.denoising_step_list is not None:
opts.denoising_step_list = [float(v) for v in opts.denoising_step_list]
return opts
def main() -> None:
args = _parse_args()
_ensure_ffmpeg_on_path()
csv_path = Path(args.csv)
if not csv_path.exists():
raise SystemExit(f"csv not found: {csv_path}")
rows = _read_csv_rows(csv_path)
if args.indices is not None:
bad = [i for i in args.indices if i < 0 or i >= len(rows)]
if bad:
raise SystemExit(f"--indices out of range {bad} "
f"(have {len(rows)} rows)")
rows = [rows[i] for i in args.indices]
if args.limit is not None:
rows = rows[: args.limit]
cfg = OmegaConf.load(args.config)
cfg = OmegaConf.to_container(cfg, resolve=True)
runtime_cfg = cfg.get("runtime", {})
observer_cfg = cfg.get("observer", {})
run_cfg = cfg.get("run", {})
device_str = args.device or runtime_cfg.get("device", "cuda:0")
device = torch.device(device_str)
cpu_offload_obs = bool(runtime_cfg.get("cpu_offload", False))
seed = int(runtime_cfg.get("seed", 71))
opts = _options_from_cfg(run_cfg, seed)
opts.cpu_offload = cpu_offload_obs
if args.num_frames is not None:
opts.num_frames = int(args.num_frames)
if opts.condition_source != "mp4":
print(f"[warn] config condition_source={opts.condition_source!r}; "
f"CSV path expects 'mp4'. Forcing condition_source='mp4'.")
opts.condition_source = "mp4"
output_root = Path(args.output_root)
cases: List[Tuple[Dict[str, str], Path]] = [
(row, output_root / row["name"]) for row in rows
]
if args.skip_existing:
pending = [(r, o) for (r, o) in cases
if not (o / "final_video.mp4").exists()]
skipped = len(cases) - len(pending)
if skipped:
print(f"[skip] {skipped}/{len(cases)} case(s) already have "
f"final_video.mp4")
cases = pending
if not cases:
print("[done] all selected cases already complete; "
"not loading the model.")
return
print(f"\n[boot] LiveWorld_comp (CSV four-field)")
print(f" csv : {csv_path}")
print(f" device : {device}")
print(f" target_hw : {opts.target_hw}")
print(f" num_frames : {opts.num_frames} "
f"(frames_per_iter={opts.frames_per_iter})")
print(f" condition_source: {opts.condition_source}")
print(f" cases : {len(cases)}\n")
pipeline = build_pipeline(
observer_cfg=observer_cfg,
device=device,
cpu_offload=cpu_offload_obs,
)
print(f"[boot] pipeline ready (use_fg_proj cfg-level={pipeline.use_fg_proj})")
n_ok, n_fail = 0, 0
for row, output_dir in cases:
print("\n" + "#" * 72)
print(f"# CASE {row['name']}")
print(f"# image : {row['input_image']}")
print(f"# bg : {row['bg_projection']}")
print(f"# fg : {row.get('fg_projection') or '(none)'}")
print(f"# out : {output_dir}")
print("#" * 72)
try:
inputs = load_user_inputs_from_paths(
input_image=row["input_image"],
text=row["text"],
bg_projection=row["bg_projection"],
fg_projection=row.get("fg_projection") or None,
target_hw=opts.target_hw,
n_poses=opts.num_frames + 1,
)
print(f"[input] prompt: {inputs.prompt[:80]!r}"
f"{'...' if len(inputs.prompt) > 80 else ''}")
print(f"[input] poses(dummy): {inputs.poses_c2w.shape},"
f" scene_mp4: {None if inputs.scene_proj_frames is None else inputs.scene_proj_frames.shape},"
f" fg_mp4: {None if inputs.fg_proj_frames is None else inputs.fg_proj_frames.shape}")
result = run_iterative_inference_user_pc(
pipeline=pipeline,
inputs=inputs,
options=opts,
output_dir=str(output_dir),
)
print(f"[done] {row['name']}: final video {result.final_video.shape}")
n_ok += 1
except Exception as e: # noqa: BLE001
n_fail += 1
print(f"[FAIL] {row['name']}: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
print(f"\n[done] ok={n_ok}, fail={n_fail}, total={len(cases)}")
if __name__ == "__main__":
main()
|