Spaces:
Runtime error
Runtime error
Delete app_endframe.py
Browse files- app_endframe.py +0 -923
app_endframe.py
DELETED
|
@@ -1,923 +0,0 @@
|
|
| 1 |
-
from diffusers_helper.hf_login import login
|
| 2 |
-
|
| 3 |
-
import os
|
| 4 |
-
|
| 5 |
-
os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))
|
| 6 |
-
|
| 7 |
-
import gradio as gr
|
| 8 |
-
import torch
|
| 9 |
-
import traceback
|
| 10 |
-
import einops
|
| 11 |
-
import safetensors.torch as sf
|
| 12 |
-
import numpy as np
|
| 13 |
-
import argparse
|
| 14 |
-
import random
|
| 15 |
-
import math
|
| 16 |
-
# 20250506 pftq: Added for video input loading
|
| 17 |
-
import decord
|
| 18 |
-
# 20250506 pftq: Added for progress bars in video_encode
|
| 19 |
-
from tqdm import tqdm
|
| 20 |
-
# 20250506 pftq: Normalize file paths for Windows compatibility
|
| 21 |
-
import pathlib
|
| 22 |
-
# 20250506 pftq: for easier to read timestamp
|
| 23 |
-
from datetime import datetime
|
| 24 |
-
# 20250508 pftq: for saving prompt to mp4 comments metadata
|
| 25 |
-
import imageio_ffmpeg
|
| 26 |
-
import tempfile
|
| 27 |
-
import shutil
|
| 28 |
-
import subprocess
|
| 29 |
-
import spaces
|
| 30 |
-
from PIL import Image
|
| 31 |
-
from diffusers import AutoencoderKLHunyuanVideo
|
| 32 |
-
from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
|
| 33 |
-
from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
|
| 34 |
-
from diffusers_helper.utils import save_bcthw_as_mp4, crop_or_pad_yield_mask, soft_append_bcthw, resize_and_center_crop, state_dict_weighted_merge, state_dict_offset_merge, generate_timestamp
|
| 35 |
-
from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
|
| 36 |
-
from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
|
| 37 |
-
from diffusers_helper.memory import cpu, gpu, get_cuda_free_memory_gb, move_model_to_device_with_memory_preservation, offload_model_from_device_for_memory_preservation, fake_diffusers_current_device, DynamicSwapInstaller, unload_complete_models, load_model_as_complete
|
| 38 |
-
from diffusers_helper.thread_utils import AsyncStream, async_run
|
| 39 |
-
from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
|
| 40 |
-
from transformers import SiglipImageProcessor, SiglipVisionModel
|
| 41 |
-
from diffusers_helper.clip_vision import hf_clip_vision_encode
|
| 42 |
-
from diffusers_helper.bucket_tools import find_nearest_bucket
|
| 43 |
-
|
| 44 |
-
parser = argparse.ArgumentParser()
|
| 45 |
-
parser.add_argument('--share', action='store_true')
|
| 46 |
-
parser.add_argument("--server", type=str, default='0.0.0.0')
|
| 47 |
-
parser.add_argument("--port", type=int, required=False)
|
| 48 |
-
parser.add_argument("--inbrowser", action='store_true')
|
| 49 |
-
args = parser.parse_args()
|
| 50 |
-
|
| 51 |
-
print(args)
|
| 52 |
-
|
| 53 |
-
free_mem_gb = get_cuda_free_memory_gb(gpu)
|
| 54 |
-
high_vram = free_mem_gb > 60
|
| 55 |
-
|
| 56 |
-
print(f'Free VRAM {free_mem_gb} GB')
|
| 57 |
-
print(f'High-VRAM Mode: {high_vram}')
|
| 58 |
-
|
| 59 |
-
text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
|
| 60 |
-
text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
|
| 61 |
-
tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
|
| 62 |
-
tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
|
| 63 |
-
vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
|
| 64 |
-
|
| 65 |
-
feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
|
| 66 |
-
image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
|
| 67 |
-
|
| 68 |
-
transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePackI2V_HY', torch_dtype=torch.bfloat16).cpu()
|
| 69 |
-
|
| 70 |
-
vae.eval()
|
| 71 |
-
text_encoder.eval()
|
| 72 |
-
text_encoder_2.eval()
|
| 73 |
-
image_encoder.eval()
|
| 74 |
-
transformer.eval()
|
| 75 |
-
|
| 76 |
-
if not high_vram:
|
| 77 |
-
vae.enable_slicing()
|
| 78 |
-
vae.enable_tiling()
|
| 79 |
-
|
| 80 |
-
transformer.high_quality_fp32_output_for_inference = True
|
| 81 |
-
print('transformer.high_quality_fp32_output_for_inference = True')
|
| 82 |
-
|
| 83 |
-
transformer.to(dtype=torch.bfloat16)
|
| 84 |
-
vae.to(dtype=torch.float16)
|
| 85 |
-
image_encoder.to(dtype=torch.float16)
|
| 86 |
-
text_encoder.to(dtype=torch.float16)
|
| 87 |
-
text_encoder_2.to(dtype=torch.float16)
|
| 88 |
-
|
| 89 |
-
vae.requires_grad_(False)
|
| 90 |
-
text_encoder.requires_grad_(False)
|
| 91 |
-
text_encoder_2.requires_grad_(False)
|
| 92 |
-
image_encoder.requires_grad_(False)
|
| 93 |
-
transformer.requires_grad_(False)
|
| 94 |
-
|
| 95 |
-
if not high_vram:
|
| 96 |
-
# DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster
|
| 97 |
-
DynamicSwapInstaller.install_model(transformer, device=gpu)
|
| 98 |
-
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
| 99 |
-
else:
|
| 100 |
-
text_encoder.to(gpu)
|
| 101 |
-
text_encoder_2.to(gpu)
|
| 102 |
-
image_encoder.to(gpu)
|
| 103 |
-
vae.to(gpu)
|
| 104 |
-
transformer.to(gpu)
|
| 105 |
-
|
| 106 |
-
stream = AsyncStream()
|
| 107 |
-
|
| 108 |
-
outputs_folder = './outputs/'
|
| 109 |
-
os.makedirs(outputs_folder, exist_ok=True)
|
| 110 |
-
|
| 111 |
-
input_video_debug_value = [None]
|
| 112 |
-
end_frame_debug_value = [None]
|
| 113 |
-
prompt_debug_value = [None]
|
| 114 |
-
total_second_length_debug_value = [None]
|
| 115 |
-
|
| 116 |
-
# 20250506 pftq: Added function to encode input video frames into latents
|
| 117 |
-
@torch.no_grad()
|
| 118 |
-
def video_encode(video_path, resolution, no_resize, vae, vae_batch_size=16, device="cuda", width=None, height=None):
|
| 119 |
-
"""
|
| 120 |
-
Encode a video into latent representations using the VAE.
|
| 121 |
-
|
| 122 |
-
Args:
|
| 123 |
-
video_path: Path to the input video file.
|
| 124 |
-
vae: AutoencoderKLHunyuanVideo model.
|
| 125 |
-
height, width: Target resolution for resizing frames.
|
| 126 |
-
vae_batch_size: Number of frames to process per batch.
|
| 127 |
-
device: Device for computation (e.g., "cuda").
|
| 128 |
-
|
| 129 |
-
Returns:
|
| 130 |
-
start_latent: Latent of the first frame (for compatibility with original code).
|
| 131 |
-
input_image_np: First frame as numpy array (for CLIP vision encoding).
|
| 132 |
-
history_latents: Latents of all frames (shape: [1, channels, frames, height//8, width//8]).
|
| 133 |
-
fps: Frames per second of the input video.
|
| 134 |
-
"""
|
| 135 |
-
# 20250506 pftq: Normalize video path for Windows compatibility
|
| 136 |
-
video_path = str(pathlib.Path(video_path).resolve())
|
| 137 |
-
print(f"Processing video: {video_path}")
|
| 138 |
-
|
| 139 |
-
# 20250506 pftq: Check CUDA availability and fallback to CPU if needed
|
| 140 |
-
if device == "cuda" and not torch.cuda.is_available():
|
| 141 |
-
print("CUDA is not available, falling back to CPU")
|
| 142 |
-
device = "cpu"
|
| 143 |
-
|
| 144 |
-
try:
|
| 145 |
-
# 20250506 pftq: Load video and get FPS
|
| 146 |
-
print("Initializing VideoReader...")
|
| 147 |
-
vr = decord.VideoReader(video_path)
|
| 148 |
-
fps = vr.get_avg_fps() # Get input video FPS
|
| 149 |
-
num_real_frames = len(vr)
|
| 150 |
-
print(f"Video loaded: {num_real_frames} frames, FPS: {fps}")
|
| 151 |
-
|
| 152 |
-
# Truncate to nearest latent size (multiple of 4)
|
| 153 |
-
latent_size_factor = 4
|
| 154 |
-
num_frames = (num_real_frames // latent_size_factor) * latent_size_factor
|
| 155 |
-
if num_frames != num_real_frames:
|
| 156 |
-
print(f"Truncating video from {num_real_frames} to {num_frames} frames for latent size compatibility")
|
| 157 |
-
num_real_frames = num_frames
|
| 158 |
-
|
| 159 |
-
# 20250506 pftq: Read frames
|
| 160 |
-
print("Reading video frames...")
|
| 161 |
-
frames = vr.get_batch(range(num_real_frames)).asnumpy() # Shape: (num_real_frames, height, width, channels)
|
| 162 |
-
print(f"Frames read: {frames.shape}")
|
| 163 |
-
|
| 164 |
-
# 20250506 pftq: Get native video resolution
|
| 165 |
-
native_height, native_width = frames.shape[1], frames.shape[2]
|
| 166 |
-
print(f"Native video resolution: {native_width}x{native_height}")
|
| 167 |
-
|
| 168 |
-
# 20250506 pftq: Use native resolution if height/width not specified, otherwise use provided values
|
| 169 |
-
target_height = native_height if height is None else height
|
| 170 |
-
target_width = native_width if width is None else width
|
| 171 |
-
|
| 172 |
-
# 20250506 pftq: Adjust to nearest bucket for model compatibility
|
| 173 |
-
if not no_resize:
|
| 174 |
-
target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution)
|
| 175 |
-
print(f"Adjusted resolution: {target_width}x{target_height}")
|
| 176 |
-
else:
|
| 177 |
-
print(f"Using native resolution without resizing: {target_width}x{target_height}")
|
| 178 |
-
|
| 179 |
-
# 20250506 pftq: Preprocess frames to match original image processing
|
| 180 |
-
processed_frames = []
|
| 181 |
-
for i, frame in enumerate(frames):
|
| 182 |
-
#print(f"Preprocessing frame {i+1}/{num_frames}")
|
| 183 |
-
frame_np = resize_and_center_crop(frame, target_width=target_width, target_height=target_height)
|
| 184 |
-
processed_frames.append(frame_np)
|
| 185 |
-
processed_frames = np.stack(processed_frames) # Shape: (num_real_frames, height, width, channels)
|
| 186 |
-
print(f"Frames preprocessed: {processed_frames.shape}")
|
| 187 |
-
|
| 188 |
-
# 20250506 pftq: Save first frame for CLIP vision encoding
|
| 189 |
-
input_image_np = processed_frames[0]
|
| 190 |
-
end_of_input_video_image_np = processed_frames[-1]
|
| 191 |
-
|
| 192 |
-
# 20250506 pftq: Convert to tensor and normalize to [-1, 1]
|
| 193 |
-
print("Converting frames to tensor...")
|
| 194 |
-
frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1
|
| 195 |
-
frames_pt = frames_pt.permute(0, 3, 1, 2) # Shape: (num_real_frames, channels, height, width)
|
| 196 |
-
frames_pt = frames_pt.unsqueeze(0) # Shape: (1, num_real_frames, channels, height, width)
|
| 197 |
-
frames_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)
|
| 198 |
-
print(f"Tensor shape: {frames_pt.shape}")
|
| 199 |
-
|
| 200 |
-
# 20250507 pftq: Save pixel frames for use in worker
|
| 201 |
-
input_video_pixels = frames_pt.cpu()
|
| 202 |
-
|
| 203 |
-
# 20250506 pftq: Move to device
|
| 204 |
-
print(f"Moving tensor to device: {device}")
|
| 205 |
-
frames_pt = frames_pt.to(device)
|
| 206 |
-
print("Tensor moved to device")
|
| 207 |
-
|
| 208 |
-
# 20250506 pftq: Move VAE to device
|
| 209 |
-
print(f"Moving VAE to device: {device}")
|
| 210 |
-
vae.to(device)
|
| 211 |
-
print("VAE moved to device")
|
| 212 |
-
|
| 213 |
-
# 20250506 pftq: Encode frames in batches
|
| 214 |
-
print(f"Encoding input video frames in VAE batch size {vae_batch_size} (reduce if memory issues here or if forcing video resolution)")
|
| 215 |
-
latents = []
|
| 216 |
-
vae.eval()
|
| 217 |
-
with torch.no_grad():
|
| 218 |
-
for i in tqdm(range(0, frames_pt.shape[2], vae_batch_size), desc="Encoding video frames", mininterval=0.1):
|
| 219 |
-
#print(f"Encoding batch {i//vae_batch_size + 1}: frames {i} to {min(i + vae_batch_size, frames_pt.shape[2])}")
|
| 220 |
-
batch = frames_pt[:, :, i:i + vae_batch_size] # Shape: (1, channels, batch_size, height, width)
|
| 221 |
-
try:
|
| 222 |
-
# 20250506 pftq: Log GPU memory before encoding
|
| 223 |
-
if device == "cuda":
|
| 224 |
-
free_mem = torch.cuda.memory_allocated() / 1024**3
|
| 225 |
-
#print(f"GPU memory before encoding: {free_mem:.2f} GB")
|
| 226 |
-
batch_latent = vae_encode(batch, vae)
|
| 227 |
-
# 20250506 pftq: Synchronize CUDA to catch issues
|
| 228 |
-
if device == "cuda":
|
| 229 |
-
torch.cuda.synchronize()
|
| 230 |
-
#print(f"GPU memory after encoding: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
| 231 |
-
latents.append(batch_latent)
|
| 232 |
-
#print(f"Batch encoded, latent shape: {batch_latent.shape}")
|
| 233 |
-
except RuntimeError as e:
|
| 234 |
-
print(f"Error during VAE encoding: {str(e)}")
|
| 235 |
-
if device == "cuda" and "out of memory" in str(e).lower():
|
| 236 |
-
print("CUDA out of memory, try reducing vae_batch_size or using CPU")
|
| 237 |
-
raise
|
| 238 |
-
|
| 239 |
-
# 20250506 pftq: Concatenate latents
|
| 240 |
-
print("Concatenating latents...")
|
| 241 |
-
history_latents = torch.cat(latents, dim=2) # Shape: (1, channels, frames, height//8, width//8)
|
| 242 |
-
print(f"History latents shape: {history_latents.shape}")
|
| 243 |
-
|
| 244 |
-
# 20250506 pftq: Get first frame's latent
|
| 245 |
-
start_latent = history_latents[:, :, :1] # Shape: (1, channels, 1, height//8, width//8)
|
| 246 |
-
end_of_input_video_latent = history_latents[:, :, -1:] # Shape: (1, channels, 1, height//8, width//8)
|
| 247 |
-
print(f"Start latent shape: {start_latent.shape}")
|
| 248 |
-
|
| 249 |
-
# 20250506 pftq: Move VAE back to CPU to free GPU memory
|
| 250 |
-
if device == "cuda":
|
| 251 |
-
vae.to(cpu)
|
| 252 |
-
torch.cuda.empty_cache()
|
| 253 |
-
print("VAE moved back to CPU, CUDA cache cleared")
|
| 254 |
-
|
| 255 |
-
return start_latent, input_image_np, history_latents, fps, target_height, target_width, input_video_pixels, end_of_input_video_latent, end_of_input_video_image_np
|
| 256 |
-
|
| 257 |
-
except Exception as e:
|
| 258 |
-
print(f"Error in video_encode: {str(e)}")
|
| 259 |
-
raise
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
# 20250507 pftq: New function to encode a single image (end frame)
|
| 263 |
-
@torch.no_grad()
|
| 264 |
-
def image_encode(image_np, target_width, target_height, vae, image_encoder, feature_extractor, device="cuda"):
|
| 265 |
-
"""
|
| 266 |
-
Encode a single image into a latent and compute its CLIP vision embedding.
|
| 267 |
-
|
| 268 |
-
Args:
|
| 269 |
-
image_np: Input image as numpy array.
|
| 270 |
-
target_width, target_height: Exact resolution to resize the image to (matches start frame).
|
| 271 |
-
vae: AutoencoderKLHunyuanVideo model.
|
| 272 |
-
image_encoder: SiglipVisionModel for CLIP vision encoding.
|
| 273 |
-
feature_extractor: SiglipImageProcessor for preprocessing.
|
| 274 |
-
device: Device for computation (e.g., "cuda").
|
| 275 |
-
|
| 276 |
-
Returns:
|
| 277 |
-
latent: Latent representation of the image (shape: [1, channels, 1, height//8, width//8]).
|
| 278 |
-
clip_embedding: CLIP vision embedding of the image.
|
| 279 |
-
processed_image_np: Processed image as numpy array (after resizing).
|
| 280 |
-
"""
|
| 281 |
-
# 20250507 pftq: Process end frame with exact start frame dimensions
|
| 282 |
-
print("Processing end frame...")
|
| 283 |
-
try:
|
| 284 |
-
print(f"Using exact start frame resolution for end frame: {target_width}x{target_height}")
|
| 285 |
-
|
| 286 |
-
# Resize and preprocess image to match start frame
|
| 287 |
-
processed_image_np = resize_and_center_crop(image_np, target_width=target_width, target_height=target_height)
|
| 288 |
-
|
| 289 |
-
# Convert to tensor and normalize
|
| 290 |
-
image_pt = torch.from_numpy(processed_image_np).float() / 127.5 - 1
|
| 291 |
-
image_pt = image_pt.permute(2, 0, 1).unsqueeze(0).unsqueeze(2) # Shape: [1, channels, 1, height, width]
|
| 292 |
-
image_pt = image_pt.to(device)
|
| 293 |
-
|
| 294 |
-
# Move VAE to device
|
| 295 |
-
vae.to(device)
|
| 296 |
-
|
| 297 |
-
# Encode to latent
|
| 298 |
-
latent = vae_encode(image_pt, vae)
|
| 299 |
-
print(f"image_encode vae output shape: {latent.shape}")
|
| 300 |
-
|
| 301 |
-
# Move image encoder to device
|
| 302 |
-
image_encoder.to(device)
|
| 303 |
-
|
| 304 |
-
# Compute CLIP vision embedding
|
| 305 |
-
clip_embedding = hf_clip_vision_encode(processed_image_np, feature_extractor, image_encoder).last_hidden_state
|
| 306 |
-
|
| 307 |
-
# Move models back to CPU and clear cache
|
| 308 |
-
if device == "cuda":
|
| 309 |
-
vae.to(cpu)
|
| 310 |
-
image_encoder.to(cpu)
|
| 311 |
-
torch.cuda.empty_cache()
|
| 312 |
-
print("VAE and image encoder moved back to CPU, CUDA cache cleared")
|
| 313 |
-
|
| 314 |
-
print(f"End latent shape: {latent.shape}")
|
| 315 |
-
return latent, clip_embedding, processed_image_np
|
| 316 |
-
|
| 317 |
-
except Exception as e:
|
| 318 |
-
print(f"Error in image_encode: {str(e)}")
|
| 319 |
-
raise
|
| 320 |
-
|
| 321 |
-
# 20250508 pftq: for saving prompt to mp4 metadata comments
|
| 322 |
-
def set_mp4_comments_imageio_ffmpeg(input_file, comments):
|
| 323 |
-
try:
|
| 324 |
-
# Get the path to the bundled FFmpeg binary from imageio-ffmpeg
|
| 325 |
-
ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
|
| 326 |
-
|
| 327 |
-
# Check if input file exists
|
| 328 |
-
if not os.path.exists(input_file):
|
| 329 |
-
print(f"Error: Input file {input_file} does not exist")
|
| 330 |
-
return False
|
| 331 |
-
|
| 332 |
-
# Create a temporary file path
|
| 333 |
-
temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
|
| 334 |
-
|
| 335 |
-
# FFmpeg command using the bundled binary
|
| 336 |
-
command = [
|
| 337 |
-
ffmpeg_path, # Use imageio-ffmpeg's FFmpeg
|
| 338 |
-
'-i', input_file, # input file
|
| 339 |
-
'-metadata', f'comment={comments}', # set comment metadata
|
| 340 |
-
'-c:v', 'copy', # copy video stream without re-encoding
|
| 341 |
-
'-c:a', 'copy', # copy audio stream without re-encoding
|
| 342 |
-
'-y', # overwrite output file if it exists
|
| 343 |
-
temp_file # temporary output file
|
| 344 |
-
]
|
| 345 |
-
|
| 346 |
-
# Run the FFmpeg command
|
| 347 |
-
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 348 |
-
|
| 349 |
-
if result.returncode == 0:
|
| 350 |
-
# Replace the original file with the modified one
|
| 351 |
-
shutil.move(temp_file, input_file)
|
| 352 |
-
print(f"Successfully added comments to {input_file}")
|
| 353 |
-
return True
|
| 354 |
-
else:
|
| 355 |
-
# Clean up temp file if FFmpeg fails
|
| 356 |
-
if os.path.exists(temp_file):
|
| 357 |
-
os.remove(temp_file)
|
| 358 |
-
print(f"Error: FFmpeg failed with message:\n{result.stderr}")
|
| 359 |
-
return False
|
| 360 |
-
|
| 361 |
-
except Exception as e:
|
| 362 |
-
# Clean up temp file in case of other errors
|
| 363 |
-
if 'temp_file' in locals() and os.path.exists(temp_file):
|
| 364 |
-
os.remove(temp_file)
|
| 365 |
-
print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e))
|
| 366 |
-
return False
|
| 367 |
-
|
| 368 |
-
# 20250506 pftq: Modified worker to accept video input, and clean frame count
|
| 369 |
-
@torch.no_grad()
|
| 370 |
-
def worker(input_video, end_frame, end_frame_weight, prompt, n_prompt, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):
|
| 371 |
-
|
| 372 |
-
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
|
| 373 |
-
|
| 374 |
-
try:
|
| 375 |
-
# Clean GPU
|
| 376 |
-
if not high_vram:
|
| 377 |
-
unload_complete_models(
|
| 378 |
-
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
| 379 |
-
)
|
| 380 |
-
|
| 381 |
-
# Text encoding
|
| 382 |
-
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
|
| 383 |
-
|
| 384 |
-
if not high_vram:
|
| 385 |
-
fake_diffusers_current_device(text_encoder, gpu) # since we only encode one text - that is one model move and one encode, offload is same time consumption since it is also one load and one encode.
|
| 386 |
-
load_model_as_complete(text_encoder_2, target_device=gpu)
|
| 387 |
-
|
| 388 |
-
llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
| 389 |
-
|
| 390 |
-
if cfg == 1:
|
| 391 |
-
llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
|
| 392 |
-
else:
|
| 393 |
-
llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
| 394 |
-
|
| 395 |
-
llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
|
| 396 |
-
llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
|
| 397 |
-
|
| 398 |
-
# 20250506 pftq: Processing input video instead of image
|
| 399 |
-
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
|
| 400 |
-
|
| 401 |
-
# 20250506 pftq: Encode video
|
| 402 |
-
start_latent, input_image_np, video_latents, fps, height, width, input_video_pixels, end_of_input_video_latent, end_of_input_video_image_np = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)
|
| 403 |
-
|
| 404 |
-
#Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
|
| 405 |
-
|
| 406 |
-
# CLIP Vision
|
| 407 |
-
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
|
| 408 |
-
|
| 409 |
-
if not high_vram:
|
| 410 |
-
load_model_as_complete(image_encoder, target_device=gpu)
|
| 411 |
-
|
| 412 |
-
image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
|
| 413 |
-
image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
|
| 414 |
-
start_embedding = image_encoder_last_hidden_state
|
| 415 |
-
|
| 416 |
-
end_of_input_video_output = hf_clip_vision_encode(end_of_input_video_image_np, feature_extractor, image_encoder)
|
| 417 |
-
end_of_input_video_last_hidden_state = end_of_input_video_output.last_hidden_state
|
| 418 |
-
end_of_input_video_embedding = end_of_input_video_last_hidden_state
|
| 419 |
-
|
| 420 |
-
# 20250507 pftq: Process end frame if provided
|
| 421 |
-
end_latent = None
|
| 422 |
-
end_clip_embedding = None
|
| 423 |
-
if end_frame is not None:
|
| 424 |
-
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'End frame encoding ...'))))
|
| 425 |
-
end_latent, end_clip_embedding, _ = image_encode(
|
| 426 |
-
end_frame, target_width=width, target_height=height, vae=vae,
|
| 427 |
-
image_encoder=image_encoder, feature_extractor=feature_extractor, device=gpu
|
| 428 |
-
)
|
| 429 |
-
|
| 430 |
-
# Dtype
|
| 431 |
-
llama_vec = llama_vec.to(transformer.dtype)
|
| 432 |
-
llama_vec_n = llama_vec_n.to(transformer.dtype)
|
| 433 |
-
clip_l_pooler = clip_l_pooler.to(transformer.dtype)
|
| 434 |
-
clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
|
| 435 |
-
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
|
| 436 |
-
end_of_input_video_embedding = end_of_input_video_embedding.to(transformer.dtype)
|
| 437 |
-
|
| 438 |
-
# 20250509 pftq: Restored original placement of total_latent_sections after video_encode
|
| 439 |
-
total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
|
| 440 |
-
total_latent_sections = int(max(round(total_latent_sections), 1))
|
| 441 |
-
|
| 442 |
-
for idx in range(batch):
|
| 443 |
-
if batch > 1:
|
| 444 |
-
print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
|
| 445 |
-
|
| 446 |
-
job_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+f"_framepack-videoinput-endframe_{width}-{total_second_length}sec_seed-{seed}_steps-{steps}_distilled-{gs}_cfg-{cfg}"
|
| 447 |
-
|
| 448 |
-
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
|
| 449 |
-
|
| 450 |
-
rnd = torch.Generator("cpu").manual_seed(seed)
|
| 451 |
-
|
| 452 |
-
history_latents = video_latents.cpu()
|
| 453 |
-
history_pixels = None
|
| 454 |
-
total_generated_latent_frames = 0
|
| 455 |
-
previous_video = None
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
# 20250509 Generate backwards with end frame for better end frame anchoring
|
| 459 |
-
if total_latent_sections > 4:
|
| 460 |
-
latent_paddings = [3] + [2] * (total_latent_sections - 3) + [1, 0]
|
| 461 |
-
else:
|
| 462 |
-
latent_paddings = list(reversed(range(total_latent_sections)))
|
| 463 |
-
|
| 464 |
-
for section_index, latent_padding in enumerate(latent_paddings):
|
| 465 |
-
is_start_of_video = latent_padding == 0
|
| 466 |
-
is_end_of_video = latent_padding == latent_paddings[0]
|
| 467 |
-
latent_padding_size = latent_padding * latent_window_size
|
| 468 |
-
|
| 469 |
-
if stream.input_queue.top() == 'end':
|
| 470 |
-
stream.output_queue.push(('end', None))
|
| 471 |
-
return
|
| 472 |
-
|
| 473 |
-
if not high_vram:
|
| 474 |
-
unload_complete_models()
|
| 475 |
-
move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
|
| 476 |
-
|
| 477 |
-
if use_teacache:
|
| 478 |
-
transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
|
| 479 |
-
else:
|
| 480 |
-
transformer.initialize_teacache(enable_teacache=False)
|
| 481 |
-
|
| 482 |
-
def callback(d):
|
| 483 |
-
try:
|
| 484 |
-
preview = d['denoised']
|
| 485 |
-
preview = vae_decode_fake(preview)
|
| 486 |
-
preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
|
| 487 |
-
preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
|
| 488 |
-
if stream.input_queue.top() == 'end':
|
| 489 |
-
stream.output_queue.push(('end', None))
|
| 490 |
-
raise KeyboardInterrupt('User ends the task.')
|
| 491 |
-
current_step = d['i'] + 1
|
| 492 |
-
percentage = int(100.0 * current_step / steps)
|
| 493 |
-
hint = f'Sampling {current_step}/{steps}'
|
| 494 |
-
desc = f'Total frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / fps) :.2f} seconds (FPS-{fps}), Seed: {seed}, Video {idx+1} of {batch}. Generating part {total_latent_sections - section_index} of {total_latent_sections} backward...'
|
| 495 |
-
stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
|
| 496 |
-
except ConnectionResetError as e:
|
| 497 |
-
print(f"Suppressed ConnectionResetError in callback: {e}")
|
| 498 |
-
return
|
| 499 |
-
|
| 500 |
-
# 20250509 pftq: Dynamic frame allocation like original num_clean_frames, fix split error
|
| 501 |
-
available_frames = video_latents.shape[2] if is_start_of_video else history_latents.shape[2]
|
| 502 |
-
if is_start_of_video:
|
| 503 |
-
effective_clean_frames = 1 # avoid jumpcuts from input video
|
| 504 |
-
else:
|
| 505 |
-
effective_clean_frames = max(0, num_clean_frames - 1) if num_clean_frames > 1 else 1
|
| 506 |
-
clean_latent_pre_frames = effective_clean_frames
|
| 507 |
-
num_2x_frames = min(2, max(1, available_frames - clean_latent_pre_frames - 1)) if available_frames > clean_latent_pre_frames + 1 else 1
|
| 508 |
-
num_4x_frames = min(16, max(1, available_frames - clean_latent_pre_frames - num_2x_frames)) if available_frames > clean_latent_pre_frames + num_2x_frames else 1
|
| 509 |
-
total_context_frames = num_2x_frames + num_4x_frames
|
| 510 |
-
total_context_frames = min(total_context_frames, available_frames - clean_latent_pre_frames)
|
| 511 |
-
|
| 512 |
-
# 20250511 pftq: Dynamically adjust post_frames based on clean_latents_post
|
| 513 |
-
post_frames = 1 if is_end_of_video and end_latent is not None else effective_clean_frames # 20250511 pftq: Single frame for end_latent, otherwise padding causes still image
|
| 514 |
-
indices = torch.arange(0, clean_latent_pre_frames + latent_padding_size + latent_window_size + post_frames + num_2x_frames + num_4x_frames).unsqueeze(0)
|
| 515 |
-
clean_latent_indices_pre, blank_indices, latent_indices, clean_latent_indices_post, clean_latent_2x_indices, clean_latent_4x_indices = indices.split(
|
| 516 |
-
[clean_latent_pre_frames, latent_padding_size, latent_window_size, post_frames, num_2x_frames, num_4x_frames], dim=1
|
| 517 |
-
)
|
| 518 |
-
clean_latent_indices = torch.cat([clean_latent_indices_pre, clean_latent_indices_post], dim=1)
|
| 519 |
-
|
| 520 |
-
# 20250509 pftq: Split context frames dynamically for 2x and 4x only
|
| 521 |
-
context_frames = history_latents[:, :, -(total_context_frames + clean_latent_pre_frames):-clean_latent_pre_frames, :, :] if total_context_frames > 0 else history_latents[:, :, :1, :, :]
|
| 522 |
-
split_sizes = [num_4x_frames, num_2x_frames]
|
| 523 |
-
split_sizes = [s for s in split_sizes if s > 0]
|
| 524 |
-
if split_sizes and context_frames.shape[2] >= sum(split_sizes):
|
| 525 |
-
splits = context_frames.split(split_sizes, dim=2)
|
| 526 |
-
split_idx = 0
|
| 527 |
-
clean_latents_4x = splits[split_idx] if num_4x_frames > 0 else history_latents[:, :, :1, :, :]
|
| 528 |
-
split_idx += 1 if num_4x_frames > 0 else 0
|
| 529 |
-
clean_latents_2x = splits[split_idx] if num_2x_frames > 0 and split_idx < len(splits) else history_latents[:, :, :1, :, :]
|
| 530 |
-
else:
|
| 531 |
-
clean_latents_4x = clean_latents_2x = history_latents[:, :, :1, :, :]
|
| 532 |
-
|
| 533 |
-
clean_latents_pre = video_latents[:, :, -min(effective_clean_frames, video_latents.shape[2]):].to(history_latents) # smoother motion but jumpcuts if end frame is too different, must change clean_latent_pre_frames to effective_clean_frames also
|
| 534 |
-
clean_latents_post = history_latents[:, :, :min(effective_clean_frames, history_latents.shape[2]), :, :] # smoother motion, must change post_frames to effective_clean_frames also
|
| 535 |
-
|
| 536 |
-
if is_end_of_video:
|
| 537 |
-
clean_latents_post = torch.zeros_like(end_of_input_video_latent).to(history_latents)
|
| 538 |
-
|
| 539 |
-
# 20250509 pftq: handle end frame if available
|
| 540 |
-
if end_latent is not None:
|
| 541 |
-
#current_end_frame_weight = end_frame_weight * (latent_padding / latent_paddings[0])
|
| 542 |
-
#current_end_frame_weight = current_end_frame_weight * 0.5 + 0.5
|
| 543 |
-
current_end_frame_weight = end_frame_weight # changing this over time introduces discontinuity
|
| 544 |
-
# 20250511 pftq: Removed end frame weight adjustment as it has no effect
|
| 545 |
-
image_encoder_last_hidden_state = (1 - current_end_frame_weight) * end_of_input_video_embedding + end_clip_embedding * current_end_frame_weight
|
| 546 |
-
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
|
| 547 |
-
|
| 548 |
-
# 20250511 pftq: Use end_latent only
|
| 549 |
-
if is_end_of_video:
|
| 550 |
-
clean_latents_post = end_latent.to(history_latents)[:, :, :1, :, :] # Ensure single frame
|
| 551 |
-
|
| 552 |
-
# 20250511 pftq: Pad clean_latents_pre to match clean_latent_pre_frames if needed
|
| 553 |
-
if clean_latents_pre.shape[2] < clean_latent_pre_frames:
|
| 554 |
-
clean_latents_pre = clean_latents_pre.repeat(1, 1, clean_latent_pre_frames // clean_latents_pre.shape[2], 1, 1)
|
| 555 |
-
# 20250511 pftq: Pad clean_latents_post to match post_frames if needed
|
| 556 |
-
if clean_latents_post.shape[2] < post_frames:
|
| 557 |
-
clean_latents_post = clean_latents_post.repeat(1, 1, post_frames // clean_latents_post.shape[2], 1, 1)
|
| 558 |
-
|
| 559 |
-
clean_latents = torch.cat([clean_latents_pre, clean_latents_post], dim=2)
|
| 560 |
-
|
| 561 |
-
max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
|
| 562 |
-
print(f"Generating video {idx+1} of {batch} with seed {seed}, part {total_latent_sections - section_index} of {total_latent_sections} backward")
|
| 563 |
-
generated_latents = sample_hunyuan(
|
| 564 |
-
transformer=transformer,
|
| 565 |
-
sampler='unipc',
|
| 566 |
-
width=width,
|
| 567 |
-
height=height,
|
| 568 |
-
frames=max_frames,
|
| 569 |
-
real_guidance_scale=cfg,
|
| 570 |
-
distilled_guidance_scale=gs,
|
| 571 |
-
guidance_rescale=rs,
|
| 572 |
-
num_inference_steps=steps,
|
| 573 |
-
generator=rnd,
|
| 574 |
-
prompt_embeds=llama_vec,
|
| 575 |
-
prompt_embeds_mask=llama_attention_mask,
|
| 576 |
-
prompt_poolers=clip_l_pooler,
|
| 577 |
-
negative_prompt_embeds=llama_vec_n,
|
| 578 |
-
negative_prompt_embeds_mask=llama_attention_mask_n,
|
| 579 |
-
negative_prompt_poolers=clip_l_pooler_n,
|
| 580 |
-
device=gpu,
|
| 581 |
-
dtype=torch.bfloat16,
|
| 582 |
-
image_embeddings=image_encoder_last_hidden_state,
|
| 583 |
-
latent_indices=latent_indices,
|
| 584 |
-
clean_latents=clean_latents,
|
| 585 |
-
clean_latent_indices=clean_latent_indices,
|
| 586 |
-
clean_latents_2x=clean_latents_2x,
|
| 587 |
-
clean_latent_2x_indices=clean_latent_2x_indices,
|
| 588 |
-
clean_latents_4x=clean_latents_4x,
|
| 589 |
-
clean_latent_4x_indices=clean_latent_4x_indices,
|
| 590 |
-
callback=callback,
|
| 591 |
-
)
|
| 592 |
-
|
| 593 |
-
if is_start_of_video:
|
| 594 |
-
generated_latents = torch.cat([video_latents[:, :, -1:].to(generated_latents), generated_latents], dim=2)
|
| 595 |
-
|
| 596 |
-
total_generated_latent_frames += int(generated_latents.shape[2])
|
| 597 |
-
history_latents = torch.cat([generated_latents.to(history_latents), history_latents], dim=2)
|
| 598 |
-
|
| 599 |
-
if not high_vram:
|
| 600 |
-
offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
|
| 601 |
-
load_model_as_complete(vae, target_device=gpu)
|
| 602 |
-
|
| 603 |
-
real_history_latents = history_latents[:, :, :total_generated_latent_frames, :, :]
|
| 604 |
-
if history_pixels is None:
|
| 605 |
-
history_pixels = vae_decode(real_history_latents, vae).cpu()
|
| 606 |
-
else:
|
| 607 |
-
section_latent_frames = (latent_window_size * 2 + 1) if is_start_of_video else (latent_window_size * 2)
|
| 608 |
-
overlapped_frames = latent_window_size * 4 - 3
|
| 609 |
-
current_pixels = vae_decode(real_history_latents[:, :, :section_latent_frames], vae).cpu()
|
| 610 |
-
history_pixels = soft_append_bcthw(current_pixels, history_pixels, overlapped_frames)
|
| 611 |
-
|
| 612 |
-
if not high_vram:
|
| 613 |
-
unload_complete_models()
|
| 614 |
-
|
| 615 |
-
output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
|
| 616 |
-
save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
|
| 617 |
-
print(f"Latest video saved: {output_filename}")
|
| 618 |
-
set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}")
|
| 619 |
-
print(f"Prompt saved to mp4 metadata comments: {output_filename}")
|
| 620 |
-
|
| 621 |
-
if previous_video is not None and os.path.exists(previous_video):
|
| 622 |
-
try:
|
| 623 |
-
os.remove(previous_video)
|
| 624 |
-
print(f"Previous partial video deleted: {previous_video}")
|
| 625 |
-
except Exception as e:
|
| 626 |
-
print(f"Error deleting previous partial video {previous_video}: {e}")
|
| 627 |
-
previous_video = output_filename
|
| 628 |
-
|
| 629 |
-
print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
|
| 630 |
-
stream.output_queue.push(('file', output_filename))
|
| 631 |
-
|
| 632 |
-
if is_start_of_video:
|
| 633 |
-
break
|
| 634 |
-
|
| 635 |
-
history_pixels = torch.cat([input_video_pixels, history_pixels], dim=2)
|
| 636 |
-
|
| 637 |
-
output_filename = os.path.join(outputs_folder, f'{job_id}_final.mp4')
|
| 638 |
-
save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
|
| 639 |
-
print(f"Final video with input blend saved: {output_filename}")
|
| 640 |
-
set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}")
|
| 641 |
-
print(f"Prompt saved to mp4 metadata comments: {output_filename}")
|
| 642 |
-
stream.output_queue.push(('file', output_filename))
|
| 643 |
-
|
| 644 |
-
if previous_video is not None and os.path.exists(previous_video):
|
| 645 |
-
try:
|
| 646 |
-
os.remove(previous_video)
|
| 647 |
-
print(f"Previous partial video deleted: {previous_video}")
|
| 648 |
-
except Exception as e:
|
| 649 |
-
print(f"Error deleting previous partial video {previous_video}: {e}")
|
| 650 |
-
previous_video = output_filename
|
| 651 |
-
|
| 652 |
-
print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
|
| 653 |
-
|
| 654 |
-
stream.output_queue.push(('file', output_filename))
|
| 655 |
-
|
| 656 |
-
seed = (seed + 1) % np.iinfo(np.int32).max
|
| 657 |
-
|
| 658 |
-
except:
|
| 659 |
-
traceback.print_exc()
|
| 660 |
-
|
| 661 |
-
if not high_vram:
|
| 662 |
-
unload_complete_models(
|
| 663 |
-
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
| 664 |
-
)
|
| 665 |
-
|
| 666 |
-
stream.output_queue.push(('end', None))
|
| 667 |
-
return
|
| 668 |
-
|
| 669 |
-
# 20250506 pftq: Modified process to pass clean frame count, etc
|
| 670 |
-
def get_duration(
|
| 671 |
-
input_video, end_frame, end_frame_weight, prompt, n_prompt,
|
| 672 |
-
randomize_seed,
|
| 673 |
-
seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache,
|
| 674 |
-
no_resize, mp4_crf, num_clean_frames, vae_batch):
|
| 675 |
-
if total_second_length_debug_value[0] is not None:
|
| 676 |
-
return min(total_second_length_debug_value[0] * 60 * 2, 600)
|
| 677 |
-
return total_second_length * 60 * 2
|
| 678 |
-
|
| 679 |
-
@spaces.GPU(duration=get_duration)
|
| 680 |
-
def process(
|
| 681 |
-
input_video, end_frame, end_frame_weight, prompt, n_prompt,
|
| 682 |
-
randomize_seed,
|
| 683 |
-
seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache,
|
| 684 |
-
no_resize, mp4_crf, num_clean_frames, vae_batch):
|
| 685 |
-
global stream, high_vram
|
| 686 |
-
|
| 687 |
-
if torch.cuda.device_count() == 0:
|
| 688 |
-
gr.Warning('Set this space to GPU config to make it work.')
|
| 689 |
-
return None, None, None, None, None, None
|
| 690 |
-
|
| 691 |
-
if input_video_debug_value[0] is not None or end_frame_debug_value[0] is not None or prompt_debug_value[0] is not None or total_second_length_debug_value[0] is not None:
|
| 692 |
-
input_video = input_video_debug_value[0]
|
| 693 |
-
end_frame = end_frame_debug_value[0]
|
| 694 |
-
prompt = prompt_debug_value[0]
|
| 695 |
-
total_second_length = total_second_length_debug_value[0]
|
| 696 |
-
allocation_time = min(total_second_length_debug_value[0] * 60 * 100, 600)
|
| 697 |
-
|
| 698 |
-
if randomize_seed:
|
| 699 |
-
seed = random.randint(0, np.iinfo(np.int32).max)
|
| 700 |
-
|
| 701 |
-
# 20250506 pftq: Updated assertion for video input
|
| 702 |
-
assert input_video is not None, 'No input video!'
|
| 703 |
-
|
| 704 |
-
yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
|
| 705 |
-
|
| 706 |
-
# 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
|
| 707 |
-
if high_vram and (no_resize or resolution>640):
|
| 708 |
-
print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
|
| 709 |
-
high_vram = False
|
| 710 |
-
vae.enable_slicing()
|
| 711 |
-
vae.enable_tiling()
|
| 712 |
-
DynamicSwapInstaller.install_model(transformer, device=gpu)
|
| 713 |
-
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
| 714 |
-
|
| 715 |
-
# 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
|
| 716 |
-
if cfg > 1:
|
| 717 |
-
gs = 1
|
| 718 |
-
|
| 719 |
-
stream = AsyncStream()
|
| 720 |
-
|
| 721 |
-
# 20250506 pftq: Pass num_clean_frames, vae_batch, etc
|
| 722 |
-
async_run(worker, input_video, end_frame, end_frame_weight, prompt, n_prompt, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch)
|
| 723 |
-
|
| 724 |
-
output_filename = None
|
| 725 |
-
|
| 726 |
-
while True:
|
| 727 |
-
flag, data = stream.output_queue.next()
|
| 728 |
-
|
| 729 |
-
if flag == 'file':
|
| 730 |
-
output_filename = data
|
| 731 |
-
yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
|
| 732 |
-
|
| 733 |
-
if flag == 'progress':
|
| 734 |
-
preview, desc, html = data
|
| 735 |
-
#yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
|
| 736 |
-
yield output_filename, gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True) # 20250506 pftq: Keep refreshing the video in case it got hidden when the tab was in the background
|
| 737 |
-
|
| 738 |
-
if flag == 'end':
|
| 739 |
-
yield output_filename, gr.update(visible=False), desc+' Video complete.', '', gr.update(interactive=True), gr.update(interactive=False)
|
| 740 |
-
break
|
| 741 |
-
|
| 742 |
-
def end_process():
|
| 743 |
-
stream.input_queue.push('end')
|
| 744 |
-
|
| 745 |
-
css = make_progress_bar_css()
|
| 746 |
-
block = gr.Blocks(css=css).queue(
|
| 747 |
-
max_size=10 # 20250507 pftq: Limit queue size
|
| 748 |
-
)
|
| 749 |
-
with block:
|
| 750 |
-
if torch.cuda.device_count() == 0:
|
| 751 |
-
with gr.Row():
|
| 752 |
-
gr.HTML("""
|
| 753 |
-
<p style="background-color: red;"><big><big><big><b>⚠️To use FramePack, <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>
|
| 754 |
-
|
| 755 |
-
You can't use FramePack directly here because this space runs on a CPU, which is not enough for FramePack. Please provide <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">feedback</a> if you have issues.
|
| 756 |
-
</big></big></big></p>
|
| 757 |
-
""")
|
| 758 |
-
# 20250506 pftq: Updated title to reflect video input functionality
|
| 759 |
-
gr.Markdown('# Framepack with Video Input (Video Extension) + End Frame')
|
| 760 |
-
with gr.Row():
|
| 761 |
-
with gr.Column():
|
| 762 |
-
|
| 763 |
-
# 20250506 pftq: Changed to Video input from Image
|
| 764 |
-
with gr.Row():
|
| 765 |
-
input_video = gr.Video(sources='upload', label="Input Video", height=320)
|
| 766 |
-
with gr.Column():
|
| 767 |
-
# 20250507 pftq: Added end_frame + weight
|
| 768 |
-
end_frame = gr.Image(sources='upload', type="numpy", label="End Frame (Optional) - Reduce context frames if very different from input video or if it is jumpcutting/slowing to still image.", height=320)
|
| 769 |
-
end_frame_weight = gr.Slider(label="End Frame Weight", minimum=0.0, maximum=1.0, value=1.0, step=0.01, info='Reduce to treat more as a reference image; no effect')
|
| 770 |
-
|
| 771 |
-
prompt = gr.Textbox(label="Prompt", value='')
|
| 772 |
-
|
| 773 |
-
with gr.Row():
|
| 774 |
-
start_button = gr.Button(value="Start Generation", variant="primary")
|
| 775 |
-
end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
|
| 776 |
-
|
| 777 |
-
with gr.Accordion("Advanced settings", open=False):
|
| 778 |
-
with gr.Row():
|
| 779 |
-
use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
|
| 780 |
-
no_resize = gr.Checkbox(label='Force Original Video Resolution (No Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
|
| 781 |
-
|
| 782 |
-
randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
|
| 783 |
-
seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
|
| 784 |
-
|
| 785 |
-
batch = gr.Slider(label="Batch Size (Number of Videos)", minimum=1, maximum=1000, value=1, step=1, info='Generate multiple videos each with a different seed.')
|
| 786 |
-
|
| 787 |
-
resolution = gr.Number(label="Resolution (max width or height)", value=640, precision=0)
|
| 788 |
-
|
| 789 |
-
total_second_length = gr.Slider(label="Additional Video Length to Generate (Seconds)", minimum=1, maximum=120, value=5, step=0.1)
|
| 790 |
-
|
| 791 |
-
# 20250506 pftq: Reduced default distilled guidance scale to improve adherence to input video
|
| 792 |
-
gs = gr.Slider(label="Distilled CFG Scale", minimum=1.0, maximum=32.0, value=10.0, step=0.01, info='Prompt adherence at the cost of less details from the input video, but to a lesser extent than Context Frames.')
|
| 793 |
-
cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01, info='Use instead of Distilled for more detail/control + Negative Prompt (make sure Distilled=1). Doubles render time.') # Should not change
|
| 794 |
-
rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01) # Should not change
|
| 795 |
-
|
| 796 |
-
n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, unrealistic position, blurred, blurry", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')
|
| 797 |
-
|
| 798 |
-
steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1, info='Expensive. Increase for more quality, especially if using high non-distilled CFG.')
|
| 799 |
-
|
| 800 |
-
# 20250506 pftq: Renamed slider to Number of Context Frames and updated description
|
| 801 |
-
num_clean_frames = gr.Slider(label="Number of Context Frames (Adherence to Video)", minimum=2, maximum=10, value=5, step=1, info="Expensive. Retain more video details. Reduce if memory issues or motion too restricted (jumpcut, ignoring prompt, still).")
|
| 802 |
-
|
| 803 |
-
default_vae = 32
|
| 804 |
-
if high_vram:
|
| 805 |
-
default_vae = 128
|
| 806 |
-
elif free_mem_gb>=20:
|
| 807 |
-
default_vae = 64
|
| 808 |
-
|
| 809 |
-
vae_batch = gr.Slider(label="VAE Batch Size for Input Video", minimum=4, maximum=256, value=default_vae, step=4, info="Expensive. Increase for better quality frames during fast motion. Reduce if running out of memory")
|
| 810 |
-
|
| 811 |
-
latent_window_size = gr.Slider(label="Latent Window Size", minimum=9, maximum=49, value=9, step=1, info='Expensive. Generate more frames at a time (larger chunks). Less degradation but higher VRAM cost.')
|
| 812 |
-
|
| 813 |
-
gpu_memory_preservation = gr.Slider(label="GPU Inference Preserved Memory (GB) (larger means slower)", minimum=6, maximum=128, value=6, step=0.1, info="Set this number to a larger value if you encounter OOM. Larger value causes slower speed.")
|
| 814 |
-
|
| 815 |
-
mp4_crf = gr.Slider(label="MP4 Compression", minimum=0, maximum=100, value=16, step=1, info="Lower means better quality. 0 is uncompressed. Change to 16 if you get black outputs. ")
|
| 816 |
-
|
| 817 |
-
with gr.Accordion("Debug", open=False):
|
| 818 |
-
input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
|
| 819 |
-
end_frame_debug = gr.Image(type="numpy", label="End Image Debug", height=320)
|
| 820 |
-
prompt_debug = gr.Textbox(label="Prompt Debug", value='')
|
| 821 |
-
total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=5, step=0.1)
|
| 822 |
-
|
| 823 |
-
with gr.Column():
|
| 824 |
-
preview_image = gr.Image(label="Next Latents", height=200, visible=False)
|
| 825 |
-
result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
|
| 826 |
-
progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
|
| 827 |
-
progress_bar = gr.HTML('', elem_classes='no-generating-animation')
|
| 828 |
-
|
| 829 |
-
with gr.Row(visible=False):
|
| 830 |
-
gr.Examples(
|
| 831 |
-
examples = [
|
| 832 |
-
[
|
| 833 |
-
"./img_examples/Example1.mp4", # input_video
|
| 834 |
-
"./img_examples/Example1.png", # end_frame
|
| 835 |
-
0.0, # end_frame_weight
|
| 836 |
-
"View of the sea as far as the eye can see, from the seaside, a piece of land is barely visible on the horizon at the middle, the sky is radiant, reflections of the sun in the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
| 837 |
-
"Missing arm, unrealistic position, blurred, blurry", # n_prompt
|
| 838 |
-
True, # randomize_seed
|
| 839 |
-
42, # seed
|
| 840 |
-
1, # batch
|
| 841 |
-
640, # resolution
|
| 842 |
-
2, # total_second_length
|
| 843 |
-
9, # latent_window_size
|
| 844 |
-
25, # steps
|
| 845 |
-
1.0, # cfg
|
| 846 |
-
10.0, # gs
|
| 847 |
-
0.0, # rs
|
| 848 |
-
6, # gpu_memory_preservation
|
| 849 |
-
False, # use_teacache
|
| 850 |
-
False, # no_resize
|
| 851 |
-
16, # mp4_crf
|
| 852 |
-
5, # num_clean_frames
|
| 853 |
-
default_vae
|
| 854 |
-
],
|
| 855 |
-
[
|
| 856 |
-
"./img_examples/Example1.mp4", # input_video
|
| 857 |
-
"./img_examples/Example1.png", # end_frame
|
| 858 |
-
0.0, # end_frame_weight
|
| 859 |
-
"View of the sea as far as the eye can see, from the seaside, a piece of land is barely visible on the horizon at the middle, the sky is radiant, reflections of the sun in the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
| 860 |
-
"Missing arm, unrealistic position, blurred, blurry", # n_prompt
|
| 861 |
-
True, # randomize_seed
|
| 862 |
-
42, # seed
|
| 863 |
-
1, # batch
|
| 864 |
-
640, # resolution
|
| 865 |
-
1, # total_second_length
|
| 866 |
-
9, # latent_window_size
|
| 867 |
-
25, # steps
|
| 868 |
-
1.0, # cfg
|
| 869 |
-
10.0, # gs
|
| 870 |
-
0.0, # rs
|
| 871 |
-
6, # gpu_memory_preservation
|
| 872 |
-
True, # use_teacache
|
| 873 |
-
False, # no_resize
|
| 874 |
-
16, # mp4_crf
|
| 875 |
-
5, # num_clean_frames
|
| 876 |
-
default_vae
|
| 877 |
-
],
|
| 878 |
-
],
|
| 879 |
-
run_on_click = True,
|
| 880 |
-
fn = process,
|
| 881 |
-
inputs = [input_video, end_frame, end_frame_weight, prompt, n_prompt, randomize_seed, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch],
|
| 882 |
-
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
|
| 883 |
-
cache_examples = True,
|
| 884 |
-
)
|
| 885 |
-
|
| 886 |
-
# 20250506 pftq: Updated inputs to include num_clean_frames
|
| 887 |
-
ips = [input_video, end_frame, end_frame_weight, prompt, n_prompt, randomize_seed, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch]
|
| 888 |
-
start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
|
| 889 |
-
end_button.click(fn=end_process)
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
def handle_field_debug_change(input_video_debug_data, end_frame_debug_data, prompt_debug_data, total_second_length_debug_data):
|
| 893 |
-
input_video_debug_value[0] = input_video_debug_data
|
| 894 |
-
end_frame_debug_value[0] = end_frame_debug_data
|
| 895 |
-
prompt_debug_value[0] = prompt_debug_data
|
| 896 |
-
total_second_length_debug_value[0] = total_second_length_debug_data
|
| 897 |
-
return []
|
| 898 |
-
|
| 899 |
-
input_video_debug.upload(
|
| 900 |
-
fn=handle_field_debug_change,
|
| 901 |
-
inputs=[input_video_debug, end_frame_debug, prompt_debug, total_second_length_debug],
|
| 902 |
-
outputs=[]
|
| 903 |
-
)
|
| 904 |
-
|
| 905 |
-
end_frame_debug.upload(
|
| 906 |
-
fn=handle_field_debug_change,
|
| 907 |
-
inputs=[input_video_debug, end_frame_debug, prompt_debug, total_second_length_debug],
|
| 908 |
-
outputs=[]
|
| 909 |
-
)
|
| 910 |
-
|
| 911 |
-
prompt_debug.change(
|
| 912 |
-
fn=handle_field_debug_change,
|
| 913 |
-
inputs=[input_video_debug, end_frame_debug, prompt_debug, total_second_length_debug],
|
| 914 |
-
outputs=[]
|
| 915 |
-
)
|
| 916 |
-
|
| 917 |
-
total_second_length_debug.change(
|
| 918 |
-
fn=handle_field_debug_change,
|
| 919 |
-
inputs=[input_video_debug, end_frame_debug, prompt_debug, total_second_length_debug],
|
| 920 |
-
outputs=[]
|
| 921 |
-
)
|
| 922 |
-
|
| 923 |
-
block.launch(mcp_server=True, ssr_mode=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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