|
|
from diffusers_helper.hf_login import login
|
|
|
|
|
|
import gc
|
|
|
import os
|
|
|
|
|
|
os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))
|
|
|
|
|
|
try:
|
|
|
import spaces
|
|
|
except:
|
|
|
print("Not on HuggingFace")
|
|
|
import gradio as gr
|
|
|
import torch
|
|
|
import traceback
|
|
|
import einops
|
|
|
import safetensors.torch as sf
|
|
|
import numpy as np
|
|
|
import random
|
|
|
import time
|
|
|
import math
|
|
|
|
|
|
import decord
|
|
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
|
import pathlib
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
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 diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
|
|
|
from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
|
|
|
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
|
|
|
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline
|
|
|
from utils.lora_utils import merge_lora_to_state_dict
|
|
|
from utils.fp8_optimization_utils import optimize_state_dict_with_fp8, apply_fp8_monkey_patch
|
|
|
import pillow_heif
|
|
|
|
|
|
pillow_heif.register_heif_opener()
|
|
|
|
|
|
high_vram = False
|
|
|
free_mem_gb = 0
|
|
|
|
|
|
transformer = [None]
|
|
|
transformer_dtype = torch.bfloat16
|
|
|
previous_lora_file = None
|
|
|
previous_lora_multiplier = None
|
|
|
previous_fp8_optimization = None
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
vae.eval()
|
|
|
text_encoder.eval()
|
|
|
text_encoder_2.eval()
|
|
|
image_encoder.eval()
|
|
|
|
|
|
|
|
|
if not high_vram:
|
|
|
vae.enable_slicing()
|
|
|
vae.enable_tiling()
|
|
|
|
|
|
|
|
|
print('transformer.high_quality_fp32_output_for_inference = True')
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
if not high_vram:
|
|
|
|
|
|
|
|
|
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
|
|
else:
|
|
|
text_encoder.to(gpu)
|
|
|
text_encoder_2.to(gpu)
|
|
|
image_encoder.to(gpu)
|
|
|
vae.to(gpu)
|
|
|
|
|
|
|
|
|
stream = AsyncStream()
|
|
|
|
|
|
outputs_folder = './outputs/'
|
|
|
os.makedirs(outputs_folder, exist_ok=True)
|
|
|
|
|
|
input_image_debug_value = [None]
|
|
|
input_video_debug_value = [None]
|
|
|
prompt_debug_value = [None]
|
|
|
total_second_length_debug_value = [None]
|
|
|
lora_file_debug_value = [None]
|
|
|
|
|
|
default_local_storage = {
|
|
|
"generation-mode": "image",
|
|
|
}
|
|
|
|
|
|
def load_transfomer():
|
|
|
print("Loading transformer ...")
|
|
|
transformer[0] = HunyuanVideoTransformer3DModelPacked.from_pretrained(
|
|
|
"lllyasviel/FramePackI2V_HY", torch_dtype=torch.bfloat16
|
|
|
).cpu()
|
|
|
transformer[0].eval()
|
|
|
transformer[0].high_quality_fp32_output_for_inference = True
|
|
|
print("transformer[0].high_quality_fp32_output_for_inference = True")
|
|
|
|
|
|
transformer[0].to(dtype=torch.bfloat16)
|
|
|
transformer[0].requires_grad_(False)
|
|
|
return transformer[0]
|
|
|
|
|
|
@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.
|
|
|
"""
|
|
|
|
|
|
video_path = str(pathlib.Path(video_path).resolve())
|
|
|
|
|
|
|
|
|
|
|
|
if device == "cuda" and not torch.cuda.is_available():
|
|
|
|
|
|
device = "cpu"
|
|
|
|
|
|
try:
|
|
|
|
|
|
|
|
|
vr = decord.VideoReader(video_path)
|
|
|
fps = vr.get_avg_fps()
|
|
|
num_real_frames = len(vr)
|
|
|
|
|
|
|
|
|
|
|
|
latent_size_factor = 4
|
|
|
num_frames = (num_real_frames // latent_size_factor) * latent_size_factor
|
|
|
|
|
|
|
|
|
num_real_frames = num_frames
|
|
|
|
|
|
|
|
|
|
|
|
frames = vr.get_batch(range(num_real_frames)).asnumpy()
|
|
|
|
|
|
|
|
|
|
|
|
native_height, native_width = frames.shape[1], frames.shape[2]
|
|
|
|
|
|
|
|
|
|
|
|
target_height = native_height if height is None else height
|
|
|
target_width = native_width if width is None else width
|
|
|
|
|
|
|
|
|
if not no_resize:
|
|
|
target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
processed_frames = []
|
|
|
for i, frame in enumerate(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)
|
|
|
|
|
|
|
|
|
|
|
|
input_image_np = processed_frames[0]
|
|
|
|
|
|
|
|
|
|
|
|
frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1
|
|
|
frames_pt = frames_pt.permute(0, 3, 1, 2)
|
|
|
frames_pt = frames_pt.unsqueeze(0)
|
|
|
frames_pt = frames_pt.permute(0, 2, 1, 3, 4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frames_pt = frames_pt.to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
vae.to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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):
|
|
|
|
|
|
batch = frames_pt[:, :, i:i + vae_batch_size]
|
|
|
try:
|
|
|
|
|
|
if device == "cuda":
|
|
|
free_mem = torch.cuda.memory_allocated() / 1024**3
|
|
|
|
|
|
batch_latent = vae_encode(batch, vae)
|
|
|
|
|
|
if device == "cuda":
|
|
|
torch.cuda.synchronize()
|
|
|
|
|
|
latents.append(batch_latent)
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
history_latents = torch.cat(latents, dim=2)
|
|
|
|
|
|
|
|
|
|
|
|
start_latent = history_latents[:, :, :1]
|
|
|
|
|
|
|
|
|
|
|
|
if device == "cuda":
|
|
|
vae.to(cpu)
|
|
|
torch.cuda.empty_cache()
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
def set_mp4_comments_imageio_ffmpeg(input_file, comments):
|
|
|
try:
|
|
|
|
|
|
ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
|
|
|
|
|
|
|
|
|
if not os.path.exists(input_file):
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
|
|
|
|
|
|
|
|
|
command = [
|
|
|
ffmpeg_path,
|
|
|
'-i', input_file,
|
|
|
'-metadata', f'comment={comments}',
|
|
|
'-c:v', 'copy',
|
|
|
'-c:a', 'copy',
|
|
|
'-y',
|
|
|
temp_file
|
|
|
]
|
|
|
|
|
|
|
|
|
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
|
|
|
|
if result.returncode == 0:
|
|
|
|
|
|
shutil.move(temp_file, input_file)
|
|
|
|
|
|
return True
|
|
|
else:
|
|
|
|
|
|
if os.path.exists(temp_file):
|
|
|
os.remove(temp_file)
|
|
|
|
|
|
return False
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
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
|
|
|
|
|
|
@torch.no_grad()
|
|
|
def worker(input_image, image_position, 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, lora_file, lora_multiplier, fp8_optimization, model_changed):
|
|
|
global transformer
|
|
|
|
|
|
if model_changed:
|
|
|
if lora_file is not None or fp8_optimization:
|
|
|
state_dict = transformer[0].state_dict()
|
|
|
|
|
|
|
|
|
if lora_file is not None:
|
|
|
|
|
|
|
|
|
|
|
|
print(f"Merging LoRA file {os.path.basename(lora_file)} ...")
|
|
|
state_dict = merge_lora_to_state_dict(state_dict, lora_file, lora_multiplier, device=gpu)
|
|
|
gc.collect()
|
|
|
|
|
|
if fp8_optimization:
|
|
|
TARGET_KEYS = ["transformer_blocks", "single_transformer_blocks"]
|
|
|
EXCLUDE_KEYS = ["norm"]
|
|
|
|
|
|
|
|
|
print("Optimizing for fp8")
|
|
|
state_dict = optimize_state_dict_with_fp8(state_dict, gpu, TARGET_KEYS, EXCLUDE_KEYS, move_to_device=False)
|
|
|
|
|
|
|
|
|
apply_fp8_monkey_patch(transformer[0], state_dict, use_scaled_mm=False)
|
|
|
gc.collect()
|
|
|
|
|
|
info = transformer[0].load_state_dict(state_dict, strict=True, assign=True)
|
|
|
print(f"LoRA and/or fp8 optimization applied: {info}")
|
|
|
|
|
|
if not high_vram:
|
|
|
DynamicSwapInstaller.install_model(transformer[0], device=gpu)
|
|
|
else:
|
|
|
transformer[0].to(gpu)
|
|
|
|
|
|
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[0].dtype)
|
|
|
llama_vec_n = llama_vec_n.to(transformer[0].dtype)
|
|
|
clip_l_pooler = clip_l_pooler.to(transformer[0].dtype)
|
|
|
clip_l_pooler_n = clip_l_pooler_n.to(transformer[0].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:
|
|
|
|
|
|
if not high_vram:
|
|
|
unload_complete_models(
|
|
|
text_encoder, text_encoder_2, image_encoder, vae, transformer[0]
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
|
|
|
|
|
|
if not high_vram:
|
|
|
fake_diffusers_current_device(text_encoder, gpu)
|
|
|
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))
|
|
|
|
|
|
|
|
|
if not high_vram:
|
|
|
unload_complete_models(
|
|
|
text_encoder, text_encoder_2
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
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=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)
|
|
|
|
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer[0].dtype)
|
|
|
|
|
|
|
|
|
|
|
|
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, device=cpu)
|
|
|
start_latent = start_latent.to(history_latents)
|
|
|
history_pixels = None
|
|
|
|
|
|
history_latents = torch.cat([history_latents, start_latent] if forward else [start_latent, history_latents], dim=2)
|
|
|
total_generated_latent_frames = 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))}, 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[0])
|
|
|
|
|
|
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):
|
|
|
prompt_parameters[prompt_index] = None
|
|
|
|
|
|
if not high_vram:
|
|
|
unload_complete_models()
|
|
|
move_model_to_device_with_memory_preservation(transformer[0], target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
|
|
|
|
|
|
if use_teacache:
|
|
|
transformer[0].initialize_teacache(enable_teacache=True, num_steps=steps)
|
|
|
else:
|
|
|
transformer[0].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[0],
|
|
|
sampler='unipc',
|
|
|
width=width,
|
|
|
height=height,
|
|
|
frames=latent_window_size * 4 - 3,
|
|
|
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,
|
|
|
)
|
|
|
|
|
|
[total_generated_latent_frames, history_latents, history_pixels] = post_process(forward, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer[0], 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)
|
|
|
real_history_latents = zero_latents = None
|
|
|
|
|
|
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[0]
|
|
|
)
|
|
|
|
|
|
stream.output_queue.push(('end', None))
|
|
|
return
|
|
|
|
|
|
|
|
|
@torch.no_grad()
|
|
|
def worker_video(input_video, 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, lora_file, lora_multiplier, fp8_optimization, model_changed):
|
|
|
global transformer
|
|
|
|
|
|
if model_changed:
|
|
|
if lora_file is not None or fp8_optimization:
|
|
|
state_dict = transformer[0].state_dict()
|
|
|
|
|
|
|
|
|
if lora_file is not None:
|
|
|
|
|
|
|
|
|
|
|
|
print(f"Merging LoRA file {os.path.basename(lora_file)} ...")
|
|
|
state_dict = merge_lora_to_state_dict(state_dict, lora_file, lora_multiplier, device=gpu)
|
|
|
gc.collect()
|
|
|
|
|
|
if fp8_optimization:
|
|
|
TARGET_KEYS = ["transformer_blocks", "single_transformer_blocks"]
|
|
|
EXCLUDE_KEYS = ["norm"]
|
|
|
|
|
|
|
|
|
print("Optimizing for fp8")
|
|
|
state_dict = optimize_state_dict_with_fp8(state_dict, gpu, TARGET_KEYS, EXCLUDE_KEYS, move_to_device=False)
|
|
|
|
|
|
|
|
|
apply_fp8_monkey_patch(transformer[0], state_dict, use_scaled_mm=False)
|
|
|
gc.collect()
|
|
|
|
|
|
info = transformer[0].load_state_dict(state_dict, strict=True, assign=True)
|
|
|
print(f"LoRA and/or fp8 optimization applied: {info}")
|
|
|
|
|
|
if not high_vram:
|
|
|
DynamicSwapInstaller.install_model(transformer[0], device=gpu)
|
|
|
else:
|
|
|
transformer[0].to(gpu)
|
|
|
|
|
|
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[0].dtype)
|
|
|
llama_vec_n = llama_vec_n.to(transformer[0].dtype)
|
|
|
clip_l_pooler = clip_l_pooler.to(transformer[0].dtype)
|
|
|
clip_l_pooler_n = clip_l_pooler_n.to(transformer[0].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:
|
|
|
|
|
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
|
|
|
|
|
|
|
|
|
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)
|
|
|
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))
|
|
|
|
|
|
|
|
|
if not high_vram:
|
|
|
unload_complete_models(
|
|
|
text_encoder, text_encoder_2, image_encoder, vae, transformer[0]
|
|
|
)
|
|
|
|
|
|
|
|
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
|
|
|
|
|
|
if not high_vram:
|
|
|
fake_diffusers_current_device(text_encoder, gpu)
|
|
|
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))
|
|
|
|
|
|
|
|
|
if not high_vram:
|
|
|
unload_complete_models(
|
|
|
text_encoder, text_encoder_2
|
|
|
)
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
if not high_vram:
|
|
|
unload_complete_models(image_encoder)
|
|
|
|
|
|
image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
|
|
|
|
|
|
|
|
|
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer[0].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, num_clean_frames, start_latent):
|
|
|
|
|
|
available_frames = history_latents.shape[2]
|
|
|
max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4)
|
|
|
adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4)
|
|
|
|
|
|
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
|
|
|
num_2x_frames = min(2, max(1, available_frames - effective_clean_frames - 1)) if available_frames > effective_clean_frames + 1 else 0
|
|
|
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
|
|
|
|
|
|
total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
|
|
|
total_context_frames = min(total_context_frames, available_frames)
|
|
|
|
|
|
indices = torch.arange(0, 1 + num_4x_frames + num_2x_frames + effective_clean_frames + adjusted_latent_frames).unsqueeze(0)
|
|
|
clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
|
|
|
[1, num_4x_frames, num_2x_frames, effective_clean_frames, adjusted_latent_frames], dim=1
|
|
|
)
|
|
|
clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
|
|
|
|
|
|
|
|
|
fallback_frame_count = 2
|
|
|
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]
|
|
|
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:
|
|
|
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:
|
|
|
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:
|
|
|
clean_latents_2x = clean_latents_4x
|
|
|
|
|
|
if effective_clean_frames > 0 and split_idx < len(splits):
|
|
|
clean_latents_1x = splits[split_idx]
|
|
|
|
|
|
clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
|
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
|
for idx in range(batch):
|
|
|
if batch > 1:
|
|
|
print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
|
|
|
|
|
|
|
|
|
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}"
|
|
|
|
|
|
|
|
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
|
|
|
|
|
|
rnd = torch.Generator("cpu").manual_seed(seed)
|
|
|
|
|
|
|
|
|
history_latents = video_latents
|
|
|
total_generated_latent_frames = history_latents.shape[2]
|
|
|
|
|
|
history_pixels = None
|
|
|
previous_video = None
|
|
|
|
|
|
for section_index in range(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}')
|
|
|
|
|
|
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[0], target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
|
|
|
|
|
|
if use_teacache:
|
|
|
transformer[0].initialize_teacache(enable_teacache=True, num_steps=steps)
|
|
|
else:
|
|
|
transformer[0].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, num_clean_frames, start_latent)
|
|
|
|
|
|
generated_latents = sample_hunyuan(
|
|
|
transformer=transformer[0],
|
|
|
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,
|
|
|
)
|
|
|
|
|
|
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[0], 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[0])
|
|
|
|
|
|
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')
|
|
|
|
|
|
|
|
|
save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
|
|
|
print(f"Latest video saved: {output_filename}")
|
|
|
|
|
|
set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompts} | Negative Prompt: {n_prompt}");
|
|
|
print(f"Prompt saved to mp4 metadata comments: {output_filename}")
|
|
|
|
|
|
|
|
|
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[0]
|
|
|
)
|
|
|
|
|
|
stream.output_queue.push(('end', None))
|
|
|
return
|
|
|
|
|
|
def get_duration(input_image, image_position, 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, lora_file, lora_multiplier, fp8_optimization, model_changed):
|
|
|
return allocation_time
|
|
|
|
|
|
|
|
|
@spaces.GPU(duration=get_duration)
|
|
|
def process_on_gpu(input_image, image_position, 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, lora_file, lora_multiplier, fp8_optimization, model_changed
|
|
|
):
|
|
|
start = time.time()
|
|
|
global stream
|
|
|
stream = AsyncStream()
|
|
|
|
|
|
async_run(worker, input_image, image_position, 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, lora_file, lora_multiplier, fp8_optimization, model_changed)
|
|
|
|
|
|
output_filename = None
|
|
|
|
|
|
while True:
|
|
|
flag, data = stream.output_queue.next()
|
|
|
|
|
|
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()
|
|
|
|
|
|
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()
|
|
|
|
|
|
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 RIFE. 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,
|
|
|
image_position=0,
|
|
|
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=25,
|
|
|
cfg=1.0,
|
|
|
gs=10.0,
|
|
|
rs=0.0,
|
|
|
gpu_memory_preservation=6,
|
|
|
enable_preview=True,
|
|
|
use_teacache=False,
|
|
|
mp4_crf=16,
|
|
|
fps_number=30,
|
|
|
lora_file=None,
|
|
|
lora_multiplier=0.8,
|
|
|
fp8_optimization=False
|
|
|
):
|
|
|
global transformer, previous_lora_file, previous_lora_multiplier, previous_fp8_optimization
|
|
|
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 input_image_debug_value[0] is not None or prompt_debug_value[0] is not None or total_second_length_debug_value[0] is not None or lora_file_debug_value[0] is not None:
|
|
|
input_image = input_image_debug_value[0]
|
|
|
prompt = prompt_debug_value[0]
|
|
|
total_second_length = total_second_length_debug_value[0]
|
|
|
allocation_time = min(total_second_length_debug_value[0] * 60 * 100, 600)
|
|
|
lora_file = lora_file_debug_value[0]
|
|
|
input_image_debug_value[0] = prompt_debug_value[0] = total_second_length_debug_value[0] = lora_file_debug_value[0] = None
|
|
|
|
|
|
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 = 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.")
|
|
|
|
|
|
yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip()
|
|
|
|
|
|
model_changed = transformer[0] is None or (
|
|
|
lora_file != previous_lora_file
|
|
|
or lora_multiplier != previous_lora_multiplier
|
|
|
or fp8_optimization != previous_fp8_optimization
|
|
|
)
|
|
|
|
|
|
|
|
|
if model_changed:
|
|
|
stream.output_queue.push(("progress", (None, "", make_progress_bar_html(0, "Loading transformer ..."))))
|
|
|
|
|
|
transformer[0] = None
|
|
|
time.sleep(1.0)
|
|
|
torch.cuda.empty_cache()
|
|
|
gc.collect()
|
|
|
|
|
|
previous_lora_file = lora_file
|
|
|
previous_lora_multiplier = lora_multiplier
|
|
|
previous_fp8_optimization = fp8_optimization
|
|
|
|
|
|
transformer[0] = load_transfomer()
|
|
|
|
|
|
yield from process_on_gpu(input_image,
|
|
|
image_position,
|
|
|
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,
|
|
|
lora_file,
|
|
|
lora_multiplier,
|
|
|
fp8_optimization,
|
|
|
model_changed
|
|
|
)
|
|
|
|
|
|
def get_duration_video(input_video, 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, lora_file, lora_multiplier, fp8_optimization, model_changed):
|
|
|
return allocation_time
|
|
|
|
|
|
|
|
|
@spaces.GPU(duration=get_duration_video)
|
|
|
def process_video_on_gpu(input_video, 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, lora_file, lora_multiplier, fp8_optimization, model_changed):
|
|
|
start = time.time()
|
|
|
global stream
|
|
|
stream = AsyncStream()
|
|
|
|
|
|
|
|
|
async_run(worker_video, input_video, 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, lora_file, lora_multiplier, fp8_optimization, model_changed)
|
|
|
|
|
|
output_filename = None
|
|
|
|
|
|
while True:
|
|
|
flag, data = stream.output_queue.next()
|
|
|
|
|
|
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()
|
|
|
|
|
|
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()
|
|
|
|
|
|
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 RIFE. 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, 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, lora_file, lora_multiplier, fp8_optimization):
|
|
|
global transformer, previous_lora_file, previous_lora_multiplier, previous_fp8_optimization, 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 input_video_debug_value[0] is not None or prompt_debug_value[0] is not None or total_second_length_debug_value[0] is not None or lora_file_debug_value is not None:
|
|
|
input_video = input_video_debug_value[0]
|
|
|
prompt = prompt_debug_value[0]
|
|
|
total_second_length = total_second_length_debug_value[0]
|
|
|
allocation_time = min(total_second_length_debug_value[0] * 60 * 100, 600)
|
|
|
lora_file = lora_file_debug_value[0]
|
|
|
input_video_debug_value[0] = prompt_debug_value[0] = total_second_length_debug_value[0] = lora_file_debug_value[0] = None
|
|
|
|
|
|
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(";")
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
model_changed = transformer[0] is None or (
|
|
|
lora_file != previous_lora_file
|
|
|
or lora_multiplier != previous_lora_multiplier
|
|
|
or fp8_optimization != previous_fp8_optimization
|
|
|
)
|
|
|
|
|
|
|
|
|
if model_changed:
|
|
|
stream.output_queue.push(("progress", (None, "", make_progress_bar_html(0, "Loading transformer ..."))))
|
|
|
|
|
|
transformer[0] = None
|
|
|
time.sleep(1.0)
|
|
|
torch.cuda.empty_cache()
|
|
|
gc.collect()
|
|
|
|
|
|
previous_lora_file = lora_file
|
|
|
previous_lora_multiplier = lora_multiplier
|
|
|
previous_fp8_optimization = fp8_optimization
|
|
|
|
|
|
transformer[0] = load_transfomer()
|
|
|
|
|
|
|
|
|
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[0], device=gpu)
|
|
|
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
|
|
|
|
|
|
|
|
if cfg > 1:
|
|
|
gs = 1
|
|
|
|
|
|
yield from process_video_on_gpu(input_video, 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, lora_file, lora_multiplier, fp8_optimization, model_changed)
|
|
|
|
|
|
def end_process():
|
|
|
stream.input_queue.push('end')
|
|
|
|
|
|
timeless_prompt_value = [""]
|
|
|
timed_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 handle_timed_prompt_change(timed_prompt_id, timed_prompt):
|
|
|
timed_prompts[timed_prompt_id] = timed_prompt
|
|
|
return refresh_prompt()
|
|
|
|
|
|
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 = """
|
|
|
<h1><center>FramePack with FramePack LoRAs</center></h1>
|
|
|
<big><center>Generate videos from text/image/video freely, without account, without watermark and download it</center></big>
|
|
|
<br/>
|
|
|
|
|
|
<p>This space is ready to work on ZeroGPU and GPU and has been tested successfully on ZeroGPU. Please leave a <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/FramePack/discussions/new">message in discussion</a> if you encounter issues.</p>
|
|
|
"""
|
|
|
|
|
|
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("""
|
|
|
<p style="background-color: red;"><big><big><big><b>⚠️To use FramePack, <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/FramePack?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>
|
|
|
|
|
|
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/FramePack/discussions/new">feedback</a> if you have issues.
|
|
|
</big></big></big></p>
|
|
|
""")
|
|
|
gr.HTML(title_html)
|
|
|
local_storage = gr.BrowserState(default_local_storage)
|
|
|
with gr.Row():
|
|
|
with gr.Column():
|
|
|
generation_mode = gr.Radio([["Text-to-Video", "text"], ["Image-to-Video", "image"], ["Video Extension", "video"]], elem_id="generation-mode", label="Generation mode", value = "image")
|
|
|
text_to_video_hint = gr.HTML("Text-to-Video badly works with a flash effect at the start. I discourage to use the Text-to-Video feature. You should rather generate an image with Flux and use Image-to-Video. You will save time.")
|
|
|
input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)
|
|
|
image_position = gr.Slider(label="Image position", minimum=0, maximum=100, value=0, step=1, info='0=Video start; 100=Video end (lower quality)')
|
|
|
input_video = gr.Video(sources='upload', label="Input Video", height=320)
|
|
|
timeless_prompt = gr.Textbox(label="Timeless prompt", info='Used on the whole duration of the generation', value='', placeholder="The creature starts to move, fast motion, fixed camera, focus motion, consistent arm, consistent position, mute colors, insanely detailed")
|
|
|
prompt_number = gr.Slider(label="Timed prompt number", minimum=0, maximum=1000, value=0, step=1, info='Prompts will automatically appear')
|
|
|
|
|
|
@gr.render(inputs=prompt_number)
|
|
|
def show_split(prompt_number):
|
|
|
for digit in range(prompt_number):
|
|
|
timed_prompt_id = gr.Textbox(value="timed_prompt_" + str(digit), visible=False)
|
|
|
timed_prompt = gr.Textbox(label="Timed prompt #" + str(digit + 1), elem_id="timed_prompt_" + str(digit), value="")
|
|
|
timed_prompt.change(fn=handle_timed_prompt_change, inputs=[timed_prompt_id, timed_prompt], outputs=[final_prompt])
|
|
|
|
|
|
final_prompt = gr.Textbox(label="Final prompt", value='', info='Use ; to separate in time; beware to write to stop the previous action')
|
|
|
prompt_hint = gr.HTML("Video extension barely follows the prompt; to force to follow the prompt, you have to set the Distilled CFG Scale to 3.0 and the Context Frames to 2 but the video quality will be poor.")
|
|
|
total_second_length = gr.Slider(label="Video length to generate (seconds if 30 fps)", minimum=1, maximum=120, value=2, step=0.1)
|
|
|
|
|
|
with gr.Row():
|
|
|
start_button = gr.Button(value="🎥 Generate", variant="primary")
|
|
|
start_button_video = gr.Button(value="🎥 Generate", variant="primary")
|
|
|
end_button = gr.Button(elem_id="end-button", value="End Generation", variant="stop", interactive=False)
|
|
|
|
|
|
with gr.Accordion("Advanced settings", open=False):
|
|
|
enable_preview = gr.Checkbox(label='Enable preview', value=True, info='Display a preview around each second generated but it costs 2 sec. for each second generated.')
|
|
|
use_teacache = gr.Checkbox(label='Use TeaCache', value=False, info='Faster speed and no break in brightness, but often makes hands and fingers slightly worse. TeaCache seems unstable with I2V.')
|
|
|
|
|
|
n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')
|
|
|
|
|
|
fps_number = gr.Slider(label="Frame per seconds", info="The model is trained for 30 fps so other fps may generate weird results", minimum=10, maximum=60, value=30, step=1)
|
|
|
|
|
|
latent_window_size = gr.Slider(label="Latent Window Size", minimum=1, maximum=33, value=9, step=1, info='Generate more frames at a time (larger chunks). Less degradation and better blending but higher VRAM cost. Should not change.')
|
|
|
steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=30, step=1, info='Increase for more quality, especially if using high non-distilled CFG. If your animation has very few motion, you may have brutal brightness change; this can be fixed increasing the steps.')
|
|
|
|
|
|
with gr.Row():
|
|
|
no_resize = gr.Checkbox(label='Force Original Video Resolution (no Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
|
|
|
resolution = gr.Dropdown([
|
|
|
["409,600 px (working)", 640],
|
|
|
["451,584 px (working)", 672],
|
|
|
["495,616 px (VRAM pb on HF)", 704],
|
|
|
["589,824 px (not tested)", 768],
|
|
|
["692,224 px (not tested)", 832],
|
|
|
["746,496 px (not tested)", 864],
|
|
|
["921,600 px (not tested)", 960]
|
|
|
], value=672, label="Resolution (width x height)", info="Do not affect the generation time")
|
|
|
|
|
|
|
|
|
cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01, info='Use this instead of Distilled for more detail/control + Negative Prompt (make sure Distilled set to 1). Doubles render time. Should not change.')
|
|
|
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; 3=follow the prompt but blurred motions & unsharped, 10=focus motion; changing this value is not recommended')
|
|
|
rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, info='Should not change')
|
|
|
|
|
|
|
|
|
|
|
|
num_clean_frames = gr.Slider(label="Number of Context Frames", minimum=2, maximum=10, value=5, step=1, info="Retain more video details but increase memory use. Reduce to 2 to avoid memory issues or to give more weight to the prompt.")
|
|
|
|
|
|
default_vae = 32
|
|
|
if high_vram:
|
|
|
default_vae = 128
|
|
|
elif free_mem_gb>=20:
|
|
|
default_vae = 64
|
|
|
|
|
|
vae_batch = gr.Slider(label="VAE Batch Size for Input Video", minimum=4, maximum=256, value=default_vae, step=4, info="Reduce if running out of memory. Increase for better quality frames during fast motion.")
|
|
|
|
|
|
|
|
|
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.")
|
|
|
|
|
|
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. ")
|
|
|
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.')
|
|
|
with gr.Row():
|
|
|
randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
|
|
|
seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
|
|
|
with gr.Row():
|
|
|
auto_allocation = gr.Checkbox(label='Auto allocation', value=True, info='If checked, the GPU allocation time is estimated from the parameters')
|
|
|
allocation_time = gr.Slider(label="GPU allocation time (in seconds)", info='lower=May abort run, higher=Quota penalty for next runs; only useful for ZeroGPU; for instance set to 88 when you have the message "You have exceeded your GPU quota (180s requested vs. 89s left)."', value=180, minimum=60, maximum=320, step=1)
|
|
|
|
|
|
with gr.Group():
|
|
|
lora_file = gr.File(label="FramePack LoRA File", file_count="single", type="filepath")
|
|
|
lora_multiplier = gr.Slider(label="LoRA Multiplier", minimum=0.0, maximum=1.0, value=0.8, step=0.1)
|
|
|
fp8_optimization = gr.Checkbox(label="FP8 Optimization", value=False)
|
|
|
|
|
|
with gr.Accordion("Debug", open=False):
|
|
|
input_image_debug = gr.Image(type="numpy", label="Image Debug", height=320)
|
|
|
input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
|
|
|
prompt_debug = gr.Textbox(label="Prompt Debug", value='')
|
|
|
total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)
|
|
|
lora_file_debug = gr.File(label="LoRA File", file_count="single", type="filepath")
|
|
|
|
|
|
with gr.Column():
|
|
|
warning = gr.HTML(elem_id="warning", value = "<center><big>Your computer must <u>not</u> enter into standby mode.</big><br/>On Chrome, you can force to keep a tab alive in <code>chrome://discards/</code></center>", visible = False)
|
|
|
result_video = gr.Video(label="Generated Frames", autoplay=True, show_share_button=False, height=512, loop=True)
|
|
|
preview_image = gr.Image(label="Next Latents", height=200, visible=False)
|
|
|
progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
|
|
|
progress_bar = gr.HTML('', elem_classes='no-generating-animation')
|
|
|
|
|
|
|
|
|
ips = [input_image, image_position, final_prompt, generation_mode, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number, lora_file, lora_multiplier, fp8_optimization]
|
|
|
ips_video = [input_video, final_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, lora_file, lora_multiplier, fp8_optimization]
|
|
|
|
|
|
with gr.Row(elem_id="text_examples", visible=False):
|
|
|
gr.Examples(
|
|
|
label = "Examples from text",
|
|
|
examples = [
|
|
|
[
|
|
|
None,
|
|
|
0,
|
|
|
"Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
|
|
"text",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
]
|
|
|
],
|
|
|
run_on_click = True,
|
|
|
fn = process,
|
|
|
inputs = ips,
|
|
|
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
|
|
|
cache_examples = torch.cuda.device_count() > 0,
|
|
|
)
|
|
|
|
|
|
with gr.Row(elem_id="image_examples", visible=False):
|
|
|
gr.Examples(
|
|
|
label = "Examples from image",
|
|
|
examples = [
|
|
|
[
|
|
|
"./img_examples/Example2.webp",
|
|
|
0,
|
|
|
"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks, the man stops talking and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example1.png",
|
|
|
0,
|
|
|
"A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example4.webp",
|
|
|
1,
|
|
|
"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example4.webp",
|
|
|
50,
|
|
|
"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example4.webp",
|
|
|
100,
|
|
|
"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
],
|
|
|
run_on_click = True,
|
|
|
fn = process,
|
|
|
inputs = ips,
|
|
|
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
|
|
|
cache_examples = torch.cuda.device_count() > 0,
|
|
|
)
|
|
|
|
|
|
with gr.Row(elem_id="video_examples", visible=False):
|
|
|
gr.Examples(
|
|
|
label = "Examples from video",
|
|
|
examples = [
|
|
|
[
|
|
|
"./img_examples/Example1.mp4",
|
|
|
"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",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
1,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
5,
|
|
|
default_vae,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example1.mp4",
|
|
|
"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",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
1,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
False,
|
|
|
16,
|
|
|
5,
|
|
|
default_vae,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
],
|
|
|
run_on_click = True,
|
|
|
fn = process_video,
|
|
|
inputs = ips_video,
|
|
|
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button, warning],
|
|
|
cache_examples = torch.cuda.device_count() > 0,
|
|
|
)
|
|
|
|
|
|
gr.Examples(
|
|
|
label = "✍️ Examples from text",
|
|
|
examples = [
|
|
|
[
|
|
|
None,
|
|
|
0,
|
|
|
"Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
|
|
"text",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
]
|
|
|
],
|
|
|
run_on_click = True,
|
|
|
fn = process,
|
|
|
inputs = ips,
|
|
|
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
|
|
|
cache_examples = False,
|
|
|
)
|
|
|
|
|
|
gr.Examples(
|
|
|
label = "🖼️ Examples from image",
|
|
|
examples = [
|
|
|
[
|
|
|
"./img_examples/Example1.png",
|
|
|
0,
|
|
|
"A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example2.webp",
|
|
|
0,
|
|
|
"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks, the man stops talking and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
2,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example2.webp",
|
|
|
0,
|
|
|
"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks, the woman stops talking and the woman listens A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
2,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example3.jpg",
|
|
|
0,
|
|
|
"A boy is walking to the right, full view, full-length view, cartoon",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
],
|
|
|
[
|
|
|
"./img_examples/Example4.webp",
|
|
|
100,
|
|
|
"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
|
|
|
"image",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
False,
|
|
|
16,
|
|
|
30,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
]
|
|
|
],
|
|
|
run_on_click = True,
|
|
|
fn = process,
|
|
|
inputs = ips,
|
|
|
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
|
|
|
cache_examples = False,
|
|
|
)
|
|
|
|
|
|
gr.Examples(
|
|
|
label = "🎥 Examples from video",
|
|
|
examples = [
|
|
|
[
|
|
|
"./img_examples/Example1.mp4",
|
|
|
"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",
|
|
|
"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth",
|
|
|
True,
|
|
|
42,
|
|
|
True,
|
|
|
180,
|
|
|
1,
|
|
|
672,
|
|
|
1,
|
|
|
9,
|
|
|
30,
|
|
|
1.0,
|
|
|
10.0,
|
|
|
0.0,
|
|
|
6,
|
|
|
False,
|
|
|
True,
|
|
|
False,
|
|
|
16,
|
|
|
5,
|
|
|
default_vae,
|
|
|
None,
|
|
|
0.8,
|
|
|
False
|
|
|
]
|
|
|
],
|
|
|
run_on_click = True,
|
|
|
fn = process_video,
|
|
|
inputs = ips_video,
|
|
|
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button, warning],
|
|
|
cache_examples = False,
|
|
|
)
|
|
|
|
|
|
def save_preferences(preferences, value):
|
|
|
preferences["generation-mode"] = value
|
|
|
return preferences
|
|
|
|
|
|
def load_preferences(saved_prefs):
|
|
|
saved_prefs = init_preferences(saved_prefs)
|
|
|
return saved_prefs["generation-mode"]
|
|
|
|
|
|
def init_preferences(saved_prefs):
|
|
|
if saved_prefs is None:
|
|
|
saved_prefs = default_local_storage
|
|
|
return saved_prefs
|
|
|
|
|
|
def check_parameters(generation_mode, input_image, input_video):
|
|
|
if generation_mode == "image" and input_image is None:
|
|
|
raise gr.Error("Please provide an image to extend.")
|
|
|
if generation_mode == "video" and input_video is None:
|
|
|
raise gr.Error("Please provide a video to extend.")
|
|
|
return [gr.update(interactive=True), gr.update(visible = True)]
|
|
|
|
|
|
def handle_generation_mode_change(generation_mode_data):
|
|
|
if generation_mode_data == "text":
|
|
|
return [gr.update(visible = True), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True)]
|
|
|
elif generation_mode_data == "image":
|
|
|
return [gr.update(visible = False), gr.update(visible = True), gr.update(visible = True), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True)]
|
|
|
elif generation_mode_data == "video":
|
|
|
return [gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = False)]
|
|
|
|
|
|
|
|
|
def handle_field_debug_change(input_image_debug_data, input_video_debug_data, prompt_debug_data, total_second_length_debug_data, lora_file_debug_data):
|
|
|
print("handle_field_debug_change")
|
|
|
input_image_debug_value[0] = input_image_debug_data
|
|
|
input_video_debug_value[0] = input_video_debug_data
|
|
|
prompt_debug_value[0] = prompt_debug_data
|
|
|
total_second_length_debug_value[0] = total_second_length_debug_data
|
|
|
lora_file_debug_value[0] = lora_file_debug_data
|
|
|
return []
|
|
|
|
|
|
input_image_debug.upload(
|
|
|
fn=handle_field_debug_change,
|
|
|
inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug, lora_file_debug],
|
|
|
outputs=[]
|
|
|
)
|
|
|
|
|
|
input_video_debug.upload(
|
|
|
fn=handle_field_debug_change,
|
|
|
inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug, lora_file_debug],
|
|
|
outputs=[]
|
|
|
)
|
|
|
|
|
|
prompt_debug.change(
|
|
|
fn=handle_field_debug_change,
|
|
|
inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug, lora_file_debug],
|
|
|
outputs=[]
|
|
|
)
|
|
|
|
|
|
total_second_length_debug.change(
|
|
|
fn=handle_field_debug_change,
|
|
|
inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug, lora_file_debug],
|
|
|
outputs=[]
|
|
|
)
|
|
|
|
|
|
lora_file_debug.upload(
|
|
|
fn=handle_field_debug_change,
|
|
|
inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug, lora_file_debug],
|
|
|
outputs=[]
|
|
|
)
|
|
|
|
|
|
prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])
|
|
|
timeless_prompt.change(fn=handle_timeless_prompt_change, inputs=[timeless_prompt], outputs=[final_prompt])
|
|
|
start_button.click(fn = check_parameters, inputs = [
|
|
|
generation_mode, input_image, input_video
|
|
|
], outputs = [end_button, warning], queue = False, show_progress = False).success(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning], scroll_to_output = True)
|
|
|
start_button_video.click(fn = check_parameters, inputs = [
|
|
|
generation_mode, input_image, input_video
|
|
|
], outputs = [end_button, warning], queue = False, show_progress = False).success(fn=process_video, inputs=ips_video, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button, warning], scroll_to_output = True)
|
|
|
end_button.click(fn=end_process)
|
|
|
|
|
|
generation_mode.change(fn = save_preferences, inputs = [
|
|
|
local_storage,
|
|
|
generation_mode,
|
|
|
], outputs = [
|
|
|
local_storage
|
|
|
])
|
|
|
|
|
|
generation_mode.change(
|
|
|
fn=handle_generation_mode_change,
|
|
|
inputs=[generation_mode],
|
|
|
outputs=[text_to_video_hint, image_position, input_image, input_video, start_button, start_button_video, no_resize, batch, num_clean_frames, vae_batch, prompt_hint, fps_number]
|
|
|
)
|
|
|
|
|
|
|
|
|
block.load(
|
|
|
fn=handle_generation_mode_change, inputs = [
|
|
|
generation_mode
|
|
|
], outputs = [
|
|
|
text_to_video_hint, image_position, input_image, input_video, start_button, start_button_video, no_resize, batch, num_clean_frames, vae_batch, prompt_hint, fps_number
|
|
|
]
|
|
|
)
|
|
|
|
|
|
|
|
|
block.load(
|
|
|
fn=load_preferences, inputs = [
|
|
|
local_storage
|
|
|
], outputs = [
|
|
|
generation_mode
|
|
|
]
|
|
|
)
|
|
|
|
|
|
block.launch(mcp_server=True, ssr_mode=False) |