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

#2
.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.29.0
8
- app_file: app.py
9
  pinned: false
 
 
10
  license: apache-2.0
11
- short_description: fast video generation from images & text
 
 
 
 
 
 
 
 
12
  ---
13
 
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: false
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
 
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,128 +38,293 @@ 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
 
@@ -164,54 +347,50 @@ 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 +400,102 @@ 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 +528,276 @@ 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 +809,54 @@ 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 +865,457 @@ 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):
310
+ is_last_frame = (image_position == 100)
311
+ def encode_prompt(prompt, n_prompt):
312
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
313
 
314
+ if cfg == 1:
315
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
316
+ else:
317
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
318
 
319
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
320
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
 
321
 
322
+ llama_vec = llama_vec.to(transformer.dtype)
323
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
324
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
325
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
326
+ return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
327
 
 
 
 
328
  total_latent_sections = (total_second_length * 30) / (latent_window_size * 4)
329
  total_latent_sections = int(max(round(total_latent_sections), 1))
330
 
 
347
  fake_diffusers_current_device(text_encoder, gpu) # since we only encode one text - that is one model move and one encode, offload is same time consumption since it is also one load and one encode.
348
  load_model_as_complete(text_encoder_2, target_device=gpu)
349
 
350
+ prompt_parameters = []
351
 
352
+ for prompt_part in prompts:
353
+ prompt_parameters.append(encode_prompt(prompt_part, n_prompt))
 
 
 
 
 
354
 
355
  # Processing input image
356
 
357
  stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))
358
 
359
  H, W, C = input_image.shape
360
+ height, width = find_nearest_bucket(H, W, resolution=resolution)
361
+
362
+ def get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram):
363
+ input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)
364
+
365
+ #Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
366
+
367
+ input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1
368
+ input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]
369
+
370
+ # VAE encoding
371
+
372
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))
373
+
374
+ if not high_vram:
375
+ load_model_as_complete(vae, target_device=gpu)
376
+
377
+ start_latent = vae_encode(input_image_pt, vae)
378
+
379
+ # CLIP Vision
380
+
381
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
382
+
383
+ if not high_vram:
384
+ load_model_as_complete(image_encoder, target_device=gpu)
385
 
386
+ image_encoder_last_hidden_state = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder).last_hidden_state
387
+
388
+ return [start_latent, image_encoder_last_hidden_state]
389
+
390
+ [start_latent, image_encoder_last_hidden_state] = get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram)
391
 
392
  # Dtype
393
 
 
 
 
 
394
  image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
395
 
396
  # Sampling
 
400
  rnd = torch.Generator("cpu").manual_seed(seed)
401
 
402
  history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()
403
+ start_latent = start_latent.to(history_latents)
404
  history_pixels = None
405
 
406
+ history_latents = torch.cat([start_latent, history_latents] if is_last_frame else [history_latents, start_latent], dim=2)
407
  total_generated_latent_frames = 1
408
 
409
+ if enable_preview:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  def callback(d):
411
  preview = d['denoised']
412
  preview = vae_decode_fake(preview)
413
+
414
  preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
415
  preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
416
+
417
  if stream.input_queue.top() == 'end':
418
  stream.output_queue.push(('end', None))
419
  raise KeyboardInterrupt('User ends the task.')
420
+
421
  current_step = d['i'] + 1
422
  percentage = int(100.0 * current_step / steps)
423
  hint = f'Sampling {current_step}/{steps}'
424
+ desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / 30) :.2f} seconds (FPS-30), Resolution: {height}px * {width}px. The video is being extended now ...'
425
  stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
426
  return
427
+ else:
428
+ def callback(d):
429
+ return
430
 
431
+ indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0)
432
+ if is_last_frame:
433
+ latent_indices, clean_latent_1x_indices, clean_latent_2x_indices, clean_latent_4x_indices, clean_latent_indices_start = indices.split([latent_window_size, 1, 2, 16, 1], dim=1)
434
+ clean_latent_indices = torch.cat([clean_latent_1x_indices, clean_latent_indices_start], dim=1)
435
+ else:
436
  clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split([1, 16, 2, 1, latent_window_size], dim=1)
437
  clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
438
 
