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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers_helper.hf_login import login
|
2 |
+
|
3 |
+
import os
|
4 |
+
|
5 |
+
os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))
|
6 |
+
|
7 |
+
try:
|
8 |
+
import spaces
|
9 |
+
except:
|
10 |
+
print("Not on HuggingFace")
|
11 |
import gradio as gr
|
|
|
12 |
import torch
|
13 |
+
import traceback
|
14 |
+
import einops
|
15 |
+
import safetensors.torch as sf
|
16 |
import numpy as np
|
17 |
+
import random
|
18 |
+
import time
|
19 |
+
import math
|
20 |
+
# 20250506 pftq: Added for video input loading
|
21 |
+
import decord
|
22 |
+
# 20250506 pftq: Added for progress bars in video_encode
|
23 |
+
from tqdm import tqdm
|
24 |
+
# 20250506 pftq: Normalize file paths for Windows compatibility
|
25 |
+
import pathlib
|
26 |
+
# 20250506 pftq: for easier to read timestamp
|
27 |
+
from datetime import datetime
|
28 |
+
# 20250508 pftq: for saving prompt to mp4 comments metadata
|
29 |
+
import imageio_ffmpeg
|
30 |
+
import tempfile
|
31 |
+
import shutil
|
32 |
+
import subprocess
|
33 |
+
|
34 |
+
from PIL import Image
|
35 |
+
from diffusers import AutoencoderKLHunyuanVideo
|
36 |
+
from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
|
37 |
+
from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
|
38 |
+
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
|
39 |
+
from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
|
40 |
+
from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
|
41 |
+
if torch.cuda.device_count() > 0:
|
42 |
+
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
|
43 |
+
from diffusers_helper.thread_utils import AsyncStream, async_run
|
44 |
+
from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
|
45 |
+
from transformers import SiglipImageProcessor, SiglipVisionModel
|
46 |
+
from diffusers_helper.clip_vision import hf_clip_vision_encode
|
47 |
+
from diffusers_helper.bucket_tools import find_nearest_bucket
|
48 |
+
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline
|
49 |
+
import pillow_heif
|
50 |
+
|
51 |
+
pillow_heif.register_heif_opener()
|
52 |
+
|
53 |
+
high_vram = False
|
54 |
+
free_mem_gb = 0
|
55 |
+
|
56 |
+
if torch.cuda.device_count() > 0:
|
57 |
+
free_mem_gb = get_cuda_free_memory_gb(gpu)
|
58 |
+
high_vram = free_mem_gb > 60
|
59 |
+
|
60 |
+
print(f'Free VRAM {free_mem_gb} GB')
|
61 |
+
print(f'High-VRAM Mode: {high_vram}')
|
62 |
+
|
63 |
+
text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
|
64 |
+
text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
|
65 |
+
tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
|
66 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
|
67 |
+
vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
|
68 |
+
|
69 |
+
feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
|
70 |
+
image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
|
71 |
+
|
72 |
+
transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu()
|
73 |
+
|
74 |
+
vae.eval()
|
75 |
+
text_encoder.eval()
|
76 |
+
text_encoder_2.eval()
|
77 |
+
image_encoder.eval()
|
78 |
+
transformer.eval()
|
79 |
+
|
80 |
+
if not high_vram:
|
81 |
+
vae.enable_slicing()
|
82 |
+
vae.enable_tiling()
|
83 |
+
|
84 |
+
transformer.high_quality_fp32_output_for_inference = True
|
85 |
+
print('transformer.high_quality_fp32_output_for_inference = True')
|
86 |
+
|
87 |
+
transformer.to(dtype=torch.bfloat16)
|
88 |
+
vae.to(dtype=torch.float16)
|
89 |
+
image_encoder.to(dtype=torch.float16)
|
90 |
+
text_encoder.to(dtype=torch.float16)
|
91 |
+
text_encoder_2.to(dtype=torch.float16)
|
92 |
+
|
93 |
+
vae.requires_grad_(False)
|
94 |
+
text_encoder.requires_grad_(False)
|
95 |
+
text_encoder_2.requires_grad_(False)
|
96 |
+
image_encoder.requires_grad_(False)
|
97 |
+
transformer.requires_grad_(False)
|
98 |
+
|
99 |
+
if not high_vram:
|
100 |
+
# DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster
|
101 |
+
DynamicSwapInstaller.install_model(transformer, device=gpu)
|
102 |
+
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
103 |
+
else:
|
104 |
+
text_encoder.to(gpu)
|
105 |
+
text_encoder_2.to(gpu)
|
106 |
+
image_encoder.to(gpu)
|
107 |
+
vae.to(gpu)
|
108 |
+
transformer.to(gpu)
|
109 |
+
|
110 |
+
stream = AsyncStream()
|
111 |
+
|
112 |
+
outputs_folder = './outputs/'
|
113 |
+
os.makedirs(outputs_folder, exist_ok=True)
|
114 |
+
|
115 |
+
default_local_storage = {
|
116 |
+
"generation-mode": "image",
|
117 |
+
}
|
118 |
+
|
119 |
+
@torch.no_grad()
|
120 |
+
def video_encode(video_path, resolution, no_resize, vae, vae_batch_size=16, device="cuda", width=None, height=None):
|
121 |
+
"""
|
122 |
+
Encode a video into latent representations using the VAE.
|
123 |
+
|
124 |
+
Args:
|
125 |
+
video_path: Path to the input video file.
|
126 |
+
vae: AutoencoderKLHunyuanVideo model.
|
127 |
+
height, width: Target resolution for resizing frames.
|
128 |
+
vae_batch_size: Number of frames to process per batch.
|
129 |
+
device: Device for computation (e.g., "cuda").
|
130 |
+
|
131 |
+
Returns:
|
132 |
+
start_latent: Latent of the first frame (for compatibility with original code).
|
133 |
+
input_image_np: First frame as numpy array (for CLIP vision encoding).
|
134 |
+
history_latents: Latents of all frames (shape: [1, channels, frames, height//8, width//8]).
|
135 |
+
fps: Frames per second of the input video.
|
136 |
+
"""
|
137 |
+
# 20250506 pftq: Normalize video path for Windows compatibility
|
138 |
+
video_path = str(pathlib.Path(video_path).resolve())
|
139 |
+
print(f"Processing video: {video_path}")
|
140 |
+
|
141 |
+
# 20250506 pftq: Check CUDA availability and fallback to CPU if needed
|
142 |
+
if device == "cuda" and not torch.cuda.is_available():
|
143 |
+
print("CUDA is not available, falling back to CPU")
|
144 |
+
device = "cpu"
|
145 |
+
|
146 |
+
try:
|
147 |
+
# 20250506 pftq: Load video and get FPS
|
148 |
+
print("Initializing VideoReader...")
|
149 |
+
vr = decord.VideoReader(video_path)
|
150 |
+
fps = vr.get_avg_fps() # Get input video FPS
|
151 |
+
num_real_frames = len(vr)
|
152 |
+
print(f"Video loaded: {num_real_frames} frames, FPS: {fps}")
|
153 |
+
|
154 |
+
# Truncate to nearest latent size (multiple of 4)
|
155 |
+
latent_size_factor = 4
|
156 |
+
num_frames = (num_real_frames // latent_size_factor) * latent_size_factor
|
157 |
+
if num_frames != num_real_frames:
|
158 |
+
print(f"Truncating video from {num_real_frames} to {num_frames} frames for latent size compatibility")
|
159 |
+
num_real_frames = num_frames
|
160 |
+
|
161 |
+
# 20250506 pftq: Read frames
|
162 |
+
print("Reading video frames...")
|
163 |
+
frames = vr.get_batch(range(num_real_frames)).asnumpy() # Shape: (num_real_frames, height, width, channels)
|
164 |
+
print(f"Frames read: {frames.shape}")
|
165 |
+
|
166 |
+
# 20250506 pftq: Get native video resolution
|
167 |
+
native_height, native_width = frames.shape[1], frames.shape[2]
|
168 |
+
print(f"Native video resolution: {native_width}x{native_height}")
|
169 |
+
|
170 |
+
# 20250506 pftq: Use native resolution if height/width not specified, otherwise use provided values
|
171 |
+
target_height = native_height if height is None else height
|
172 |
+
target_width = native_width if width is None else width
|
173 |
+
|
174 |
+
# 20250506 pftq: Adjust to nearest bucket for model compatibility
|
175 |
+
if not no_resize:
|
176 |
+
target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution)
|
177 |
+
print(f"Adjusted resolution: {target_width}x{target_height}")
|
178 |
+
else:
|
179 |
+
print(f"Using native resolution without resizing: {target_width}x{target_height}")
|
180 |
+
|
181 |
+
# 20250506 pftq: Preprocess frames to match original image processing
|
182 |
+
processed_frames = []
|
183 |
+
for i, frame in enumerate(frames):
|
184 |
+
#print(f"Preprocessing frame {i+1}/{num_frames}")
|
185 |
+
frame_np = resize_and_center_crop(frame, target_width=target_width, target_height=target_height)
|
186 |
+
processed_frames.append(frame_np)
|
187 |
+
processed_frames = np.stack(processed_frames) # Shape: (num_real_frames, height, width, channels)
|
188 |
+
print(f"Frames preprocessed: {processed_frames.shape}")
|
189 |
+
|
190 |
+
# 20250506 pftq: Save first frame for CLIP vision encoding
|
191 |
+
input_image_np = processed_frames[0]
|
192 |
+
|
193 |
+
# 20250506 pftq: Convert to tensor and normalize to [-1, 1]
|
194 |
+
print("Converting frames to tensor...")
|
195 |
+
frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1
|
196 |
+
frames_pt = frames_pt.permute(0, 3, 1, 2) # Shape: (num_real_frames, channels, height, width)
|
197 |
+
frames_pt = frames_pt.unsqueeze(0) # Shape: (1, num_real_frames, channels, height, width)
|
198 |
+
frames_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)
|
199 |
+
print(f"Tensor shape: {frames_pt.shape}")
|
200 |
+
|
201 |
+
# 20250507 pftq: Save pixel frames for use in worker
|
202 |
+
input_video_pixels = frames_pt.cpu()
|
203 |
+
|
204 |
+
# 20250506 pftq: Move to device
|
205 |
+
print(f"Moving tensor to device: {device}")
|
206 |
+
frames_pt = frames_pt.to(device)
|
207 |
+
print("Tensor moved to device")
|
208 |
+
|
209 |
+
# 20250506 pftq: Move VAE to device
|
210 |
+
print(f"Moving VAE to device: {device}")
|
211 |
+
vae.to(device)
|
212 |
+
print("VAE moved to device")
|
213 |
+
|
214 |
+
# 20250506 pftq: Encode frames in batches
|
215 |
+
print(f"Encoding input video frames in VAE batch size {vae_batch_size} (reduce if memory issues here or if forcing video resolution)")
|
216 |
+
latents = []
|
217 |
+
vae.eval()
|
218 |
+
with torch.no_grad():
|
219 |
+
for i in tqdm(range(0, frames_pt.shape[2], vae_batch_size), desc="Encoding video frames", mininterval=0.1):
|
220 |
+
#print(f"Encoding batch {i//vae_batch_size + 1}: frames {i} to {min(i + vae_batch_size, frames_pt.shape[2])}")
|
221 |
+
batch = frames_pt[:, :, i:i + vae_batch_size] # Shape: (1, channels, batch_size, height, width)
|
222 |
+
try:
|
223 |
+
# 20250506 pftq: Log GPU memory before encoding
|
224 |
+
if device == "cuda":
|
225 |
+
free_mem = torch.cuda.memory_allocated() / 1024**3
|
226 |
+
#print(f"GPU memory before encoding: {free_mem:.2f} GB")
|
227 |
+
batch_latent = vae_encode(batch, vae)
|
228 |
+
# 20250506 pftq: Synchronize CUDA to catch issues
|
229 |
+
if device == "cuda":
|
230 |
+
torch.cuda.synchronize()
|
231 |
+
#print(f"GPU memory after encoding: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
232 |
+
latents.append(batch_latent)
|
233 |
+
#print(f"Batch encoded, latent shape: {batch_latent.shape}")
|
234 |
+
except RuntimeError as e:
|
235 |
+
print(f"Error during VAE encoding: {str(e)}")
|
236 |
+
if device == "cuda" and "out of memory" in str(e).lower():
|
237 |
+
print("CUDA out of memory, try reducing vae_batch_size or using CPU")
|
238 |
+
raise
|
239 |
+
|
240 |
+
# 20250506 pftq: Concatenate latents
|
241 |
+
print("Concatenating latents...")
|
242 |
+
history_latents = torch.cat(latents, dim=2) # Shape: (1, channels, frames, height//8, width//8)
|
243 |
+
print(f"History latents shape: {history_latents.shape}")
|
244 |
+
|
245 |
+
# 20250506 pftq: Get first frame's latent
|
246 |
+
start_latent = history_latents[:, :, :1] # Shape: (1, channels, 1, height//8, width//8)
|
247 |
+
print(f"Start latent shape: {start_latent.shape}")
|
248 |
+
|
249 |
+
# 20250506 pftq: Move VAE back to CPU to free GPU memory
|
250 |
+
if device == "cuda":
|
251 |
+
vae.to(cpu)
|
252 |
+
torch.cuda.empty_cache()
|
253 |
+
print("VAE moved back to CPU, CUDA cache cleared")
|
254 |
+
|
255 |
+
return start_latent, input_image_np, history_latents, fps, target_height, target_width, input_video_pixels
|
256 |
+
|
257 |
+
except Exception as e:
|
258 |
+
print(f"Error in video_encode: {str(e)}")
|
259 |
+
raise
|
260 |
+
|
261 |
+
# 20250508 pftq: for saving prompt to mp4 metadata comments
|
262 |
+
def set_mp4_comments_imageio_ffmpeg(input_file, comments):
|
263 |
+
try:
|
264 |
+
# Get the path to the bundled FFmpeg binary from imageio-ffmpeg
|
265 |
+
ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
|
266 |
+
|
267 |
+
# Check if input file exists
|
268 |
+
if not os.path.exists(input_file):
|
269 |
+
print(f"Error: Input file {input_file} does not exist")
|
270 |
+
return False
|
271 |
+
|
272 |
+
# Create a temporary file path
|
273 |
+
temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
|
274 |
+
|
275 |
+
# FFmpeg command using the bundled binary
|
276 |
+
command = [
|
277 |
+
ffmpeg_path, # Use imageio-ffmpeg's FFmpeg
|
278 |
+
'-i', input_file, # input file
|
279 |
+
'-metadata', f'comment={comments}', # set comment metadata
|
280 |
+
'-c:v', 'copy', # copy video stream without re-encoding
|
281 |
+
'-c:a', 'copy', # copy audio stream without re-encoding
|
282 |
+
'-y', # overwrite output file if it exists
|
283 |
+
temp_file # temporary output file
|
284 |
+
]
|
285 |
+
|
286 |
+
# Run the FFmpeg command
|
287 |
+
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
288 |
+
|
289 |
+
if result.returncode == 0:
|
290 |
+
# Replace the original file with the modified one
|
291 |
+
shutil.move(temp_file, input_file)
|
292 |
+
print(f"Successfully added comments to {input_file}")
|
293 |
+
return True
|
294 |
+
else:
|
295 |
+
# Clean up temp file if FFmpeg fails
|
296 |
+
if os.path.exists(temp_file):
|
297 |
+
os.remove(temp_file)
|
298 |
+
print(f"Error: FFmpeg failed with message:\n{result.stderr}")
|
299 |
+
return False
|
300 |
+
|
301 |
+
except Exception as e:
|
302 |
+
# Clean up temp file in case of other errors
|
303 |
+
if 'temp_file' in locals() and os.path.exists(temp_file):
|
304 |
+
os.remove(temp_file)
|
305 |
+
print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e))
|
306 |
+
return False
|
307 |
+
|
308 |
+
@torch.no_grad()
|
309 |
+
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):
|
310 |
+
is_last_frame = (image_position == 100)
|
311 |
+
def encode_prompt(prompt, n_prompt):
|
312 |
+
llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
313 |
+
|
314 |
+
if cfg == 1:
|
315 |
+
llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
|
316 |
+
else:
|
317 |
+
llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
318 |
+
|
319 |
+
llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
|
320 |
+
llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
|
321 |
+
|
322 |
+
llama_vec = llama_vec.to(transformer.dtype)
|
323 |
+
llama_vec_n = llama_vec_n.to(transformer.dtype)
|
324 |
+
clip_l_pooler = clip_l_pooler.to(transformer.dtype)
|
325 |
+
clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
|
326 |
+
return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
|
327 |
+
|
328 |
+
total_latent_sections = (total_second_length * 30) / (latent_window_size * 4)
|
329 |
+
total_latent_sections = int(max(round(total_latent_sections), 1))
|
330 |
+
|
331 |
+
job_id = generate_timestamp()
|
332 |
+
|
333 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
|
334 |
+
|
335 |
+
try:
|
336 |
+
# Clean GPU
|
337 |
+
if not high_vram:
|
338 |
+
unload_complete_models(
|
339 |
+
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
340 |
+
)
|
341 |
+
|
342 |
+
# Text encoding
|
343 |
+
|
344 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
|
345 |
+
|
346 |
+
if not high_vram:
|
347 |
+
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.
|
348 |
+
load_model_as_complete(text_encoder_2, target_device=gpu)
|
349 |
+
|
350 |
+
prompt_parameters = []
|
351 |
+
|
352 |
+
for prompt_part in prompts:
|
353 |
+
prompt_parameters.append(encode_prompt(prompt_part, n_prompt))
|
354 |
+
|
355 |
+
# Processing input image
|
356 |
+
|
357 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))
|
358 |
+
|
359 |
+
H, W, C = input_image.shape
|
360 |
+
height, width = find_nearest_bucket(H, W, resolution=resolution)
|
361 |
+
|
362 |
+
def get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram):
|
363 |
+
input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)
|
364 |
+
|
365 |
+
#Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
|
366 |
+
|
367 |
+
input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1
|
368 |
+
input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]
|
369 |
+
|
370 |
+
# VAE encoding
|
371 |
+
|
372 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))
|
373 |
+
|
374 |
+
if not high_vram:
|
375 |
+
load_model_as_complete(vae, target_device=gpu)
|
376 |
+
|
377 |
+
start_latent = vae_encode(input_image_pt, vae)
|
378 |
+
|
379 |
+
# CLIP Vision
|
380 |
+
|
381 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
|
382 |
+
|
383 |
+
if not high_vram:
|
384 |
+
load_model_as_complete(image_encoder, target_device=gpu)
|
385 |
+
|
386 |
+
image_encoder_last_hidden_state = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder).last_hidden_state
|
387 |
+
|
388 |
+
return [start_latent, image_encoder_last_hidden_state]
|
389 |
+
|
390 |
+
[start_latent, image_encoder_last_hidden_state] = get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram)
|
391 |
+
|
392 |
+
# Dtype
|
393 |
+
|
394 |
+
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
|
395 |
+
|
396 |
+
# Sampling
|
397 |
+
|
398 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
|
399 |
+
|
400 |
+
rnd = torch.Generator("cpu").manual_seed(seed)
|
401 |
+
|
402 |
+
history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()
|
403 |
+
start_latent = start_latent.to(history_latents)
|
404 |
+
history_pixels = None
|
405 |
+
|
406 |
+
history_latents = torch.cat([start_latent, history_latents] if is_last_frame else [history_latents, start_latent], dim=2)
|
407 |
+
total_generated_latent_frames = 1
|
408 |
+
|
409 |
+
if enable_preview:
|
410 |
+
def callback(d):
|
411 |
+
preview = d['denoised']
|
412 |
+
preview = vae_decode_fake(preview)
|
413 |
+
|
414 |
+
preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
|
415 |
+
preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
|
416 |
+
|
417 |
+
if stream.input_queue.top() == 'end':
|
418 |
+
stream.output_queue.push(('end', None))
|
419 |
+
raise KeyboardInterrupt('User ends the task.')
|
420 |
+
|
421 |
+
current_step = d['i'] + 1
|
422 |
+
percentage = int(100.0 * current_step / steps)
|
423 |
+
hint = f'Sampling {current_step}/{steps}'
|
424 |
+
desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / 30) :.2f} seconds (FPS-30), Resolution: {height}px * {width}px. The video is being extended now ...'
|
425 |
+
stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
|
426 |
+
return
|
427 |
+
else:
|
428 |
+
def callback(d):
|
429 |
+
return
|
430 |
+
|
431 |
+
indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0)
|
432 |
+
if is_last_frame:
|
433 |
+
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)
|
434 |
+
clean_latent_indices = torch.cat([clean_latent_1x_indices, clean_latent_indices_start], dim=1)
|
435 |
+
else:
|
436 |
+
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)
|
437 |
+
clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
|
438 |
+
|
439 |
+
def post_process(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):
|
440 |
+
total_generated_latent_frames += int(generated_latents.shape[2])
|
441 |
+
history_latents = torch.cat([generated_latents.to(history_latents), history_latents], dim=2) if is_last_frame else torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
|
442 |
+
|
443 |
+
if not high_vram:
|
444 |
+
offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
|
445 |
+
load_model_as_complete(vae, target_device=gpu)
|
446 |
+
|
447 |
+
if history_pixels is None:
|
448 |
+
real_history_latents = history_latents[:, :, :total_generated_latent_frames, :, :] if is_last_frame else history_latents[:, :, -total_generated_latent_frames:, :, :]
|
449 |
+
history_pixels = vae_decode(real_history_latents, vae).cpu()
|
450 |
+
else:
|
451 |
+
section_latent_frames = latent_window_size * 2
|
452 |
+
overlapped_frames = latent_window_size * 4 - 3
|
453 |
+
|
454 |
+
if is_last_frame:
|
455 |
+
real_history_latents = history_latents[:, :, :min(section_latent_frames, total_generated_latent_frames), :, :]
|
456 |
+
history_pixels = soft_append_bcthw(vae_decode(real_history_latents, vae).cpu(), history_pixels, overlapped_frames)
|
457 |
+
else:
|
458 |
+
real_history_latents = history_latents[:, :, -min(section_latent_frames, total_generated_latent_frames):, :, :]
|
459 |
+
history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames)
|
460 |
+
|
461 |
+
if not high_vram:
|
462 |
+
unload_complete_models()
|
463 |
+
|
464 |
+
if enable_preview or section_index == (0 if is_last_frame else (total_latent_sections - 1)):
|
465 |
+
output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
|
466 |
+
|
467 |
+
save_bcthw_as_mp4(history_pixels, output_filename, fps=30, crf=mp4_crf)
|
468 |
+
|
469 |
+
print(f'Decoded. Current latent shape pixel shape {history_pixels.shape}')
|
470 |
+
|
471 |
+
stream.output_queue.push(('file', output_filename))
|
472 |
+
return [total_generated_latent_frames, history_latents, history_pixels]
|
473 |
+
|
474 |
+
for section_index in range(total_latent_sections - 1, -1, -1) if is_last_frame else range(total_latent_sections):
|
475 |
+
if stream.input_queue.top() == 'end':
|
476 |
+
stream.output_queue.push(('end', None))
|
477 |
+
return
|
478 |
+
|
479 |
+
print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
|
480 |
+
|
481 |
+
if len(prompt_parameters) > 0:
|
482 |
+
[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) if is_last_frame else 0)
|
483 |
+
|
484 |
+
if not high_vram:
|
485 |
+
unload_complete_models()
|
486 |
+
move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
|
487 |
+
|
488 |
+
if use_teacache:
|
489 |
+
transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
|
490 |
+
else:
|
491 |
+
transformer.initialize_teacache(enable_teacache=False)
|
492 |
+
|
493 |
+
if is_last_frame:
|
494 |
+
clean_latents_1x, clean_latents_2x, clean_latents_4x = history_latents[:, :, :sum([1, 2, 16]), :, :].split([1, 2, 16], dim=2)
|
495 |
+
clean_latents = torch.cat([clean_latents_1x, start_latent], dim=2)
|
496 |
+
else:
|
497 |
+
clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -sum([16, 2, 1]):, :, :].split([16, 2, 1], dim=2)
|
498 |
+
clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
|
499 |
+
|
500 |
+
generated_latents = sample_hunyuan(
|
501 |
+
transformer=transformer,
|
502 |
+
sampler='unipc',
|
503 |
+
width=width,
|
504 |
+
height=height,
|
505 |
+
frames=latent_window_size * 4 - 3,
|
506 |
+
real_guidance_scale=cfg,
|
507 |
+
distilled_guidance_scale=gs,
|
508 |
+
guidance_rescale=rs,
|
509 |
+
# shift=3.0,
|
510 |
+
num_inference_steps=steps,
|
511 |
+
generator=rnd,
|
512 |
+
prompt_embeds=llama_vec,
|
513 |
+
prompt_embeds_mask=llama_attention_mask,
|
514 |
+
prompt_poolers=clip_l_pooler,
|
515 |
+
negative_prompt_embeds=llama_vec_n,
|
516 |
+
negative_prompt_embeds_mask=llama_attention_mask_n,
|
517 |
+
negative_prompt_poolers=clip_l_pooler_n,
|
518 |
+
device=gpu,
|
519 |
+
dtype=torch.bfloat16,
|
520 |
+
image_embeddings=image_encoder_last_hidden_state,
|
521 |
+
latent_indices=latent_indices,
|
522 |
+
clean_latents=clean_latents,
|
523 |
+
clean_latent_indices=clean_latent_indices,
|
524 |
+
clean_latents_2x=clean_latents_2x,
|
525 |
+
clean_latent_2x_indices=clean_latent_2x_indices,
|
526 |
+
clean_latents_4x=clean_latents_4x,
|
527 |
+
clean_latent_4x_indices=clean_latent_4x_indices,
|
528 |
+
callback=callback,
|
529 |
+
)
|
530 |
+
|
531 |
+
[total_generated_latent_frames, history_latents, history_pixels] = post_process(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)
|
532 |
+
except:
|
533 |
+
traceback.print_exc()
|
534 |
+
|
535 |
+
if not high_vram:
|
536 |
+
unload_complete_models(
|
537 |
+
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
538 |
+
)
|
539 |
+
|
540 |
+
stream.output_queue.push(('end', None))
|
541 |
+
return
|
542 |
+
|
543 |
+
# 20250506 pftq: Modified worker to accept video input and clean frame count
|
544 |
+
@torch.no_grad()
|
545 |
+
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):
|
546 |
+
def encode_prompt(prompt, n_prompt):
|
547 |
+
llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
548 |
+
|
549 |
+
if cfg == 1:
|
550 |
+
llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
|
551 |
+
else:
|
552 |
+
llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
553 |
+
|
554 |
+
llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
|
555 |
+
llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
|
556 |
+
|
557 |
+
llama_vec = llama_vec.to(transformer.dtype)
|
558 |
+
llama_vec_n = llama_vec_n.to(transformer.dtype)
|
559 |
+
clip_l_pooler = clip_l_pooler.to(transformer.dtype)
|
560 |
+
clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
|
561 |
+
return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
|
562 |
+
|
563 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
|
564 |
+
|
565 |
+
try:
|
566 |
+
# Clean GPU
|
567 |
+
if not high_vram:
|
568 |
+
unload_complete_models(
|
569 |
+
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
570 |
+
)
|
571 |
+
|
572 |
+
# Text encoding
|
573 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
|
574 |
+
|
575 |
+
if not high_vram:
|
576 |
+
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.
|
577 |
+
load_model_as_complete(text_encoder_2, target_device=gpu)
|
578 |
+
|
579 |
+
prompt_parameters = []
|
580 |
+
|
581 |
+
for prompt_part in prompts:
|
582 |
+
prompt_parameters.append(encode_prompt(prompt_part, n_prompt))
|
583 |
+
|
584 |
+
# 20250506 pftq: Processing input video instead of image
|
585 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
|
586 |
+
|
587 |
+
# 20250506 pftq: Encode video
|
588 |
+
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)[:6]
|
589 |
+
start_latent = start_latent.to(dtype=torch.float32).cpu()
|
590 |
+
video_latents = video_latents.cpu()
|
591 |
|
592 |
+
# CLIP Vision
|
593 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
|
594 |
+
|
595 |
+
if not high_vram:
|
596 |
+
load_model_as_complete(image_encoder, target_device=gpu)
|
597 |
+
|
598 |
+
image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
|
599 |
+
image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
|
600 |
+
|
601 |
+
# Dtype
|
602 |
+
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
|
603 |
+
|
604 |
+
total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
|
605 |
+
total_latent_sections = int(max(round(total_latent_sections), 1))
|
606 |
+
|
607 |
+
if enable_preview:
|
608 |
+
def callback(d):
|
609 |
+
preview = d['denoised']
|
610 |
+
preview = vae_decode_fake(preview)
|
611 |
+
|
612 |
+
preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
|
613 |
+
preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
|
614 |
+
|
615 |
+
if stream.input_queue.top() == 'end':
|
616 |
+
stream.output_queue.push(('end', None))
|
617 |
+
raise KeyboardInterrupt('User ends the task.')
|
618 |
+
|
619 |
+
current_step = d['i'] + 1
|
620 |
+
percentage = int(100.0 * current_step / steps)
|
621 |
+
hint = f'Sampling {current_step}/{steps}'
|
622 |
+
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}...'
|
623 |
+
stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
|
624 |
+
return
|
625 |
+
else:
|
626 |
+
def callback(d):
|
627 |
+
return
|
628 |
+
|
629 |
+
def compute_latent(history_latents, latent_window_size, num_clean_frames, start_latent):
|
630 |
+
# 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2
|
631 |
+
available_frames = history_latents.shape[2] # Number of latent frames
|
632 |
+
max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames
|
633 |
+
adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames
|
634 |
+
# Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x
|
635 |
+
effective_clean_frames = max(0, num_clean_frames - 1)
|
636 |
+
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
|
637 |
+
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
|
638 |
+
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
|
639 |
+
|
640 |
+
total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
|
641 |
+
total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos
|
642 |
+
|
643 |
+
indices = torch.arange(0, sum([1, num_4x_frames, num_2x_frames, effective_clean_frames, adjusted_latent_frames])).unsqueeze(0) # 20250507 pftq: latent_window_size to adjusted_latent_frames for edge case for <=1 sec videos
|
644 |
+
clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
|
645 |
+
[1, num_4x_frames, num_2x_frames, effective_clean_frames, adjusted_latent_frames], dim=1 # 20250507 pftq: latent_window_size to adjusted_latent_frames for edge case for <=1 sec videos
|
646 |
+
)
|
647 |
+
clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
|
648 |
+
|
649 |
+
# 20250506 pftq: Split history_latents dynamically based on available frames
|
650 |
+
fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos
|
651 |
+
context_frames = clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
|
652 |
+
|
653 |
+
if total_context_frames > 0:
|
654 |
+
context_frames = history_latents[:, :, -total_context_frames:, :, :]
|
655 |
+
split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames]
|
656 |
+
split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes
|
657 |
+
if split_sizes:
|
658 |
+
splits = context_frames.split(split_sizes, dim=2)
|
659 |
+
split_idx = 0
|
660 |
+
|
661 |
+
if num_4x_frames > 0:
|
662 |
+
clean_latents_4x = splits[split_idx]
|
663 |
+
split_idx = 1
|
664 |
+
if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
|
665 |
+
print("Edge case for <=1 sec videos 4x")
|
666 |
+
clean_latents_4x = clean_latents_4x.expand(-1, -1, 2, -1, -1)
|
667 |
+
|
668 |
+
if num_2x_frames > 0 and split_idx < len(splits):
|
669 |
+
clean_latents_2x = splits[split_idx]
|
670 |
+
if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
|
671 |
+
print("Edge case for <=1 sec videos 2x")
|
672 |
+
clean_latents_2x = clean_latents_2x.expand(-1, -1, 2, -1, -1)
|
673 |
+
split_idx += 1
|
674 |
+
elif clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
|
675 |
+
clean_latents_2x = clean_latents_4x
|
676 |
+
|
677 |
+
if effective_clean_frames > 0 and split_idx < len(splits):
|
678 |
+
clean_latents_1x = splits[split_idx]
|
679 |
+
|
680 |
+
clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
|
681 |
+
|
682 |
+
# 20250507 pftq: Fix for <=1 sec videos.
|
683 |
+
max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
|
684 |
+
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]
|
685 |
+
|
686 |
+
for idx in range(batch):
|
687 |
+
if batch > 1:
|
688 |
+
print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
|
689 |
+
|
690 |
+
#job_id = generate_timestamp()
|
691 |
+
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
|
692 |
+
|
693 |
+
# Sampling
|
694 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
|
695 |
+
|
696 |
+
rnd = torch.Generator("cpu").manual_seed(seed)
|
697 |
+
|
698 |
+
# 20250506 pftq: Initialize history_latents with video latents
|
699 |
+
history_latents = video_latents
|
700 |
+
total_generated_latent_frames = history_latents.shape[2]
|
701 |
+
# 20250506 pftq: Initialize history_pixels to fix UnboundLocalError
|
702 |
+
history_pixels = None
|
703 |
+
previous_video = None
|
704 |
+
|
705 |
+
for section_index in range(total_latent_sections):
|
706 |
+
if stream.input_queue.top() == 'end':
|
707 |
+
stream.output_queue.push(('end', None))
|
708 |
+
return
|
709 |
+
|
710 |
+
print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
|
711 |
+
|
712 |
+
if len(prompt_parameters) > 0:
|
713 |
+
[llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters.pop(0)
|
714 |
+
|
715 |
+
if not high_vram:
|
716 |
+
unload_complete_models()
|
717 |
+
move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
|
718 |
+
|
719 |
+
if use_teacache:
|
720 |
+
transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
|
721 |
+
else:
|
722 |
+
transformer.initialize_teacache(enable_teacache=False)
|
723 |
+
|
724 |
+
[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)
|
725 |
+
|
726 |
+
generated_latents = sample_hunyuan(
|
727 |
+
transformer=transformer,
|
728 |
+
sampler='unipc',
|
729 |
+
width=width,
|
730 |
+
height=height,
|
731 |
+
frames=max_frames,
|
732 |
+
real_guidance_scale=cfg,
|
733 |
+
distilled_guidance_scale=gs,
|
734 |
+
guidance_rescale=rs,
|
735 |
+
num_inference_steps=steps,
|
736 |
+
generator=rnd,
|
737 |
+
prompt_embeds=llama_vec,
|
738 |
+
prompt_embeds_mask=llama_attention_mask,
|
739 |
+
prompt_poolers=clip_l_pooler,
|
740 |
+
negative_prompt_embeds=llama_vec_n,
|
741 |
+
negative_prompt_embeds_mask=llama_attention_mask_n,
|
742 |
+
negative_prompt_poolers=clip_l_pooler_n,
|
743 |
+
device=gpu,
|
744 |
+
dtype=torch.bfloat16,
|
745 |
+
image_embeddings=image_encoder_last_hidden_state,
|
746 |
+
latent_indices=latent_indices,
|
747 |
+
clean_latents=clean_latents,
|
748 |
+
clean_latent_indices=clean_latent_indices,
|
749 |
+
clean_latents_2x=clean_latents_2x,
|
750 |
+
clean_latent_2x_indices=clean_latent_2x_indices,
|
751 |
+
clean_latents_4x=clean_latents_4x,
|
752 |
+
clean_latent_4x_indices=clean_latent_4x_indices,
|
753 |
+
callback=callback,
|
754 |
+
)
|
755 |
+
|
756 |
+
total_generated_latent_frames += int(generated_latents.shape[2])
|
757 |
+
history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
|
758 |
+
|
759 |
+
if not high_vram:
|
760 |
+
offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
|
761 |
+
load_model_as_complete(vae, target_device=gpu)
|
762 |
+
|
763 |
+
if history_pixels is None:
|
764 |
+
real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
|
765 |
+
history_pixels = vae_decode(real_history_latents, vae).cpu()
|
766 |
+
else:
|
767 |
+
section_latent_frames = latent_window_size * 2
|
768 |
+
overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2])
|
769 |
+
|
770 |
+
real_history_latents = history_latents[:, :, -min(total_generated_latent_frames, section_latent_frames):, :, :]
|
771 |
+
history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames)
|
772 |
+
|
773 |
+
if not high_vram:
|
774 |
+
unload_complete_models()
|
775 |
+
|
776 |
+
if enable_preview or section_index == total_latent_sections - 1:
|
777 |
+
output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
|
778 |
+
|
779 |
+
# 20250506 pftq: Use input video FPS for output
|
780 |
+
save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
|
781 |
+
print(f"Latest video saved: {output_filename}")
|
782 |
+
# 20250508 pftq: Save prompt to mp4 metadata comments
|
783 |
+
set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompts} | Negative Prompt: {n_prompt}");
|
784 |
+
print(f"Prompt saved to mp4 metadata comments: {output_filename}")
|
785 |
+
|
786 |
+
# 20250506 pftq: Clean up previous partial files
|
787 |
+
if previous_video is not None and os.path.exists(previous_video):
|
788 |
+
try:
|
789 |
+
os.remove(previous_video)
|
790 |
+
print(f"Previous partial video deleted: {previous_video}")
|
791 |
+
except Exception as e:
|
792 |
+
print(f"Error deleting previous partial video {previous_video}: {e}")
|
793 |
+
previous_video = output_filename
|
794 |
+
|
795 |
+
print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
|
796 |
+
|
797 |
+
stream.output_queue.push(('file', output_filename))
|
798 |
+
|
799 |
+
seed = (seed + 1) % np.iinfo(np.int32).max
|
800 |
+
|
801 |
+
except:
|
802 |
+
traceback.print_exc()
|
803 |
+
|
804 |
+
if not high_vram:
|
805 |
+
unload_complete_models(
|
806 |
+
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
807 |
+
)
|
808 |
+
|
809 |
+
stream.output_queue.push(('end', None))
|
810 |
+
return
|
811 |
+
|
812 |
+
def get_duration(input_image, image_position, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf):
|
813 |
+
return total_second_length * 60 * (0.9 if use_teacache else 1.5) * (1 + ((steps - 25) / 100))
|
814 |
+
|
815 |
+
# Remove this decorator if you run on local
|
816 |
+
@spaces.GPU(duration=get_duration)
|
817 |
+
def process_on_gpu(input_image,
|
818 |
+
image_position=0,
|
819 |
+
prompts=[""],
|
820 |
+
generation_mode="image",
|
821 |
+
n_prompt="",
|
822 |
+
seed=31337,
|
823 |
+
resolution=640,
|
824 |
+
total_second_length=5,
|
825 |
+
latent_window_size=9,
|
826 |
+
steps=25,
|
827 |
+
cfg=1.0,
|
828 |
+
gs=10.0,
|
829 |
+
rs=0.0,
|
830 |
+
gpu_memory_preservation=6,
|
831 |
+
enable_preview=True,
|
832 |
+
use_teacache=False,
|
833 |
+
mp4_crf=16
|
834 |
+
):
|
835 |
+
start = time.time()
|
836 |
+
global stream
|
837 |
+
stream = AsyncStream()
|
838 |
+
|
839 |
+
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)
|
840 |
+
|
841 |
+
output_filename = None
|
842 |
+
|
843 |
+
while True:
|
844 |
+
flag, data = stream.output_queue.next()
|
845 |
+
|
846 |
+
if flag == 'file':
|
847 |
+
output_filename = data
|
848 |
+
yield gr.update(value=output_filename, label="Previewed Frames"), gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True), gr.update()
|
849 |
+
|
850 |
+
if flag == 'progress':
|
851 |
+
preview, desc, html = data
|
852 |
+
yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.update()
|
853 |
+
|
854 |
+
if flag == 'end':
|
855 |
+
end = time.time()
|
856 |
+
secondes = int(end - start)
|
857 |
+
minutes = math.floor(secondes / 60)
|
858 |
+
secondes = secondes - (minutes * 60)
|
859 |
+
hours = math.floor(minutes / 60)
|
860 |
+
minutes = minutes - (hours * 60)
|
861 |
+
yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), gr.update(), "The process has lasted " + \
|
862 |
+
((str(hours) + " h, ") if hours != 0 else "") + \
|
863 |
+
((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
|
864 |
+
str(secondes) + " sec. " + \
|
865 |
+
"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)
|
866 |
+
break
|
867 |
+
|
868 |
+
def process(input_image,
|
869 |
+
image_position=0,
|
870 |
+
prompt="",
|
871 |
+
generation_mode="image",
|
872 |
+
n_prompt="",
|
873 |
+
randomize_seed=True,
|
874 |
+
seed=31337,
|
875 |
+
resolution=640,
|
876 |
+
total_second_length=5,
|
877 |
+
latent_window_size=9,
|
878 |
+
steps=25,
|
879 |
+
cfg=1.0,
|
880 |
+
gs=10.0,
|
881 |
+
rs=0.0,
|
882 |
+
gpu_memory_preservation=6,
|
883 |
+
enable_preview=True,
|
884 |
+
use_teacache=False,
|
885 |
+
mp4_crf=16
|
886 |
+
):
|
887 |
+
|
888 |
+
if torch.cuda.device_count() == 0:
|
889 |
+
gr.Warning('Set this space to GPU config to make it work.')
|
890 |
+
yield gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(visible = False)
|
891 |
+
return
|
892 |
+
|
893 |
+
if randomize_seed:
|
894 |
+
seed = random.randint(0, np.iinfo(np.int32).max)
|
895 |
+
|
896 |
+
prompts = prompt.split(";")
|
897 |
+
|
898 |
+
# assert input_image is not None, 'No input image!'
|
899 |
+
if generation_mode == "text":
|
900 |
+
default_height, default_width = 640, 640
|
901 |
+
input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
|
902 |
+
print("No input image provided. Using a blank white image.")
|
903 |
+
|
904 |
+
yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.update()
|
905 |
+
|
906 |
+
yield from process_on_gpu(input_image,
|
907 |
+
image_position,
|
908 |
+
prompts,
|
909 |
+
generation_mode,
|
910 |
+
n_prompt,
|
911 |
+
seed,
|
912 |
+
resolution,
|
913 |
+
total_second_length,
|
914 |
+
latent_window_size,
|
915 |
+
steps,
|
916 |
+
cfg,
|
917 |
+
gs,
|
918 |
+
rs,
|
919 |
+
gpu_memory_preservation,
|
920 |
+
enable_preview,
|
921 |
+
use_teacache,
|
922 |
+
mp4_crf
|
923 |
+
)
|
924 |
+
|
925 |
+
def get_duration_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):
|
926 |
+
return total_second_length * 60 * (1.5 if use_teacache else 2.5) * (1 + ((steps - 25) / 100))
|
927 |
+
|
928 |
+
# Remove this decorator if you run on local
|
929 |
+
@spaces.GPU(duration=get_duration_video)
|
930 |
+
def process_video_on_gpu(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):
|
931 |
+
start = time.time()
|
932 |
+
global stream
|
933 |
+
stream = AsyncStream()
|
934 |
+
|
935 |
+
# 20250506 pftq: Pass num_clean_frames, vae_batch, etc
|
936 |
+
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)
|
937 |
+
|
938 |
+
output_filename = None
|
939 |
+
|
940 |
+
while True:
|
941 |
+
flag, data = stream.output_queue.next()
|
942 |
+
|
943 |
+
if flag == 'file':
|
944 |
+
output_filename = data
|
945 |
+
yield gr.update(value=output_filename, label="Previewed Frames"), gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True), gr.update()
|
946 |
+
|
947 |
+
if flag == 'progress':
|
948 |
+
preview, desc, html = data
|
949 |
+
yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.update() # 20250506 pftq: Keep refreshing the video in case it got hidden when the tab was in the background
|
950 |
+
|
951 |
+
if flag == 'end':
|
952 |
+
end = time.time()
|
953 |
+
secondes = int(end - start)
|
954 |
+
minutes = math.floor(secondes / 60)
|
955 |
+
secondes = secondes - (minutes * 60)
|
956 |
+
hours = math.floor(minutes / 60)
|
957 |
+
minutes = minutes - (hours * 60)
|
958 |
+
yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), desc + \
|
959 |
+
" The process has lasted " + \
|
960 |
+
((str(hours) + " h, ") if hours != 0 else "") + \
|
961 |
+
((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
|
962 |
+
str(secondes) + " sec. " + \
|
963 |
+
" 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)
|
964 |
+
break
|
965 |
+
|
966 |
+
def process_video(input_video, prompt, n_prompt, randomize_seed, 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):
|
967 |
+
global high_vram
|
968 |
+
|
969 |
+
if torch.cuda.device_count() == 0:
|
970 |
+
gr.Warning('Set this space to GPU config to make it work.')
|
971 |
+
yield gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(visible = False)
|
972 |
+
return
|
973 |
+
|
974 |
+
if randomize_seed:
|
975 |
+
seed = random.randint(0, np.iinfo(np.int32).max)
|
976 |
+
|
977 |
+
prompts = prompt.split(";")
|
978 |
+
|
979 |
+
# 20250506 pftq: Updated assertion for video input
|
980 |
+
assert input_video is not None, 'No input video!'
|
981 |
+
|
982 |
+
yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.update()
|
983 |
+
|
984 |
+
# 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
|
985 |
+
if high_vram and (no_resize or resolution>640):
|
986 |
+
print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
|
987 |
+
high_vram = False
|
988 |
+
vae.enable_slicing()
|
989 |
+
vae.enable_tiling()
|
990 |
+
DynamicSwapInstaller.install_model(transformer, device=gpu)
|
991 |
+
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
992 |
+
|
993 |
+
# 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
|
994 |
+
if cfg > 1:
|
995 |
+
gs = 1
|
996 |
+
|
997 |
+
yield from process_video_on_gpu(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)
|
998 |
+
|
999 |
+
def end_process():
|
1000 |
+
stream.input_queue.push('end')
|
1001 |
+
|
1002 |
+
timeless_prompt_value = [""]
|
1003 |
+
timed_prompts = {}
|
1004 |
+
|
1005 |
+
def handle_prompt_number_change():
|
1006 |
+
timed_prompts.clear()
|
1007 |
+
return []
|
1008 |
+
|
1009 |
+
def handle_timeless_prompt_change(timeless_prompt):
|
1010 |
+
timeless_prompt_value[0] = timeless_prompt
|
1011 |
+
return refresh_prompt()
|
1012 |
+
|
1013 |
+
def handle_timed_prompt_change(timed_prompt_id, timed_prompt):
|
1014 |
+
timed_prompts[timed_prompt_id] = timed_prompt
|
1015 |
+
return refresh_prompt()
|
1016 |
+
|
1017 |
+
def refresh_prompt():
|
1018 |
+
dict_values = {k: v for k, v in timed_prompts.items()}
|
1019 |
+
sorted_dict_values = sorted(dict_values.items(), key=lambda x: x[0])
|
1020 |
+
array = []
|
1021 |
+
for sorted_dict_value in sorted_dict_values:
|
1022 |
+
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]):
|
1023 |
+
array.append(timeless_prompt_value[0] + ". " + sorted_dict_value[1])
|
1024 |
+
else:
|
1025 |
+
array.append(timeless_prompt_value[0] + sorted_dict_value[1])
|
1026 |
+
print(str(array))
|
1027 |
+
return ";".join(array)
|
1028 |
+
|
1029 |
+
title_html = """
|
1030 |
+
<h1><center>FramePack</center></h1>
|
1031 |
+
<big><center>Generate videos from text/image/video freely, without account, without watermark and download it</center></big>
|
1032 |
+
<br/>
|
1033 |
+
|
1034 |
+
<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>
|
1035 |
+
"""
|
1036 |
+
|
1037 |
+
js = """
|
1038 |
+
function createGradioAnimation() {
|
1039 |
+
window.addEventListener("beforeunload", function (e) {
|
1040 |
+
if (document.getElementById('end-button') && !document.getElementById('end-button').disabled) {
|
1041 |
+
var confirmationMessage = 'A process is still running. '
|
1042 |
+
+ 'If you leave before saving, your changes will be lost.';
|
1043 |
+
|
1044 |
+
(e || window.event).returnValue = confirmationMessage;
|
1045 |
+
}
|
1046 |
+
return confirmationMessage;
|
1047 |
+
});
|
1048 |
+
return 'Animation created';
|
1049 |
+
}
|
1050 |
"""
|
1051 |
+
|
1052 |
+
css = make_progress_bar_css()
|
1053 |
+
block = gr.Blocks(css=css, js=js).queue()
|
1054 |
+
with block:
|
1055 |
+
if torch.cuda.device_count() == 0:
|
1056 |
+
with gr.Row():
|
1057 |
+
gr.HTML("""
|
1058 |
+
<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>
|
1059 |
+
|
1060 |
+
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.
|
1061 |
+
</big></big></big></p>
|
1062 |
+
""")
|
1063 |
+
gr.HTML(title_html)
|
1064 |
+
local_storage = gr.BrowserState(default_local_storage)
|
1065 |
+
with gr.Row():
|
1066 |
+
with gr.Column():
|
1067 |
+
generation_mode = gr.Radio([["Text-to-Video", "text"], ["Image-to-Video", "image"], ["Video Extension", "video"]], elem_id="generation-mode", label="Generation mode", value = "image")
|
1068 |
+
text_to_video_hint = gr.HTML("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.")
|
1069 |
+
input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)
|
1070 |
+
image_position = gr.Slider(label="Image position", minimum=0, maximum=100, value=0, step=100, info='0=Video start; 100=Video end (lower quality)')
|
1071 |
+
input_video = gr.Video(sources='upload', label="Input Video", height=320)
|
1072 |
+
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")
|
1073 |
+
prompt_number = gr.Slider(label="Timed prompt number", minimum=0, maximum=1000, value=0, step=1, info='Prompts will automatically appear')
|
1074 |
+
|
1075 |
+
@gr.render(inputs=prompt_number)
|
1076 |
+
def show_split(prompt_number):
|
1077 |
+
for digit in range(prompt_number):
|
1078 |
+
timed_prompt_id = gr.Textbox(value="timed_prompt_" + str(digit), visible=False)
|
1079 |
+
timed_prompt = gr.Textbox(label="Timed prompt #" + str(digit + 1), elem_id="timed_prompt_" + str(digit), value="")
|
1080 |
+
timed_prompt.change(fn=handle_timed_prompt_change, inputs=[timed_prompt_id, timed_prompt], outputs=[final_prompt])
|
1081 |
+
|
1082 |
+
final_prompt = gr.Textbox(label="Final prompt", value='', info='Use ; to separate in time; beware to write to stop the previous action')
|
1083 |
+
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.")
|
1084 |
+
total_second_length = gr.Slider(label="Video Length to Generate (seconds)", minimum=1, maximum=120, value=2, step=0.1)
|
1085 |
+
|
1086 |
+
with gr.Row():
|
1087 |
+
start_button = gr.Button(value="🎥 Generate", variant="primary")
|
1088 |
+
start_button_video = gr.Button(value="🎥 Generate", variant="primary")
|
1089 |
+
end_button = gr.Button(elem_id="end-button", value="End Generation", variant="stop", interactive=False)
|
1090 |
+
|
1091 |
+
with gr.Accordion("Advanced settings", open=False):
|
1092 |
+
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.')
|
1093 |
+
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.')
|
1094 |
+
|
1095 |
+
n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')
|
1096 |
+
|
1097 |
+
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.')
|
1098 |
+
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.')
|
1099 |
+
|
1100 |
+
with gr.Row():
|
1101 |
+
no_resize = gr.Checkbox(label='Force Original Video Resolution (no Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
|
1102 |
+
resolution = gr.Dropdown([
|
1103 |
+
["409,600 px (working)", 640],
|
1104 |
+
["451,584 px (working)", 672],
|
1105 |
+
["495,616 px (VRAM pb on HF)", 704],
|
1106 |
+
["589,824 px (not tested)", 768],
|
1107 |
+
["692,224 px (not tested)", 832],
|
1108 |
+
["746,496 px (not tested)", 864],
|
1109 |
+
["921,600 px (not tested)", 960]
|
1110 |
+
], value=672, label="Resolution (width x height)", info="Do not affect the generation time")
|
1111 |
+
|
1112 |
+
# 20250506 pftq: Reduced default distilled guidance scale to improve adherence to input video
|
1113 |
+
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.')
|
1114 |
+
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')
|
1115 |
+
rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, info='Should not change')
|
1116 |
+
|
1117 |
+
|
1118 |
+
# 20250506 pftq: Renamed slider to Number of Context Frames and updated description
|
1119 |
+
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.")
|
1120 |
+
|
1121 |
+
default_vae = 32
|
1122 |
+
if high_vram:
|
1123 |
+
default_vae = 128
|
1124 |
+
elif free_mem_gb>=20:
|
1125 |
+
default_vae = 64
|
1126 |
+
|
1127 |
+
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.")
|
1128 |
+
|
1129 |
+
|
1130 |
+
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.")
|
1131 |
+
|
1132 |
+
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. ")
|
1133 |
+
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.')
|
1134 |
+
with gr.Row():
|
1135 |
+
randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
|
1136 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
|
1137 |
+
|
1138 |
+
with gr.Column():
|
1139 |
+
warning = gr.HTML(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)
|
1140 |
+
result_video = gr.Video(label="Generated Frames", autoplay=True, show_share_button=False, height=512, loop=True)
|
1141 |
+
preview_image = gr.Image(label="Next Latents", height=200, visible=False)
|
1142 |
+
progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
|
1143 |
+
progress_bar = gr.HTML('', elem_classes='no-generating-animation')
|
1144 |
+
|
1145 |
+
# 20250506 pftq: Updated inputs to include num_clean_frames
|
1146 |
+
ips = [input_image, image_position, final_prompt, generation_mode, n_prompt, randomize_seed, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf]
|
1147 |
+
ips_video = [input_video, final_prompt, n_prompt, randomize_seed, 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]
|
1148 |
+
|
1149 |
+
gr.Examples(
|
1150 |
+
label = "Examples from text",
|
1151 |
+
examples = [
|
1152 |
+
[
|
1153 |
+
None, # input_image
|
1154 |
+
0, # image_position
|
1155 |
+
"Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
1156 |
+
"text", # generation_mode
|
1157 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1158 |
+
True, # randomize_seed
|
1159 |
+
42, # seed
|
1160 |
+
672, # resolution
|
1161 |
+
1, # total_second_length
|
1162 |
+
9, # latent_window_size
|
1163 |
+
30, # steps
|
1164 |
+
1.0, # cfg
|
1165 |
+
10.0, # gs
|
1166 |
+
0.0, # rs
|
1167 |
+
6, # gpu_memory_preservation
|
1168 |
+
False, # enable_preview
|
1169 |
+
False, # use_teacache
|
1170 |
+
16 # mp4_crf
|
1171 |
+
]
|
1172 |
+
],
|
1173 |
+
run_on_click = True,
|
1174 |
+
fn = process,
|
1175 |
+
inputs = ips,
|
1176 |
+
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
|
1177 |
+
cache_examples = False,
|
1178 |
+
)
|
1179 |
+
|
1180 |
+
gr.Examples(
|
1181 |
+
label = "Examples from image",
|
1182 |
+
examples = [
|
1183 |
+
[
|
1184 |
+
"./img_examples/Example1.png", # input_image
|
1185 |
+
0, # image_position
|
1186 |
+
"A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
|
1187 |
+
"image", # generation_mode
|
1188 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1189 |
+
True, # randomize_seed
|
1190 |
+
42, # seed
|
1191 |
+
672, # resolution
|
1192 |
+
1, # total_second_length
|
1193 |
+
9, # latent_window_size
|
1194 |
+
30, # steps
|
1195 |
+
1.0, # cfg
|
1196 |
+
10.0, # gs
|
1197 |
+
0.0, # rs
|
1198 |
+
6, # gpu_memory_preservation
|
1199 |
+
False, # enable_preview
|
1200 |
+
True, # use_teacache
|
1201 |
+
16 # mp4_crf
|
1202 |
+
],
|
1203 |
+
[
|
1204 |
+
"./img_examples/Example2.webp", # input_image
|
1205 |
+
0, # image_position
|
1206 |
+
"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",
|
1207 |
+
"image", # generation_mode
|
1208 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1209 |
+
True, # randomize_seed
|
1210 |
+
42, # seed
|
1211 |
+
672, # resolution
|
1212 |
+
2, # total_second_length
|
1213 |
+
9, # latent_window_size
|
1214 |
+
30, # steps
|
1215 |
+
1.0, # cfg
|
1216 |
+
10.0, # gs
|
1217 |
+
0.0, # rs
|
1218 |
+
6, # gpu_memory_preservation
|
1219 |
+
False, # enable_preview
|
1220 |
+
True, # use_teacache
|
1221 |
+
16 # mp4_crf
|
1222 |
+
],
|
1223 |
+
[
|
1224 |
+
"./img_examples/Example2.webp", # input_image
|
1225 |
+
0, # image_position
|
1226 |
+
"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",
|
1227 |
+
"image", # generation_mode
|
1228 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1229 |
+
True, # randomize_seed
|
1230 |
+
42, # seed
|
1231 |
+
672, # resolution
|
1232 |
+
2, # total_second_length
|
1233 |
+
9, # latent_window_size
|
1234 |
+
30, # steps
|
1235 |
+
1.0, # cfg
|
1236 |
+
10.0, # gs
|
1237 |
+
0.0, # rs
|
1238 |
+
6, # gpu_memory_preservation
|
1239 |
+
False, # enable_preview
|
1240 |
+
True, # use_teacache
|
1241 |
+
16 # mp4_crf
|
1242 |
+
],
|
1243 |
+
[
|
1244 |
+
"./img_examples/Example3.jpg", # input_image
|
1245 |
+
0, # image_position
|
1246 |
+
"A boy is walking to the right, full view, full-length view, cartoon",
|
1247 |
+
"image", # generation_mode
|
1248 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1249 |
+
True, # randomize_seed
|
1250 |
+
42, # seed
|
1251 |
+
672, # resolution
|
1252 |
+
1, # total_second_length
|
1253 |
+
9, # latent_window_size
|
1254 |
+
30, # steps
|
1255 |
+
1.0, # cfg
|
1256 |
+
10.0, # gs
|
1257 |
+
0.0, # rs
|
1258 |
+
6, # gpu_memory_preservation
|
1259 |
+
False, # enable_preview
|
1260 |
+
True, # use_teacache
|
1261 |
+
16 # mp4_crf
|
1262 |
+
],
|
1263 |
+
[
|
1264 |
+
"./img_examples/Example4.webp", # input_image
|
1265 |
+
100, # image_position
|
1266 |
+
"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
|
1267 |
+
"image", # generation_mode
|
1268 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1269 |
+
True, # randomize_seed
|
1270 |
+
42, # seed
|
1271 |
+
672, # resolution
|
1272 |
+
1, # total_second_length
|
1273 |
+
9, # latent_window_size
|
1274 |
+
30, # steps
|
1275 |
+
1.0, # cfg
|
1276 |
+
10.0, # gs
|
1277 |
+
0.0, # rs
|
1278 |
+
6, # gpu_memory_preservation
|
1279 |
+
False, # enable_preview
|
1280 |
+
False, # use_teacache
|
1281 |
+
16 # mp4_crf
|
1282 |
+
]
|
1283 |
+
],
|
1284 |
+
run_on_click = True,
|
1285 |
+
fn = process,
|
1286 |
+
inputs = ips,
|
1287 |
+
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
|
1288 |
+
cache_examples = False,
|
1289 |
+
)
|
1290 |
+
|
1291 |
+
gr.Examples(
|
1292 |
+
label = "Examples from video",
|
1293 |
+
examples = [
|
1294 |
+
[
|
1295 |
+
"./img_examples/Example1.mp4", # input_video
|
1296 |
+
"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",
|
1297 |
+
"Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
|
1298 |
+
True, # randomize_seed
|
1299 |
+
42, # seed
|
1300 |
+
1, # batch
|
1301 |
+
672, # resolution
|
1302 |
+
1, # total_second_length
|
1303 |
+
9, # latent_window_size
|
1304 |
+
30, # steps
|
1305 |
+
1.0, # cfg
|
1306 |
+
10.0, # gs
|
1307 |
+
0.0, # rs
|
1308 |
+
6, # gpu_memory_preservation
|
1309 |
+
False, # enable_preview
|
1310 |
+
True, # use_teacache
|
1311 |
+
False, # no_resize
|
1312 |
+
16, # mp4_crf
|
1313 |
+
5, # num_clean_frames
|
1314 |
+
default_vae
|
1315 |
+
]
|
1316 |
+
],
|
1317 |
+
run_on_click = True,
|
1318 |
+
fn = process_video,
|
1319 |
+
inputs = ips_video,
|
1320 |
+
outputs = [result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button],
|
1321 |
+
cache_examples = False,
|
1322 |
+
)
|
1323 |
+
|
1324 |
+
def save_preferences(preferences, value):
|
1325 |
+
preferences["generation-mode"] = value
|
1326 |
+
return preferences
|
1327 |
+
|
1328 |
+
def load_preferences(saved_prefs):
|
1329 |
+
saved_prefs = init_preferences(saved_prefs)
|
1330 |
+
return saved_prefs["generation-mode"]
|
1331 |
+
|
1332 |
+
def init_preferences(saved_prefs):
|
1333 |
+
if saved_prefs is None:
|
1334 |
+
saved_prefs = default_local_storage
|
1335 |
+
return saved_prefs
|
1336 |
+
|
1337 |
+
def check_parameters(generation_mode, input_image, input_video):
|
1338 |
+
if generation_mode == "image" and input_image is None:
|
1339 |
+
raise gr.Error("Please provide an image to extend.")
|
1340 |
+
if generation_mode == "video" and input_video is None:
|
1341 |
+
raise gr.Error("Please provide a video to extend.")
|
1342 |
+
return [gr.update(interactive=True), gr.update(visible = True)]
|
1343 |
+
|
1344 |
+
def handle_generation_mode_change(generation_mode_data):
|
1345 |
+
if generation_mode_data == "text":
|
1346 |
+
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)]
|
1347 |
+
elif generation_mode_data == "image":
|
1348 |
+
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)]
|
1349 |
+
elif generation_mode_data == "video":
|
1350 |
+
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)]
|
1351 |
+
|
1352 |
+
prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])
|
1353 |
+
timeless_prompt.change(fn=handle_timeless_prompt_change, inputs=[timeless_prompt], outputs=[final_prompt])
|
1354 |
+
start_button.click(fn = check_parameters, inputs = [
|
1355 |
+
generation_mode, input_image, input_video
|
1356 |
+
], 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)
|
1357 |
+
start_button_video.click(fn = check_parameters, inputs = [
|
1358 |
+
generation_mode, input_image, input_video
|
1359 |
+
], 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)
|
1360 |
+
end_button.click(fn=end_process)
|
1361 |
+
|
1362 |
+
generation_mode.change(fn = save_preferences, inputs = [
|
1363 |
+
local_storage,
|
1364 |
+
generation_mode,
|
1365 |
+
], outputs = [
|
1366 |
+
local_storage
|
1367 |
+
])
|
1368 |
+
|
1369 |
+
generation_mode.change(
|
1370 |
+
fn=handle_generation_mode_change,
|
1371 |
+
inputs=[generation_mode],
|
1372 |
+
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]
|
1373 |
+
)
|
1374 |
+
|
1375 |
+
# Update display when the page loads
|
1376 |
+
block.load(
|
1377 |
+
fn=handle_generation_mode_change, inputs = [
|
1378 |
+
generation_mode
|
1379 |
+
], outputs = [
|
1380 |
+
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
|
1381 |
+
]
|
1382 |
+
)
|
1383 |
+
|
1384 |
+
# Load saved preferences when the page loads
|
1385 |
+
block.load(
|
1386 |
+
fn=load_preferences, inputs = [
|
1387 |
+
local_storage
|
1388 |
+
], outputs = [
|
1389 |
+
generation_mode
|
1390 |
+
]
|
1391 |
+
)
|
1392 |
+
|
1393 |
+
block.launch(mcp_server=True, ssr_mode=False)
|