rahul7star commited on
Commit
0de6c30
ยท
verified ยท
1 Parent(s): afa05d9

Create app_g.py

Browse files
Files changed (1) hide show
  1. app_g.py +1198 -0
app_g.py ADDED
@@ -0,0 +1,1198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ import sys
5
+ import datetime
6
+ import shutil
7
+ from PIL import Image
8
+ import cv2
9
+ import numpy as np
10
+ from diffsynth import ModelManager, PusaMultiFramesPipeline, PusaV2VPipeline, WanVideoPusaPipeline, save_video
11
+ import tempfile
12
+
13
+ class PusaVideoDemo:
14
+ def __init__(self):
15
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
16
+ self.model_manager = None
17
+ self.multi_frames_pipe = None
18
+ self.v2v_pipe = None
19
+ self.t2v_pipe = None
20
+ self.base_dir = "model_zoo/PusaV1/Wan2.1-T2V-14B"
21
+ self.output_dir = "outputs"
22
+ os.makedirs(self.output_dir, exist_ok=True)
23
+
24
+ def load_models(self):
25
+ """Load all models once for efficiency"""
26
+ if self.model_manager is None:
27
+ print("Loading models...")
28
+ self.model_manager = ModelManager(device="cpu")
29
+
30
+ model_files = sorted([os.path.join(self.base_dir, f) for f in os.listdir(self.base_dir) if f.endswith('.safetensors')])
31
+
32
+ self.model_manager.load_models(
33
+ [
34
+ model_files,
35
+ os.path.join(self.base_dir, "models_t5_umt5-xxl-enc-bf16.pth"),
36
+ os.path.join(self.base_dir, "Wan2.1_VAE.pth"),
37
+ ],
38
+ torch_dtype=torch.bfloat16,
39
+ )
40
+ print("Models loaded successfully!")
41
+
42
+ def load_lora_and_get_pipe(self, pipe_type, lora_path, lora_alpha):
43
+ """Load LoRA and return appropriate pipeline"""
44
+ self.load_models()
45
+
46
+ # Load LoRA
47
+ self.model_manager.load_lora(lora_path, lora_alpha=lora_alpha)
48
+
49
+ if pipe_type == "multi_frames":
50
+ pipe = PusaMultiFramesPipeline.from_model_manager(self.model_manager, torch_dtype=torch.bfloat16, device=self.device)
51
+ pipe.enable_vram_management(num_persistent_param_in_dit=6*10**9)
52
+ elif pipe_type == "v2v":
53
+ pipe = PusaV2VPipeline.from_model_manager(self.model_manager, torch_dtype=torch.bfloat16, device=self.device)
54
+ pipe.enable_vram_management(num_persistent_param_in_dit=6*10**9)
55
+ elif pipe_type == "t2v":
56
+ pipe = WanVideoPusaPipeline.from_model_manager(self.model_manager, torch_dtype=torch.bfloat16, device=self.device)
57
+ pipe.enable_vram_management(num_persistent_param_in_dit=None)
58
+
59
+ return pipe
60
+
61
+ def process_video_frames(self, video_path):
62
+ """Process video frames for V2V pipeline"""
63
+ if not os.path.isfile(video_path):
64
+ raise FileNotFoundError(f"Video file not found: {video_path}")
65
+
66
+ cap = cv2.VideoCapture(video_path)
67
+ frames = []
68
+
69
+ # Get original video dimensions
70
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
71
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
72
+
73
+ # Calculate scaling and cropping parameters
74
+ target_width = 1280
75
+ target_height = 720
76
+ target_ratio = target_width / target_height
77
+ original_ratio = width / height
78
+
79
+ while True:
80
+ ret, frame = cap.read()
81
+ if not ret:
82
+ break
83
+
84
+ # Resize maintaining aspect ratio
85
+ if original_ratio > target_ratio:
86
+ # Video is wider than target
87
+ new_width = int(height * target_ratio)
88
+ # Crop width from center
89
+ start_x = (width - new_width) // 2
90
+ frame = frame[:, start_x:start_x + new_width]
91
+ else:
92
+ # Video is taller than target
93
+ new_height = int(width / target_ratio)
94
+ # Crop height from center
95
+ start_y = (height - new_height) // 2
96
+ frame = frame[start_y:start_y + new_height]
97
+
98
+ # Resize to target dimensions
99
+ frame = cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_LANCZOS4)
100
+
101
+ # Convert to RGB
102
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
103
+ frames.append(Image.fromarray(frame))
104
+
105
+ cap.release()
106
+ return frames
107
+
108
+ def generate_i2v_video(self, image_path, prompt, noise_multiplier,
109
+ lora_alpha, num_inference_steps, negative_prompt, progress=gr.Progress()):
110
+ """Generate video from single image (I2V)"""
111
+ try:
112
+ progress(0.1, desc="Loading models...")
113
+ lora_path = "./model_zoo/PusaV1/pusa_v1.pt"
114
+ pipe = self.load_lora_and_get_pipe("multi_frames", lora_path, lora_alpha)
115
+
116
+ progress(0.2, desc="Processing input image...")
117
+
118
+ # Process single image for I2V
119
+ if image_path is None:
120
+ raise ValueError("No image provided")
121
+
122
+ # Handle image path - Gradio with type="filepath" returns the path directly
123
+ img = Image.open(image_path)
124
+ processed_image = img.convert("RGB").resize((1280, 720), Image.LANCZOS)
125
+
126
+ # I2V always uses position 0 (first frame)
127
+ multi_frame_images = {0: (processed_image, float(noise_multiplier))}
128
+
129
+ progress(0.4, desc="Generating video...")
130
+ video = pipe(
131
+ prompt=prompt,
132
+ negative_prompt=negative_prompt,
133
+ multi_frame_images=multi_frame_images,
134
+ num_inference_steps=num_inference_steps,
135
+ height=720, width=1280, num_frames=81,
136
+ seed=0, tiled=True
137
+ )
138
+
139
+ progress(0.9, desc="Saving video...")
140
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
141
+ video_filename = os.path.join(self.output_dir, f"i2v_output_{timestamp}_noise_{noise_multiplier}_alpha_{lora_alpha}.mp4")
142
+ save_video(video, video_filename, fps=25, quality=5)
143
+
144
+ progress(1.0, desc="Complete!")
145
+ return video_filename, f"Video generated successfully! Saved to {video_filename}"
146
+
147
+ except Exception as e:
148
+ return None, f"Error: {str(e)}"
149
+
150
+ def generate_multi_frames_video(self, image1, image2, image3, num_imgs, prompt, cond_position, noise_multipliers,
151
+ lora_alpha, num_inference_steps, negative_prompt, progress=gr.Progress()):
152
+ """Generate video from multiple frames (Start-End, Multi-frame)"""
153
+ try:
154
+ progress(0.1, desc="Loading models...")
155
+ lora_path = "./model_zoo/PusaV1/pusa_v1.pt"
156
+ pipe = self.load_lora_and_get_pipe("multi_frames", lora_path, lora_alpha)
157
+
158
+ progress(0.2, desc="Processing input images...")
159
+
160
+ # Parse conditioning positions and noise multipliers
161
+ cond_pos_list = [int(x.strip()) for x in cond_position.split(',')]
162
+ noise_mult_list = [float(x.strip()) for x in noise_multipliers.split(',')]
163
+
164
+ # Collect images based on num_imgs
165
+ image_paths = [image1, image2]
166
+ if num_imgs == "3" and image3 is not None:
167
+ image_paths.append(image3)
168
+
169
+ # Filter out None values
170
+ image_paths = [path for path in image_paths if path is not None]
171
+
172
+ if len(image_paths) != len(cond_pos_list) or len(image_paths) != len(noise_mult_list):
173
+ raise ValueError("The number of images, conditioning positions, and noise multipliers must be the same.")
174
+
175
+ # Process images
176
+ processed_images = []
177
+ for img_path in image_paths:
178
+ img = Image.open(img_path)
179
+ processed_images.append(img.convert("RGB").resize((1280, 720), Image.LANCZOS))
180
+
181
+ multi_frame_images = {
182
+ cond_pos: (img, noise_mult)
183
+ for cond_pos, img, noise_mult in zip(cond_pos_list, processed_images, noise_mult_list)
184
+ }
185
+
186
+ progress(0.4, desc="Generating video...")
187
+ video = pipe(
188
+ prompt=prompt,
189
+ negative_prompt=negative_prompt,
190
+ multi_frame_images=multi_frame_images,
191
+ num_inference_steps=num_inference_steps,
192
+ height=720, width=1280, num_frames=81,
193
+ seed=0, tiled=True
194
+ )
195
+
196
+ progress(0.9, desc="Saving video...")
197
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
198
+ video_filename = os.path.join(self.output_dir, f"multi_frame_output_{timestamp}.mp4")
199
+ save_video(video, video_filename, fps=25, quality=5)
200
+
201
+ progress(1.0, desc="Complete!")
202
+ return video_filename, f"Video generated successfully! Saved to {video_filename}"
203
+
204
+ except Exception as e:
205
+ return None, f"Error: {str(e)}"
206
+
207
+ def generate_v2v_video(self, video_path, prompt, cond_position, noise_multipliers,
208
+ lora_alpha, num_inference_steps, negative_prompt, progress=gr.Progress()):
209
+ """Generate video from video (V2V completion, extension)"""
210
+ try:
211
+ progress(0.1, desc="Loading models...")
212
+ lora_path = "./model_zoo/PusaV1/pusa_v1.pt"
213
+ pipe = self.load_lora_and_get_pipe("v2v", lora_path, lora_alpha)
214
+
215
+ progress(0.2, desc="Processing input video...")
216
+
217
+ # Parse conditioning positions and noise multipliers
218
+ cond_pos_list = [int(x.strip()) for x in cond_position.split(',')]
219
+ noise_mult_list = [float(x.strip()) for x in noise_multipliers.split(',')]
220
+
221
+ # Process video
222
+ conditioning_video = self.process_video_frames(video_path)
223
+
224
+ progress(0.4, desc="Generating video...")
225
+ video = pipe(
226
+ prompt=prompt,
227
+ negative_prompt=negative_prompt,
228
+ conditioning_video=conditioning_video,
229
+ conditioning_indices=cond_pos_list,
230
+ conditioning_noise_multipliers=noise_mult_list,
231
+ num_inference_steps=num_inference_steps,
232
+ height=720, width=1280, num_frames=81,
233
+ seed=0, tiled=True
234
+ )
235
+
236
+ progress(0.9, desc="Saving video...")
237
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
238
+ output_filename = os.path.basename(video_path).split('.')[0]
239
+ video_filename = os.path.join(self.output_dir, f"v2v_{output_filename}_{timestamp}.mp4")
240
+ save_video(video, video_filename, fps=25, quality=5)
241
+
242
+ progress(1.0, desc="Complete!")
243
+ return video_filename, f"Video generated successfully! Saved to {video_filename}"
244
+
245
+ except Exception as e:
246
+ return None, f"Error: {str(e)}"
247
+
248
+ def generate_t2v_video(self, prompt, lora_alpha, num_inference_steps,
249
+ negative_prompt, progress=gr.Progress()):
250
+ """Generate video from text prompt"""
251
+ try:
252
+ progress(0.1, desc="Loading models...")
253
+ lora_path = "./model_zoo/PusaV1/pusa_v1.pt"
254
+ pipe = self.load_lora_and_get_pipe("t2v", lora_path, lora_alpha)
255
+
256
+ progress(0.3, desc="Generating video...")
257
+ video = pipe(
258
+ prompt=prompt,
259
+ negative_prompt=negative_prompt,
260
+ num_inference_steps=num_inference_steps,
261
+ height=720, width=1280, num_frames=81,
262
+ seed=0, tiled=True
263
+ )
264
+
265
+ progress(0.9, desc="Saving video...")
266
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
267
+ video_filename = os.path.join(self.output_dir, f"t2v_output_{timestamp}.mp4")
268
+ save_video(video, video_filename, fps=25, quality=5)
269
+
270
+ progress(1.0, desc="Complete!")
271
+ return video_filename, f"Video generated successfully! Saved to {video_filename}"
272
+
273
+ except Exception as e:
274
+ return None, f"Error: {str(e)}"
275
+
276
+ def create_demo():
277
+ demo_instance = PusaVideoDemo()
278
+
279
+ # Set custom cache directory to avoid permission issues
280
+ import tempfile
281
+ import os
282
+ try:
283
+ # Try to use a custom cache directory in the current workspace
284
+ cache_dir = os.path.join(os.getcwd(), "gradio_cache")
285
+ os.makedirs(cache_dir, exist_ok=True)
286
+ os.environ["GRADIO_TEMP_DIR"] = cache_dir
287
+ except:
288
+ pass # Fall back to default if this fails
289
+
290
+ # Helper function to safely load demo files
291
+ def safe_file_path(file_path):
292
+ """Return file path if it exists, None otherwise"""
293
+ try:
294
+ if os.path.exists(file_path):
295
+ return file_path
296
+ except:
297
+ pass
298
+ return None
299
+
300
+ # Custom CSS for fancy black design
301
+ css = """
302
+ /* === Main Theme: "Cosmic Flow" === */
303
+ :root {
304
+ --color-primary: #22d3ee; /* Cosmic Cyan */
305
+ --color-secondary: #ec4899; /* Galactic Pink */
306
+ --color-accent: #a78bfa; /* Astral Violet */
307
+ --color-background-dark: #0f172a; /* Midnight Slate */
308
+ --color-background-light: #1e293b; /* Twilight Slate */
309
+ --color-surface: rgba(30, 41, 59, 0.6); /* Glassy Slate */
310
+ --color-surface-hover: rgba(30, 41, 59, 0.9);
311
+ --color-text-light: #f1f5f9; /* Starlight White */
312
+ --color-text-medium: #94a3b8; /* Nebula Gray */
313
+ --color-text-dark: #64748b; /* Meteor Gray */
314
+ --font-main: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
315
+ --radius-lg: 20px;
316
+ --radius-md: 12px;
317
+ --radius-sm: 8px;
318
+ }
319
+
320
+ /* === Global Styles === */
321
+ .gradio-container {
322
+ font-family: var(--font-main) !important;
323
+ background: linear-gradient(135deg, var(--color-background-dark) 0%, var(--color-background-light) 100%) !important;
324
+ color: var(--color-text-light) !important;
325
+ }
326
+
327
+ * {
328
+ color: var(--color-text-light);
329
+ border-color: rgba(148, 163, 184, 0.1); /* slate-400/10% */
330
+ }
331
+
332
+ /* === Glassmorphism Containers === */
333
+ .gr-panel, .gr-box, .gr-group, .gr-column, .gr-tabitem, .gr-accordion {
334
+ background: var(--color-surface) !important;
335
+ backdrop-filter: blur(12px) !important;
336
+ -webkit-backdrop-filter: blur(12px) !important;
337
+ border: 1px solid rgba(148, 163, 184, 0.1) !important;
338
+ border-radius: var(--radius-lg) !important;
339
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) !important;
340
+ transition: all 0.3s ease !important;
341
+ }
342
+
343
+ .gr-panel:hover, .gr-box:hover, .gr-group:hover, .gr-column:hover {
344
+ background: var(--color-surface-hover) !important;
345
+ border-color: rgba(148, 163, 184, 0.2) !important;
346
+ transform: translateY(-2px) scale(1.01);
347
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.3) !important;
348
+ }
349
+
350
+ /* === Header (Static Nebula) === */
351
+ .fancy-header {
352
+ text-align: center !important;
353
+ background-color: var(--color-background-dark) !important;
354
+ padding: 40px !important;
355
+ border-radius: var(--radius-lg) !important;
356
+ margin-bottom: 40px !important;
357
+ border: 1px solid rgba(148, 163, 184, 0.2) !important;
358
+ position: relative !important;
359
+ overflow: hidden !important;
360
+ box-shadow: 0 20px 60px rgba(15, 23, 42, 0.5) !important;
361
+ }
362
+ .fancy-header::before {
363
+ content: '' !important;
364
+ position: absolute !important;
365
+ top: -150px; left: -150px; right: -150px; bottom: -150px;
366
+ background:
367
+ radial-gradient(ellipse at 20% 25%, var(--color-primary), transparent 40%),
368
+ radial-gradient(ellipse at 80% 30%, var(--color-accent), transparent 40%),
369
+ radial-gradient(ellipse at 50% 90%, var(--color-secondary), transparent 45%) !important;
370
+ opacity: 0.2 !important;
371
+ filter: blur(80px) !important;
372
+ transform: scale(1.2) !important;
373
+ z-index: 0 !important;
374
+ }
375
+ .fancy-header > * {
376
+ position: relative !important; /* Ensures content is on top of the nebula effect */
377
+ z-index: 1 !important;
378
+ }
379
+
380
+ /* === Tabs === */
381
+ .gr-tabs { background: transparent !important; }
382
+ .gr-tab-nav {
383
+ background: rgba(30, 41, 59, 0.8) !important;
384
+ border-radius: var(--radius-lg) !important;
385
+ padding: 6px !important;
386
+ border: none !important;
387
+ }
388
+ .gr-tab-nav button {
389
+ background: transparent !important;
390
+ color: var(--color-text-medium) !important;
391
+ border-radius: var(--radius-md) !important;
392
+ font-weight: 600 !important;
393
+ transition: all 0.3s ease !important;
394
+ padding: 12px 20px !important;
395
+ border: none !important;
396
+ }
397
+ .gr-tab-nav button:hover {
398
+ background: rgba(167, 139, 250, 0.2) !important;
399
+ color: var(--color-text-light) !important;
400
+ }
401
+ .gr-tab-nav button.selected {
402
+ background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-accent) 100%) !important;
403
+ color: white !important;
404
+ box-shadow: 0 8px 25px rgba(34, 211, 238, 0.3) !important;
405
+ }
406
+
407
+ /* === Primary Generate Button === */
408
+ .generate-btn, .primary-btn, button.primary, .gr-button-primary {
409
+ background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%) !important;
410
+ background-size: 250% 250% !important;
411
+ border: 2px solid transparent !important;
412
+ border-radius: var(--radius-lg) !important;
413
+ color: white !important;
414
+ font-weight: 700 !important;
415
+ padding: 18px 36px !important;
416
+ text-transform: uppercase !important;
417
+ letter-spacing: 1.5px !important;
418
+ transition: all 0.4s ease !important;
419
+ box-shadow: 0 10px 30px rgba(34, 211, 238, 0.2), 0 10px 30px rgba(236, 72, 153, 0.2) !important;
420
+ position: relative;
421
+ overflow: hidden;
422
+ z-index: 1;
423
+ }
424
+ .generate-btn::before, .primary-btn::before {
425
+ content: '' !important;
426
+ position: absolute !important;
427
+ top: 0; left: -100%; width: 100%; height: 100%;
428
+ background: linear-gradient(120deg, transparent, rgba(255,255,255,0.4), transparent);
429
+ transition: left 0.6s ease;
430
+ z-index: -1;
431
+ }
432
+ .generate-btn:hover::before, .primary-btn:hover::before {
433
+ left: 100%;
434
+ }
435
+ .generate-btn:hover, .primary-btn:hover {
436
+ transform: translateY(-5px) scale(1.03) !important;
437
+ box-shadow: 0 15px 40px rgba(34, 211, 238, 0.4), 0 15px 40px rgba(236, 72, 153, 0.4) !important;
438
+ background-position: 100% 50% !important;
439
+ }
440
+
441
+ /* === Secondary & Tertiary Buttons (e.g., "Load Example") === */
442
+ button:not(.primary):not(.selected) {
443
+ background: rgba(148, 163, 184, 0.1) !important;
444
+ border: 1px solid rgba(148, 163, 184, 0.2) !important;
445
+ color: var(--color-text-medium) !important;
446
+ border-radius: var(--radius-md) !important;
447
+ padding: 10px 20px !important;
448
+ font-weight: 500 !important;
449
+ transition: all 0.3s ease !important;
450
+ }
451
+ button:not(.primary):not(.selected):hover {
452
+ background: var(--color-accent) !important;
453
+ border-color: var(--color-accent) !important;
454
+ color: white !important;
455
+ transform: translateY(-2px);
456
+ box-shadow: 0 6px 20px rgba(167, 139, 250, 0.3) !important;
457
+ }
458
+
459
+ /* === Input Fields & Textareas === */
460
+ input, textarea, .gr-textbox, .gr-number {
461
+ background: rgba(15, 23, 42, 0.8) !important; /* Midnight Slate dark */
462
+ border: 1px solid rgba(148, 163, 184, 0.2) !important;
463
+ border-radius: var(--radius-md) !important;
464
+ color: var(--color-text-light) !important;
465
+ padding: 12px !important;
466
+ transition: all 0.3s ease !important;
467
+ }
468
+ input:focus, textarea:focus, .gr-textbox:focus-within, .gr-number:focus-within {
469
+ border-color: var(--color-primary) !important;
470
+ box-shadow: 0 0 15px rgba(34, 211, 238, 0.2) !important;
471
+ outline: none !important;
472
+ }
473
+ input::placeholder, textarea::placeholder {
474
+ color: var(--color-text-dark) !important;
475
+ }
476
+
477
+ /* === Sliders === */
478
+ .gr-slider {
479
+ --slider-track-color: rgba(15, 23, 42, 0.9);
480
+ --slider-range-color: linear-gradient(90deg, var(--color-primary) 0%, var(--color-accent) 100%);
481
+ --slider-handle-color: white;
482
+ --slider-handle-shadow: 0 4px 15px rgba(34, 211, 238, 0.4);
483
+ }
484
+ .gradio-container .gr-slider .gr-slider-track { background: var(--slider-track-color) !important; }
485
+ .gradio-container .gr-slider .gr-slider-range { background: var(--slider-range-color) !important; }
486
+ .gradio-container .gr-slider .gr-slider-handle {
487
+ background: var(--slider-handle-color) !important;
488
+ border: 2px solid var(--color-primary) !important;
489
+ box-shadow: var(--slider-handle-shadow) !important;
490
+ }
491
+
492
+ /* === File Upload === */
493
+ .gr-file, .gr-upload {
494
+ background: rgba(15, 23, 42, 0.7) !important;
495
+ border: 2px dashed var(--color-text-dark) !important;
496
+ border-radius: var(--radius-lg) !important;
497
+ transition: all 0.3s ease !important;
498
+ }
499
+ .gr-file:hover, .gr-upload:hover {
500
+ border-color: var(--color-primary) !important;
501
+ background: rgba(34, 211, 238, 0.1) !important;
502
+ }
503
+ .gr-file *, .gr-upload * { color: var(--color-text-medium) !important; background: transparent !important; }
504
+
505
+ /* === Markdown & Text === */
506
+ .gr-markdown { color: var(--color-text-light) !important; }
507
+ .gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {
508
+ background: linear-gradient(90deg, var(--color-primary) 0%, var(--color-secondary) 100%);
509
+ -webkit-background-clip: text;
510
+ -moz-background-clip: text;
511
+ background-clip: text;
512
+ -webkit-text-fill-color: transparent;
513
+ margin-bottom: 1rem;
514
+ }
515
+ .gr-markdown a {
516
+ color: var(--color-primary) !important;
517
+ text-decoration: none !important;
518
+ transition: all 0.2s ease;
519
+ }
520
+ .gr-markdown a:hover {
521
+ color: var(--color-secondary) !important;
522
+ text-decoration: underline !important;
523
+ }
524
+ label {
525
+ color: var(--color-text-medium) !important;
526
+ font-weight: 600 !important;
527
+ margin-bottom: 8px !important;
528
+ text-transform: uppercase;
529
+ font-size: 0.8rem;
530
+ letter-spacing: 0.5px;
531
+ }
532
+ .gr-info {
533
+ color: var(--color-text-dark) !important;
534
+ font-style: italic;
535
+ }
536
+
537
+ /* === Progress Bar === */
538
+ .gr-progress {
539
+ background: rgba(15, 23, 42, 0.8) !important;
540
+ border-radius: var(--radius-sm) !important;
541
+ }
542
+ .gr-progress-bar {
543
+ background: linear-gradient(90deg, var(--color-primary) 0%, var(--color-accent) 100%) !important;
544
+ border-radius: var(--radius-sm) !important;
545
+ }
546
+
547
+ /* === Scrollbar === */
548
+ ::-webkit-scrollbar { width: 10px; }
549
+ ::-webkit-scrollbar-track { background: var(--color-background-light); }
550
+ ::-webkit-scrollbar-thumb {
551
+ background: linear-gradient(var(--color-accent), var(--color-primary));
552
+ border-radius: 5px;
553
+ }
554
+ ::-webkit-scrollbar-thumb:hover {
555
+ background: linear-gradient(var(--color-primary), var(--color-secondary));
556
+ }
557
+
558
+ /* === Final cleanup & overrides === */
559
+ .gradio-container .prose {
560
+ color: var(--color-text-light) !important;
561
+ }
562
+ .gradio-container .gr-button * {
563
+ color: inherit !important;
564
+ }
565
+ """
566
+
567
+ with gr.Blocks(css=css, title="โœจ Pusa V1.0 - Revolutionary AI Video Generation โœจ", theme=gr.themes.Default(primary_hue="purple", neutral_hue="gray").set(
568
+ body_background_fill="linear-gradient(135deg, #0f172a 0%, #1e293b 100%)",
569
+ background_fill_primary="#1e293b",
570
+ background_fill_secondary="#0f172a",
571
+ border_color_primary="rgba(148, 163, 184, 0.1)"
572
+ )) as demo:
573
+
574
+ # Header
575
+ gr.HTML("""
576
+ <div class="fancy-header">
577
+ <div style="position: relative; z-index: 1;">
578
+ <h1 style="font-size: 3.5em; margin-bottom: 20px; text-shadow: 0 4px 15px rgba(0,0,0,0.4); background: none !important; color: white !important;">
579
+ โœจ PUSA V1.0 โœจ
580
+ </h1>
581
+ <h2 style="font-size: 1.4em; margin-bottom: 15px; opacity: 0.95; background: none !important; color: white !important;">
582
+ ๐ŸŽฌ Revolutionary Video Generation with Vectorized Timestep Adaptation
583
+ </h2>
584
+ <p style="font-size: 1.2em; margin-bottom: 10px; background: none !important; color: white !important;">
585
+ ๐Ÿ”ฅ <strong>BREAKTHROUGH PERFORMANCE:</strong> Surpassing Wan-I2V on Vbench-I2V with only $500 training cost! ๐Ÿ”ฅ
586
+ </p>
587
+ <p style="font-size: 1.1em; opacity: 0.9; background: none !important; color: white !important;">
588
+ ๐Ÿš€ <strong>4 Powerful Modes:</strong> I2V โ€ข Multi-Frame โ€ข V2V โ€ข T2V ๐Ÿš€
589
+ </p>
590
+ <div style="margin-top: 20px; font-size: 0.9em; opacity: 0.8; background: none !important; color: white !important;">
591
+ ๐Ÿ’Ž State-of-the-Art โ€ข โšก Lightning Fast โ€ข ๐ŸŽฏ Precision Control โ€ข ๐ŸŒŸ Professional Quality
592
+ </div>
593
+ </div>
594
+ </div>
595
+ """)
596
+
597
+ # Set default LoRA path (hidden from users)
598
+ lora_path = "./model_zoo/PusaV1/pusa_v1.pt"
599
+
600
+ # Tabs for different functionalities
601
+ with gr.Tabs():
602
+
603
+ # Tab 1: Image-to-Video (I2V)
604
+ with gr.TabItem("๐ŸŽจ Image-to-Video"):
605
+ gr.Markdown("""
606
+ ### Image-to-Video Generation (I2V)
607
+ Generate videos from a single starting image. Perfect for bringing static images to life with natural motion and animation.
608
+ """)
609
+
610
+ with gr.Row():
611
+ with gr.Column(scale=1):
612
+ gr.Markdown("#### ๐Ÿ“ท Input Image")
613
+ image_input = gr.Image(
614
+ label="Upload Single Image",
615
+ type="filepath", # This returns the file path directly
616
+ height=300
617
+ )
618
+
619
+ gr.Markdown("#### โš™๏ธ Generation Parameters")
620
+ with gr.Group():
621
+ noise_multiplier_i2v = gr.Slider(
622
+ minimum=0.0, maximum=1.0, value=0.2, step=0.1,
623
+ label="Noise Multiplier",
624
+ info="Controls how faithful the generation is to the input image (0=faithful, 1=creative)"
625
+ )
626
+ lora_alpha_i2v = gr.Slider(
627
+ minimum=0.5, maximum=3.0, value=1.4, step=0.1,
628
+ label="LoRA Alpha",
629
+ info="Controls temporal consistency (1-2 recommended)"
630
+ )
631
+ steps_i2v = gr.Slider(
632
+ minimum=10, maximum=50, value=10, step=5,
633
+ label="Inference Steps"
634
+ )
635
+
636
+ with gr.Column(scale=1):
637
+ gr.Markdown("#### ๐Ÿ“ Text Prompts")
638
+ prompt_i2v = gr.Textbox(
639
+ lines=4,
640
+ label="Prompt",
641
+ placeholder="Describe the motion and animation you want to see in the video..."
642
+ )
643
+ negative_prompt_i2v = gr.Textbox(
644
+ lines=3,
645
+ value="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",
646
+ label="Negative Prompt"
647
+ )
648
+
649
+ generate_i2v_btn = gr.Button("๐ŸŽฌ Generate I2V Video", variant="primary", size="lg", elem_classes=["generate-btn", "primary-btn"])
650
+
651
+ gr.Markdown("#### ๐Ÿ“น Output")
652
+ video_output_i2v = gr.Video(label="Generated Video")
653
+ status_i2v = gr.Textbox(label="Status", interactive=False)
654
+
655
+ # Demo examples for I2V
656
+ gr.Markdown("### ๐ŸŽญ Demo Examples")
657
+ with gr.Accordion("Example 1: Monk Meditation", open=False):
658
+ gr.Markdown("""
659
+ **Prompt:** "A wide-angle shot shows a serene monk meditating with gentle swaying and peaceful movement..."
660
+ - **Noise Multiplier:** 0.2
661
+ - **LoRA Alpha:** 1.4
662
+ """)
663
+ gr.Button("Load Example 1").click(
664
+ lambda: (0.2, 1.4, "A wide-angle shot shows a serene monk meditating perched atop a pile of weathered rocks that spell out 'ZEN'. The scene is bathed in warm sunrise light with gentle swaying movement."),
665
+ outputs=[noise_multiplier_i2v, lora_alpha_i2v, prompt_i2v]
666
+ )
667
+
668
+ with gr.Accordion("Example 2: Space Adventure", open=False):
669
+ gr.Markdown("""
670
+ **Prompt:** "A female climber rock climbing on an asteroid in deep space with dynamic movement..."
671
+ - **Noise Multiplier:** 0.3
672
+ - **LoRA Alpha:** 1.2
673
+ """)
674
+ gr.Button("Load Example 2").click(
675
+ lambda: (0.3, 1.2, "A low-angle, long exposure shot of a lone female climber, wearing shorts and tank top rock climbing on a massive asteroid in deep space. The climber moves methodically with focused determination."),
676
+ outputs=[noise_multiplier_i2v, lora_alpha_i2v, prompt_i2v]
677
+ )
678
+
679
+ # Tab 2: Multi-Frames to Video
680
+ with gr.TabItem("๐Ÿ–ผ๏ธ Multi-Frames to Video"):
681
+ gr.Markdown("""
682
+ ### Multi-Frames to Video Generation
683
+ Generate videos using multiple conditioning frames for advanced control:
684
+ - **Start-End Frames**: Create smooth transitions between two frames
685
+ - **Multi-frame Conditioning**: Use multiple frames for complex scenarios
686
+ """)
687
+
688
+ with gr.Row():
689
+ with gr.Column(scale=1):
690
+ gr.Markdown("#### ๐Ÿ“ท Input Images")
691
+ # Replace gr.Files with multiple gr.Image components for better display
692
+ with gr.Row():
693
+ image1_input = gr.Image(label="Image 1", type="filepath", height=200)
694
+ image2_input = gr.Image(label="Image 2", type="filepath", height=200)
695
+ image3_input = gr.Image(label="Image 3 (Optional)", type="filepath", height=200)
696
+
697
+ # Add a textbox to specify how many images are being used
698
+ num_images = gr.Dropdown(
699
+ choices=["2", "3"],
700
+ value="2",
701
+ label="Number of Images"
702
+ )
703
+
704
+ gr.Markdown("#### ๐ŸŽฏ Conditioning Parameters")
705
+ with gr.Group():
706
+ cond_position_multi = gr.Textbox(
707
+ value="0,20",
708
+ label="Conditioning Positions",
709
+ info="Comma-separated frame indices (0-20). E.g., '0,20' for start-end, '0,10,20' for multi-frame"
710
+ )
711
+ noise_multipliers_multi = gr.Textbox(
712
+ value="0.2,0.5",
713
+ label="Noise Multipliers",
714
+ info="Comma-separated values (0-1). Controls noise for each frame. E.g., '0.2,0.5' for start-end"
715
+ )
716
+
717
+ gr.Markdown("#### โš™๏ธ Generation Parameters")
718
+ with gr.Group():
719
+ lora_alpha_multi = gr.Slider(
720
+ minimum=0.5, maximum=3.0, value=1.4, step=0.1,
721
+ label="LoRA Alpha",
722
+ info="Controls temporal consistency (1-2 recommended)"
723
+ )
724
+ steps_multi = gr.Slider(
725
+ minimum=10, maximum=50, value=10, step=5,
726
+ label="Inference Steps"
727
+ )
728
+
729
+ with gr.Column(scale=1):
730
+ gr.Markdown("#### ๐Ÿ“ Text Prompts")
731
+ prompt_multi = gr.Textbox(
732
+ lines=4,
733
+ label="Prompt",
734
+ placeholder="Describe the transition or sequence you want to generate..."
735
+ )
736
+ negative_prompt_multi = gr.Textbox(
737
+ lines=3,
738
+ value="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",
739
+ label="Negative Prompt"
740
+ )
741
+
742
+ generate_multi_btn = gr.Button("๐ŸŽฌ Generate Multi-Frame Video", variant="primary", size="lg", elem_classes=["generate-btn", "primary-btn"])
743
+
744
+ gr.Markdown("#### ๐Ÿ“น Output")
745
+ video_output_multi = gr.Video(label="Generated Video")
746
+ status_multi = gr.Textbox(label="Status", interactive=False)
747
+
748
+ # Demo examples for Multi-Frame
749
+ gr.Markdown("### ๐ŸŽญ Demo Examples")
750
+ with gr.Accordion("Example 1: Start-End Transition", open=False):
751
+ gr.Markdown("""
752
+ **Prompt:** "Plastic injection machine opens releasing a soft inflatable figure..."
753
+ - **Conditioning Position:** 0,20 (first and last frame)
754
+ - **Noise Multiplier:** 0.2,0.5
755
+ - **LoRA Alpha:** 1.4
756
+ """)
757
+ gr.Button("Load Example 1").click(
758
+ lambda: ("0,20", "0.2,0.5", 1.4, "Plastic injection machine opens releasing a soft inflatable foamy morphing sticky figure over a hand. Isometric. Low light. Dramatic light. Macro shot. Real footage"),
759
+ outputs=[cond_position_multi, noise_multipliers_multi, lora_alpha_multi, prompt_multi]
760
+ )
761
+
762
+ with gr.Accordion("Example 2: Multi-Frame Sequence", open=False):
763
+ gr.Markdown("""
764
+ **Prompt:** "Smooth transformation sequence with gradual changes..."
765
+ - **Conditioning Position:** 0,10,20 (beginning, middle, end)
766
+ - **Noise Multiplier:** 0.2,0.4,0.6
767
+ - **LoRA Alpha:** 1.5
768
+ """)
769
+ gr.Button("Load Example 2").click(
770
+ lambda: ("0,10,20", "0.2,0.4,0.6", 1.5, "A smooth transformation sequence showing gradual morphing with consistent lighting and style throughout the video."),
771
+ outputs=[cond_position_multi, noise_multipliers_multi, lora_alpha_multi, prompt_multi]
772
+ )
773
+
774
+ # Tab 3: Video-to-Video
775
+ with gr.TabItem("๐ŸŽฅ Video-to-Video"):
776
+ gr.Markdown("""
777
+ ### Video-to-Video Generation
778
+ Transform existing videos with various conditioning strategies:
779
+ - **Video Completion**: Fill in missing parts using start-end frames
780
+ - **Video Extension**: Extend video duration using initial frames
781
+ - **Video Transition**: Create smooth transitions between scenes
782
+ """)
783
+
784
+ with gr.Row():
785
+ with gr.Column(scale=1):
786
+ gr.Markdown("#### ๐ŸŽฌ Input Video")
787
+ video_input = gr.File(
788
+ file_types=["video"],
789
+ label="Upload Video (minimum 81 frames)"
790
+ )
791
+
792
+ gr.Markdown("#### ๐ŸŽฏ Conditioning Parameters")
793
+ with gr.Group():
794
+ cond_position_v2v = gr.Textbox(
795
+ value="0,20",
796
+ label="Conditioning Positions",
797
+ info="Frame indices for conditioning. E.g., '0,20' for completion, '0,1,2,3' for extension"
798
+ )
799
+ noise_multipliers_v2v = gr.Textbox(
800
+ value="0.3,0.3",
801
+ label="Noise Multipliers",
802
+ info="Noise levels for each conditioning frame"
803
+ )
804
+
805
+ gr.Markdown("#### โš™๏ธ Generation Parameters")
806
+ with gr.Group():
807
+ lora_alpha_v2v = gr.Slider(
808
+ minimum=0.5, maximum=3.0, value=1.4, step=0.1,
809
+ label="LoRA Alpha"
810
+ )
811
+ steps_v2v = gr.Slider(
812
+ minimum=10, maximum=50, value=10, step=5,
813
+ label="Inference Steps"
814
+ )
815
+
816
+ with gr.Column(scale=1):
817
+ gr.Markdown("#### ๐Ÿ“ Text Prompts")
818
+ prompt_v2v = gr.Textbox(
819
+ lines=4,
820
+ label="Prompt",
821
+ placeholder="Describe how you want to transform the video..."
822
+ )
823
+ negative_prompt_v2v = gr.Textbox(
824
+ lines=3,
825
+ value="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",
826
+ label="Negative Prompt"
827
+ )
828
+
829
+ generate_v2v_btn = gr.Button("๐ŸŽฌ Generate Video", variant="primary", size="lg", elem_classes=["generate-btn", "primary-btn"])
830
+
831
+ gr.Markdown("#### ๐Ÿ“น Output")
832
+ video_output_v2v = gr.Video(label="Generated Video")
833
+ status_v2v = gr.Textbox(label="Status", interactive=False)
834
+
835
+ # Demo examples for V2V
836
+ gr.Markdown("### ๐ŸŽญ Demo Examples")
837
+ with gr.Accordion("Example 1: Video Completion", open=False):
838
+ gr.Markdown("""
839
+ **Prompt:** "Piggy bank surfing a tube in Teahupoo wave at dusk..."
840
+ - **Conditioning Position:** 0,20 (start and end frames)
841
+ - **Noise Multiplier:** 0.3,0.3
842
+ """)
843
+ gr.Button("Load Example 1").click(
844
+ lambda: ("0,20", "0.3,0.3", "Piggy bank surfing a tube in teahupo'o wave dusk light cinematic shot shot in 35mm film"),
845
+ outputs=[cond_position_v2v, noise_multipliers_v2v, prompt_v2v]
846
+ )
847
+
848
+ with gr.Accordion("Example 2: Video Extension", open=False):
849
+ gr.Markdown("""
850
+ **Prompt:** "Piggy bank surfing a tube in Teahupoo wave at dusk..."
851
+ - **Conditioning Position:** 0,1,2,3 (first 4 latent frames)
852
+ - **Noise Multiplier:** 0.0,0.3,0.4,0.5
853
+ """)
854
+ gr.Button("Load Example 2").click(
855
+ lambda: ("0,1,2,3", "0.0,0.3,0.4,0.5", "Piggy bank surfing a tube in teahupo'o wave dusk light cinematic shot shot in 35mm film"),
856
+ outputs=[cond_position_v2v, noise_multipliers_v2v, prompt_v2v]
857
+ )
858
+
859
+ # Tab 4: Text-to-Video
860
+ with gr.TabItem("๐Ÿ“ Text-to-Video"):
861
+ gr.Markdown("""
862
+ ### Text-to-Video Generation
863
+ Generate videos directly from text descriptions. Create entirely new video content from your imagination!
864
+ """)
865
+
866
+ with gr.Row():
867
+ with gr.Column(scale=1):
868
+ gr.Markdown("#### ๐Ÿ“ Text Prompts")
869
+ prompt_t2v = gr.Textbox(
870
+ lines=6,
871
+ label="Prompt",
872
+ placeholder="Describe the video you want to create in detail...",
873
+ value="A person is enjoying a meal of spaghetti with a fork in a cozy, dimly lit Italian restaurant."
874
+ )
875
+ negative_prompt_t2v = gr.Textbox(
876
+ lines=4,
877
+ value="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",
878
+ label="Negative Prompt"
879
+ )
880
+
881
+ gr.Markdown("#### โš™๏ธ Generation Parameters")
882
+ with gr.Group():
883
+ lora_alpha_t2v = gr.Slider(
884
+ minimum=0.5, maximum=3.0, value=1.4, step=0.1,
885
+ label="LoRA Alpha",
886
+ info="Controls generation quality and consistency"
887
+ )
888
+ steps_t2v = gr.Slider(
889
+ minimum=10, maximum=50, value=10, step=5,
890
+ label="Inference Steps"
891
+ )
892
+
893
+ with gr.Column(scale=1):
894
+ generate_t2v_btn = gr.Button("๐ŸŽฌ Generate Video", variant="primary", size="lg", elem_classes=["generate-btn", "primary-btn"])
895
+
896
+ gr.Markdown("#### ๐Ÿ“น Output")
897
+ video_output_t2v = gr.Video(label="Generated Video")
898
+ status_t2v = gr.Textbox(label="Status", interactive=False)
899
+
900
+ # Demo examples for T2V
901
+ gr.Markdown("### ๐ŸŽญ Demo Examples")
902
+ with gr.Accordion("Example 1: Restaurant Scene", open=True):
903
+ gr.Markdown("""
904
+ **Prompt:** "A person enjoying spaghetti in a cozy Italian restaurant..."
905
+ """)
906
+ gr.Button("Load Example 1").click(
907
+ lambda: "A person is enjoying a meal of spaghetti with a fork in a cozy, dimly lit Italian restaurant. The person has warm, friendly features and is dressed casually but stylishly in jeans and a colorful sweater. They are sitting at a small, round table, leaning slightly forward as they eat with enthusiasm. The spaghetti is piled high on their plate, with some strands hanging over the edge. The background shows soft lighting from nearby candles and a few other diners in the corner, creating a warm and inviting atmosphere. The scene captures a close-up view of the person's face and hands as they take a bite of spaghetti, with subtle movements of their mouth and fork. The overall style is realistic with a touch of warmth and authenticity, reflecting the comfort of a genuine dining experience.",
908
+ outputs=[prompt_t2v]
909
+ )
910
+
911
+ with gr.Accordion("Example 2: Space Adventure", open=False):
912
+ gr.Markdown("""
913
+ **Prompt:** "A female climber rock climbing on an asteroid in deep space..."
914
+ """)
915
+ gr.Button("Load Example 2").click(
916
+ lambda: "A low-angle, long exposure shot of a lone female climber, wearing shorts and tank top rock climbing on a massive asteroid in deep space. The climber is suspended against a star-filled void. Dramatic shadows across the asteroid's rugged surface, emphasizing the climber's isolation and the scale of the space rock. Dust particles float in the light beams, catching the light. The climber moves methodically, with focused determination.",
917
+ outputs=[prompt_t2v]
918
+ )
919
+
920
+ # Demo Gallery Section
921
+ with gr.Group():
922
+ gr.HTML("""
923
+ <div style="text-align: center; padding: 25px; background: linear-gradient(135deg, rgba(34, 211, 238, 0.1) 0%, rgba(167, 139, 250, 0.1) 100%); border-radius: 20px; margin: 20px 0; border: 1px solid rgba(34, 211, 238, 0.2);">
924
+ <h2 style="background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-accent) 100%); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 20px; font-size: 2.2em;">
925
+ ๐ŸŽฌ Demo Gallery - See Pusa V1.0 in Action!
926
+ </h2>
927
+ <p style="font-size: 1.2em; line-height: 1.6; margin-bottom: 15px; color: var(--color-text-light);">
928
+ Explore real examples showcasing the power and versatility of Pusa V1.0 across different generation modes.
929
+ </p>
930
+ <p style="font-size: 1.0em; margin-bottom: 10px; color: var(--color-text-medium); font-style: italic;">
931
+ ๐Ÿ“‚ Note: Demo files should be placed in ./demos/ and ./assets/ directories to display properly.
932
+ </p>
933
+ </div>
934
+ """)
935
+
936
+ with gr.Tabs():
937
+ # Image-to-Video Demo
938
+ with gr.TabItem("๐ŸŽจ I2V Demo Results"):
939
+ gr.Markdown("### ๐Ÿ“ทโžก๏ธ๐ŸŽฌ Image-to-Video Generation Example")
940
+
941
+ with gr.Row():
942
+ with gr.Column():
943
+ gr.Markdown("#### ๐Ÿ–ผ๏ธ Input Image")
944
+ demo_input_image = gr.Image(
945
+ value=safe_file_path("./demos/input_image.jpg"),
946
+ label="Monk Meditation Scene",
947
+ interactive=False
948
+ )
949
+ gr.Markdown("""
950
+ **Settings Used:**
951
+ - **Prompt:** "A wide-angle shot shows a serene monk meditating perched a top of the letter E of a pile of weathered rocks that vertically spell out 'ZEN'. The rock formation is perched atop a misty mountain peak at sunrise..."
952
+ - **Conditioning Position:** 0 (first frame)
953
+ - **Noise Multiplier:** 0.2
954
+ - **LoRA Alpha:** 1.4
955
+ - **Inference Steps:** 30
956
+ - **File Path:** ./demos/input_image.jpg
957
+ """)
958
+
959
+ with gr.Column():
960
+ gr.Markdown("#### ๐ŸŽฅ Generated Video")
961
+ demo_i2v_video = gr.Video(
962
+ value=safe_file_path("./assets/multi_frame_output_cond_0_noise_0p2.mp4"),
963
+ label="I2V Result - Single Image Animation",
964
+ height=400
965
+ )
966
+
967
+ # Multi-Frame Demo
968
+ with gr.TabItem("๐Ÿ–ผ๏ธ Multi-Frame Demo Results"):
969
+ gr.Markdown("### ๐ŸŽฏ Start-End Frame Generation Example")
970
+
971
+ with gr.Row():
972
+ with gr.Column():
973
+ gr.Markdown("#### ๐Ÿ–ผ๏ธ Input Frames")
974
+ with gr.Row():
975
+ start_frame = gr.Image(
976
+ value=safe_file_path("./demos/start_frame.jpg"),
977
+ label="Start Frame (Position 0)",
978
+ interactive=False
979
+ )
980
+ end_frame = gr.Image(
981
+ value=safe_file_path("./demos/end_frame.jpg"),
982
+ label="End Frame (Position 20)",
983
+ interactive=False
984
+ )
985
+ gr.Markdown("""
986
+ **Settings Used:**
987
+ - **Prompt:** "plastic injection machine opens releasing a soft inflatable foamy morphing sticky figure over a hand. isometric. low light. dramatic light. macro shot. real footage"
988
+ - **Conditioning Positions:** 0,20 (start and end frames)
989
+ - **Noise Multipliers:** 0.2,0.5
990
+ - **LoRA Alpha:** 1.4
991
+ - **Inference Steps:** 30
992
+ - **File Paths:** ./demos/start_frame.jpg, ./demos/end_frame.jpg
993
+ """)
994
+
995
+ with gr.Column():
996
+ gr.Markdown("#### ๐ŸŽฅ Generated Video")
997
+ demo_multi_video = gr.Video(
998
+ value=safe_file_path("./assets/multi_frame_output_cond_0_20_noise_0p2_0p5.mp4"),
999
+ label="Start-End Frame Transition",
1000
+ height=400
1001
+ )
1002
+
1003
+ # Video-to-Video Demo
1004
+ with gr.TabItem("๐ŸŽฅ V2V Demo Results"):
1005
+ gr.Markdown("### ๐ŸŽฌโžก๏ธ๐ŸŽฌ Video Extension Example")
1006
+
1007
+ with gr.Row():
1008
+ with gr.Column():
1009
+ gr.Markdown("#### ๐Ÿ“น Input Video")
1010
+ demo_input_video = gr.Video(
1011
+ value=safe_file_path("./demos/input_video.mp4"),
1012
+ label="Original Video (Input for Extension)",
1013
+ height=300
1014
+ )
1015
+ gr.Markdown("""
1016
+ **Settings Used:**
1017
+ - **Prompt:** "piggy bank surfing a tube in teahupo'o wave dusk light cinematic shot shot in 35mm film"
1018
+ - **Conditioning Positions:** 0,1,2,3 (first 4 latent frames)
1019
+ - **Noise Multipliers:** 0.0,0.3,0.4,0.5
1020
+ - **LoRA Alpha:** 1.4
1021
+ - **Inference Steps:** 30
1022
+ - **Task:** Video Extension (using first 13 frames as conditioning)
1023
+ - **File Path:** ./demos/input_video.mp4
1024
+ """)
1025
+
1026
+ with gr.Column():
1027
+ gr.Markdown("#### ๐ŸŽฅ Extended Video")
1028
+ demo_v2v_video = gr.Video(
1029
+ value=safe_file_path("./assets/v2v_input_video_cond_0_1_2_3_noise_0p0_0p3_0p4_0p5.mp4"),
1030
+ label="V2V Extension Result (81 frames total)",
1031
+ height=400
1032
+ )
1033
+
1034
+ # Text-to-Video Demo
1035
+ with gr.TabItem("๐Ÿ“ T2V Demo Results"):
1036
+ gr.Markdown("### ๐Ÿ“โžก๏ธ๐ŸŽฌ Text-to-Video Generation Example")
1037
+
1038
+ with gr.Row():
1039
+ with gr.Column():
1040
+ gr.Markdown("#### ๐Ÿ“ Text Prompt")
1041
+ gr.Textbox(
1042
+ value="A person is enjoying a meal of spaghetti with a fork in a cozy, dimly lit Italian restaurant. The person has warm, friendly features and is dressed casually but stylishly in jeans and a colorful sweater. They are sitting at a small, round table, leaning slightly forward as they eat with enthusiasm. The spaghetti is piled high on their plate, with some strands hanging over the edge. The background shows soft lighting from nearby candles and a few other diners in the corner, creating a warm and inviting atmosphere. The scene captures a close-up view of the person's face and hands as they take a bite of spaghetti, with subtle movements of their mouth and fork. The overall style is realistic with a touch of warmth and authenticity, reflecting the comfort of a genuine dining experience.",
1043
+ label="Input Prompt",
1044
+ lines=8,
1045
+ interactive=False
1046
+ )
1047
+ gr.Markdown("""
1048
+ **Settings Used:**
1049
+ - **LoRA Alpha:** 1.4
1050
+ - **Inference Steps:** 30
1051
+ - **Negative Prompt:** "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality..."
1052
+ - **Task:** Pure Text-to-Video Generation (81 frames)
1053
+ - **File Path:** ./assets/t2v_output.mp4
1054
+ """)
1055
+
1056
+ with gr.Column():
1057
+ gr.Markdown("#### ๐ŸŽฅ Generated Video")
1058
+ demo_t2v_video = gr.Video(
1059
+ value=safe_file_path("./assets/t2v_output.mp4"),
1060
+ label="T2V Result - Generated from Text Only",
1061
+ height=400
1062
+ )
1063
+
1064
+ # Comparison Section
1065
+ with gr.TabItem("๐Ÿ“Š Method Comparison"):
1066
+ gr.Markdown("### ๐Ÿ†š Pusa V1.0 vs Other Methods")
1067
+
1068
+ with gr.Group():
1069
+ gr.Markdown("""
1070
+ #### ๐Ÿ† Performance Highlights
1071
+
1072
+ **Pusa V1.0 achieves breakthrough efficiency:**
1073
+ - ๐Ÿ’ฐ **Training Cost:** Only $500 vs $10,000+ for comparable methods
1074
+ - ๐Ÿ“Š **Data Efficiency:** 4K training samples vs 100K+ typically required
1075
+ - ๐ŸŽฏ **Performance:** Surpasses Wan-I2V on Vbench-I2V metrics
1076
+ - ๐Ÿ”ง **Versatility:** 4 generation modes in one unified model
1077
+ """)
1078
+
1079
+ with gr.Row():
1080
+ with gr.Column():
1081
+ gr.Markdown("""
1082
+ #### โšก Technical Innovation
1083
+ - **Vectorized Timestep Adaptation (VTA)** for fine-grained temporal control
1084
+ - **LoRA with large rank (512)** for efficient approximation of full fine-tuning
1085
+ - **Multi-task capabilities** without task-specific training
1086
+ - **Preserved T2V abilities** while gaining new I2V/V2V capabilities
1087
+ """)
1088
+
1089
+ with gr.Column():
1090
+ gr.Markdown("""
1091
+ #### ๐ŸŽฎ Usage Modes
1092
+ 1. **Image-to-Video (I2V):** Single image โ†’ 81-frame video
1093
+ 2. **Multi-Frame:** Start-end frames โ†’ smooth transition
1094
+ 3. **Video-to-Video (V2V):** Completion, extension, editing
1095
+ 4. **Text-to-Video (T2V):** Pure text prompt โ†’ video
1096
+ """)
1097
+
1098
+ gr.HTML("""
1099
+ <div style="text-align: center; padding: 20px; background: rgba(34, 211, 238, 0.1); border-radius: 15px; margin: 20px 0;">
1100
+ <h3 style="color: var(--color-primary); margin-bottom: 15px;">
1101
+ ๐Ÿ”ฌ Research Impact
1102
+ </h3>
1103
+ <p style="font-size: 1.1em; line-height: 1.6;">
1104
+ Pusa V1.0 demonstrates that <strong>high-quality video generation doesn't require massive computational resources</strong>.
1105
+ Our vectorized timestep adaptation approach opens new possibilities for democratizing video AI research and applications.
1106
+ </p>
1107
+ </div>
1108
+ """)
1109
+
1110
+ # Information section
1111
+ with gr.Group():
1112
+ gr.HTML("""
1113
+ <div style="text-align: center; padding: 20px; background: rgba(30, 41, 59, 0.6); border-radius: 15px; margin: 20px 0; backdrop-filter: blur(12px);">
1114
+ <h2 style="background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 15px;">
1115
+ ๐Ÿ“– About Pusa V1.0
1116
+ </h2>
1117
+ <p style="font-size: 1.1em; line-height: 1.6; margin-bottom: 20px; color: var(--color-text-light);">
1118
+ <strong>Pusa V1.0</strong> leverages <span style="color: var(--color-primary);">vectorized timestep adaptation (VTA)</span> for fine-grained temporal control
1119
+ within a unified video diffusion framework. The model achieves unprecedented efficiency, surpassing Wan-I2V on Vbench-I2V with only <span style="color: var(--color-secondary);">$500 training cost</span> and 4k data.
1120
+ </p>
1121
+ </div>
1122
+ """)
1123
+
1124
+ with gr.Row():
1125
+ with gr.Column():
1126
+ gr.Markdown("""
1127
+ ### ๐Ÿ’ก Pro Tips for Best Results
1128
+
1129
+ ๐ŸŽš๏ธ **LoRA Alpha**: Use values between 1-2 for optimal balance between quality and consistency
1130
+
1131
+ ๐Ÿ”Š **Noise Multipliers**: Lower values (0.0-0.3) for faithful conditioning, higher values (0.4-1.0) for more variation
1132
+
1133
+ ๐Ÿ“ **Conditioning Positions**: Frame 0 is first frame, frame 20 is last frame in the 21-frame latent space
1134
+
1135
+ โœ๏ธ **Prompts**: Be descriptive and specific for better results
1136
+ """)
1137
+
1138
+ with gr.Column():
1139
+ gr.Markdown("""
1140
+ ### ๐Ÿ”— Important Links
1141
+
1142
+ ๐ŸŒ **[Project Page](https://yaofang-liu.github.io/Pusa_Web/)** - Official project website
1143
+
1144
+ ๐Ÿ“„ **[Technical Report](https://arxiv.org/abs/2507.16116)** - Detailed research paper
1145
+
1146
+ ๐Ÿค— **[Model on HuggingFace](https://huggingface.co/RaphaelLiu/PusaV1)** - Download models
1147
+
1148
+ ๐Ÿ“š **[Training Dataset](https://huggingface.co/datasets/RaphaelLiu/PusaV1_training)** - Training data
1149
+ """)
1150
+
1151
+ # Footer
1152
+ gr.HTML("""
1153
+ <div style="text-align: center; padding: 30px; margin-top: 40px; background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); border-radius: 15px; border: 1px solid rgba(255, 255, 255, 0.1);">
1154
+ <p style="font-size: 1.2em; margin-bottom: 10px;">
1155
+ <strong>โœจ Made with โค๏ธ for the AI Community โœจ</strong>
1156
+ </p>
1157
+ <p style="opacity: 0.8;">
1158
+ Experience the future of video generation with Pusa V1.0 ๐Ÿš€
1159
+ </p>
1160
+ </div>
1161
+ """)
1162
+
1163
+ # Event handlers
1164
+ generate_i2v_btn.click(
1165
+ fn=demo_instance.generate_i2v_video,
1166
+ inputs=[image_input, prompt_i2v, noise_multiplier_i2v,
1167
+ lora_alpha_i2v, steps_i2v, negative_prompt_i2v],
1168
+ outputs=[video_output_i2v, status_i2v]
1169
+ )
1170
+
1171
+ generate_multi_btn.click(
1172
+ fn=demo_instance.generate_multi_frames_video,
1173
+ inputs=[image1_input, image2_input, image3_input, num_images, prompt_multi, cond_position_multi, noise_multipliers_multi,
1174
+ lora_alpha_multi, steps_multi, negative_prompt_multi],
1175
+ outputs=[video_output_multi, status_multi]
1176
+ )
1177
+
1178
+ generate_v2v_btn.click(
1179
+ fn=demo_instance.generate_v2v_video,
1180
+ inputs=[video_input, prompt_v2v, cond_position_v2v, noise_multipliers_v2v,
1181
+ lora_alpha_v2v, steps_v2v, negative_prompt_v2v],
1182
+ outputs=[video_output_v2v, status_v2v]
1183
+ )
1184
+
1185
+ generate_t2v_btn.click(
1186
+ fn=demo_instance.generate_t2v_video,
1187
+ inputs=[prompt_t2v, lora_alpha_t2v, steps_t2v, negative_prompt_t2v],
1188
+ outputs=[video_output_t2v, status_t2v]
1189
+ )
1190
+
1191
+ return demo
1192
+
1193
+ if __name__ == "__main__":
1194
+ demo = create_demo()
1195
+ demo.launch(
1196
+ share=False,
1197
+ show_error=True
1198
+ )