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