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