Fabrice-TIERCELIN commited on
Commit
87554e6
·
verified ·
1 Parent(s): e4642a8

Comment logs

Browse files
Files changed (1) hide show
  1. app_v2v.py +743 -742
app_v2v.py CHANGED
@@ -1,742 +1,743 @@
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
- import spaces
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
- import decord
16
- from tqdm import tqdm
17
- import pathlib
18
- from datetime import datetime
19
- import imageio_ffmpeg
20
- import tempfile
21
- import shutil
22
- import subprocess
23
-
24
- from PIL import Image
25
- from diffusers import AutoencoderKLHunyuanVideo
26
- from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
27
- from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
28
- 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
29
- from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
30
- from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
31
- 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
32
- from diffusers_helper.thread_utils import AsyncStream, async_run
33
- from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
34
- from transformers import SiglipImageProcessor, SiglipVisionModel
35
- from diffusers_helper.clip_vision import hf_clip_vision_encode
36
- from diffusers_helper.bucket_tools import find_nearest_bucket
37
- from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline
38
-
39
- parser = argparse.ArgumentParser()
40
- parser.add_argument('--share', action='store_true')
41
- parser.add_argument("--server", type=str, default='0.0.0.0')
42
- parser.add_argument("--port", type=int, required=False)
43
- parser.add_argument("--inbrowser", action='store_true')
44
- args = parser.parse_args()
45
-
46
- print(args)
47
-
48
- free_mem_gb = get_cuda_free_memory_gb(gpu)
49
- high_vram = free_mem_gb > 80
50
-
51
- print(f'Free VRAM {free_mem_gb} GB')
52
- print(f'High-VRAM Mode: {high_vram}')
53
-
54
-
55
-
56
- text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
57
- text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
58
- tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
59
- tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
60
- vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
61
-
62
- feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
63
- image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
64
-
65
- quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
66
- transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained(
67
- "lllyasviel/FramePack_F1_I2V_HY_20250503",
68
- quantization_config=quant_config,
69
- torch_dtype=torch.bfloat16,
70
- ).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
- input_video_debug_value = None
116
- prompt_debug_value = None
117
- total_second_length_debug_value = None
118
-
119
- @spaces.GPU()
120
- @torch.no_grad()
121
- def video_encode(video_path, resolution, no_resize, vae, vae_batch_size=16, device="cuda", width=None, height=None):
122
- """
123
- Encode a video into latent representations using the VAE.
124
-
125
- Args:
126
- video_path: Path to the input video file.
127
- vae: AutoencoderKLHunyuanVideo model.
128
- height, width: Target resolution for resizing frames.
129
- vae_batch_size: Number of frames to process per batch.
130
- device: Device for computation (e.g., "cuda").
131
-
132
- Returns:
133
- start_latent: Latent of the first frame (for compatibility with original code).
134
- input_image_np: First frame as numpy array (for CLIP vision encoding).
135
- history_latents: Latents of all frames (shape: [1, channels, frames, height//8, width//8]).
136
- fps: Frames per second of the input video.
137
- """
138
- video_path = str(pathlib.Path(video_path).resolve())
139
- print(f"Processing video: {video_path}")
140
-
141
- if device == "cuda" and not torch.cuda.is_available():
142
- print("CUDA is not available, falling back to CPU")
143
- device = "cpu"
144
-
145
- try:
146
- print("Initializing VideoReader...")
147
- vr = decord.VideoReader(video_path)
148
- fps = vr.get_avg_fps() # Get input video FPS
149
- num_real_frames = len(vr)
150
- print(f"Video loaded: {num_real_frames} frames, FPS: {fps}")
151
-
152
- # Truncate to nearest latent size (multiple of 4)
153
- latent_size_factor = 4
154
- num_frames = (num_real_frames // latent_size_factor) * latent_size_factor
155
- if num_frames != num_real_frames:
156
- print(f"Truncating video from {num_real_frames} to {num_frames} frames for latent size compatibility")
157
- num_real_frames = num_frames
158
-
159
- print("Reading video frames...")
160
- frames = vr.get_batch(range(num_real_frames)).asnumpy() # Shape: (num_real_frames, height, width, channels)
161
- print(f"Frames read: {frames.shape}")
162
-
163
- native_height, native_width = frames.shape[1], frames.shape[2]
164
- print(f"Native video resolution: {native_width}x{native_height}")
165
-
166
- target_height = native_height if height is None else height
167
- target_width = native_width if width is None else width
168
-
169
- if not no_resize:
170
- target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution)
171
- print(f"Adjusted resolution: {target_width}x{target_height}")
172
- else:
173
- print(f"Using native resolution without resizing: {target_width}x{target_height}")
174
-
175
- processed_frames = []
176
- for i, frame in enumerate(frames):
177
- #print(f"Preprocessing frame {i+1}/{num_frames}")
178
- frame_np = resize_and_center_crop(frame, target_width=target_width, target_height=target_height)
179
- processed_frames.append(frame_np)
180
- processed_frames = np.stack(processed_frames) # Shape: (num_real_frames, height, width, channels)
181
- print(f"Frames preprocessed: {processed_frames.shape}")
182
-
183
- input_image_np = processed_frames[0]
184
-
185
- print("Converting frames to tensor...")
186
- frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1
187
- frames_pt = frames_pt.permute(0, 3, 1, 2) # Shape: (num_real_frames, channels, height, width)
188
- frames_pt = frames_pt.unsqueeze(0) # Shape: (1, num_real_frames, channels, height, width)
189
- frames_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)
190
- print(f"Tensor shape: {frames_pt.shape}")
191
-
192
- input_video_pixels = frames_pt.cpu()
193
-
194
- print(f"Moving tensor to device: {device}")
195
- frames_pt = frames_pt.to(device)
196
- print("Tensor moved to device")
197
-
198
- print(f"Moving VAE to device: {device}")
199
- vae.to(device)
200
- print("VAE moved to device")
201
-
202
- print(f"Encoding input video frames in VAE batch size {vae_batch_size} (reduce if memory issues here or if forcing video resolution)")
203
- latents = []
204
- vae.eval()
205
- with torch.no_grad():
206
- for i in tqdm(range(0, frames_pt.shape[2], vae_batch_size), desc="Encoding video frames", mininterval=0.1):
207
- #print(f"Encoding batch {i//vae_batch_size + 1}: frames {i} to {min(i + vae_batch_size, frames_pt.shape[2])}")
208
- batch = frames_pt[:, :, i:i + vae_batch_size] # Shape: (1, channels, batch_size, height, width)
209
- try:
210
- if device == "cuda":
211
- free_mem = torch.cuda.memory_allocated() / 1024**3
212
- print(f"GPU memory before encoding: {free_mem:.2f} GB")
213
- batch_latent = vae_encode(batch, vae)
214
- if device == "cuda":
215
- torch.cuda.synchronize()
216
- print(f"GPU memory after encoding: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
217
- latents.append(batch_latent)
218
- #print(f"Batch encoded, latent shape: {batch_latent.shape}")
219
- except RuntimeError as e:
220
- print(f"Error during VAE encoding: {str(e)}")
221
- if device == "cuda" and "out of memory" in str(e).lower():
222
- print("CUDA out of memory, try reducing vae_batch_size or using CPU")
223
- raise
224
-
225
- print("Concatenating latents...")
226
- history_latents = torch.cat(latents, dim=2) # Shape: (1, channels, frames, height//8, width//8)
227
- print(f"History latents shape: {history_latents.shape}")
228
-
229
- start_latent = history_latents[:, :, :1] # Shape: (1, channels, 1, height//8, width//8)
230
- print(f"Start latent shape: {start_latent.shape}")
231
-
232
- if device == "cuda":
233
- vae.to(cpu)
234
- torch.cuda.empty_cache()
235
- print("VAE moved back to CPU, CUDA cache cleared")
236
-
237
- return start_latent, input_image_np, history_latents, fps, target_height, target_width, input_video_pixels
238
-
239
- except Exception as e:
240
- print(f"Error in video_encode: {str(e)}")
241
- raise
242
-
243
- def set_mp4_comments_imageio_ffmpeg(input_file, comments):
244
- try:
245
- ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
246
-
247
- if not os.path.exists(input_file):
248
- print(f"Error: Input file {input_file} does not exist")
249
- return False
250
-
251
- # Create a temporary file path
252
- temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
253
-
254
- # FFmpeg command using the bundled binary
255
- command = [
256
- ffmpeg_path, # Use imageio-ffmpeg's FFmpeg
257
- '-i', input_file, # input file
258
- '-metadata', f'comment={comments}', # set comment metadata
259
- '-c:v', 'copy', # copy video stream without re-encoding
260
- '-c:a', 'copy', # copy audio stream without re-encoding
261
- '-y', # overwrite output file if it exists
262
- temp_file # temporary output file
263
- ]
264
-
265
- result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
266
-
267
- if result.returncode == 0:
268
- # Replace the original file with the modified one
269
- shutil.move(temp_file, input_file)
270
- print(f"Successfully added comments to {input_file}")
271
- return True
272
- else:
273
- # Clean up temp file if FFmpeg fails
274
- if os.path.exists(temp_file):
275
- os.remove(temp_file)
276
- print(f"Error: FFmpeg failed with message:\n{result.stderr}")
277
- return False
278
-
279
- except Exception as e:
280
- # Clean up temp file in case of other errors
281
- if 'temp_file' in locals() and os.path.exists(temp_file):
282
- os.remove(temp_file)
283
- print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e))
284
- return False
285
-
286
- @spaces.GPU()
287
- @torch.no_grad()
288
- def worker(input_video, 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):
289
-
290
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
291
-
292
- try:
293
- if not high_vram:
294
- unload_complete_models(
295
- text_encoder, text_encoder_2, image_encoder, vae
296
- )
297
-
298
- # Text encoding
299
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
300
-
301
- if not high_vram:
302
- 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.
303
- load_model_as_complete(text_encoder_2, target_device=gpu)
304
-
305
- llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
306
-
307
- if cfg == 1:
308
- llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
309
- else:
310
- llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
311
-
312
- llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
313
- llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
314
-
315
- # 20250506 pftq: Processing input video instead of image
316
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
317
-
318
- # 20250506 pftq: Encode video
319
- #H, W = 640, 640 # Default resolution, will be adjusted
320
- #height, width = find_nearest_bucket(H, W, resolution=640)
321
- #start_latent, input_image_np, history_latents, fps = video_encode(input_video, vae, height, width, vae_batch_size=16, device=gpu)
322
- start_latent, input_image_np, video_latents, fps, height, width, input_video_pixels = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)
323
-
324
- #Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
325
-
326
- # CLIP Vision
327
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
328
-
329
- if not high_vram:
330
- load_model_as_complete(image_encoder, target_device=gpu)
331
-
332
- image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
333
- image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
334
-
335
- # Dtype
336
- llama_vec = llama_vec.to(transformer.dtype)
337
- llama_vec_n = llama_vec_n.to(transformer.dtype)
338
- clip_l_pooler = clip_l_pooler.to(transformer.dtype)
339
- clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
340
- image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
341
-
342
- total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
343
- total_latent_sections = int(max(round(total_latent_sections), 1))
344
-
345
- for idx in range(batch):
346
- if idx>0:
347
- seed = seed + 1
348
-
349
- if batch > 1:
350
- print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
351
-
352
- #job_id = generate_timestamp()
353
- 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
354
-
355
- # Sampling
356
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
357
-
358
- rnd = torch.Generator("cpu").manual_seed(seed)
359
-
360
- history_latents = video_latents.cpu()
361
- total_generated_latent_frames = history_latents.shape[2]
362
- history_pixels = None
363
- previous_video = None
364
-
365
- # 20250507 pftq: hot fix for initial video being corrupted by vae encoding, issue with ghosting because of slight differences
366
- #history_pixels = input_video_pixels
367
- #save_bcthw_as_mp4(vae_decode(video_latents, vae).cpu(), os.path.join(outputs_folder, f'{job_id}_input_video.mp4'), fps=fps, crf=mp4_crf) # 20250507 pftq: test fast movement corrupted by vae encoding if vae batch size too low
368
-
369
- for section_index in range(total_latent_sections):
370
- if stream.input_queue.top() == 'end':
371
- stream.output_queue.push(('end', None))
372
- return
373
-
374
- print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
375
-
376
- if not high_vram:
377
- unload_complete_models()
378
- # move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
379
-
380
- if use_teacache:
381
- transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
382
- else:
383
- transformer.initialize_teacache(enable_teacache=False)
384
-
385
- def callback(d):
386
- preview = d['denoised']
387
- preview = vae_decode_fake(preview)
388
-
389
- preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
390
- preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
391
-
392
- if stream.input_queue.top() == 'end':
393
- stream.output_queue.push(('end', None))
394
- raise KeyboardInterrupt('User ends the task.')
395
-
396
- current_step = d['i'] + 1
397
- percentage = int(100.0 * current_step / steps)
398
- hint = f'Sampling {current_step}/{steps}'
399
- 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}. The video is generating part {section_index+1} of {total_latent_sections}...'
400
- stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
401
- return
402
-
403
- # 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2
404
- available_frames = history_latents.shape[2] # Number of latent frames
405
- max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames
406
- adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames
407
- # Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x
408
- effective_clean_frames = max(0, num_clean_frames - 1) if num_clean_frames > 1 else 0
409
- 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
410
- 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
411
- 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
412
-
413
- total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
414
- total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos
415
-
416
- 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
417
- clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
418
- [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
419
- )
420
- clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
421
-
422
- # 20250506 pftq: Split history_latents dynamically based on available frames
423
- fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos
424
- context_frames = history_latents[:, :, -total_context_frames:, :, :] if total_context_frames > 0 else history_latents[:, :, :fallback_frame_count, :, :]
425
- if total_context_frames > 0:
426
- split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames]
427
- split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes
428
- if split_sizes:
429
- splits = context_frames.split(split_sizes, dim=2)
430
- split_idx = 0
431
- clean_latents_4x = splits[split_idx] if num_4x_frames > 0 else history_latents[:, :, :fallback_frame_count, :, :]
432
- if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
433
- clean_latents_4x = torch.cat([clean_latents_4x, clean_latents_4x[:, :, -1:, :, :]], dim=2)[:, :, :2, :, :]
434
- split_idx += 1 if num_4x_frames > 0 else 0
435
- clean_latents_2x = splits[split_idx] if num_2x_frames > 0 and split_idx < len(splits) else history_latents[:, :, :fallback_frame_count, :, :]
436
- if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
437
- clean_latents_2x = torch.cat([clean_latents_2x, clean_latents_2x[:, :, -1:, :, :]], dim=2)[:, :, :2, :, :]
438
- split_idx += 1 if num_2x_frames > 0 else 0
439
- clean_latents_1x = splits[split_idx] if effective_clean_frames > 0 and split_idx < len(splits) else history_latents[:, :, :fallback_frame_count, :, :]
440
- else:
441
- clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
442
- else:
443
- clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
444
-
445
- clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)
446
-
447
- # 20250507 pftq: Fix for <=1 sec videos.
448
- max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
449
-
450
- generated_latents = sample_hunyuan(
451
- transformer=transformer,
452
- sampler='unipc',
453
- width=width,
454
- height=height,
455
- frames=max_frames,
456
- real_guidance_scale=cfg,
457
- distilled_guidance_scale=gs,
458
- guidance_rescale=rs,
459
- num_inference_steps=steps,
460
- generator=rnd,
461
- prompt_embeds=llama_vec,
462
- prompt_embeds_mask=llama_attention_mask,
463
- prompt_poolers=clip_l_pooler,
464
- negative_prompt_embeds=llama_vec_n,
465
- negative_prompt_embeds_mask=llama_attention_mask_n,
466
- negative_prompt_poolers=clip_l_pooler_n,
467
- device=gpu,
468
- dtype=torch.bfloat16,
469
- image_embeddings=image_encoder_last_hidden_state,
470
- latent_indices=latent_indices,
471
- clean_latents=clean_latents,
472
- clean_latent_indices=clean_latent_indices,
473
- clean_latents_2x=clean_latents_2x,
474
- clean_latent_2x_indices=clean_latent_2x_indices,
475
- clean_latents_4x=clean_latents_4x,
476
- clean_latent_4x_indices=clean_latent_4x_indices,
477
- callback=callback,
478
- )
479
-
480
- total_generated_latent_frames += int(generated_latents.shape[2])
481
- history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
482
-
483
- if not high_vram:
484
- offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
485
- load_model_as_complete(vae, target_device=gpu)
486
-
487
- real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
488
-
489
- if history_pixels is None:
490
- history_pixels = vae_decode(real_history_latents, vae).cpu()
491
- else:
492
- section_latent_frames = latent_window_size * 2
493
- overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2])
494
-
495
- #if section_index == 0:
496
- #extra_latents = 1 # Add up to 2 extra latent frames for smoother overlap to initial video
497
- #extra_pixel_frames = extra_latents * 4 # Approx. 4 pixel frames per latent
498
- #overlapped_frames = min(overlapped_frames + extra_pixel_frames, history_pixels.shape[2], section_latent_frames * 4)
499
-
500
- current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()
501
- history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)
502
-
503
- if not high_vram:
504
- unload_complete_models()
505
-
506
- output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
507
-
508
- # 20250506 pftq: Use input video FPS for output
509
- save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
510
- print(f"Latest video saved: {output_filename}")
511
- # 20250508 pftq: Save prompt to mp4 metadata comments
512
- set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}");
513
- print(f"Prompt saved to mp4 metadata comments: {output_filename}")
514
-
515
- # 20250506 pftq: Clean up previous partial files
516
- if previous_video is not None and os.path.exists(previous_video):
517
- try:
518
- os.remove(previous_video)
519
- print(f"Previous partial video deleted: {previous_video}")
520
- except Exception as e:
521
- print(f"Error deleting previous partial video {previous_video}: {e}")
522
- previous_video = output_filename
523
-
524
- print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
525
-
526
- stream.output_queue.push(('file', output_filename))
527
- except:
528
- traceback.print_exc()
529
-
530
- if not high_vram:
531
- unload_complete_models(
532
- text_encoder, text_encoder_2, image_encoder, vae
533
- )
534
-
535
- stream.output_queue.push(('end', None))
536
- return
537
-
538
- def get_duration(input_video, 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):
539
- global total_second_length_debug_value
540
- if total_second_length_debug_value is not None:
541
- return 5 * 60
542
- return 5 * 60
543
-
544
- @spaces.GPU(duration=get_duration)
545
- def process(input_video, 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):
546
- global stream, high_vram, input_video_debug_value, prompt_debug_value, total_second_length_debug_value
547
-
548
- if torch.cuda.device_count() == 0:
549
- gr.Warning('Set this space to GPU config to make it work.')
550
- return None, None, None, None, None, None
551
-
552
- if input_video_debug_value is not None:
553
- input_video = input_video_debug_value
554
- input_video_debug_value = None
555
-
556
- if prompt_debug_value is not None:
557
- prompt = prompt_debug_value
558
- prompt_debug_value = None
559
-
560
- if total_second_length_debug_value is not None:
561
- total_second_length = total_second_length_debug_value
562
- total_second_length_debug_value = None
563
-
564
- # 20250506 pftq: Updated assertion for video input
565
- assert input_video is not None, 'No input video!'
566
-
567
- yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
568
-
569
- # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
570
- if high_vram and (no_resize or resolution>640):
571
- print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
572
- high_vram = False
573
- vae.enable_slicing()
574
- vae.enable_tiling()
575
- DynamicSwapInstaller.install_model(transformer, device=gpu)
576
- DynamicSwapInstaller.install_model(text_encoder, device=gpu)
577
-
578
- # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
579
- if cfg > 1:
580
- gs = 1
581
-
582
- stream = AsyncStream()
583
-
584
- # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
585
- async_run(worker, input_video, 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)
586
-
587
- output_filename = None
588
-
589
- while True:
590
- flag, data = stream.output_queue.next()
591
-
592
- if flag == 'file':
593
- output_filename = data
594
- yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
595
-
596
- if flag == 'progress':
597
- preview, desc, html = data
598
- #yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
599
- 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
600
-
601
- if flag == 'end':
602
- yield output_filename, gr.update(visible=False), desc+' Video complete.', '', gr.update(interactive=True), gr.update(interactive=False)
603
- break
604
-
605
- def end_process():
606
- stream.input_queue.push('end')
607
-
608
- quick_prompts = [
609
- 'The girl dances gracefully, with clear movements, full of charm.',
610
- 'A character doing some simple body movements.',
611
- ]
612
- quick_prompts = [[x] for x in quick_prompts]
613
-
614
- css = make_progress_bar_css()
615
- block = gr.Blocks(css=css).queue()
616
- with block:
617
- gr.Markdown('# Framepack F1 (Video Extender)')
618
- with gr.Row():
619
- with gr.Column():
620
- # 20250506 pftq: Changed to Video input from Image
621
- input_video = gr.Video(sources='upload', label="Input Video", height=320)
622
- prompt = gr.Textbox(label="Prompt", value='')
623
- #example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Quick List', samples_per_page=1000, components=[prompt])
624
- #example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False)
625
-
626
- with gr.Row():
627
- start_button = gr.Button(value="Start Generation", variant="primary")
628
- end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
629
-
630
- with gr.Group():
631
- with gr.Row():
632
- use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
633
- no_resize = gr.Checkbox(label='Force Original Video Resolution (No Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
634
-
635
- seed = gr.Number(label="Seed", value=31337, precision=0)
636
-
637
- 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.')
638
-
639
- resolution = gr.Number(label="Resolution (max width or height)", value=640, precision=0, visible=False)
640
-
641
- total_second_length = gr.Slider(label="Additional Video Length to Generate (Seconds)", minimum=1, maximum=120, value=1, step=0.1)
642
-
643
- 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.')
644
- cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01, visible=True, info='Use this instead of Distilled for more detail/control + Negative Prompt (make sure Distilled set to 1). Doubles render time.') # Should not change
645
- rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, visible=False) # Should not change
646
-
647
- 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).')
648
- steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1, info='Increase for more quality, especially if using high non-distilled CFG.')
649
-
650
- 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 if memory issues.")
651
-
652
- default_vae = 32
653
- if high_vram:
654
- default_vae = 128
655
- elif free_mem_gb>=20:
656
- default_vae = 64
657
-
658
- 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.")
659
-
660
- latent_window_size = gr.Slider(label="Latent Window Size", minimum=9, maximum=33, value=9, step=1, visible=True, info='Generate more frames at a time (larger chunks). Less degradation and better blending but higher VRAM cost.')
661
-
662
- 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.")
663
-
664
- 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. ")
665
-
666
- with gr.Row():
667
- input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
668
- prompt_debug = gr.Textbox(label="Prompt Debug", value='')
669
- total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)
670
-
671
- with gr.Column():
672
- preview_image = gr.Image(label="Next Latents", height=200, visible=False)
673
- result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
674
- progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
675
- progress_bar = gr.HTML('', elem_classes='no-generating-animation')
676
-
677
- with gr.Row(visible=False):
678
- gr.Examples(
679
- examples = [
680
- [
681
- "./img_examples/Example1.mp4", # input_video
682
- "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",
683
- "", # n_prompt
684
- 42, # seed
685
- 1, # batch
686
- 640, # resolution
687
- 1, # total_second_length
688
- 9, # latent_window_size
689
- 25, # steps
690
- 1.0, # cfg
691
- 10.0, # gs
692
- 0.0, # rs
693
- 6, # gpu_memory_preservation
694
- True, # use_teacache
695
- False, # no_resize
696
- 16, # mp4_crf
697
- 5, # num_clean_frames
698
- default_vae
699
- ],
700
- ],
701
- run_on_click = True,
702
- fn = process,
703
- inputs = [input_video, 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],
704
- outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
705
- cache_examples = True,
706
- )
707
-
708
- gr.HTML("""
709
- <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>
710
- """)
711
-
712
- ips = [input_video, 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]
713
- start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
714
- end_button.click(fn=end_process)
715
-
716
-
717
- def handle_field_debug_change(input_video_debug_data, prompt_debug_data, total_second_length_debug_data):
718
- global input_video_debug_value, prompt_debug_value, total_second_length_debug_value
719
- input_video_debug_value = input_video_debug_data
720
- prompt_debug_value = prompt_debug_data
721
- total_second_length_debug_value = total_second_length_debug_data
722
- return []
723
-
724
- input_video_debug.upload(
725
- fn=handle_field_debug_change,
726
- inputs=[input_video_debug, prompt_debug, total_second_length_debug],
727
- outputs=[]
728
- )
729
-
730
- prompt_debug.change(
731
- fn=handle_field_debug_change,
732
- inputs=[input_video_debug, prompt_debug, total_second_length_debug],
733
- outputs=[]
734
- )
735
-
736
- total_second_length_debug.change(
737
- fn=handle_field_debug_change,
738
- inputs=[input_video_debug, prompt_debug, total_second_length_debug],
739
- outputs=[]
740
- )
741
-
742
- block.launch(ssr_mode=False)
 
 
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
+ import spaces
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
+ import decord
16
+ from tqdm import tqdm
17
+ import pathlib
18
+ from datetime import datetime
19
+ import imageio_ffmpeg
20
+ import tempfile
21
+ import shutil
22
+ import subprocess
23
+
24
+ from PIL import Image
25
+ from diffusers import AutoencoderKLHunyuanVideo
26
+ from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
27
+ from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
28
+ 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
29
+ from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
30
+ from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
31
+ 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
32
+ from diffusers_helper.thread_utils import AsyncStream, async_run
33
+ from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
34
+ from transformers import SiglipImageProcessor, SiglipVisionModel
35
+ from diffusers_helper.clip_vision import hf_clip_vision_encode
36
+ from diffusers_helper.bucket_tools import find_nearest_bucket
37
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline
38
+
39
+ parser = argparse.ArgumentParser()
40
+ parser.add_argument('--share', action='store_true')
41
+ parser.add_argument("--server", type=str, default='0.0.0.0')
42
+ parser.add_argument("--port", type=int, required=False)
43
+ parser.add_argument("--inbrowser", action='store_true')
44
+ args = parser.parse_args()
45
+
46
+ print(args)
47
+
48
+ free_mem_gb = get_cuda_free_memory_gb(gpu)
49
+ high_vram = free_mem_gb > 80
50
+
51
+ print(f'Free VRAM {free_mem_gb} GB')
52
+ print(f'High-VRAM Mode: {high_vram}')
53
+
54
+
55
+
56
+ text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
57
+ text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
58
+ tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
59
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
60
+ vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
61
+
62
+ feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
63
+ image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
64
+
65
+ quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
66
+ transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained(
67
+ "lllyasviel/FramePack_F1_I2V_HY_20250503",
68
+ quantization_config=quant_config,
69
+ torch_dtype=torch.bfloat16,
70
+ ).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
+ input_video_debug_value = None
116
+ prompt_debug_value = None
117
+ total_second_length_debug_value = None
118
+
119
+ @spaces.GPU()
120
+ @torch.no_grad()
121
+ def video_encode(video_path, resolution, no_resize, vae, vae_batch_size=16, device="cuda", width=None, height=None):
122
+ """
123
+ Encode a video into latent representations using the VAE.
124
+
125
+ Args:
126
+ video_path: Path to the input video file.
127
+ vae: AutoencoderKLHunyuanVideo model.
128
+ height, width: Target resolution for resizing frames.
129
+ vae_batch_size: Number of frames to process per batch.
130
+ device: Device for computation (e.g., "cuda").
131
+
132
+ Returns:
133
+ start_latent: Latent of the first frame (for compatibility with original code).
134
+ input_image_np: First frame as numpy array (for CLIP vision encoding).
135
+ history_latents: Latents of all frames (shape: [1, channels, frames, height//8, width//8]).
136
+ fps: Frames per second of the input video.
137
+ """
138
+ video_path = str(pathlib.Path(video_path).resolve())
139
+ print(f"Processing video: {video_path}")
140
+
141
+ if device == "cuda" and not torch.cuda.is_available():
142
+ print("CUDA is not available, falling back to CPU")
143
+ device = "cpu"
144
+
145
+ try:
146
+ print("Initializing VideoReader...")
147
+ vr = decord.VideoReader(video_path)
148
+ fps = vr.get_avg_fps() # Get input video FPS
149
+ num_real_frames = len(vr)
150
+ print(f"Video loaded: {num_real_frames} frames, FPS: {fps}")
151
+
152
+ # Truncate to nearest latent size (multiple of 4)
153
+ latent_size_factor = 4
154
+ num_frames = (num_real_frames // latent_size_factor) * latent_size_factor
155
+ if num_frames != num_real_frames:
156
+ print(f"Truncating video from {num_real_frames} to {num_frames} frames for latent size compatibility")
157
+ num_real_frames = num_frames
158
+
159
+ print("Reading video frames...")
160
+ frames = vr.get_batch(range(num_real_frames)).asnumpy() # Shape: (num_real_frames, height, width, channels)
161
+ print(f"Frames read: {frames.shape}")
162
+
163
+ native_height, native_width = frames.shape[1], frames.shape[2]
164
+ print(f"Native video resolution: {native_width}x{native_height}")
165
+
166
+ target_height = native_height if height is None else height
167
+ target_width = native_width if width is None else width
168
+
169
+ if not no_resize:
170
+ target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution)
171
+ print(f"Adjusted resolution: {target_width}x{target_height}")
172
+ else:
173
+ print(f"Using native resolution without resizing: {target_width}x{target_height}")
174
+
175
+ processed_frames = []
176
+ for i, frame in enumerate(frames):
177
+ #print(f"Preprocessing frame {i+1}/{num_frames}")
178
+ frame_np = resize_and_center_crop(frame, target_width=target_width, target_height=target_height)
179
+ processed_frames.append(frame_np)
180
+ processed_frames = np.stack(processed_frames) # Shape: (num_real_frames, height, width, channels)
181
+ print(f"Frames preprocessed: {processed_frames.shape}")
182
+
183
+ input_image_np = processed_frames[0]
184
+
185
+ print("Converting frames to tensor...")
186
+ frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1
187
+ frames_pt = frames_pt.permute(0, 3, 1, 2) # Shape: (num_real_frames, channels, height, width)
188
+ frames_pt = frames_pt.unsqueeze(0) # Shape: (1, num_real_frames, channels, height, width)
189
+ frames_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)
190
+ print(f"Tensor shape: {frames_pt.shape}")
191
+
192
+ input_video_pixels = frames_pt.cpu()
193
+
194
+ print(f"Moving tensor to device: {device}")
195
+ frames_pt = frames_pt.to(device)
196
+ print("Tensor moved to device")
197
+
198
+ print(f"Moving VAE to device: {device}")
199
+ vae.to(device)
200
+ print("VAE moved to device")
201
+
202
+ print(f"Encoding input video frames in VAE batch size {vae_batch_size} (reduce if memory issues here or if forcing video resolution)")
203
+ latents = []
204
+ vae.eval()
205
+ with torch.no_grad():
206
+ for i in tqdm(range(0, frames_pt.shape[2], vae_batch_size), desc="Encoding video frames", mininterval=0.1):
207
+ #print(f"Encoding batch {i//vae_batch_size + 1}: frames {i} to {min(i + vae_batch_size, frames_pt.shape[2])}")
208
+ batch = frames_pt[:, :, i:i + vae_batch_size] # Shape: (1, channels, batch_size, height, width)
209
+ try:
210
+ if device == "cuda":
211
+ free_mem = torch.cuda.memory_allocated() / 1024**3
212
+ #print(f"GPU memory before encoding: {free_mem:.2f} GB")
213
+ batch_latent = vae_encode(batch, vae)
214
+ if device == "cuda":
215
+ torch.cuda.synchronize()
216
+ #print(f"GPU memory after encoding: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
217
+ latents.append(batch_latent)
218
+ #print(f"Batch encoded, latent shape: {batch_latent.shape}")
219
+ except RuntimeError as e:
220
+ print(f"Error during VAE encoding: {str(e)}")
221
+ if device == "cuda" and "out of memory" in str(e).lower():
222
+ print("CUDA out of memory, try reducing vae_batch_size or using CPU")
223
+ raise
224
+
225
+ print("Concatenating latents...")
226
+ history_latents = torch.cat(latents, dim=2) # Shape: (1, channels, frames, height//8, width//8)
227
+ print(f"History latents shape: {history_latents.shape}")
228
+
229
+ start_latent = history_latents[:, :, :1] # Shape: (1, channels, 1, height//8, width//8)
230
+ print(f"Start latent shape: {start_latent.shape}")
231
+
232
+ if device == "cuda":
233
+ vae.to(cpu)
234
+ torch.cuda.empty_cache()
235
+ print("VAE moved back to CPU, CUDA cache cleared")
236
+
237
+ return start_latent, input_image_np, history_latents, fps, target_height, target_width, input_video_pixels
238
+
239
+ except Exception as e:
240
+ print(f"Error in video_encode: {str(e)}")
241
+ raise
242
+
243
+ def set_mp4_comments_imageio_ffmpeg(input_file, comments):
244
+ try:
245
+ ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
246
+
247
+ if not os.path.exists(input_file):
248
+ print(f"Error: Input file {input_file} does not exist")
249
+ return False
250
+
251
+ # Create a temporary file path
252
+ temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
253
+
254
+ # FFmpeg command using the bundled binary
255
+ command = [
256
+ ffmpeg_path, # Use imageio-ffmpeg's FFmpeg
257
+ '-i', input_file, # input file
258
+ '-metadata', f'comment={comments}', # set comment metadata
259
+ '-c:v', 'copy', # copy video stream without re-encoding
260
+ '-c:a', 'copy', # copy audio stream without re-encoding
261
+ '-y', # overwrite output file if it exists
262
+ temp_file # temporary output file
263
+ ]
264
+
265
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
266
+
267
+ if result.returncode == 0:
268
+ # Replace the original file with the modified one
269
+ shutil.move(temp_file, input_file)
270
+ print(f"Successfully added comments to {input_file}")
271
+ return True
272
+ else:
273
+ # Clean up temp file if FFmpeg fails
274
+ if os.path.exists(temp_file):
275
+ os.remove(temp_file)
276
+ print(f"Error: FFmpeg failed with message:\n{result.stderr}")
277
+ return False
278
+
279
+ except Exception as e:
280
+ # Clean up temp file in case of other errors
281
+ if 'temp_file' in locals() and os.path.exists(temp_file):
282
+ os.remove(temp_file)
283
+ print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e))
284
+ return False
285
+
286
+ @spaces.GPU()
287
+ @torch.no_grad()
288
+ def worker(input_video, 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):
289
+
290
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
291
+
292
+ try:
293
+ # Clean GPU
294
+ if not high_vram:
295
+ unload_complete_models(
296
+ text_encoder, text_encoder_2, image_encoder, vae
297
+ )
298
+
299
+ # Text encoding
300
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
301
+
302
+ if not high_vram:
303
+ 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.
304
+ load_model_as_complete(text_encoder_2, target_device=gpu)
305
+
306
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
307
+
308
+ if cfg == 1:
309
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
310
+ else:
311
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
312
+
313
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
314
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
315
+
316
+ # 20250506 pftq: Processing input video instead of image
317
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
318
+
319
+ # 20250506 pftq: Encode video
320
+ #H, W = 640, 640 # Default resolution, will be adjusted
321
+ #height, width = find_nearest_bucket(H, W, resolution=640)
322
+ #start_latent, input_image_np, history_latents, fps = video_encode(input_video, vae, height, width, vae_batch_size=16, device=gpu)
323
+ start_latent, input_image_np, video_latents, fps, height, width, input_video_pixels = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)
324
+
325
+ #Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
326
+
327
+ # CLIP Vision
328
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
329
+
330
+ if not high_vram:
331
+ load_model_as_complete(image_encoder, target_device=gpu)
332
+
333
+ image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
334
+ image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
335
+
336
+ # Dtype
337
+ llama_vec = llama_vec.to(transformer.dtype)
338
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
339
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
340
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
341
+ image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
342
+
343
+ total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
344
+ total_latent_sections = int(max(round(total_latent_sections), 1))
345
+
346
+ for idx in range(batch):
347
+ if idx>0:
348
+ seed = seed + 1
349
+
350
+ if batch > 1:
351
+ print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
352
+
353
+ #job_id = generate_timestamp()
354
+ 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
355
+
356
+ # Sampling
357
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
358
+
359
+ rnd = torch.Generator("cpu").manual_seed(seed)
360
+
361
+ history_latents = video_latents.cpu()
362
+ total_generated_latent_frames = history_latents.shape[2]
363
+ history_pixels = None
364
+ previous_video = None
365
+
366
+ # 20250507 pftq: hot fix for initial video being corrupted by vae encoding, issue with ghosting because of slight differences
367
+ #history_pixels = input_video_pixels
368
+ #save_bcthw_as_mp4(vae_decode(video_latents, vae).cpu(), os.path.join(outputs_folder, f'{job_id}_input_video.mp4'), fps=fps, crf=mp4_crf) # 20250507 pftq: test fast movement corrupted by vae encoding if vae batch size too low
369
+
370
+ for section_index in range(total_latent_sections):
371
+ if stream.input_queue.top() == 'end':
372
+ stream.output_queue.push(('end', None))
373
+ return
374
+
375
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
376
+
377
+ if not high_vram:
378
+ unload_complete_models()
379
+ # move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
380
+
381
+ if use_teacache:
382
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
383
+ else:
384
+ transformer.initialize_teacache(enable_teacache=False)
385
+
386
+ def callback(d):
387
+ preview = d['denoised']
388
+ preview = vae_decode_fake(preview)
389
+
390
+ preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
391
+ preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
392
+
393
+ if stream.input_queue.top() == 'end':
394
+ stream.output_queue.push(('end', None))
395
+ raise KeyboardInterrupt('User ends the task.')
396
+
397
+ current_step = d['i'] + 1
398
+ percentage = int(100.0 * current_step / steps)
399
+ hint = f'Sampling {current_step}/{steps}'
400
+ 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}. The video is generating part {section_index+1} of {total_latent_sections}...'
401
+ stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
402
+ return
403
+
404
+ # 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2
405
+ available_frames = history_latents.shape[2] # Number of latent frames
406
+ max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames
407
+ adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames
408
+ # Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x
409
+ effective_clean_frames = max(0, num_clean_frames - 1) if num_clean_frames > 1 else 0
410
+ 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
411
+ 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
412
+ 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
413
+
414
+ total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
415
+ total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos
416
+
417
+ 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
418
+ clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
419
+ [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
420
+ )
421
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
422
+
423
+ # 20250506 pftq: Split history_latents dynamically based on available frames
424
+ fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos
425
+ context_frames = history_latents[:, :, -total_context_frames:, :, :] if total_context_frames > 0 else history_latents[:, :, :fallback_frame_count, :, :]
426
+ if total_context_frames > 0:
427
+ split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames]
428
+ split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes
429
+ if split_sizes:
430
+ splits = context_frames.split(split_sizes, dim=2)
431
+ split_idx = 0
432
+ clean_latents_4x = splits[split_idx] if num_4x_frames > 0 else history_latents[:, :, :fallback_frame_count, :, :]
433
+ if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
434
+ clean_latents_4x = torch.cat([clean_latents_4x, clean_latents_4x[:, :, -1:, :, :]], dim=2)[:, :, :2, :, :]
435
+ split_idx += 1 if num_4x_frames > 0 else 0
436
+ clean_latents_2x = splits[split_idx] if num_2x_frames > 0 and split_idx < len(splits) else history_latents[:, :, :fallback_frame_count, :, :]
437
+ if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
438
+ clean_latents_2x = torch.cat([clean_latents_2x, clean_latents_2x[:, :, -1:, :, :]], dim=2)[:, :, :2, :, :]
439
+ split_idx += 1 if num_2x_frames > 0 else 0
440
+ clean_latents_1x = splits[split_idx] if effective_clean_frames > 0 and split_idx < len(splits) else history_latents[:, :, :fallback_frame_count, :, :]
441
+ else:
442
+ clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
443
+ else:
444
+ clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
445
+
446
+ clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)
447
+
448
+ # 20250507 pftq: Fix for <=1 sec videos.
449
+ max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
450
+
451
+ generated_latents = sample_hunyuan(
452
+ transformer=transformer,
453
+ sampler='unipc',
454
+ width=width,
455
+ height=height,
456
+ frames=max_frames,
457
+ real_guidance_scale=cfg,
458
+ distilled_guidance_scale=gs,
459
+ guidance_rescale=rs,
460
+ num_inference_steps=steps,
461
+ generator=rnd,
462
+ prompt_embeds=llama_vec,
463
+ prompt_embeds_mask=llama_attention_mask,
464
+ prompt_poolers=clip_l_pooler,
465
+ negative_prompt_embeds=llama_vec_n,
466
+ negative_prompt_embeds_mask=llama_attention_mask_n,
467
+ negative_prompt_poolers=clip_l_pooler_n,
468
+ device=gpu,
469
+ dtype=torch.bfloat16,
470
+ image_embeddings=image_encoder_last_hidden_state,
471
+ latent_indices=latent_indices,
472
+ clean_latents=clean_latents,
473
+ clean_latent_indices=clean_latent_indices,
474
+ clean_latents_2x=clean_latents_2x,
475
+ clean_latent_2x_indices=clean_latent_2x_indices,
476
+ clean_latents_4x=clean_latents_4x,
477
+ clean_latent_4x_indices=clean_latent_4x_indices,
478
+ callback=callback,
479
+ )
480
+
481
+ total_generated_latent_frames += int(generated_latents.shape[2])
482
+ history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
483
+
484
+ if not high_vram:
485
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
486
+ load_model_as_complete(vae, target_device=gpu)
487
+
488
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
489
+
490
+ if history_pixels is None:
491
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
492
+ else:
493
+ section_latent_frames = latent_window_size * 2
494
+ overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2])
495
+
496
+ #if section_index == 0:
497
+ #extra_latents = 1 # Add up to 2 extra latent frames for smoother overlap to initial video
498
+ #extra_pixel_frames = extra_latents * 4 # Approx. 4 pixel frames per latent
499
+ #overlapped_frames = min(overlapped_frames + extra_pixel_frames, history_pixels.shape[2], section_latent_frames * 4)
500
+
501
+ current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()
502
+ history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)
503
+
504
+ if not high_vram:
505
+ unload_complete_models()
506
+
507
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
508
+
509
+ # 20250506 pftq: Use input video FPS for output
510
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
511
+ print(f"Latest video saved: {output_filename}")
512
+ # 20250508 pftq: Save prompt to mp4 metadata comments
513
+ set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}");
514
+ print(f"Prompt saved to mp4 metadata comments: {output_filename}")
515
+
516
+ # 20250506 pftq: Clean up previous partial files
517
+ if previous_video is not None and os.path.exists(previous_video):
518
+ try:
519
+ os.remove(previous_video)
520
+ print(f"Previous partial video deleted: {previous_video}")
521
+ except Exception as e:
522
+ print(f"Error deleting previous partial video {previous_video}: {e}")
523
+ previous_video = output_filename
524
+
525
+ print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
526
+
527
+ stream.output_queue.push(('file', output_filename))
528
+ except:
529
+ traceback.print_exc()
530
+
531
+ if not high_vram:
532
+ unload_complete_models(
533
+ text_encoder, text_encoder_2, image_encoder, vae
534
+ )
535
+
536
+ stream.output_queue.push(('end', None))
537
+ return
538
+
539
+ def get_duration(input_video, 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):
540
+ global total_second_length_debug_value
541
+ if total_second_length_debug_value is not None:
542
+ return 5 * 60
543
+ return 5 * 60
544
+
545
+ @spaces.GPU(duration=get_duration)
546
+ def process(input_video, 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):
547
+ global stream, high_vram, input_video_debug_value, prompt_debug_value, total_second_length_debug_value
548
+
549
+ if torch.cuda.device_count() == 0:
550
+ gr.Warning('Set this space to GPU config to make it work.')
551
+ return None, None, None, None, None, None
552
+
553
+ if input_video_debug_value is not None:
554
+ input_video = input_video_debug_value
555
+ input_video_debug_value = None
556
+
557
+ if prompt_debug_value is not None:
558
+ prompt = prompt_debug_value
559
+ prompt_debug_value = None
560
+
561
+ if total_second_length_debug_value is not None:
562
+ total_second_length = total_second_length_debug_value
563
+ total_second_length_debug_value = None
564
+
565
+ # 20250506 pftq: Updated assertion for video input
566
+ assert input_video is not None, 'No input video!'
567
+
568
+ yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
569
+
570
+ # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
571
+ if high_vram and (no_resize or resolution>640):
572
+ print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
573
+ high_vram = False
574
+ vae.enable_slicing()
575
+ vae.enable_tiling()
576
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
577
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
578
+
579
+ # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
580
+ if cfg > 1:
581
+ gs = 1
582
+
583
+ stream = AsyncStream()
584
+
585
+ # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
586
+ async_run(worker, input_video, 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)
587
+
588
+ output_filename = None
589
+
590
+ while True:
591
+ flag, data = stream.output_queue.next()
592
+
593
+ if flag == 'file':
594
+ output_filename = data
595
+ yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
596
+
597
+ if flag == 'progress':
598
+ preview, desc, html = data
599
+ #yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
600
+ 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
601
+
602
+ if flag == 'end':
603
+ yield output_filename, gr.update(visible=False), desc+' Video complete.', '', gr.update(interactive=True), gr.update(interactive=False)
604
+ break
605
+
606
+ def end_process():
607
+ stream.input_queue.push('end')
608
+
609
+ quick_prompts = [
610
+ 'The girl dances gracefully, with clear movements, full of charm.',
611
+ 'A character doing some simple body movements.',
612
+ ]
613
+ quick_prompts = [[x] for x in quick_prompts]
614
+
615
+ css = make_progress_bar_css()
616
+ block = gr.Blocks(css=css).queue()
617
+ with block:
618
+ gr.Markdown('# Framepack F1 (Video Extender)')
619
+ with gr.Row():
620
+ with gr.Column():
621
+ # 20250506 pftq: Changed to Video input from Image
622
+ input_video = gr.Video(sources='upload', label="Input Video", height=320)
623
+ prompt = gr.Textbox(label="Prompt", value='')
624
+ #example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Quick List', samples_per_page=1000, components=[prompt])
625
+ #example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False)
626
+
627
+ with gr.Row():
628
+ start_button = gr.Button(value="Start Generation", variant="primary")
629
+ end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
630
+
631
+ with gr.Group():
632
+ with gr.Row():
633
+ use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
634
+ no_resize = gr.Checkbox(label='Force Original Video Resolution (No Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
635
+
636
+ seed = gr.Number(label="Seed", value=31337, precision=0)
637
+
638
+ 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.')
639
+
640
+ resolution = gr.Number(label="Resolution (max width or height)", value=640, precision=0, visible=False)
641
+
642
+ total_second_length = gr.Slider(label="Additional Video Length to Generate (Seconds)", minimum=1, maximum=120, value=1, step=0.1)
643
+
644
+ 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.')
645
+ cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01, visible=True, info='Use this instead of Distilled for more detail/control + Negative Prompt (make sure Distilled set to 1). Doubles render time.') # Should not change
646
+ rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, visible=False) # Should not change
647
+
648
+ 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).')
649
+ steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1, info='Increase for more quality, especially if using high non-distilled CFG.')
650
+
651
+ 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 if memory issues.")
652
+
653
+ default_vae = 32
654
+ if high_vram:
655
+ default_vae = 128
656
+ elif free_mem_gb>=20:
657
+ default_vae = 64
658
+
659
+ 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.")
660
+
661
+ latent_window_size = gr.Slider(label="Latent Window Size", minimum=9, maximum=33, value=9, step=1, visible=True, info='Generate more frames at a time (larger chunks). Less degradation and better blending but higher VRAM cost.')
662
+
663
+ 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.")
664
+
665
+ 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. ")
666
+
667
+ with gr.Row():
668
+ input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
669
+ prompt_debug = gr.Textbox(label="Prompt Debug", value='')
670
+ total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)
671
+
672
+ with gr.Column():
673
+ preview_image = gr.Image(label="Next Latents", height=200, visible=False)
674
+ result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
675
+ progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
676
+ progress_bar = gr.HTML('', elem_classes='no-generating-animation')
677
+
678
+ with gr.Row(visible=False):
679
+ gr.Examples(
680
+ examples = [
681
+ [
682
+ "./img_examples/Example1.mp4", # input_video
683
+ "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",
684
+ "", # n_prompt
685
+ 42, # seed
686
+ 1, # batch
687
+ 640, # resolution
688
+ 1, # total_second_length
689
+ 9, # latent_window_size
690
+ 25, # steps
691
+ 1.0, # cfg
692
+ 10.0, # gs
693
+ 0.0, # rs
694
+ 6, # gpu_memory_preservation
695
+ True, # use_teacache
696
+ False, # no_resize
697
+ 16, # mp4_crf
698
+ 5, # num_clean_frames
699
+ default_vae
700
+ ],
701
+ ],
702
+ run_on_click = True,
703
+ fn = process,
704
+ inputs = [input_video, 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],
705
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
706
+ cache_examples = True,
707
+ )
708
+
709
+ gr.HTML("""
710
+ <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>
711
+ """)
712
+
713
+ ips = [input_video, 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]
714
+ start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
715
+ end_button.click(fn=end_process)
716
+
717
+
718
+ def handle_field_debug_change(input_video_debug_data, prompt_debug_data, total_second_length_debug_data):
719
+ global input_video_debug_value, prompt_debug_value, total_second_length_debug_value
720
+ input_video_debug_value = input_video_debug_data
721
+ prompt_debug_value = prompt_debug_data
722
+ total_second_length_debug_value = total_second_length_debug_data
723
+ return []
724
+
725
+ input_video_debug.upload(
726
+ fn=handle_field_debug_change,
727
+ inputs=[input_video_debug, prompt_debug, total_second_length_debug],
728
+ outputs=[]
729
+ )
730
+
731
+ prompt_debug.change(
732
+ fn=handle_field_debug_change,
733
+ inputs=[input_video_debug, prompt_debug, total_second_length_debug],
734
+ outputs=[]
735
+ )
736
+
737
+ total_second_length_debug.change(
738
+ fn=handle_field_debug_change,
739
+ inputs=[input_video_debug, prompt_debug, total_second_length_debug],
740
+ outputs=[]
741
+ )
742
+
743
+ block.launch(ssr_mode=False)