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