Spaces:
Running
on
Zero
Running
on
Zero
Commit
Β·
2d7afa1
1
Parent(s):
bb449c5
Major Tab re-write of app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
import spaces
|
2 |
import torch
|
3 |
-
from diffusers import AutoencoderKLWan, WanImageToVideoPipeline, UniPCMultistepScheduler
|
4 |
from diffusers.utils import export_to_video
|
5 |
from transformers import CLIPVisionModel
|
6 |
import gradio as gr
|
@@ -14,43 +14,62 @@ import numpy as np
|
|
14 |
from PIL import Image
|
15 |
import random
|
16 |
|
17 |
-
#
|
18 |
-
|
|
|
19 |
|
20 |
-
#
|
|
|
|
|
|
|
|
|
21 |
LORA_REPO_ID = "vrgamedevgirl84/Wan14BT2VFusioniX"
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
MODEL_ID, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
|
30 |
)
|
|
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
-
# Load
|
|
|
|
|
37 |
try:
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
)
|
42 |
-
print("β
LoRA downloaded to:", lora_path)
|
43 |
-
|
44 |
-
# Load, set weight, and fuse the LoRA into the pipeline
|
45 |
-
pipe.load_lora_weights(lora_path, adapter_name="fusionx_lora")
|
46 |
-
pipe.set_adapters(["fusionx_lora"], adapter_weights=[0.75])
|
47 |
-
pipe.fuse_lora()
|
48 |
-
print("β
FusionX LoRA loaded and fused with a weight of 0.75.")
|
49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
except Exception as e:
|
51 |
-
print("β Error
|
52 |
traceback.print_exc()
|
53 |
|
|
|
|
|
54 |
MOD_VALUE = 32
|
55 |
DEFAULT_H_SLIDER_VALUE = 640
|
56 |
DEFAULT_W_SLIDER_VALUE = 1024
|
@@ -64,11 +83,12 @@ FIXED_FPS = 24
|
|
64 |
MIN_FRAMES_MODEL = 8
|
65 |
MAX_FRAMES_MODEL = 81
|
66 |
|
67 |
-
#
|
68 |
default_prompt_i2v = "Cinematic motion, smooth animation, detailed textures, dynamic lighting, professional cinematography"
|
|
|
69 |
default_negative_prompt = "Static image, no motion, blurred details, overexposed, underexposed, low quality, worst quality, JPEG artifacts, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, watermark, text, signature, three legs, many people in the background, walking backwards"
|
70 |
|
71 |
-
# Enhanced CSS for FusionX theme
|
72 |
custom_css = """
|
73 |
/* Enhanced FusionX theme with cinematic styling */
|
74 |
.gradio-container {
|
@@ -237,75 +257,56 @@ video {
|
|
237 |
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4) !important;
|
238 |
border: 2px solid rgba(106, 76, 147, 0.3) !important;
|
239 |
}
|
240 |
-
/*
|
241 |
-
.gr-
|
242 |
-
|
243 |
-
|
244 |
-
padding: 25px !important;
|
245 |
-
margin-top: 25px !important;
|
246 |
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
247 |
}
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
transform: scale(1.2) !important;
|
252 |
-
}
|
253 |
-
/* Responsive enhancements */
|
254 |
-
@media (max-width: 768px) {
|
255 |
-
h1 { font-size: 2.2rem !important; }
|
256 |
-
.main-container { padding: 25px !important; }
|
257 |
-
.generate-btn { padding: 12px 30px !important; font-size: 1.1rem !important; }
|
258 |
}
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
flex-wrap: wrap;
|
266 |
-
}
|
267 |
-
.badge-container img {
|
268 |
-
border-radius: 8px;
|
269 |
-
transition: transform 0.3s ease;
|
270 |
}
|
271 |
-
.
|
272 |
-
|
|
|
|
|
273 |
}
|
274 |
"""
|
275 |
|
|
|
276 |
def sanitize_prompt_for_filename(prompt: str, max_len: int = 60) -> str:
|
277 |
"""Sanitizes a prompt string to be used as a valid filename."""
|
278 |
if not prompt:
|
279 |
prompt = "video"
|
280 |
-
# Remove non-alphanumeric characters (except spaces, hyphens, underscores)
|
281 |
sanitized = re.sub(r'[^\w\s_-]', '', prompt).strip()
|
282 |
-
# Replace spaces and multiple hyphens/underscores with a single underscore
|
283 |
sanitized = re.sub(r'[\s_-]+', '_', sanitized)
|
284 |
-
# Truncate to max_len
|
285 |
return sanitized[:max_len]
|
286 |
|
287 |
def _calculate_new_dimensions_wan(pil_image, mod_val, calculation_max_area,
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
orig_w, orig_h = pil_image.size
|
292 |
if orig_w <= 0 or orig_h <= 0:
|
293 |
return default_h, default_w
|
294 |
-
|
295 |
aspect_ratio = orig_h / orig_w
|
296 |
-
|
297 |
calc_h = round(np.sqrt(calculation_max_area * aspect_ratio))
|
298 |
calc_w = round(np.sqrt(calculation_max_area / aspect_ratio))
|
299 |
-
|
300 |
calc_h = max(mod_val, (calc_h // mod_val) * mod_val)
|
301 |
calc_w = max(mod_val, (calc_w // mod_val) * mod_val)
|
302 |
-
|
303 |
new_h = int(np.clip(calc_h, min_slider_h, (max_slider_h // mod_val) * mod_val))
|
304 |
new_w = int(np.clip(calc_w, min_slider_w, (max_slider_w // mod_val) * mod_val))
|
305 |
-
|
306 |
return new_h, new_w
|
307 |
|
308 |
-
def handle_image_upload_for_dims_wan(uploaded_pil_image
|
309 |
if uploaded_pil_image is None:
|
310 |
return gr.update(value=DEFAULT_H_SLIDER_VALUE), gr.update(value=DEFAULT_W_SLIDER_VALUE)
|
311 |
try:
|
@@ -316,180 +317,201 @@ def handle_image_upload_for_dims_wan(uploaded_pil_image, current_h_val, current_
|
|
316 |
)
|
317 |
return gr.update(value=new_h), gr.update(value=new_w)
|
318 |
except Exception as e:
|
319 |
-
gr.Warning("Error
|
320 |
return gr.update(value=DEFAULT_H_SLIDER_VALUE), gr.update(value=DEFAULT_W_SLIDER_VALUE)
|
321 |
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
|
|
|
|
342 |
if input_image is None:
|
343 |
-
raise gr.Error("Please upload an input image.")
|
344 |
|
345 |
target_h = max(MOD_VALUE, (int(height) // MOD_VALUE) * MOD_VALUE)
|
346 |
target_w = max(MOD_VALUE, (int(width) // MOD_VALUE) * MOD_VALUE)
|
347 |
-
|
348 |
num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
|
349 |
-
|
350 |
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
351 |
-
|
352 |
resized_image = input_image.resize((target_w, target_h))
|
353 |
-
|
354 |
-
# Enhanced prompt for FusionX-style output
|
355 |
enhanced_prompt = f"{prompt}, cinematic quality, smooth motion, detailed animation, dynamic lighting"
|
356 |
|
357 |
with torch.inference_mode():
|
358 |
-
output_frames_list =
|
359 |
-
image=resized_image,
|
360 |
-
prompt=enhanced_prompt,
|
361 |
negative_prompt=negative_prompt,
|
362 |
-
height=target_h,
|
363 |
-
width=target_w,
|
364 |
num_frames=num_frames,
|
365 |
-
guidance_scale=float(guidance_scale),
|
366 |
num_inference_steps=int(steps),
|
367 |
generator=torch.Generator(device="cuda").manual_seed(current_seed)
|
368 |
).frames[0]
|
369 |
|
370 |
-
# Create a unique filename for download
|
371 |
sanitized_prompt = sanitize_prompt_for_filename(prompt)
|
372 |
-
filename = f"{sanitized_prompt}_{current_seed}.mp4"
|
373 |
-
|
374 |
temp_dir = tempfile.mkdtemp()
|
375 |
video_path = os.path.join(temp_dir, filename)
|
|
|
376 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
|
|
|
378 |
return video_path, current_seed, gr.File(value=video_path, visible=True, label=f"π₯ Download: {filename}")
|
379 |
|
380 |
-
with gr.Blocks() as demo:
|
381 |
-
with gr.Column(elem_classes=["main-container"]):
|
382 |
-
gr.Markdown("# β‘ FusionX Enhanced Wan 2.1 I2V (14B)")
|
383 |
|
384 |
-
|
385 |
-
|
386 |
-
|
|
|
387 |
|
388 |
-
with gr.
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
value=default_prompt_i2v,
|
398 |
-
lines=3
|
399 |
-
)
|
400 |
-
duration_seconds_input = gr.Slider(
|
401 |
-
minimum=round(MIN_FRAMES_MODEL/FIXED_FPS,1),
|
402 |
-
maximum=round(MAX_FRAMES_MODEL/FIXED_FPS,1),
|
403 |
-
step=0.1,
|
404 |
-
value=2,
|
405 |
-
label="β±οΈ Duration (seconds)",
|
406 |
-
info=f"FusionX Enhanced supports {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps. Recommended: 2-5 seconds"
|
407 |
-
)
|
408 |
-
|
409 |
-
with gr.Accordion("βοΈ Advanced FusionX Settings", open=False):
|
410 |
-
negative_prompt_input = gr.Textbox(
|
411 |
-
label="β Negative Prompt (FusionX Enhanced)",
|
412 |
-
value=default_negative_prompt,
|
413 |
-
lines=4
|
414 |
-
)
|
415 |
-
seed_input = gr.Slider(
|
416 |
-
label="π² Seed",
|
417 |
-
minimum=0,
|
418 |
-
maximum=MAX_SEED,
|
419 |
-
step=1,
|
420 |
-
value=42,
|
421 |
-
interactive=True
|
422 |
-
)
|
423 |
-
randomize_seed_checkbox = gr.Checkbox(
|
424 |
-
label="π Randomize seed",
|
425 |
-
value=True,
|
426 |
-
interactive=True
|
427 |
-
)
|
428 |
-
with gr.Row():
|
429 |
-
height_input = gr.Slider(
|
430 |
-
minimum=SLIDER_MIN_H,
|
431 |
-
maximum=SLIDER_MAX_H,
|
432 |
-
step=MOD_VALUE,
|
433 |
-
value=DEFAULT_H_SLIDER_VALUE,
|
434 |
-
label=f"π Output Height (FusionX optimized: {MOD_VALUE} multiples)"
|
435 |
)
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
step=MOD_VALUE,
|
440 |
-
value=DEFAULT_W_SLIDER_VALUE,
|
441 |
-
label=f"π Output Width (FusionX optimized: {MOD_VALUE} multiples)"
|
442 |
)
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
generate_button = gr.Button(
|
461 |
-
"π¬ Generate FusionX Enhanced Video",
|
462 |
-
variant="primary",
|
463 |
-
elem_classes=["generate-btn"]
|
464 |
-
)
|
465 |
-
|
466 |
-
with gr.Column(elem_classes=["output-container"]):
|
467 |
-
video_output = gr.Video(
|
468 |
-
label="π₯ FusionX Enhanced Generated Video",
|
469 |
-
autoplay=True,
|
470 |
-
interactive=False
|
471 |
-
)
|
472 |
-
download_output = gr.File(label="π₯ Download Video", visible=False)
|
473 |
-
|
474 |
-
input_image_component.upload(
|
475 |
-
fn=handle_image_upload_for_dims_wan,
|
476 |
-
inputs=[input_image_component, height_input, width_input],
|
477 |
-
outputs=[height_input, width_input]
|
478 |
-
)
|
479 |
-
|
480 |
-
input_image_component.clear(
|
481 |
-
fn=handle_image_upload_for_dims_wan,
|
482 |
-
inputs=[input_image_component, height_input, width_input],
|
483 |
-
outputs=[height_input, width_input]
|
484 |
-
)
|
485 |
-
|
486 |
-
ui_inputs = [
|
487 |
-
input_image_component, prompt_input, height_input, width_input,
|
488 |
-
negative_prompt_input, duration_seconds_input,
|
489 |
-
guidance_scale_input, steps_slider, seed_input, randomize_seed_checkbox
|
490 |
-
]
|
491 |
-
generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input, download_output])
|
492 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
493 |
|
494 |
if __name__ == "__main__":
|
495 |
demo.queue().launch()
|
|
|
1 |
import spaces
|
2 |
import torch
|
3 |
+
from diffusers import AutoencoderKLWan, WanImageToVideoPipeline, WanTextToVideoPipeline, UniPCMultistepScheduler
|
4 |
from diffusers.utils import export_to_video
|
5 |
from transformers import CLIPVisionModel
|
6 |
import gradio as gr
|
|
|
14 |
from PIL import Image
|
15 |
import random
|
16 |
|
17 |
+
# --- I2V (Image-to-Video) Configuration ---
|
18 |
+
I2V_MODEL_ID = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
|
19 |
+
I2V_LORA_FILENAME = "FusionX_LoRa/Wan2.1_I2V_14B_FusionX_LoRA.safetensors"
|
20 |
|
21 |
+
# --- T2V (Text-to-Video) Configuration ---
|
22 |
+
T2V_MODEL_ID = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
23 |
+
T2V_LORA_FILENAME = "FusionX_LoRa/Wan2.1_T2V_14B_FusionX_LoRA.safetensors"
|
24 |
+
|
25 |
+
# --- Common LoRA Configuration ---
|
26 |
LORA_REPO_ID = "vrgamedevgirl84/Wan14BT2VFusioniX"
|
27 |
+
|
28 |
+
# --- Load I2V Pipeline ---
|
29 |
+
print("π Loading FusionX Enhanced Wan2.1 I2V Pipeline...")
|
30 |
+
i2v_image_encoder = CLIPVisionModel.from_pretrained(I2V_MODEL_ID, subfolder="image_encoder", torch_dtype=torch.float32)
|
31 |
+
i2v_vae = AutoencoderKLWan.from_pretrained(I2V_MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
|
32 |
+
i2v_pipe = WanImageToVideoPipeline.from_pretrained(
|
33 |
+
I2V_MODEL_ID, vae=i2v_vae, image_encoder=i2v_image_encoder, torch_dtype=torch.bfloat16
|
|
|
34 |
)
|
35 |
+
i2v_pipe.scheduler = UniPCMultistepScheduler.from_config(i2v_pipe.scheduler.config, flow_shift=8.0)
|
36 |
+
i2v_pipe.to("cuda")
|
37 |
|
38 |
+
try:
|
39 |
+
i2v_lora_path = hf_hub_download(repo_id=LORA_REPO_ID, filename=I2V_LORA_FILENAME)
|
40 |
+
print("β
I2V LoRA downloaded to:", i2v_lora_path)
|
41 |
+
i2v_pipe.load_lora_weights(i2v_lora_path, adapter_name="fusionx_lora")
|
42 |
+
i2v_pipe.set_adapters(["fusionx_lora"], adapter_weights=[0.75])
|
43 |
+
i2v_pipe.fuse_lora()
|
44 |
+
print("β
I2V FusionX LoRA loaded and fused with a weight of 0.75.")
|
45 |
+
except Exception as e:
|
46 |
+
print("β Error during I2V LoRA loading:")
|
47 |
+
traceback.print_exc()
|
48 |
|
49 |
+
# --- Load T2V Pipeline ---
|
50 |
+
print("\nπ Loading FusionX Enhanced Wan2.1 T2V Pipeline...")
|
51 |
+
t2v_pipe = None
|
52 |
try:
|
53 |
+
t2v_pipe = WanTextToVideoPipeline.from_pretrained(T2V_MODEL_ID, torch_dtype=torch.bfloat16)
|
54 |
+
t2v_pipe.scheduler = UniPCMultistepScheduler.from_config(t2v_pipe.scheduler.config, flow_shift=8.0)
|
55 |
+
t2v_pipe.to("cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
+
try:
|
58 |
+
t2v_lora_path = hf_hub_download(repo_id=LORA_REPO_ID, filename=T2V_LORA_FILENAME)
|
59 |
+
print("β
T2V LoRA downloaded to:", t2v_lora_path)
|
60 |
+
t2v_pipe.load_lora_weights(t2v_lora_path, adapter_name="fusionx_lora")
|
61 |
+
t2v_pipe.set_adapters(["fusionx_lora"], adapter_weights=[0.75])
|
62 |
+
t2v_pipe.fuse_lora()
|
63 |
+
print("β
T2V FusionX LoRA loaded and fused with a weight of 0.75.")
|
64 |
+
except Exception as e:
|
65 |
+
print("β Error during T2V LoRA loading:")
|
66 |
+
traceback.print_exc()
|
67 |
except Exception as e:
|
68 |
+
print("β Critical Error: T2V Pipeline failed to load. The Text-to-Video tab will be disabled.")
|
69 |
traceback.print_exc()
|
70 |
|
71 |
+
|
72 |
+
# --- Constants and Configuration ---
|
73 |
MOD_VALUE = 32
|
74 |
DEFAULT_H_SLIDER_VALUE = 640
|
75 |
DEFAULT_W_SLIDER_VALUE = 1024
|
|
|
83 |
MIN_FRAMES_MODEL = 8
|
84 |
MAX_FRAMES_MODEL = 81
|
85 |
|
86 |
+
# --- Default Prompts ---
|
87 |
default_prompt_i2v = "Cinematic motion, smooth animation, detailed textures, dynamic lighting, professional cinematography"
|
88 |
+
default_prompt_t2v = "A breathtaking landscape with a flowing river, cinematic, 8k, photorealistic"
|
89 |
default_negative_prompt = "Static image, no motion, blurred details, overexposed, underexposed, low quality, worst quality, JPEG artifacts, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, watermark, text, signature, three legs, many people in the background, walking backwards"
|
90 |
|
91 |
+
# --- Enhanced CSS for FusionX theme ---
|
92 |
custom_css = """
|
93 |
/* Enhanced FusionX theme with cinematic styling */
|
94 |
.gradio-container {
|
|
|
257 |
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4) !important;
|
258 |
border: 2px solid rgba(106, 76, 147, 0.3) !important;
|
259 |
}
|
260 |
+
/* Tab styling */
|
261 |
+
.gr-tabs {
|
262 |
+
border-radius: 15px !important;
|
263 |
+
overflow: hidden;
|
|
|
|
|
264 |
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
265 |
}
|
266 |
+
.gr-tabs .tabs {
|
267 |
+
background-color: rgba(255, 255, 255, 0.05) !important;
|
268 |
+
border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
269 |
}
|
270 |
+
.gr-tabs .tab-item {
|
271 |
+
background: transparent !important;
|
272 |
+
color: #a9a9d8 !important;
|
273 |
+
border-radius: 10px 10px 0 0 !important;
|
274 |
+
transition: all 0.3s ease !important;
|
275 |
+
padding: 12px 20px !important;
|
|
|
|
|
|
|
|
|
|
|
276 |
}
|
277 |
+
.gr-tabs .tab-item.selected {
|
278 |
+
background: rgba(255, 255, 255, 0.1) !important;
|
279 |
+
color: #ffffff !important;
|
280 |
+
border-bottom: 2px solid #6a4c93 !important;
|
281 |
}
|
282 |
"""
|
283 |
|
284 |
+
# --- Helper Functions ---
|
285 |
def sanitize_prompt_for_filename(prompt: str, max_len: int = 60) -> str:
|
286 |
"""Sanitizes a prompt string to be used as a valid filename."""
|
287 |
if not prompt:
|
288 |
prompt = "video"
|
|
|
289 |
sanitized = re.sub(r'[^\w\s_-]', '', prompt).strip()
|
|
|
290 |
sanitized = re.sub(r'[\s_-]+', '_', sanitized)
|
|
|
291 |
return sanitized[:max_len]
|
292 |
|
293 |
def _calculate_new_dimensions_wan(pil_image, mod_val, calculation_max_area,
|
294 |
+
min_slider_h, max_slider_h,
|
295 |
+
min_slider_w, max_slider_w,
|
296 |
+
default_h, default_w):
|
297 |
orig_w, orig_h = pil_image.size
|
298 |
if orig_w <= 0 or orig_h <= 0:
|
299 |
return default_h, default_w
|
|
|
300 |
aspect_ratio = orig_h / orig_w
|
|
|
301 |
calc_h = round(np.sqrt(calculation_max_area * aspect_ratio))
|
302 |
calc_w = round(np.sqrt(calculation_max_area / aspect_ratio))
|
|
|
303 |
calc_h = max(mod_val, (calc_h // mod_val) * mod_val)
|
304 |
calc_w = max(mod_val, (calc_w // mod_val) * mod_val)
|
|
|
305 |
new_h = int(np.clip(calc_h, min_slider_h, (max_slider_h // mod_val) * mod_val))
|
306 |
new_w = int(np.clip(calc_w, min_slider_w, (max_slider_w // mod_val) * mod_val))
|
|
|
307 |
return new_h, new_w
|
308 |
|
309 |
+
def handle_image_upload_for_dims_wan(uploaded_pil_image):
|
310 |
if uploaded_pil_image is None:
|
311 |
return gr.update(value=DEFAULT_H_SLIDER_VALUE), gr.update(value=DEFAULT_W_SLIDER_VALUE)
|
312 |
try:
|
|
|
317 |
)
|
318 |
return gr.update(value=new_h), gr.update(value=new_w)
|
319 |
except Exception as e:
|
320 |
+
gr.Warning("Error calculating new dimensions. Resetting to default.")
|
321 |
return gr.update(value=DEFAULT_H_SLIDER_VALUE), gr.update(value=DEFAULT_W_SLIDER_VALUE)
|
322 |
|
323 |
+
# --- GPU Duration Estimators for @spaces.GPU ---
|
324 |
+
def get_i2v_duration(steps, duration_seconds):
|
325 |
+
"""Estimates GPU time for Image-to-Video generation."""
|
326 |
+
if steps > 8 and duration_seconds > 3: return 600
|
327 |
+
elif steps > 8 or duration_seconds > 3: return 300
|
328 |
+
else: return 150
|
329 |
+
|
330 |
+
def get_t2v_duration(steps, duration_seconds):
|
331 |
+
"""Estimates GPU time for Text-to-Video generation."""
|
332 |
+
if steps > 15 and duration_seconds > 4: return 700
|
333 |
+
elif steps > 15 or duration_seconds > 4: return 400
|
334 |
+
else: return 200
|
335 |
+
|
336 |
+
# --- Core Generation Functions ---
|
337 |
+
|
338 |
+
@spaces.GPU(duration_from_args=get_i2v_duration)
|
339 |
+
def generate_i2v_video(input_image, prompt, height, width,
|
340 |
+
negative_prompt, duration_seconds,
|
341 |
+
guidance_scale, steps,
|
342 |
+
seed, randomize_seed,
|
343 |
+
progress=gr.Progress(track_tqdm=True)):
|
344 |
+
"""Generates a video from an initial image and a prompt."""
|
345 |
if input_image is None:
|
346 |
+
raise gr.Error("Please upload an input image for Image-to-Video generation.")
|
347 |
|
348 |
target_h = max(MOD_VALUE, (int(height) // MOD_VALUE) * MOD_VALUE)
|
349 |
target_w = max(MOD_VALUE, (int(width) // MOD_VALUE) * MOD_VALUE)
|
|
|
350 |
num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
|
|
|
351 |
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
|
|
352 |
resized_image = input_image.resize((target_w, target_h))
|
|
|
|
|
353 |
enhanced_prompt = f"{prompt}, cinematic quality, smooth motion, detailed animation, dynamic lighting"
|
354 |
|
355 |
with torch.inference_mode():
|
356 |
+
output_frames_list = i2v_pipe(
|
357 |
+
image=resized_image,
|
358 |
+
prompt=enhanced_prompt,
|
359 |
negative_prompt=negative_prompt,
|
360 |
+
height=target_h,
|
361 |
+
width=target_w,
|
362 |
num_frames=num_frames,
|
363 |
+
guidance_scale=float(guidance_scale),
|
364 |
num_inference_steps=int(steps),
|
365 |
generator=torch.Generator(device="cuda").manual_seed(current_seed)
|
366 |
).frames[0]
|
367 |
|
|
|
368 |
sanitized_prompt = sanitize_prompt_for_filename(prompt)
|
369 |
+
filename = f"i2v_{sanitized_prompt}_{current_seed}.mp4"
|
|
|
370 |
temp_dir = tempfile.mkdtemp()
|
371 |
video_path = os.path.join(temp_dir, filename)
|
372 |
+
export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
|
373 |
|
374 |
+
return video_path, current_seed, gr.File(value=video_path, visible=True, label=f"π₯ Download: {filename}")
|
375 |
+
|
376 |
+
|
377 |
+
@spaces.GPU(duration_from_args=get_t2v_duration)
|
378 |
+
def generate_t2v_video(prompt, height, width,
|
379 |
+
negative_prompt, duration_seconds,
|
380 |
+
guidance_scale, steps,
|
381 |
+
seed, randomize_seed,
|
382 |
+
progress=gr.Progress(track_tqdm=True)):
|
383 |
+
"""Generates a video from a text prompt."""
|
384 |
+
if t2v_pipe is None:
|
385 |
+
raise gr.Error("Text-to-Video pipeline is not available due to a loading error.")
|
386 |
+
if not prompt:
|
387 |
+
raise gr.Error("Please enter a prompt for Text-to-Video generation.")
|
388 |
+
|
389 |
+
target_h = max(MOD_VALUE, (int(height) // MOD_VALUE) * MOD_VALUE)
|
390 |
+
target_w = max(MOD_VALUE, (int(width) // MOD_VALUE) * MOD_VALUE)
|
391 |
+
num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
|
392 |
+
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
393 |
+
enhanced_prompt = f"{prompt}, cinematic, high detail, photorealistic, professional lighting"
|
394 |
+
|
395 |
+
with torch.inference_mode():
|
396 |
+
output_frames_list = t2v_pipe(
|
397 |
+
prompt=enhanced_prompt,
|
398 |
+
negative_prompt=negative_prompt,
|
399 |
+
height=target_h,
|
400 |
+
width=target_w,
|
401 |
+
num_frames=num_frames,
|
402 |
+
guidance_scale=float(guidance_scale),
|
403 |
+
num_inference_steps=int(steps),
|
404 |
+
generator=torch.Generator(device="cuda").manual_seed(current_seed)
|
405 |
+
).frames[0]
|
406 |
+
|
407 |
+
sanitized_prompt = sanitize_prompt_for_filename(prompt)
|
408 |
+
filename = f"t2v_{sanitized_prompt}_{current_seed}.mp4"
|
409 |
+
temp_dir = tempfile.mkdtemp()
|
410 |
+
video_path = os.path.join(temp_dir, filename)
|
411 |
export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
|
412 |
+
|
413 |
return video_path, current_seed, gr.File(value=video_path, visible=True, label=f"π₯ Download: {filename}")
|
414 |
|
|
|
|
|
|
|
415 |
|
416 |
+
# --- Gradio UI Layout ---
|
417 |
+
with gr.Blocks(css=custom_css) as demo:
|
418 |
+
with gr.Column(elem_classes=["main-container"]):
|
419 |
+
gr.Markdown("# β‘ FusionX Enhanced Wan 2.1 Video Suite")
|
420 |
|
421 |
+
with gr.Tabs(elem_classes=["gr-tabs"]):
|
422 |
+
# --- Image-to-Video Tab ---
|
423 |
+
with gr.TabItem("πΌοΈ Image-to-Video", id="i2v_tab"):
|
424 |
+
with gr.Row():
|
425 |
+
with gr.Column(elem_classes=["input-container"]):
|
426 |
+
i2v_input_image = gr.Image(
|
427 |
+
type="pil",
|
428 |
+
label="πΌοΈ Input Image (auto-resizes H/W sliders)",
|
429 |
+
elem_classes=["image-upload"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
430 |
)
|
431 |
+
i2v_prompt = gr.Textbox(
|
432 |
+
label="βοΈ Prompt",
|
433 |
+
value=default_prompt_i2v, lines=3
|
|
|
|
|
|
|
434 |
)
|
435 |
+
i2v_duration = gr.Slider(
|
436 |
+
minimum=round(MIN_FRAMES_MODEL/FIXED_FPS,1),
|
437 |
+
maximum=round(MAX_FRAMES_MODEL/FIXED_FPS,1),
|
438 |
+
step=0.1, value=2, label="β±οΈ Duration (seconds)",
|
439 |
+
info=f"Generates {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps."
|
440 |
+
)
|
441 |
+
with gr.Accordion("βοΈ Advanced Settings", open=False):
|
442 |
+
i2v_neg_prompt = gr.Textbox(label="β Negative Prompt", value=default_negative_prompt, lines=4)
|
443 |
+
i2v_seed = gr.Slider(label="π² Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
|
444 |
+
i2v_rand_seed = gr.Checkbox(label="π Randomize seed", value=True, interactive=True)
|
445 |
+
with gr.Row():
|
446 |
+
i2v_height = gr.Slider(minimum=SLIDER_MIN_H, maximum=SLIDER_MAX_H, step=MOD_VALUE, value=DEFAULT_H_SLIDER_VALUE, label=f"π Height ({MOD_VALUE}px steps)")
|
447 |
+
i2v_width = gr.Slider(minimum=SLIDER_MIN_W, maximum=SLIDER_MAX_W, step=MOD_VALUE, value=DEFAULT_W_SLIDER_VALUE, label=f"π Width ({MOD_VALUE}px steps)")
|
448 |
+
i2v_steps = gr.Slider(minimum=1, maximum=20, step=1, value=8, label="π Inference Steps", info="8-10 recommended for great results.")
|
449 |
+
i2v_guidance = gr.Slider(minimum=0.0, maximum=20.0, step=0.5, value=1.0, label="π― Guidance Scale", visible=False)
|
450 |
+
|
451 |
+
i2v_generate_btn = gr.Button("π¬ Generate I2V", variant="primary", elem_classes=["generate-btn"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
452 |
|
453 |
+
with gr.Column(elem_classes=["output-container"]):
|
454 |
+
i2v_output_video = gr.Video(label="π₯ Generated Video", autoplay=True, interactive=False)
|
455 |
+
i2v_download = gr.File(label="π₯ Download Video", visible=False)
|
456 |
+
|
457 |
+
# --- Text-to-Video Tab ---
|
458 |
+
with gr.TabItem("βοΈ Text-to-Video", id="t2v_tab", interactive=t2v_pipe is not None):
|
459 |
+
if t2v_pipe is None:
|
460 |
+
gr.Markdown("<h3 style='color: #ff9999; text-align: center;'>β οΈ Text-to-Video Pipeline Failed to Load. This tab is disabled.</h3>")
|
461 |
+
else:
|
462 |
+
with gr.Row():
|
463 |
+
with gr.Column(elem_classes=["input-container"]):
|
464 |
+
t2v_prompt = gr.Textbox(
|
465 |
+
label="βοΈ Prompt",
|
466 |
+
value=default_prompt_t2v, lines=4
|
467 |
+
)
|
468 |
+
t2v_duration = gr.Slider(
|
469 |
+
minimum=round(MIN_FRAMES_MODEL/FIXED_FPS,1),
|
470 |
+
maximum=round(MAX_FRAMES_MODEL/FIXED_FPS,1),
|
471 |
+
step=0.1, value=2, label="β±οΈ Duration (seconds)",
|
472 |
+
info=f"Generates {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps."
|
473 |
+
)
|
474 |
+
with gr.Accordion("βοΈ Advanced Settings", open=False):
|
475 |
+
t2v_neg_prompt = gr.Textbox(label="β Negative Prompt", value=default_negative_prompt, lines=4)
|
476 |
+
t2v_seed = gr.Slider(label="π² Seed", minimum=0, maximum=MAX_SEED, step=1, value=1234, interactive=True)
|
477 |
+
t2v_rand_seed = gr.Checkbox(label="π Randomize seed", value=True, interactive=True)
|
478 |
+
with gr.Row():
|
479 |
+
t2v_height = gr.Slider(minimum=SLIDER_MIN_H, maximum=SLIDER_MAX_H, step=MOD_VALUE, value=DEFAULT_H_SLIDER_VALUE, label=f"π Height ({MOD_VALUE}px steps)")
|
480 |
+
t2v_width = gr.Slider(minimum=SLIDER_MIN_W, maximum=SLIDER_MAX_W, step=MOD_VALUE, value=DEFAULT_W_SLIDER_VALUE, label=f"π Width ({MOD_VALUE}px steps)")
|
481 |
+
t2v_steps = gr.Slider(minimum=1, maximum=25, step=1, value=15, label="π Inference Steps", info="15-20 recommended for quality.")
|
482 |
+
t2v_guidance = gr.Slider(minimum=0.0, maximum=20.0, step=0.5, value=7.5, label="π― Guidance Scale")
|
483 |
+
|
484 |
+
t2v_generate_btn = gr.Button("π¬ Generate T2V", variant="primary", elem_classes=["generate-btn"])
|
485 |
+
|
486 |
+
with gr.Column(elem_classes=["output-container"]):
|
487 |
+
t2v_output_video = gr.Video(label="π₯ Generated Video", autoplay=True, interactive=False)
|
488 |
+
t2v_download = gr.File(label="π₯ Download Video", visible=False)
|
489 |
+
|
490 |
+
# --- Event Handlers ---
|
491 |
+
# I2V Handlers
|
492 |
+
i2v_input_image.upload(
|
493 |
+
fn=handle_image_upload_for_dims_wan,
|
494 |
+
inputs=[i2v_input_image],
|
495 |
+
outputs=[i2v_height, i2v_width]
|
496 |
+
)
|
497 |
+
i2v_input_image.clear(
|
498 |
+
fn=lambda: (DEFAULT_H_SLIDER_VALUE, DEFAULT_W_SLIDER_VALUE),
|
499 |
+
inputs=[],
|
500 |
+
outputs=[i2v_height, i2v_width]
|
501 |
+
)
|
502 |
+
i2v_generate_btn.click(
|
503 |
+
fn=generate_i2v_video,
|
504 |
+
inputs=[i2v_input_image, i2v_prompt, i2v_height, i2v_width, i2v_neg_prompt, i2v_duration, i2v_guidance, i2v_steps, i2v_seed, i2v_rand_seed],
|
505 |
+
outputs=[i2v_output_video, i2v_seed, i2v_download]
|
506 |
+
)
|
507 |
+
|
508 |
+
# T2V Handlers
|
509 |
+
if t2v_pipe is not None:
|
510 |
+
t2v_generate_btn.click(
|
511 |
+
fn=generate_t2v_video,
|
512 |
+
inputs=[t2v_prompt, t2v_height, t2v_width, t2v_neg_prompt, t2v_duration, t2v_guidance, t2v_steps, t2v_seed, t2v_rand_seed],
|
513 |
+
outputs=[t2v_output_video, t2v_seed, t2v_download]
|
514 |
+
)
|
515 |
|
516 |
if __name__ == "__main__":
|
517 |
demo.queue().launch()
|