wan22-lor / app.py
cometa21's picture
Update app.py
b45998a verified
Raw History Blame Contribute Delete
23.9 kB
import os; os.system('pip install --upgrade --no-deps spaces')
import spaces
import shutil
import subprocess
import sys
import copy
import random
import tempfile
import warnings
import time
import gc
import uuid
from tqdm import tqdm
import cv2
import numpy as np
import torch
import torch._dynamo
from torch.nn import functional as F
from PIL import Image
import gradio as gr
from diffusers import (
FlowMatchEulerDiscreteScheduler,
SASolverScheduler,
DEISMultistepScheduler,
DPMSolverMultistepInverseScheduler,
UniPCMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
WanPipeline, # <-- CAMBIO: pipeline T2V en lugar de I2V
)
from diffusers.utils.export_utils import export_to_video
from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
import aoti
import lora_loader
os.environ["TOKENIZERS_PARALLELISM"] = "true"
warnings.filterwarnings("ignore")
IS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))
def clear_vram():
gc.collect()
torch.cuda.empty_cache()
# ============ RIFE ============
RIFE_DIR = "RIFE"
if not os.path.exists(RIFE_DIR):
os.makedirs(RIFE_DIR, exist_ok=True)
# 1) Baja el zip que sí funciona (trae train_log/ con flownet.pkl)
subprocess.run([
"wget", "-q",
"https://huggingface.co/thornmaze/RIFE/resolve/main/RIFEv4.26_0921.zip",
"-O", "rife.zip"
], check=True)
subprocess.run(["unzip", "-o", "rife.zip", "-d", RIFE_DIR], check=True)
# 2) Clona Practical-RIFE solo para extraer 'model/'
subprocess.run([
"git", "clone", "--depth", "1",
"https://github.com/hzwer/Practical-RIFE",
"_rife_src"
], check=True)
# 3) Copia 'model/' (y otros módulos que falten) al RIFE_DIR
if os.path.exists("_rife_src/model"):
shutil.copytree("_rife_src/model", os.path.join(RIFE_DIR, "model"))
if os.path.exists("_rife_src/scripts"):
shutil.copytree("_rife_src/scripts", os.path.join(RIFE_DIR, "scripts"),
dirs_exist_ok=True)
sys.path.insert(0, os.path.abspath(RIFE_DIR))
from train_log.RIFE_HDv3 import Model
rife_model = Model()
rife_model.load_model(os.path.join(RIFE_DIR, "train_log"), -1)
rife_model.eval()
@torch.no_grad()
def interpolate_bits(frames_np, multiplier=2, scale=1.0):
if isinstance(frames_np, list):
T = len(frames_np)
H, W, C = frames_np[0].shape
else:
T, H, W, C = frames_np.shape
if multiplier < 2:
if isinstance(frames_np, np.ndarray):
return list(frames_np)
return frames_np
n_interp = multiplier - 1
tmp = max(128, int(128 / scale))
ph = ((H - 1) // tmp + 1) * tmp
pw = ((W - 1) // tmp + 1) * tmp
padding = (0, pw - W, 0, ph - H)
def to_tensor(frame_np):
t = torch.from_numpy(frame_np).to(device)
t = t.permute(2, 0, 1).unsqueeze(0)
return F.pad(t, padding).half()
def from_tensor(tensor):
t = tensor[0, :, :H, :W]
t = t.permute(1, 2, 0)
return t.float().cpu().numpy()
def make_inference(I0, I1, n):
if rife_model.version >= 3.9:
res = []
for i in range(n):
res.append(rife_model.inference(I0, I1, (i + 1) * 1. / (n + 1), scale))
return res
else:
middle = rife_model.inference(I0, I1, scale)
if n == 1:
return [middle]
first_half = make_inference(I0, middle, n=n // 2)
second_half = make_inference(middle, I1, n=n // 2)
if n % 2:
return [*first_half, middle, *second_half]
else:
return [*first_half, *second_half]
output_frames = []
I1 = to_tensor(frames_np[0])
total_steps = T - 1
with tqdm(total=total_steps, desc="Interpolating", unit="frame") as pbar:
for i in range(total_steps):
I0 = I1
output_frames.append(from_tensor(I0))
I1 = to_tensor(frames_np[i + 1])
mid_tensors = make_inference(I0, I1, n_interp)
for mid in mid_tensors:
output_frames.append(from_tensor(mid))
if (i + 1) % 50 == 0:
pbar.update(50)
pbar.update(total_steps % 50)
output_frames.append(from_tensor(I1))
del I0, I1, mid_tensors
torch.cuda.empty_cache()
return output_frames
# ============ WAN T2V ============
MODEL_ID = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"
# Alternativas lightning (más rápidas, sin LoRAs extra):
# "lightx2v/Wan2.2-Lightning" (4-step distilled)
# "Wan-AI/Wan2.2-T2V-A14B-Lightning"
LORA_MODELS = []
MAX_DIM = 832
MIN_DIM = 480
MULTIPLE_OF = 16
MAX_SEED = np.iinfo(np.int32).max
FIXED_FPS = 16
MIN_FRAMES_MODEL = 8
MAX_FRAMES_MODEL = 321
MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)
MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)
# ---- Presets de resolución para T2V ----
RESOLUTION_PRESETS = {
"Landscape 832×480 (16:9)": (832, 480),
"Landscape 640×640 (1:1)": (640, 640),
"Portrait 480×832 (9:16)": (480, 832),
"Wide 1280×720 (16:9 HD)": (1280, 720),
"Tall 720×1280 (9:16 HD)": (720, 1280),
"Cinematic 1024×576 (16:9)": (1024, 576),
}
SCHEDULER_MAP = {
"FlowMatchEulerDiscrete": FlowMatchEulerDiscreteScheduler,
"SASolver": SASolverScheduler,
"DEISMultistep": DEISMultistepScheduler,
"DPMSolverMultistepInverse": DPMSolverMultistepInverseScheduler,
"UniPCMultistep": UniPCMultistepScheduler,
"DPMSolverMultistep": DPMSolverMultistepScheduler,
"DPMSolverSinglestep": DPMSolverSinglestepScheduler,
}
pipe = WanPipeline.from_pretrained(
MODEL_ID,
torch_dtype=torch.bfloat16,
).to('cuda')
original_scheduler = copy.deepcopy(pipe.scheduler)
for i, lora in enumerate(LORA_MODELS):
name_high_tr = lora["high_tr"].split(".")[0].split("/")[-1] + "Hh"
name_low_tr = lora["low_tr"].split(".")[0].split("/")[-1] + "Ll"
try:
pipe.load_lora_weights(
lora["repo_id"],
weight_name=lora["high_tr"],
adapter_name=name_high_tr
)
kwargs_lora = {"load_into_transformer_2": True}
pipe.load_lora_weights(
lora["repo_id"],
weight_name=lora["low_tr"],
adapter_name=name_low_tr,
**kwargs_lora
)
pipe.set_adapters([name_high_tr, name_low_tr], adapter_weights=[1.0, 1.0])
pipe.fuse_lora(adapter_names=[name_high_tr], lora_scale=lora["high_scale"], components=["transformer"])
pipe.fuse_lora(adapter_names=[name_low_tr], lora_scale=lora["low_scale"], components=["transformer_2"])
pipe.unload_lora_weights()
print(f"Applied: {lora['high_tr']}, hs={lora['high_scale']}/ls={lora['low_scale']}, {i+1}/{len(LORA_MODELS)}")
except Exception as e:
print("Error:", str(e))
print("Failed LoRA:", name_high_tr)
pipe.unload_lora_weights()
quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
torch._dynamo.reset()
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
torch._dynamo.reset()
quantize_(pipe.transformer_2, Float8DynamicActivationFloat8WeightConfig())
torch._dynamo.reset()
# ⚠️ IMPORTANTE: los repos AoT fueron compilados para el transformer I2V.
# Para T2V necesitas repos AoT específicos o comentar estas 2 llamadas.
# spaces.aoti_load(module=pipe.transformer, repo_id='<tu_repo_aot_t2v>')
# spaces.aoti_load(module=pipe.transformer_2, repo_id='<tu_repo_aot_t2v>')
default_prompt = (
"A cinematic wide shot of a serene mountain lake at sunset, "
"golden light reflecting on the water, gentle camera dolly forward, "
"birds flying in the distance, high detail, film grain, 35mm"
)
default_negative_prompt = (
"色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, "
"最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, "
"畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
)
LORA_CHOICES = lora_loader.get_lora_choices()
def model_title():
return "## Wan 2.2 T2V 14B Custom Lora"
def get_resolution(preset):
"""Devuelve (width, height) enteros múltiplos de 16 a partir del preset."""
w, h = RESOLUTION_PRESETS.get(preset, (832, 480))
w = max(MIN_DIM, min(1280, round(w / MULTIPLE_OF) * MULTIPLE_OF))
h = max(MIN_DIM, min(1280, round(h / MULTIPLE_OF) * MULTIPLE_OF))
return w, h
def get_num_frames(duration_seconds):
seconds = float(duration_seconds) # cast defensivo (spaces.zero)
raw = int(round(seconds * FIXED_FPS))
raw = max(MIN_FRAMES_MODEL, min(MAX_FRAMES_MODEL, raw))
return ((raw - 1) // 4) * 4 + 1
def get_inference_duration(
prompt,
steps,
negative_prompt,
num_frames,
width,
height,
guidance_scale,
guidance_scale_2,
current_seed,
scheduler_name,
flow_shift,
frame_multiplier,
quality,
duration_seconds,
safe_mode,
lora_groups,
progress,
):
# casts defensivos por si spaces.zero los serializa como str
steps = int(float(steps))
num_frames = int(float(num_frames))
width = int(float(width))
height = int(float(height))
frame_multiplier = int(float(frame_multiplier))
BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 480 # referencia T2V
BASE_STEP_DURATION = 5.
factor = num_frames * width * height / BASE_FRAMES_HEIGHT_WIDTH
step_duration = BASE_STEP_DURATION * factor ** 1.5
gen_time = steps * step_duration
if float(guidance_scale) > 1:
gen_time = gen_time * 2.4
frame_factor = frame_multiplier // FIXED_FPS
if frame_factor > 1:
total_out_frames = (num_frames * frame_factor) - num_frames
gen_time += total_out_frames * 0.02
total_time = 15 + gen_time
if safe_mode:
total_time = total_time * 1.30
return total_time
@spaces.GPU(duration=get_inference_duration, size='xlarge')
def run_inference(
prompt,
steps,
negative_prompt,
num_frames,
width,
height,
guidance_scale,
guidance_scale_2,
current_seed,
scheduler_name,
flow_shift,
frame_multiplier,
quality,
duration_seconds,
safe_mode=False,
lora_groups=None,
progress=gr.Progress(track_tqdm=True),
):
scheduler_class = SCHEDULER_MAP.get(scheduler_name)
if (scheduler_class.__name__ != pipe.scheduler.config._class_name
or flow_shift != pipe.scheduler.config.get("flow_shift", "shift")):
config = copy.deepcopy(original_scheduler.config)
if scheduler_class == FlowMatchEulerDiscreteScheduler:
config['shift'] = flow_shift
else:
config['flow_shift'] = flow_shift
pipe.scheduler = scheduler_class.from_config(config)
clear_vram()
task_name = str(uuid.uuid4())[:8]
print(f"Generating {num_frames} frames @ {width}x{height}, task: {task_name}, "
f"{duration_seconds}s, lora={lora_groups}")
start = time.time()
lora_loaded = False
if lora_groups:
try:
lora_loaded = lora_loader.load_lora_slots(pipe, lora_groups)
print(f"LoRA loaded: {lora_groups}")
except Exception as e:
print(f"LoRA warning: {e}")
try:
lora_loader.unload_lora(pipe)
except Exception:
pass
result = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
height=int(height),
width=int(width),
num_frames=int(num_frames),
guidance_scale=float(guidance_scale),
guidance_scale_2=float(guidance_scale_2),
num_inference_steps=int(steps),
generator=torch.Generator(device="cuda").manual_seed(int(current_seed)),
output_type="np",
)
if lora_loaded:
lora_loader.unload_lora(pipe)
print("gen time passed:", time.time() - start)
raw_frames_np = result.frames[0]
pipe.scheduler = original_scheduler
frame_factor = int(frame_multiplier) // FIXED_FPS
if frame_factor > 1:
start = time.time()
print(f"Processing frames (RIFE Multiplier: {frame_factor}x)...")
rife_model.device()
rife_model.flownet = rife_model.flownet.half()
final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
print("Interpolation time passed:", time.time() - start)
else:
final_frames = list(raw_frames_np)
final_fps = FIXED_FPS * int(frame_factor)
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
video_path = tmpfile.name
start = time.time()
with tqdm(total=3, desc="Rendering Media", unit="clip") as pbar:
pbar.update(2)
export_to_video(final_frames, video_path, fps=final_fps, quality=quality)
pbar.update(1)
print(f"Export time passed, {final_fps} FPS:", time.time() - start)
return video_path, task_name
def generate_video(
prompt,
resolution_preset,
steps=4,
negative_prompt=default_negative_prompt,
duration_seconds=MAX_DURATION,
guidance_scale=1,
guidance_scale_2=1,
seed=42,
randomize_seed=False,
quality=5,
scheduler="UniPCMultistep",
flow_shift=6.0,
frame_multiplier=16,
safe_mode=False,
# original 3
lora1_preset="(None)",
lora1_high_scale=1.0,
lora1_low_scale=1.0,
lora2_preset="(None)",
lora2_high_scale=1.0,
lora2_low_scale=1.0,
lora3_preset="(None)",
lora3_high_scale=1.0,
lora3_low_scale=1.0,
# my 5
my1_repo="", my1_high="(None)", my1_hs=1.0, my1_low="(None)", my1_ls=1.0,
my2_repo="", my2_high="(None)", my2_hs=1.0, my2_low="(None)", my2_ls=1.0,
my3_repo="", my3_high="(None)", my3_hs=1.0, my3_low="(None)", my3_ls=1.0,
my4_repo="", my4_high="(None)", my4_hs=1.0, my4_low="(None)", my4_ls=1.0,
my5_repo="", my5_high="(None)", my5_hs=1.0, my5_low="(None)", my5_ls=1.0,
video_component=True,
progress=gr.Progress(track_tqdm=True),
):
if not prompt or not prompt.strip():
raise gr.Error("Please enter a prompt.")
width, height = get_resolution(resolution_preset)
num_frames = get_num_frames(duration_seconds)
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
lora_groups = [
{"preset": lora1_preset, "high_scale": lora1_high_scale, "low_scale": lora1_low_scale},
{"preset": lora2_preset, "high_scale": lora2_high_scale, "low_scale": lora2_low_scale},
{"preset": lora3_preset, "high_scale": lora3_high_scale, "low_scale": lora3_low_scale},
{"repo": my1_repo, "file_high": my1_high, "file_low": my1_low, "high_scale": my1_hs, "low_scale": my1_ls},
{"repo": my2_repo, "file_high": my2_high, "file_low": my2_low, "high_scale": my2_hs, "low_scale": my2_ls},
{"repo": my3_repo, "file_high": my3_high, "file_low": my3_low, "high_scale": my3_hs, "low_scale": my3_ls},
{"repo": my4_repo, "file_high": my4_high, "file_low": my4_low, "high_scale": my4_hs, "low_scale": my4_ls},
{"repo": my5_repo, "file_high": my5_high, "file_low": my5_low, "high_scale": my5_hs, "low_scale": my5_ls},
]
video_path, task_n = run_inference(
prompt,
steps,
negative_prompt,
num_frames,
width,
height,
guidance_scale,
guidance_scale_2,
current_seed,
scheduler,
flow_shift,
frame_multiplier,
quality,
duration_seconds,
safe_mode,
lora_groups,
progress,
)
print(f"GPU complete: {task_n}")
return (video_path if video_component else None), video_path, current_seed
def _load_repo_files(repo_link):
files = lora_loader.list_loras_from_repo(repo_link)
return (
gr.update(choices=files, value="(None)"),
gr.update(choices=files, value="(None)"),
)
CSS = """
#hidden-timestamp { opacity: 0; height: 0; width: 0; margin: 0; padding: 0;
overflow: hidden; position: absolute; pointer-events: none; }
"""
with gr.Blocks(delete_cache=(3600, 10800)) as demo:
gr.Markdown(model_title())
gr.Markdown("Wan 2.2 T2V 14B — fp8 quantization, ZeroGPU, custom LoRA slots")
with gr.Row():
with gr.Column():
prompt_input = gr.Textbox(
label="Prompt",
value=default_prompt,
lines=4,
placeholder="Describe the video you want to generate...",
)
resolution_preset = gr.Dropdown(
choices=list(RESOLUTION_PRESETS.keys()),
value="Landscape 832×480 (16:9)",
label="Aspect / resolution",
)
duration_seconds_input = gr.Slider(
minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=3.5,
label="Duration (seconds)",
info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.",
)
frame_multi = gr.Dropdown(
choices=[FIXED_FPS, FIXED_FPS * 2, FIXED_FPS * 4, FIXED_FPS * 8],
value=FIXED_FPS,
label="Video Fluidity (Frames per Second)",
info="Extra frames generated via RIFE flow estimation.",
)
safe_mode_checkbox = gr.Checkbox(
label="🛠️ Safe Mode", value=True,
info="Requests 30% extra processing time.",
)
with gr.Accordion("Advanced Settings", open=False):
negative_prompt_input = gr.Textbox(
label="Negative Prompt", value=default_negative_prompt,
info="Used if any Guidance Scale > 1.", lines=3,
)
quality_slider = gr.Slider(minimum=1, maximum=10, step=1, value=6,
label="Video Quality")
seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1,
value=42, interactive=True)
randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True,
interactive=True)
steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=6,
label="Inference Steps")
guidance_scale_input = gr.Slider(0.0, 10.0, step=0.5, value=1,
label="Guidance Scale - high noise stage")
guidance_scale_2_input = gr.Slider(0.0, 10.0, step=0.5, value=1,
label="Guidance Scale 2 - low noise stage")
scheduler_dropdown = gr.Dropdown(
label="Scheduler",
choices=list(SCHEDULER_MAP.keys()),
value="UniPCMultistep",
)
flow_shift_slider = gr.Slider(0.5, 15.0, step=0.1, value=3.0,
label="Flow Shift")
gr.Markdown("### 1) Original LoRA x3 + strength")
with gr.Row():
lora1_preset = gr.Dropdown(choices=LORA_CHOICES, value="(None)",
label="Original LoRA 1", filterable=True)
lora1_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
lora1_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
with gr.Row():
lora2_preset = gr.Dropdown(choices=LORA_CHOICES, value="(None)",
label="Original LoRA 2", filterable=True)
lora2_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
lora2_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
with gr.Row():
lora3_preset = gr.Dropdown(choices=LORA_CHOICES, value="(None)",
label="Original LoRA 3", filterable=True)
lora3_high_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
lora3_low_scale = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
gr.Markdown("### 2) My LoRA x5 from HF repo + strength")
gr.Markdown("For each slot: paste repo → Load files → pick High/Low → set strength. "
"Example: `username/my-loras`")
my_slots = []
for idx in range(1, 6):
gr.Markdown(f"**My LoRA {idx}**")
with gr.Row():
repo_box = gr.Textbox(label="Repo link", placeholder="username/repo",
lines=1, scale=4)
load_btn = gr.Button("Load files", scale=1)
with gr.Row():
high_dd = gr.Dropdown(choices=["(None)"], value="(None)",
label="High file", filterable=True)
hs = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="High strength")
with gr.Row():
low_dd = gr.Dropdown(choices=["(None)"], value="(None)",
label="Low file", filterable=True)
ls = gr.Slider(0.0, 2.0, value=1.0, step=0.05, label="Low strength")
load_btn.click(fn=_load_repo_files, inputs=[repo_box],
outputs=[high_dd, low_dd])
my_slots.append((repo_box, high_dd, hs, low_dd, ls))
play_result_video = gr.Checkbox(label="Display result", value=True,
interactive=True)
generate_button = gr.Button("Generate Video", variant="primary")
with gr.Column():
video_output = gr.Video(label="Generated Video", autoplay=True,
sources=["upload"], buttons=["download", "share"],
interactive=True, elem_id="generated-video")
file_output = gr.File(label="Download Video")
my1_repo, my1_high, my1_hs, my1_low, my1_ls = my_slots[0]
my2_repo, my2_high, my2_hs, my2_low, my2_ls = my_slots[1]
my3_repo, my3_high, my3_hs, my3_low, my3_ls = my_slots[2]
my4_repo, my4_high, my4_hs, my4_low, my4_ls = my_slots[3]
my5_repo, my5_high, my5_hs, my5_low, my5_ls = my_slots[4]
ui_inputs = [
prompt_input, resolution_preset, steps_slider,
negative_prompt_input, duration_seconds_input,
guidance_scale_input, guidance_scale_2_input, seed_input, randomize_seed_checkbox,
quality_slider, scheduler_dropdown, flow_shift_slider, frame_multi,
safe_mode_checkbox,
# original 3
lora1_preset, lora1_high_scale, lora1_low_scale,
lora2_preset, lora2_high_scale, lora2_low_scale,
lora3_preset, lora3_high_scale, lora3_low_scale,
# my 5
my1_repo, my1_high, my1_hs, my1_low, my1_ls,
my2_repo, my2_high, my2_hs, my2_low, my2_ls,
my3_repo, my3_high, my3_hs, my3_low, my3_ls,
my4_repo, my4_high, my4_hs, my4_low, my4_ls,
my5_repo, my5_high, my5_hs, my5_low, my5_ls,
play_result_video,
]
generate_button.click(
fn=generate_video,
inputs=ui_inputs,
outputs=[video_output, file_output, seed_input],
)
if __name__ == "__main__":
demo.queue().launch(mcp_server=True, css=CSS, show_error=True)