439
+ def post_process(generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, section_index, total_latent_sections, outputs_folder, mp4_crf, stream):
440
+ total_generated_latent_frames += int(generated_latents.shape[2])
441
+ history_latents = torch.cat([generated_latents.to(history_latents), history_latents], dim=2) if is_last_frame else torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
442
+
443
+ if not high_vram:
444
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
445
+ load_model_as_complete(vae, target_device=gpu)
446
+
447
+ if history_pixels is None:
448
+ real_history_latents = history_latents[:, :, :total_generated_latent_frames, :, :] if is_last_frame else history_latents[:, :, -total_generated_latent_frames:, :, :]
449
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
450
+ else:
451
+ section_latent_frames = latent_window_size * 2
452
+ overlapped_frames = latent_window_size * 4 - 3
453
+
454
+ if is_last_frame:
455
+ real_history_latents = history_latents[:, :, :min(section_latent_frames, total_generated_latent_frames), :, :]
456
+ history_pixels = soft_append_bcthw(vae_decode(real_history_latents, vae).cpu(), history_pixels, overlapped_frames)
457
+ else:
458
+ real_history_latents = history_latents[:, :, -min(section_latent_frames, total_generated_latent_frames):, :, :]
459
+ history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames)
460
+
461
+ if not high_vram:
462
+ unload_complete_models()
463
+
464
+ if enable_preview or section_index == (0 if is_last_frame else (total_latent_sections - 1)):
465
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
466
+
467
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=30, crf=mp4_crf)
468
+
469
+ print(f'Decoded. Current latent shape pixel shape {history_pixels.shape}')
470
+
471
+ stream.output_queue.push(('file', output_filename))
472
+ return [total_generated_latent_frames, history_latents, history_pixels]
473
+
474
+ for section_index in range(total_latent_sections - 1, -1, -1) if is_last_frame else range(total_latent_sections):
475
+ if stream.input_queue.top() == 'end':
476
+ stream.output_queue.push(('end', None))
477
+ return
478
+
479
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
480
+
481
+ if len(prompt_parameters) > 0:
482
+ [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters.pop((len(prompt_parameters) - 1) if is_last_frame else 0)
483
+
484
+ if not high_vram:
485
+ unload_complete_models()
486
+ move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
487
+
488
+ if use_teacache:
489
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
490
+ else:
491
+ transformer.initialize_teacache(enable_teacache=False)
492
+
493
+ if is_last_frame:
494
+ clean_latents_1x, clean_latents_2x, clean_latents_4x = history_latents[:, :, :sum([1, 2, 16]), :, :].split([1, 2, 16], dim=2)
495
+ clean_latents = torch.cat([clean_latents_1x, start_latent], dim=2)
496
+ else:
497
+ clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -sum([16, 2, 1]):, :, :].split([16, 2, 1], dim=2)
498
+ clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
499
 
500
  generated_latents = sample_hunyuan(
501
  transformer=transformer,
 
528
  callback=callback,
529
  )
530
 
531
+ [total_generated_latent_frames, history_latents, history_pixels] = post_process(generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, section_index, total_latent_sections, outputs_folder, mp4_crf, stream)
532
+ except:
533
+ traceback.print_exc()
534
 
535
+ if not high_vram:
536
+ unload_complete_models(
537
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
538
+ )
539
 
540
+ stream.output_queue.push(('end', None))
541
+ return
542
 
543
+ # 20250506 pftq: Modified worker to accept video input and clean frame count
544
+ @torch.no_grad()
545
+ def worker_video(input_video, prompts, n_prompt, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):
546
+ def encode_prompt(prompt, n_prompt):
547
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
548
 
549
+ if cfg == 1:
550
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
551
+ else:
552
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
553
 
554
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
555
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
556
+
557
+ llama_vec = llama_vec.to(transformer.dtype)
558
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
559
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
560
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
561
+ return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
562
+
563
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
564
+
565
+ try:
566
+ # Clean GPU
567
+ if not high_vram:
568
+ unload_complete_models(
569
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
570
+ )
571
+
572
+ # Text encoding
573
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
574
+
575
+ if not high_vram:
576
+ fake_diffusers_current_device(text_encoder, gpu) # since we only encode one text - that is one model move and one encode, offload is same time consumption since it is also one load and one encode.
577
+ load_model_as_complete(text_encoder_2, target_device=gpu)
578
 
579
+ prompt_parameters = []
580
 
581
+ for prompt_part in prompts:
582
+ prompt_parameters.append(encode_prompt(prompt_part, n_prompt))
583
+
584
+ # 20250506 pftq: Processing input video instead of image
585
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
586
+
587
+ # 20250506 pftq: Encode video
588
+ start_latent, input_image_np, video_latents, fps, height, width = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)[:6]
589
+ start_latent = start_latent.to(dtype=torch.float32).cpu()
590
+ video_latents = video_latents.cpu()
591
+
592
+ # CLIP Vision
593
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
594
+
595
+ if not high_vram:
596
+ load_model_as_complete(image_encoder, target_device=gpu)
597
+
598
+ image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
599
+ image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
600
+
601
+ # Dtype
602
+ image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
603
 
