Spaces:
Running on Zero
Running on Zero
File size: 9,763 Bytes
5c93746 | 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 | """Public Python API for simple offline video-to-video inference."""
from __future__ import annotations
from contextlib import ExitStack
from importlib.resources import as_file, files
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import tempfile
from typing import Literal, Sequence
import torch
from streamv2v.inference_common import load_mp4_as_tensor, normalize_acceleration_flags
InferenceMode = Literal["single", "single-wo", "pipe"]
_SINGLE_MODE_TO_MODULE = {
"single": "streamv2v.inference",
"single-wo": "streamv2v.inference_wo_batch",
}
def _resolve_default_config_path(resource_stack: ExitStack) -> str:
resource = files("streamv2v.configs").joinpath("wan_causal_dmd_v2v.yaml")
return str(resource_stack.enter_context(as_file(resource)))
def _normalize_gpu_ids(gpu_ids: int | Sequence[int] | None) -> list[int] | None:
if gpu_ids is None:
return None
if isinstance(gpu_ids, int):
return [gpu_ids]
return [int(gpu_id) for gpu_id in gpu_ids]
def _normalize_device_gpu_id(device: str | torch.device | None) -> list[int] | None:
if device is None:
return None
device_str = str(device)
if not device_str.startswith("cuda:"):
return None
return [int(device_str.split(":", 1)[1])]
def _resolve_single_gpu_id(gpu_ids: list[int] | None) -> int | None:
if gpu_ids is None:
return None
if len(gpu_ids) != 1:
raise ValueError("single and single-wo modes accept exactly one GPU id")
return int(gpu_ids[0])
def _pick_free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
def _build_common_args(
*,
config_path: str,
checkpoint_folder: str,
video_path: str,
prompt_file_path: str,
output_folder: str,
noise_scale: float,
height: int,
width: int,
fps: int,
step: int,
seed: int,
model_type: str,
profile: bool,
use_taehv: bool,
use_tensorrt: bool,
fast: bool,
) -> list[str]:
args = [
"--config_path",
config_path,
"--checkpoint_folder",
checkpoint_folder,
"--output_folder",
output_folder,
"--prompt_file_path",
prompt_file_path,
"--video_path",
video_path,
"--noise_scale",
str(noise_scale),
"--height",
str(height),
"--width",
str(width),
"--fps",
str(fps),
"--step",
str(step),
"--seed",
str(seed),
"--model_type",
model_type,
]
if profile:
args.append("--profile")
if use_taehv:
args.append("--use_taehv")
if use_tensorrt:
args.append("--use_tensorrt")
if fast:
args.append("--fast")
return args
class StreamVideoToVideo:
"""Convenience wrapper around the offline Python entrypoints."""
def __init__(
self,
checkpoint_folder: str,
mode: InferenceMode = "single",
*,
config_path: str | None = None,
device: str | torch.device | None = None,
gpu_ids: int | Sequence[int] | None = None,
num_gpus: int | None = None,
noise_scale: float = 0.8,
height: int = 480,
width: int = 832,
fps: int = 16,
step: int = 2,
seed: int = 0,
model_type: str = "T2V-1.3B",
use_taehv: bool = False,
use_tensorrt: bool = False,
fast: bool = False,
profile: bool = False,
schedule_block: bool = False,
) -> None:
self.checkpoint_folder = checkpoint_folder
self.mode = mode
self.config_path = config_path
self.device = device
self.gpu_ids = gpu_ids
self.num_gpus = num_gpus
self.noise_scale = noise_scale
self.height = height
self.width = width
self.fps = fps
self.step = step
self.seed = seed
self.model_type = model_type
self.use_taehv = use_taehv
self.use_tensorrt = use_tensorrt
self.fast = fast
self.profile = profile
self.schedule_block = schedule_block
def generate(self, video_path: str, prompt: str) -> torch.Tensor:
with tempfile.TemporaryDirectory(prefix="streamv2v_generate_") as temp_dir:
output_path = os.path.join(temp_dir, "output.mp4")
self.run_video(video_path=video_path, prompt=prompt, output_path=output_path)
return load_mp4_as_tensor(output_path, normalize=False)
def run_video(self, video_path: str, prompt: str, output_path: str) -> str:
return run_video_to_video(
checkpoint_folder=self.checkpoint_folder,
video_path=video_path,
prompt=prompt,
output_path=output_path,
mode=self.mode,
config_path=self.config_path,
device=self.device,
gpu_ids=self.gpu_ids,
num_gpus=self.num_gpus,
noise_scale=self.noise_scale,
height=self.height,
width=self.width,
fps=self.fps,
step=self.step,
seed=self.seed,
model_type=self.model_type,
use_taehv=self.use_taehv,
use_tensorrt=self.use_tensorrt,
fast=self.fast,
profile=self.profile,
schedule_block=self.schedule_block,
)
def run_video_to_video(
*,
checkpoint_folder: str,
video_path: str,
prompt: str,
output_path: str,
mode: InferenceMode = "single",
config_path: str | None = None,
device: str | torch.device | None = None,
gpu_ids: int | Sequence[int] | None = None,
num_gpus: int | None = None,
noise_scale: float = 0.8,
height: int = 480,
width: int = 832,
fps: int = 16,
step: int = 2,
seed: int = 0,
model_type: str = "T2V-1.3B",
use_taehv: bool = False,
use_tensorrt: bool = False,
fast: bool = False,
profile: bool = False,
schedule_block: bool = False,
) -> str:
"""Run offline video-to-video inference from Python."""
flags = normalize_acceleration_flags(
{
"use_taehv": use_taehv,
"use_tensorrt": use_tensorrt,
"fast": fast,
}
)
use_taehv = bool(flags["use_taehv"])
use_tensorrt = bool(flags["use_tensorrt"])
fast = bool(flags["fast"])
requested_gpu_ids = _normalize_gpu_ids(gpu_ids)
device_gpu_ids = _normalize_device_gpu_id(device)
if requested_gpu_ids is None and device_gpu_ids is not None:
requested_gpu_ids = device_gpu_ids
if mode == "pipe":
if num_gpus is None:
num_gpus = len(requested_gpu_ids) if requested_gpu_ids is not None else 2
if requested_gpu_ids is not None and len(requested_gpu_ids) != num_gpus:
raise ValueError("num_gpus must match len(gpu_ids) for pipe mode")
elif num_gpus is not None and num_gpus != 1:
raise ValueError("num_gpus is only used for pipe mode")
resource_stack = ExitStack()
try:
resolved_config_path = config_path or _resolve_default_config_path(resource_stack)
output_file = Path(output_path)
output_file.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="streamv2v_api_") as temp_dir:
temp_dir_path = Path(temp_dir)
prompt_path = temp_dir_path / "prompt.txt"
prompt_path.write_text(prompt + "\n", encoding="utf-8")
temp_output_dir = temp_dir_path / "outputs"
temp_output_dir.mkdir(parents=True, exist_ok=True)
common_args = _build_common_args(
config_path=resolved_config_path,
checkpoint_folder=checkpoint_folder,
video_path=video_path,
prompt_file_path=str(prompt_path),
output_folder=str(temp_output_dir),
noise_scale=noise_scale,
height=height,
width=width,
fps=fps,
step=step,
seed=seed,
model_type=model_type,
profile=profile,
use_taehv=use_taehv,
use_tensorrt=use_tensorrt,
fast=fast,
)
env = os.environ.copy()
if requested_gpu_ids is not None and mode == "pipe":
env["CUDA_VISIBLE_DEVICES"] = ",".join(str(gpu_id) for gpu_id in requested_gpu_ids)
if mode == "pipe":
cmd = [
sys.executable,
"-m",
"torch.distributed.run",
f"--nproc_per_node={num_gpus}",
f"--master_port={_pick_free_port()}",
"-m",
"streamv2v.inference_pipe",
*common_args,
]
if schedule_block:
cmd.append("--schedule_block")
else:
module_name = _SINGLE_MODE_TO_MODULE.get(mode)
if module_name is None:
raise ValueError(f"Unsupported mode: {mode}")
cmd = [sys.executable, "-m", module_name, *common_args]
single_gpu_id = _resolve_single_gpu_id(requested_gpu_ids)
if single_gpu_id is not None:
cmd.extend(["--gpu_id", str(single_gpu_id)])
subprocess.run(cmd, env=env, check=True)
generated_path = temp_output_dir / "output_000.mp4"
shutil.copy2(generated_path, output_file)
return str(output_file)
finally:
resource_stack.close()
|