Fabrice-TIERCELIN commited on
Commit
96430ad
·
verified ·
1 Parent(s): 6fe9f57

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

Browse files

This PR:
1. Extends a video,
1. Optimizes time & VRAM,
1. Displays generation time,
1. Chooses resolution,
1. Adds examples,
1. Handles prompts on period,
1. Choose image position

It removes the inpaint that does not work.

Click on _Merge_ to add those features.

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