Spaces:
Runtime error
Runtime error
obsxrver commited on
Commit ·
ffbfb7e
1
Parent(s): e8d5a4a
initial commit
Browse files- .gitignore +4 -0
- aoti.py +34 -0
- app.py +882 -0
- modify_model/modify_wan.py +108 -0
- requirements.txt +16 -0
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
__pycache__/
|
| 4 |
+
*.pyc
|
aoti.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
"""
|
| 3 |
+
from typing import cast
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
from spaces.zero.torch.aoti import ZeroGPUCompiledModel
|
| 8 |
+
from spaces.zero.torch.aoti import ZeroGPUWeights
|
| 9 |
+
from torch._functorch._aot_autograd.subclass_parametrization import unwrap_tensor_subclass_parameters
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _shallow_clone_module(module: torch.nn.Module) -> torch.nn.Module:
|
| 13 |
+
clone = object.__new__(module.__class__)
|
| 14 |
+
clone.__dict__ = module.__dict__.copy()
|
| 15 |
+
clone._parameters = module._parameters.copy()
|
| 16 |
+
clone._buffers = module._buffers.copy()
|
| 17 |
+
clone._modules = {k: _shallow_clone_module(v) for k, v in module._modules.items() if v is not None}
|
| 18 |
+
return clone
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def aoti_blocks_load(module: torch.nn.Module, repo_id: str, variant: str | None = None):
|
| 22 |
+
repeated_blocks = cast(list[str], module._repeated_blocks)
|
| 23 |
+
aoti_files = {name: hf_hub_download(
|
| 24 |
+
repo_id=repo_id,
|
| 25 |
+
filename='package.pt2',
|
| 26 |
+
subfolder=name if variant is None else f'{name}.{variant}',
|
| 27 |
+
) for name in repeated_blocks}
|
| 28 |
+
for block_name, aoti_file in aoti_files.items():
|
| 29 |
+
for block in module.modules():
|
| 30 |
+
if block.__class__.__name__ == block_name:
|
| 31 |
+
block_ = _shallow_clone_module(block)
|
| 32 |
+
unwrap_tensor_subclass_parameters(block_)
|
| 33 |
+
weights = ZeroGPUWeights(block_.state_dict())
|
| 34 |
+
block.forward = ZeroGPUCompiledModel(aoti_file, weights)
|
app.py
ADDED
|
@@ -0,0 +1,882 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import hmac
|
| 4 |
+
import ipaddress
|
| 5 |
+
import json
|
| 6 |
+
import spaces
|
| 7 |
+
import torch
|
| 8 |
+
import torch._dynamo
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
import urllib.error
|
| 11 |
+
import urllib.request
|
| 12 |
+
from diffusers.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
|
| 13 |
+
from diffusers.models.transformers.transformer_wan import WanTransformer3DModel
|
| 14 |
+
from diffusers import FlowMatchEulerDiscreteScheduler
|
| 15 |
+
import gradio as gr
|
| 16 |
+
import tempfile
|
| 17 |
+
import numpy as np
|
| 18 |
+
import imageio.v2 as imageio
|
| 19 |
+
import shutil
|
| 20 |
+
import time
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import random
|
| 23 |
+
import gc
|
| 24 |
+
from datetime import datetime
|
| 25 |
+
from huggingface_hub import CommitOperationAdd, HfApi
|
| 26 |
+
from uuid import uuid4
|
| 27 |
+
from modify_model.modify_wan import set_sage_attn_wan
|
| 28 |
+
from sageattention import sageattn
|
| 29 |
+
from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
|
| 30 |
+
import warnings
|
| 31 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "true"
|
| 32 |
+
warnings.filterwarnings("ignore")
|
| 33 |
+
default_prompt_i2v = "a woman, jumpcut, after the transition, the woman is nude, lying on a bed on her stomach with her hands gripping the bed in front of her, a nude man is standing in front of the woman with his penis inside her mouth, he is holding her head with his right hand with his left hand at his side, the man is pissing in the woman's mouth while his penis is inside her mouth, piss spills out of her mouth and drips onto the bed"
|
| 34 |
+
default_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 低质量, JPEG压缩残留, 残缺的, 多余的手指, 画得不好的手部,畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走, 容貌改变, incorrect genitalia"
|
| 35 |
+
|
| 36 |
+
key=os.environ.get("DS_APIKEY")
|
| 37 |
+
diffusers_apikey=os.environ.get("DIFFUSERS_APIKEY")
|
| 38 |
+
MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
|
| 39 |
+
DS_ID = os.environ.get("DS_ID")
|
| 40 |
+
PRIVATE_MODEL_KEY = os.environ.get("PRIVATE_MODEL_KEY")
|
| 41 |
+
hf_api = HfApi(token=key) if key and DS_ID else None
|
| 42 |
+
GENERATION_SECRET=os.environ.get("GENERATION_SECRET")
|
| 43 |
+
PUBLIC_ENABLED=os.environ.get("PUBLIC_ENABLED")
|
| 44 |
+
PUBLIC_ENABLED = str(PUBLIC_ENABLED).strip().lower() == "true"
|
| 45 |
+
DENIED_US_REGION_CODES = {
|
| 46 |
+
code.strip().upper()
|
| 47 |
+
for code in os.environ.get("DENIED_US_REGION_CODES", "MN").split(",")
|
| 48 |
+
if code.strip()
|
| 49 |
+
}
|
| 50 |
+
DENIED_US_REGION_NAMES = {
|
| 51 |
+
code.strip().upper()
|
| 52 |
+
for code in os.environ.get("DENIED_US_REGION_NAMES", "MINNESOTA").split(",")
|
| 53 |
+
if code.strip()
|
| 54 |
+
}
|
| 55 |
+
IP_API_URL = "http://ip-api.com/json/{ip}?fields=status,message,query,countryCode,region,regionName"
|
| 56 |
+
IP_GEO_CACHE = {}
|
| 57 |
+
DENIED_IP_NETWORKS = []
|
| 58 |
+
for cidr in os.environ.get("DENIED_IP_CIDRS", "").split(","):
|
| 59 |
+
cidr = cidr.strip()
|
| 60 |
+
if not cidr:
|
| 61 |
+
continue
|
| 62 |
+
try:
|
| 63 |
+
DENIED_IP_NETWORKS.append(ipaddress.ip_network(cidr, strict=False))
|
| 64 |
+
except ValueError:
|
| 65 |
+
print(f"Ignoring invalid DENIED_IP_CIDRS entry: {cidr}")
|
| 66 |
+
|
| 67 |
+
MAX_DIM = 832
|
| 68 |
+
MIN_DIM = 480
|
| 69 |
+
SQUARE_DIM = 640
|
| 70 |
+
MULTIPLE_OF = 16
|
| 71 |
+
|
| 72 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 73 |
+
|
| 74 |
+
FIXED_FPS = 16
|
| 75 |
+
MIN_FRAMES_MODEL = 8
|
| 76 |
+
MAX_FRAMES_MODEL = 128
|
| 77 |
+
POSTPROCESS_OVERHEAD_SECONDS = 10
|
| 78 |
+
|
| 79 |
+
MIN_DURATION = round(MIN_FRAMES_MODEL/FIXED_FPS,1)
|
| 80 |
+
MAX_DURATION = round(MAX_FRAMES_MODEL/FIXED_FPS,1)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
pipe = WanImageToVideoPipeline.from_pretrained(
|
| 85 |
+
"TestOrganizationPleaseIgnore/WAMU_v2_WAN2.2_I2V_LIGHTNING",
|
| 86 |
+
torch_dtype=torch.bfloat16,
|
| 87 |
+
).to('cuda')
|
| 88 |
+
|
| 89 |
+
# Use sage attention for speed
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
pipe.load_lora_weights(
|
| 93 |
+
"lightx2v/Wan2.2-Distill-Loras",
|
| 94 |
+
weight_name="wan2.2_i2v_A14b_high_noise_lora_rank64_lightx2v_4step_1022.safetensors",
|
| 95 |
+
adapter_name="lightx2v"
|
| 96 |
+
)
|
| 97 |
+
"""
|
| 98 |
+
pipe.load_lora_weights(
|
| 99 |
+
"obsxrver/Wan2.2-I2Pee-5XL",
|
| 100 |
+
weight_name="WAN2.2-I2V_HighNoise_I2Pee-5.5XL.safetensors",
|
| 101 |
+
adapter_name="i2pee_high",
|
| 102 |
+
token=PRIVATE_MODEL_KEY,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
kwargs_lora = {}
|
| 107 |
+
kwargs_lora["load_into_transformer_2"] = True
|
| 108 |
+
"""
|
| 109 |
+
pipe.load_lora_weights(
|
| 110 |
+
"lightx2v/Wan2.2-Distill-Loras",
|
| 111 |
+
weight_name="wan2.2_i2v_A14b_low_noise_lora_rank64_lightx2v_4step_1022.safetensors",
|
| 112 |
+
adapter_name="lightx2v_2", **kwargs_lora
|
| 113 |
+
)
|
| 114 |
+
"""
|
| 115 |
+
pipe.load_lora_weights(
|
| 116 |
+
"obsxrver/Wan2.2-I2Pee-5XL",
|
| 117 |
+
weight_name="WAN2.2-I2V_LowNoise_I2Pee-5.5XL.safetensors",
|
| 118 |
+
adapter_name="i2pee_low",token=PRIVATE_MODEL_KEY, **kwargs_lora
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
pipe.set_adapters(["i2pee_high", "i2pee_low"], adapter_weights=[1., 1.])
|
| 123 |
+
#pipe.fuse_lora(adapter_names=["lightx2v"], lora_scale=0.9, components=["transformer"])
|
| 124 |
+
pipe.fuse_lora(adapter_names=["i2pee_high"], lora_scale=1., components=["transformer"])
|
| 125 |
+
|
| 126 |
+
#pipe.fuse_lora(adapter_names=["lightx2v_2"], lora_scale=1., components=["transformer_2"])
|
| 127 |
+
pipe.fuse_lora(adapter_names=["i2pee_low"], lora_scale=1., components=["transformer_2"])
|
| 128 |
+
|
| 129 |
+
pipe.unload_lora_weights()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
print("Quantizing model to fp8da")
|
| 133 |
+
quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
|
| 134 |
+
torch._dynamo.reset()
|
| 135 |
+
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 136 |
+
torch._dynamo.reset()
|
| 137 |
+
quantize_(pipe.transformer_2, Float8DynamicActivationFloat8WeightConfig())
|
| 138 |
+
torch._dynamo.reset()
|
| 139 |
+
|
| 140 |
+
#print("AOT Compiling model.")
|
| 141 |
+
#spaces.aoti_blocks_load(pipe.transformer, 'zerogpu-aoti/Wan2', variant='fp8da')
|
| 142 |
+
#spaces.aoti_blocks_load(pipe.transformer_2, 'zerogpu-aoti/Wan2', variant='fp8da')
|
| 143 |
+
print("Monkey-Patching Sage Attention")
|
| 144 |
+
set_sage_attn_wan(pipe.transformer, sageattn)
|
| 145 |
+
set_sage_attn_wan(pipe.transformer_2, sageattn)
|
| 146 |
+
def resize_image(image: Image.Image) -> Image.Image:
|
| 147 |
+
"""
|
| 148 |
+
Resizes an image to fit within the model's constraints, preserving aspect ratio as much as possible.
|
| 149 |
+
"""
|
| 150 |
+
width, height = image.size
|
| 151 |
+
|
| 152 |
+
# Handle square case
|
| 153 |
+
if width == height:
|
| 154 |
+
return image.resize((SQUARE_DIM, SQUARE_DIM), Image.LANCZOS)
|
| 155 |
+
|
| 156 |
+
aspect_ratio = width / height
|
| 157 |
+
|
| 158 |
+
MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
|
| 159 |
+
MIN_ASPECT_RATIO = MIN_DIM / MAX_DIM
|
| 160 |
+
|
| 161 |
+
image_to_resize = image
|
| 162 |
+
|
| 163 |
+
if aspect_ratio > MAX_ASPECT_RATIO:
|
| 164 |
+
# Very wide image -> crop width to fit 832x480 aspect ratio
|
| 165 |
+
target_w, target_h = MAX_DIM, MIN_DIM
|
| 166 |
+
crop_width = int(round(height * MAX_ASPECT_RATIO))
|
| 167 |
+
left = (width - crop_width) // 2
|
| 168 |
+
image_to_resize = image.crop((left, 0, left + crop_width, height))
|
| 169 |
+
elif aspect_ratio < MIN_ASPECT_RATIO:
|
| 170 |
+
# Very tall image -> crop height to fit 480x832 aspect ratio
|
| 171 |
+
target_w, target_h = MIN_DIM, MAX_DIM
|
| 172 |
+
crop_height = int(round(width / MIN_ASPECT_RATIO))
|
| 173 |
+
top = (height - crop_height) // 2
|
| 174 |
+
image_to_resize = image.crop((0, top, width, top + crop_height))
|
| 175 |
+
else:
|
| 176 |
+
if width > height: # Landscape
|
| 177 |
+
target_w = MAX_DIM
|
| 178 |
+
target_h = int(round(target_w / aspect_ratio))
|
| 179 |
+
else: # Portrait
|
| 180 |
+
target_h = MAX_DIM
|
| 181 |
+
target_w = int(round(target_h * aspect_ratio))
|
| 182 |
+
|
| 183 |
+
final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
|
| 184 |
+
final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
|
| 185 |
+
|
| 186 |
+
final_w = max(MIN_DIM, min(MAX_DIM, final_w))
|
| 187 |
+
final_h = max(MIN_DIM, min(MAX_DIM, final_h))
|
| 188 |
+
|
| 189 |
+
return image_to_resize.resize((final_w, final_h), Image.LANCZOS)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def get_num_frames(duration_seconds: float):
|
| 193 |
+
return 1 + int(np.clip(
|
| 194 |
+
int(round(duration_seconds * FIXED_FPS)),
|
| 195 |
+
MIN_FRAMES_MODEL,
|
| 196 |
+
MAX_FRAMES_MODEL,
|
| 197 |
+
))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def to_ds(
|
| 201 |
+
*,
|
| 202 |
+
video_path: str,
|
| 203 |
+
original_image_path: str,
|
| 204 |
+
original_image_name: str,
|
| 205 |
+
prompt: str,
|
| 206 |
+
negative_prompt: str,
|
| 207 |
+
duration_seconds: float,
|
| 208 |
+
steps: int,
|
| 209 |
+
guidance_scale: float,
|
| 210 |
+
guidance_scale_2: float,
|
| 211 |
+
seed: int,
|
| 212 |
+
output_width: int,
|
| 213 |
+
output_height: int,
|
| 214 |
+
):
|
| 215 |
+
if hf_api is None:
|
| 216 |
+
print("cannot complete operation.")
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
timestamp = datetime.now()
|
| 220 |
+
folder = timestamp.strftime("%m/%d")
|
| 221 |
+
stem = timestamp.strftime("%H%M%S-%f")
|
| 222 |
+
unique_suffix = uuid4().hex[:8]
|
| 223 |
+
base_name = f"{stem}-{unique_suffix}"
|
| 224 |
+
video_repo_path = f"{folder}/{base_name}.mp4"
|
| 225 |
+
image_repo_path = f"{folder}/{base_name}.png"
|
| 226 |
+
text_repo_path = f"{folder}/{base_name}.txt"
|
| 227 |
+
|
| 228 |
+
metadata = "\n".join([
|
| 229 |
+
f"timestamp={timestamp.isoformat()}",
|
| 230 |
+
f"original_image_name={original_image_name}",
|
| 231 |
+
f"prompt={prompt}",
|
| 232 |
+
f"negative_prompt={negative_prompt}",
|
| 233 |
+
f"steps={steps}",
|
| 234 |
+
f"duration_seconds={duration_seconds}",
|
| 235 |
+
f"guidance_scale={guidance_scale}",
|
| 236 |
+
f"guidance_scale_2={guidance_scale_2}",
|
| 237 |
+
f"seed={seed}",
|
| 238 |
+
f"resolution={output_width}x{output_height}",
|
| 239 |
+
f"fps={FIXED_FPS}",
|
| 240 |
+
])
|
| 241 |
+
|
| 242 |
+
try:
|
| 243 |
+
hf_api.create_commit(
|
| 244 |
+
repo_id=DS_ID,
|
| 245 |
+
repo_type="dataset",
|
| 246 |
+
commit_message=f"Add generation {base_name}",
|
| 247 |
+
operations=[
|
| 248 |
+
CommitOperationAdd(
|
| 249 |
+
path_in_repo=video_repo_path,
|
| 250 |
+
path_or_fileobj=video_path,
|
| 251 |
+
),
|
| 252 |
+
CommitOperationAdd(
|
| 253 |
+
path_in_repo=image_repo_path,
|
| 254 |
+
path_or_fileobj=original_image_path,
|
| 255 |
+
),
|
| 256 |
+
CommitOperationAdd(
|
| 257 |
+
path_in_repo=text_repo_path,
|
| 258 |
+
path_or_fileobj=metadata.encode("utf-8"),
|
| 259 |
+
),
|
| 260 |
+
],
|
| 261 |
+
)
|
| 262 |
+
print(f"{DS_ID}:{video_repo_path}")
|
| 263 |
+
print(f"{DS_ID}:{image_repo_path}")
|
| 264 |
+
print(f"{DS_ID}:{text_repo_path}")
|
| 265 |
+
except Exception as exc:
|
| 266 |
+
print(f"failed: {exc}")
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def load_input_image(image_path: str) -> Image.Image:
|
| 270 |
+
if not image_path:
|
| 271 |
+
raise gr.Error("Please upload an input image.")
|
| 272 |
+
with Image.open(image_path) as image:
|
| 273 |
+
return image.convert("RGB")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def get_duration(
|
| 277 |
+
input_image,
|
| 278 |
+
prompt,
|
| 279 |
+
steps,
|
| 280 |
+
negative_prompt,
|
| 281 |
+
duration_seconds,
|
| 282 |
+
guidance_scale,
|
| 283 |
+
guidance_scale_2,
|
| 284 |
+
seed,
|
| 285 |
+
randomize_seed,
|
| 286 |
+
access_granted,
|
| 287 |
+
request,
|
| 288 |
+
progress,
|
| 289 |
+
):
|
| 290 |
+
if _is_denied_ip(request):
|
| 291 |
+
return 1
|
| 292 |
+
|
| 293 |
+
BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 624
|
| 294 |
+
BASE_STEP_DURATION = 15
|
| 295 |
+
image = load_input_image(input_image)
|
| 296 |
+
width, height = resize_image(image).size
|
| 297 |
+
frames = get_num_frames(duration_seconds)
|
| 298 |
+
factor = frames * width * height / BASE_FRAMES_HEIGHT_WIDTH
|
| 299 |
+
step_duration = BASE_STEP_DURATION * factor ** 1.5
|
| 300 |
+
# Keep duration estimates conservative to avoid ZeroGPU task aborts right after inference.
|
| 301 |
+
return int(steps) * step_duration + POSTPROCESS_OVERHEAD_SECONDS
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def get_original_image_name(image_path: str) -> str:
|
| 305 |
+
if not image_path:
|
| 306 |
+
return "unknown"
|
| 307 |
+
return os.path.basename(image_path)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def get_original_media_stem(media_path: str) -> str:
|
| 311 |
+
if not media_path:
|
| 312 |
+
return "generated-video"
|
| 313 |
+
media_name = os.path.basename(media_path)
|
| 314 |
+
media_stem, _ = os.path.splitext(media_name)
|
| 315 |
+
media_stem = media_stem.strip()
|
| 316 |
+
return media_stem or "generated-video"
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def build_download_video(video_path: str, original_media_path: str) -> str:
|
| 320 |
+
download_dir = tempfile.mkdtemp(prefix="wan22-download-")
|
| 321 |
+
download_filename = f"{get_original_media_stem(original_media_path)}.mp4"
|
| 322 |
+
download_path = os.path.join(download_dir, download_filename)
|
| 323 |
+
shutil.copyfile(video_path, download_path)
|
| 324 |
+
return download_path
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def export_to_video_h264(frames, output_path: str, fps: int = FIXED_FPS) -> None:
|
| 328 |
+
"""
|
| 329 |
+
Export frames to an H.264 MP4 compatible with mobile browsers/players.
|
| 330 |
+
"""
|
| 331 |
+
if len(frames) == 0:
|
| 332 |
+
raise ValueError("No frames to export.")
|
| 333 |
+
|
| 334 |
+
normalized_frames = []
|
| 335 |
+
for frame in frames:
|
| 336 |
+
if isinstance(frame, Image.Image):
|
| 337 |
+
arr = np.array(frame)
|
| 338 |
+
else:
|
| 339 |
+
arr = np.asarray(frame)
|
| 340 |
+
|
| 341 |
+
if arr.ndim == 2:
|
| 342 |
+
arr = np.stack([arr, arr, arr], axis=-1)
|
| 343 |
+
elif arr.ndim == 3 and arr.shape[2] == 4:
|
| 344 |
+
arr = arr[:, :, :3]
|
| 345 |
+
|
| 346 |
+
if arr.ndim != 3 or arr.shape[2] != 3:
|
| 347 |
+
raise ValueError(f"Unsupported frame shape: {arr.shape}")
|
| 348 |
+
|
| 349 |
+
if arr.dtype != np.uint8:
|
| 350 |
+
if np.issubdtype(arr.dtype, np.floating):
|
| 351 |
+
max_val = float(np.nanmax(arr)) if arr.size else 1.0
|
| 352 |
+
if max_val <= 1.0:
|
| 353 |
+
arr = arr * 255.0
|
| 354 |
+
arr = np.clip(arr, 0, 255).astype(np.uint8)
|
| 355 |
+
|
| 356 |
+
normalized_frames.append(arr)
|
| 357 |
+
|
| 358 |
+
height, width = normalized_frames[0].shape[:2]
|
| 359 |
+
ffmpeg_params = [
|
| 360 |
+
"-movflags",
|
| 361 |
+
"+faststart",
|
| 362 |
+
"-profile:v",
|
| 363 |
+
"baseline",
|
| 364 |
+
"-level",
|
| 365 |
+
"3.1",
|
| 366 |
+
]
|
| 367 |
+
|
| 368 |
+
with imageio.get_writer(
|
| 369 |
+
output_path,
|
| 370 |
+
format="FFMPEG",
|
| 371 |
+
mode="I",
|
| 372 |
+
fps=fps,
|
| 373 |
+
codec="libx264",
|
| 374 |
+
pixelformat="yuv420p",
|
| 375 |
+
ffmpeg_params=ffmpeg_params,
|
| 376 |
+
) as writer:
|
| 377 |
+
for frame in normalized_frames:
|
| 378 |
+
if frame.shape[:2] != (height, width):
|
| 379 |
+
frame = np.array(
|
| 380 |
+
Image.fromarray(frame).resize((width, height), Image.LANCZOS)
|
| 381 |
+
)
|
| 382 |
+
writer.append_data(frame)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _request_headers(request: gr.Request | None) -> dict[str, str]:
|
| 386 |
+
if request is None or not getattr(request, "headers", None):
|
| 387 |
+
return {}
|
| 388 |
+
return {str(key).lower(): str(value) for key, value in request.headers.items()}
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def _first_header_value(headers: dict[str, str], names: tuple[str, ...]) -> str:
|
| 392 |
+
for name in names:
|
| 393 |
+
value = headers.get(name)
|
| 394 |
+
if value:
|
| 395 |
+
return value
|
| 396 |
+
return ""
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _client_ip(request: gr.Request | None) -> str:
|
| 400 |
+
headers = _request_headers(request)
|
| 401 |
+
forwarded_for = headers.get("x-forwarded-for", "")
|
| 402 |
+
if forwarded_for:
|
| 403 |
+
return forwarded_for.split(",", 1)[0].strip()
|
| 404 |
+
|
| 405 |
+
direct_ip = _first_header_value(headers, ("cf-connecting-ip", "x-real-ip"))
|
| 406 |
+
if direct_ip:
|
| 407 |
+
return direct_ip.strip()
|
| 408 |
+
|
| 409 |
+
client = getattr(request, "client", None)
|
| 410 |
+
return str(getattr(client, "host", "") or "").strip()
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _is_denied_cidr(client_ip: str) -> bool:
|
| 414 |
+
if DENIED_IP_NETWORKS and client_ip:
|
| 415 |
+
try:
|
| 416 |
+
ip = ipaddress.ip_address(client_ip)
|
| 417 |
+
except ValueError:
|
| 418 |
+
return False
|
| 419 |
+
return any(ip in network for network in DENIED_IP_NETWORKS)
|
| 420 |
+
|
| 421 |
+
return False
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def _lookup_ip_region(client_ip: str) -> dict:
|
| 425 |
+
if not client_ip:
|
| 426 |
+
return {}
|
| 427 |
+
if client_ip in IP_GEO_CACHE:
|
| 428 |
+
return IP_GEO_CACHE[client_ip]
|
| 429 |
+
|
| 430 |
+
try:
|
| 431 |
+
with urllib.request.urlopen(IP_API_URL.format(ip=client_ip), timeout=3) as response:
|
| 432 |
+
data = json.loads(response.read().decode("utf-8"))
|
| 433 |
+
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
|
| 434 |
+
data = {
|
| 435 |
+
"status": "fail",
|
| 436 |
+
"message": str(exc),
|
| 437 |
+
"query": client_ip,
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
IP_GEO_CACHE[client_ip] = data
|
| 441 |
+
return data
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _is_denied_ip(request: gr.Request | None) -> bool:
|
| 445 |
+
client_ip = _client_ip(request)
|
| 446 |
+
if _is_denied_cidr(client_ip):
|
| 447 |
+
print(f"Access check: ip={client_ip} country=unknown region=denied-cidr regionName=denied-cidr")
|
| 448 |
+
return True
|
| 449 |
+
|
| 450 |
+
geo = _lookup_ip_region(client_ip)
|
| 451 |
+
country_code = str(geo.get("countryCode", "")).upper()
|
| 452 |
+
region_code = str(geo.get("region", "")).upper()
|
| 453 |
+
region_name = str(geo.get("regionName", "")).upper()
|
| 454 |
+
status = str(geo.get("status", "unknown"))
|
| 455 |
+
message = str(geo.get("message", ""))
|
| 456 |
+
print(
|
| 457 |
+
"Access check: "
|
| 458 |
+
f"ip={client_ip or 'unknown'} "
|
| 459 |
+
f"status={status} "
|
| 460 |
+
f"country={country_code or 'unknown'} "
|
| 461 |
+
f"region={region_code or 'unknown'} "
|
| 462 |
+
f"regionName={region_name or 'unknown'} "
|
| 463 |
+
f"message={message or 'none'}"
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
return (
|
| 467 |
+
country_code == "US"
|
| 468 |
+
and (
|
| 469 |
+
region_code in DENIED_US_REGION_CODES
|
| 470 |
+
or region_name in DENIED_US_REGION_NAMES
|
| 471 |
+
)
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _assert_accessible_region(request: gr.Request | None) -> None:
|
| 476 |
+
if _is_denied_ip(request):
|
| 477 |
+
raise gr.Error("Access is not available from your current network location.")
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def reset_verification(request: gr.Request = None):
|
| 481 |
+
if _is_denied_ip(request):
|
| 482 |
+
return (
|
| 483 |
+
gr.update(value="Generation Unavailable", interactive=False),
|
| 484 |
+
"Access is not available from your current network location.",
|
| 485 |
+
False,
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
if PUBLIC_ENABLED:
|
| 489 |
+
return (
|
| 490 |
+
gr.update(value="Generate Video", interactive=True),
|
| 491 |
+
"Public generation is enabled.",
|
| 492 |
+
True,
|
| 493 |
+
)
|
| 494 |
+
return (
|
| 495 |
+
gr.update(value="Verify Passcode to Enable Generation", interactive=False),
|
| 496 |
+
"Enter the passcode and click Verify to unlock generation.",
|
| 497 |
+
False,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def verify_passcode(passcode: str, request: gr.Request = None):
|
| 502 |
+
if _is_denied_ip(request):
|
| 503 |
+
return (
|
| 504 |
+
gr.update(value="Generation Unavailable", interactive=False),
|
| 505 |
+
"Access is not available from your current network location.",
|
| 506 |
+
False,
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
if PUBLIC_ENABLED:
|
| 510 |
+
return (
|
| 511 |
+
gr.update(value="Generate Video", interactive=True),
|
| 512 |
+
"Public generation is enabled.",
|
| 513 |
+
True,
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
secret = GENERATION_SECRET or ""
|
| 517 |
+
candidate = (passcode or "").strip()
|
| 518 |
+
|
| 519 |
+
if not secret:
|
| 520 |
+
return (
|
| 521 |
+
gr.update(value="Verify Passcode to Enable Generation", interactive=False),
|
| 522 |
+
"Generation is unavailable because `GENERATION_SECRET` is not configured.",
|
| 523 |
+
False,
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
if hmac.compare_digest(candidate, secret):
|
| 527 |
+
return (
|
| 528 |
+
gr.update(value="Generate Video", interactive=True),
|
| 529 |
+
"Passcode verified. Generation unlocked.",
|
| 530 |
+
True,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
return (
|
| 534 |
+
gr.update(value="Verify Passcode to Enable Generation", interactive=False),
|
| 535 |
+
"Incorrect passcode.",
|
| 536 |
+
False,
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@spaces.GPU(size="xlarge", duration=get_duration)
|
| 541 |
+
def generate_video(
|
| 542 |
+
input_image,
|
| 543 |
+
prompt,
|
| 544 |
+
steps = 6,
|
| 545 |
+
negative_prompt=default_negative_prompt,
|
| 546 |
+
duration_seconds = 5.0,
|
| 547 |
+
guidance_scale = 1,
|
| 548 |
+
guidance_scale_2 = 1,
|
| 549 |
+
seed = 696969696,
|
| 550 |
+
randomize_seed = False,
|
| 551 |
+
access_granted = True,
|
| 552 |
+
request: gr.Request = None,
|
| 553 |
+
progress=gr.Progress(track_tqdm=True),
|
| 554 |
+
):
|
| 555 |
+
"""
|
| 556 |
+
Generate a video from an input image using the Wan 2.2 14B I2V model with Lightning LoRA.
|
| 557 |
+
|
| 558 |
+
This function takes an input image and generates a video animation based on the provided
|
| 559 |
+
prompt and parameters. It uses an FP8 qunatized Wan 2.2 14B Image-to-Video model in with Lightning LoRA
|
| 560 |
+
for fast generation in 4-8 steps.
|
| 561 |
+
|
| 562 |
+
Args:
|
| 563 |
+
input_image (str): Filepath to the input image to animate. Will be loaded and resized to target dimensions.
|
| 564 |
+
prompt (str): Text prompt describing the desired animation or motion.
|
| 565 |
+
steps (int, optional): Number of inference steps. More steps = higher quality but slower.
|
| 566 |
+
Defaults to 4. Range: 1-30.
|
| 567 |
+
negative_prompt (str, optional): Negative prompt to avoid unwanted elements.
|
| 568 |
+
Defaults to default_negative_prompt (contains unwanted visual artifacts).
|
| 569 |
+
duration_seconds (float, optional): Duration of the generated video in seconds.
|
| 570 |
+
Defaults to 2. Clamped between MIN_FRAMES_MODEL/FIXED_FPS and MAX_FRAMES_MODEL/FIXED_FPS.
|
| 571 |
+
guidance_scale (float, optional): Controls adherence to the prompt. Higher values = more adherence.
|
| 572 |
+
Defaults to 1.0. Range: 0.0-20.0.
|
| 573 |
+
guidance_scale_2 (float, optional): Controls adherence to the prompt. Higher values = more adherence.
|
| 574 |
+
Defaults to 1.0. Range: 0.0-20.0.
|
| 575 |
+
seed (int, optional): Random seed for reproducible results. Defaults to 42.
|
| 576 |
+
Range: 0 to MAX_SEED (2147483647).
|
| 577 |
+
randomize_seed (bool, optional): Whether to use a random seed instead of the provided seed.
|
| 578 |
+
Defaults to False.
|
| 579 |
+
progress (gr.Progress, optional): Gradio progress tracker. Defaults to gr.Progress(track_tqdm=True).
|
| 580 |
+
|
| 581 |
+
Returns:
|
| 582 |
+
tuple: A tuple containing:
|
| 583 |
+
- video_path (str): Path to the generated video file (.mp4)
|
| 584 |
+
- current_seed (int): The seed used for generation (useful when randomize_seed=True)
|
| 585 |
+
|
| 586 |
+
Raises:
|
| 587 |
+
gr.Error: If input_image is None (no image uploaded).
|
| 588 |
+
|
| 589 |
+
Note:
|
| 590 |
+
- Frame count is calculated as duration_seconds * FIXED_FPS (24)
|
| 591 |
+
- Output dimensions are adjusted to be multiples of MOD_VALUE (32)
|
| 592 |
+
- The function uses GPU acceleration via the @spaces.GPU decorator
|
| 593 |
+
- Generation time varies based on steps and duration (see get_duration function)
|
| 594 |
+
"""
|
| 595 |
+
_assert_accessible_region(request)
|
| 596 |
+
|
| 597 |
+
if not access_granted:
|
| 598 |
+
raise gr.Error("Please verify the passcode before generating.")
|
| 599 |
+
|
| 600 |
+
if input_image is None:
|
| 601 |
+
raise gr.Error("Please upload an input image.")
|
| 602 |
+
torch.cuda.synchronize()
|
| 603 |
+
|
| 604 |
+
start_time = time.perf_counter()
|
| 605 |
+
num_frames = get_num_frames(duration_seconds)
|
| 606 |
+
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 607 |
+
input_image_path = input_image
|
| 608 |
+
input_image = load_input_image(input_image_path)
|
| 609 |
+
resized_image = resize_image(input_image)
|
| 610 |
+
|
| 611 |
+
output_frames_list = pipe(
|
| 612 |
+
image=resized_image,
|
| 613 |
+
prompt=prompt,
|
| 614 |
+
negative_prompt=negative_prompt,
|
| 615 |
+
height=resized_image.height,
|
| 616 |
+
width=resized_image.width,
|
| 617 |
+
num_frames=num_frames,
|
| 618 |
+
guidance_scale=float(guidance_scale),
|
| 619 |
+
guidance_scale_2=float(guidance_scale_2),
|
| 620 |
+
num_inference_steps=int(steps),
|
| 621 |
+
generator=torch.Generator(device="cuda").manual_seed(current_seed),
|
| 622 |
+
output_type="np",
|
| 623 |
+
).frames[0]
|
| 624 |
+
|
| 625 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
|
| 626 |
+
video_path = tmpfile.name
|
| 627 |
+
|
| 628 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
|
| 629 |
+
original_image_upload_path = tmpfile.name
|
| 630 |
+
|
| 631 |
+
input_image.save(original_image_upload_path, format="PNG")
|
| 632 |
+
export_to_video_h264(output_frames_list, video_path, fps=FIXED_FPS)
|
| 633 |
+
try:
|
| 634 |
+
to_ds(
|
| 635 |
+
video_path=video_path,
|
| 636 |
+
original_image_path=original_image_upload_path,
|
| 637 |
+
original_image_name=get_original_image_name(input_image_path),
|
| 638 |
+
prompt=prompt if prompt is not None else default_prompt_i2v,
|
| 639 |
+
negative_prompt=negative_prompt if negative_prompt is not None else default_negative_prompt,
|
| 640 |
+
duration_seconds=float(duration_seconds) if duration_seconds is not None else MAX_DURATION,
|
| 641 |
+
steps=int(steps) if steps is not None else 6,
|
| 642 |
+
guidance_scale=float(guidance_scale) if guidance_scale is not None else 1,
|
| 643 |
+
guidance_scale_2=float(guidance_scale_2) if guidance_scale_2 is not None else 1,
|
| 644 |
+
seed=current_seed if current_seed is not None else 42,
|
| 645 |
+
output_width=resized_image.width if resized_image.width is not None else 832,
|
| 646 |
+
output_height=resized_image.height if resized_image.height is not None else 480,
|
| 647 |
+
)
|
| 648 |
+
finally:
|
| 649 |
+
if os.path.exists(original_image_upload_path):
|
| 650 |
+
os.remove(original_image_upload_path)
|
| 651 |
+
|
| 652 |
+
elapsed_seconds = time.perf_counter() - start_time
|
| 653 |
+
render_message = f"Generated in {elapsed_seconds:.1f} seconds."
|
| 654 |
+
download_path = build_download_video(video_path, input_image_path)
|
| 655 |
+
|
| 656 |
+
return video_path, current_seed, render_message, download_path
|
| 657 |
+
|
| 658 |
+
custom_css = """
|
| 659 |
+
.gradio-container {
|
| 660 |
+
max-width: 1180px !important;
|
| 661 |
+
margin: 0 auto !important;
|
| 662 |
+
background:
|
| 663 |
+
radial-gradient(circle at 10% 20%, rgba(124, 58, 237, 0.2), transparent 35%),
|
| 664 |
+
radial-gradient(circle at 90% 10%, rgba(14, 165, 233, 0.15), transparent 30%),
|
| 665 |
+
linear-gradient(180deg, #070b1a 0%, #0f172a 100%);
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
#hero-card {
|
| 669 |
+
border-radius: 18px;
|
| 670 |
+
border: 1px solid rgba(255, 255, 255, 0.12);
|
| 671 |
+
background: linear-gradient(130deg, rgba(76, 29, 149, 0.9), rgba(30, 64, 175, 0.9));
|
| 672 |
+
padding: 16px 20px;
|
| 673 |
+
box-shadow: 0 18px 45px rgba(10, 10, 20, 0.35);
|
| 674 |
+
margin-bottom: 10px;
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
#hero-card h1 {
|
| 678 |
+
margin: 0 0 6px 0;
|
| 679 |
+
font-size: 1.9rem;
|
| 680 |
+
line-height: 1.1;
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
#hero-card p {
|
| 684 |
+
margin: 0;
|
| 685 |
+
opacity: 0.95;
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
#control-panel,
|
| 689 |
+
#preview-panel {
|
| 690 |
+
border-radius: 16px;
|
| 691 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 692 |
+
background: rgba(15, 23, 42, 0.72);
|
| 693 |
+
backdrop-filter: blur(6px);
|
| 694 |
+
padding: 16px;
|
| 695 |
+
box-shadow: 0 14px 35px rgba(0, 0, 0, 0.22);
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
#generated-video {
|
| 699 |
+
min-height: 500px;
|
| 700 |
+
}
|
| 701 |
+
|
| 702 |
+
#generate-button {
|
| 703 |
+
min-height: 48px;
|
| 704 |
+
font-weight: 700;
|
| 705 |
+
letter-spacing: 0.2px;
|
| 706 |
+
}
|
| 707 |
+
|
| 708 |
+
.status-note {
|
| 709 |
+
margin-top: 8px;
|
| 710 |
+
padding: 10px 12px;
|
| 711 |
+
font-size: 1rem;
|
| 712 |
+
border-radius: 10px;
|
| 713 |
+
border: 1px solid rgba(255, 255, 255, 0.16);
|
| 714 |
+
background: rgba(15, 118, 110, 0.2);
|
| 715 |
+
}
|
| 716 |
+
"""
|
| 717 |
+
|
| 718 |
+
theme = gr.themes.Soft(
|
| 719 |
+
primary_hue=gr.themes.colors.violet,
|
| 720 |
+
secondary_hue=gr.themes.colors.cyan,
|
| 721 |
+
neutral_hue=gr.themes.colors.slate,
|
| 722 |
+
).set(
|
| 723 |
+
body_background_fill="#050816",
|
| 724 |
+
block_background_fill="#111827",
|
| 725 |
+
block_border_width="1px",
|
| 726 |
+
block_title_text_weight="700",
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
with gr.Blocks() as demo:
|
| 730 |
+
gr.HTML(
|
| 731 |
+
"""
|
| 732 |
+
<div id="hero-card">
|
| 733 |
+
<h1>Wan2.2 I2V + I2Pee-5.5XL Faster</h1>
|
| 734 |
+
</div>
|
| 735 |
+
"""
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
if PUBLIC_ENABLED:
|
| 739 |
+
access_copy = (
|
| 740 |
+
"Updated: 1.5x speed boost and massive quality increase! FREE TO ALL FOR A LIMITED TIME!"
|
| 741 |
+
"Subscribers on <a href='https://ko-fi.com/obsxrver' target='_blank'>ko-fi</a> unlock permanent generation access "
|
| 742 |
+
"and can download the I2Pee-5XL LoRA."
|
| 743 |
+
)
|
| 744 |
+
else:
|
| 745 |
+
access_copy = (
|
| 746 |
+
"Insiders-only mode. 🔒"
|
| 747 |
+
"Public access is disabled. 🔑 Become an insider on <a href='https://ko-fi.com/obsxrver' target='_blank'>ko-fi</a> to unlock generation access and download the I2Pee-5.5XL LoRA."
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
gr.HTML(f"<div class='status-note'>{access_copy}</div>")
|
| 751 |
+
gr.Markdown("### Join the discord: [discord.gg/8wMr2mmaRF](https://discord.gg/8wMr2mmaRF)")
|
| 752 |
+
|
| 753 |
+
with gr.Row(equal_height=True):
|
| 754 |
+
with gr.Column(elem_id="control-panel", scale=5):
|
| 755 |
+
gr.Markdown("### Input + Prompt Controls")
|
| 756 |
+
input_image_component = gr.Image(type="filepath", label="Input Image")
|
| 757 |
+
verification_state = gr.State(PUBLIC_ENABLED)
|
| 758 |
+
passcode_input = gr.Textbox(
|
| 759 |
+
label="Passcode",
|
| 760 |
+
type="password",
|
| 761 |
+
placeholder="Enter passcode to unlock generation",
|
| 762 |
+
visible=not PUBLIC_ENABLED,
|
| 763 |
+
)
|
| 764 |
+
verify_button = gr.Button("Verify Access", variant="secondary", visible=not PUBLIC_ENABLED)
|
| 765 |
+
verification_status = gr.Markdown(
|
| 766 |
+
"Public generation is enabled."
|
| 767 |
+
if PUBLIC_ENABLED
|
| 768 |
+
else "Insiders: Find the passcode in 🔒#hf-space-access-code on the [discord server](https://discord.gg/8wMr2mmaRF)."
|
| 769 |
+
)
|
| 770 |
+
prompt_input = gr.Textbox(
|
| 771 |
+
label="Prompt",
|
| 772 |
+
value=default_prompt_i2v,
|
| 773 |
+
lines=4,
|
| 774 |
+
placeholder="Describe the motion or scene transition you want to animate..."
|
| 775 |
+
)
|
| 776 |
+
duration_seconds_input = gr.Slider(
|
| 777 |
+
minimum=MIN_DURATION,
|
| 778 |
+
maximum=MAX_DURATION,
|
| 779 |
+
step=0.1,
|
| 780 |
+
value=4.0,
|
| 781 |
+
label="Duration (seconds)",
|
| 782 |
+
info=f"Clamped to {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.",
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 786 |
+
negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=4)
|
| 787 |
+
seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=696969696, interactive=True)
|
| 788 |
+
randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
|
| 789 |
+
steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=6, label="Inference Steps", interactive=True)
|
| 790 |
+
guidance_scale_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale (high noise stage)", interactive=True)
|
| 791 |
+
guidance_scale_2_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale 2 (low noise stage)", interactive=True)
|
| 792 |
+
|
| 793 |
+
generate_button = gr.Button(
|
| 794 |
+
"Generate Video",
|
| 795 |
+
variant="primary",
|
| 796 |
+
interactive=PUBLIC_ENABLED,
|
| 797 |
+
elem_id="generate-button",
|
| 798 |
+
)
|
| 799 |
+
with gr.Column(elem_id="preview-panel", scale=5):
|
| 800 |
+
gr.Markdown("### Render Preview")
|
| 801 |
+
video_output = gr.Video(
|
| 802 |
+
label="Generated Video",
|
| 803 |
+
autoplay=True,
|
| 804 |
+
sources=["upload"],
|
| 805 |
+
interactive=False,
|
| 806 |
+
elem_id="generated-video",
|
| 807 |
+
)
|
| 808 |
+
render_status = gr.Markdown("")
|
| 809 |
+
file_output = gr.File(label="Download Video")
|
| 810 |
+
|
| 811 |
+
ui_inputs = [
|
| 812 |
+
input_image_component, prompt_input, steps_slider,
|
| 813 |
+
negative_prompt_input, duration_seconds_input,
|
| 814 |
+
guidance_scale_input, guidance_scale_2_input, seed_input, randomize_seed_checkbox,
|
| 815 |
+
verification_state,
|
| 816 |
+
]
|
| 817 |
+
demo.load(
|
| 818 |
+
fn=reset_verification,
|
| 819 |
+
outputs=[generate_button, verification_status, verification_state],
|
| 820 |
+
)
|
| 821 |
+
passcode_input.change(
|
| 822 |
+
fn=reset_verification,
|
| 823 |
+
outputs=[generate_button, verification_status, verification_state],
|
| 824 |
+
)
|
| 825 |
+
verify_button.click(
|
| 826 |
+
fn=verify_passcode,
|
| 827 |
+
inputs=[passcode_input],
|
| 828 |
+
outputs=[generate_button, verification_status, verification_state],
|
| 829 |
+
)
|
| 830 |
+
generate_button.click(
|
| 831 |
+
fn=generate_video,
|
| 832 |
+
inputs=ui_inputs,
|
| 833 |
+
outputs=[video_output, seed_input, render_status, file_output],
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
gr.Examples(
|
| 837 |
+
examples=[
|
| 838 |
+
[
|
| 839 |
+
"examples/example_10.png",
|
| 840 |
+
"jumpcut to the young woman on the left, who is sitting on a toilet with her legs spread wide, touching her pussy. Her discarded outfit in a pile on the floor. The words \"I luv Pee\" and hearts are written in black marker across her torso and legs. She stares directly into the camera with a smile on her face. The nude man on the left stands next to her, his penis in his hand. The man is filled with confidence, while the woman's posture appears giggling and happy, she is rubbing her pussy while the man is pissing all over her face. The scene focuses on the stream of piss hitting the woman's face. the real splash as the liquid soaks the woman's hair, and the woman's expression as she continues staring directly into the camera in laughter. The woman's identity remains the exact same, retain identical facial features and body shape. same face, good body drawing, wet pussy, realistic fluid, high-definition graphics.",
|
| 841 |
+
6,
|
| 842 |
+
],
|
| 843 |
+
[
|
| 844 |
+
"examples/example_9.png",
|
| 845 |
+
"jumpcut to the young woman on the left, who is sitting on a bed in a dimly lit bedroom with her legs spread wide. Her discarded outfit in a pile on the bed. The words “sex toy” and hearts are scrawled in black permanent marker across her torso and thighs. She stares directly into the camera with a smile on her face. The naked man on the right stands next to her, his huge penis deep inside her pussy, one hand gripping her raised leg. He smiles as he looks down at her. The man's gaze is filled with confidence and a sense of dominance, while the woman's posture appears happy and submissive. The man continues to thrust his penis in and out of her pussy. The footage emphasizes the physical nature of the act: the rhythmic thrusting during deep penetration, and the woman’s moaning expression as she stares toward the camera. At the end of the video, the man’s penis withdraws, and white thick sticky cum coats her genitals. Her genitals are covered in white thick sticky cum. The woman's identity remains the exact same, retain identical facial features and body shape. same face, good body drawing, wet pussy, realistic, high-definition graphics.",
|
| 846 |
+
6,
|
| 847 |
+
],
|
| 848 |
+
[
|
| 849 |
+
"examples/example_6.jpg",
|
| 850 |
+
"a woman, jumpcut, after the transition, she is nude, the woman is straddling a nude man, the man is lying down and holding the woman by her sides, the man's penis is inside the woman's pussy, she is moaning and bouncing on his penis",
|
| 851 |
+
6,
|
| 852 |
+
],
|
| 853 |
+
[
|
| 854 |
+
"examples/example_2.jpg",
|
| 855 |
+
"a woman, jumpcut, after the transition, the woman is nude, lying on a bed on her stomach with her hands gripping the bed in front of her, a nude man is standing in front of the woman with his penis inside her mouth, he is holding her head with his right hand with his left hand at his side, the man is pissing in the woman's mouth while his penis is inside her mouth, piss spills out of her mouth and drips onto the bed",
|
| 856 |
+
6,
|
| 857 |
+
],
|
| 858 |
+
[
|
| 859 |
+
"examples/example_8.jpg",
|
| 860 |
+
"a woman, jumpcut, after the transition, the woman is nude,looking at the camera, bent over a table, a nude man is standing in front her and holding her head with his left hand with his right hand at his side, his penis is inside the woman's mouth, another nude man is standing behind the woman and holding her waist with his penis inside the woman's ass",
|
| 861 |
+
6,
|
| 862 |
+
],
|
| 863 |
+
[
|
| 864 |
+
"examples/example_5.png",
|
| 865 |
+
"a man and a woman, jumpcut, after the transition, the woman is nude on a table on her hands and knees with her mouth open, the man is nude standing behind the woman holding her neck with both hands, the man's penis is inside the woman's ass, the man is looking down at her and smiling, he is thrusting his penis inside the woman's ass",
|
| 866 |
+
6,
|
| 867 |
+
],
|
| 868 |
+
[
|
| 869 |
+
"examples/example_1.png",
|
| 870 |
+
"a woman, jumpcut, after the transition, she is nude, she is sitting with her legs spread and looking at the camera, she is pissing on the floor",
|
| 871 |
+
6
|
| 872 |
+
],
|
| 873 |
+
],
|
| 874 |
+
inputs=[input_image_component, prompt_input, steps_slider],
|
| 875 |
+
outputs=[video_output, seed_input, render_status, file_output],
|
| 876 |
+
fn=generate_video,
|
| 877 |
+
cache_examples=True,
|
| 878 |
+
cache_mode="lazy",
|
| 879 |
+
)
|
| 880 |
+
gr.Markdown("*Content Warning:* This research demonstration may generate material that is not suitable for all audiences. By using this application, you agree to assume full responsibility for compliance with the platform's terms of service and any applicable legal and regulatory guidelines.")
|
| 881 |
+
if __name__ == "__main__":
|
| 882 |
+
demo.queue().launch(theme=theme, css=custom_css)
|
modify_model/modify_wan.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
from diffusers.models import WanTransformer3DModel
|
| 5 |
+
from diffusers.models.transformers.transformer_wan import WanAttention, _get_qkv_projections, _get_added_kv_projections
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SageWanAttnProcessor:
|
| 9 |
+
def __init__(self, attn_func):
|
| 10 |
+
self.attn_func = attn_func
|
| 11 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 12 |
+
raise ImportError(
|
| 13 |
+
"WanAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher."
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
def __call__(
|
| 17 |
+
self,
|
| 18 |
+
attn: "WanAttention",
|
| 19 |
+
hidden_states: torch.Tensor,
|
| 20 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 21 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 22 |
+
rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 23 |
+
) -> torch.Tensor:
|
| 24 |
+
encoder_hidden_states_img = None
|
| 25 |
+
if attn.add_k_proj is not None:
|
| 26 |
+
# 512 is the context length of the text encoder, hardcoded for now
|
| 27 |
+
image_context_length = encoder_hidden_states.shape[1] - 512
|
| 28 |
+
encoder_hidden_states_img = encoder_hidden_states[:, :image_context_length]
|
| 29 |
+
encoder_hidden_states = encoder_hidden_states[:, image_context_length:]
|
| 30 |
+
|
| 31 |
+
query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states)
|
| 32 |
+
|
| 33 |
+
query = attn.norm_q(query)
|
| 34 |
+
key = attn.norm_k(key)
|
| 35 |
+
|
| 36 |
+
query = query.unflatten(2, (attn.heads, -1))
|
| 37 |
+
key = key.unflatten(2, (attn.heads, -1))
|
| 38 |
+
value = value.unflatten(2, (attn.heads, -1))
|
| 39 |
+
|
| 40 |
+
if rotary_emb is not None:
|
| 41 |
+
|
| 42 |
+
def apply_rotary_emb(
|
| 43 |
+
hidden_states: torch.Tensor,
|
| 44 |
+
freqs_cos: torch.Tensor,
|
| 45 |
+
freqs_sin: torch.Tensor,
|
| 46 |
+
):
|
| 47 |
+
x1, x2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1)
|
| 48 |
+
cos = freqs_cos[..., 0::2]
|
| 49 |
+
sin = freqs_sin[..., 1::2]
|
| 50 |
+
out = torch.empty_like(hidden_states)
|
| 51 |
+
out[..., 0::2] = x1 * cos - x2 * sin
|
| 52 |
+
out[..., 1::2] = x1 * sin + x2 * cos
|
| 53 |
+
return out.type_as(hidden_states)
|
| 54 |
+
|
| 55 |
+
query = apply_rotary_emb(query, *rotary_emb)
|
| 56 |
+
key = apply_rotary_emb(key, *rotary_emb)
|
| 57 |
+
|
| 58 |
+
# ---- transpose to (B, H, N, D) for sageattn/sdpa ----
|
| 59 |
+
query = query.transpose(1, 2)
|
| 60 |
+
key = key.transpose(1, 2)
|
| 61 |
+
value = value.transpose(1, 2)
|
| 62 |
+
|
| 63 |
+
# I2V task
|
| 64 |
+
hidden_states_img = None
|
| 65 |
+
if encoder_hidden_states_img is not None:
|
| 66 |
+
key_img, value_img = _get_added_kv_projections(attn, encoder_hidden_states_img)
|
| 67 |
+
key_img = attn.norm_added_k(key_img)
|
| 68 |
+
|
| 69 |
+
key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
| 70 |
+
value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
| 71 |
+
|
| 72 |
+
hidden_states_img = self.attn_func(
|
| 73 |
+
query,
|
| 74 |
+
key_img,
|
| 75 |
+
value_img,
|
| 76 |
+
attn_mask=None,
|
| 77 |
+
dropout_p=0.0,
|
| 78 |
+
is_causal=False,
|
| 79 |
+
)
|
| 80 |
+
hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
|
| 81 |
+
hidden_states_img = hidden_states_img.type_as(query)
|
| 82 |
+
|
| 83 |
+
hidden_states = self.attn_func(
|
| 84 |
+
query,
|
| 85 |
+
key,
|
| 86 |
+
value,
|
| 87 |
+
attn_mask=attention_mask,
|
| 88 |
+
dropout_p=0.0,
|
| 89 |
+
is_causal=False,
|
| 90 |
+
)
|
| 91 |
+
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
|
| 92 |
+
hidden_states = hidden_states.type_as(query)
|
| 93 |
+
|
| 94 |
+
if hidden_states_img is not None:
|
| 95 |
+
hidden_states = hidden_states + hidden_states_img
|
| 96 |
+
|
| 97 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 98 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 99 |
+
return hidden_states
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def set_sage_attn_wan(
|
| 103 |
+
model: WanTransformer3DModel,
|
| 104 |
+
attn_func,
|
| 105 |
+
):
|
| 106 |
+
for idx, block in enumerate(model.blocks):
|
| 107 |
+
processor = SageWanAttnProcessor(attn_func)
|
| 108 |
+
block.attn1.processor = processor
|
requirements.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diffusers==0.37.0
|
| 2 |
+
transformers < 5
|
| 3 |
+
accelerate
|
| 4 |
+
safetensors
|
| 5 |
+
sentencepiece
|
| 6 |
+
peft<0.19.0
|
| 7 |
+
ftfy
|
| 8 |
+
imageio-ffmpeg
|
| 9 |
+
imageio
|
| 10 |
+
opencv-python
|
| 11 |
+
torchao==0.11.0
|
| 12 |
+
sageattention
|
| 13 |
+
numpy>=1.16, <=1.23.5
|
| 14 |
+
torch==2.9.1
|
| 15 |
+
torchvision
|
| 16 |
+
huggingface-hub
|