Moved from YourlifeisGame/Spritegenerator; projects are found via _bootstrap.py (cwd or --project) and provide config.py plus list modules. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
140 lines
7.4 KiB
Python
140 lines
7.4 KiB
Python
"""
|
|
Animate the intro story stills with Wan 2.2 I2V (A14B, high+low noise experts)
|
|
plus the lightx2v step-distill LoRA, on a local ComfyUI server.
|
|
|
|
Usage:
|
|
py -3.12 generate_video.py <name> [<name> ...] e.g. story_old
|
|
py -3.12 generate_video.py --all
|
|
|
|
Frames land in output/video/<name>/frame_XXXX.png plus a preview.gif.
|
|
"""
|
|
import json
|
|
import os
|
|
import random
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
|
|
import config
|
|
|
|
ROOT = os.path.dirname(os.path.abspath(__file__))
|
|
SPRITES = os.path.join(config.ASSETS_DIR, "Sprites")
|
|
OUT = os.path.join(config.OUTPUT_DIR, "video")
|
|
|
|
WIDTH, HEIGHT = 832, 480 # 16:9-ish 480p, what Wan 14B handles on 12 GB
|
|
LENGTH = 49 # frames at 16 fps -> ~3 s
|
|
STEPS, SPLIT = 8, 4 # high-noise expert 0..4, low-noise expert 4..8
|
|
SHIFT = 5.0
|
|
|
|
# Projektdaten (Stil, Negativ-Prompt, Bewegungen, Größen) aus dem Projekt: config.VIDEO_MODULE
|
|
import importlib as _il
|
|
_d = _il.import_module(getattr(config, "VIDEO_MODULE", "video_life"))
|
|
STYLE, NEGATIVE, MOTION, SIZE = _d.STYLE, _d.NEGATIVE, _d.MOTION, _d.SIZE
|
|
|
|
|
|
def post(path, payload):
|
|
req = urllib.request.Request(config.HOST + path, data=json.dumps(payload).encode("utf-8"),
|
|
headers={"Content-Type": "application/json"})
|
|
with urllib.request.urlopen(req) as r:
|
|
return json.loads(r.read().decode("utf-8"))
|
|
|
|
|
|
def get(path):
|
|
with urllib.request.urlopen(config.HOST + path) as r:
|
|
return json.loads(r.read().decode("utf-8"))
|
|
|
|
|
|
def upload(path, width=WIDTH, height=HEIGHT):
|
|
"""Uploads the still cover-cropped to width x height so the video starts exactly on it."""
|
|
from PIL import Image
|
|
im = Image.open(path).convert("RGB")
|
|
s = max(width / im.width, height / im.height)
|
|
im = im.resize((round(im.width * s), round(im.height * s)), Image.LANCZOS)
|
|
l, t = (im.width - width) // 2, (im.height - height) // 2
|
|
im = im.crop((l, t, l + width, t + height))
|
|
tmp = os.path.join(OUT, "_upload.png")
|
|
im.save(tmp)
|
|
boundary = uuid.uuid4().hex
|
|
name = "yl_" + os.path.basename(path).rsplit(".", 1)[0] + ".png"
|
|
body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n"
|
|
f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{name}\"\r\n"
|
|
f"Content-Type: image/png\r\n\r\n").encode() + open(tmp, "rb").read() + f"\r\n--{boundary}--\r\n".encode()
|
|
req = urllib.request.Request(config.HOST + "/upload/image", data=body,
|
|
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
|
|
with urllib.request.urlopen(req) as r:
|
|
return json.loads(r.read().decode("utf-8"))["name"]
|
|
|
|
|
|
def workflow(image_name, prompt, seed, prefix, width=WIDTH, height=HEIGHT):
|
|
lora = "Wan21_I2V_14B_lightx2v_cfg_step_distill_lora_rank64.safetensors"
|
|
return {
|
|
"1": {"class_type": "UNETLoader", "inputs": {"unet_name": "Wan2_2-I2V-A14B-HIGH_fp8_e5m2_scaled_KJ.safetensors", "weight_dtype": "default"}},
|
|
"2": {"class_type": "UNETLoader", "inputs": {"unet_name": "Wan2_2-I2V-A14B-LOW_fp8_e5m2_scaled_KJ.safetensors", "weight_dtype": "default"}},
|
|
"3": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["1", 0], "lora_name": lora, "strength_model": 3.0}},
|
|
"4": {"class_type": "LoraLoaderModelOnly", "inputs": {"model": ["2", 0], "lora_name": lora, "strength_model": 1.5}},
|
|
"5": {"class_type": "ModelSamplingSD3", "inputs": {"model": ["3", 0], "shift": SHIFT}},
|
|
"6": {"class_type": "ModelSamplingSD3", "inputs": {"model": ["4", 0], "shift": SHIFT}},
|
|
"7": {"class_type": "CLIPLoader", "inputs": {"clip_name": "umt5_xxl_fp16.safetensors", "type": "wan"}},
|
|
"8": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["7", 0], "text": f"{prompt}, {STYLE}"}},
|
|
"9": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["7", 0], "text": NEGATIVE}},
|
|
"10": {"class_type": "VAELoader", "inputs": {"vae_name": "wan_2.1_vae.safetensors"}},
|
|
"11": {"class_type": "LoadImage", "inputs": {"image": image_name}},
|
|
"12": {"class_type": "WanImageToVideo", "inputs": {"positive": ["8", 0], "negative": ["9", 0], "vae": ["10", 0],
|
|
"width": width, "height": height, "length": LENGTH,
|
|
"batch_size": 1, "start_image": ["11", 0]}},
|
|
"13": {"class_type": "KSamplerAdvanced", "inputs": {"model": ["5", 0], "add_noise": "enable", "noise_seed": seed,
|
|
"steps": STEPS, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple",
|
|
"positive": ["12", 0], "negative": ["12", 1], "latent_image": ["12", 2],
|
|
"start_at_step": 0, "end_at_step": SPLIT, "return_with_leftover_noise": "enable"}},
|
|
"14": {"class_type": "KSamplerAdvanced", "inputs": {"model": ["6", 0], "add_noise": "disable", "noise_seed": seed,
|
|
"steps": STEPS, "cfg": 1.0, "sampler_name": "euler", "scheduler": "simple",
|
|
"positive": ["12", 0], "negative": ["12", 1], "latent_image": ["13", 0],
|
|
"start_at_step": SPLIT, "end_at_step": 10000, "return_with_leftover_noise": "disable"}},
|
|
"15": {"class_type": "VAEDecode", "inputs": {"samples": ["14", 0], "vae": ["10", 0]}},
|
|
"16": {"class_type": "SaveImage", "inputs": {"images": ["15", 0], "filename_prefix": prefix}},
|
|
}
|
|
|
|
|
|
def run(name):
|
|
src = os.path.join(SPRITES, name + ".jpg")
|
|
dest = os.path.join(OUT, name)
|
|
os.makedirs(dest, exist_ok=True)
|
|
w, h = SIZE.get(name, (WIDTH, HEIGHT))
|
|
img = upload(src, w, h)
|
|
seed = random.randint(1, 2**31)
|
|
pid = post("/prompt", {"prompt": workflow(img, MOTION[name], seed, f"yl_video/{name}", w, h)})["prompt_id"]
|
|
t0 = time.time()
|
|
print(f"{name}: queued (seed {seed})", flush=True)
|
|
while True:
|
|
time.sleep(5)
|
|
h = get(f"/history/{pid}")
|
|
if pid in h:
|
|
st = h[pid].get("status", {})
|
|
if st.get("status_str") == "error":
|
|
print(json.dumps(st, indent=1)[:3000]); return False
|
|
if st.get("completed"):
|
|
break
|
|
print(f"{name}: done in {time.time() - t0:.0f} s", flush=True)
|
|
from PIL import Image
|
|
frames = []
|
|
for node in h[pid]["outputs"].values():
|
|
for i, info in enumerate(node.get("images", [])):
|
|
qs = urllib.parse.urlencode({"filename": info["filename"], "subfolder": info.get("subfolder", ""), "type": info.get("type", "output")})
|
|
p = os.path.join(dest, f"frame_{i:04d}.png")
|
|
urllib.request.urlretrieve(f"{config.HOST}/view?{qs}", p)
|
|
frames.append(Image.open(p).convert("RGB"))
|
|
if frames:
|
|
frames[0].save(os.path.join(dest, "preview.gif"), save_all=True, append_images=frames[1:], duration=62, loop=0)
|
|
print(f"{name}: {len(frames)} frames -> {dest}")
|
|
return True
|
|
|
|
|
|
if __name__ == "__main__":
|
|
os.makedirs(OUT, exist_ok=True)
|
|
names = [n for n in MOTION if n.startswith("story_")] if "--all" in sys.argv else [a for a in sys.argv[1:] if not a.startswith("--")]
|
|
for n in names:
|
|
run(n)
|