diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,8 +1,17 @@ +from diffusers_helper.hf_login import login + import os -os.environ['HF_HOME'] = os.path.abspath( - os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')) -) +os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download'))) + +try: + import spaces +except: + class spaces(): + def GPU(*args, **kwargs): + def decorator(function): + return lambda *dummy_args, **dummy_kwargs: function(*dummy_args, **dummy_kwargs) + return decorator import gradio as gr import torch @@ -10,365 +19,875 @@ import traceback import einops import safetensors.torch as sf import numpy as np +import random +import time import math -import spaces +import gc +# 20250506 pftq: Added for video input loading +import decord +# 20250506 pftq: Added for progress bars in video_encode +from tqdm import tqdm +# 20250506 pftq: Normalize file paths for Windows compatibility +import pathlib +# 20250506 pftq: for easier to read timestamp +from datetime import datetime +# 20250508 pftq: for saving prompt to mp4 comments metadata +import imageio_ffmpeg +import tempfile +import shutil +import subprocess from PIL import Image from diffusers import AutoencoderKLHunyuanVideo -from transformers import ( - LlamaModel, CLIPTextModel, - LlamaTokenizerFast, CLIPTokenizer -) -from diffusers_helper.hunyuan import ( - encode_prompt_conds, vae_decode, - vae_encode, vae_decode_fake -) -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 -) +from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer +from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake +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 from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan -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 -) +if torch.cuda.device_count() > 0: + 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 from diffusers_helper.thread_utils import AsyncStream, async_run from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html from transformers import SiglipImageProcessor, SiglipVisionModel from diffusers_helper.clip_vision import hf_clip_vision_encode from diffusers_helper.bucket_tools import find_nearest_bucket - -# Check GPU memory -free_mem_gb = get_cuda_free_memory_gb(gpu) -high_vram = free_mem_gb > 60 - -print(f'Free VRAM {free_mem_gb} GB') -print(f'High-VRAM Mode: {high_vram}') - -# Load models -text_encoder = LlamaModel.from_pretrained( - "hunyuanvideo-community/HunyuanVideo", - subfolder='text_encoder', - torch_dtype=torch.float16 -).cpu() -text_encoder_2 = CLIPTextModel.from_pretrained( - "hunyuanvideo-community/HunyuanVideo", - subfolder='text_encoder_2', - torch_dtype=torch.float16 -).cpu() -tokenizer = LlamaTokenizerFast.from_pretrained( - "hunyuanvideo-community/HunyuanVideo", - subfolder='tokenizer' -) -tokenizer_2 = CLIPTokenizer.from_pretrained( - "hunyuanvideo-community/HunyuanVideo", - subfolder='tokenizer_2' -) -vae = AutoencoderKLHunyuanVideo.from_pretrained( - "hunyuanvideo-community/HunyuanVideo", - subfolder='vae', - torch_dtype=torch.float16 -).cpu() - -feature_extractor = SiglipImageProcessor.from_pretrained( - "lllyasviel/flux_redux_bfl", - subfolder='feature_extractor' -) -image_encoder = SiglipVisionModel.from_pretrained( - "lllyasviel/flux_redux_bfl", - subfolder='image_encoder', - torch_dtype=torch.float16 -).cpu() - -transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained( - 'lllyasviel/FramePack_F1_I2V_HY_20250503', - torch_dtype=torch.bfloat16 -).cpu() - -# Evaluation mode -vae.eval() -text_encoder.eval() -text_encoder_2.eval() -image_encoder.eval() -transformer.eval() - -# Slicing/Tiling for low VRAM -if not high_vram: - vae.enable_slicing() - vae.enable_tiling() - -transformer.high_quality_fp32_output_for_inference = True -print('transformer.high_quality_fp32_output_for_inference = True') - -# Move to correct dtype -transformer.to(dtype=torch.bfloat16) -vae.to(dtype=torch.float16) -image_encoder.to(dtype=torch.float16) -text_encoder.to(dtype=torch.float16) -text_encoder_2.to(dtype=torch.float16) - -# No gradient -vae.requires_grad_(False) -text_encoder.requires_grad_(False) -text_encoder_2.requires_grad_(False) -image_encoder.requires_grad_(False) -transformer.requires_grad_(False) - -# DynamicSwap if low VRAM -if not high_vram: - DynamicSwapInstaller.install_model(transformer, device=gpu) - DynamicSwapInstaller.install_model(text_encoder, device=gpu) -else: - text_encoder.to(gpu) - text_encoder_2.to(gpu) - image_encoder.to(gpu) - vae.to(gpu) - transformer.to(gpu) +from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline +import pillow_heif + +pillow_heif.register_heif_opener() + +high_vram = False +free_mem_gb = 0 + +if torch.cuda.device_count() > 0: + free_mem_gb = get_cuda_free_memory_gb(gpu) + high_vram = free_mem_gb > 60 + + #print(f'Free VRAM {free_mem_gb} GB') + #print(f'High-VRAM Mode: {high_vram}') + + text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu() + text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu() + tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer') + tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2') + vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu() + + feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor') + image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu() + + transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu() + + vae.eval() + text_encoder.eval() + text_encoder_2.eval() + image_encoder.eval() + transformer.eval() + + if not high_vram: + vae.enable_slicing() + vae.enable_tiling() + + transformer.high_quality_fp32_output_for_inference = True + #print('transformer.high_quality_fp32_output_for_inference = True') + + transformer.to(dtype=torch.bfloat16) + vae.to(dtype=torch.float16) + image_encoder.to(dtype=torch.float16) + text_encoder.to(dtype=torch.float16) + text_encoder_2.to(dtype=torch.float16) + + vae.requires_grad_(False) + text_encoder.requires_grad_(False) + text_encoder_2.requires_grad_(False) + image_encoder.requires_grad_(False) + transformer.requires_grad_(False) + + if not high_vram: + # DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster + DynamicSwapInstaller.install_model(transformer, device=gpu) + DynamicSwapInstaller.install_model(text_encoder, device=gpu) + else: + text_encoder.to(gpu) + text_encoder_2.to(gpu) + image_encoder.to(gpu) + vae.to(gpu) + transformer.to(gpu) stream = AsyncStream() outputs_folder = './outputs/' os.makedirs(outputs_folder, exist_ok=True) -examples = [ - ["img_examples/1.png", "The girl dances gracefully, with clear movements, full of charm."], - ["img_examples/2.jpg", "The man dances flamboyantly, swinging his hips and striking bold poses with dramatic flair."], - ["img_examples/3.png", "The woman dances elegantly among the blossoms, spinning slowly with flowing sleeves and graceful hand movements."] -] - -# Example generation (optional) -def generate_examples(input_image, prompt): - t2v=False - n_prompt="" - seed=31337 - total_second_length=5 - latent_window_size=9 - steps=25 - cfg=1.0 - gs=10.0 - rs=0.0 - gpu_memory_preservation=6 - use_teacache=True - mp4_crf=16 +default_local_storage = { + "generation-mode": "image", + } - global stream +@torch.no_grad() +def video_encode(video_path, resolution, no_resize, vae, vae_batch_size=16, device="cuda", width=None, height=None): + """ + Encode a video into latent representations using the VAE. + + Args: + video_path: Path to the input video file. + vae: AutoencoderKLHunyuanVideo model. + height, width: Target resolution for resizing frames. + vae_batch_size: Number of frames to process per batch. + device: Device for computation (e.g., "cuda"). + + Returns: + start_latent: Latent of the first frame (for compatibility with original code). + input_image_np: First frame as numpy array (for CLIP vision encoding). + history_latents: Latents of all frames (shape: [1, channels, frames, height//8, width//8]). + fps: Frames per second of the input video. + """ + # 20250506 pftq: Normalize video path for Windows compatibility + video_path = str(pathlib.Path(video_path).resolve()) + #print(f"Processing video: {video_path}") - if t2v: - default_height, default_width = 640, 640 - input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255 - print("No input image provided. Using a blank white image.") + # 20250506 pftq: Check CUDA availability and fallback to CPU if needed + if device == "cuda" and not torch.cuda.is_available(): + #print("CUDA is not available, falling back to CPU") + device = "cpu" - yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True) + try: + # 20250506 pftq: Load video and get FPS + #print("Initializing VideoReader...") + vr = decord.VideoReader(video_path) + fps = vr.get_avg_fps() # Get input video FPS + num_real_frames = len(vr) + #print(f"Video loaded: {num_real_frames} frames, FPS: {fps}") + + # Truncate to nearest latent size (multiple of 4) + latent_size_factor = 4 + num_frames = (num_real_frames // latent_size_factor) * latent_size_factor + #if num_frames != num_real_frames: + #print(f"Truncating video from {num_real_frames} to {num_frames} frames for latent size compatibility") + num_real_frames = num_frames + + # 20250506 pftq: Read frames + #print("Reading video frames...") + frames = vr.get_batch(range(num_real_frames)).asnumpy() # Shape: (num_real_frames, height, width, channels) + #print(f"Frames read: {frames.shape}") + + # 20250506 pftq: Get native video resolution + native_height, native_width = frames.shape[1], frames.shape[2] + #print(f"Native video resolution: {native_width}x{native_height}") + + # 20250506 pftq: Use native resolution if height/width not specified, otherwise use provided values + target_height = native_height if height is None else height + target_width = native_width if width is None else width + + # 20250506 pftq: Adjust to nearest bucket for model compatibility + if not no_resize: + target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution) + #print(f"Adjusted resolution: {target_width}x{target_height}") + #else: + #print(f"Using native resolution without resizing: {target_width}x{target_height}") + + # 20250506 pftq: Preprocess frames to match original image processing + processed_frames = [] + for i, frame in enumerate(frames): + #print(f"Preprocessing frame {i+1}/{num_frames}") + frame_np = resize_and_center_crop(frame, target_width=target_width, target_height=target_height) + processed_frames.append(frame_np) + processed_frames = np.stack(processed_frames) # Shape: (num_real_frames, height, width, channels) + #print(f"Frames preprocessed: {processed_frames.shape}") + + # 20250506 pftq: Save first frame for CLIP vision encoding + input_image_np = processed_frames[0] + + # 20250506 pftq: Convert to tensor and normalize to [-1, 1] + #print("Converting frames to tensor...") + frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1 + frames_pt = frames_pt.permute(0, 3, 1, 2) # Shape: (num_real_frames, channels, height, width) + frames_pt = frames_pt.unsqueeze(0) # Shape: (1, num_real_frames, channels, height, width) + frames_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width) + #print(f"Tensor shape: {frames_pt.shape}") + + # 20250506 pftq: Move to device + #print(f"Moving tensor to device: {device}") + frames_pt = frames_pt.to(device) + #print("Tensor moved to device") + + # 20250506 pftq: Move VAE to device + #print(f"Moving VAE to device: {device}") + vae.to(device) + #print("VAE moved to device") + + # 20250506 pftq: Encode frames in batches + #print(f"Encoding input video frames in VAE batch size {vae_batch_size} (reduce if memory issues here or if forcing video resolution)") + latents = [] + vae.eval() + with torch.no_grad(): + for i in tqdm(range(0, frames_pt.shape[2], vae_batch_size), desc="Encoding video frames", mininterval=0.1): + #print(f"Encoding batch {i//vae_batch_size + 1}: frames {i} to {min(i + vae_batch_size, frames_pt.shape[2])}") + batch = frames_pt[:, :, i:i + vae_batch_size] # Shape: (1, channels, batch_size, height, width) + try: + # 20250506 pftq: Log GPU memory before encoding + if device == "cuda": + free_mem = torch.cuda.memory_allocated() / 1024**3 + #print(f"GPU memory before encoding: {free_mem:.2f} GB") + batch_latent = vae_encode(batch, vae) + # 20250506 pftq: Synchronize CUDA to catch issues + if device == "cuda": + torch.cuda.synchronize() + #print(f"GPU memory after encoding: {torch.cuda.memory_allocated() / 1024**3:.2f} GB") + latents.append(batch_latent) + #print(f"Batch encoded, latent shape: {batch_latent.shape}") + except RuntimeError as e: + print(f"Error during VAE encoding: {str(e)}") + if device == "cuda" and "out of memory" in str(e).lower(): + print("CUDA out of memory, try reducing vae_batch_size or using CPU") + raise + + # 20250506 pftq: Concatenate latents + #print("Concatenating latents...") + history_latents = torch.cat(latents, dim=2) # Shape: (1, channels, frames, height//8, width//8) + #print(f"History latents shape: {history_latents.shape}") + + # 20250506 pftq: Get first frame's latent + start_latent = history_latents[:, :, :1] # Shape: (1, channels, 1, height//8, width//8) + #print(f"Start latent shape: {start_latent.shape}") + + # 20250506 pftq: Move VAE back to CPU to free GPU memory + if device == "cuda": + vae.to(cpu) + torch.cuda.empty_cache() + #print("VAE moved back to CPU, CUDA cache cleared") + + return start_latent, input_image_np, history_latents, fps, target_height, target_width + + except Exception as e: + print(f"Error in video_encode: {str(e)}") + raise + +# 20250508 pftq: for saving prompt to mp4 metadata comments +def set_mp4_comments_imageio_ffmpeg(input_file, comments): + try: + # Get the path to the bundled FFmpeg binary from imageio-ffmpeg + ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe() + + # Check if input file exists + if not os.path.exists(input_file): + #print(f"Error: Input file {input_file} does not exist") + return False + + # Create a temporary file path + temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name + + # FFmpeg command using the bundled binary + command = [ + ffmpeg_path, # Use imageio-ffmpeg's FFmpeg + '-i', input_file, # input file + '-metadata', f'comment={comments}', # set comment metadata + '-c:v', 'copy', # copy video stream without re-encoding + '-c:a', 'copy', # copy audio stream without re-encoding + '-y', # overwrite output file if it exists + temp_file # temporary output file + ] + + # Run the FFmpeg command + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + if result.returncode == 0: + # Replace the original file with the modified one + shutil.move(temp_file, input_file) + #print(f"Successfully added comments to {input_file}") + return True + else: + # Clean up temp file if FFmpeg fails + if os.path.exists(temp_file): + os.remove(temp_file) + #print(f"Error: FFmpeg failed with message:\n{result.stderr}") + return False + + except Exception as e: + # Clean up temp file in case of other errors + if 'temp_file' in locals() and os.path.exists(temp_file): + os.remove(temp_file) + print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e)) + return False + +# 20250507 pftq: New function to encode a single image (end frame) +@torch.no_grad() +def image_encode(image_np, target_width, target_height, vae, image_encoder, feature_extractor, device="cuda"): + """ + Encode a single image into a latent and compute its CLIP vision embedding. + + Args: + image_np: Input image as numpy array. + target_width, target_height: Exact resolution to resize the image to (matches start frame). + vae: AutoencoderKLHunyuanVideo model. + image_encoder: SiglipVisionModel for CLIP vision encoding. + feature_extractor: SiglipImageProcessor for preprocessing. + device: Device for computation (e.g., "cuda"). + + Returns: + latent: Latent representation of the image (shape: [1, channels, 1, height//8, width//8]). + clip_embedding: CLIP vision embedding of the image. + processed_image_np: Processed image as numpy array (after resizing). + """ + # 20250507 pftq: Process end frame with exact start frame dimensions + print("Processing end frame...") + try: + print(f"Using exact start frame resolution for end frame: {target_width}x{target_height}") - stream = AsyncStream() + # Resize and preprocess image to match start frame + processed_image_np = resize_and_center_crop(image_np, target_width=target_width, target_height=target_height) - async_run( - worker, input_image, prompt, n_prompt, seed, - total_second_length, latent_window_size, steps, - cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf - ) + # Convert to tensor and normalize + image_pt = torch.from_numpy(processed_image_np).float() / 127.5 - 1 + image_pt = image_pt.permute(2, 0, 1).unsqueeze(0).unsqueeze(2) # Shape: [1, channels, 1, height, width] + image_pt = image_pt.to(device) - output_filename = None + # Move VAE to device + vae.to(device) - while True: - flag, data = stream.output_queue.next() + # Encode to latent + latent = vae_encode(image_pt, vae) + print(f"image_encode vae output shape: {latent.shape}") - if flag == 'file': - output_filename = data - yield ( - output_filename, - gr.update(), - gr.update(), - gr.update(), - gr.update(interactive=False), - gr.update(interactive=True) - ) + # Move image encoder to device + image_encoder.to(device) - if flag == 'progress': - preview, desc, html = data - yield ( - gr.update(), - gr.update(visible=True, value=preview), - desc, - html, - gr.update(interactive=False), - gr.update(interactive=True) - ) + # Compute CLIP vision embedding + clip_embedding = hf_clip_vision_encode(processed_image_np, feature_extractor, image_encoder).last_hidden_state - if flag == 'end': - yield ( - output_filename, - gr.update(visible=False), - gr.update(), - '', - gr.update(interactive=True), - gr.update(interactive=False) - ) - break + # Move models back to CPU and clear cache + if device == "cuda": + vae.to(cpu) + image_encoder.to(cpu) + torch.cuda.empty_cache() + print("VAE and image encoder moved back to CPU, CUDA cache cleared") + + print(f"End latent shape: {latent.shape}") + return latent, clip_embedding, processed_image_np + + except Exception as e: + print(f"Error in image_encode: {str(e)}") + raise @torch.no_grad() -def worker( - input_image, prompt, n_prompt, seed, - total_second_length, latent_window_size, steps, - cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf -): - # Calculate total sections - total_latent_sections = (total_second_length * 30) / (latent_window_size * 4) +def worker(input_image, end_image, image_position, end_stillness, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number): + def encode_prompt(prompt, n_prompt): + llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + + if cfg == 1: + llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler) + else: + llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + + llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512) + llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512) + + llama_vec = llama_vec.to(transformer.dtype) + llama_vec_n = llama_vec_n.to(transformer.dtype) + clip_l_pooler = clip_l_pooler.to(transformer.dtype) + clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype) + return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] + + total_latent_sections = (total_second_length * fps_number) / (latent_window_size * 4) total_latent_sections = int(max(round(total_latent_sections), 1)) + first_section_index = max(min(math.floor(image_position * (total_latent_sections - 1) / 100), (total_latent_sections - 1)), 0) + section_index = first_section_index + forward = (image_position == 0) + job_id = generate_timestamp() stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...')))) try: - # Unload if VRAM is low + # Clean GPU if not high_vram: unload_complete_models( text_encoder, text_encoder_2, image_encoder, vae, transformer ) # Text encoding + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...')))) if not high_vram: - fake_diffusers_current_device(text_encoder, gpu) + 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. load_model_as_complete(text_encoder_2, target_device=gpu) - llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + prompt_parameters = [] - if cfg == 1: - llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler) - else: - llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + for prompt_part in prompts[:total_latent_sections]: + prompt_parameters.append(encode_prompt(prompt_part, n_prompt)) - llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512) - llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512) + # Clean GPU + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2 + ) + + # Processing input image - # Process image stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...')))) H, W, C = input_image.shape - height, width = find_nearest_bucket(H, W, resolution=640) - input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height) - - Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png')) - - input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1 - input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None] - - # VAE encoding - stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...')))) - - if not high_vram: - load_model_as_complete(vae, target_device=gpu) - start_latent = vae_encode(input_image_pt, vae) + height, width = find_nearest_bucket(H, W, resolution=resolution) + + def get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram): + input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height) + + #Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png')) + + input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1 + input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None] + + # VAE encoding + + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...')))) + + if not high_vram: + load_model_as_complete(vae, target_device=gpu) + + start_latent = vae_encode(input_image_pt, vae) + + # CLIP Vision + + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...')))) + + if not high_vram: + unload_complete_models(vae) + load_model_as_complete(image_encoder, target_device=gpu) - # CLIP Vision - stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...')))) + image_encoder_last_hidden_state = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder).last_hidden_state + + if not high_vram: + unload_complete_models(image_encoder) + + return [start_latent, image_encoder_last_hidden_state] + + [start_latent, image_encoder_last_hidden_state] = get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram) + del input_image + del end_image - if not high_vram: - load_model_as_complete(image_encoder, target_device=gpu) - image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder) - image_encoder_last_hidden_state = image_encoder_output.last_hidden_state + # Dtype - # Convert dtype - llama_vec = llama_vec.to(transformer.dtype) - llama_vec_n = llama_vec_n.to(transformer.dtype) - clip_l_pooler = clip_l_pooler.to(transformer.dtype) - clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype) image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype) - # Start sampling + # Sampling + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...')))) rnd = torch.Generator("cpu").manual_seed(seed) - history_latents = torch.zeros( - size=(1, 16, 16 + 2 + 1, height // 8, width // 8), - dtype=torch.float32 - ).cpu() + history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32, device=cpu) + start_latent = start_latent.to(history_latents) history_pixels = None - # Add start_latent - history_latents = torch.cat([history_latents, start_latent.to(history_latents)], dim=2) + history_latents = torch.cat([history_latents, start_latent] if forward else [start_latent, history_latents], dim=2) total_generated_latent_frames = 1 - for section_index in range(total_latent_sections): + if enable_preview: + def callback(d): + preview = d['denoised'] + preview = vae_decode_fake(preview) + + preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8) + preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c') + + if stream.input_queue.top() == 'end': + stream.output_queue.push(('end', None)) + raise KeyboardInterrupt('User ends the task.') + + current_step = d['i'] + 1 + percentage = int(100.0 * current_step / steps) + hint = f'Sampling {current_step}/{steps}' + desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / fps_number) :.2f} seconds (FPS-30), Resolution: {height}px * {width}px. The video is being extended now ...' + stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint)))) + return + else: + def callback(d): + return + + indices = torch.arange(0, 1 + 16 + 2 + 1 + latent_window_size).unsqueeze(0) + if forward: + clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split([1, 16, 2, 1, latent_window_size], dim=1) + clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1) + else: + latent_indices, clean_latent_1x_indices, clean_latent_2x_indices, clean_latent_4x_indices, clean_latent_indices_start = indices.split([latent_window_size, 1, 2, 16, 1], dim=1) + clean_latent_indices = torch.cat([clean_latent_1x_indices, clean_latent_indices_start], dim=1) + + def post_process(forward, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, section_index, total_latent_sections, outputs_folder, mp4_crf, stream): + total_generated_latent_frames += int(generated_latents.shape[2]) + history_latents = torch.cat([history_latents, generated_latents.to(history_latents)] if forward else [generated_latents.to(history_latents), history_latents], dim=2) + + if not high_vram: + offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8) + load_model_as_complete(vae, target_device=gpu) + + if history_pixels is None: + real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :] if forward else history_latents[:, :, :total_generated_latent_frames, :, :] + history_pixels = vae_decode(real_history_latents, vae).cpu() + else: + section_latent_frames = latent_window_size * 2 + overlapped_frames = latent_window_size * 4 - 3 + + if forward: + real_history_latents = history_latents[:, :, -min(section_latent_frames, total_generated_latent_frames):, :, :] + history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames) + else: + real_history_latents = history_latents[:, :, :min(section_latent_frames, total_generated_latent_frames), :, :] + history_pixels = soft_append_bcthw(vae_decode(real_history_latents, vae).cpu(), history_pixels, overlapped_frames) + + if not high_vram: + unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer) + + if enable_preview or section_index == (0 if first_section_index == (total_latent_sections - 1) else (total_latent_sections - 1)): + output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4') + + save_bcthw_as_mp4(history_pixels, output_filename, fps=fps_number, crf=mp4_crf) + + print(f'Decoded. Current latent shape pixel shape {history_pixels.shape}') + + stream.output_queue.push(('file', output_filename)) + return [total_generated_latent_frames, history_latents, history_pixels] + + while section_index < total_latent_sections: if stream.input_queue.top() == 'end': stream.output_queue.push(('end', None)) return print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}') + prompt_index = min(section_index, len(prompt_parameters) - 1) + + [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters[prompt_index] + + if prompt_index < len(prompt_parameters) - 1 or (prompt_index == total_latent_sections - 1): + del prompt_parameters[prompt_index] + if not high_vram: unload_complete_models() - move_model_to_device_with_memory_preservation( - transformer, target_device=gpu, - preserved_memory_gb=gpu_memory_preservation - ) + move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation) if use_teacache: transformer.initialize_teacache(enable_teacache=True, num_steps=steps) else: transformer.initialize_teacache(enable_teacache=False) + if forward: + clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -(16 + 2 + 1):, :, :].split([16, 2, 1], dim=2) + clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2) + else: + clean_latents_1x, clean_latents_2x, clean_latents_4x = history_latents[:, :, :(1 + 2 + 16), :, :].split([1, 2, 16], dim=2) + clean_latents = torch.cat([clean_latents_1x, start_latent], dim=2) + + generated_latents = sample_hunyuan( + transformer=transformer, + sampler='unipc', + width=width, + height=height, + frames=latent_window_size * 4 - 3, + real_guidance_scale=cfg, + distilled_guidance_scale=gs, + guidance_rescale=rs, + # shift=3.0, + num_inference_steps=steps, + generator=rnd, + prompt_embeds=llama_vec, + prompt_embeds_mask=llama_attention_mask, + prompt_poolers=clip_l_pooler, + negative_prompt_embeds=llama_vec_n, + negative_prompt_embeds_mask=llama_attention_mask_n, + negative_prompt_poolers=clip_l_pooler_n, + device=gpu, + dtype=torch.bfloat16, + image_embeddings=image_encoder_last_hidden_state, + latent_indices=latent_indices, + clean_latents=clean_latents, + clean_latent_indices=clean_latent_indices, + clean_latents_2x=clean_latents_2x, + clean_latent_2x_indices=clean_latent_2x_indices, + clean_latents_4x=clean_latents_4x, + clean_latent_4x_indices=clean_latent_4x_indices, + callback=callback, + ) + del clean_latents + del clean_latents_2x + del clean_latents_4x + del latent_indices + del clean_latent_indices + del clean_latent_2x_indices + del clean_latent_4x_indices + + [total_generated_latent_frames, history_latents, history_pixels] = post_process(forward, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, section_index, total_latent_sections, outputs_folder, mp4_crf, stream) + + if not forward: + if section_index > 0: + section_index -= 1 + else: + clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split([1, 16, 2, 1, latent_window_size], dim=1) + clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1) + + real_history_latents = history_latents[:, :, :total_generated_latent_frames, :, :] + zero_latents = history_latents[:, :, total_generated_latent_frames:, :, :] + history_latents = torch.cat([zero_latents, real_history_latents], dim=2) + del real_history_latents + del zero_latents + + forward = True + section_index = first_section_index + + if forward: + section_index += 1 + except: + traceback.print_exc() + + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2, image_encoder, vae, transformer + ) + + stream.output_queue.push(('end', None)) + return + +@torch.no_grad() +def worker_start_end(input_image, end_image, image_position, end_stillness, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number): + def encode_prompt(prompt, n_prompt): + llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + + if cfg == 1: + llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler) + else: + llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + + llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512) + llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512) + + llama_vec = llama_vec.to(transformer.dtype) + llama_vec_n = llama_vec_n.to(transformer.dtype) + clip_l_pooler = clip_l_pooler.to(transformer.dtype) + clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype) + return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] + + total_latent_sections = (total_second_length * fps_number) / (latent_window_size * 4) + total_latent_sections = int(max(round(total_latent_sections), 1)) + + job_id = generate_timestamp() + + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...')))) + + try: + # Clean GPU + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2, image_encoder, vae, transformer + ) + + # Text encoding + + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...')))) + + if not high_vram: + 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. + load_model_as_complete(text_encoder_2, target_device=gpu) + + + prompt_parameters = [] + + for prompt_part in prompts[:total_latent_sections]: + prompt_parameters.append(encode_prompt(prompt_part, n_prompt)) + + # Clean GPU + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2 + ) + + # Processing input image (start frame) + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Processing start frame ...')))) + + H, W, C = input_image.shape + height, width = find_nearest_bucket(H, W, resolution=resolution) + has_end_image = end_image is not None + + def get_start_latent(input_image, has_end_image, end_image, height, width, vae, gpu, image_encoder, high_vram): + input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height) + + input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1 + input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None] + + # Processing end image (if provided) + if has_end_image: + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Processing end frame ...')))) + + end_image_np = resize_and_center_crop(end_image, target_width=width, target_height=height) + + end_image_pt = torch.from_numpy(end_image_np).float() / 127.5 - 1 + end_image_pt = end_image_pt.permute(2, 0, 1)[None, :, None] + + # VAE encoding + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...')))) + + if not high_vram: + load_model_as_complete(vae, target_device=gpu) + + start_latent = vae_encode(input_image_pt, vae) + + if has_end_image: + end_latent = vae_encode(end_image_pt, vae) + + # CLIP Vision + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...')))) + + if not high_vram: + load_model_as_complete(image_encoder, target_device=gpu) + + image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder) + image_encoder_last_hidden_state = image_encoder_output.last_hidden_state + + if has_end_image: + end_image_encoder_output = hf_clip_vision_encode(end_image_np, feature_extractor, image_encoder) + end_image_encoder_last_hidden_state = end_image_encoder_output.last_hidden_state + # Combine both image embeddings or use a weighted approach + image_encoder_last_hidden_state = (image_encoder_last_hidden_state + end_image_encoder_last_hidden_state) / 2 + + # Clean GPU + if not high_vram: + unload_complete_models( + image_encoder + ) + + return [start_latent, end_latent, image_encoder_last_hidden_state] + + [start_latent, end_latent, image_encoder_last_hidden_state] = get_start_latent(input_image, has_end_image, end_image, height, width, vae, gpu, image_encoder, high_vram) + del input_image + del end_image + + # Dtype + image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype) + + # Sampling + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...')))) + + rnd = torch.Generator("cpu").manual_seed(seed) + num_frames = latent_window_size * 4 - 3 + + history_latents = torch.zeros(size=(1, 16, 1 + 2 + 16, height // 8, width // 8), dtype=torch.float32, device=cpu) + start_latent = start_latent.to(history_latents) + if has_end_image: + end_latent = end_latent.to(history_latents) + + history_pixels = None + total_generated_latent_frames = 0 + + if total_latent_sections > 4: + # In theory the latent_paddings should follow the else sequence, but it seems that duplicating some + # items looks better than expanding it when total_latent_sections > 4 + # One can try to remove below trick and just + # use `latent_paddings = list(reversed(range(total_latent_sections)))` to compare + latent_paddings = [3] + [2] * (total_latent_sections - 3) + [1, 0] + else: + # Convert an iterator to a list + latent_paddings = list(range(total_latent_sections - 1, -1, -1)) + + if enable_preview: def callback(d): preview = d['denoised'] preview = vae_decode_fake(preview) + preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8) preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c') - + if stream.input_queue.top() == 'end': stream.output_queue.push(('end', None)) raise KeyboardInterrupt('User ends the task.') - + current_step = d['i'] + 1 percentage = int(100.0 * current_step / steps) hint = f'Sampling {current_step}/{steps}' - desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}' + desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / fps_number) :.2f} seconds (FPS-30), Resolution: {height}px * {width}px. The video is being extended now ...' stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint)))) return + else: + def callback(d): + return - indices = torch.arange( - 0, sum([1, 16, 2, 1, latent_window_size]) - ).unsqueeze(0) - ( - clean_latent_indices_start, - clean_latent_4x_indices, - clean_latent_2x_indices, - clean_latent_1x_indices, - latent_indices - ) = indices.split([1, 16, 2, 1, latent_window_size], dim=1) + def post_process(job_id, start_latent, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, outputs_folder, mp4_crf, stream, is_last_section): + if is_last_section: + generated_latents = torch.cat([start_latent.to(generated_latents), generated_latents], dim=2) + + total_generated_latent_frames += int(generated_latents.shape[2]) + history_latents = torch.cat([generated_latents.to(history_latents), history_latents], dim=2) + + if not high_vram: + offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8) + load_model_as_complete(vae, target_device=gpu) + + if history_pixels is None: + history_pixels = vae_decode(history_latents[:, :, :total_generated_latent_frames, :, :], vae).cpu() + else: + section_latent_frames = (latent_window_size * 2 + 1) if is_last_section else (latent_window_size * 2) + overlapped_frames = latent_window_size * 4 - 3 + + current_pixels = vae_decode(history_latents[:, :, :min(total_generated_latent_frames, section_latent_frames)], vae).cpu() + history_pixels = soft_append_bcthw(current_pixels, history_pixels, overlapped_frames) + + if not high_vram: + unload_complete_models(vae) + + if enable_preview or is_last_section: + output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4') + + save_bcthw_as_mp4(history_pixels, output_filename, fps=fps_number, crf=mp4_crf) + + print(f'Decoded. Pixel shape {history_pixels.shape}') + + stream.output_queue.push(('file', output_filename)) + + return [total_generated_latent_frames, history_latents, history_pixels] + + for latent_padding in latent_paddings: + is_last_section = latent_padding == 0 + is_first_section = latent_padding == latent_paddings[0] + latent_padding_size = latent_padding * latent_window_size - clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1) + if stream.input_queue.top() == 'end': + stream.output_queue.push(('end', None)) + return - clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[ - :, :, -sum([16, 2, 1]):, :, : - ].split([16, 2, 1], dim=2) + print(f'latent_padding_size = {latent_padding_size}, is_last_section = {is_last_section}, is_first_section = {is_first_section}') - clean_latents = torch.cat( - [start_latent.to(history_latents), clean_latents_1x], - dim=2 - ) + if len(prompt_parameters) > 0: + [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters.pop(len(prompt_parameters) - 1) + + indices = torch.arange(1 + latent_padding_size + latent_window_size + 1 + (end_stillness if is_first_section else 0) + 2 + 16).unsqueeze(0) + clean_latent_indices_pre, blank_indices, latent_indices, clean_latent_indices_post, clean_latent_2x_indices, clean_latent_4x_indices = indices.split([1, latent_padding_size, latent_window_size, 1 + (end_stillness if is_first_section else 0), 2, 16], dim=1) + clean_latent_indices = torch.cat([clean_latent_indices_pre, clean_latent_indices_post], dim=1) + + clean_latents_post, clean_latents_2x, clean_latents_4x = history_latents[:, :, :1 + 2 + 16, :, :].split([1, 2, 16], dim=2) + + # Use end image latent for the first section if provided + if has_end_image and is_first_section: + clean_latents_post = end_latent.expand(-1, -1, 1 + end_stillness, -1, -1) + + clean_latents = torch.cat([start_latent, clean_latents_post], dim=2) + + if not high_vram: + unload_complete_models() + move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation) + + if use_teacache: + transformer.initialize_teacache(enable_teacache=True, num_steps=steps) + else: + transformer.initialize_teacache(enable_teacache=False) generated_latents = sample_hunyuan( transformer=transformer, sampler='unipc', width=width, height=height, - frames=latent_window_size * 4 - 3, + frames=num_frames, real_guidance_scale=cfg, distilled_guidance_scale=gs, guidance_rescale=rs, + # shift=3.0, num_inference_steps=steps, generator=rnd, prompt_embeds=llama_vec, @@ -389,94 +908,471 @@ def worker( clean_latent_4x_indices=clean_latent_4x_indices, callback=callback, ) + del clean_latents + del clean_latents_2x + del clean_latents_4x + del latent_indices + del clean_latent_indices + del clean_latent_2x_indices + del clean_latent_4x_indices + + [total_generated_latent_frames, history_latents, history_pixels] = post_process(job_id, start_latent, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, outputs_folder, mp4_crf, stream, is_last_section) + + if is_last_section: + break + except: + traceback.print_exc() - total_generated_latent_frames += int(generated_latents.shape[2]) - history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2) + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2, image_encoder, vae, transformer + ) + + stream.output_queue.push(('end', None)) + return + +# 20250506 pftq: Modified worker to accept video input and clean frame count +@torch.no_grad() +def worker_video(input_video, end_frame, end_stillness, prompts, n_prompt, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch): + def encode_prompt(prompt, n_prompt): + llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + + if cfg == 1: + llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler) + else: + llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) + + llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512) + llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512) + + llama_vec = llama_vec.to(transformer.dtype) + llama_vec_n = llama_vec_n.to(transformer.dtype) + clip_l_pooler = clip_l_pooler.to(transformer.dtype) + clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype) + return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...')))) + + try: + # 20250506 pftq: Processing input video instead of image + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...')))) + + # 20250506 pftq: Encode video + start_latent, input_image_np, video_latents, fps, height, width = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu) + del input_video + start_latent = start_latent.to(dtype=torch.float32, device=cpu) + video_latents = video_latents.cpu() + + total_latent_sections = (total_second_length * fps) / (latent_window_size * 4) + total_latent_sections = int(max(round(total_latent_sections), 1)) + + # Clean GPU + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2, image_encoder, vae, transformer + ) + + # Text encoding + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...')))) + + if not high_vram: + 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. + load_model_as_complete(text_encoder_2, target_device=gpu) + + prompt_parameters = [] + + for prompt_part in prompts[:total_latent_sections]: + prompt_parameters.append(encode_prompt(prompt_part, n_prompt)) + + # Clean GPU + if not high_vram: + unload_complete_models( + text_encoder, text_encoder_2 + ) + + # CLIP Vision + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...')))) + + if not high_vram: + load_model_as_complete(image_encoder, target_device=gpu) + + image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder) + del input_image_np + + # 20250507 pftq: Process end frame if provided + if end_frame is not None: if not high_vram: - offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8) load_model_as_complete(vae, target_device=gpu) - real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :] + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'End frame encoding ...')))) + end_latent = image_encode( + end_frame, target_width=width, target_height=height, vae=vae, + image_encoder=image_encoder, feature_extractor=feature_extractor, device=gpu + )[0] + del end_frame + end_latent = end_latent.to(dtype=torch.float32, device=cpu) + else: + end_latent = None - if history_pixels is None: - history_pixels = vae_decode(real_history_latents, vae).cpu() + # Clean GPU + if not high_vram: + unload_complete_models(image_encoder, vae) + + image_encoder_last_hidden_state = image_encoder_output.last_hidden_state + del image_encoder_output + + # Dtype + image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype) + + if enable_preview: + def callback(d): + preview = d['denoised'] + preview = vae_decode_fake(preview) + + preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8) + preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c') + + if stream.input_queue.top() == 'end': + stream.output_queue.push(('end', None)) + raise KeyboardInterrupt('User ends the task.') + + current_step = d['i'] + 1 + percentage = int(100.0 * current_step / steps) + hint = f'Sampling {current_step}/{steps}' + 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}), Resolution: {height}px * {width}px, Seed: {seed}, Video {idx+1} of {batch}. The video is generating part {section_index+1} of {total_latent_sections}...' + stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint)))) + return + else: + def callback(d): + return + + def compute_latent(history_latents, latent_window_size, latent_padding_size, num_clean_frames, start_latent, end_latent, end_stillness, is_end_of_video): + if end_latent is not None and is_end_of_video: + local_end_stillness = end_stillness + local_end_latent = end_latent.expand(-1, -1, 1 + local_end_stillness, -1, -1) else: - section_latent_frames = latent_window_size * 2 - overlapped_frames = latent_window_size * 4 - 3 + local_end_stillness = 0 + local_end_latent = end_latent + # 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2 + available_frames = history_latents.shape[2] # Number of latent frames + max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames + adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames + # Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x + effective_clean_frames = max(0, num_clean_frames - 1) + effective_clean_frames = min(effective_clean_frames, available_frames - 2) if available_frames > 2 else 0 # 20250507 pftq: changed 1 to 2 for edge case for <=1 sec videos + num_2x_frames = min(2, max(1, available_frames - effective_clean_frames - 1)) if available_frames > effective_clean_frames + 1 else 0 # 20250507 pftq: subtracted 1 for edge case for <=1 sec videos + num_4x_frames = min(16, max(1, available_frames - effective_clean_frames - num_2x_frames)) if available_frames > effective_clean_frames + num_2x_frames else 0 # 20250507 pftq: Edge case for <=1 sec + + total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames + total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos + + indices = torch.arange(0, 1 + num_4x_frames + num_2x_frames + effective_clean_frames + adjusted_latent_frames + ((latent_padding_size + 1 + local_end_stillness) if end_latent is not None else 0)).unsqueeze(0) # 20250507 pftq: latent_window_size to adjusted_latent_frames for edge case for <=1 sec videos + clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices, blank_indices, clean_latent_indices_post = indices.split( + [1, num_4x_frames, num_2x_frames, effective_clean_frames, adjusted_latent_frames, latent_padding_size if end_latent is not None else 0, (1 + local_end_stillness) if end_latent is not None else 0], dim=1 # 20250507 pftq: latent_window_size to adjusted_latent_frames for edge case for <=1 sec videos + ) + clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices, clean_latent_indices_post], dim=1) + + # 20250506 pftq: Split history_latents dynamically based on available frames + fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos + context_frames = clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :] + + if total_context_frames > 0: + context_frames = history_latents[:, :, -total_context_frames:, :, :] + split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames] + split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes + if split_sizes: + splits = context_frames.split(split_sizes, dim=2) + split_idx = 0 + + if num_4x_frames > 0: + clean_latents_4x = splits[split_idx] + split_idx = 1 + if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos + print("Edge case for <=1 sec videos 4x") + clean_latents_4x = clean_latents_4x.expand(-1, -1, 2, -1, -1) + + if num_2x_frames > 0 and split_idx < len(splits): + clean_latents_2x = splits[split_idx] + if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos + print("Edge case for <=1 sec videos 2x") + clean_latents_2x = clean_latents_2x.expand(-1, -1, 2, -1, -1) + split_idx += 1 + elif clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos + clean_latents_2x = clean_latents_4x + + if effective_clean_frames > 0 and split_idx < len(splits): + clean_latents_1x = splits[split_idx] + + if end_latent is not None: + clean_latents = torch.cat([start_latent, clean_latents_1x, local_end_latent], dim=2) + else: + clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2) - current_pixels = vae_decode( - real_history_latents[:, :, -section_latent_frames:], vae - ).cpu() - history_pixels = soft_append_bcthw( - history_pixels, current_pixels, overlapped_frames - ) + # 20250507 pftq: Fix for <=1 sec videos. + max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4) + return [max_frames, clean_latents, clean_latents_2x, clean_latents_4x, latent_indices, clean_latents, clean_latent_indices, clean_latent_2x_indices, clean_latent_4x_indices] - if not high_vram: - unload_complete_models() + for idx in range(batch): + if batch > 1: + print(f"Beginning video {idx+1} of {batch} with seed {seed} ") - output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4') + #job_id = generate_timestamp() + job_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+f"_framepackf1-videoinput_{width}-{total_second_length}sec_seed-{seed}_steps-{steps}_distilled-{gs}_cfg-{cfg}" # 20250506 pftq: easier to read timestamp and filename - save_bcthw_as_mp4(history_pixels, output_filename, fps=30) + # Sampling + stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...')))) - print(f'Decoded. Latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}') + rnd = torch.Generator("cpu").manual_seed(seed) - stream.output_queue.push(('file', output_filename)) + # 20250506 pftq: Initialize history_latents with video latents + history_latents = video_latents + total_generated_latent_frames = history_latents.shape[2] + # 20250506 pftq: Initialize history_pixels to fix UnboundLocalError + history_pixels = previous_video = None + + # 20250509 Generate backwards with end frame for better end frame anchoring + if total_latent_sections > 4: + latent_paddings = [3] + [2] * (total_latent_sections - 3) + [1, 0] + else: + latent_paddings = list(reversed(range(total_latent_sections))) + + for section_index, latent_padding in enumerate(latent_paddings): + is_start_of_video = latent_padding == 0 + is_end_of_video = latent_padding == latent_paddings[0] + latent_padding_size = latent_padding * latent_window_size + if stream.input_queue.top() == 'end': + stream.output_queue.push(('end', None)) + return + + print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}') + + if len(prompt_parameters) > 0: + [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters.pop(0) + + if not high_vram: + unload_complete_models() + move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation) + + if use_teacache: + transformer.initialize_teacache(enable_teacache=True, num_steps=steps) + else: + transformer.initialize_teacache(enable_teacache=False) + + [max_frames, clean_latents, clean_latents_2x, clean_latents_4x, latent_indices, clean_latents, clean_latent_indices, clean_latent_2x_indices, clean_latent_4x_indices] = compute_latent(history_latents, latent_window_size, latent_padding_size, num_clean_frames, start_latent, end_latent, end_stillness, is_end_of_video) + + generated_latents = sample_hunyuan( + transformer=transformer, + sampler='unipc', + width=width, + height=height, + frames=max_frames, + real_guidance_scale=cfg, + distilled_guidance_scale=gs, + guidance_rescale=rs, + num_inference_steps=steps, + generator=rnd, + prompt_embeds=llama_vec, + prompt_embeds_mask=llama_attention_mask, + prompt_poolers=clip_l_pooler, + negative_prompt_embeds=llama_vec_n, + negative_prompt_embeds_mask=llama_attention_mask_n, + negative_prompt_poolers=clip_l_pooler_n, + device=gpu, + dtype=torch.bfloat16, + image_embeddings=image_encoder_last_hidden_state, + latent_indices=latent_indices, + clean_latents=clean_latents, + clean_latent_indices=clean_latent_indices, + clean_latents_2x=clean_latents_2x, + clean_latent_2x_indices=clean_latent_2x_indices, + clean_latents_4x=clean_latents_4x, + clean_latent_4x_indices=clean_latent_4x_indices, + callback=callback, + ) + del clean_latents + del clean_latents_2x + del clean_latents_4x + del latent_indices + del clean_latent_indices + del clean_latent_2x_indices + del clean_latent_4x_indices + + total_generated_latent_frames += int(generated_latents.shape[2]) + history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2) + + if not high_vram: + offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8) + load_model_as_complete(vae, target_device=gpu) + + if history_pixels is None: + real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :] + history_pixels = vae_decode(real_history_latents, vae).cpu() + else: + section_latent_frames = latent_window_size * 2 + overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2]) + + real_history_latents = history_latents[:, :, -min(total_generated_latent_frames, section_latent_frames):, :, :] + history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames) + + if not high_vram: + unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer) + + if enable_preview or section_index == total_latent_sections - 1: + output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4') + + # 20250506 pftq: Use input video FPS for output + save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf) + print(f"Latest video saved: {output_filename}") + # 20250508 pftq: Save prompt to mp4 metadata comments + set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompts} | Negative Prompt: {n_prompt}"); + print(f"Prompt saved to mp4 metadata comments: {output_filename}") + + # 20250506 pftq: Clean up previous partial files + if previous_video is not None and os.path.exists(previous_video): + try: + os.remove(previous_video) + print(f"Previous partial video deleted: {previous_video}") + except Exception as e: + print(f"Error deleting previous partial video {previous_video}: {e}") + previous_video = output_filename + + print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}') + + stream.output_queue.push(('file', output_filename)) + + seed = (seed + 1) % np.iinfo(np.int32).max except: traceback.print_exc() + if not high_vram: - unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer) + unload_complete_models( + text_encoder, text_encoder_2, image_encoder, vae, transformer + ) stream.output_queue.push(('end', None)) return -def get_duration( - input_image, prompt, t2v, n_prompt, - seed, total_second_length, latent_window_size, - steps, cfg, gs, rs, gpu_memory_preservation, - use_teacache, mp4_crf -): - return total_second_length * 60 +def get_duration(input_image, end_image, image_position, end_stillness, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number): + return allocation_time @spaces.GPU(duration=get_duration) -def process( - input_image, prompt, t2v=False, n_prompt="", seed=31337, - total_second_length=5, latent_window_size=9, steps=25, - cfg=1.0, gs=10.0, rs=0.0, gpu_memory_preservation=6, - use_teacache=True, mp4_crf=16 -): +def process_on_gpu(input_image, end_image, image_position, end_stillness, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number + ): + start = time.time() global stream - if t2v: - default_height, default_width = 640, 640 - input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255 - print("No input image provided. Using a blank white image.") - else: - composite_rgba_uint8 = input_image["composite"] + stream = AsyncStream() - rgb_uint8 = composite_rgba_uint8[:, :, :3] - mask_uint8 = composite_rgba_uint8[:, :, 3] + async_run(worker_start_end if generation_mode == "start_end" else worker, input_image, end_image, image_position, end_stillness, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number) - h, w = rgb_uint8.shape[:2] - background_uint8 = np.full((h, w, 3), 255, dtype=np.uint8) + output_filename = None - alpha_normalized_float32 = mask_uint8.astype(np.float32) / 255.0 - alpha_mask_float32 = np.stack([alpha_normalized_float32]*3, axis=2) + while True: + flag, data = stream.output_queue.next() - blended_image_float32 = rgb_uint8.astype(np.float32) * alpha_mask_float32 + \ - background_uint8.astype(np.float32) * (1.0 - alpha_mask_float32) + if flag == 'file': + output_filename = data + yield gr.update(value=output_filename, label="Previewed Frames"), gr.skip(), gr.skip(), gr.skip(), gr.update(interactive=False), gr.update(interactive=True), gr.skip() - input_image = np.clip(blended_image_float32, 0, 255).astype(np.uint8) + if flag == 'progress': + preview, desc, html = data + yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.skip() - yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True) + if flag == 'end': + end = time.time() + secondes = int(end - start) + minutes = math.floor(secondes / 60) + secondes = secondes - (minutes * 60) + hours = math.floor(minutes / 60) + minutes = minutes - (hours * 60) + yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), gr.skip(), "The process has lasted " + \ + ((str(hours) + " h, ") if hours != 0 else "") + \ + ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \ + str(secondes) + " sec. " + \ + "You can upscale the result with https://huggingface.co/spaces/Nick088/Real-ESRGAN_Pytorch. To make all your generated scenes consistent, you can then apply a face swap on the main character. If you do not see the generated video above, the process may have failed. See the logs for more information. If you see an error like ''NVML_SUCCESS == r INTERNAL ASSERT FAILED'', you probably haven't enough VRAM. Test an example or other options to compare. You can share your inputs to the original space or set your space in public for a peer review.", gr.update(interactive=True), gr.update(interactive=False), gr.update(visible = False) + break +def process(input_image, + end_image, + image_position=0, + end_stillness=1, + prompt="", + generation_mode="image", + n_prompt="", + randomize_seed=True, + seed=31337, + auto_allocation=True, + allocation_time=180, + resolution=640, + total_second_length=5, + latent_window_size=9, + steps=30, + cfg=1.0, + gs=10.0, + rs=0.0, + gpu_memory_preservation=6, + enable_preview=False, + use_teacache=False, + mp4_crf=16, + fps_number=30 + ): + if auto_allocation: + allocation_time = min(total_second_length * 60 * (1.5 if use_teacache else 3.0) * (1 + ((steps - 25) / 25))**2, 600) + + if torch.cuda.device_count() == 0: + gr.Warning('Set this space to GPU config to make it work.') + yield gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.update(visible = False) + return + + if randomize_seed: + seed = random.randint(0, np.iinfo(np.int32).max) + + prompts = prompt.split(";") + + if generation_mode == "text": + default_height, default_width = resolution, resolution + input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255 + print("No input image provided. Using a blank white image.") + assert input_image is not None, 'No input image!' + assert (generation_mode != "start_end") or end_image is not None, 'No end image!' + + yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip() + + gc.collect() + yield from process_on_gpu(input_image, + end_image, + image_position, + end_stillness, + prompts, + generation_mode, + n_prompt, + seed, + resolution, + total_second_length, + allocation_time, + latent_window_size, + steps, + cfg, + gs, + rs, + gpu_memory_preservation, + enable_preview, + use_teacache, + mp4_crf, + fps_number + ) + +def get_duration_video(input_video, end_frame, end_stillness, prompts, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch): + return allocation_time + +@spaces.GPU(duration=get_duration_video) +def process_video_on_gpu(input_video, end_frame, end_stillness, prompts, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch): + start = time.time() + global stream stream = AsyncStream() - async_run( - worker, input_image, prompt, n_prompt, seed, - total_second_length, latent_window_size, steps, - cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf - ) + # 20250506 pftq: Pass num_clean_frames, vae_batch, etc + async_run(worker_video, input_video, end_frame, end_stillness, prompts, n_prompt, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch) output_filename = None @@ -485,112 +1381,127 @@ def process( if flag == 'file': output_filename = data - yield ( - output_filename, - gr.update(), - gr.update(), - gr.update(), - gr.update(interactive=False), - gr.update(interactive=True) - ) + yield gr.update(value=output_filename, label="Previewed Frames"), gr.skip(), gr.skip(), gr.skip(), gr.update(interactive=False), gr.update(interactive=True), gr.skip() - elif flag == 'progress': + if flag == 'progress': preview, desc, html = data - yield ( - gr.update(), - gr.update(visible=True, value=preview), - desc, - html, - gr.update(interactive=False), - gr.update(interactive=True) - ) + yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.skip() # 20250506 pftq: Keep refreshing the video in case it got hidden when the tab was in the background - elif flag == 'end': - yield ( - output_filename, - gr.update(visible=False), - gr.update(), - '', - gr.update(interactive=True), - gr.update(interactive=False) - ) + if flag == 'end': + end = time.time() + secondes = int(end - start) + minutes = math.floor(secondes / 60) + secondes = secondes - (minutes * 60) + hours = math.floor(minutes / 60) + minutes = minutes - (hours * 60) + yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), desc + \ + " The process has lasted " + \ + ((str(hours) + " h, ") if hours != 0 else "") + \ + ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \ + str(secondes) + " sec. " + \ + " You can upscale the result with https://huggingface.co/spaces/Nick088/Real-ESRGAN_Pytorch. To make all your generated scenes consistent, you can then apply a face swap on the main character. If you do not see the generated video above, the process may have failed. See the logs for more information. If you see an error like ''NVML_SUCCESS == r INTERNAL ASSERT FAILED'', you probably haven't enough VRAM. Test an example or other options to compare. You can share your inputs to the original space or set your space in public for a peer review.", '', gr.update(interactive=True), gr.update(interactive=False), gr.update(visible = False) break +def process_video(input_video, end_frame, end_stillness, prompt, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch): + global high_vram + if auto_allocation: + allocation_time = min(total_second_length * 60 * (2.5 if use_teacache else 3.5) * (1 + ((steps - 25) / 25))**2, 600) + + if torch.cuda.device_count() == 0: + gr.Warning('Set this space to GPU config to make it work.') + yield gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.update(visible = False) + return + + if randomize_seed: + seed = random.randint(0, np.iinfo(np.int32).max) + + prompts = prompt.split(";") + + # 20250506 pftq: Updated assertion for video input + assert input_video is not None, 'No input video!' + + yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip() + + # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher + if high_vram and (no_resize or resolution>640): + print("Disabling high vram mode due to no resize and/or potentially higher resolution...") + high_vram = False + vae.enable_slicing() + vae.enable_tiling() + DynamicSwapInstaller.install_model(transformer, device=gpu) + DynamicSwapInstaller.install_model(text_encoder, device=gpu) + + # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used + if cfg > 1: + gs = 1 + + gc.collect() + yield from process_video_on_gpu(input_video, end_frame, end_stillness, prompt, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch) + def end_process(): stream.input_queue.push('end') +timeless_prompt_value = [""] +timed_prompts = {} -quick_prompts = [ - 'The girl dances gracefully, with clear movements, full of charm.', - 'A character doing some simple body movements.' -] -quick_prompts = [[x] for x in quick_prompts] +def handle_prompt_number_change(): + timed_prompts.clear() + return [] +def handle_timeless_prompt_change(timeless_prompt): + timeless_prompt_value[0] = timeless_prompt + return refresh_prompt() -def make_custom_css(): - base_progress_css = make_progress_bar_css() - extra_css = """ - body { - background: #fafbfe !important; - font-family: "Noto Sans", sans-serif; - } - #title-container { - text-align: center; - padding: 20px 0; - background: linear-gradient(135deg, #a8c0ff 0%, #fbc2eb 100%); - border-radius: 0 0 10px 10px; - margin-bottom: 20px; - } - #title-container h1 { - color: white; - font-size: 2rem; - margin: 0; - font-weight: 800; - text-shadow: 1px 2px 2px rgba(0,0,0,0.1); - } - .gr-panel { - background: #ffffffcc; - backdrop-filter: blur(4px); - border: 1px solid #dcdcf7; - border-radius: 12px; - padding: 16px; - margin-bottom: 8px; - box-shadow: 0 2px 4px rgba(0,0,0,0.1); - } - .gr-box > label { - font-size: 0.9rem; - font-weight: 600; - color: #333; - } - .button-container button { - min-height: 48px; - font-size: 1rem; - font-weight: 600; - border-radius: 8px; - border: none !important; - } - .button-container button#start-button { - background-color: #4b9ffa !important; - color: #fff; - } - .button-container button#stop-button { - background-color: #ef5d84 !important; - color: #fff; - } - .button-container button:hover { - filter: brightness(0.97); - } - .no-generating-animation { - margin-top: 10px; - margin-bottom: 10px; - } - """ - return base_progress_css + extra_css +def handle_timed_prompt_change(timed_prompt_id, timed_prompt): + timed_prompts[timed_prompt_id] = timed_prompt + return refresh_prompt() -css = make_custom_css() +def refresh_prompt(): + dict_values = {k: v for k, v in timed_prompts.items()} + sorted_dict_values = sorted(dict_values.items(), key=lambda x: x[0]) + array = [] + for sorted_dict_value in sorted_dict_values: + if timeless_prompt_value[0] is not None and len(timeless_prompt_value[0]) and sorted_dict_value[1] is not None and len(sorted_dict_value[1]): + array.append(timeless_prompt_value[0] + ". " + sorted_dict_value[1]) + else: + array.append(timeless_prompt_value[0] + sorted_dict_value[1]) + print(str(array)) + return ";".join(array) + +title_html = """ +
This space is ready to work on ZeroGPU and GPU and has been tested successfully on ZeroGPU. Please leave a message in discussion if you encounter issues.
+ """ -block = gr.Blocks(css=css).queue() +js = """ +function createGradioAnimation() { + window.addEventListener("beforeunload", function(e) { + if (document.getElementById('end-button') && !document.getElementById('end-button').disabled) { + var confirmationMessage = 'A process is still running. ' + + 'If you leave before saving, your changes will be lost.'; + + (e || window.event).returnValue = confirmationMessage; + } + return confirmationMessage; + }); + return 'Animation created'; +} +""" + +css = make_progress_bar_css() +block = gr.Blocks(css=css, js=js).queue() with block: + if torch.cuda.device_count() == 0: + with gr.Row(): + gr.HTML(""" +⚠️To use FramePack, duplicate this space and set a GPU with 30 GB VRAM. + + You can't use FramePack directly here because this space runs on a CPU, which is not enough for FramePack. Please provide feedback if you have issues. +
+ """) # Title (use gr.Group instead of gr.Box for older Gradio versions) with gr.Group(elem_id="title-container"): gr.Markdown("chrome://discards/