| """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 |
| from core.model_loader import build_pipeline |
| from core.pipeline import RunOptions, run_iterative_inference_user_pc |
|
|
|
|
| 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: |
| 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 = { |
| "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 |
| 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: |
| 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() |
|
|