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