Fabrice-TIERCELIN commited on
Commit
cf30012
·
verified ·
1 Parent(s): 6327f36

print("File: " + output_filename)

Browse files
Files changed (1) hide show
  1. app_v2v.py +740 -738
app_v2v.py CHANGED
@@ -1,738 +1,740 @@
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 input_video_debug_value is not None:
549
- input_video = input_video_debug_value
550
- input_video_debug_value = None
551
-
552
- if prompt_debug_value is not None:
553
- prompt = prompt_debug_value
554
- prompt_debug_value = None
555
-
556
- if total_second_length_debug_value is not None:
557
- total_second_length = total_second_length_debug_value
558
- total_second_length_debug_value = None
559
-
560
- # 20250506 pftq: Updated assertion for video input
561
- assert input_video is not None, 'No input video!'
562
-
563
- yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
564
-
565
- # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
566
- if high_vram and (no_resize or resolution>640):
567
- print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
568
- high_vram = False
569
- vae.enable_slicing()
570
- vae.enable_tiling()
571
- DynamicSwapInstaller.install_model(transformer, device=gpu)
572
- DynamicSwapInstaller.install_model(text_encoder, device=gpu)
573
-
574
- # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
575
- if cfg > 1:
576
- gs = 1
577
-
578
- stream = AsyncStream()
579
-
580
- # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
581
- 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)
582
-
583
- output_filename = None
584
-
585
- while True:
586
- flag, data = stream.output_queue.next()
587
-
588
- if flag == 'file':
589
- output_filename = data
590
- yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
591
-
592
- if flag == 'progress':
593
- preview, desc, html = data
594
- #yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
595
- 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
596
-
597
- if flag == 'end':
598
- yield output_filename, gr.update(visible=False), desc+' Video complete.', '', gr.update(interactive=True), gr.update(interactive=False)
599
- break
600
-
601
- def end_process():
602
- stream.input_queue.push('end')
603
-
604
- quick_prompts = [
605
- 'The girl dances gracefully, with clear movements, full of charm.',
606
- 'A character doing some simple body movements.',
607
- ]
608
- quick_prompts = [[x] for x in quick_prompts]
609
-
610
- css = make_progress_bar_css()
611
- block = gr.Blocks(css=css).queue()
612
- with block:
613
- gr.Markdown('# Framepack F1 (Video Extender)')
614
- with gr.Row():
615
- with gr.Column():
616
- # 20250506 pftq: Changed to Video input from Image
617
- input_video = gr.Video(sources='upload', label="Input Video", height=320)
618
- prompt = gr.Textbox(label="Prompt", value='')
619
- #example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Quick List', samples_per_page=1000, components=[prompt])
620
- #example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False)
621
-
622
- with gr.Row():
623
- start_button = gr.Button(value="Start Generation", variant="primary")
624
- end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
625
-
626
- with gr.Group():
627
- with gr.Row():
628
- use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
629
- no_resize = gr.Checkbox(label='Force Original Video Resolution (No Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
630
-
631
- seed = gr.Number(label="Seed", value=31337, precision=0)
632
-
633
- 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.')
634
-
635
- resolution = gr.Number(label="Resolution (max width or height)", value=640, precision=0, visible=False)
636
-
637
- total_second_length = gr.Slider(label="Additional Video Length to Generate (Seconds)", minimum=1, maximum=120, value=1, step=0.1)
638
-
639
- 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.')
640
- 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
641
- rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, visible=False) # Should not change
642
-
643
- 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).')
644
- 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.')
645
-
646
- 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.")
647
-
648
- default_vae = 32
649
- if high_vram:
650
- default_vae = 128
651
- elif free_mem_gb>=20:
652
- default_vae = 64
653
-
654
- 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.")
655
-
656
- 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.')
657
-
658
- 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.")
659
-
660
- 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. ")
661
-
662
- with gr.Row():
663
- input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
664
- prompt_debug = gr.Textbox(label="Prompt Debug", value='')
665
- total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)
666
-
667
- with gr.Column():
668
- preview_image = gr.Image(label="Next Latents", height=200, visible=False)
669
- result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
670
- progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
671
- progress_bar = gr.HTML('', elem_classes='no-generating-animation')
672
-
673
- with gr.Row(visible=False):
674
- gr.Examples(
675
- examples = [
676
- [
677
- "./img_examples/Example1.mp4", # input_video
678
- "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",
679
- "", # n_prompt
680
- 42, # seed
681
- 1, # batch
682
- 640, # resolution
683
- 1, # total_second_length
684
- 9, # latent_window_size
685
- 25, # steps
686
- 1.0, # cfg
687
- 10.0, # gs
688
- 0.0, # rs
689
- 6, # gpu_memory_preservation
690
- True, # use_teacache
691
- False, # no_resize
692
- 16, # mp4_crf
693
- 5, # num_clean_frames
694
- default_vae
695
- ],
696
- ],
697
- run_on_click = True,
698
- fn = process,
699
- 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],
700
- outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
701
- cache_examples = True,
702
- )
703
-
704
- gr.HTML("""
705
- <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>
706
- """)
707
-
708
- 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]
709
- start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
710
- end_button.click(fn=end_process)
711
-
712
-
713
- def handle_field_debug_change(input_video_debug_data, prompt_debug_data, total_second_length_debug_data):
714
- global input_video_debug_value, prompt_debug_value, total_second_length_debug_value
715
- input_video_debug_value = input_video_debug_data
716
- prompt_debug_value = prompt_debug_data
717
- total_second_length_debug_value = total_second_length_debug_data
718
- return []
719
-
720
- input_video_debug.upload(
721
- fn=handle_field_debug_change,
722
- inputs=[input_video_debug, prompt_debug, total_second_length_debug],
723
- outputs=[]
724
- )
725
-
726
- prompt_debug.change(
727
- fn=handle_field_debug_change,
728
- inputs=[input_video_debug, prompt_debug, total_second_length_debug],
729
- outputs=[]
730
- )
731
-
732
- total_second_length_debug.change(
733
- fn=handle_field_debug_change,
734
- inputs=[input_video_debug, prompt_debug, total_second_length_debug],
735
- outputs=[]
736
- )
737
-
738
- 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
+ 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 input_video_debug_value is not None:
549
+ input_video = input_video_debug_value
550
+ input_video_debug_value = None
551
+
552
+ if prompt_debug_value is not None:
553
+ prompt = prompt_debug_value
554
+ prompt_debug_value = None
555
+
556
+ if total_second_length_debug_value is not None:
557
+ total_second_length = total_second_length_debug_value
558
+ total_second_length_debug_value = None
559
+
560
+ # 20250506 pftq: Updated assertion for video input
561
+ assert input_video is not None, 'No input video!'
562
+
563
+ yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
564
+
565
+ # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
566
+ if high_vram and (no_resize or resolution>640):
567
+ print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
568
+ high_vram = False
569
+ vae.enable_slicing()
570
+ vae.enable_tiling()
571
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
572
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
573
+
574
+ # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
575
+ if cfg > 1:
576
+ gs = 1
577
+
578
+ stream = AsyncStream()
579
+
580
+ # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
581
+ 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)
582
+
583
+ output_filename = None
584
+
585
+ while True:
586
+ flag, data = stream.output_queue.next()
587
+
588
+ if flag == 'file':
589
+ output_filename = data
590
+ print("File: " + output_filename)
591
+ yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
592
+
593
+ if flag == 'progress':
594
+ preview, desc, html = data
595
+ #yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
596
+ 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
597
+
598
+ if flag == 'end':
599
+ print("End: " + output_filename)
600
+ yield output_filename, gr.update(visible=False), desc+' Video complete.', '', gr.update(interactive=True), gr.update(interactive=False)
601
+ break
602
+
603
+ def end_process():
604
+ stream.input_queue.push('end')
605
+
606
+ quick_prompts = [
607
+ 'The girl dances gracefully, with clear movements, full of charm.',
608
+ 'A character doing some simple body movements.',
609
+ ]
610
+ quick_prompts = [[x] for x in quick_prompts]
611
+
612
+ css = make_progress_bar_css()
613
+ block = gr.Blocks(css=css).queue()
614
+ with block:
615
+ gr.Markdown('# Framepack F1 (Video Extender)')
616
+ with gr.Row():
617
+ with gr.Column():
618
+ # 20250506 pftq: Changed to Video input from Image
619
+ input_video = gr.Video(sources='upload', label="Input Video", height=320)
620
+ prompt = gr.Textbox(label="Prompt", value='')
621
+ #example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Quick List', samples_per_page=1000, components=[prompt])
622
+ #example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False)
623
+
624
+ with gr.Row():
625
+ start_button = gr.Button(value="Start Generation", variant="primary")
626
+ end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
627
+
628
+ with gr.Group():
629
+ with gr.Row():
630
+ use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
631
+ no_resize = gr.Checkbox(label='Force Original Video Resolution (No Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
632
+
633
+ seed = gr.Number(label="Seed", value=31337, precision=0)
634
+
635
+ 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.')
636
+
637
+ resolution = gr.Number(label="Resolution (max width or height)", value=640, precision=0, visible=False)
638
+
639
+ total_second_length = gr.Slider(label="Additional Video Length to Generate (Seconds)", minimum=1, maximum=120, value=1, step=0.1)
640
+
641
+ 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.')
642
+ 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
643
+ rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, visible=False) # Should not change
644
+
645
+ 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).')
646
+ 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.')
647
+
648
+ 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.")
649
+
650
+ default_vae = 32
651
+ if high_vram:
652
+ default_vae = 128
653
+ elif free_mem_gb>=20:
654
+ default_vae = 64
655
+
656
+ 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.")
657
+
658
+ 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.')
659
+
660
+ 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.")
661
+
662
+ 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. ")
663
+
664
+ with gr.Row():
665
+ input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
666
+ prompt_debug = gr.Textbox(label="Prompt Debug", value='')
667
+ total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)
668
+
669
+ with gr.Column():
670
+ preview_image = gr.Image(label="Next Latents", height=200, visible=False)
671
+ result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
672
+ progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
673
+ progress_bar = gr.HTML('', elem_classes='no-generating-animation')
674
+
675
+ with gr.Row(visible=False):
676
+ gr.Examples(
677
+ examples = [
678
+ [
679
+ "./img_examples/Example1.mp4", # input_video
680
+ "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",
681
+ "", # n_prompt
682
+ 42, # seed
683
+ 1, # batch
684
+ 640, # resolution
685
+ 1, # total_second_length
686
+ 9, # latent_window_size
687
+ 25, # steps
688
+ 1.0, # cfg
689
+ 10.0, # gs
690
+ 0.0, # rs
691
+ 6, # gpu_memory_preservation
692
+ True, # use_teacache
693
+ False, # no_resize
694
+ 16, # mp4_crf
695
+ 5, # num_clean_frames
696
+ default_vae
697
+ ],
698
+ ],
699
+ run_on_click = True,
700
+ fn = process,
701
+ 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],
702
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
703
+ cache_examples = True,
704
+ )
705
+
706
+ gr.HTML("""
707
+ <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>
708
+ """)
709
+
710
+ 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]
711
+ start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
712
+ end_button.click(fn=end_process)
713
+
714
+
715
+ def handle_field_debug_change(input_video_debug_data, prompt_debug_data, total_second_length_debug_data):
716
+ global input_video_debug_value, prompt_debug_value, total_second_length_debug_value
717
+ input_video_debug_value = input_video_debug_data
718
+ prompt_debug_value = prompt_debug_data
719
+ total_second_length_debug_value = total_second_length_debug_data
720
+ return []
721
+
722
+ input_video_debug.upload(
723
+ fn=handle_field_debug_change,
724
+ inputs=[input_video_debug, prompt_debug, total_second_length_debug],
725
+ outputs=[]
726
+ )
727
+
728
+ prompt_debug.change(
729
+ fn=handle_field_debug_change,
730
+ inputs=[input_video_debug, prompt_debug, total_second_length_debug],
731
+ outputs=[]
732
+ )
733
+
734
+ total_second_length_debug.change(
735
+ fn=handle_field_debug_change,
736
+ inputs=[input_video_debug, prompt_debug, total_second_length_debug],
737
+ outputs=[]
738
+ )
739
+
740
+ block.launch(ssr_mode=False)