Fabrice-TIERCELIN commited on
Commit
68dfef0
·
verified ·
1 Parent(s): 7b66d9c

for prompt_part in prompt.split(";"):

Browse files
Files changed (1) hide show
  1. app.py +537 -537
app.py CHANGED
@@ -1,538 +1,538 @@
1
- from diffusers_helper.hf_login import login
2
-
3
- import os
4
-
5
- os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))
6
-
7
- import gradio as gr
8
- import torch
9
- import traceback
10
- import einops
11
- import safetensors.torch as sf
12
- import numpy as np
13
- import math
14
- import random
15
- import spaces
16
-
17
- from PIL import Image
18
- from diffusers import AutoencoderKLHunyuanVideo
19
- from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
20
- from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
21
- 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
22
- from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
23
- from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
24
- 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
25
- from diffusers_helper.thread_utils import AsyncStream, async_run
26
- from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
27
- from transformers import SiglipImageProcessor, SiglipVisionModel
28
- from diffusers_helper.clip_vision import hf_clip_vision_encode
29
- from diffusers_helper.bucket_tools import find_nearest_bucket
30
-
31
-
32
- free_mem_gb = get_cuda_free_memory_gb(gpu)
33
- high_vram = free_mem_gb > 80
34
-
35
- print(f'Free VRAM {free_mem_gb} GB')
36
- print(f'High-VRAM Mode: {high_vram}')
37
-
38
- text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
39
- text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
40
- tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
41
- tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
42
- vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
43
-
44
- feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
45
- image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
46
-
47
- transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu()
48
-
49
- vae.eval()
50
- text_encoder.eval()
51
- text_encoder_2.eval()
52
- image_encoder.eval()
53
- transformer.eval()
54
-
55
- if not high_vram:
56
- vae.enable_slicing()
57
- vae.enable_tiling()
58
-
59
- transformer.high_quality_fp32_output_for_inference = True
60
- print('transformer.high_quality_fp32_output_for_inference = True')
61
-
62
- transformer.to(dtype=torch.bfloat16)
63
- vae.to(dtype=torch.float16)
64
- image_encoder.to(dtype=torch.float16)
65
- text_encoder.to(dtype=torch.float16)
66
- text_encoder_2.to(dtype=torch.float16)
67
-
68
- vae.requires_grad_(False)
69
- text_encoder.requires_grad_(False)
70
- text_encoder_2.requires_grad_(False)
71
- image_encoder.requires_grad_(False)
72
- transformer.requires_grad_(False)
73
-
74
- if not high_vram:
75
- # DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster
76
- DynamicSwapInstaller.install_model(transformer, device=gpu)
77
- DynamicSwapInstaller.install_model(text_encoder, device=gpu)
78
- else:
79
- text_encoder.to(gpu)
80
- text_encoder_2.to(gpu)
81
- image_encoder.to(gpu)
82
- vae.to(gpu)
83
- transformer.to(gpu)
84
-
85
- stream = AsyncStream()
86
-
87
- outputs_folder = './outputs/'
88
- os.makedirs(outputs_folder, exist_ok=True)
89
-
90
- input_image_debug_value = prompt_debug_value = total_second_length_debug_value = None
91
-
92
- @torch.no_grad()
93
- 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):
94
- def encode_prompt(prompt, n_prompt):
95
- llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
96
-
97
- if cfg == 1:
98
- llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
99
- else:
100
- llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
101
-
102
- llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
103
- llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
104
-
105
- llama_vec = llama_vec.to(transformer.dtype)
106
- llama_vec_n = llama_vec_n.to(transformer.dtype)
107
- clip_l_pooler = clip_l_pooler.to(transformer.dtype)
108
- clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
109
- return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
110
-
111
- total_latent_sections = (total_second_length * 30) / (latent_window_size * 4)
112
- total_latent_sections = int(max(round(total_latent_sections), 1))
113
-
114
- job_id = generate_timestamp()
115
-
116
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
117
-
118
- try:
119
- # Clean GPU
120
- if not high_vram:
121
- unload_complete_models(
122
- text_encoder, text_encoder_2, image_encoder, vae, transformer
123
- )
124
-
125
- # Text encoding
126
-
127
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
128
-
129
- if not high_vram:
130
- 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.
131
- load_model_as_complete(text_encoder_2, target_device=gpu)
132
-
133
- [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = encode_prompt(prompt, n_prompt)
134
- [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = encode_prompt(prompt, n_prompt)
135
-
136
- # Processing input image
137
-
138
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))
139
-
140
- H, W, C = input_image.shape
141
- height, width = find_nearest_bucket(H, W, resolution=640)
142
- input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)
143
-
144
- Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
145
-
146
- input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1
147
- input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]
148
-
149
- # VAE encoding
150
-
151
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))
152
-
153
- if not high_vram:
154
- load_model_as_complete(vae, target_device=gpu)
155
-
156
- start_latent = vae_encode(input_image_pt, vae)
157
-
158
- # CLIP Vision
159
-
160
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
161
-
162
- if not high_vram:
163
- load_model_as_complete(image_encoder, target_device=gpu)
164
-
165
- image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
166
- image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
167
-
168
- # Dtype
169
-
170
- image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
171
-
172
- # Sampling
173
-
174
- stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
175
-
176
- rnd = torch.Generator("cpu").manual_seed(seed)
177
-
178
- history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()
179
- history_pixels = None
180
-
181
- history_latents = torch.cat([history_latents, start_latent.to(history_latents)], dim=2)
182
- total_generated_latent_frames = 1
183
-
184
- for section_index in range(total_latent_sections):
185
- if stream.input_queue.top() == 'end':
186
- stream.output_queue.push(('end', None))
187
- return
188
-
189
- print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
190
-
191
- if not high_vram:
192
- unload_complete_models()
193
- move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
194
-
195
- if use_teacache:
196
- transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
197
- else:
198
- transformer.initialize_teacache(enable_teacache=False)
199
-
200
- def callback(d):
201
- preview = d['denoised']
202
- preview = vae_decode_fake(preview)
203
-
204
- preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
205
- preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
206
-
207
- if stream.input_queue.top() == 'end':
208
- stream.output_queue.push(('end', None))
209
- raise KeyboardInterrupt('User ends the task.')
210
-
211
- current_step = d['i'] + 1
212
- percentage = int(100.0 * current_step / steps)
213
- hint = f'Sampling {current_step}/{steps}'
214
- 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 ...'
215
- stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
216
- return
217
-
218
- indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0)
219
- 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)
220
- clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
221
-
222
- clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -sum([16, 2, 1]):, :, :].split([16, 2, 1], dim=2)
223
- clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)
224
-
225
- generated_latents = sample_hunyuan(
226
- transformer=transformer,
227
- sampler='unipc',
228
- width=width,
229
- height=height,
230
- frames=latent_window_size * 4 - 3,
231
- real_guidance_scale=cfg,
232
- distilled_guidance_scale=gs,
233
- guidance_rescale=rs,
234
- # shift=3.0,
235
- num_inference_steps=steps,
236
- generator=rnd,
237
- prompt_embeds=llama_vec,
238
- prompt_embeds_mask=llama_attention_mask,
239
- prompt_poolers=clip_l_pooler,
240
- negative_prompt_embeds=llama_vec_n,
241
- negative_prompt_embeds_mask=llama_attention_mask_n,
242
- negative_prompt_poolers=clip_l_pooler_n,
243
- device=gpu,
244
- dtype=torch.bfloat16,
245
- image_embeddings=image_encoder_last_hidden_state,
246
- latent_indices=latent_indices,
247
- clean_latents=clean_latents,
248
- clean_latent_indices=clean_latent_indices,
249
- clean_latents_2x=clean_latents_2x,
250
- clean_latent_2x_indices=clean_latent_2x_indices,
251
- clean_latents_4x=clean_latents_4x,
252
- clean_latent_4x_indices=clean_latent_4x_indices,
253
- callback=callback,
254
- )
255
-
256
- total_generated_latent_frames += int(generated_latents.shape[2])
257
- history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
258
-
259
- if not high_vram:
260
- offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
261
- load_model_as_complete(vae, target_device=gpu)
262
-
263
- real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
264
-
265
- if history_pixels is None:
266
- history_pixels = vae_decode(real_history_latents, vae).cpu()
267
- else:
268
- section_latent_frames = latent_window_size * 2
269
- overlapped_frames = latent_window_size * 4 - 3
270
-
271
- current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()
272
- history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)
273
-
274
- if not high_vram:
275
- unload_complete_models()
276
-
277
- output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
278
-
279
- save_bcthw_as_mp4(history_pixels, output_filename, fps=30, crf=mp4_crf)
280
-
281
- print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
282
-
283
- stream.output_queue.push(('file', output_filename))
284
- except:
285
- traceback.print_exc()
286
-
287
- if not high_vram:
288
- unload_complete_models(
289
- text_encoder, text_encoder_2, image_encoder, vae, transformer
290
- )
291
-
292
- stream.output_queue.push(('end', None))
293
- return
294
-
295
- def get_duration(input_image, prompt, t2v, n_prompt, randomize_seed, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):
296
- global total_second_length_debug_value
297
-
298
- if total_second_length_debug_value is not None:
299
- return min(total_second_length_debug_value * 60, 600)
300
- return total_second_length * 60
301
-
302
-
303
- @spaces.GPU(duration=get_duration)
304
- def process(input_image, prompt,
305
- t2v=False,
306
- n_prompt="",
307
- randomize_seed=True,
308
- seed=31337,
309
- total_second_length=5,
310
- latent_window_size=9,
311
- steps=25,
312
- cfg=1.0,
313
- gs=10.0,
314
- rs=0.0,
315
- gpu_memory_preservation=6,
316
- use_teacache=True,
317
- mp4_crf=16
318
- ):
319
- global stream, input_image_debug_value, prompt_debug_value, total_second_length_debug_value
320
-
321
- if input_image_debug_value is not None or prompt_debug_value is not None or total_second_length_debug_value is not None:
322
- print("Debug mode")
323
- input_image = input_image_debug_value
324
- prompt = prompt_debug_value
325
- total_second_length = total_second_length_debug_value
326
- input_image_debug_value = prompt_debug_value = total_second_length_debug_value = None
327
-
328
- if randomize_seed:
329
- seed = random.randint(0, np.iinfo(np.int32).max)
330
-
331
- # assert input_image is not None, 'No input image!'
332
- if t2v:
333
- default_height, default_width = 640, 640
334
- input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
335
- print("No input image provided. Using a blank white image.")
336
-
337
- yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
338
-
339
- stream = AsyncStream()
340
-
341
- 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)
342
-
343
- output_filename = None
344
-
345
- while True:
346
- flag, data = stream.output_queue.next()
347
-
348
- if flag == 'file':
349
- output_filename = data
350
- yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
351
-
352
- if flag == 'progress':
353
- preview, desc, html = data
354
- yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
355
-
356
- if flag == 'end':
357
- yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)
358
- break
359
-
360
-
361
- def end_process():
362
- stream.input_queue.push('end')
363
-
364
-
365
- css = make_progress_bar_css()
366
- block = gr.Blocks(css=css).queue()
367
- with block:
368
- if torch.cuda.device_count() == 0:
369
- with gr.Row():
370
- gr.HTML("""
371
- <p style="background-color: red;"><big><big><big><b>⚠️To use FramePack, <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>
372
-
373
- You can't use FramePack directly here because this space runs on a CPU, which is not enough for FramePack. Please provide <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">feedback</a> if you have issues.
374
- </big></big></big></p>
375
- """)
376
- gr.Markdown('# FramePack-F1')
377
- gr.Markdown(f"""### Video diffusion, but feels like image diffusion
378
- *FramePack F1 - a FramePack model that only predicts future frames from history frames*
379
- ### *beta* FramePack Fill 🖋️- draw a mask over the input image to inpaint the video output
380
- 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) 🙌🏻
381
- """)
382
- with gr.Row():
383
- with gr.Column():
384
- input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)
385
- prompt = gr.Textbox(label="Prompt", value='')
386
- t2v = gr.Checkbox(label="do text-to-video", value=False)
387
-
388
- with gr.Row():
389
- start_button = gr.Button(value="Start Generation", variant="primary")
390
- end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
391
-
392
- total_second_length = gr.Slider(label="Generated Video Length (Seconds)", minimum=1, maximum=5, value=2, step=0.1)
393
- with gr.Group():
394
- with gr.Accordion("Advanced settings", open=False):
395
- use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
396
-
397
- n_prompt = gr.Textbox(label="Negative Prompt", value="") # Not used
398
- randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
399
- seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
400
-
401
-
402
- latent_window_size = gr.Slider(label="Latent Window Size", minimum=1, maximum=33, value=9, step=1) # Should not change
403
- steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1, info='Changing this value is not recommended.')
404
-
405
- cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01) # Should not change
406
- 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; 3=blurred motions& & unsharped; 10 focus motion')
407
- rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01) # Should not change
408
-
409
- 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.")
410
-
411
- 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. ")
412
-
413
- with gr.Accordion("Debug", open=False):
414
- input_image_debug = gr.Image(type="numpy", label="Image Debug", height=320)
415
- prompt_debug = gr.Textbox(label="Prompt Debug", value='')
416
- total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=5, step=0.1)
417
-
418
- with gr.Column():
419
- preview_image = gr.Image(label="Next Latents", height=200, visible=False)
420
- result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
421
- progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
422
- progress_bar = gr.HTML('', elem_classes='no-generating-animation')
423
-
424
- 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>')
425
-
426
- ips = [input_image, prompt, t2v, n_prompt, randomize_seed, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf]
427
- start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
428
- end_button.click(fn=end_process)
429
-
430
- with gr.Row(visible=False):
431
- gr.Examples(
432
- examples = [
433
- [
434
- "./img_examples/Example1.png", # input_image
435
- "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",
436
- False, # t2v
437
- "", # n_prompt
438
- True, # randomize_seed
439
- 42, # seed
440
- 1, # total_second_length
441
- 9, # latent_window_size
442
- 25, # steps
443
- 1.0, # cfg
444
- 10.0, # gs
445
- 0.0, # rs
446
- 6, # gpu_memory_preservation
447
- True, # use_teacache
448
- 16 # mp4_crf
449
- ],
450
- [
451
- "./img_examples/Example1.png", # input_image
452
- "A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
453
- False, # t2v
454
- "", # n_prompt
455
- True, # randomize_seed
456
- 42, # seed
457
- 1, # total_second_length
458
- 9, # latent_window_size
459
- 25, # steps
460
- 1.0, # cfg
461
- 10.0, # gs
462
- 0.0, # rs
463
- 6, # gpu_memory_preservation
464
- True, # use_teacache
465
- 16 # mp4_crf
466
- ],
467
- [
468
- "./img_examples/Example1.png", # input_image
469
- "We are sinking, photorealistic, realistic, intricate details, 8k, insanely detailed",
470
- False, # t2v
471
- "", # n_prompt
472
- True, # randomize_seed
473
- 42, # seed
474
- 1, # total_second_length
475
- 9, # latent_window_size
476
- 25, # steps
477
- 1.0, # cfg
478
- 10.0, # gs
479
- 0.0, # rs
480
- 6, # gpu_memory_preservation
481
- True, # use_teacache
482
- 16 # mp4_crf
483
- ],
484
- [
485
- "./img_examples/Example1.png", # input_image
486
- "A boat is passing, photorealistic, realistic, intricate details, 8k, insanely detailed",
487
- False, # t2v
488
- "", # n_prompt
489
- True, # randomize_seed
490
- 42, # seed
491
- 1, # total_second_length
492
- 9, # latent_window_size
493
- 25, # steps
494
- 1.0, # cfg
495
- 10.0, # gs
496
- 0.0, # rs
497
- 6, # gpu_memory_preservation
498
- True, # use_teacache
499
- 16 # mp4_crf
500
- ],
501
- ],
502
- run_on_click = True,
503
- fn = process,
504
- inputs = ips,
505
- outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
506
- cache_examples = True,
507
- )
508
- gr.Markdown('## Guide')
509
- gr.Markdown("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.")
510
-
511
-
512
- def handle_field_debug_change(input_image_debug_data, prompt_debug_data, total_second_length_debug_data):
513
- global input_image_debug_value, prompt_debug_value, total_second_length_debug_value
514
- input_image_debug_value = input_image_debug_data
515
- prompt_debug_value = prompt_debug_data
516
- total_second_length_debug_value = total_second_length_debug_data
517
- return []
518
-
519
- input_image_debug.upload(
520
- fn=handle_field_debug_change,
521
- inputs=[input_image_debug, prompt_debug, total_second_length_debug],
522
- outputs=[]
523
- )
524
-
525
- prompt_debug.change(
526
- fn=handle_field_debug_change,
527
- inputs=[input_image_debug, prompt_debug, total_second_length_debug],
528
- outputs=[]
529
- )
530
-
531
- total_second_length_debug.change(
532
- fn=handle_field_debug_change,
533
- inputs=[input_image_debug, prompt_debug, total_second_length_debug],
534
- outputs=[]
535
- )
536
-
537
-
538
  block.launch(mcp_server=False)
 