604
+ total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
605
+ total_latent_sections = int(max(round(total_latent_sections), 1))
606
+
607
+ if enable_preview:
608
+ def callback(d):
609
+ preview = d['denoised']
610
+ preview = vae_decode_fake(preview)
611
+
612
+ preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
613
+ preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
614
+
615
+ if stream.input_queue.top() == 'end':
616
+ stream.output_queue.push(('end', None))
617
+ raise KeyboardInterrupt('User ends the task.')
618
+
619
+ current_step = d['i'] + 1
620
+ percentage = int(100.0 * current_step / steps)
621
+ hint = f'Sampling {current_step}/{steps}'
622
+ desc = f'Total frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / fps) :.2f} seconds (FPS-{fps}), Resolution: {height}px * {width}px, Seed: {seed}, Video {idx+1} of {batch}. The video is generating part {section_index+1} of {total_latent_sections}...'
623
+ stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
624
+ return
625
+ else:
626
+ def callback(d):
627
+ return
628
+
629
+ def compute_latent(history_latents, latent_window_size, num_clean_frames, start_latent):
630
+ # 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2
631
+ available_frames = history_latents.shape[2] # Number of latent frames
632
+ max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames
633
+ adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames
634
+ # Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x
635
+ effective_clean_frames = max(0, num_clean_frames - 1)
636
+ effective_clean_frames = min(effective_clean_frames, available_frames - 2) if available_frames > 2 else 0 # 20250507 pftq: changed 1 to 2 for edge case for <=1 sec videos
637
+ num_2x_frames = min(2, max(1, available_frames - effective_clean_frames - 1)) if available_frames > effective_clean_frames + 1 else 0 # 20250507 pftq: subtracted 1 for edge case for <=1 sec videos
638
+ num_4x_frames = min(16, max(1, available_frames - effective_clean_frames - num_2x_frames)) if available_frames > effective_clean_frames + num_2x_frames else 0 # 20250507 pftq: Edge case for <=1 sec
639
+
640
+ total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
641
+ total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos
642
+
643
+ indices = torch.arange(0, sum([1, num_4x_frames, num_2x_frames, effective_clean_frames, adjusted_latent_frames])).unsqueeze(0) # 20250507 pftq: latent_window_size to adjusted_latent_frames for edge case for <=1 sec videos
644
+ clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
645
+ [1, num_4x_frames, num_2x_frames, effective_clean_frames, adjusted_latent_frames], dim=1 # 20250507 pftq: latent_window_size to adjusted_latent_frames for edge case for <=1 sec videos
646
+ )
647
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
648
+
649
+ # 20250506 pftq: Split history_latents dynamically based on available frames
650
+ fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos
651
+ context_frames = clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
652
+
653
+ if total_context_frames > 0:
654
+ context_frames = history_latents[:, :, -total_context_frames:, :, :]
655
+ split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames]
656
+ split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes
657
+ if split_sizes:
658
+ splits = context_frames.split(split_sizes, dim=2)
659
+ split_idx = 0
660
+
661
+ if num_4x_frames > 0:
662
+ clean_latents_4x = splits[split_idx]
663
+ split_idx = 1
664
+ if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
665
+ print("Edge case for <=1 sec videos 4x")
666
+ clean_latents_4x = clean_latents_4x.expand(-1, -1, 2, -1, -1)
667
+
668
+ if num_2x_frames > 0 and split_idx < len(splits):
669
+ clean_latents_2x = splits[split_idx]
670
+ if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
671
+ print("Edge case for <=1 sec videos 2x")
672
+ clean_latents_2x = clean_latents_2x.expand(-1, -1, 2, -1, -1)
673
+ split_idx += 1
674
+ elif clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
675
+ clean_latents_2x = clean_latents_4x
676
+
677
+ if effective_clean_frames > 0 and split_idx < len(splits):
678
+ clean_latents_1x = splits[split_idx]
679
+
680
+ clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
681
+
682
+ # 20250507 pftq: Fix for <=1 sec videos.
683
+ max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
684
+ return [max_frames, clean_latents, clean_latents_2x, clean_latents_4x, latent_indices, clean_latents, clean_latent_indices, clean_latent_2x_indices, clean_latent_4x_indices]
685
+
686
+ for idx in range(batch):
687
+ if batch > 1:
688
+ print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
689
+
690
+ #job_id = generate_timestamp()
691
+ job_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+f"_framepackf1-videoinput_{width}-{total_second_length}sec_seed-{seed}_steps-{steps}_distilled-{gs}_cfg-{cfg}" # 20250506 pftq: easier to read timestamp and filename
692
+
693
+ # Sampling
694
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
695
+
696
+ rnd = torch.Generator("cpu").manual_seed(seed)
697
+
698
+ # 20250506 pftq: Initialize history_latents with video latents
699
+ history_latents = video_latents
700
+ total_generated_latent_frames = history_latents.shape[2]
701
+ # 20250506 pftq: Initialize history_pixels to fix UnboundLocalError
702
+ history_pixels = None
703
+ previous_video = None
704
+
705
+ for section_index in range(total_latent_sections):
706
+ if stream.input_queue.top() == 'end':
707
+ stream.output_queue.push(('end', None))
708
+ return
709
+
710
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
711
+
712
+ if len(prompt_parameters) > 0:
713
+ [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters.pop(0)
714
+
715
+ if not high_vram:
716
+ unload_complete_models()
717
+ move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
718
+
719
+ if use_teacache:
720
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
721
+ else:
722
+ transformer.initialize_teacache(enable_teacache=False)
723
+
724
+ [max_frames, clean_latents, clean_latents_2x, clean_latents_4x, latent_indices, clean_latents, clean_latent_indices, clean_latent_2x_indices, clean_latent_4x_indices] = compute_latent(history_latents, latent_window_size, num_clean_frames, start_latent)
725
+
726
+ generated_latents = sample_hunyuan(
727
+ transformer=transformer,
728
+ sampler='unipc',
729
+ width=width,
730
+ height=height,
731
+ frames=max_frames,
732
+ real_guidance_scale=cfg,
733
+ distilled_guidance_scale=gs,
734
+ guidance_rescale=rs,
735
+ num_inference_steps=steps,
736
+ generator=rnd,
737
+ prompt_embeds=llama_vec,
738
+ prompt_embeds_mask=llama_attention_mask,
739
+ prompt_poolers=clip_l_pooler,
740
+ negative_prompt_embeds=llama_vec_n,
741
+ negative_prompt_embeds_mask=llama_attention_mask_n,
742
+ negative_prompt_poolers=clip_l_pooler_n,
743
+ device=gpu,
744
+ dtype=torch.bfloat16,
745
+ image_embeddings=image_encoder_last_hidden_state,
746
+ latent_indices=latent_indices,
747
+ clean_latents=clean_latents,
748
+ clean_latent_indices=clean_latent_indices,
749
+ clean_latents_2x=clean_latents_2x,
750
+ clean_latent_2x_indices=clean_latent_2x_indices,
751
+ clean_latents_4x=clean_latents_4x,
752
+ clean_latent_4x_indices=clean_latent_4x_indices,
753
+ callback=callback,
754
+ )
755
+
756
+ total_generated_latent_frames += int(generated_latents.shape[2])
757
+ history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
758
+
759
+ if not high_vram:
760
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
761
+ load_model_as_complete(vae, target_device=gpu)
762
+
763
+ if history_pixels is None:
764
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
765
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
766
+ else:
767
+ section_latent_frames = latent_window_size * 2
768
+ overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2])
769
+
770
+ real_history_latents = history_latents[:, :, -min(total_generated_latent_frames, section_latent_frames):, :, :]
771
+ history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames)
772
+
773
+ if not high_vram:
774
+ unload_complete_models()
775
+
776
+ if enable_preview or section_index == total_latent_sections - 1:
777
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
778
+
779
+ # 20250506 pftq: Use input video FPS for output
780
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
781
+ print(f"Latest video saved: {output_filename}")
782
+ # 20250508 pftq: Save prompt to mp4 metadata comments
783
+ set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompts} | Negative Prompt: {n_prompt}");
784
+ print(f"Prompt saved to mp4 metadata comments: {output_filename}")
785
+
786
+ # 20250506 pftq: Clean up previous partial files
787
+ if previous_video is not None and os.path.exists(previous_video):
788
+ try:
789
+ os.remove(previous_video)
790
+ print(f"Previous partial video deleted: {previous_video}")
791
+ except Exception as e:
792
+ print(f"Error deleting previous partial video {previous_video}: {e}")
793
+ previous_video = output_filename
794
+
795
+ print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
796
+
797
+ stream.output_queue.push(('file', output_filename))
798
+
799
+ seed = (seed + 1) % np.iinfo(np.int32).max
800
 
 
801
  except:
