This Pull Request also extends a video & optimizes time & VRAM

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

Git LFS Details

  • SHA256: b1a9be93d2f117d687e08c91c043e67598bdb7c44f5c932f18a3026790fb82fa
  • Pointer size: 131 Bytes
  • Size of remote file: 208 kB
img_examples/Example4.webp ADDED

Git LFS Details

  • SHA256: dd4e7ef35f4cfc8d44ff97f38b68ba7cc248ad5b54c89f8525f5046508f7c4a3
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
requirements.txt CHANGED
@@ -1,12 +1,12 @@
1
- accelerate==1.6.0
2
  diffusers==0.33.1
3
- transformers==4.46.2
4
  sentencepiece==0.2.0
5
- pillow==11.1.0
6
  av==12.1.0
7
  numpy==1.26.2
8
  scipy==1.12.0
9
- requests==2.31.0
10
  torchsde==0.2.6
11
  torch>=2.0.0
12
  torchvision
@@ -15,4 +15,10 @@ einops
15
  opencv-contrib-python
16
  safetensors
17
  huggingface_hub
18
- spaces
 
 
 
 
 
 
 
1
+ accelerate==1.7.0
2
  diffusers==0.33.1
3
+ transformers==4.52.4
4
  sentencepiece==0.2.0
5
+ pillow==11.2.1
6
  av==12.1.0
7
  numpy==1.26.2
8
  scipy==1.12.0
9
+ requests==2.32.4
10
  torchsde==0.2.6
11
  torch>=2.0.0
12
  torchvision
 
15
  opencv-contrib-python
16
  safetensors
17
  huggingface_hub
18
+ decord
19
+ imageio_ffmpeg
20
+ sageattention==1.0.6
21
+ xformers==0.0.29.post3
22
+ bitsandbytes==0.46.0
23
+ pillow-heif==0.22.0
24
+ spaces[security]