Fabrice-TIERCELIN commited on
Commit
f0cab5e
·
verified ·
1 Parent(s): 6d0c1b7

Merge code

Browse files
Files changed (1) hide show
  1. app.py +327 -0
app.py CHANGED
@@ -574,6 +574,333 @@ def process(input_image, prompt,
574
  yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)
575
  break
576
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
 
578
  def end_process():
579
  stream.input_queue.push('end')
 
574
  yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False)
575
  break
576
 
577
+ # 20250506 pftq: Modified worker to accept video input and clean frame count
578
+ @spaces.GPU()
579
+ @torch.no_grad()
580
+ def worker_video(input_video, 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):
581
+
582
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
583
+
584
+ try:
585
+ # Clean GPU
586
+ if not high_vram:
587
+ unload_complete_models(
588
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
589
+ )
590
+
591
+ # Text encoding
592
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
593
+
594
+ if not high_vram:
595
+ 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.
596
+ load_model_as_complete(text_encoder_2, target_device=gpu)
597
+
598
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
599
+
600
+ if cfg == 1:
601
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
602
+ else:
603
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
604
+
605
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
606
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
607
+
608
+ # 20250506 pftq: Processing input video instead of image
609
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
610
+
611
+ # 20250506 pftq: Encode video
612
+ #H, W = 640, 640 # Default resolution, will be adjusted
613
+ #height, width = find_nearest_bucket(H, W, resolution=640)
614
+ #start_latent, input_image_np, history_latents, fps = video_encode(input_video, vae, height, width, vae_batch_size=16, device=gpu)
615
+ 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)
616
+
617
+ #Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
618
+
619
+ # CLIP Vision
620
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
621
+
622
+ if not high_vram:
623
+ load_model_as_complete(image_encoder, target_device=gpu)
624
+
625
+ image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
626
+ image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
627
+
628
+ # Dtype
629
+ llama_vec = llama_vec.to(transformer.dtype)
630
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
631
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
632
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
633
+ image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
634
+
635
+ total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
636
+ total_latent_sections = int(max(round(total_latent_sections), 1))
637
+
638
+ for idx in range(batch):
639
+ if batch > 1:
640
+ print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
641
+
642
+ #job_id = generate_timestamp()
643
+ 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
644
+
645
+ # Sampling
646
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
647
+
648
+ rnd = torch.Generator("cpu").manual_seed(seed)
649
+
650
+ # 20250506 pftq: Initialize history_latents with video latents
651
+ history_latents = video_latents.cpu()
652
+ total_generated_latent_frames = history_latents.shape[2]
653
+ # 20250506 pftq: Initialize history_pixels to fix UnboundLocalError
654
+ history_pixels = None
655
+ previous_video = None
656
+
657
+ # 20250507 pftq: hot fix for initial video being corrupted by vae encoding, issue with ghosting because of slight differences
658
+ #history_pixels = input_video_pixels
659
+ #save_bcthw_as_mp4(vae_decode(video_latents, vae).cpu(), os.path.join(outputs_folder, f'{job_id}_input_video.mp4'), fps=fps, crf=mp4_crf) # 20250507 pftq: test fast movement corrupted by vae encoding if vae batch size too low
660
+
661
+ for section_index in range(total_latent_sections):
662
+ if stream.input_queue.top() == 'end':
663
+ stream.output_queue.push(('end', None))
664
+ return
665
+
666
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
667
+
668
+ if not high_vram:
669
+ unload_complete_models()
670
+ move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
671
+
672
+ if use_teacache:
673
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
674
+ else:
675
+ transformer.initialize_teacache(enable_teacache=False)
676
+
677
+ def callback(d):
678
+ preview = d['denoised']
679
+ preview = vae_decode_fake(preview)
680
+
681
+ preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
682
+ preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
683
+
684
+ if stream.input_queue.top() == 'end':
685
+ stream.output_queue.push(('end', None))
686
+ raise KeyboardInterrupt('User ends the task.')
687
+
688
+ current_step = d['i'] + 1
689
+ percentage = int(100.0 * current_step / steps)
690
+ hint = f'Sampling {current_step}/{steps}'
691
+ 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}. The video is generating part {section_index+1} of {total_latent_sections}...'
692
+ stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
693
+ return
694
+
695
+ # 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2
696
+ available_frames = history_latents.shape[2] # Number of latent frames
697
+ max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames
698
+ adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames
699
+ # Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x
700
+ effective_clean_frames = max(0, num_clean_frames - 1) if num_clean_frames > 1 else 0
701
+ 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
702
+ 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
703
+ 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
704
+
705
+ total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
706
+ total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos
707
+
708
+ 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
709
+ clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
710
+ [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
711
+ )
712
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
713
+
714
+ # 20250506 pftq: Split history_latents dynamically based on available frames
715
+ fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos
716
+ context_frames = history_latents[:, :, -total_context_frames:, :, :] if total_context_frames > 0 else history_latents[:, :, :fallback_frame_count, :, :]
717
+ if total_context_frames > 0:
718
+ split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames]
719
+ split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes
720
+ if split_sizes:
721
+ splits = context_frames.split(split_sizes, dim=2)
722
+ split_idx = 0
723
+ clean_latents_4x = splits[split_idx] if num_4x_frames > 0 else history_latents[:, :, :fallback_frame_count, :, :]
724
+ if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
725
+ clean_latents_4x = torch.cat([clean_latents_4x, clean_latents_4x[:, :, -1:, :, :]], dim=2)[:, :, :2, :, :]
726
+ split_idx += 1 if num_4x_frames > 0 else 0
727
+ clean_latents_2x = splits[split_idx] if num_2x_frames > 0 and split_idx < len(splits) else history_latents[:, :, :fallback_frame_count, :, :]
728
+ if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
729
+ clean_latents_2x = torch.cat([clean_latents_2x, clean_latents_2x[:, :, -1:, :, :]], dim=2)[:, :, :2, :, :]
730
+ split_idx += 1 if num_2x_frames > 0 else 0
731
+ clean_latents_1x = splits[split_idx] if effective_clean_frames > 0 and split_idx < len(splits) else history_latents[:, :, :fallback_frame_count, :, :]
732
+ else:
733
+ clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
734
+ else:
735
+ clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
736
+
737
+ clean_latents = torch.cat([start_latent.to(history_latents), clean_latents_1x], dim=2)
738
+
739
+ # 20250507 pftq: Fix for <=1 sec videos.
740
+ max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
741
+
742
+ generated_latents = sample_hunyuan(
743
+ transformer=transformer,
744
+ sampler='unipc',
745
+ width=width,
746
+ height=height,
747
+ frames=max_frames,
748
+ real_guidance_scale=cfg,
749
+ distilled_guidance_scale=gs,
750
+ guidance_rescale=rs,
751
+ num_inference_steps=steps,
752
+ generator=rnd,
753
+ prompt_embeds=llama_vec,
754
+ prompt_embeds_mask=llama_attention_mask,
755
+ prompt_poolers=clip_l_pooler,
756
+ negative_prompt_embeds=llama_vec_n,
757
+ negative_prompt_embeds_mask=llama_attention_mask_n,
758
+ negative_prompt_poolers=clip_l_pooler_n,
759
+ device=gpu,
760
+ dtype=torch.bfloat16,
761
+ image_embeddings=image_encoder_last_hidden_state,
762
+ latent_indices=latent_indices,
763
+ clean_latents=clean_latents,
764
+ clean_latent_indices=clean_latent_indices,
765
+ clean_latents_2x=clean_latents_2x,
766
+ clean_latent_2x_indices=clean_latent_2x_indices,
767
+ clean_latents_4x=clean_latents_4x,
768
+ clean_latent_4x_indices=clean_latent_4x_indices,
769
+ callback=callback,
770
+ )
771
+
772
+ total_generated_latent_frames += int(generated_latents.shape[2])
773
+ history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
774
+
775
+ if not high_vram:
776
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
777
+ load_model_as_complete(vae, target_device=gpu)
778
+
779
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
780
+
781
+ if history_pixels is None:
782
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
783
+ else:
784
+ section_latent_frames = latent_window_size * 2
785
+ overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2])
786
+
787
+ #if section_index == 0:
788
+ #extra_latents = 1 # Add up to 2 extra latent frames for smoother overlap to initial video
789
+ #extra_pixel_frames = extra_latents * 4 # Approx. 4 pixel frames per latent
790
+ #overlapped_frames = min(overlapped_frames + extra_pixel_frames, history_pixels.shape[2], section_latent_frames * 4)
791
+
792
+ current_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()
793
+ history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)
794
+
795
+ if not high_vram:
796
+ unload_complete_models()
797
+
798
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
799
+
800
+ # 20250506 pftq: Use input video FPS for output
801
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
802
+ print(f"Latest video saved: {output_filename}")
803
+ # 20250508 pftq: Save prompt to mp4 metadata comments
804
+ set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}");
805
+ print(f"Prompt saved to mp4 metadata comments: {output_filename}")
806
+
807
+ # 20250506 pftq: Clean up previous partial files
808
+ if previous_video is not None and os.path.exists(previous_video):
809
+ try:
810
+ os.remove(previous_video)
811
+ print(f"Previous partial video deleted: {previous_video}")
812
+ except Exception as e:
813
+ print(f"Error deleting previous partial video {previous_video}: {e}")
814
+ previous_video = output_filename
815
+
816
+ print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
817
+
818
+ stream.output_queue.push(('file', output_filename))
819
+
820
+ seed = (seed + 1) % np.iinfo(np.int32).max
821
+
822
+ except:
823
+ traceback.print_exc()
824
+
825
+ if not high_vram:
826
+ unload_complete_models(
827
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
828
+ )
829
+
830
+ stream.output_queue.push(('end', None))
831
+ return
832
+
833
+ 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, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):
834
+ global total_second_length_debug_value
835
+ if total_second_length_debug_value is not None:
836
+ return min(total_second_length_debug_value * 60 * 10, 600)
837
+ return total_second_length * 60 * 10
838
+
839
+ # 20250506 pftq: Modified process to pass clean frame count, etc from video_encode
840
+ @spaces.GPU(duration=get_duration_video)
841
+ 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, use_teacache, no_resize, mp4_crf, num_clean_frames, vae_batch):
842
+ global stream, high_vram, input_video_debug_value, prompt_debug_value, total_second_length_debug_value
843
+
844
+ if torch.cuda.device_count() == 0:
845
+ gr.Warning('Set this space to GPU config to make it work.')
846
+ return None, None, None, None, None, None
847
+
848
+ if input_video_debug_value is not None:
849
+ input_video = input_video_debug_value
850
+ input_video_debug_value = None
851
+
852
+ if prompt_debug_value is not None:
853
+ prompt = prompt_debug_value
854
+ prompt_debug_value = None
855
+
856
+ if total_second_length_debug_value is not None:
857
+ total_second_length = total_second_length_debug_value
858
+ total_second_length_debug_value = None
859
+
860
+ if randomize_seed:
861
+ seed = random.randint(0, np.iinfo(np.int32).max)
862
+
863
+ # 20250506 pftq: Updated assertion for video input
864
+ assert input_video is not None, 'No input video!'
865
+
866
+ yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True)
867
+
868
+ # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
869
+ if high_vram and (no_resize or resolution>640):
870
+ print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
871
+ high_vram = False
872
+ vae.enable_slicing()
873
+ vae.enable_tiling()
874
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
875
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
876
+
877
+ # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
878
+ if cfg > 1:
879
+ gs = 1
880
+
881
+ stream = AsyncStream()
882
+
883
+ # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
884
+ async_run(worker_video, input_video, 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)
885
+
886
+ output_filename = None
887
+
888
+ while True:
889
+ flag, data = stream.output_queue.next()
890
+
891
+ if flag == 'file':
892
+ output_filename = data
893
+ yield output_filename, gr.update(), gr.update(), gr.update(), gr.update(interactive=False), gr.update(interactive=True)
894
+
895
+ if flag == 'progress':
896
+ preview, desc, html = data
897
+ #yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True)
898
+ 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
899
+
900
+ if flag == 'end':
901
+ yield output_filename, gr.update(visible=False), desc+' Video complete.', '', gr.update(interactive=True), gr.update(interactive=False)
902
+ break
903
+
904
 
905
  def end_process():
906
  stream.input_queue.push('end')