802
  traceback.print_exc()
803
 
 
809
  stream.output_queue.push(('end', None))
810
  return
811
 
812
+ def get_duration(input_image, image_position, prompt, generation_mode, n_prompt, randomize_seed, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf):
813
+ return total_second_length * 60 * (0.9 if use_teacache else 1.5) * (1 + ((steps - 25) / 100))
814
 
815
+ # Remove this decorator if you run on local
816
  @spaces.GPU(duration=get_duration)
817
+ def process(input_image,
818
+ image_position=0,
819
+ prompt="",
820
+ generation_mode="image",
821
+ n_prompt="",
822
+ randomize_seed=True,
823
+ seed=31337,
824
+ resolution=640,
825
+ total_second_length=5,
826
+ latent_window_size=9,
827
+ steps=25,
828
+ cfg=1.0,
829
+ gs=10.0,
830
+ rs=0.0,
831
+ gpu_memory_preservation=6,
832
+ enable_preview=True,
833
+ use_teacache=False,
834
  mp4_crf=16
835
  ):
836
+ start = time.time()
837
  global stream
838
+
839
+ if torch.cuda.device_count() == 0:
840
+ gr.Warning('Set this space to GPU config to make it work.')
841
+ yield gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(visible = False)
842
+ return
843
+
844
+ if randomize_seed:
845
+ seed = random.randint(0, np.iinfo(np.int32).max)
846
+
847
+ prompts = prompt.split(";")
848
+
849
  # assert input_image is not None, 'No input image!'
