rahul7star commited on
Commit
e3d64e7
·
verified ·
1 Parent(s): 717be31

Create wan2_fast.py

Browse files
Files changed (1) hide show
  1. wan2_fast.py +302 -0
wan2_fast.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import AutoencoderKLWan, WanPipeline, UniPCMultistepScheduler
3
+ from diffusers.utils import export_to_video
4
+ import gradio as gr
5
+ import tempfile
6
+ import spaces
7
+ from huggingface_hub import hf_hub_download
8
+ import numpy as np
9
+ import random
10
+ import os
11
+ # LIGHT WEIGHT 1.3b
12
+ # MODEL_ID = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
13
+ # LORA_REPO_ID = "Kijai/WanVideo_comfy"
14
+ # LORA_FILENAME = "Wan21_CausVid_bidirect2_T2V_1_3B_lora_rank32.safetensors"
15
+
16
+
17
+ MODEL_ID = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
18
+
19
+ #MODEL_ID ="FastWan/FastWan_T2V_14B_480p_lora_rank_128_bf16.safetensors"
20
+
21
+
22
+ LORA_REPO_ID = "Kijai/WanVideo_comfy"
23
+ LORA_FILENAME = "Lightx2v/lightx2v_T2V_14B_cfg_step_distill_v2_lora_rank256_bf16.safetensors"
24
+ #LORA_FILENAME = "Pusa/Wan21_PusaV1_LoRA_14B_rank512_bf16.safetensors"
25
+
26
+
27
+
28
+
29
+ # LORA_REPO_ID = "RaphaelLiu/PusaV1"
30
+ # LORA_FILENAME="pusa_v1.safetensors"
31
+ #LORA_REPO_ID = "Kijai/WanVideo_comfy"
32
+ #LORA_FILENAME = "Wan21_CausVid_14B_T2V_lora_rank32.safetensors"
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
42
+ pipe = WanPipeline.from_pretrained(
43
+ MODEL_ID, vae=vae, torch_dtype=torch.bfloat16
44
+ )
45
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=8.0)
46
+ pipe.to("cuda")
47
+
48
+ causvid_path = hf_hub_download(repo_id=LORA_REPO_ID, filename=LORA_FILENAME)
49
+ pipe.load_lora_weights(causvid_path, adapter_name="causvid_lora")
50
+ pipe.set_adapters(["causvid_lora"], adapter_weights=[0.95])
51
+ pipe.fuse_lora()
52
+
53
+ # MOD_VALUE = 32
54
+ # DEFAULT_H_SLIDER_VALUE = 512
55
+ # DEFAULT_W_SLIDER_VALUE = 896
56
+
57
+ # # Environment variable check
58
+ # IS_ORIGINAL_SPACE = os.environ.get("IS_ORIGINAL_SPACE", "True") == "True"
59
+
60
+ # # Original limits
61
+ # ORIGINAL_SLIDER_MIN_H, ORIGINAL_SLIDER_MAX_H = 128, 1280
62
+ # ORIGINAL_SLIDER_MIN_W, ORIGINAL_SLIDER_MAX_W = 128, 1280
63
+ # ORIGINAL_MAX_DURATION = round(81/24, 1) # MAX_FRAMES_MODEL/FIXED_FPS
64
+
65
+ # # Limited space constants
66
+ # LIMITED_MAX_RESOLUTION = 640
67
+ # LIMITED_MAX_DURATION = 2.0
68
+ # LIMITED_MAX_STEPS = 4
69
+
70
+ # # Set limits based on environment variable
71
+ # if IS_ORIGINAL_SPACE:
72
+ # SLIDER_MIN_H, SLIDER_MAX_H = 128, LIMITED_MAX_RESOLUTION
73
+ # SLIDER_MIN_W, SLIDER_MAX_W = 128, LIMITED_MAX_RESOLUTION
74
+ # MAX_DURATION = LIMITED_MAX_DURATION
75
+ # MAX_STEPS = LIMITED_MAX_STEPS
76
+ # else:
77
+ # SLIDER_MIN_H, SLIDER_MAX_H = ORIGINAL_SLIDER_MIN_H, ORIGINAL_SLIDER_MAX_H
78
+ # SLIDER_MIN_W, SLIDER_MAX_W = ORIGINAL_SLIDER_MIN_W, ORIGINAL_SLIDER_MAX_W
79
+ # MAX_DURATION = ORIGINAL_MAX_DURATION
80
+ # MAX_STEPS = 8
81
+
82
+ # MAX_SEED = np.iinfo(np.int32).max
83
+
84
+ # FIXED_FPS = 24
85
+ # FIXED_OUTPUT_FPS = 18 # we downspeed the output video as a temporary "trick"
86
+ # MIN_FRAMES_MODEL = 8
87
+ # MAX_FRAMES_MODEL = 81
88
+
89
+
90
+ #New math to make it High Res
91
+
92
+ MOD_VALUE = 32
93
+
94
+ # Defaults for higher-res generation
95
+ DEFAULT_H_SLIDER_VALUE = 768
96
+ DEFAULT_W_SLIDER_VALUE = 1344 # 16:9 friendly and divisible by MOD_VALUE
97
+
98
+ # Original Space = Hugging Face space with compute limits
99
+ IS_ORIGINAL_SPACE = os.environ.get("IS_ORIGINAL_SPACE", "True") == "True"
100
+
101
+ # Conservative limits for low-end environments
102
+ LIMITED_MAX_RESOLUTION = 640
103
+ LIMITED_MAX_DURATION = 2.0
104
+ LIMITED_MAX_STEPS = 4
105
+
106
+ # Generous limits for local or Pro spaces
107
+ ORIGINAL_SLIDER_MIN_H, ORIGINAL_SLIDER_MAX_H = 128, 1536
108
+ ORIGINAL_SLIDER_MIN_W, ORIGINAL_SLIDER_MAX_W = 128, 1536
109
+ ORIGINAL_MAX_DURATION = round(81 / 24, 1) # 3.4 seconds
110
+ ORIGINAL_MAX_STEPS = 8
111
+
112
+ # Use limited or original (generous) settings
113
+ if IS_ORIGINAL_SPACE:
114
+ SLIDER_MIN_H, SLIDER_MAX_H = 128, LIMITED_MAX_RESOLUTION
115
+ SLIDER_MIN_W, SLIDER_MAX_W = 128, LIMITED_MAX_RESOLUTION
116
+ MAX_DURATION = LIMITED_MAX_DURATION
117
+ MAX_STEPS = LIMITED_MAX_STEPS
118
+ else:
119
+ SLIDER_MIN_H, SLIDER_MAX_H = ORIGINAL_SLIDER_MIN_H, ORIGINAL_SLIDER_MAX_H
120
+ SLIDER_MIN_W, SLIDER_MAX_W = ORIGINAL_SLIDER_MIN_W, ORIGINAL_SLIDER_MAX_W
121
+ MAX_DURATION = ORIGINAL_MAX_DURATION
122
+ MAX_STEPS = ORIGINAL_MAX_STEPS
123
+
124
+ MAX_SEED = np.iinfo(np.int32).max
125
+
126
+ FIXED_FPS = 24
127
+ FIXED_OUTPUT_FPS = 18 # reduce final video FPS to save space
128
+ MIN_FRAMES_MODEL = 8
129
+ MAX_FRAMES_MODEL = 81
130
+
131
+
132
+ 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"
133
+ 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"
134
+
135
+ def get_duration(prompt, height, width,
136
+ negative_prompt, duration_seconds,
137
+ guidance_scale, steps,
138
+ seed, randomize_seed,
139
+ progress):
140
+ if steps > 4 and duration_seconds > 2:
141
+ return 90
142
+ elif steps > 4 or duration_seconds > 2:
143
+ return 75
144
+ else:
145
+ return 60
146
+
147
+ @spaces.GPU(duration=get_duration)
148
+ def generate_video(prompt, height, width,
149
+ negative_prompt=default_negative_prompt, duration_seconds = 2,
150
+ guidance_scale = 1, steps = 4,
151
+ seed = 42, randomize_seed = False,
152
+ progress=gr.Progress(track_tqdm=True)):
153
+ """
154
+ Generate a video from a text prompt using the Wan 2.1 T2V model with CausVid LoRA.
155
+
156
+ This function takes a text prompt and generates a video based on the provided
157
+ prompt and parameters. It uses the Wan 2.1 1.3B Text-to-Video model with CausVid LoRA
158
+ for fast generation in 3-8 steps.
159
+
160
+ Args:
161
+ prompt (str): Text prompt describing the desired video content.
162
+ height (int): Target height for the output video. Will be adjusted to multiple of MOD_VALUE (32).
163
+ width (int): Target width for the output video. Will be adjusted to multiple of MOD_VALUE (32).
164
+ negative_prompt (str, optional): Negative prompt to avoid unwanted elements.
165
+ Defaults to default_negative_prompt (contains unwanted visual artifacts).
166
+ duration_seconds (float, optional): Duration of the generated video in seconds.
167
+ Defaults to 2. Clamped between MIN_FRAMES_MODEL/FIXED_FPS and MAX_FRAMES_MODEL/FIXED_FPS.
168
+ guidance_scale (float, optional): Controls adherence to the prompt. Higher values = more adherence.
169
+ Defaults to 1.0. Range: 0.0-20.0.
170
+ steps (int, optional): Number of inference steps. More steps = higher quality but slower.
171
+ Defaults to 4. Range: 1-30.
172
+ seed (int, optional): Random seed for reproducible results. Defaults to 42.
173
+ Range: 0 to MAX_SEED (2147483647).
174
+ randomize_seed (bool, optional): Whether to use a random seed instead of the provided seed.
175
+ Defaults to False.
176
+ progress (gr.Progress, optional): Gradio progress tracker. Defaults to gr.Progress(track_tqdm=True).
177
+
178
+ Returns:
179
+ tuple: A tuple containing:
180
+ - video_path (str): Path to the generated video file (.mp4)
181
+ - current_seed (int): The seed used for generation (useful when randomize_seed=True)
182
+
183
+ Raises:
184
+ gr.Error: If prompt is empty or None.
185
+
186
+ Note:
187
+ - Frame count is calculated as duration_seconds * FIXED_FPS (24)
188
+ - Output dimensions are adjusted to be multiples of MOD_VALUE (32)
189
+ - The function uses GPU acceleration via the @spaces.GPU decorator
190
+ - Generation time varies based on steps and duration (see get_duration function)
191
+ """
192
+ if not prompt or prompt.strip() == "":
193
+ raise gr.Error("Please enter a text prompt. Try to use long and precise descriptions.")
194
+
195
+ # Apply limits based on environment variable
196
+ if IS_ORIGINAL_SPACE:
197
+ height = min(height, LIMITED_MAX_RESOLUTION)
198
+ width = min(width, LIMITED_MAX_RESOLUTION)
199
+ duration_seconds = min(duration_seconds, LIMITED_MAX_DURATION)
200
+ steps = min(steps, LIMITED_MAX_STEPS)
201
+
202
+ target_h = max(MOD_VALUE, (int(height) // MOD_VALUE) * MOD_VALUE)
203
+ target_w = max(MOD_VALUE, (int(width) // MOD_VALUE) * MOD_VALUE)
204
+
205
+ num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
206
+
207
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
208
+
209
+ with torch.inference_mode():
210
+ output_frames_list = pipe(
211
+ prompt=prompt, negative_prompt=negative_prompt,
212
+ height=target_h, width=target_w, num_frames=num_frames,
213
+ guidance_scale=float(guidance_scale), num_inference_steps=int(steps),
214
+ generator=torch.Generator(device="cuda").manual_seed(current_seed)
215
+ ).frames[0]
216
+
217
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
218
+ video_path = tmpfile.name
219
+ export_to_video(output_frames_list, video_path, fps=FIXED_OUTPUT_FPS)
220
+ return video_path, current_seed
221
+
222
+
223
+
224
+ with gr.Blocks(css="body { max-width: 100vw; overflow-x: hidden; }") as demo:
225
+ gr.HTML('<meta name="viewport" content="width=device-width, initial-scale=1">')
226
+ # ... your other components here ...
227
+ gr.Markdown("# ⚡ InstaVideo")
228
+ 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).")
229
+
230
+ # Add notice for limited spaces
231
+ if IS_ORIGINAL_SPACE:
232
+ 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.**")
233
+
234
+ with gr.Row():
235
+ with gr.Column():
236
+ prompt_input = gr.Textbox(label="Prompt", value=default_prompt_t2v, placeholder="Describe the video you want to generate...")
237
+
238
+ with gr.Accordion("Advanced Settings", open=False):
239
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
240
+ seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
241
+ randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
242
+ with gr.Row():
243
+ height_input = gr.Slider(
244
+ minimum=SLIDER_MIN_H,
245
+ maximum=SLIDER_MAX_H,
246
+ step=MOD_VALUE,
247
+ value=min(DEFAULT_H_SLIDER_VALUE, SLIDER_MAX_H),
248
+ label=f"Output Height (multiple of {MOD_VALUE})"
249
+ )
250
+ width_input = gr.Slider(
251
+ minimum=SLIDER_MIN_W,
252
+ maximum=SLIDER_MAX_W,
253
+ step=MOD_VALUE,
254
+ value=min(DEFAULT_W_SLIDER_VALUE, SLIDER_MAX_W),
255
+ label=f"Output Width (multiple of {MOD_VALUE})"
256
+ )
257
+ duration_seconds_input = gr.Slider(
258
+ minimum=round(MIN_FRAMES_MODEL/FIXED_FPS,1),
259
+ maximum=MAX_DURATION,
260
+ step=0.1,
261
+ value=2,
262
+ label="Duration (seconds)",
263
+ info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps."
264
+ )
265
+ steps_slider = gr.Slider(minimum=1, maximum=MAX_STEPS, step=1, value=4, label="Inference Steps")
266
+ guidance_scale_input = gr.Slider(minimum=0.0, maximum=20.0, step=0.5, value=1.0, label="Guidance Scale", visible=False)
267
+
268
+ generate_button = gr.Button("Generate Video", variant="primary")
269
+ with gr.Column():
270
+ video_output = gr.Video(label="Generated Video", autoplay=True, interactive=False)
271
+
272
+ ui_inputs = [
273
+ prompt_input, height_input, width_input,
274
+ negative_prompt_input, duration_seconds_input,
275
+ guidance_scale_input, steps_slider, seed_input, randomize_seed_checkbox
276
+ ]
277
+ generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
278
+
279
+ # Adjust examples based on space limits
280
+ example_configs = [
281
+ ["a majestic eagle soaring through mountain peaks, cinematic aerial view", 896, 512],
282
+ ["a serene ocean wave crashing on a sandy beach at sunset", 448, 832],
283
+ ["a field of flowers swaying in the wind, spring morning light", 512, 896],
284
+ ]
285
+
286
+ if IS_ORIGINAL_SPACE:
287
+ # Limit example resolutions for limited spaces
288
+ example_configs = [
289
+ [example[0], min(example[1], LIMITED_MAX_RESOLUTION), min(example[2], LIMITED_MAX_RESOLUTION)]
290
+ for example in example_configs
291
+ ]
292
+
293
+ gr.Examples(
294
+ examples=example_configs,
295
+ inputs=[prompt_input, height_input, width_input],
296
+ outputs=[video_output, seed_input],
297
+ fn=generate_video,
298
+ cache_examples="lazy"
299
+ )
300
+
301
+ if __name__ == "__main__":
302
+ demo.queue().launch()