rahul7star commited on
Commit
8d3f129
·
verified ·
1 Parent(s): 9a107d7

Create wan2fast_1.py

Browse files
Files changed (1) hide show
  1. wan2fast_1.py +175 -0
wan2fast_1.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # ✅ Patch for NVML-related crash in ZeroGPU
4
+ os.environ["PYTORCH_NO_NVML"] = "1"
5
+
6
+ # ✅ Ensure proper PyTorch version for CUDA 12.6 in Spaces
7
+ os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9"')
8
+
9
+ import torch
10
+ from diffusers import AutoencoderKLWan, WanPipeline, UniPCMultistepScheduler
11
+ from diffusers.utils import export_to_video
12
+ import gradio as gr
13
+ import tempfile
14
+ import spaces
15
+ from huggingface_hub import hf_hub_download
16
+ import numpy as np
17
+ import random
18
+
19
+ # MODEL_ID
20
+ MODEL_ID = "Runware/Wan2.2-T2V-A14B"
21
+
22
+ # Load model and scheduler (no .to("cuda") yet)
23
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
24
+ pipe = WanPipeline.from_pretrained(MODEL_ID, vae=vae, torch_dtype=torch.bfloat16)
25
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=8.0)
26
+
27
+ # Configuration
28
+ MOD_VALUE = 32
29
+ DEFAULT_H_SLIDER_VALUE = 768
30
+ DEFAULT_W_SLIDER_VALUE = 1344
31
+
32
+ IS_ORIGINAL_SPACE = os.environ.get("IS_ORIGINAL_SPACE", "True") == "True"
33
+
34
+ LIMITED_MAX_RESOLUTION = 640
35
+ LIMITED_MAX_DURATION = 2.0
36
+ LIMITED_MAX_STEPS = 4
37
+
38
+ ORIGINAL_SLIDER_MIN_H, ORIGINAL_SLIDER_MAX_H = 128, 1536
39
+ ORIGINAL_SLIDER_MIN_W, ORIGINAL_SLIDER_MAX_W = 128, 1536
40
+ ORIGINAL_MAX_DURATION = round(81 / 24, 1)
41
+ ORIGINAL_MAX_STEPS = 8
42
+
43
+ if IS_ORIGINAL_SPACE:
44
+ SLIDER_MIN_H, SLIDER_MAX_H = 128, LIMITED_MAX_RESOLUTION
45
+ SLIDER_MIN_W, SLIDER_MAX_W = 128, LIMITED_MAX_RESOLUTION
46
+ MAX_DURATION = LIMITED_MAX_DURATION
47
+ MAX_STEPS = LIMITED_MAX_STEPS
48
+ else:
49
+ SLIDER_MIN_H, SLIDER_MAX_H = ORIGINAL_SLIDER_MIN_H, ORIGINAL_SLIDER_MAX_H
50
+ SLIDER_MIN_W, SLIDER_MAX_W = ORIGINAL_SLIDER_MIN_W, ORIGINAL_SLIDER_MAX_W
51
+ MAX_DURATION = ORIGINAL_MAX_DURATION
52
+ MAX_STEPS = ORIGINAL_MAX_STEPS
53
+
54
+ MAX_SEED = np.iinfo(np.int32).max
55
+ FIXED_FPS = 24
56
+ FIXED_OUTPUT_FPS = 18
57
+ MIN_FRAMES_MODEL = 8
58
+ MAX_FRAMES_MODEL = 81
59
+
60
+ default_prompt_t2v = "cinematic footage, group of pedestrians dancing in the streets of NYC, high quality breakdance, 4K, tiktok video, intricate details, instagram feel, dynamic camera, smooth dance motion, dimly lit, stylish, beautiful faces, smiling, music video"
61
+ default_negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards, watermark, text, signature"
62
+
63
+ def get_duration(prompt, height, width, negative_prompt, duration_seconds, guidance_scale, steps, seed, randomize_seed, progress):
64
+ return int(duration_seconds) * int(steps) * 2.25 + 5
65
+
66
+ @spaces.GPU(duration=get_duration)
67
+ def generate_video(prompt, height, width,
68
+ negative_prompt=default_negative_prompt, duration_seconds=2,
69
+ guidance_scale=1, steps=4,
70
+ seed=42, randomize_seed=False,
71
+ progress=gr.Progress(track_tqdm=True)):
72
+
73
+ if not prompt or prompt.strip() == "":
74
+ raise gr.Error("Please enter a text prompt. Try to use long and precise descriptions.")
75
+
76
+ if IS_ORIGINAL_SPACE:
77
+ height = min(height, LIMITED_MAX_RESOLUTION)
78
+ width = min(width, LIMITED_MAX_RESOLUTION)
79
+ duration_seconds = min(duration_seconds, LIMITED_MAX_DURATION)
80
+ steps = min(steps, LIMITED_MAX_STEPS)
81
+
82
+ target_h = max(MOD_VALUE, (int(height) // MOD_VALUE) * MOD_VALUE)
83
+ target_w = max(MOD_VALUE, (int(width) // MOD_VALUE) * MOD_VALUE)
84
+
85
+ num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
86
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
87
+
88
+ # ✅ Move to GPU inside @spaces.GPU function
89
+ pipe.to("cuda")
90
+
91
+ with torch.inference_mode():
92
+ output_frames_list = pipe(
93
+ prompt=prompt, negative_prompt=negative_prompt,
94
+ height=target_h, width=target_w, num_frames=num_frames,
95
+ guidance_scale=float(guidance_scale), num_inference_steps=int(steps),
96
+ generator=torch.Generator(device="cuda").manual_seed(current_seed)
97
+ ).frames[0]
98
+
99
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
100
+ video_path = tmpfile.name
101
+ export_to_video(output_frames_list, video_path, fps=FIXED_OUTPUT_FPS)
102
+ return video_path, current_seed
103
+
104
+ # Gradio UI
105
+ with gr.Blocks(css="body { max-width: 100vw; overflow-x: hidden; }") as demo:
106
+ gr.HTML('<meta name="viewport" content="width=device-width, initial-scale=1">')
107
+ gr.Markdown("# ⚡ InstaVideo")
108
+ gr.Markdown("This Gradio space is a fork of [wan2-1-fast from multimodalart](https://huggingface.co/spaces/multimodalart/wan2-1-fast), and is powered by the Wan CausVid LoRA [from Kijai](https://huggingface.co/Kijai/WanVideo_comfy/blob/main/Wan21_CausVid_bidirect2_T2V_1_3B_lora_rank32.safetensors).")
109
+
110
+ if IS_ORIGINAL_SPACE:
111
+ gr.Markdown("⚠️ **This free public demo limits the resolution to 640px, duration to 2s, and inference steps to 4. For full capabilities please duplicate this space.**")
112
+
113
+ with gr.Row():
114
+ with gr.Column():
115
+ prompt_input = gr.Textbox(label="Prompt", value=default_prompt_t2v)
116
+ with gr.Accordion("Advanced Settings", open=False):
117
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
118
+ seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
119
+ randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
120
+ with gr.Row():
121
+ height_input = gr.Slider(
122
+ minimum=SLIDER_MIN_H,
123
+ maximum=SLIDER_MAX_H,
124
+ step=MOD_VALUE,
125
+ value=min(DEFAULT_H_SLIDER_VALUE, SLIDER_MAX_H),
126
+ label=f"Output Height (multiple of {MOD_VALUE})"
127
+ )
128
+ width_input = gr.Slider(
129
+ minimum=SLIDER_MIN_W,
130
+ maximum=SLIDER_MAX_W,
131
+ step=MOD_VALUE,
132
+ value=min(DEFAULT_W_SLIDER_VALUE, SLIDER_MAX_W),
133
+ label=f"Output Width (multiple of {MOD_VALUE})"
134
+ )
135
+ duration_seconds_input = gr.Slider(
136
+ minimum=round(MIN_FRAMES_MODEL / FIXED_FPS, 1),
137
+ maximum=MAX_DURATION,
138
+ step=0.1,
139
+ value=2,
140
+ label="Duration (seconds)",
141
+ info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps."
142
+ )
143
+ steps_slider = gr.Slider(minimum=1, maximum=MAX_STEPS, step=1, value=4, label="Inference Steps")
144
+ guidance_scale_input = gr.Slider(minimum=0.0, maximum=20.0, step=0.5, value=1.0, label="Guidance Scale", visible=False)
145
+ generate_button = gr.Button("Generate Video", variant="primary")
146
+ with gr.Column():
147
+ video_output = gr.Video(label="Generated Video", autoplay=True, interactive=False)
148
+
149
+ ui_inputs = [
150
+ prompt_input, height_input, width_input,
151
+ negative_prompt_input, duration_seconds_input,
152
+ guidance_scale_input, steps_slider, seed_input, randomize_seed_checkbox
153
+ ]
154
+ generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
155
+
156
+ example_configs = [
157
+ ["a majestic eagle soaring through mountain peaks, cinematic aerial view", 896, 512],
158
+ ["a serene ocean wave crashing on a sandy beach at sunset", 448, 832],
159
+ ["a field of flowers swaying in the wind, spring morning light", 512, 896],
160
+ ]
161
+ if IS_ORIGINAL_SPACE:
162
+ example_configs = [
163
+ [example[0], min(example[1], LIMITED_MAX_RESOLUTION), min(example[2], LIMITED_MAX_RESOLUTION)]
164
+ for example in example_configs
165
+ ]
166
+ gr.Examples(
167
+ examples=example_configs,
168
+ inputs=[prompt_input, height_input, width_input],
169
+ outputs=[video_output, seed_input],
170
+ fn=generate_video,
171
+ cache_examples="lazy"
172
+ )
173
+
174
+ if __name__ == "__main__":
175
+ demo.queue().launch()