850
+ if generation_mode == "text":
851
  default_height, default_width = 640, 640
852
  input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
853
  print("No input image provided. Using a blank white image.")
 
 
854
 
855
+ yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.update()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
856
 
857
  stream = AsyncStream()
858
 
859
+ 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)
860
 
861
  output_filename = None
862
 
 
865
 
866
  if flag == 'file':
867
  output_filename = data
868
+ yield gr.update(value=output_filename, label="Previewed Frames"), gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True), gr.update()
869
 
870
  if flag == 'progress':
871
  preview, desc, html = data
872
+ yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.update()
873
 
874
  if flag == 'end':
875
+ end = time.time()
876
+ secondes = int(end - start)
877
+ minutes = math.floor(secondes / 60)
878
+ secondes = secondes - (minutes * 60)
879
+ hours = math.floor(minutes / 60)
880
+ minutes = minutes - (hours * 60)
881
+ yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), gr.update(), "The process has lasted " + \
882
+ ((str(hours) + " h, ") if hours != 0 else "") + \
883
+ ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
884
+ str(secondes) + " sec. " + \
885
+ "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)
886
  break
887
 
888
+ def get_duration_video(input_video, prompt, n_prompt, randomize_seed, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):
889
+ return total_second_length * 60 * (1.5 if use_teacache else 2.5) * (1 + ((steps - 25) / 100))
890
+
891
+ # Remove this decorator if you run on local
892
+ @spaces.GPU(duration=get_duration_video)
893
+ def process_video(input_video, prompt, n_prompt, randomize_seed, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):
894
+ start = time.time()
895
+ global stream, high_vram
896
+
897
+ if torch.cuda.device_count() == 0:
898
+ gr.Warning('Set this space to GPU config to make it work.')
899
+ yield gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(visible = False)
900
+ return
901
+
902
+ if randomize_seed:
903
+ seed = random.randint(0, np.iinfo(np.int32).max)
904
+
905
+ prompts = prompt.split(";")
906
+
907
+ # 20250506 pftq: Updated assertion for video input
908
+ assert input_video is not None, 'No input video!'
909
+
910
+ yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.update()
911
+
912
+ # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
913
+ if high_vram and (no_resize or resolution>640):
914
+ print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
915
+ high_vram = False
916
+ vae.enable_slicing()
917
+ vae.enable_tiling()
918
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
919
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
920
+
921
+ # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
922
+ if cfg > 1:
923
+ gs = 1
924
+
925
+ stream = AsyncStream()
926
+
927
+ # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
928
+ 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)
929
+
930
+ output_filename = None
931
+
932
+ while True:
933
+ flag, data = stream.output_queue.next()
934
+
935
+ if flag == 'file':
936
+ output_filename = data
937
+ yield gr.update(value=output_filename, label="Previewed Frames"), gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True), gr.update()
938
+
939
+ if flag == 'progress':
940
+ preview, desc, html = data
941
+ yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.update() # 20250506 pftq: Keep refreshing the video in case it got hidden when the tab was in the background
942
+
943
+ if flag == 'end':
944
+ end = time.time()
945
+ secondes = int(end - start)
946
+ minutes = math.floor(secondes / 60)
947
+ secondes = secondes - (minutes * 60)
948
+ hours = math.floor(minutes / 60)
949
+ minutes = minutes - (hours * 60)
950
+ yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), desc + \
951
+ " The process has lasted " + \
952
+ ((str(hours) + " h, ") if hours != 0 else "") + \
953
+ ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
954
+ str(secondes) + " sec. " + \
955
+ " 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)
956
+ break
957
 
958
  def end_process():
959
  stream.input_queue.push('end')
960
 
961
+ timeless_prompt_value = [""]
962
+ timed_prompts = {}
963
+
964
+ def handle_prompt_number_change():
965
+ timed_prompts.clear()
966
+ return []
967
 
968
+ def handle_timeless_prompt_change(timeless_prompt):
969
+ timeless_prompt_value[0] = timeless_prompt
970
+ return refresh_prompt()
 
 
971
 
