Spaces:
Runtime error
Runtime error
Create mask_sp_app.py
Browse files- mask_sp_app.py +453 -0
mask_sp_app.py
ADDED
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers_helper.hf_login import login
|
2 |
+
import os
|
3 |
+
os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download')))
|
4 |
+
|
5 |
+
import gradio as gr
|
6 |
+
import torch
|
7 |
+
import traceback
|
8 |
+
import einops
|
9 |
+
import safetensors.torch as sf
|
10 |
+
import numpy as np
|
11 |
+
import math
|
12 |
+
import spaces
|
13 |
+
from PIL import Image
|
14 |
+
from diffusers import AutoencoderKLHunyuanVideo
|
15 |
+
from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
|
16 |
+
from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
|
17 |
+
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
|
18 |
+
from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
|
19 |
+
from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
|
20 |
+
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
|
21 |
+
from diffusers_helper.thread_utils import AsyncStream, async_run
|
22 |
+
from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
|
23 |
+
from transformers import SiglipImageProcessor, SiglipVisionModel
|
24 |
+
from diffusers_helper.clip_vision import hf_clip_vision_encode
|
25 |
+
from diffusers_helper.bucket_tools import find_nearest_bucket
|
26 |
+
|
27 |
+
free_mem_gb = get_cuda_free_memory_gb(gpu)
|
28 |
+
high_vram = free_mem_gb > 60
|
29 |
+
|
30 |
+
print(f'Free VRAM {free_mem_gb} GB')
|
31 |
+
print(f'High-VRAM Mode: {high_vram}')
|
32 |
+
|
33 |
+
text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
|
34 |
+
text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
|
35 |
+
tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
|
36 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
|
37 |
+
vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
|
38 |
+
|
39 |
+
feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
|
40 |
+
image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
|
41 |
+
|
42 |
+
transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu()
|
43 |
+
|
44 |
+
vae.eval()
|
45 |
+
text_encoder.eval()
|
46 |
+
text_encoder_2.eval()
|
47 |
+
image_encoder.eval()
|
48 |
+
transformer.eval()
|
49 |
+
|
50 |
+
if not high_vram:
|
51 |
+
vae.enable_slicing()
|
52 |
+
vae.enable_tiling()
|
53 |
+
|
54 |
+
transformer.high_quality_fp32_output_for_inference = True
|
55 |
+
print('transformer.high_quality_fp32_output_for_inference = True')
|
56 |
+
|
57 |
+
transformer.to(dtype=torch.bfloat16)
|
58 |
+
vae.to(dtype=torch.float16)
|
59 |
+
image_encoder.to(dtype=torch.float16)
|
60 |
+
text_encoder.to(dtype=torch.float16)
|
61 |
+
text_encoder_2.to(dtype=torch.float16)
|
62 |
+
|
63 |
+
vae.requires_grad_(False)
|
64 |
+
text_encoder.requires_grad_(False)
|
65 |
+
text_encoder_2.requires_grad_(False)
|
66 |
+
image_encoder.requires_grad_(False)
|
67 |
+
transformer.requires_grad_(False)
|
68 |
+
|
69 |
+
if not high_vram:
|
70 |
+
DynamicSwapInstaller.install_model(transformer, device=gpu)
|
71 |
+
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
72 |
+
else:
|
73 |
+
text_encoder.to(gpu)
|
74 |
+
text_encoder_2.to(gpu)
|
75 |
+
image_encoder.to(gpu)
|
76 |
+
vae.to(gpu)
|
77 |
+
transformer.to(gpu)
|
78 |
+
|
79 |
+
stream = AsyncStream()
|
80 |
+
|
81 |
+
outputs_folder = './outputs/'
|
82 |
+
os.makedirs(outputs_folder, exist_ok=True)
|
83 |
+
|
84 |
+
examples = [
|
85 |
+
["img_examples/1.png", "The girl dances gracefully, with clear movements, full of charm."],
|
86 |
+
["img_examples/2.jpg", "The man dances flamboyantly, swinging his hips and striking bold poses with dramatic flair."],
|
87 |
+
["img_examples/3.png", "The woman dances elegantly among the blossoms, spinning slowly with flowing sleeves and graceful hand movements."],
|
88 |
+
]
|
89 |
+
|
90 |
+
def generate_examples(input_image, prompt):
|
91 |
+
t2v=False
|
92 |
+
n_prompt=""
|
93 |
+
seed=31337
|
94 |
+
total_second_length=5
|
95 |
+
latent_window_size=9
|
96 |
+
steps=25
|
97 |
+
cfg=1.0
|
98 |
+
gs=10.0
|
99 |
+
rs=0.0
|
100 |
+
gpu_memory_preservation=6
|
101 |
+
use_teacache=True
|
102 |
+
mp4_crf=16
|
103 |
+
|
104 |
+
global stream
|
105 |
+
|
106 |
+
if t2v:
|
107 |
+
default_height, default_width = 640, 640
|
108 |
+
input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
|
109 |
+
print("No input image provided. Using a blank white image.")
|
110 |
+
|
111 |
+
yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
|
112 |
+
|
113 |
+
stream = AsyncStream()
|
114 |
+
|
115 |
+
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)
|
116 |
+
|
117 |
+
output_filename = None
|
118 |
+
|
119 |
+
while True:
|
120 |
+
flag, data = stream.output_queue.next()
|
121 |
+
|
122 |
+
if flag == 'file':
|
123 |
+
output_filename = data
|
124 |
+
yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
|
125 |
+
|
126 |
+
if flag == 'progress':
|
127 |
+
preview, desc, html = data
|
128 |
+
yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
|
129 |
+
|
130 |
+
if flag == 'end':
|
131 |
+
yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)
|
132 |
+
break
|
133 |
+
|
134 |
+
@torch.no_grad()
|
135 |
+
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):
|
136 |
+
total_latent_sections = (total_second_length * 30) / (latent_window_size * 4)
|
137 |
+
total_latent_sections = int(max(round(total_latent_sections), 1))
|
138 |
+
|
139 |
+
job_id = generate_timestamp()
|
140 |
+
|
141 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
|
142 |
+
|
143 |
+
try:
|
144 |
+
if not high_vram:
|
145 |
+
unload_complete_models(
|
146 |
+
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
147 |
+
)
|
148 |
+
|
149 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
|
150 |
+
|
151 |
+
if not high_vram:
|
152 |
+
fake_diffusers_current_device(text_encoder, gpu)
|
153 |
+
load_model_as_complete(text_encoder_2, target_device=gpu)
|
154 |
+
|
155 |
+
llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
156 |
+
|
157 |
+
if cfg == 1:
|
158 |
+
llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
|
159 |
+
else:
|
160 |
+
llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
161 |
+
|
162 |
+
llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
|
163 |
+
llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
|
164 |
+
|
165 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))
|
166 |
+
|
167 |
+
H, W, C = input_image.shape
|
168 |
+
height, width = find_nearest_bucket(H, W, resolution=640)
|
169 |
+
input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)
|
170 |
+
|
171 |
+
Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
|
172 |
+
|
173 |
+
input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1
|
174 |
+
input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]
|
175 |
+
|
176 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))
|
177 |
+
|
178 |
+
if not high_vram:
|
179 |
+
load_model_as_complete(vae, target_device=gpu)
|
180 |
+
|
181 |
+
start_latent = vae_encode(input_image_pt, vae)
|
182 |
+
|
183 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
|
184 |
+
|
185 |
+
if not high_vram:
|
186 |
+
load_model_as_complete(image_encoder, target_device=gpu)
|
187 |
+
|
188 |
+
image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
|
189 |
+
image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
|
190 |
+
|
191 |
+
llama_vec = llama_vec.to(transformer.dtype)
|
192 |
+
llama_vec_n = llama_vec_n.to(transformer.dtype)
|
193 |
+
clip_l_pooler = clip_l_pooler.to(transformer.dtype)
|
194 |
+
clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
|
195 |
+
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
|
196 |
+
|
197 |
+
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
|
198 |
+
|
199 |
+
rnd = torch.Generator("cpu").manual_seed(seed)
|
200 |
+
|
201 |
+
history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()
|
202 |
+
history_pixels = None
|
203 |
+
|
204 |
+
history_latents = torch.cat([history_latents, start_latent.to(history_latents)], dim=2)
|
205 |
+
total_generated_latent_frames = 1
|
206 |
+
|
207 |
+
for section_index in range(total_latent_sections):
|
208 |
+
if stream.input_queue.top() == 'end':
|
209 |
+
stream.output_queue.push(('end', None))
|
210 |
+
return
|
211 |
+
|
212 |
+
print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
|
213 |
+
|
214 |
+
if not high_vram:
|
215 |
+
unload_complete_models()
|
216 |
+
move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
|
217 |
+
|
218 |
+
if use_teacache:
|
219 |
+
transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
|
220 |
+
else:
|
221 |
+
transformer.initialize_teacache(enable_teacache=False)
|
222 |
+
|
223 |
+
def callback(d):
|
224 |
+
preview = d['denoised']
|
225 |
+
preview = vae_decode_fake(preview)
|
226 |
+
|
227 |
+
preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
|
228 |
+
preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
|
229 |
+
|
230 |
+
if stream.input_queue.top() == 'end':
|
231 |
+
stream.output_queue.push(('end', None))
|
232 |
+
raise KeyboardInterrupt('User ends the task.')
|
233 |
+
|
234 |
+
current_step = d['i'] + 1
|
235 |
+
percentage = int(100.0 * current_step / steps)
|
236 |
+
hint = f'Sampling {current_step}/{steps}'
|
237 |
+
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 ...'
|
238 |
+
stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
|
239 |
+
return
|
240 |
+
|
241 |
+
indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0)
|
242 |
+
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)
|
243 |
+
clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
|
244 |
+
|
245 |
+
clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -sum([16, 2, 1]):, :, :].split([16, 2, 1], dim=2)
|
246 |
+
clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)
|
247 |
+
|
248 |
+
generated_latents = sample_hunyuan(
|
249 |
+
transformer=transformer,
|
250 |
+
sampler='unipc',
|
251 |
+
width=width,
|
252 |
+
height=height,
|
253 |
+
frames=latent_window_size * 4 - 3,
|
254 |
+
real_guidance_scale=cfg,
|
255 |
+
distilled_guidance_scale=gs,
|
256 |
+
guidance_rescale=rs,
|
257 |
+
num_inference_steps=steps,
|
258 |
+
generator=rnd,
|
259 |
+
prompt_embeds=llama_vec,
|
260 |
+
prompt_embeds_mask=llama_attention_mask,
|
261 |
+
prompt_poolers=clip_l_pooler,
|
262 |
+
negative_prompt_embeds=llama_vec_n,
|
263 |
+
negative_prompt_embeds_mask=llama_attention_mask_n,
|
264 |
+
negative_prompt_poolers=clip_l_pooler_n,
|
265 |
+
device=gpu,
|
266 |
+
dtype=torch.bfloat16,
|
267 |
+
image_embeddings=image_encoder_last_hidden_state,
|
268 |
+
latent_indices=latent_indices,
|
269 |
+
clean_latents=clean_latents,
|
270 |
+
clean_latent_indices=clean_latent_indices,
|
271 |
+
clean_latents_2x=clean_latents_2x,
|
272 |
+
clean_latent_2x_indices=clean_latent_2x_indices,
|
273 |
+
clean_latents_4x=clean_latents_4x,
|
274 |
+
clean_latent_4x_indices=clean_latent_4x_indices,
|
275 |
+
callback=callback,
|
276 |
+
)
|
277 |
+
|
278 |
+
total_generated_latent_frames += int(generated_latents.shape[2])
|
279 |
+
history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
|
280 |
+
|
281 |
+
if not high_vram:
|
282 |
+
offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
|
283 |
+
load_model_as_complete(vae, target_device=gpu)
|
284 |
+
|
285 |
+
real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
|
286 |
+
|
287 |
+
if history_pixels is None:
|
288 |
+
history_pixels = vae_decode(real_history_latents, vae).cpu()
|
289 |
+
else:
|
290 |
+
section_latent_frames = latent_window_size * 2
|
291 |
+
overlapped_frames = latent_window_size * 4 - 3
|
292 |
+
|
293 |
+
current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()
|
294 |
+
history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)
|
295 |
+
|
296 |
+
if not high_vram:
|
297 |
+
unload_complete_models()
|
298 |
+
|
299 |
+
output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
|
300 |
+
|
301 |
+
save_bcthw_as_mp4(history_pixels, output_filename, fps=30, crf=mp4_crf)
|
302 |
+
|
303 |
+
print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
|
304 |
+
|
305 |
+
stream.output_queue.push(('file', output_filename))
|
306 |
+
except:
|
307 |
+
traceback.print_exc()
|
308 |
+
|
309 |
+
if not high_vram:
|
310 |
+
unload_complete_models(
|
311 |
+
text_encoder, text_encoder_2, image_encoder, vae, transformer
|
312 |
+
)
|
313 |
+
|
314 |
+
stream.output_queue.push(('end', None))
|
315 |
+
return
|
316 |
+
|
317 |
+
def get_duration(input_image, prompt, t2v, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):
|
318 |
+
return total_second_length * 60
|
319 |
+
|
320 |
+
@spaces.GPU(duration=get_duration)
|
321 |
+
def process(input_image, input_mask, prompt,
|
322 |
+
t2v=False,
|
323 |
+
n_prompt="",
|
324 |
+
seed=31337,
|
325 |
+
total_second_length=5,
|
326 |
+
latent_window_size=9,
|
327 |
+
steps=25,
|
328 |
+
cfg=1.0,
|
329 |
+
gs=10.0,
|
330 |
+
rs=0.0,
|
331 |
+
gpu_memory_preservation=6,
|
332 |
+
use_teacache=True,
|
333 |
+
mp4_crf=16
|
334 |
+
):
|
335 |
+
global stream
|
336 |
+
|
337 |
+
if t2v:
|
338 |
+
default_height, default_width = 640, 640
|
339 |
+
input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
|
340 |
+
print("No input image provided. Using a blank white image.")
|
341 |
+
else:
|
342 |
+
# 处理分别上传的图像和mask
|
343 |
+
rgb_uint8 = input_image.astype(np.uint8)
|
344 |
+
|
345 |
+
from PIL import Image
|
346 |
+
if len(input_mask.shape) >= 3:
|
347 |
+
input_mask = np.asarray(Image.fromarray(input_mask).convert("L"))
|
348 |
+
print("input_mask shape: ", input_mask.shape)
|
349 |
+
|
350 |
+
mask_uint8 = input_mask.astype(np.uint8)
|
351 |
+
|
352 |
+
# 创建白色背景
|
353 |
+
h, w = rgb_uint8.shape[:2]
|
354 |
+
background_uint8 = np.full((h, w, 3), 255, dtype=np.uint8)
|
355 |
+
|
356 |
+
# 归一化mask
|
357 |
+
alpha_normalized_float32 = mask_uint8.astype(np.float32) / 255.0
|
358 |
+
alpha_mask_float32 = np.stack([alpha_normalized_float32] * 3, axis=2)
|
359 |
+
|
360 |
+
# alpha混合
|
361 |
+
blended_image_float32 = rgb_uint8.astype(np.float32) * alpha_mask_float32 + \
|
362 |
+
background_uint8.astype(np.float32) * (1.0 - alpha_mask_float32)
|
363 |
+
|
364 |
+
input_image = np.clip(blended_image_float32, 0, 255).astype(np.uint8)
|
365 |
+
|
366 |
+
yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
|
367 |
+
|
368 |
+
stream = AsyncStream()
|
369 |
+
|
370 |
+
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)
|
371 |
+
|
372 |
+
output_filename = None
|
373 |
+
|
374 |
+
while True:
|
375 |
+
flag, data = stream.output_queue.next()
|
376 |
+
|
377 |
+
if flag == 'file':
|
378 |
+
output_filename = data
|
379 |
+
yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
|
380 |
+
|
381 |
+
if flag == 'progress':
|
382 |
+
preview, desc, html = data
|
383 |
+
yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
|
384 |
+
|
385 |
+
if flag == 'end':
|
386 |
+
yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)
|
387 |
+
break
|
388 |
+
|
389 |
+
def end_process():
|
390 |
+
stream.input_queue.push('end')
|
391 |
+
|
392 |
+
quick_prompts = [
|
393 |
+
'The girl dances gracefully, with clear movements, full of charm.',
|
394 |
+
'A character doing some simple body movements.',
|
395 |
+
]
|
396 |
+
quick_prompts = [[x] for x in quick_prompts]
|
397 |
+
|
398 |
+
css = make_progress_bar_css()
|
399 |
+
block = gr.Blocks(css=css).queue()
|
400 |
+
with block:
|
401 |
+
gr.Markdown('# FramePack-F1')
|
402 |
+
gr.Markdown(f"""### Video diffusion, but feels like image diffusion
|
403 |
+
*FramePack F1 - a FramePack model that only predicts future frames from history frames*
|
404 |
+
### *beta* FramePack Fill 🖋️- draw a mask over the input image to inpaint the video output
|
405 |
+
adapted from the official code repo [FramePack](https://github.com/lllyasviel/FramePack) by [lllyasviel](lllyasviel/FramePack_F1_I2V_HY_20250503) and [FramePack Studio](https://github.com/colinurbs/FramePack-Studio) 🙌🏻
|
406 |
+
""")
|
407 |
+
with gr.Row():
|
408 |
+
with gr.Column():
|
409 |
+
# 修改为分别上传图像和mask
|
410 |
+
input_image = gr.Image(label="Image", type="numpy", height=320)
|
411 |
+
input_mask = gr.Image(label="Mask", type="numpy", height=320)
|
412 |
+
prompt = gr.Textbox(label="Prompt", value='')
|
413 |
+
t2v = gr.Checkbox(label="do text-to-video", value=False)
|
414 |
+
example_quick_prompts = gr.Dataset(samples=quick_prompts, label='Quick List', samples_per_page=1000, components=[prompt])
|
415 |
+
example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False)
|
416 |
+
|
417 |
+
with gr.Row():
|
418 |
+
start_button = gr.Button(value="Start Generation")
|
419 |
+
end_button = gr.Button(value="End Generation", interactive=False)
|
420 |
+
|
421 |
+
total_second_length = gr.Slider(label="Total Video Length (Seconds)", minimum=1, maximum=5, value=2, step=0.1)
|
422 |
+
with gr.Group():
|
423 |
+
with gr.Accordion("Advanced settings", open=False):
|
424 |
+
use_teacache = gr.Checkbox(label='Use TeaCache', value=True, info='Faster speed, but often makes hands and fingers slightly worse.')
|
425 |
+
|
426 |
+
n_prompt = gr.Textbox(label="Negative Prompt", value="", visible=False)
|
427 |
+
seed = gr.Number(label="Seed", value=31337, precision=0)
|
428 |
+
|
429 |
+
latent_window_size = gr.Slider(label="Latent Window Size", minimum=1, maximum=33, value=9, step=1, visible=False)
|
430 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=25, step=1, info='Changing this value is not recommended.')
|
431 |
+
|
432 |
+
cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=32.0, value=1.0, step=0.01, visible=False)
|
433 |
+
gs = gr.Slider(label="Distilled CFG Scale", minimum=1.0, maximum=32.0, value=10.0, step=0.01, info='Changing this value is not recommended.')
|
434 |
+
rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, visible=False)
|
435 |
+
|
436 |
+
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.")
|
437 |
+
|
438 |
+
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.")
|
439 |
+
|
440 |
+
with gr.Column():
|
441 |
+
preview_image = gr.Image(label="Next Latents", height=200, visible=False)
|
442 |
+
result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)
|
443 |
+
progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
|
444 |
+
progress_bar = gr.HTML('', elem_classes='no-generating-animation')
|
445 |
+
|
446 |
+
gr.HTML('<div style="text-align:center; margin-top:20px;">Share your results and find ideas at the <a href="https://x.com/search?q=framepack&f=live" target="_blank">FramePack Twitter (X) thread</a></div>')
|
447 |
+
|
448 |
+
# 更新输入参数列表,包含input_mask
|
449 |
+
ips = [input_image, input_mask, prompt, t2v, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf]
|
450 |
+
start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button])
|
451 |
+
end_button.click(fn=end_process)
|
452 |
+
|
453 |
+
block.launch(server_name = "0.0.0.0" ,share=True)
|