1
+ from diffusers_helper.hf_login import login
2
+
3
+ import os
4
+
5
+ os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))
6
+
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 random
15
+ import spaces
16
+
17
+ from PIL import Image
18
+ from diffusers import AutoencoderKLHunyuanVideo
19
+ from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
20
+ from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
21
+ 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
22
+ from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
23
+ from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
24
+ 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
25
+ from diffusers_helper.thread_utils import AsyncStream, async_run
26
+ from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
27
+ from transformers import SiglipImageProcessor, SiglipVisionModel
28
+ from diffusers_helper.clip_vision import hf_clip_vision_encode
29
+ from diffusers_helper.bucket_tools import find_nearest_bucket
30
+
31
+
32
+ free_mem_gb = get_cuda_free_memory_gb(gpu)
33
+ high_vram = free_mem_gb > 80
34
+
35
+ print(f'Free VRAM {free_mem_gb} GB')
36
+ print(f'High-VRAM Mode: {high_vram}')
37
+
38
+ text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
39
+ text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
40
+ tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
41
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
42
+ vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
43
+
44
+ feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
45
+ image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
46
+
47
+ transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu()
48
+
49
+ vae.eval()
50
+ text_encoder.eval()
51
+ text_encoder_2.eval()
52
+ image_encoder.eval()
53
+ transformer.eval()
54
+
55
+ if not high_vram:
56
+ vae.enable_slicing()
57
+ vae.enable_tiling()
58
+
59
+ transformer.high_quality_fp32_output_for_inference = True
60
+ print('transformer.high_quality_fp32_output_for_inference = True')
61
+
62
+ transformer.to(dtype=torch.bfloat16)
63
+ vae.to(dtype=torch.float16)
64
+ image_encoder.to(dtype=torch.float16)
65
+ text_encoder.to(dtype=torch.float16)
66
+ text_encoder_2.to(dtype=torch.float16)
67
+
68
+ vae.requires_grad_(False)
69
+ text_encoder.requires_grad_(False)
70
+ text_encoder_2.requires_grad_(False)
71
+ image_encoder.requires_grad_(False)
72
+ transformer.requires_grad_(False)
73
+
74
+ if not high_vram:
75
+ # DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster
76
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
77
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
78
+ else:
79
+ text_encoder.to(gpu)
80
+ text_encoder_2.to(gpu)
81
+ image_encoder.to(gpu)
82
+ vae.to(gpu)
83
+ transformer.to(gpu)
84
+
85
+ stream = AsyncStream()
86
+
87
+ outputs_folder = './outputs/'
88
+ os.makedirs(outputs_folder, exist_ok=True)
89
+
90
+ input_image_debug_value = prompt_debug_value = total_second_length_debug_value = None
91
+
92
+ @torch.no_grad()
93
+ 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):
94
+ def encode_prompt(prompt, n_prompt):
95
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
96
+
97
+ if cfg == 1:
98
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
99
+ else:
100
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
101
+
102
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
103
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
104
+
105
+ llama_vec = llama_vec.to(transformer.dtype)
106
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
107
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
108
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
109
+ return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
110
+
111
+ total_latent_sections = (total_second_length * 30) / (latent_window_size * 4)
112
+ total_latent_sections = int(max(round(total_latent_sections), 1))
113
+
114
+ job_id = generate_timestamp()
115
+
116
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
117
+
118
+ try:
119
+ # Clean GPU
120
+ if not high_vram:
121
+ unload_complete_models(
122
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
123
+ )
124
+
125
+ # Text encoding
126
+
127
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
128
+
129
+ if not high_vram:
130
+ 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.
131
+ load_model_as_complete(text_encoder_2, target_device=gpu)
132
+
133
+ for prompt_part in prompt.split(";"):
134
+ [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = encode_prompt(prompt_part, n_prompt)
135
+
136
+ # Processing input image
137
+
138
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))
139
+
140
+ H, W, C = input_image.shape
141
+ height, width = find_nearest_bucket(H, W, resolution=640)
142
+ input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)
143
+
144
+ Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
145
+
146
+ input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1
147
+ input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]
148
+
149
+ # VAE encoding
150
+
151
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))
152
+
153
+ if not high_vram:
154
+ load_model_as_complete(vae, target_device=gpu)
155
+
156
+ start_latent = vae_encode(input_image_pt, vae)
157
+
158
+ # CLIP Vision
159
+
160
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
161
+
162
+ if not high_vram:
163
+ load_model_as_complete(image_encoder, target_device=gpu)
164
+
165
+ image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
166
+ image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
167
+
168
+ # Dtype
169
+
170
+ image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
171
+
172
+ # Sampling
173
+
174
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
175
+
176
+ rnd = torch.Generator("cpu").manual_seed(seed)
177
+
178
+ history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()
179
+ history_pixels = None
180
+
181
+ history_latents = torch.cat([history_latents, start_latent.to(history_latents)], dim=2)
182
+ total_generated_latent_frames = 1
183
+
184
+ for section_index in range(total_latent_sections):
185
+ if stream.input_queue.top() == 'end':
186
+ stream.output_queue.push(('end', None))
187
+ return
188
+
189
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
190
+
191
+ if not high_vram:
192
+ unload_complete_models()
193
+ move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
194
+
195
+ if use_teacache:
196
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
197
+ else:
198
+ transformer.initialize_teacache(enable_teacache=False)
199
+
200
+ def callback(d):
201
+ preview = d['denoised']
202
+ preview = vae_decode_fake(preview)
203
+
204
+ preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
205
+ preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
206
+
207
+ if stream.input_queue.top() == 'end':
208
+ stream.output_queue.push(('end', None))
209
+ raise KeyboardInterrupt('User ends the task.')
210
+
211
+ current_step = d['i'] + 1
212
+ percentage = int(100.0 * current_step / steps)
213
+ hint = f'Sampling {current_step}/{steps}'
214
+ 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 ...'
215
+ stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
216
+ return
217
+
218
+ indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0)
219
+ 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)
220
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
221
+
222
+ clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -sum([16, 2, 1]):, :, :].split([16, 2, 1], dim=2)
223
+ clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)
224
+
225
+ generated_latents = sample_hunyuan(
226
+ transformer=transformer,
227
+ sampler='unipc',
228
+ width=width,
229
+ height=height,
230
+ frames=latent_window_size * 4 - 3,
231
+ real_guidance_scale=cfg,
232
+ distilled_guidance_scale=gs,
233
+ guidance_rescale=rs,
234
+ # shift=3.0,
235
+ num_inference_steps=steps,
236
+ generator=rnd,
237
+ prompt_embeds=llama_vec,
238
+ prompt_embeds_mask=llama_attention_mask,
239
+ prompt_poolers=clip_l_pooler,
240
+ negative_prompt_embeds=llama_vec_n,
241
+ negative_prompt_embeds_mask=llama_attention_mask_n,
242
+ negative_prompt_poolers=clip_l_pooler_n,
243
+ device=gpu,
244
+ dtype=torch.bfloat16,
245
+ image_embeddings=image_encoder_last_hidden_state,
246
+ latent_indices=latent_indices,
247
+ clean_latents=clean_latents,
248
+ clean_latent_indices=clean_latent_indices,
249
+ clean_latents_2x=clean_latents_2x,
250
+ clean_latent_2x_indices=clean_latent_2x_indices,
251
+ clean_latents_4x=clean_latents_4x,
252
+ clean_latent_4x_indices=clean_latent_4x_indices,
253
+ callback=callback,
254
+ )
255
+
256
+ total_generated_latent_frames += int(generated_latents.shape[2])
257
+ history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
258
+
259
+ if not high_vram:
260
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
261
+ load_model_as_complete(vae, target_device=gpu)
262
+
263
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
264
+
265
+ if history_pixels is None:
266
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
267
+ else:
268
+ section_latent_frames = latent_window_size * 2
269
+ overlapped_frames = latent_window_size * 4 - 3
270
+
271
+ current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()
272
+ history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)
273
+
274
+ if not high_vram:
275
+ unload_complete_models()
276
+
277
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
278
+
279
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=30, crf=mp4_crf)
280
+
281
+ print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
282
+
283
+ stream.output_queue.push(('file', output_filename))
284
+ except:
285
+ traceback.print_exc()
286
+
287
+ if not high_vram:
288
+ unload_complete_models(
289
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
290
+ )
291
+
292
+ stream.output_queue.push(('end', None))
293
+ return
294
+
295
+ def get_duration(input_image, prompt, t2v, n_prompt, randomize_seed, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):
296
+ global total_second_length_debug_value
297
+
298
+ if total_second_length_debug_value is not None:
299
+ return min(total_second_length_debug_value * 60, 600)
300
+ return total_second_length * 60
301
+
302
+
303
+ @spaces.GPU(duration=get_duration)
304
+ def process(input_image, prompt,
305
+ t2v=False,
306
+ n_prompt="",
307
+ randomize_seed=True,
308
+ seed=31337,
309
+ total_second_length=5,
310
+ latent_window_size=9,
311
+ steps=25,
312
+ cfg=1.0,
313
+ gs=10.0,
314
+ rs=0.0,
315
+ gpu_memory_preservation=6,
316
+ use_teacache=True,
317
+ mp4_crf=16
318
+ ):
319
+ global stream, input_image_debug_value, prompt_debug_value, total_second_length_debug_value
320
+
321
+ if input_image_debug_value is not None or prompt_debug_value is not None or total_second_length_debug_value is not None:
322
+ print("Debug mode")
323
+ input_image = input_image_debug_value
324
+ prompt = prompt_debug_value
325
+ total_second_length = total_second_length_debug_value
326
+ input_image_debug_value = prompt_debug_value = total_second_length_debug_value = None
327
+
328
+ if randomize_seed:
329
+ seed = random.randint(0, np.iinfo(np.int32).max)
330
+
331
+ # assert input_image is not None, 'No input image!'
332
+ if t2v:
333
+ default_height, default_width = 640, 640
334
+ input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
335
+ print("No input image provided. Using a blank white image.")
336
+
337
+ yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
338
+
339
+ stream = AsyncStream()
340
+
341
+ 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)
342
+
343
+ output_filename = None
344
+
345
+ while True:
346
+ flag, data = stream.output_queue.next()
347
+
348
+ if flag == 'file':
349
+ output_filename = data
350
+ yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
351
+
352
+ if flag == 'progress':
353
+ preview, desc, html = data
354
+ yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
355
+
356
+ if flag == 'end':
357
+ yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)
358
+ break
359
+
360
+
361
+ def end_process():
362
+ stream.input_queue.push('end')
363
+
364
+
365
+ css = make_progress_bar_css()
366
+ block = gr.Blocks(css=css).queue()
367
+ with block:
368
+ if torch.cuda.device_count() == 0:
369
+ with gr.Row():
370
+ gr.HTML("""
371
+ <p style="background-color: red;"><big><big><big><b>⚠️To use FramePack, <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>
372
+
373
+ You can't use FramePack directly here because this space runs on a CPU, which is not enough for FramePack. Please provide <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/SUPIR/discussions/new">feedback</a> if you have issues.
374
+ </big></big></big></p>
375
+ """)
376
+ gr.Markdown('# FramePack-F1')
377
+ gr.Markdown(f"""### Video diffusion, but feels like image diffusion
378
+ *FramePack F1 - a FramePack model that only predicts future frames from history frames*
379
+ ### *beta* FramePack Fill 🖋️- draw a mask over the input image to inpaint the video output
380
+ 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) 🙌🏻
381
+ """)
382
+ with gr.Row():
383
+ with gr.Column():
384
+ input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)
385
+ prompt = gr.Textbox(label="Prompt", value='')
386
+ t2v = gr.Checkbox(label="do text-to-video", value=False)
387
+
388
+ with gr.Row():
389
+ start_button = gr.Button(value="Start Generation", variant="primary")
390
+ end_button = gr.Button(value="End Generation", variant="stop", interactive=False)
391
+
392
+ total_second_length = gr.Slider(label="Generated Video Length (Seconds)", minimum=1, maximum=5, value=2, step=0.1)
393
+ with gr.Group():
394
+ with gr.Accordion("Advanced settings", open=False):
395
+ use_teacache = gr.Checkbox(label='Use TeaCache', value=False, info='Faster speed, but often makes hands and fingers slightly worse.')
396
+
397
+ n_prompt = gr.Textbox(label="Negative Prompt", value="") # Not used
398
+ randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
399
+ seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
400
+
401
+
402
+ latent_window_size = gr.Slider(label="Latent Window Size", minimum=1, maximum=33, value=9, step=1) # Should not change
403
+ steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1, info='Changing this value is not recommended.')
404
+
405
+ cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01) # Should not change
406
+ 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; 3=blurred motions& & unsharped; 10 focus motion')
407
+ rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01) # Should not change
408
+
409
+ 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.")
410
+
411
+ 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. ")
412
+
413
+ with gr.Accordion("Debug", open=False):
414
+ input_image_debug = gr.Image(type="numpy", label="Image Debug", height=320)
415
+ prompt_debug = gr.Textbox(label="Prompt Debug", value='')
416
+ total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=5, step=0.1)
417
+
418
+ with gr.Column():
419
+ preview_image = gr.Image(label="Next Latents", height=200, visible=False)
420
+ result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
421
+ progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
422
+ progress_bar = gr.HTML('', elem_classes='no-generating-animation')
423
+
424
+ 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>')
425
+
426
+ ips = [input_image, prompt, t2v, n_prompt, randomize_seed, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf]
427
+ start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
428
+ end_button.click(fn=end_process)
429
+
430
+ with gr.Row(visible=False):
431
+ gr.Examples(
432
+ examples = [
433
+ [
434
+ "./img_examples/Example1.png", # input_image
435
+ "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",
436
+ False, # t2v
437
+ "", # n_prompt
438
+ True, # randomize_seed
439
+ 42, # seed
440
+ 1, # total_second_length
441
+ 9, # latent_window_size
442
+ 25, # steps
443
+ 1.0, # cfg
444
+ 10.0, # gs
445
+ 0.0, # rs
446
+ 6, # gpu_memory_preservation
447
+ False, # use_teacache
448
+ 16 # mp4_crf
449
+ ],
450
+ [
451
+ "./img_examples/Example1.png", # input_image
452
+ "A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
453
+ False, # t2v
454
+ "", # n_prompt
455
+ True, # randomize_seed
456
+ 42, # seed
457
+ 1, # total_second_length
458
+ 9, # latent_window_size
459
+ 25, # steps
460
+ 1.0, # cfg
461
+ 10.0, # gs
462
+ 0.0, # rs
463
+ 6, # gpu_memory_preservation
464
+ False, # use_teacache
465
+ 16 # mp4_crf
466
+ ],
467
+ [
468
+ "./img_examples/Example1.png", # input_image
469
+ "We are sinking, photorealistic, realistic, intricate details, 8k, insanely detailed",
470
+ False, # t2v
471
+ "", # n_prompt
472
+ True, # randomize_seed
473
+ 42, # seed
474
+ 1, # total_second_length
475
+ 9, # latent_window_size
476
+ 25, # steps
477
+ 1.0, # cfg
478
+ 10.0, # gs
479
+ 0.0, # rs
480
+ 6, # gpu_memory_preservation
481
+ False, # use_teacache
482
+ 16 # mp4_crf
483
+ ],
484
+ [
485
+ "./img_examples/Example1.png", # input_image
486
+ "A boat is passing, photorealistic, realistic, intricate details, 8k, insanely detailed",
487
+ False, # t2v
488
+ "", # n_prompt
489
+ True, # randomize_seed
490
+ 42, # seed
491
+ 1, # total_second_length
492
+ 9, # latent_window_size
493
+ 25, # steps
494
+ 1.0, # cfg
495
+ 10.0, # gs
496
+ 0.0, # rs
497
+ 6, # gpu_memory_preservation
498
+ False, # use_teacache
499
+ 16 # mp4_crf
500
+ ],
501
+ ],
502
+ run_on_click = True,
503
+ fn = process,
504
+ inputs = ips,
505
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button],
506
+ cache_examples = True,
507
+ )
508
+ gr.Markdown('## Guide')
509
+ gr.Markdown("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.")
510
+
511
+
512
+ def handle_field_debug_change(input_image_debug_data, prompt_debug_data, total_second_length_debug_data):
513
+ global input_image_debug_value, prompt_debug_value, total_second_length_debug_value
514
+ input_image_debug_value = input_image_debug_data
515
+ prompt_debug_value = prompt_debug_data
516
+ total_second_length_debug_value = total_second_length_debug_data
517
+ return []
518
+
519
+ input_image_debug.upload(
520
+ fn=handle_field_debug_change,
521
+ inputs=[input_image_debug, prompt_debug, total_second_length_debug],
522
+ outputs=[]
523
+ )
524
+
525
+ prompt_debug.change(
526
+ fn=handle_field_debug_change,
527
+ inputs=[input_image_debug, prompt_debug, total_second_length_debug],
528
+ outputs=[]
529
+ )
530
+
531
+ total_second_length_debug.change(
532
+ fn=handle_field_debug_change,
533
+ inputs=[input_image_debug, prompt_debug, total_second_length_debug],
534
+ outputs=[]
535
+ )
536
+
537
+
538
  block.launch(mcp_server=False)