972
+ def handle_timed_prompt_change(timed_prompt_id, timed_prompt):
973
+ timed_prompts[timed_prompt_id] = timed_prompt
974
+ return refresh_prompt()
975
+
976
+ def refresh_prompt():
977
+ dict_values = {k: v for k, v in timed_prompts.items()}
978
+ sorted_dict_values = sorted(dict_values.items(), key=lambda x: x[0])
979
+ array = []
980
+ for sorted_dict_value in sorted_dict_values:
981
+ 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]):
982
+ array.append(timeless_prompt_value[0] + ". " + sorted_dict_value[1])
983
+ else:
984
+ array.append(timeless_prompt_value[0] + sorted_dict_value[1])
985
+ print(str(array))
986
+ return ";".join(array)
987
+
988
+ title_html = """
989
+ <h1><center>FramePack</center></h1>
990
+ <big><center>Generate videos from text/image/video freely, without account, without watermark and download it</center></big>
991
+ <br/>
992
+
993
+ <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>
994
+ """
995
+
996
+ js = """
997
+ function createGradioAnimation() {
998
+ window.addEventListener("beforeunload", function (e) {
999
+ if (document.getElementById('end-button') && !document.getElementById('end-button').disabled) {
1000
+ var confirmationMessage = 'A process is still running. '
1001
+ + 'If you leave before saving, your changes will be lost.';
1002
+
1003
+ (e || window.event).returnValue = confirmationMessage;
1004
+ }
1005
+ return confirmationMessage;
1006
+ });
1007
+ return 'Animation created';
1008
+ }
1009
+ """
1010
 
1011
  css = make_progress_bar_css()
1012
+ block = gr.Blocks(css=css, js=js).queue()
1013
  with block:
1014
+ if torch.cuda.device_count() == 0:
1015
+ with gr.Row():
1016
+ gr.HTML("""
1017
+ <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>
1018
+
1019
+ 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.
1020
+ </big></big></big></p>
1021
  """)
1022
+ gr.HTML(title_html)
1023
+ local_storage = gr.BrowserState(default_local_storage)
1024
  with gr.Row():
1025
  with gr.Column():
1026
+ generation_mode = gr.Radio([["Text-to-Video", "text"], ["Image-to-Video", "image"], ["Video Extension", "video"]], elem_id="generation-mode", label="Generation mode", value = "image")
1027
+ text_to_video_hint = gr.HTML("I discourage to use the Text-to-Video feature. You should rather generate an image with Flux and use Image-to-Video. You will save time.")
1028
+ input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)
1029
+ image_position = gr.Slider(label="Image position", minimum=0, maximum=100, value=0, step=100, info='0=Video start; 100=Video end (lower quality)')
1030
+ input_video = gr.Video(sources='upload', label="Input Video", height=320)
1031
+ 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")
1032
+ prompt_number = gr.Slider(label="Timed prompt number", minimum=0, maximum=1000, value=0, step=1, info='Prompts will automatically appear')
1033
+
1034
+ @gr.render(inputs=prompt_number)
1035
+ def show_split(prompt_number):
1036
+ for digit in range(prompt_number):
1037
+ timed_prompt_id = gr.Textbox(value="timed_prompt_" + str(digit), visible=False)
1038
+ timed_prompt = gr.Textbox(label="Timed prompt #" + str(digit + 1), elem_id="timed_prompt_" + str(digit), value="")
1039
+ timed_prompt.change(fn=handle_timed_prompt_change, inputs=[timed_prompt_id, timed_prompt], outputs=[final_prompt])
1040
+
1041
+ final_prompt = gr.Textbox(label="Final prompt", value='', info='Use ; to separate in time')
1042
+ 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.")
1043
+ total_second_length = gr.Slider(label="Video Length to Generate (seconds)", minimum=1, maximum=120, value=2, step=0.1)
1044
 
1045
  with gr.Row():
1046
+ start_button = gr.Button(value="🎥 Generate", variant="primary")
1047
+ start_button_video = gr.Button(value="🎥 Generate", variant="primary")
1048
+ end_button = gr.Button(elem_id="end-button", value="End Generation", variant="stop", interactive=False)
1049
 
