Spaces:
Running
on
Zero
Running
on
Zero
File size: 28,205 Bytes
9867d34 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 |
import os
import tempfile
import gradio as gr
import torch
import torchaudio
from loguru import logger
from typing import Optional, Tuple
import random
import numpy as np
from hunyuanvideo_foley.utils.model_utils import load_model
from hunyuanvideo_foley.utils.feature_utils import feature_process
from hunyuanvideo_foley.utils.model_utils import denoise_process
from hunyuanvideo_foley.utils.media_utils import merge_audio_video
# Global variables for model storage
model_dict = None
cfg = None
device = None
# need to modify the model path
MODEL_PATH = os.environ.get("HIFI_FOLEY_MODEL_PATH", "./pretrained_models/")
CONFIG_PATH = "configs/hunyuanvideo-foley-xxl.yaml"
def setup_device(device_str: str = "auto", gpu_id: int = 0) -> torch.device:
"""Setup computing device"""
if device_str == "auto":
if torch.cuda.is_available():
device = torch.device(f"cuda:{gpu_id}")
logger.info(f"Using CUDA device: {device}")
elif torch.backends.mps.is_available():
device = torch.device("mps")
logger.info("Using MPS device")
else:
device = torch.device("cpu")
logger.info("Using CPU device")
else:
if device_str == "cuda":
device = torch.device(f"cuda:{gpu_id}")
else:
device = torch.device(device_str)
logger.info(f"Using specified device: {device}")
return device
def auto_load_models() -> str:
"""Automatically load preset models"""
global model_dict, cfg, device
try:
if not os.path.exists(MODEL_PATH):
return f"β Model file not found: {MODEL_PATH}"
if not os.path.exists(CONFIG_PATH):
return f"β Config file not found: {CONFIG_PATH}"
# Use GPU by default
device = setup_device("auto", 0)
# Load model
logger.info("Auto-loading model...")
logger.info(f"Model path: {MODEL_PATH}")
logger.info(f"Config path: {CONFIG_PATH}")
model_dict, cfg = load_model(MODEL_PATH, CONFIG_PATH, device)
logger.info("β
Model loaded successfully!")
return "β
Model loaded successfully!"
except Exception as e:
logger.error(f"Model loading failed: {str(e)}")
return f"β Model loading failed: {str(e)}"
def infer_single_video(
video_file,
text_prompt: str,
guidance_scale: float = 4.5,
num_inference_steps: int = 50,
sample_nums: int = 1
) -> Tuple[list, str]:
"""Single video inference"""
global model_dict, cfg, device
if model_dict is None or cfg is None:
return [], "β Please load the model first!"
if video_file is None:
return [], "β Please upload a video file!"
# Allow empty text prompt, use empty string if no prompt provided
if text_prompt is None:
text_prompt = ""
text_prompt = text_prompt.strip()
try:
logger.info(f"Processing video: {video_file}")
logger.info(f"Text prompt: {text_prompt}")
# Feature processing
visual_feats, text_feats, audio_len_in_s = feature_process(
video_file,
text_prompt,
model_dict,
cfg
)
# Denoising process to generate multiple audio samples
# Note: The model now generates sample_nums audio samples per inference
# The denoise_process function returns audio with shape [batch_size, channels, samples]
logger.info(f"Generating {sample_nums} audio samples...")
audio, sample_rate = denoise_process(
visual_feats,
text_feats,
audio_len_in_s,
model_dict,
cfg,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
batch_size=sample_nums
)
# Create temporary files to save results
temp_dir = tempfile.mkdtemp()
video_outputs = []
# Process each generated audio sample
for i in range(sample_nums):
# Save audio file
audio_output = os.path.join(temp_dir, f"generated_audio_{i+1}.wav")
torchaudio.save(audio_output, audio[i], sample_rate)
# Merge video and audio
video_output = os.path.join(temp_dir, f"video_with_audio_{i+1}.mp4")
merge_audio_video(audio_output, video_file, video_output)
video_outputs.append(video_output)
logger.info(f"Inference completed! Generated {sample_nums} samples.")
return video_outputs, f"β
Generated {sample_nums} audio sample(s) successfully!"
except Exception as e:
logger.error(f"Inference failed: {str(e)}")
return [], f"β Inference failed: {str(e)}"
def update_video_outputs(video_list, status_msg):
"""Update video outputs based on the number of generated samples"""
# Initialize all outputs as None
outputs = [None] * 6
# Set values based on generated videos
for i, video_path in enumerate(video_list[:6]): # Max 6 samples
outputs[i] = video_path
# Return all outputs plus status message
return tuple(outputs + [status_msg])
def create_gradio_interface():
"""Create Gradio interface"""
# Custom CSS for beautiful interface with better contrast
css = """
.gradio-container {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
}
.main-header {
text-align: center;
padding: 2rem 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 20px;
margin-bottom: 2rem;
box-shadow: 0 8px 32px rgba(0,0,0,0.15);
}
.main-header h1 {
color: white;
font-size: 3rem;
font-weight: 700;
margin-bottom: 0.5rem;
text-shadow: 0 2px 10px rgba(0,0,0,0.3);
}
.main-header p {
color: rgba(255, 255, 255, 0.95);
font-size: 1.2rem;
font-weight: 300;
}
.status-card {
background: white;
border-radius: 15px;
padding: 1rem;
margin-bottom: 1.5rem;
border: 1px solid #e1e5e9;
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
}
.status-card label {
color: #2d3748 !important;
font-weight: 600 !important;
}
.usage-guide h3 {
color: #2d3748 !important;
font-weight: 600 !important;
margin-bottom: 0.5rem !important;
}
.usage-guide p {
color: #4a5568 !important;
font-size: 1rem !important;
line-height: 1.6 !important;
margin: 0.5rem 0 !important;
}
.usage-guide strong {
color: #1a202c !important;
font-weight: 700 !important;
}
.usage-guide em {
color: #1a202c !important;
font-weight: 700 !important;
font-style: normal !important;
}
.main-interface {
margin-bottom: 2rem;
}
.input-section {
background: white;
border-radius: 20px;
padding: 2rem;
margin-right: 1rem;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
border: 1px solid #e1e5e9;
}
.input-section h3 {
color: #2d3748 !important;
font-weight: 600 !important;
margin-bottom: 1rem !important;
}
.input-section label {
color: #4a5568 !important;
font-weight: 500 !important;
}
.output-section {
background: white;
border-radius: 20px;
padding: 2rem;
margin-left: 1rem;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
border: 1px solid #e1e5e9;
}
.output-section h3 {
color: #2d3748 !important;
font-weight: 600 !important;
margin-bottom: 1rem !important;
}
.output-section label {
color: #4a5568 !important;
font-weight: 500 !important;
}
.examples-section h3 {
color: #2d3748 !important;
font-weight: 600 !important;
margin-bottom: 1.5rem !important;
}
.generate-btn {
background: linear-gradient(45deg, #667eea, #764ba2) !important;
border: none !important;
color: white !important;
font-weight: 600 !important;
font-size: 1.1rem !important;
padding: 12px 30px !important;
border-radius: 25px !important;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4) !important;
transition: all 0.3s ease !important;
}
.generate-btn:hover {
transform: translateY(-2px) !important;
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6) !important;
}
.examples-section {
background: white;
border-radius: 20px;
padding: 2rem;
margin-top: 2rem;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
border: 1px solid #e1e5e9;
}
.examples-section p {
color: #4a5568 !important;
margin-bottom: 1rem !important;
}
.example-row {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 15px;
padding: 1.5rem;
margin: 1rem 0;
transition: all 0.3s ease;
align-items: center;
}
.example-row:hover {
border-color: #667eea;
transform: translateY(-2px);
box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15);
}
.example-row .markdown {
color: #2d3748 !important;
}
.example-row .markdown p {
color: #2d3748 !important;
margin: 0.5rem 0 !important;
line-height: 1.5 !important;
}
.example-row .markdown strong {
color: #1a202c !important;
font-weight: 600 !important;
}
/* Example grid layout styles */
.example-grid-row {
margin: 1rem 0;
gap: 1rem;
}
.example-item {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 15px;
padding: 1rem;
transition: all 0.3s ease;
margin: 0.25rem;
max-width: 250px;
margin-left: auto;
margin-right: auto;
}
.example-item:hover {
border-color: #667eea;
transform: translateY(-2px);
box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15);
}
.example-caption {
margin: 0.5rem 0 !important;
min-height: 2.8rem !important;
display: flex !important;
align-items: flex-start !important;
}
.example-caption p {
color: #2d3748 !important;
font-size: 0.9rem !important;
line-height: 1.4 !important;
margin: 0.5rem 0 !important;
}
/* Multi-video gallery styles */
.additional-samples {
margin-top: 1rem;
gap: 0.5rem;
}
.additional-samples .gradio-video {
border-radius: 10px;
overflow: hidden;
}
/* Video gallery responsive layout */
.video-gallery {
display: grid;
gap: 1rem;
margin-top: 1rem;
}
.video-gallery.single {
grid-template-columns: 1fr;
}
.video-gallery.dual {
grid-template-columns: 1fr 1fr;
}
.video-gallery.multi {
grid-template-columns: repeat(2, 1fr);
grid-template-rows: auto auto auto;
}
.footer-text {
color: #718096 !important;
text-align: center;
padding: 2rem;
font-size: 0.9rem;
}
/* Video component styling for consistent size */
.input-section video,
.output-section video,
.example-row video {
width: 100% !important;
height: 300px !important;
object-fit: contain !important;
border-radius: 10px !important;
background-color: #000 !important;
}
.example-row video {
height: 150px !important;
}
/* Fix for additional samples video display */
.additional-samples video {
height: 150px !important;
object-fit: contain !important;
border-radius: 10px !important;
background-color: #000 !important;
}
.additional-samples .gradio-video {
border-radius: 10px !important;
overflow: hidden !important;
background-color: #000 !important;
}
.additional-samples .gradio-video > div {
background-color: #000 !important;
border-radius: 10px !important;
}
/* Video container styling */
.input-section .video-container,
.output-section .video-container,
.example-row .video-container {
background-color: #000 !important;
border-radius: 10px !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
overflow: hidden !important;
}
/* Ensure proper alignment */
.example-row {
display: flex !important;
align-items: stretch !important;
}
.example-row > div {
display: flex !important;
flex-direction: column !important;
justify-content: center !important;
}
/* Video wrapper for better control */
.video-wrapper {
position: relative !important;
width: 100% !important;
background: #000 !important;
border-radius: 10px !important;
overflow: hidden !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
}
"""
with gr.Blocks(css=css, title="HunyuanVideo-Foley") as app:
# Main header
with gr.Column(elem_classes=["main-header"]):
gr.HTML("""
<h1>π΅ HunyuanVideo-Foley</h1>
<p>Text-Video-to-Audio Synthesis: Generate realistic audio from video and text descriptions</p>
""")
# Usage Guide
with gr.Column(elem_classes=["status-card"]):
gr.Markdown("""
### π Quick Start Guide
**1.** Upload your video file\t**2.** Add optional text description\t**3.** Adjust sample numbers (1-6)\t**4.** Click Generate Audio
π‘ For quick start, you can load the prepared examples by clicking the button.
""", elem_classes=["usage-guide"])
# Main inference interface - Input and Results side by side
with gr.Row(elem_classes=["main-interface"]):
# Input section
with gr.Column(scale=1, elem_classes=["input-section"]):
gr.Markdown("### πΉ Video Input")
video_input = gr.Video(
label="Upload Video",
info="Supported formats: MP4, AVI, MOV, etc.",
height=300
)
text_input = gr.Textbox(
label="π― Audio Description (English)",
placeholder="A person walks on frozen ice",
lines=3,
info="Describe the audio you want to generate (optional)"
)
with gr.Row():
guidance_scale = gr.Slider(
minimum=1.0,
maximum=10.0,
value=4.5,
step=0.1,
label="ποΈ CFG Scale",
)
inference_steps = gr.Slider(
minimum=10,
maximum=100,
value=50,
step=5,
label="β‘ Steps",
)
sample_nums = gr.Slider(
minimum=1,
maximum=6,
value=1,
step=1,
label="π² Sample Nums",
)
generate_btn = gr.Button(
"π΅ Generate Audio",
variant="primary",
elem_classes=["generate-btn"]
)
# Results section
with gr.Column(scale=1, elem_classes=["output-section"]):
gr.Markdown("### π₯ Generated Results")
# Multi-video gallery for displaying multiple generated samples
with gr.Column():
# Primary video (Sample 1)
video_output_1 = gr.Video(
label="Sample 1",
height=250,
visible=True
)
# Additional videos (Samples 2-6) - initially hidden
with gr.Row(elem_classes=["additional-samples"]):
with gr.Column(scale=1):
video_output_2 = gr.Video(
label="Sample 2",
height=150,
visible=False
)
video_output_3 = gr.Video(
label="Sample 3",
height=150,
visible=False
)
with gr.Column(scale=1):
video_output_4 = gr.Video(
label="Sample 4",
height=150,
visible=False
)
video_output_5 = gr.Video(
label="Sample 5",
height=150,
visible=False
)
# Sample 6 - full width
video_output_6 = gr.Video(
label="Sample 6",
height=150,
visible=False
)
result_text = gr.Textbox(
label="Status",
interactive=False,
lines=2
)
# Examples section at the bottom
with gr.Column(elem_classes=["examples-section"]):
gr.Markdown("### π Examples")
gr.Markdown("Click on any example to load it into the interface above")
# Define your custom examples here - 8 examples total
examples_data = [
# Example 1
{
"caption": "A person walks on frozen ice",
"video_path": "examples/1_video.mp4",
"result_path": "examples/1_result.mp4"
},
# Example 2
{
"caption": "With a faint sound as their hands parted, the two embraced, a soft 'mm' escaping between them.",
"video_path": "examples/2_video.mp4",
"result_path": "examples/2_result.mp4"
},
# Example 3
{
"caption": "The sound of the number 3's bouncing footsteps is as light and clear as glass marbles hitting the ground. Each step carries a magical sound.",
"video_path": "examples/3_video.mp4",
"result_path": "examples/3_result.mp4"
},
# Example 4
{
"caption": "gentle gurgling of the stream's current, and music plays in the background which is a beautiful and serene piano solo with a hint of classical charm, evoking a sense of peace and serenity in people's hearts.",
"video_path": "examples/4_video.mp4",
"result_path": "examples/4_result.mp4"
},
# Example 5 - Add your new examples here
{
"caption": "snow crunching under the snowboard's edge.",
"video_path": "examples/5_video.mp4",
"result_path": "examples/5_result.mp4"
},
# Example 6
{
"caption": "The crackling of the fire, the whooshing of the flames, and the occasional crisp popping of charred leaves filled the forest.",
"video_path": "examples/6_video.mp4",
"result_path": "examples/6_result.mp4"
},
# Example 7
{
"caption": "humming of the scooter engine accelerates slowly.",
"video_path": "examples/7_video.mp4",
"result_path": "examples/7_result.mp4"
},
# Example 8
{
"caption": "splash of water and loud thud as person hits the surface.",
"video_path": "examples/8_video.mp4",
"result_path": "examples/8_result.mp4"
}
]
# Create example grid - 4 examples per row, 2 rows total
example_buttons = []
for row in range(2): # 2 rows
with gr.Row(elem_classes=["example-grid-row"]):
for col in range(4): # 4 columns
idx = row * 4 + col
if idx < len(examples_data):
example = examples_data[idx]
with gr.Column(scale=1, elem_classes=["example-item"]):
# Video thumbnail
if os.path.exists(example['video_path']):
example_video = gr.Video(
value=example['video_path'],
label=f"Example {idx+1}",
interactive=False,
show_label=True,
height=180
)
else:
example_video = gr.HTML(f"""
<div style="background: #f0f0f0; padding: 15px; text-align: center; border-radius: 8px; height: 180px; display: flex; align-items: center; justify-content: center;">
<div>
<p style="color: #666; margin: 0; font-size: 12px;">πΉ Video not found</p>
<small style="color: #999; font-size: 10px;">{example['video_path']}</small>
</div>
</div>
""")
# Caption (truncated for grid layout)
caption_preview = example['caption'][:60] + "..." if len(example['caption']) > 60 else example['caption']
gr.Markdown(f"{caption_preview}", elem_classes=["example-caption"])
# Load button
example_btn = gr.Button(
f"Load Example {idx+1}",
variant="secondary",
size="sm"
)
example_buttons.append((example_btn, example))
# Event handlers
def process_inference(video_file, text_prompt, guidance_scale, inference_steps, sample_nums):
# Generate videos
video_list, status_msg = infer_single_video(
video_file, text_prompt, guidance_scale, inference_steps, int(sample_nums)
)
# Update outputs with proper visibility
return update_video_outputs(video_list, status_msg)
# Add dynamic visibility control based on sample_nums
def update_visibility(sample_nums):
sample_nums = int(sample_nums)
return [
gr.update(visible=True), # Sample 1 always visible
gr.update(visible=sample_nums >= 2), # Sample 2
gr.update(visible=sample_nums >= 3), # Sample 3
gr.update(visible=sample_nums >= 4), # Sample 4
gr.update(visible=sample_nums >= 5), # Sample 5
gr.update(visible=sample_nums >= 6), # Sample 6
]
# Update visibility when sample_nums changes
sample_nums.change(
fn=update_visibility,
inputs=[sample_nums],
outputs=[video_output_1, video_output_2, video_output_3, video_output_4, video_output_5, video_output_6]
)
generate_btn.click(
fn=process_inference,
inputs=[video_input, text_input, guidance_scale, inference_steps, sample_nums],
outputs=[
video_output_1, # Sample 1 value
video_output_2, # Sample 2 value
video_output_3, # Sample 3 value
video_output_4, # Sample 4 value
video_output_5, # Sample 5 value
video_output_6, # Sample 6 value
result_text
]
)
# Add click handlers for example buttons
for btn, example in example_buttons:
def create_example_handler(ex):
def handler():
# Check if files exist, if not, return placeholder message
if os.path.exists(ex['video_path']):
video_file = ex['video_path']
else:
video_file = None
if os.path.exists(ex['result_path']):
result_video = ex['result_path']
else:
result_video = None
status_msg = f"β
Loaded example with caption: {ex['caption'][:50]}..."
if not video_file:
status_msg += f"\nβ οΈ Video file not found: {ex['video_path']}"
if not result_video:
status_msg += f"\nβ οΈ Result video not found: {ex['result_path']}"
return video_file, ex['caption'], result_video, status_msg
return handler
btn.click(
fn=create_example_handler(example),
outputs=[video_input, text_input, video_output_1, result_text]
)
# Footer
gr.HTML("""
<div class="footer-text">
<p>π Powered by HunyuanVideo-Foley | Generate high-quality audio from video and text descriptions</p>
</div>
""")
return app
def set_manual_seed(global_seed):
random.seed(global_seed)
np.random.seed(global_seed)
torch.manual_seed(global_seed)
if __name__ == "__main__":
set_manual_seed(1)
# Setup logging
logger.remove()
logger.add(lambda msg: print(msg, end=''), level="INFO")
# Auto-load model
logger.info("Starting application and loading model...")
model_load_result = auto_load_models()
logger.info(model_load_result)
# Create and launch Gradio app
app = create_gradio_interface()
# Log completion status
if "successfully" in model_load_result:
logger.info("Application ready, model loaded")
app.launch(
server_name="0.0.0.0",
server_port=8080,
share=False,
debug=False,
show_error=True
)
|