Datasets:
File size: 7,536 Bytes
75292da 3f4d8c0 75292da 3f4d8c0 70698b7 75292da 70698b7 75292da 70698b7 75292da 3f4d8c0 70698b7 75292da 70698b7 3f4d8c0 75292da 3f4d8c0 75292da 70698b7 75292da 3f4d8c0 75292da 3f4d8c0 75292da 3f4d8c0 75292da | 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 | """The camera. A thin, honest wrapper around a text-to-video pipeline.
Two rules from the house are baked in here:
* **Record the seed.** A plate that cannot be re-rendered is a plate that cannot be fixed (R17).
* **Announce what you hold.** Before loading, the camera checks free VRAM against the model's own
declared size, so a shoot fails at the door rather than halfway through the third shot (C3).
python -m blue_morpho.camera "a lighthouse beam cutting fog" --out plates/shot1.mp4 --seed 4417
"""
from __future__ import annotations
import argparse
import json
import time
from dataclasses import dataclass, asdict
from pathlib import Path
DEFAULT_MODEL = "Wan-AI/Wan2.2-TI2V-5B-Diffusers"
# THE OFFICIAL SETTINGS, taken from the model card rather than guessed. The card says, verbatim:
# "this model supports both text-to-video and image-to-video generation at 720P resolution with
# 24fps" and "Unlike other tasks, the 720P resolution of the Text-Image-to-Video task is
# 1280*704 or 704*1280."
# Our first film rendered 480x832 - under half the pixels, in a shape the model was not trained on.
# That single mistake was the largest cause of the poor quality a human noticed immediately.
#
# Wan's VAE compresses 4 frames temporally, so num_frames must satisfy (n - 1) % 4 == 0. 121 frames
# at 24fps is 5.04s, which is the card's own "5-second 720P video".
DEFAULT_HEIGHT, DEFAULT_WIDTH, DEFAULT_FRAMES, DEFAULT_FPS = 1280, 704, 121, 24
DEFAULT_STEPS = 40 # the card's examples are not run at 20; detail arrives late in sampling
NATIVE_SIZES = ((1280, 704), (704, 1280)) # the only two resolutions the card names
# The ComfyUI official workflow runs the 5B with a *negative* prompt as well as a positive one; our
# first film passed none. This is the standard Wan negative: it suppresses the exact failures a
# viewer notices first - oversaturation, overexposure, flat or blurry detail, static frames.
NEGATIVE_PROMPT = ("oversaturated, overexposed, static, blurred details, subtitles, watermark, "
"text, signature, extra limbs, deformed hands, warped face, low quality, "
"worst quality, jpeg artifacts, cartoon, 3d render")
@dataclass
class Plate:
"""One rendered shot, with everything needed to reproduce it."""
shot: str
prompt: str
path: str
seed: int
engine: str
height: int
width: int
num_frames: int
fps: int
steps: int
guidance: float
seconds: float
vram_peak_gb: float = 0.0
started: float = 0.0
def to_json(self) -> str:
return json.dumps(asdict(self), indent=2)
def preflight(needed_gb: float = 40.0) -> float:
"""C3. Prove there is room before loading anything."""
import torch
if not torch.cuda.is_available():
raise RuntimeError("no CUDA device: the camera cannot roll")
free, total = torch.cuda.mem_get_info()
free_gb = free / 1e9
if free_gb < needed_gb:
raise RuntimeError(f"needs ~{needed_gb:.0f} GB free, only {free_gb:.1f} GB available")
return free_gb
def official_size(height: int, width: int) -> tuple[int, int]:
"""Warn when a render is not at one of the two resolutions the model card names."""
if (height, width) not in NATIVE_SIZES:
print(f"[camera] NOTE: {width}x{height} is not an official TI2V-5B size "
f"(the card names 1280*704 and 704*1280) - quality and motion will suffer")
return height, width
def load(model_id: str = DEFAULT_MODEL, dtype=None, i2v: bool = False):
"""Load the camera onto the card at full precision by default (H9).
`i2v=True` loads the image-conditioned pipeline. That is the path a casting needs: a character is
only *cast* if the same locked look can be shot again from a reference frame, not merely described.
"""
import torch
from diffusers import WanImageToVideoPipeline, WanPipeline
dtype = dtype or torch.bfloat16
pipeline = WanImageToVideoPipeline if i2v else WanPipeline
pipe = pipeline.from_pretrained(model_id, torch_dtype=dtype)
pipe.to("cuda")
if hasattr(pipe, "vae") and hasattr(pipe.vae, "enable_tiling"):
pipe.vae.enable_tiling()
return pipe
def render(pipe, prompt: str, *, shot: str = "shot", seed: int = 0,
height: int = DEFAULT_HEIGHT, width: int = DEFAULT_WIDTH,
num_frames: int = DEFAULT_FRAMES, fps: int = DEFAULT_FPS, steps: int = 20,
guidance: float = 5.0, out: str | Path = "plate.mp4",
engine: str = DEFAULT_MODEL, image=None, negative_prompt: str = NEGATIVE_PROMPT) -> Plate:
"""Render one take. The seed goes in, the seed comes out.
`image` is a PIL frame or a path to one; supplying it makes this an image-to-video take, which is
how a cast character is carried from shot to shot.
"""
import torch
from diffusers.utils import export_to_video
torch.manual_seed(seed)
started = time.time()
if torch.cuda.is_available():
torch.cuda.reset_peak_memory_stats()
kwargs = {}
if image is not None:
from PIL import Image as PILImage
frame = PILImage.open(image) if isinstance(image, (str, Path)) else image
kwargs["image"] = frame.convert("RGB")
official_size(height, width)
frames = pipe(
prompt=prompt, negative_prompt=negative_prompt or None,
height=height, width=width, num_frames=num_frames,
num_inference_steps=steps, guidance_scale=guidance,
generator=torch.Generator("cuda").manual_seed(seed), **kwargs
).frames[0]
out = Path(out)
out.parent.mkdir(parents=True, exist_ok=True)
export_to_video(frames, str(out), fps=fps)
peak = torch.cuda.max_memory_allocated() / 1e9 if torch.cuda.is_available() else 0.0
return Plate(shot=shot, prompt=prompt, path=str(out), seed=seed, engine=engine,
height=height, width=width, num_frames=num_frames, fps=fps, steps=steps,
guidance=guidance, seconds=round(time.time() - started, 1),
vram_peak_gb=round(peak, 1), started=started)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(prog="blue_morpho.camera")
ap.add_argument("prompt")
ap.add_argument("--out", default="plates/shot.mp4")
ap.add_argument("--shot", default="shot")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--frames", type=int, default=DEFAULT_FRAMES)
ap.add_argument("--height", type=int, default=DEFAULT_HEIGHT)
ap.add_argument("--width", type=int, default=DEFAULT_WIDTH)
ap.add_argument("--steps", type=int, default=DEFAULT_STEPS)
ap.add_argument("--guidance", type=float, default=5.0)
ap.add_argument("--model", default=DEFAULT_MODEL)
ap.add_argument("--negative", default=NEGATIVE_PROMPT)
args = ap.parse_args(argv)
print(f"[camera] free VRAM before load: {preflight():.1f} GB", flush=True)
t0 = time.time()
pipe = load(args.model)
print(f"[camera] loaded {args.model} in {time.time()-t0:.1f}s", flush=True)
plate = render(pipe, args.prompt, shot=args.shot, seed=args.seed, height=args.height,
width=args.width, num_frames=args.frames, steps=args.steps,
guidance=args.guidance, out=args.out, engine=args.model,
negative_prompt=args.negative)
Path(args.out).with_suffix(".json").write_text(plate.to_json())
print("[camera] PLATE " + json.dumps(asdict(plate)), flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|