1050
+ with gr.Accordion("Advanced settings", open=False):
1051
+ 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.')
1052
+ 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.')
1053
+
1054
+ n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')
1055
+
1056
+ 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.')
1057
+ 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.')
1058
+
1059
+ with gr.Row():
1060
+ no_resize = gr.Checkbox(label='Force Original Video Resolution (no Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
1061
+ resolution = gr.Dropdown([
1062
+ ["409,600 px (working)", 640],
1063
+ ["451,584 px (working)", 672],
1064
+ ["495,616 px (VRAM pb on HF)", 704],
1065
+ ["589,824 px (not tested)", 768],
1066
+ ["692,224 px (not tested)", 832],
1067
+ ["746,496 px (not tested)", 864],
1068
+ ["921,600 px (not tested)", 960]
1069
+ ], value=672, label="Resolution (width x height)", info="Do not affect the generation time")
1070
+
1071
+ # 20250506 pftq: Reduced default distilled guidance scale to improve adherence to input video
1072
+ 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.')
1073
+ 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')
1074
+ rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, info='Should not change')
1075
+
1076
+
1077
+ # 20250506 pftq: Renamed slider to Number of Context Frames and updated description
1078
+ 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.")
1079
+
1080
+ default_vae = 32
1081
+ if high_vram:
1082
+ default_vae = 128
1083
+ elif free_mem_gb>=20:
1084
+ default_vae = 64
1085
+
1086
+ 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.")
1087
+
1088
+
1089
+ 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.")
1090
+
1091
+ 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. ")
1092
+ 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.')
1093
+ with gr.Row():
1094
+ randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
1095
+ seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
1096
 
1097
  with gr.Column():
1098
+ warning = gr.HTML(value = "<center><big>Your computer must <u>not</u> enter into standby mode.</big><br/>On Chrome, you can force to keep a tab alive in <code>chrome://discards/</code></center>", visible = False)
1099
+ result_video = gr.Video(label="Generated Frames", autoplay=True, show_share_button=False, height=512, loop=True)
1100
  preview_image = gr.Image(label="Next Latents", height=200, visible=False)
 
1101
  progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
1102
  progress_bar = gr.HTML('', elem_classes='no-generating-animation')
1103
 
