Spaces:
Paused
Paused
Start & end frame mode
Browse files6 unmodified lines78910111213184 unmodified lines19819920020120220320420520645 unmodified lines25225325425525625725847 unmodified lines30630730830931031131299 unmodified lines412413414415416417418156 unmodified lines57557657757857958021 unmodified lines602603604605606607608609245 unmodified lines85585685785885986086186286386486586686786886987087187223 unmodified lines8968978988999009015 unmodified lines90790890991091191291391491591691791891992092192292392414 unmodified lines93994094194294394417 unmodified lines96296396496596696796834 unmodified lines100310041005100610071008100993 unmodified lines11031104110511061107110811091110111119 unmodified lines113111321133113411351136113748 unmodified lines118611871188118911901191119211931 unmodified line119511961197119811991200120112021203120424 unmodified lines122912301231123212331234123512361237123813 unmodified lines125212531254125512561257125812591260126113 unmodified lines127512761277127812791280128112821283128413 unmodified lines129812991300130113021303130413051306130713 unmodified lines132113221323132413251326132713281329133019 unmodified lines135013511352135313541355135613571358135913601361136238 unmodified lines1401140214031404140514061407140814091410141114121413141414151416141715 unmodified lines14331434143514361437143814391 unmodified line14411442144314441445144614476 unmodified linestry:import spacesexcept:print("Not on HuggingFace")import gradio as grimport torchimport traceback184 unmodified linesframes_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)#print(f"Tensor shape: {frames_pt.shape}")# 20250507 pftq: Save pixel frames for use in workerinput_video_pixels = frames_pt.cpu()# 20250506 pftq: Move to device#print(f"Moving tensor to device: {device}")frames_pt = frames_pt.to(device)45 unmodified linestorch.cuda.empty_cache()#print("VAE moved back to CPU, CUDA cache cleared")return start_latent, input_image_np, history_latents, fps, target_height, target_width, input_video_pixelsexcept Exception as e:print(f"Error in video_encode: {str(e)}")47 unmodified linesreturn False@torch.no_grad()def worker(input_image, image_position, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):def encode_prompt(prompt, n_prompt):llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)99 unmodified linesrnd = torch.Generator("cpu").manual_seed(seed)history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32).cpu()start_latent = start_latent.to(history_latents)history_pixels = None156 unmodified linesstream.output_queue.push(('end', None))return# 20250506 pftq: Modified worker to accept video input and clean frame count@torch.no_grad()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):21 unmodified linesstream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))# 20250506 pftq: Encode videostart_latent, input_image_np, video_latents, fps, height, width = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)[:6]start_latent = start_latent.to(dtype=torch.float32).cpu()video_latents = video_latents.cpu()total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)245 unmodified linesstream.output_queue.push(('end', None))returndef get_duration(input_image, image_position, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):return allocation_time# Remove this decorator if you run on local@spaces.GPU(duration=get_duration)def process_on_gpu(input_image, image_position, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):start = time.time()global streamstream = AsyncStream()async_run(worker, input_image, image_position, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number)output_filename = None23 unmodified linesbreakdef process(input_image,image_position=0,prompt="",generation_mode="image",5 unmodified linesresolution=640,total_second_length=5,latent_window_size=9,steps=25,cfg=1.0,gs=10.0,rs=0.0,gpu_memory_preservation=6,enable_preview=True,use_teacache=False,mp4_crf=16,fps_number=30):if auto_allocation:allocation_time = min(total_second_length * 60 * (1.5 if use_teacache else 3.0) * (1 + ((steps - 25) / 25)), 600)if torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')14 unmodified linesyield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip()yield from process_on_gpu(input_image,image_position,prompts,generation_mode,17 unmodified linesdef get_duration_video(input_video, prompts, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):return allocation_time# Remove this decorator if you run on local@spaces.GPU(duration=get_duration_video)def process_video_on_gpu(input_video, prompts, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):start = time.time()34 unmodified linesdef process_video(input_video, prompt, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):global high_vramif auto_allocation:allocation_time = min(total_second_length * 60 * (2.5 if use_teacache else 3.5) * (1 + ((steps - 25) / 25)), 600)if torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')93 unmodified lineslocal_storage = gr.BrowserState(default_local_storage)with gr.Row():with gr.Column():generation_mode = gr.Radio([["Text-to-Video", "text"], ["Image-to-Video", "image"], ["Video Extension", "video"]], elem_id="generation-mode", label="Generation mode", value = "image")text_to_video_hint = gr.HTML("Text-to-Video badly works with a flash effect at the start. I discourage to use the Text-to-Video feature. You should rather generate an image with Flux and use Image-to-Video. You will save time.")input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)image_position = gr.Slider(label="Image position", minimum=0, maximum=100, value=0, step=1, info='0=Video start; 100=Video end (lower quality)')input_video = gr.Video(sources='upload', label="Input Video", height=320)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")19 unmodified linesenable_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.')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.')n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')fps_number = gr.Slider(label="Frame per seconds", info="The model is trained for 30 fps so other fps may generate weird results", minimum=10, maximum=60, value=30, step=1)48 unmodified linesprogress_desc = gr.Markdown('', elem_classes='no-generating-animation')progress_bar = gr.HTML('', elem_classes='no-generating-animation')# 20250506 pftq: Updated inputs to include num_clean_framesips = [input_image, image_position, final_prompt, generation_mode, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number]ips_video = [input_video, final_prompt, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch]gr.Examples(1 unmodified lineexamples = [[None, # input_image0, # image_position"Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed","text", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation24 unmodified linesexamples = [["./img_examples/Example1.png", # input_image0, # image_position"A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example2.webp", # input_image0, # image_position"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks, the man stops talking and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example2.webp", # input_image0, # image_position"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks, the woman stops talking and the woman listens A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example3.jpg", # input_image0, # image_position"A boy is walking to the right, full view, full-length view, cartoon","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example4.webp", # input_image100, # image_position"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation19 unmodified linescache_examples = False,)gr.Examples(label = "🎥 Examples from video",examples = [["./img_examples/Example1.mp4", # input_video"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","Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation38 unmodified linesdef check_parameters(generation_mode, input_image, input_video):if generation_mode == "image" and input_image is None:raise gr.Error("Please provide an image to extend.")if generation_mode == "video" and input_video is None:raise gr.Error("Please provide a video to extend.")return [gr.update(interactive=True), gr.update(visible = True)]def handle_generation_mode_change(generation_mode_data):if generation_mode_data == "text":return [gr.update(visible = True), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True)]elif generation_mode_data == "image":return [gr.update(visible = False), gr.update(visible = True), gr.update(visible = True), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True)]elif generation_mode_data == "video":return [gr.update(visible = False), gr.update(visible = False), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = True), gr.update(visible = False)]prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])timeless_prompt.change(fn=handle_timeless_prompt_change, inputs=[timeless_prompt], outputs=[final_prompt])15 unmodified linesgeneration_mode.change(fn=handle_generation_mode_change,inputs=[generation_mode],outputs=[text_to_video_hint, image_position, input_image, input_video, start_button, start_button_video, no_resize, batch, num_clean_frames, vae_batch, prompt_hint, fps_number])# Update display when the page loads1 unmodified linefn=handle_generation_mode_change, inputs = [generation_mode], outputs = [text_to_video_hint, image_position, input_image, input_video, start_button, start_button_video, no_resize, batch, num_clean_frames, vae_batch, prompt_hint, fps_number])6 unmodified lines7891011121314151617181920184 unmodified lines20520620720820921045 unmodified lines25625725825926026126247 unmodified lines31031131231331431531699 unmodified lines416417418419420421422156 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286321 unmodified lines885886887888889890891892245 unmodified lines1138113911401141114211431144114511461147114811491150115111521153115423 unmodified lines11781179118011811182118311845 unmodified lines11901191119211931194119511961197119811991200120112021203120412051206120714 unmodified lines122212231224122512261227122817 unmodified lines12461247124812491250125134 unmodified lines128612871288128912901291129293 unmodified lines138613871388138913901391139213931394139519 unmodified lines141514161417141814191420142148 unmodified lines14701471147214731474147514761 unmodified line1478147914801481148214831484148514861487148824 unmodified lines1513151415151516151715181519152015211522152313 unmodified lines1537153815391540154115421543154415451546154713 unmodified lines1561156215631564156515661567156815691570157113 unmodified lines1585158615871588158915901591159215931594159513 unmodified lines1609161016111612161316141615161616171618161919 unmodified lines1639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168538 unmodified lines1724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180015 unmodified lines18161817181818191820182118221 unmodified line18241825182618271828182918306 unmodified linestry:import spacesexcept:class spaces():def GPU(*args, **kwargs):def decorator(function):def new_function(*dummy_args, **dummy_kwargs):return function(*dummy_args, **dummy_kwargs)return new_functionreturn decoratorimport gradio as grimport torchimport traceback184 unmodified linesframes_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)#print(f"Tensor shape: {frames_pt.shape}")# 20250506 pftq: Move to device#print(f"Moving tensor to device: {device}")frames_pt = frames_pt.to(device)45 unmodified linestorch.cuda.empty_cache()#print("VAE moved back to CPU, CUDA cache cleared")return start_latent, input_image_np, history_latents, fps, target_height, target_widthexcept Exception as e:print(f"Error in video_encode: {str(e)}")47 unmodified linesreturn False@torch.no_grad()def worker(input_image, end_image, image_position, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):def encode_prompt(prompt, n_prompt):llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)99 unmodified linesrnd = torch.Generator("cpu").manual_seed(seed)history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32, device=cpu)start_latent = start_latent.to(history_latents)history_pixels = None156 unmodified linesstream.output_queue.push(('end', None))return@torch.no_grad()def worker_start_end(input_image, end_image, image_position, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):def encode_prompt(prompt, n_prompt):llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)if cfg == 1:llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)else:llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)llama_vec = llama_vec.to(transformer.dtype)llama_vec_n = llama_vec_n.to(transformer.dtype)clip_l_pooler = clip_l_pooler.to(transformer.dtype)clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]total_latent_sections = (total_second_length * fps_number) / (latent_window_size * 4)total_latent_sections = int(max(round(total_latent_sections), 1))job_id = generate_timestamp()stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))try:# Clean GPUif not high_vram:unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer)# Text encodingstream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))if not high_vram: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.load_model_as_complete(text_encoder_2, target_device=gpu)prompt_parameters = []for prompt_part in prompts[:total_latent_sections]:prompt_parameters.append(encode_prompt(prompt_part, n_prompt))# Clean GPUif not high_vram:unload_complete_models(text_encoder, text_encoder_2)# Processing input image (start frame)stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Processing start frame ...'))))H, W, C = input_image.shapeheight, width = find_nearest_bucket(H, W, resolution=resolution)has_end_image = end_image is not Nonedef get_start_latent(input_image, has_end_image, end_image, height, width, vae, gpu, image_encoder, high_vram):input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}_start.png'))input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]# Processing end image (if provided)if has_end_image:stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Processing end frame ...'))))end_image_np = resize_and_center_crop(end_image, target_width=width, target_height=height)Image.fromarray(end_image_np).save(os.path.join(outputs_folder, f'{job_id}_end.png'))end_image_pt = torch.from_numpy(end_image_np).float() / 127.5 - 1end_image_pt = end_image_pt.permute(2, 0, 1)[None, :, None]# VAE encodingstream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))if not high_vram:load_model_as_complete(vae, target_device=gpu)start_latent = vae_encode(input_image_pt, vae)if has_end_image:end_latent = vae_encode(end_image_pt, vae)# CLIP Visionstream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))if not high_vram:load_model_as_complete(image_encoder, target_device=gpu)image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)image_encoder_last_hidden_state = image_encoder_output.last_hidden_stateif has_end_image:end_image_encoder_output = hf_clip_vision_encode(end_image_np, feature_extractor, image_encoder)end_image_encoder_last_hidden_state = end_image_encoder_output.last_hidden_state# Combine both image embeddings or use a weighted approachimage_encoder_last_hidden_state = (image_encoder_last_hidden_state + end_image_encoder_last_hidden_state) / 2# Clean GPUif not high_vram:unload_complete_models(image_encoder)return [start_latent, end_latent, image_encoder_last_hidden_state][start_latent, end_latent, image_encoder_last_hidden_state] = get_start_latent(input_image, has_end_image, end_image, height, width, vae, gpu, image_encoder, high_vram)# Dtypeimage_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)# Samplingstream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))rnd = torch.Generator("cpu").manual_seed(seed)num_frames = latent_window_size * 4 - 3history_latents = torch.zeros(size=(1, 16, 1 + 2 + 16, height // 8, width // 8), dtype=torch.float32, device=cpu)start_latent = start_latent.to(history_latents)if has_end_image:end_latent = end_latent.to(history_latents)history_pixels = Nonetotal_generated_latent_frames = 0if total_latent_sections > 4:# In theory the latent_paddings should follow the above sequence, but it seems that duplicating some# items looks better than expanding it when total_latent_sections > 4# One can try to remove below trick and just# use `latent_paddings = list(reversed(range(total_latent_sections)))` to comparelatent_paddings = [3] + [2] * (total_latent_sections - 3) + [1, 0]else:# Convert an iterator to a listlatent_paddings = list(range(total_latent_sections - 1, -1, -1))if enable_preview:def callback(d):preview = d['denoised']preview = vae_decode_fake(preview)preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')if stream.input_queue.top() == 'end':stream.output_queue.push(('end', None))raise KeyboardInterrupt('User ends the task.')current_step = d['i'] + 1percentage = int(100.0 * current_step / steps)hint = f'Sampling {current_step}/{steps}'desc = f'Total generated frames: {int(max(0, total_generated_latent_frames * 4 - 3))}, Video length: {max(0, (total_generated_latent_frames * 4 - 3) / fps_number) :.2f} seconds (FPS-30), Resolution: {height}px * {width}px. The video is being extended now ...'stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))returnelse:def callback(d):returndef post_process(job_id, start_latent, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, outputs_folder, mp4_crf, stream, is_last_section):if is_last_section:generated_latents = torch.cat([start_latent.to(generated_latents), generated_latents], dim=2)total_generated_latent_frames += int(generated_latents.shape[2])history_latents = torch.cat([generated_latents.to(history_latents), history_latents], dim=2)if not high_vram:offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)load_model_as_complete(vae, target_device=gpu)if history_pixels is None:history_pixels = vae_decode(history_latents[:, :, :total_generated_latent_frames, :, :], vae).cpu()else:section_latent_frames = (latent_window_size * 2 + 1) if is_last_section else (latent_window_size * 2)overlapped_frames = latent_window_size * 4 - 3current_pixels = vae_decode(history_latents[:, :, :min(total_generated_latent_frames, section_latent_frames)], vae).cpu()history_pixels = soft_append_bcthw(current_pixels, history_pixels, overlapped_frames)if not high_vram:unload_complete_models(vae)if enable_preview or is_last_section:output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')save_bcthw_as_mp4(history_pixels, output_filename, fps=fps_number, crf=mp4_crf)print(f'Decoded. Pixel shape {history_pixels.shape}')stream.output_queue.push(('file', output_filename))return [total_generated_latent_frames, history_latents, history_pixels]for latent_padding in latent_paddings:is_last_section = latent_padding == 0is_first_section = latent_padding == latent_paddings[0]latent_padding_size = latent_padding * latent_window_sizeif stream.input_queue.top() == 'end':stream.output_queue.push(('end', None))returnprint(f'latent_padding_size = {latent_padding_size}, is_last_section = {is_last_section}, is_first_section = {is_first_section}')if len(prompt_parameters) > 0:[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)indices = torch.arange(1 + latent_padding_size + latent_window_size + 1 + 2 + 16).unsqueeze(0)clean_latent_indices_pre, blank_indices, latent_indices, clean_latent_indices_post, clean_latent_2x_indices, clean_latent_4x_indices = indices.split([1, latent_padding_size, latent_window_size, 1, 2, 16], dim=1)clean_latent_indices = torch.cat([clean_latent_indices_pre, clean_latent_indices_post], dim=1)clean_latents_post, clean_latents_2x, clean_latents_4x = history_latents[:, :, :1 + 2 + 16, :, :].split([1, 2, 16], dim=2)# Use end image latent for the first section if providedif has_end_image and is_first_section:clean_latents_post = end_latentclean_latents = torch.cat([start_latent, clean_latents_post], dim=2)if not high_vram:unload_complete_models()move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)if use_teacache:transformer.initialize_teacache(enable_teacache=True, num_steps=steps)else:transformer.initialize_teacache(enable_teacache=False)generated_latents = sample_hunyuan(transformer=transformer,sampler='unipc',width=width,height=height,frames=num_frames,real_guidance_scale=cfg,distilled_guidance_scale=gs,guidance_rescale=rs,# shift=3.0,num_inference_steps=steps,generator=rnd,prompt_embeds=llama_vec,prompt_embeds_mask=llama_attention_mask,prompt_poolers=clip_l_pooler,negative_prompt_embeds=llama_vec_n,negative_prompt_embeds_mask=llama_attention_mask_n,negative_prompt_poolers=clip_l_pooler_n,device=gpu,dtype=torch.bfloat16,image_embeddings=image_encoder_last_hidden_state,latent_indices=latent_indices,clean_latents=clean_latents,clean_latent_indices=clean_latent_indices,clean_latents_2x=clean_latents_2x,clean_latent_2x_indices=clean_latent_2x_indices,clean_latents_4x=clean_latents_4x,clean_latent_4x_indices=clean_latent_4x_indices,callback=callback,)[total_generated_latent_frames, history_latents, history_pixels] = post_process(job_id, start_latent, generated_latents, total_generated_latent_frames, history_latents, high_vram, transformer, gpu, vae, history_pixels, latent_window_size, enable_preview, outputs_folder, mp4_crf, stream, is_last_section)if is_last_section:breakexcept:traceback.print_exc()if not high_vram:unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer)stream.output_queue.push(('end', None))return# 20250506 pftq: Modified worker to accept video input and clean frame count@torch.no_grad()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):21 unmodified linesstream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))# 20250506 pftq: Encode videostart_latent, input_image_np, video_latents, fps, height, width = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)start_latent = start_latent.to(dtype=torch.float32, device=cpu)video_latents = video_latents.cpu()total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)245 unmodified linesstream.output_queue.push(('end', None))returndef get_duration(input_image, end_image, image_position, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):return allocation_time@spaces.GPU(duration=get_duration)def process_on_gpu(input_image, end_image, image_position, prompts, generation_mode, n_prompt, seed, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number):start = time.time()global streamstream = AsyncStream()async_run(worker_start_end if generation_mode == "start_end" else worker, input_image, end_image, image_position, prompts, n_prompt, seed, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number)output_filename = None23 unmodified linesbreakdef process(input_image,end_image,image_position=0,prompt="",generation_mode="image",5 unmodified linesresolution=640,total_second_length=5,latent_window_size=9,steps=30,cfg=1.0,gs=10.0,rs=0.0,gpu_memory_preservation=6,enable_preview=False,use_teacache=False,mp4_crf=16,fps_number=30):if auto_allocation:allocation_time = min(total_second_length * 60 * (1.5 if use_teacache else 3.0) * (1 + ((steps - 25) / 25))**2, 600)if torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')14 unmodified linesyield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip()yield from process_on_gpu(input_image,end_image,image_position,prompts,generation_mode,17 unmodified linesdef get_duration_video(input_video, prompts, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):return allocation_time@spaces.GPU(duration=get_duration_video)def process_video_on_gpu(input_video, prompts, n_prompt, seed, batch, resolution, total_second_length, allocation_time, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):start = time.time()34 unmodified linesdef process_video(input_video, prompt, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):global high_vramif auto_allocation:allocation_time = min(total_second_length * 60 * (2.5 if use_teacache else 3.5) * (1 + ((steps - 25) / 25))**2, 600)if torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')93 unmodified lineslocal_storage = gr.BrowserState(default_local_storage)with gr.Row():with gr.Column():generation_mode = gr.Radio([["Text-to-Video", "text"], ["Image-to-Video", "image"], ["Start & end frames", "start_end"], ["Video Extension", "video"]], elem_id="generation-mode", label="Generation mode", value = "image")text_to_video_hint = gr.HTML("Text-to-Video badly works with a flash effect at the start. I discourage to use the Text-to-Video feature. You should rather generate an image with Flux and use Image-to-Video. You will save time.")input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)end_image = gr.Image(sources='upload', type="numpy", label="End Frame (Optional)", height=320)image_position = gr.Slider(label="Image position", minimum=0, maximum=100, value=0, step=1, info='0=Video start; 100=Video end (lower quality)')input_video = gr.Video(sources='upload', label="Input Video", height=320)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")19 unmodified linesenable_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.')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.')n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')fps_number = gr.Slider(label="Frame per seconds", info="The model is trained for 30 fps so other fps may generate weird results", minimum=10, maximum=60, value=30, step=1)48 unmodified linesprogress_desc = gr.Markdown('', elem_classes='no-generating-animation')progress_bar = gr.HTML('', elem_classes='no-generating-animation')ips = [input_image, end_image, image_position, final_prompt, generation_mode, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, mp4_crf, fps_number]ips_video = [input_video, final_prompt, n_prompt, randomize_seed, seed, auto_allocation, allocation_time, batch, resolution, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, enable_preview, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch]gr.Examples(1 unmodified lineexamples = [[None, # input_imageNone, # end_image0, # image_position"Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed","text", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation24 unmodified linesexamples = [["./img_examples/Example1.png", # input_imageNone, # end_image0, # image_position"A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example2.webp", # input_imageNone, # end_image0, # image_position"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks, the man stops talking and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example2.webp", # input_imageNone, # end_image0, # image_position"A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The woman talks and the man listens; A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks, the woman stops talking and the woman listens A man on the left and a woman on the right face each other ready to start a conversation, large space between the persons, full view, full-length view, 3D, pixar, 3D render, CGI. The man talks and the woman listens","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example3.jpg", # input_imageNone, # end_image0, # image_position"एउटा केटा दायाँतिर हिँडिरहेको छ, पूर्ण दृश्य, पूर्ण-लम्बाइको दृश्य, कार्टुन","image", # generation_mode"हात छुटेको, लामो हात, अवास्तविक स्थिति, असम्भव विकृति, देखिने हड्डी, मांसपेशी संकुचन, कमजोर फ्रेम, धमिलो, धमिलो, अत्यधिक चिल्लो", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation13 unmodified lines],["./img_examples/Example4.webp", # input_imageNone, # end_image100, # image_position"A building starting to explode, photorealistic, realisitc, 8k, insanely detailed","image", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation19 unmodified linescache_examples = False,)gr.Examples(label = "🖼️ Examples from start and end frames",examples = [["./img_examples/Example5.png", # input_image"./img_examples/Example6.png", # end_image0, # image_position"A woman jumps out of the train and arrives on the ground, viewed from the outside, photorealistic, realistic, amateur photography, midday, insanely detailed, 8k", # generation_mode"Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation180, # allocation_time672, # resolution1, # total_second_length9, # latent_window_size30, # steps1.0, # cfg10.0, # gs0.0, # rs6, # gpu_memory_preservationFalse, # enable_previewTrue, # use_teacache16, # mp4_crf30 # fps_number],],run_on_click = True,fn = process,inputs = ips,outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],cache_examples = False,)gr.Examples(label = "🎥 Examples from video",examples = [["./img_examples/Example1.mp4", # input_video"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","Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, poorly framed, blurred, blurry, over-smooth", # n_promptTrue, # randomize_seed42, # seedTrue, # auto_allocation38 unmodified linesdef check_parameters(generation_mode, input_image, input_video):if generation_mode == "image" and input_image is None:raise gr.Error("Please provide an image to extend.")if generation_mode == "start_end" and input_image is None:raise gr.Error("Please provide an image to extend.")if generation_mode == "video" and input_video is None:raise gr.Error("Please provide a video to extend.")return [gr.update(interactive=True), gr.update(visible = True)]def handle_generation_mode_change(generation_mode_data):if generation_mode_data == "text":return [gr.update(visible = True), # text_to_video_hintgr.update(visible = False), # image_positiongr.update(visible = False), # input_imagegr.update(visible = False), # end_imagegr.update(visible = False), # input_videogr.update(visible = True), # start_buttongr.update(visible = False), # start_button_videogr.update(visible = False), # no_resizegr.update(visible = False), # batchgr.update(visible = False), # num_clean_framesgr.update(visible = False), # vae_batchgr.update(visible = False), # prompt_hintgr.update(visible = True) # fps_number]elif generation_mode_data == "image":return [gr.update(visible = False), # text_to_video_hintgr.update(visible = True), # image_positiongr.update(visible = True), # input_imagegr.update(visible = False), # end_imagegr.update(visible = False), # input_videogr.update(visible = True), # start_buttongr.update(visible = False), # start_button_videogr.update(visible = False), # no_resizegr.update(visible = False), # batchgr.update(visible = False), # num_clean_framesgr.update(visible = False), # vae_batchgr.update(visible = False), # prompt_hintgr.update(visible = True) # fps_number]elif generation_mode_data == "start_end":return [gr.update(visible = False), # text_to_video_hintgr.update(visible = False), # image_positiongr.update(visible = True), # input_imagegr.update(visible = True), # end_imagegr.update(visible = False), # input_videogr.update(visible = True), # start_buttongr.update(visible = False), # start_button_videogr.update(visible = False), # no_resizegr.update(visible = False), # batchgr.update(visible = False), # num_clean_framesgr.update(visible = False), # vae_batchgr.update(visible = False), # prompt_hintgr.update(visible = True) # fps_number]elif generation_mode_data == "video":return [gr.update(visible = False), # text_to_video_hintgr.update(visible = False), # image_positiongr.update(visible = False), # input_imagegr.update(visible = False), # end_imagegr.update(visible = True), # input_videogr.update(visible = False), # start_buttongr.update(visible = True), # start_button_videogr.update(visible = True), # no_resizegr.update(visible = True), # batchgr.update(visible = True), # num_clean_framesgr.update(visible = True), # vae_batchgr.update(visible = True), # prompt_hintgr.update(visible = False) # fps_number]prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])timeless_prompt.change(fn=handle_timeless_prompt_change, inputs=[timeless_prompt], outputs=[final_prompt])15 unmodified linesgeneration_mode.change(fn=handle_generation_mode_change,inputs=[generation_mode],outputs=[text_to_video_hint, image_position, input_image, end_image, input_video, start_button, start_button_video, no_resize, batch, num_clean_frames, vae_batch, prompt_hint, fps_number])# Update display when the page loads1 unmodified linefn=handle_generation_mode_change, inputs = [generation_mode], outputs = [text_to_video_hint, image_position, input_image, end_image, input_video, start_button, start_button_video, no_resize, batch, num_clean_frames, vae_batch, prompt_hint, fps_number])
app.py+418-35