Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import subprocess
|
| 4 |
-
import argparse
|
| 5 |
-
from pathlib import Path
|
| 6 |
import torch
|
| 7 |
import datetime
|
| 8 |
import numpy as np
|
|
@@ -13,15 +11,14 @@ import spaces
|
|
| 13 |
# --- Part 1: Auto-Setup (Clone Repo & Download Weights) ---
|
| 14 |
|
| 15 |
REPO_URL = "https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5.git"
|
| 16 |
-
REPO_DIR = "HunyuanVideo-1.5"
|
| 17 |
-
|
|
|
|
| 18 |
HF_REPO_ID = "tencent/HunyuanVideo"
|
| 19 |
|
| 20 |
# Configuration
|
| 21 |
TRANSFORMER_VERSION = "480p_i2v_distilled"
|
| 22 |
DTYPE = torch.bfloat16
|
| 23 |
-
# Set to False if you have >40GB VRAM and want everything on GPU constantly.
|
| 24 |
-
# Set to True (Default) to allow running on 16GB-24GB cards via CPU offloading.
|
| 25 |
ENABLE_OFFLOADING = True
|
| 26 |
|
| 27 |
def setup_environment():
|
|
@@ -31,19 +28,20 @@ def setup_environment():
|
|
| 31 |
|
| 32 |
# 1. Clone Repository
|
| 33 |
if not os.path.exists(REPO_DIR):
|
| 34 |
-
print(f"Cloning repository
|
| 35 |
-
subprocess.run(["git", "clone", REPO_URL], check=True)
|
| 36 |
else:
|
| 37 |
-
print(f"Repository {REPO_DIR}
|
| 38 |
|
| 39 |
# 2. Add Repo to Python Path
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
sys.path.insert(0, repo_path)
|
| 43 |
|
| 44 |
# 3. Download Weights
|
| 45 |
-
if
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
from huggingface_hub import snapshot_download
|
| 49 |
allow_patterns = [
|
|
@@ -54,11 +52,18 @@ def setup_environment():
|
|
| 54 |
"scheduler/*",
|
| 55 |
"tokenizer/*"
|
| 56 |
]
|
| 57 |
-
snapshot_download(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
print("Download complete.")
|
| 59 |
except Exception as e:
|
| 60 |
print(f"Error downloading weights: {e}")
|
| 61 |
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
| 62 |
print("Environment Ready.")
|
| 63 |
print("=" * 50)
|
| 64 |
|
|
@@ -70,12 +75,12 @@ setup_environment()
|
|
| 70 |
# Set Env Vars for HyVideo
|
| 71 |
if 'PYTORCH_CUDA_ALLOC_CONF' not in os.environ:
|
| 72 |
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
|
|
|
|
| 73 |
os.environ['RANK'] = '0'
|
| 74 |
os.environ['WORLD_SIZE'] = '1'
|
| 75 |
|
| 76 |
try:
|
| 77 |
from hyvideo.pipelines.hunyuan_video_pipeline import HunyuanVideo_1_5_Pipeline
|
| 78 |
-
from hyvideo.commons.parallel_states import initialize_parallel_state
|
| 79 |
from hyvideo.commons.infer_state import initialize_infer_state
|
| 80 |
except ImportError as e:
|
| 81 |
print(f"CRITICAL ERROR: Could not import hyvideo modules. {e}")
|
|
@@ -85,17 +90,14 @@ import gradio as gr
|
|
| 85 |
|
| 86 |
# --- Part 3: Model Initialization (Pre-Load) ---
|
| 87 |
|
| 88 |
-
#
|
| 89 |
-
#parallel_dims = initialize_parallel_state(sp=1)
|
| 90 |
-
#if torch.cuda.is_available():
|
| 91 |
-
# torch.cuda.set_device(0)
|
| 92 |
-
|
| 93 |
class ArgsNamespace:
|
| 94 |
def __init__(self):
|
| 95 |
self.use_sageattn = False
|
| 96 |
self.sage_blocks_range = "0-53"
|
| 97 |
self.enable_torch_compile = False
|
| 98 |
|
|
|
|
| 99 |
initialize_infer_state(ArgsNamespace())
|
| 100 |
|
| 101 |
# Global Pipeline Variable
|
|
@@ -104,7 +106,13 @@ pipe = None
|
|
| 104 |
def pre_load_model():
|
| 105 |
"""Loads the model into memory/GPU before UI launch."""
|
| 106 |
global pipe
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
try:
|
| 110 |
pipe = HunyuanVideo_1_5_Pipeline.create_pipeline(
|
|
@@ -115,12 +123,10 @@ def pre_load_model():
|
|
| 115 |
transformer_dtype=DTYPE,
|
| 116 |
)
|
| 117 |
print("✅ Model loaded successfully!")
|
| 118 |
-
if not ENABLE_OFFLOADING:
|
| 119 |
-
print(" Model is fully resident on GPU.")
|
| 120 |
-
else:
|
| 121 |
-
print(" Model loaded with CPU Offloading enabled (optimizes VRAM usage).")
|
| 122 |
except Exception as e:
|
| 123 |
print(f"❌ Failed to load model: {e}")
|
|
|
|
|
|
|
| 124 |
sys.exit(1)
|
| 125 |
|
| 126 |
def save_video_tensor(video_tensor, path, fps=24):
|
|
@@ -176,7 +182,6 @@ def generate(input_image, prompt, length, steps, shift, seed, guidance):
|
|
| 176 |
def create_ui():
|
| 177 |
with gr.Blocks(title="HunyuanVideo 1.5 I2V") as demo:
|
| 178 |
gr.Markdown(f"### 🎬 HunyuanVideo 1.5 I2V ({TRANSFORMER_VERSION})")
|
| 179 |
-
gr.Markdown("Model is pre-loaded. Ready to generate.")
|
| 180 |
|
| 181 |
with gr.Row():
|
| 182 |
with gr.Column():
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import subprocess
|
|
|
|
|
|
|
| 4 |
import torch
|
| 5 |
import datetime
|
| 6 |
import numpy as np
|
|
|
|
| 11 |
# --- Part 1: Auto-Setup (Clone Repo & Download Weights) ---
|
| 12 |
|
| 13 |
REPO_URL = "https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5.git"
|
| 14 |
+
REPO_DIR = os.path.abspath("HunyuanVideo-1.5")
|
| 15 |
+
# Use Absolute Path to ensure the loader finds the folder
|
| 16 |
+
MODEL_DIR = os.path.abspath("ckpts")
|
| 17 |
HF_REPO_ID = "tencent/HunyuanVideo"
|
| 18 |
|
| 19 |
# Configuration
|
| 20 |
TRANSFORMER_VERSION = "480p_i2v_distilled"
|
| 21 |
DTYPE = torch.bfloat16
|
|
|
|
|
|
|
| 22 |
ENABLE_OFFLOADING = True
|
| 23 |
|
| 24 |
def setup_environment():
|
|
|
|
| 28 |
|
| 29 |
# 1. Clone Repository
|
| 30 |
if not os.path.exists(REPO_DIR):
|
| 31 |
+
print(f"Cloning repository to {REPO_DIR}...")
|
| 32 |
+
subprocess.run(["git", "clone", REPO_URL, REPO_DIR], check=True)
|
| 33 |
else:
|
| 34 |
+
print(f"Repository exists at {REPO_DIR}")
|
| 35 |
|
| 36 |
# 2. Add Repo to Python Path
|
| 37 |
+
if REPO_DIR not in sys.path:
|
| 38 |
+
sys.path.insert(0, REPO_DIR)
|
|
|
|
| 39 |
|
| 40 |
# 3. Download Weights
|
| 41 |
+
# Check if key folders exist to verify download
|
| 42 |
+
transformer_path = os.path.join(MODEL_DIR, "transformer", TRANSFORMER_VERSION)
|
| 43 |
+
if not os.path.exists(transformer_path):
|
| 44 |
+
print(f"Downloading weights to {MODEL_DIR}...")
|
| 45 |
try:
|
| 46 |
from huggingface_hub import snapshot_download
|
| 47 |
allow_patterns = [
|
|
|
|
| 52 |
"scheduler/*",
|
| 53 |
"tokenizer/*"
|
| 54 |
]
|
| 55 |
+
snapshot_download(
|
| 56 |
+
repo_id=HF_REPO_ID,
|
| 57 |
+
local_dir=MODEL_DIR,
|
| 58 |
+
allow_patterns=allow_patterns
|
| 59 |
+
)
|
| 60 |
print("Download complete.")
|
| 61 |
except Exception as e:
|
| 62 |
print(f"Error downloading weights: {e}")
|
| 63 |
sys.exit(1)
|
| 64 |
+
else:
|
| 65 |
+
print(f"Weights found in {MODEL_DIR}")
|
| 66 |
+
|
| 67 |
print("Environment Ready.")
|
| 68 |
print("=" * 50)
|
| 69 |
|
|
|
|
| 75 |
# Set Env Vars for HyVideo
|
| 76 |
if 'PYTORCH_CUDA_ALLOC_CONF' not in os.environ:
|
| 77 |
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
|
| 78 |
+
# Even for single GPU, HyVideo code expects these env vars to be set
|
| 79 |
os.environ['RANK'] = '0'
|
| 80 |
os.environ['WORLD_SIZE'] = '1'
|
| 81 |
|
| 82 |
try:
|
| 83 |
from hyvideo.pipelines.hunyuan_video_pipeline import HunyuanVideo_1_5_Pipeline
|
|
|
|
| 84 |
from hyvideo.commons.infer_state import initialize_infer_state
|
| 85 |
except ImportError as e:
|
| 86 |
print(f"CRITICAL ERROR: Could not import hyvideo modules. {e}")
|
|
|
|
| 90 |
|
| 91 |
# --- Part 3: Model Initialization (Pre-Load) ---
|
| 92 |
|
| 93 |
+
# Mock args for inference configuration (required by internal logic)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
class ArgsNamespace:
|
| 95 |
def __init__(self):
|
| 96 |
self.use_sageattn = False
|
| 97 |
self.sage_blocks_range = "0-53"
|
| 98 |
self.enable_torch_compile = False
|
| 99 |
|
| 100 |
+
# Initialize internal state mock
|
| 101 |
initialize_infer_state(ArgsNamespace())
|
| 102 |
|
| 103 |
# Global Pipeline Variable
|
|
|
|
| 106 |
def pre_load_model():
|
| 107 |
"""Loads the model into memory/GPU before UI launch."""
|
| 108 |
global pipe
|
| 109 |
+
|
| 110 |
+
# Double check path exists
|
| 111 |
+
if not os.path.isdir(MODEL_DIR):
|
| 112 |
+
print(f"❌ Error: Model directory not found at {MODEL_DIR}")
|
| 113 |
+
sys.exit(1)
|
| 114 |
+
|
| 115 |
+
print(f"⏳ Initializing Pipeline ({TRANSFORMER_VERSION}) from {MODEL_DIR}...")
|
| 116 |
|
| 117 |
try:
|
| 118 |
pipe = HunyuanVideo_1_5_Pipeline.create_pipeline(
|
|
|
|
| 123 |
transformer_dtype=DTYPE,
|
| 124 |
)
|
| 125 |
print("✅ Model loaded successfully!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
except Exception as e:
|
| 127 |
print(f"❌ Failed to load model: {e}")
|
| 128 |
+
import traceback
|
| 129 |
+
traceback.print_exc()
|
| 130 |
sys.exit(1)
|
| 131 |
|
| 132 |
def save_video_tensor(video_tensor, path, fps=24):
|
|
|
|
| 182 |
def create_ui():
|
| 183 |
with gr.Blocks(title="HunyuanVideo 1.5 I2V") as demo:
|
| 184 |
gr.Markdown(f"### 🎬 HunyuanVideo 1.5 I2V ({TRANSFORMER_VERSION})")
|
|
|
|
| 185 |
|
| 186 |
with gr.Row():
|
| 187 |
with gr.Column():
|