1104
+ # 20250506 pftq: Updated inputs to include num_clean_frames
1105
+ ips = [input_image, image_position, final_prompt, generation_mode, n_prompt, randomize_seed, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf]
1106
+ ips_video = [input_video, final_prompt, n_prompt, randomize_seed, seed, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch]
1107
+
1108
+ gr.Examples(
1109
+ label = "Examples from image",
1110
+ examples = [
1111
+ [
1112
+ "./img_examples/Example1.png", # input_image
1113
+ 0, # image_position
1114
+ "A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
1115
+ "image", # generation_mode
1116
+ "Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
1117
+ True, # randomize_seed
1118
+ 42, # seed
1119
+ 672, # resolution
1120
+ 1, # total_second_length
1121
+ 9, # latent_window_size
1122
+ 30, # steps
1123
+ 1.0, # cfg
1124
+ 10.0, # gs
1125
+ 0.0, # rs
1126
+ 6, # gpu_memory_preservation
1127
+ False, # enable_preview
1128
+ True, # use_teacache
1129
+ 16 # mp4_crf
1130
+ ],
1131
+ [
1132
+ "./img_examples/Example2.webp", # input_image
1133
+ 0, # image_position
1134
+ "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",
1135
+ "image", # generation_mode
1136
+ "Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
1137
+ True, # randomize_seed
1138
+ 42, # seed
1139
+ 672, # resolution
1140
+ 2, # total_second_length
1141
+ 9, # latent_window_size
1142
+ 30, # steps
1143
+ 1.0, # cfg
1144
+ 10.0, # gs
1145
+ 0.0, # rs
1146
+ 6, # gpu_memory_preservation
1147
+ False, # enable_preview
1148
+ True, # use_teacache
1149
+ 16 # mp4_crf
1150
+ ],
1151
+ [
1152
+ "./img_examples/Example2.webp", # input_image
1153
+ 0, # image_position
1154
+ "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",
1155
+ "image", # generation_mode
1156
+ "Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
1157
+ True, # randomize_seed
1158
+ 42, # seed
1159
+ 672, # resolution
1160
+ 2, # total_second_length
1161
+ 9, # latent_window_size
1162
+ 30, # steps
1163
+ 1.0, # cfg
1164
+ 10.0, # gs
1165
+ 0.0, # rs
1166
+ 6, # gpu_memory_preservation
1167
+ False, # enable_preview
1168
+ True, # use_teacache
1169
+ 16 # mp4_crf
1170
+ ],
1171
+ [
1172
+ "./img_examples/Example3.jpg", # input_image
1173
+ 0, # image_position
1174
+ "A boy is walking to the right, full view, full-length view, cartoon",
1175
+ "image", # generation_mode
1176
+ "Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
1177
+ True, # randomize_seed
1178
+ 42, # seed
1179
+ 672, # resolution
1180
+ 1, # total_second_length
1181
+ 9, # latent_window_size
1182
+ 30, # steps
1183
+ 1.0, # cfg
1184
+ 10.0, # gs
1185
+ 0.0, # rs
1186
+ 6, # gpu_memory_preservation
1187
+ False, # enable_preview
1188
+ True, # use_teacache
1189
+ 16 # mp4_crf
1190
+ ],
1191
+ [
1192
+ "./img_examples/Example4.webp", # input_image
1193
+ 100, # image_position
1194
+ "A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
1195
+ "image", # generation_mode
1196
+ "Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
1197
+ True, # randomize_seed
1198
+ 42, # seed
1199
+ 672, # resolution
1200
+ 1, # total_second_length
1201
+ 9, # latent_window_size
1202
+ 30, # steps
1203
+ 1.0, # cfg
1204
+ 10.0, # gs
1205
+ 0.0, # rs
1206
+ 6, # gpu_memory_preservation
1207
+ False, # enable_preview
1208
+ False, # use_teacache
1209
+ 16 # mp4_crf
1210
+ ]
1211
+ ],
1212
+ run_on_click = True,
1213
+ fn = process,
1214
+ inputs = ips,
1215
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
1216
+ cache_examples = False,
1217
+ )
1218
+
1219
+ gr.Examples(
1220
+ label = "Examples from video",
1221
+ examples = [
1222
+ [
1223
+ "./img_examples/Example1.mp4", # input_video
1224
+ "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",
1225
+ "Missing arm, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_prompt
1226
+ True, # randomize_seed
1227
+ 42, # seed
1228
+ 1, # batch
1229
+ 672, # resolution
1230
+ 1, # total_second_length
1231
+ 9, # latent_window_size
1232
+ 30, # steps
1233
+ 1.0, # cfg
1234
+ 10.0, # gs
1235
+ 0.0, # rs
1236
+ 6, # gpu_memory_preservation
1237
+ False, # enable_preview
1238
+ True, # use_teacache
1239
+ False, # no_resize
1240
+ 16, # mp4_crf
1241
+ 5, # num_clean_frames
1242
+ default_vae
1243
+ ]
1244
+ ],
1245
+ run_on_click = True,
1246
+ fn = process_video,
1247
+ inputs = ips_video,
1248
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button],
1249
+ cache_examples = False,
1250
+ )
1251
+
1252
+ def save_preferences(preferences, value):
1253
+ preferences["generation-mode"] = value
1254
+ return preferences
1255
+
1256
+ def load_preferences(saved_prefs):
1257
+ saved_prefs = init_preferences(saved_prefs)
1258
+ return saved_prefs["generation-mode"]
1259
+
1260
+ def init_preferences(saved_prefs):
1261
+ if saved_prefs is None:
1262
+ saved_prefs = default_local_storage
1263
+ return saved_prefs
1264
+
1265
+ def check_parameters(generation_mode, input_image, input_video):
1266
+ if generation_mode == "image" and input_image is None:
1267
+ raise gr.Error("Please provide an image to extend.")
1268
+ if generation_mode == "video" and input_video is None:
1269
+ raise gr.Error("Please provide a video to extend.")
1270
+ return [gr.update(interactive=True), gr.update(visible = True)]
1271
+
1272
+ def handle_generation_mode_change(generation_mode_data):
1273
+ if generation_mode_data == "text":
1274
+ 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)]
1275
+ elif generation_mode_data == "image":
1276
+ 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)]
1277
+ elif generation_mode_data == "video":
1278
+ 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)]
1279
+
1280
+ prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])
1281
+ timeless_prompt.change(fn=handle_timeless_prompt_change, inputs=[timeless_prompt], outputs=[final_prompt])
1282
+ start_button.click(fn = check_parameters, inputs = [
1283
+ generation_mode, input_image, input_video
1284
+ ], 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)
1285
+ start_button_video.click(fn = check_parameters, inputs = [
1286
+ generation_mode, input_image, input_video
1287
+ ], 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)
1288
  end_button.click(fn=end_process)
1289
 
1290
+ generation_mode.change(fn = save_preferences, inputs = [
1291
+ local_storage,
1292
+ generation_mode,
1293
+ ], outputs = [
1294
+ local_storage
1295
+ ])
1296
+
1297
+ generation_mode.change(
1298
+ fn=handle_generation_mode_change,
1299
+ inputs=[generation_mode],
1300
+ 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]
1301
+ )
1302
+
1303
+ # Update display when the page loads
1304
+ block.load(
1305
+ fn=handle_generation_mode_change, inputs = [
1306
+ generation_mode
1307
+ ], outputs = [
1308
+ 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
1309
+ ]
1310
+ )
1311
+
1312
+ # Load saved preferences when the page loads
1313
+ block.load(
1314
+ fn=load_preferences, inputs = [
1315
+ local_storage
1316
+ ], outputs = [
1317
+ generation_mode
1318
+ ]
1319
+ )
1320
+
1321
+ 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]