Fabrice-TIERCELIN commited on
Commit
d24151d
·
verified ·
1 Parent(s): 04fa470

Upload 6 files

Browse files
Files changed (5) hide show
  1. README.md +15 -15
  2. app.py +0 -0
  3. app_lora.py +0 -0
  4. app_start_end.py +1741 -0
  5. requirements.txt +21 -38
README.md CHANGED
@@ -1,21 +1,21 @@
1
  ---
2
- title: SUPIR Image Upscaler
 
 
 
3
  sdk: gradio
4
- emoji: 📷
5
- sdk_version: 4.38.1
6
- app_file: app.py
7
- license: mit
8
- colorFrom: blue
9
- colorTo: pink
10
  tags:
11
- - Upscaling
12
- - Restoring
13
- - Image-to-Image
14
- - Image-2-Image
15
- - Img-to-Img
16
- - Img-2-Img
17
  - language models
18
  - LLMs
19
- short_description: Restore blurred or small images with prompt
20
  suggested_hardware: zero-a10g
21
- ---
 
 
 
1
  ---
2
+ title: FramePack/HunyuanVideo
3
+ emoji: 🎥
4
+ colorFrom: pink
5
+ colorTo: gray
6
  sdk: gradio
7
+ sdk_version: 5.29.1
8
+ app_file: app_lora.py
9
+ license: apache-2.0
10
+ short_description: Text-to-Video/Image-to-Video/Video extender (timed prompt)
 
 
11
  tags:
12
+ - Image-to-Video
13
+ - Image-2-Video
14
+ - Img-to-Vid
15
+ - Img-2-Vid
 
 
16
  - language models
17
  - LLMs
 
18
  suggested_hardware: zero-a10g
19
+ ---
20
+
21
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
app_lora.py ADDED
The diff for this file is too large to render. See raw diff
 
app_start_end.py ADDED
@@ -0,0 +1,1741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ try:
8
+ import spaces
9
+ except:
10
+ print("Not on HuggingFace")
11
+ import gradio as gr
12
+ import torch
13
+ import traceback
14
+ import einops
15
+ import safetensors.torch as sf
16
+ import numpy as np
17
+ import random
18
+ import time
19
+ import math
20
+ # 20250506 pftq: Added for video input loading
21
+ import decord
22
+ # 20250506 pftq: Added for progress bars in video_encode
23
+ from tqdm import tqdm
24
+ # 20250506 pftq: Normalize file paths for Windows compatibility
25
+ import pathlib
26
+ # 20250506 pftq: for easier to read timestamp
27
+ from datetime import datetime
28
+ # 20250508 pftq: for saving prompt to mp4 comments metadata
29
+ import imageio_ffmpeg
30
+ import tempfile
31
+ import shutil
32
+ import subprocess
33
+
34
+ from PIL import Image
35
+ from diffusers import AutoencoderKLHunyuanVideo
36
+ from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer
37
+ from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
38
+ 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
39
+ from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
40
+ from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
41
+ if torch.cuda.device_count() > 0:
42
+ 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
43
+ from diffusers_helper.thread_utils import AsyncStream, async_run
44
+ from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
45
+ from transformers import SiglipImageProcessor, SiglipVisionModel
46
+ from diffusers_helper.clip_vision import hf_clip_vision_encode
47
+ from diffusers_helper.bucket_tools import find_nearest_bucket
48
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline
49
+ import pillow_heif
50
+
51
+ pillow_heif.register_heif_opener()
52
+
53
+ high_vram = False
54
+ free_mem_gb = 0
55
+
56
+ if torch.cuda.device_count() > 0:
57
+ free_mem_gb = get_cuda_free_memory_gb(gpu)
58
+ high_vram = free_mem_gb > 60
59
+
60
+ #print(f'Free VRAM {free_mem_gb} GB')
61
+ #print(f'High-VRAM Mode: {high_vram}')
62
+
63
+ text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=torch.float16).cpu()
64
+ text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=torch.float16).cpu()
65
+ tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer')
66
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2')
67
+ vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=torch.float16).cpu()
68
+
69
+ feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor')
70
+ image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=torch.float16).cpu()
71
+
72
+ transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePack_F1_I2V_HY_20250503', torch_dtype=torch.bfloat16).cpu()
73
+
74
+ vae.eval()
75
+ text_encoder.eval()
76
+ text_encoder_2.eval()
77
+ image_encoder.eval()
78
+ transformer.eval()
79
+
80
+ if not high_vram:
81
+ vae.enable_slicing()
82
+ vae.enable_tiling()
83
+
84
+ transformer.high_quality_fp32_output_for_inference = True
85
+ #print('transformer.high_quality_fp32_output_for_inference = True')
86
+
87
+ transformer.to(dtype=torch.bfloat16)
88
+ vae.to(dtype=torch.float16)
89
+ image_encoder.to(dtype=torch.float16)
90
+ text_encoder.to(dtype=torch.float16)
91
+ text_encoder_2.to(dtype=torch.float16)
92
+
93
+ vae.requires_grad_(False)
94
+ text_encoder.requires_grad_(False)
95
+ text_encoder_2.requires_grad_(False)
96
+ image_encoder.requires_grad_(False)
97
+ transformer.requires_grad_(False)
98
+
99
+ if not high_vram:
100
+ # DynamicSwapInstaller is same as huggingface's enable_sequential_offload but 3x faster
101
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
102
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
103
+ else:
104
+ text_encoder.to(gpu)
105
+ text_encoder_2.to(gpu)
106
+ image_encoder.to(gpu)
107
+ vae.to(gpu)
108
+ transformer.to(gpu)
109
+
110
+ stream = AsyncStream()
111
+
112
+ outputs_folder = './outputs/'
113
+ os.makedirs(outputs_folder, exist_ok=True)
114
+
115
+ input_image_debug_value = [None]
116
+ input_video_debug_value = [None]
117
+ prompt_debug_value = [None]
118
+ total_second_length_debug_value = [None]
119
+
120
+ default_local_storage = {
121
+ "generation-mode": "image",
122
+ }
123
+
124
+ @torch.no_grad()
125
+ def video_encode(video_path, resolution, no_resize, vae, vae_batch_size=16, device="cuda", width=None, height=None):
126
+ """
127
+ Encode a video into latent representations using the VAE.
128
+
129
+ Args:
130
+ video_path: Path to the input video file.
131
+ vae: AutoencoderKLHunyuanVideo model.
132
+ height, width: Target resolution for resizing frames.
133
+ vae_batch_size: Number of frames to process per batch.
134
+ device: Device for computation (e.g., "cuda").
135
+
136
+ Returns:
137
+ start_latent: Latent of the first frame (for compatibility with original code).
138
+ input_image_np: First frame as numpy array (for CLIP vision encoding).
139
+ history_latents: Latents of all frames (shape: [1, channels, frames, height//8, width//8]).
140
+ fps: Frames per second of the input video.
141
+ """
142
+ # 20250506 pftq: Normalize video path for Windows compatibility
143
+ video_path = str(pathlib.Path(video_path).resolve())
144
+ #print(f"Processing video: {video_path}")
145
+
146
+ # 20250506 pftq: Check CUDA availability and fallback to CPU if needed
147
+ if device == "cuda" and not torch.cuda.is_available():
148
+ #print("CUDA is not available, falling back to CPU")
149
+ device = "cpu"
150
+
151
+ try:
152
+ # 20250506 pftq: Load video and get FPS
153
+ #print("Initializing VideoReader...")
154
+ vr = decord.VideoReader(video_path)
155
+ fps = vr.get_avg_fps() # Get input video FPS
156
+ num_real_frames = len(vr)
157
+ #print(f"Video loaded: {num_real_frames} frames, FPS: {fps}")
158
+
159
+ # Truncate to nearest latent size (multiple of 4)
160
+ latent_size_factor = 4
161
+ num_frames = (num_real_frames // latent_size_factor) * latent_size_factor
162
+ #if num_frames != num_real_frames:
163
+ #print(f"Truncating video from {num_real_frames} to {num_frames} frames for latent size compatibility")
164
+ num_real_frames = num_frames
165
+
166
+ # 20250506 pftq: Read frames
167
+ #print("Reading video frames...")
168
+ frames = vr.get_batch(range(num_real_frames)).asnumpy() # Shape: (num_real_frames, height, width, channels)
169
+ #print(f"Frames read: {frames.shape}")
170
+
171
+ # 20250506 pftq: Get native video resolution
172
+ native_height, native_width = frames.shape[1], frames.shape[2]
173
+ #print(f"Native video resolution: {native_width}x{native_height}")
174
+
175
+ # 20250506 pftq: Use native resolution if height/width not specified, otherwise use provided values
176
+ target_height = native_height if height is None else height
177
+ target_width = native_width if width is None else width
178
+
179
+ # 20250506 pftq: Adjust to nearest bucket for model compatibility
180
+ if not no_resize:
181
+ target_height, target_width = find_nearest_bucket(target_height, target_width, resolution=resolution)
182
+ #print(f"Adjusted resolution: {target_width}x{target_height}")
183
+ #else:
184
+ #print(f"Using native resolution without resizing: {target_width}x{target_height}")
185
+
186
+ # 20250506 pftq: Preprocess frames to match original image processing
187
+ processed_frames = []
188
+ for i, frame in enumerate(frames):
189
+ #print(f"Preprocessing frame {i+1}/{num_frames}")
190
+ frame_np = resize_and_center_crop(frame, target_width=target_width, target_height=target_height)
191
+ processed_frames.append(frame_np)
192
+ processed_frames = np.stack(processed_frames) # Shape: (num_real_frames, height, width, channels)
193
+ #print(f"Frames preprocessed: {processed_frames.shape}")
194
+
195
+ # 20250506 pftq: Save first frame for CLIP vision encoding
196
+ input_image_np = processed_frames[0]
197
+
198
+ # 20250506 pftq: Convert to tensor and normalize to [-1, 1]
199
+ #print("Converting frames to tensor...")
200
+ frames_pt = torch.from_numpy(processed_frames).float() / 127.5 - 1
201
+ frames_pt = frames_pt.permute(0, 3, 1, 2) # Shape: (num_real_frames, channels, height, width)
202
+ frames_pt = frames_pt.unsqueeze(0) # Shape: (1, num_real_frames, channels, height, width)
203
+ frames_pt = frames_pt.permute(0, 2, 1, 3, 4) # Shape: (1, channels, num_real_frames, height, width)
204
+ #print(f"Tensor shape: {frames_pt.shape}")
205
+
206
+ # 20250506 pftq: Move to device
207
+ #print(f"Moving tensor to device: {device}")
208
+ frames_pt = frames_pt.to(device)
209
+ #print("Tensor moved to device")
210
+
211
+ # 20250506 pftq: Move VAE to device
212
+ #print(f"Moving VAE to device: {device}")
213
+ vae.to(device)
214
+ #print("VAE moved to device")
215
+
216
+ # 20250506 pftq: Encode frames in batches
217
+ #print(f"Encoding input video frames in VAE batch size {vae_batch_size} (reduce if memory issues here or if forcing video resolution)")
218
+ latents = []
219
+ vae.eval()
220
+ with torch.no_grad():
221
+ for i in tqdm(range(0, frames_pt.shape[2], vae_batch_size), desc="Encoding video frames", mininterval=0.1):
222
+ #print(f"Encoding batch {i//vae_batch_size + 1}: frames {i} to {min(i + vae_batch_size, frames_pt.shape[2])}")
223
+ batch = frames_pt[:, :, i:i + vae_batch_size] # Shape: (1, channels, batch_size, height, width)
224
+ try:
225
+ # 20250506 pftq: Log GPU memory before encoding
226
+ if device == "cuda":
227
+ free_mem = torch.cuda.memory_allocated() / 1024**3
228
+ #print(f"GPU memory before encoding: {free_mem:.2f} GB")
229
+ batch_latent = vae_encode(batch, vae)
230
+ # 20250506 pftq: Synchronize CUDA to catch issues
231
+ if device == "cuda":
232
+ torch.cuda.synchronize()
233
+ #print(f"GPU memory after encoding: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
234
+ latents.append(batch_latent)
235
+ #print(f"Batch encoded, latent shape: {batch_latent.shape}")
236
+ except RuntimeError as e:
237
+ print(f"Error during VAE encoding: {str(e)}")
238
+ if device == "cuda" and "out of memory" in str(e).lower():
239
+ print("CUDA out of memory, try reducing vae_batch_size or using CPU")
240
+ raise
241
+
242
+ # 20250506 pftq: Concatenate latents
243
+ #print("Concatenating latents...")
244
+ history_latents = torch.cat(latents, dim=2) # Shape: (1, channels, frames, height//8, width//8)
245
+ #print(f"History latents shape: {history_latents.shape}")
246
+
247
+ # 20250506 pftq: Get first frame's latent
248
+ start_latent = history_latents[:, :, :1] # Shape: (1, channels, 1, height//8, width//8)
249
+ #print(f"Start latent shape: {start_latent.shape}")
250
+
251
+ # 20250506 pftq: Move VAE back to CPU to free GPU memory
252
+ if device == "cuda":
253
+ vae.to(cpu)
254
+ torch.cuda.empty_cache()
255
+ #print("VAE moved back to CPU, CUDA cache cleared")
256
+
257
+ return start_latent, input_image_np, history_latents, fps, target_height, target_width
258
+
259
+ except Exception as e:
260
+ print(f"Error in video_encode: {str(e)}")
261
+ raise
262
+
263
+ # 20250508 pftq: for saving prompt to mp4 metadata comments
264
+ def set_mp4_comments_imageio_ffmpeg(input_file, comments):
265
+ try:
266
+ # Get the path to the bundled FFmpeg binary from imageio-ffmpeg
267
+ ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
268
+
269
+ # Check if input file exists
270
+ if not os.path.exists(input_file):
271
+ #print(f"Error: Input file {input_file} does not exist")
272
+ return False
273
+
274
+ # Create a temporary file path
275
+ temp_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False).name
276
+
277
+ # FFmpeg command using the bundled binary
278
+ command = [
279
+ ffmpeg_path, # Use imageio-ffmpeg's FFmpeg
280
+ '-i', input_file, # input file
281
+ '-metadata', f'comment={comments}', # set comment metadata
282
+ '-c:v', 'copy', # copy video stream without re-encoding
283
+ '-c:a', 'copy', # copy audio stream without re-encoding
284
+ '-y', # overwrite output file if it exists
285
+ temp_file # temporary output file
286
+ ]
287
+
288
+ # Run the FFmpeg command
289
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
290
+
291
+ if result.returncode == 0:
292
+ # Replace the original file with the modified one
293
+ shutil.move(temp_file, input_file)
294
+ #print(f"Successfully added comments to {input_file}")
295
+ return True
296
+ else:
297
+ # Clean up temp file if FFmpeg fails
298
+ if os.path.exists(temp_file):
299
+ os.remove(temp_file)
300
+ #print(f"Error: FFmpeg failed with message:\n{result.stderr}")
301
+ return False
302
+
303
+ except Exception as e:
304
+ # Clean up temp file in case of other errors
305
+ if 'temp_file' in locals() and os.path.exists(temp_file):
306
+ os.remove(temp_file)
307
+ print(f"Error saving prompt to video metadata, ffmpeg may be required: "+str(e))
308
+ return False
309
+
310
+ @torch.no_grad()
311
+ 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):
312
+ def encode_prompt(prompt, n_prompt):
313
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
314
+
315
+ if cfg == 1:
316
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
317
+ else:
318
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
319
+
320
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
321
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
322
+
323
+ llama_vec = llama_vec.to(transformer.dtype)
324
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
325
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
326
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
327
+ return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
328
+
329
+ total_latent_sections = (total_second_length * fps_number) / (latent_window_size * 4)
330
+ total_latent_sections = int(max(round(total_latent_sections), 1))
331
+
332
+ first_section_index = max(min(math.floor(image_position * (total_latent_sections - 1) / 100), (total_latent_sections - 1)), 0)
333
+ section_index = first_section_index
334
+ forward = (image_position == 0)
335
+
336
+ job_id = generate_timestamp()
337
+
338
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
339
+
340
+ try:
341
+ # Clean GPU
342
+ if not high_vram:
343
+ unload_complete_models(
344
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
345
+ )
346
+
347
+ # Text encoding
348
+
349
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
350
+
351
+ if not high_vram:
352
+ 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.
353
+ load_model_as_complete(text_encoder_2, target_device=gpu)
354
+
355
+ prompt_parameters = []
356
+
357
+ for prompt_part in prompts[:total_latent_sections]:
358
+ prompt_parameters.append(encode_prompt(prompt_part, n_prompt))
359
+
360
+ # Clean GPU
361
+ if not high_vram:
362
+ unload_complete_models(
363
+ text_encoder, text_encoder_2
364
+ )
365
+
366
+ # Processing input image
367
+
368
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Image processing ...'))))
369
+
370
+ H, W, C = input_image.shape
371
+ height, width = find_nearest_bucket(H, W, resolution=resolution)
372
+
373
+ def get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram):
374
+ input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height)
375
+
376
+ #Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png'))
377
+
378
+ input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1
379
+ input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None]
380
+
381
+ # VAE encoding
382
+
383
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAE encoding ...'))))
384
+
385
+ if not high_vram:
386
+ load_model_as_complete(vae, target_device=gpu)
387
+
388
+ start_latent = vae_encode(input_image_pt, vae)
389
+
390
+ # CLIP Vision
391
+
392
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
393
+
394
+ if not high_vram:
395
+ unload_complete_models(vae)
396
+ load_model_as_complete(image_encoder, target_device=gpu)
397
+
398
+ image_encoder_last_hidden_state = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder).last_hidden_state
399
+
400
+ if not high_vram:
401
+ unload_complete_models(image_encoder)
402
+
403
+ return [start_latent, image_encoder_last_hidden_state]
404
+
405
+ [start_latent, image_encoder_last_hidden_state] = get_start_latent(input_image, height, width, vae, gpu, image_encoder, high_vram)
406
+
407
+ # Dtype
408
+
409
+ image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
410
+
411
+ # Sampling
412
+
413
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
414
+
415
+ rnd = torch.Generator("cpu").manual_seed(seed)
416
+
417
+ history_latents = torch.zeros(size=(1, 16, 16 + 2 + 1, height // 8, width // 8), dtype=torch.float32, device=cpu)
418
+ start_latent = start_latent.to(history_latents)
419
+ history_pixels = None
420
+
421
+ history_latents = torch.cat([history_latents, start_latent] if forward else [start_latent, history_latents], dim=2)
422
+ total_generated_latent_frames = 1
423
+
424
+ if enable_preview:
425
+ def callback(d):
426
+ preview = d['denoised']
427
+ preview = vae_decode_fake(preview)
428
+
429
+ preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
430
+ preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
431
+
432
+ if stream.input_queue.top() == 'end':
433
+ stream.output_queue.push(('end', None))
434
+ raise KeyboardInterrupt('User ends the task.')
435
+
436
+ current_step = d['i'] + 1
437
+ percentage = int(100.0 * current_step / steps)
438
+ hint = f'Sampling {current_step}/{steps}'
439
+ 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 ...'
440
+ stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
441
+ return
442
+ else:
443
+ def callback(d):
444
+ return
445
+
446
+ indices = torch.arange(0, 1 + 16 + 2 + 1 + latent_window_size).unsqueeze(0)
447
+ if forward:
448
+ 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)
449
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
450
+ else:
451
+ 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)
452
+ clean_latent_indices = torch.cat([clean_latent_1x_indices, clean_latent_indices_start], dim=1)
453
+
454
+ def post_process(forward, 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):
455
+ total_generated_latent_frames += int(generated_latents.shape[2])
456
+ history_latents = torch.cat([history_latents, generated_latents.to(history_latents)] if forward else [generated_latents.to(history_latents), history_latents], dim=2)
457
+
458
+ if not high_vram:
459
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
460
+ load_model_as_complete(vae, target_device=gpu)
461
+
462
+ if history_pixels is None:
463
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :] if forward else history_latents[:, :, :total_generated_latent_frames, :, :]
464
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
465
+ else:
466
+ section_latent_frames = latent_window_size * 2
467
+ overlapped_frames = latent_window_size * 4 - 3
468
+
469
+ if forward:
470
+ real_history_latents = history_latents[:, :, -min(section_latent_frames, total_generated_latent_frames):, :, :]
471
+ history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames)
472
+ else:
473
+ real_history_latents = history_latents[:, :, :min(section_latent_frames, total_generated_latent_frames), :, :]
474
+ history_pixels = soft_append_bcthw(vae_decode(real_history_latents, vae).cpu(), history_pixels, overlapped_frames)
475
+
476
+ if not high_vram:
477
+ unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer)
478
+
479
+ if enable_preview or section_index == (0 if first_section_index == (total_latent_sections - 1) else (total_latent_sections - 1)):
480
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
481
+
482
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=fps_number, crf=mp4_crf)
483
+
484
+ print(f'Decoded. Current latent shape pixel shape {history_pixels.shape}')
485
+
486
+ stream.output_queue.push(('file', output_filename))
487
+ return [total_generated_latent_frames, history_latents, history_pixels]
488
+
489
+ while section_index < total_latent_sections:
490
+ if stream.input_queue.top() == 'end':
491
+ stream.output_queue.push(('end', None))
492
+ return
493
+
494
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
495
+
496
+ prompt_index = min(section_index, len(prompt_parameters) - 1)
497
+
498
+ [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters[prompt_index]
499
+
500
+ if prompt_index < len(prompt_parameters) - 1 or (prompt_index == total_latent_sections - 1):
501
+ prompt_parameters[prompt_index] = None
502
+
503
+ if not high_vram:
504
+ unload_complete_models()
505
+ move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
506
+
507
+ if use_teacache:
508
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
509
+ else:
510
+ transformer.initialize_teacache(enable_teacache=False)
511
+
512
+ if forward:
513
+ clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents[:, :, -(16 + 2 + 1):, :, :].split([16, 2, 1], dim=2)
514
+ clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
515
+ else:
516
+ clean_latents_1x, clean_latents_2x, clean_latents_4x = history_latents[:, :, :(1 + 2 + 16), :, :].split([1, 2, 16], dim=2)
517
+ clean_latents = torch.cat([clean_latents_1x, start_latent], dim=2)
518
+
519
+ generated_latents = sample_hunyuan(
520
+ transformer=transformer,
521
+ sampler='unipc',
522
+ width=width,
523
+ height=height,
524
+ frames=latent_window_size * 4 - 3,
525
+ real_guidance_scale=cfg,
526
+ distilled_guidance_scale=gs,
527
+ guidance_rescale=rs,
528
+ # shift=3.0,
529
+ num_inference_steps=steps,
530
+ generator=rnd,
531
+ prompt_embeds=llama_vec,
532
+ prompt_embeds_mask=llama_attention_mask,
533
+ prompt_poolers=clip_l_pooler,
534
+ negative_prompt_embeds=llama_vec_n,
535
+ negative_prompt_embeds_mask=llama_attention_mask_n,
536
+ negative_prompt_poolers=clip_l_pooler_n,
537
+ device=gpu,
538
+ dtype=torch.bfloat16,
539
+ image_embeddings=image_encoder_last_hidden_state,
540
+ latent_indices=latent_indices,
541
+ clean_latents=clean_latents,
542
+ clean_latent_indices=clean_latent_indices,
543
+ clean_latents_2x=clean_latents_2x,
544
+ clean_latent_2x_indices=clean_latent_2x_indices,
545
+ clean_latents_4x=clean_latents_4x,
546
+ clean_latent_4x_indices=clean_latent_4x_indices,
547
+ callback=callback,
548
+ )
549
+
550
+ [total_generated_latent_frames, history_latents, history_pixels] = post_process(forward, 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)
551
+
552
+ if not forward:
553
+ if section_index > 0:
554
+ section_index -= 1
555
+ else:
556
+ 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)
557
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
558
+
559
+ real_history_latents = history_latents[:, :, :total_generated_latent_frames, :, :]
560
+ zero_latents = history_latents[:, :, total_generated_latent_frames:, :, :]
561
+ history_latents = torch.cat([zero_latents, real_history_latents], dim=2)
562
+ real_history_latents = zero_latents = None
563
+
564
+ forward = True
565
+ section_index = first_section_index
566
+
567
+ if forward:
568
+ section_index += 1
569
+ except:
570
+ traceback.print_exc()
571
+
572
+ if not high_vram:
573
+ unload_complete_models(
574
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
575
+ )
576
+
577
+ stream.output_queue.push(('end', None))
578
+ return
579
+
580
+ # 20250506 pftq: Modified worker to accept video input and clean frame count
581
+ @torch.no_grad()
582
+ 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):
583
+ def encode_prompt(prompt, n_prompt):
584
+ llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
585
+
586
+ if cfg == 1:
587
+ llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler)
588
+ else:
589
+ llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
590
+
591
+ llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512)
592
+ llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512)
593
+
594
+ llama_vec = llama_vec.to(transformer.dtype)
595
+ llama_vec_n = llama_vec_n.to(transformer.dtype)
596
+ clip_l_pooler = clip_l_pooler.to(transformer.dtype)
597
+ clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype)
598
+ return [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n]
599
+
600
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Starting ...'))))
601
+
602
+ try:
603
+ # 20250506 pftq: Processing input video instead of image
604
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Video processing ...'))))
605
+
606
+ # 20250506 pftq: Encode video
607
+ start_latent, input_image_np, video_latents, fps, height, width = video_encode(input_video, resolution, no_resize, vae, vae_batch_size=vae_batch, device=gpu)
608
+ start_latent = start_latent.to(dtype=torch.float32, device=cpu)
609
+ video_latents = video_latents.cpu()
610
+
611
+ total_latent_sections = (total_second_length * fps) / (latent_window_size * 4)
612
+ total_latent_sections = int(max(round(total_latent_sections), 1))
613
+
614
+ # Clean GPU
615
+ if not high_vram:
616
+ unload_complete_models(
617
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
618
+ )
619
+
620
+ # Text encoding
621
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Text encoding ...'))))
622
+
623
+ if not high_vram:
624
+ 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.
625
+ load_model_as_complete(text_encoder_2, target_device=gpu)
626
+
627
+ prompt_parameters = []
628
+
629
+ for prompt_part in prompts[:total_latent_sections]:
630
+ prompt_parameters.append(encode_prompt(prompt_part, n_prompt))
631
+
632
+ # Clean GPU
633
+ if not high_vram:
634
+ unload_complete_models(
635
+ text_encoder, text_encoder_2
636
+ )
637
+
638
+ # CLIP Vision
639
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Vision encoding ...'))))
640
+
641
+ if not high_vram:
642
+ load_model_as_complete(image_encoder, target_device=gpu)
643
+
644
+ image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder)
645
+
646
+ # Clean GPU
647
+ if not high_vram:
648
+ unload_complete_models(image_encoder)
649
+
650
+ image_encoder_last_hidden_state = image_encoder_output.last_hidden_state
651
+
652
+ # Dtype
653
+ image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype)
654
+
655
+ if enable_preview:
656
+ def callback(d):
657
+ preview = d['denoised']
658
+ preview = vae_decode_fake(preview)
659
+
660
+ preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8)
661
+ preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c')
662
+
663
+ if stream.input_queue.top() == 'end':
664
+ stream.output_queue.push(('end', None))
665
+ raise KeyboardInterrupt('User ends the task.')
666
+
667
+ current_step = d['i'] + 1
668
+ percentage = int(100.0 * current_step / steps)
669
+ hint = f'Sampling {current_step}/{steps}'
670
+ 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}...'
671
+ stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint))))
672
+ return
673
+ else:
674
+ def callback(d):
675
+ return
676
+
677
+ def compute_latent(history_latents, latent_window_size, num_clean_frames, start_latent):
678
+ # 20250506 pftq: Use user-specified number of context frames, matching original allocation for num_clean_frames=2
679
+ available_frames = history_latents.shape[2] # Number of latent frames
680
+ max_pixel_frames = min(latent_window_size * 4 - 3, available_frames * 4) # Cap at available pixel frames
681
+ adjusted_latent_frames = max(1, (max_pixel_frames + 3) // 4) # Convert back to latent frames
682
+ # Adjust num_clean_frames to match original behavior: num_clean_frames=2 means 1 frame for clean_latents_1x
683
+ effective_clean_frames = max(0, num_clean_frames - 1)
684
+ 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
685
+ 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
686
+ 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
687
+
688
+ total_context_frames = num_4x_frames + num_2x_frames + effective_clean_frames
689
+ total_context_frames = min(total_context_frames, available_frames) # 20250507 pftq: Edge case for <=1 sec videos
690
+
691
+ indices = torch.arange(0, 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
692
+ clean_latent_indices_start, clean_latent_4x_indices, clean_latent_2x_indices, clean_latent_1x_indices, latent_indices = indices.split(
693
+ [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
694
+ )
695
+ clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1)
696
+
697
+ # 20250506 pftq: Split history_latents dynamically based on available frames
698
+ fallback_frame_count = 2 # 20250507 pftq: Changed 0 to 2 Edge case for <=1 sec videos
699
+ context_frames = clean_latents_4x = clean_latents_2x = clean_latents_1x = history_latents[:, :, :fallback_frame_count, :, :]
700
+
701
+ if total_context_frames > 0:
702
+ context_frames = history_latents[:, :, -total_context_frames:, :, :]
703
+ split_sizes = [num_4x_frames, num_2x_frames, effective_clean_frames]
704
+ split_sizes = [s for s in split_sizes if s > 0] # Remove zero sizes
705
+ if split_sizes:
706
+ splits = context_frames.split(split_sizes, dim=2)
707
+ split_idx = 0
708
+
709
+ if num_4x_frames > 0:
710
+ clean_latents_4x = splits[split_idx]
711
+ split_idx = 1
712
+ if clean_latents_4x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
713
+ print("Edge case for <=1 sec videos 4x")
714
+ clean_latents_4x = clean_latents_4x.expand(-1, -1, 2, -1, -1)
715
+
716
+ if num_2x_frames > 0 and split_idx < len(splits):
717
+ clean_latents_2x = splits[split_idx]
718
+ if clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
719
+ print("Edge case for <=1 sec videos 2x")
720
+ clean_latents_2x = clean_latents_2x.expand(-1, -1, 2, -1, -1)
721
+ split_idx += 1
722
+ elif clean_latents_2x.shape[2] < 2: # 20250507 pftq: edge case for <=1 sec videos
723
+ clean_latents_2x = clean_latents_4x
724
+
725
+ if effective_clean_frames > 0 and split_idx < len(splits):
726
+ clean_latents_1x = splits[split_idx]
727
+
728
+ clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2)
729
+
730
+ # 20250507 pftq: Fix for <=1 sec videos.
731
+ max_frames = min(latent_window_size * 4 - 3, history_latents.shape[2] * 4)
732
+ 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]
733
+
734
+ for idx in range(batch):
735
+ if batch > 1:
736
+ print(f"Beginning video {idx+1} of {batch} with seed {seed} ")
737
+
738
+ #job_id = generate_timestamp()
739
+ 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
740
+
741
+ # Sampling
742
+ stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'Start sampling ...'))))
743
+
744
+ rnd = torch.Generator("cpu").manual_seed(seed)
745
+
746
+ # 20250506 pftq: Initialize history_latents with video latents
747
+ history_latents = video_latents
748
+ total_generated_latent_frames = history_latents.shape[2]
749
+ # 20250506 pftq: Initialize history_pixels to fix UnboundLocalError
750
+ history_pixels = None
751
+ previous_video = None
752
+
753
+ for section_index in range(total_latent_sections):
754
+ if stream.input_queue.top() == 'end':
755
+ stream.output_queue.push(('end', None))
756
+ return
757
+
758
+ print(f'section_index = {section_index}, total_latent_sections = {total_latent_sections}')
759
+
760
+ if len(prompt_parameters) > 0:
761
+ [llama_vec, clip_l_pooler, llama_vec_n, clip_l_pooler_n, llama_attention_mask, llama_attention_mask_n] = prompt_parameters.pop(0)
762
+
763
+ if not high_vram:
764
+ unload_complete_models()
765
+ move_model_to_device_with_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=gpu_memory_preservation)
766
+
767
+ if use_teacache:
768
+ transformer.initialize_teacache(enable_teacache=True, num_steps=steps)
769
+ else:
770
+ transformer.initialize_teacache(enable_teacache=False)
771
+
772
+ [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)
773
+
774
+ generated_latents = sample_hunyuan(
775
+ transformer=transformer,
776
+ sampler='unipc',
777
+ width=width,
778
+ height=height,
779
+ frames=max_frames,
780
+ real_guidance_scale=cfg,
781
+ distilled_guidance_scale=gs,
782
+ guidance_rescale=rs,
783
+ num_inference_steps=steps,
784
+ generator=rnd,
785
+ prompt_embeds=llama_vec,
786
+ prompt_embeds_mask=llama_attention_mask,
787
+ prompt_poolers=clip_l_pooler,
788
+ negative_prompt_embeds=llama_vec_n,
789
+ negative_prompt_embeds_mask=llama_attention_mask_n,
790
+ negative_prompt_poolers=clip_l_pooler_n,
791
+ device=gpu,
792
+ dtype=torch.bfloat16,
793
+ image_embeddings=image_encoder_last_hidden_state,
794
+ latent_indices=latent_indices,
795
+ clean_latents=clean_latents,
796
+ clean_latent_indices=clean_latent_indices,
797
+ clean_latents_2x=clean_latents_2x,
798
+ clean_latent_2x_indices=clean_latent_2x_indices,
799
+ clean_latents_4x=clean_latents_4x,
800
+ clean_latent_4x_indices=clean_latent_4x_indices,
801
+ callback=callback,
802
+ )
803
+
804
+ total_generated_latent_frames += int(generated_latents.shape[2])
805
+ history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)
806
+
807
+ if not high_vram:
808
+ offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)
809
+ load_model_as_complete(vae, target_device=gpu)
810
+
811
+ if history_pixels is None:
812
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]
813
+ history_pixels = vae_decode(real_history_latents, vae).cpu()
814
+ else:
815
+ section_latent_frames = latent_window_size * 2
816
+ overlapped_frames = min(latent_window_size * 4 - 3, history_pixels.shape[2])
817
+
818
+ real_history_latents = history_latents[:, :, -min(total_generated_latent_frames, section_latent_frames):, :, :]
819
+ history_pixels = soft_append_bcthw(history_pixels, vae_decode(real_history_latents, vae).cpu(), overlapped_frames)
820
+
821
+ if not high_vram:
822
+ unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer)
823
+
824
+ if enable_preview or section_index == total_latent_sections - 1:
825
+ output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')
826
+
827
+ # 20250506 pftq: Use input video FPS for output
828
+ save_bcthw_as_mp4(history_pixels, output_filename, fps=fps, crf=mp4_crf)
829
+ print(f"Latest video saved: {output_filename}")
830
+ # 20250508 pftq: Save prompt to mp4 metadata comments
831
+ set_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompts} | Negative Prompt: {n_prompt}");
832
+ print(f"Prompt saved to mp4 metadata comments: {output_filename}")
833
+
834
+ # 20250506 pftq: Clean up previous partial files
835
+ if previous_video is not None and os.path.exists(previous_video):
836
+ try:
837
+ os.remove(previous_video)
838
+ print(f"Previous partial video deleted: {previous_video}")
839
+ except Exception as e:
840
+ print(f"Error deleting previous partial video {previous_video}: {e}")
841
+ previous_video = output_filename
842
+
843
+ print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')
844
+
845
+ stream.output_queue.push(('file', output_filename))
846
+
847
+ seed = (seed + 1) % np.iinfo(np.int32).max
848
+
849
+ except:
850
+ traceback.print_exc()
851
+
852
+ if not high_vram:
853
+ unload_complete_models(
854
+ text_encoder, text_encoder_2, image_encoder, vae, transformer
855
+ )
856
+
857
+ stream.output_queue.push(('end', None))
858
+ return
859
+
860
+ def 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):
861
+ return allocation_time
862
+
863
+ # Remove this decorator if you run on local
864
+ @spaces.GPU(duration=get_duration)
865
+ 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
866
+ ):
867
+ start = time.time()
868
+ global stream
869
+ stream = AsyncStream()
870
+
871
+ 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)
872
+
873
+ output_filename = None
874
+
875
+ while True:
876
+ flag, data = stream.output_queue.next()
877
+
878
+ if flag == 'file':
879
+ output_filename = data
880
+ yield gr.update(value=output_filename, label="Previewed Frames"), gr.skip(), gr.skip(), gr.skip(), gr.update(interactive=False), gr.update(interactive=True), gr.skip()
881
+
882
+ if flag == 'progress':
883
+ preview, desc, html = data
884
+ yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.skip()
885
+
886
+ if flag == 'end':
887
+ end = time.time()
888
+ secondes = int(end - start)
889
+ minutes = math.floor(secondes / 60)
890
+ secondes = secondes - (minutes * 60)
891
+ hours = math.floor(minutes / 60)
892
+ minutes = minutes - (hours * 60)
893
+ yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), gr.skip(), "The process has lasted " + \
894
+ ((str(hours) + " h, ") if hours != 0 else "") + \
895
+ ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
896
+ str(secondes) + " sec. " + \
897
+ "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. If you do not see the generated video above, the process may have failed. See the logs for more information. If you see an error like ''NVML_SUCCESS == r INTERNAL ASSERT FAILED'', you probably haven't enough VRAM. Test an example or other options to compare. You can share your inputs to the original space or set your space in public for a peer review.", gr.update(interactive=True), gr.update(interactive=False), gr.update(visible = False)
898
+ break
899
+
900
+ def process(input_image,
901
+ image_position=0,
902
+ prompt="",
903
+ generation_mode="image",
904
+ n_prompt="",
905
+ randomize_seed=True,
906
+ seed=31337,
907
+ auto_allocation=True,
908
+ allocation_time=180,
909
+ resolution=640,
910
+ total_second_length=5,
911
+ latent_window_size=9,
912
+ steps=25,
913
+ cfg=1.0,
914
+ gs=10.0,
915
+ rs=0.0,
916
+ gpu_memory_preservation=6,
917
+ enable_preview=True,
918
+ use_teacache=False,
919
+ mp4_crf=16,
920
+ fps_number=30
921
+ ):
922
+ if auto_allocation:
923
+ allocation_time = min(total_second_length * 60 * (1.5 if use_teacache else 3.0) * (1 + ((steps - 25) / 25))**2, 600)
924
+
925
+ if input_image_debug_value[0] is not None or prompt_debug_value[0] is not None or total_second_length_debug_value[0] is not None:
926
+ input_image = input_image_debug_value[0]
927
+ prompt = prompt_debug_value[0]
928
+ total_second_length = total_second_length_debug_value[0]
929
+ allocation_time = min(total_second_length_debug_value[0] * 60 * 100, 600)
930
+ input_image_debug_value[0] = prompt_debug_value[0] = total_second_length_debug_value[0] = None
931
+
932
+ if torch.cuda.device_count() == 0:
933
+ gr.Warning('Set this space to GPU config to make it work.')
934
+ yield gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.update(visible = False)
935
+ return
936
+
937
+ if randomize_seed:
938
+ seed = random.randint(0, np.iinfo(np.int32).max)
939
+
940
+ prompts = prompt.split(";")
941
+
942
+ # assert input_image is not None, 'No input image!'
943
+ if generation_mode == "text":
944
+ default_height, default_width = 640, 640
945
+ input_image = np.ones((default_height, default_width, 3), dtype=np.uint8) * 255
946
+ print("No input image provided. Using a blank white image.")
947
+
948
+ yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip()
949
+
950
+ yield from process_on_gpu(input_image,
951
+ image_position,
952
+ prompts,
953
+ generation_mode,
954
+ n_prompt,
955
+ seed,
956
+ resolution,
957
+ total_second_length,
958
+ allocation_time,
959
+ latent_window_size,
960
+ steps,
961
+ cfg,
962
+ gs,
963
+ rs,
964
+ gpu_memory_preservation,
965
+ enable_preview,
966
+ use_teacache,
967
+ mp4_crf,
968
+ fps_number
969
+ )
970
+
971
+ def 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):
972
+ return allocation_time
973
+
974
+ # Remove this decorator if you run on local
975
+ @spaces.GPU(duration=get_duration_video)
976
+ 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):
977
+ start = time.time()
978
+ global stream
979
+ stream = AsyncStream()
980
+
981
+ # 20250506 pftq: Pass num_clean_frames, vae_batch, etc
982
+ 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)
983
+
984
+ output_filename = None
985
+
986
+ while True:
987
+ flag, data = stream.output_queue.next()
988
+
989
+ if flag == 'file':
990
+ output_filename = data
991
+ yield gr.update(value=output_filename, label="Previewed Frames"), gr.skip(), gr.skip(), gr.skip(), gr.update(interactive=False), gr.update(interactive=True), gr.skip()
992
+
993
+ if flag == 'progress':
994
+ preview, desc, html = data
995
+ yield gr.update(label="Previewed Frames"), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.skip() # 20250506 pftq: Keep refreshing the video in case it got hidden when the tab was in the background
996
+
997
+ if flag == 'end':
998
+ end = time.time()
999
+ secondes = int(end - start)
1000
+ minutes = math.floor(secondes / 60)
1001
+ secondes = secondes - (minutes * 60)
1002
+ hours = math.floor(minutes / 60)
1003
+ minutes = minutes - (hours * 60)
1004
+ yield gr.update(value=output_filename, label="Finished Frames"), gr.update(visible=False), desc + \
1005
+ " The process has lasted " + \
1006
+ ((str(hours) + " h, ") if hours != 0 else "") + \
1007
+ ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + \
1008
+ str(secondes) + " sec. " + \
1009
+ " 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. If you do not see the generated video above, the process may have failed. See the logs for more information. If you see an error like ''NVML_SUCCESS == r INTERNAL ASSERT FAILED'', you probably haven't enough VRAM. Test an example or other options to compare. You can share your inputs to the original space or set your space in public for a peer review.", '', gr.update(interactive=True), gr.update(interactive=False), gr.update(visible = False)
1010
+ break
1011
+
1012
+ def 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):
1013
+ global high_vram
1014
+ if auto_allocation:
1015
+ allocation_time = min(total_second_length * 60 * (2.5 if use_teacache else 3.5) * (1 + ((steps - 25) / 25))**2, 600)
1016
+
1017
+ if input_video_debug_value[0] is not None or prompt_debug_value[0] is not None or total_second_length_debug_value[0] is not None:
1018
+ input_video = input_video_debug_value[0]
1019
+ prompt = prompt_debug_value[0]
1020
+ total_second_length = total_second_length_debug_value[0]
1021
+ allocation_time = min(total_second_length_debug_value[0] * 60 * 100, 600)
1022
+ input_video_debug_value[0] = prompt_debug_value[0] = total_second_length_debug_value[0] = None
1023
+
1024
+ if torch.cuda.device_count() == 0:
1025
+ gr.Warning('Set this space to GPU config to make it work.')
1026
+ yield gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.update(visible = False)
1027
+ return
1028
+
1029
+ if randomize_seed:
1030
+ seed = random.randint(0, np.iinfo(np.int32).max)
1031
+
1032
+ prompts = prompt.split(";")
1033
+
1034
+ # 20250506 pftq: Updated assertion for video input
1035
+ assert input_video is not None, 'No input video!'
1036
+
1037
+ yield gr.update(label="Previewed Frames"), None, '', '', gr.update(interactive=False), gr.update(interactive=True), gr.skip()
1038
+
1039
+ # 20250507 pftq: Even the H100 needs offloading if the video dimensions are 720p or higher
1040
+ if high_vram and (no_resize or resolution>640):
1041
+ print("Disabling high vram mode due to no resize and/or potentially higher resolution...")
1042
+ high_vram = False
1043
+ vae.enable_slicing()
1044
+ vae.enable_tiling()
1045
+ DynamicSwapInstaller.install_model(transformer, device=gpu)
1046
+ DynamicSwapInstaller.install_model(text_encoder, device=gpu)
1047
+
1048
+ # 20250508 pftq: automatically set distilled cfg to 1 if cfg is used
1049
+ if cfg > 1:
1050
+ gs = 1
1051
+
1052
+ yield from 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)
1053
+
1054
+ def end_process():
1055
+ stream.input_queue.push('end')
1056
+
1057
+ timeless_prompt_value = [""]
1058
+ timed_prompts = {}
1059
+
1060
+ def handle_prompt_number_change():
1061
+ timed_prompts.clear()
1062
+ return []
1063
+
1064
+ def handle_timeless_prompt_change(timeless_prompt):
1065
+ timeless_prompt_value[0] = timeless_prompt
1066
+ return refresh_prompt()
1067
+
1068
+ def handle_timed_prompt_change(timed_prompt_id, timed_prompt):
1069
+ timed_prompts[timed_prompt_id] = timed_prompt
1070
+ return refresh_prompt()
1071
+
1072
+ def refresh_prompt():
1073
+ dict_values = {k: v for k, v in timed_prompts.items()}
1074
+ sorted_dict_values = sorted(dict_values.items(), key=lambda x: x[0])
1075
+ array = []
1076
+ for sorted_dict_value in sorted_dict_values:
1077
+ 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]):
1078
+ array.append(timeless_prompt_value[0] + ". " + sorted_dict_value[1])
1079
+ else:
1080
+ array.append(timeless_prompt_value[0] + sorted_dict_value[1])
1081
+ print(str(array))
1082
+ return ";".join(array)
1083
+
1084
+ title_html = """
1085
+ <h1><center>FramePack</center></h1>
1086
+ <big><center>Generate videos from text/image/video freely, without account, without watermark and download it</center></big>
1087
+ <br/>
1088
+
1089
+ <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>
1090
+ """
1091
+
1092
+ js = """
1093
+ function createGradioAnimation() {
1094
+ window.addEventListener("beforeunload", function(e) {
1095
+ if (document.getElementById('end-button') && !document.getElementById('end-button').disabled) {
1096
+ var confirmationMessage = 'A process is still running. '
1097
+ + 'If you leave before saving, your changes will be lost.';
1098
+
1099
+ (e || window.event).returnValue = confirmationMessage;
1100
+ }
1101
+ return confirmationMessage;
1102
+ });
1103
+ return 'Animation created';
1104
+ }
1105
+ """
1106
+
1107
+ css = make_progress_bar_css()
1108
+ block = gr.Blocks(css=css, js=js).queue()
1109
+ with block:
1110
+ if torch.cuda.device_count() == 0:
1111
+ with gr.Row():
1112
+ gr.HTML("""
1113
+ <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>
1114
+
1115
+ 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.
1116
+ </big></big></big></p>
1117
+ """)
1118
+ gr.HTML(title_html)
1119
+ local_storage = gr.BrowserState(default_local_storage)
1120
+ with gr.Row():
1121
+ with gr.Column():
1122
+ generation_mode = gr.Radio([["Text-to-Video", "text"], ["Image-to-Video", "image"], ["Video Extension", "video"]], elem_id="generation-mode", label="Generation mode", value = "image")
1123
+ 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.")
1124
+ input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)
1125
+ image_position = gr.Slider(label="Image position", minimum=0, maximum=100, value=0, step=1, info='0=Video start; 100=Video end (lower quality)')
1126
+ input_video = gr.Video(sources='upload', label="Input Video", height=320)
1127
+ 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")
1128
+ prompt_number = gr.Slider(label="Timed prompt number", minimum=0, maximum=1000, value=0, step=1, info='Prompts will automatically appear')
1129
+
1130
+ @gr.render(inputs=prompt_number)
1131
+ def show_split(prompt_number):
1132
+ for digit in range(prompt_number):
1133
+ timed_prompt_id = gr.Textbox(value="timed_prompt_" + str(digit), visible=False)
1134
+ timed_prompt = gr.Textbox(label="Timed prompt #" + str(digit + 1), elem_id="timed_prompt_" + str(digit), value="")
1135
+ timed_prompt.change(fn=handle_timed_prompt_change, inputs=[timed_prompt_id, timed_prompt], outputs=[final_prompt])
1136
+
1137
+ final_prompt = gr.Textbox(label="Final prompt", value='', info='Use ; to separate in time; beware to write to stop the previous action')
1138
+ 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.")
1139
+ total_second_length = gr.Slider(label="Video length to generate (seconds if 30 fps)", minimum=1, maximum=120, value=2, step=0.1)
1140
+
1141
+ with gr.Row():
1142
+ start_button = gr.Button(value="🎥 Generate", variant="primary")
1143
+ start_button_video = gr.Button(value="🎥 Generate", variant="primary")
1144
+ end_button = gr.Button(elem_id="end-button", value="End Generation", variant="stop", interactive=False)
1145
+
1146
+ with gr.Accordion("Advanced settings", open=False):
1147
+ 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.')
1148
+ 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.')
1149
+
1150
+ n_prompt = gr.Textbox(label="Negative Prompt", value="Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", info='Requires using normal CFG (undistilled) instead of Distilled (set Distilled=1 and CFG > 1).')
1151
+
1152
+ 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)
1153
+
1154
+ 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.')
1155
+ steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=30, 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.')
1156
+
1157
+ with gr.Row():
1158
+ no_resize = gr.Checkbox(label='Force Original Video Resolution (no Resizing)', value=False, info='Might run out of VRAM (720p requires > 24GB VRAM).')
1159
+ resolution = gr.Dropdown([
1160
+ ["409,600 px (working)", 640],
1161
+ ["451,584 px (working)", 672],
1162
+ ["495,616 px (VRAM pb on HF)", 704],
1163
+ ["589,824 px (not tested)", 768],
1164
+ ["692,224 px (not tested)", 832],
1165
+ ["746,496 px (not tested)", 864],
1166
+ ["921,600 px (not tested)", 960]
1167
+ ], value=672, label="Resolution (width x height)", info="Do not affect the generation time")
1168
+
1169
+ # 20250506 pftq: Reduced default distilled guidance scale to improve adherence to input video
1170
+ 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.')
1171
+ 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')
1172
+ rs = gr.Slider(label="CFG Re-Scale", minimum=0.0, maximum=1.0, value=0.0, step=0.01, info='Should not change')
1173
+
1174
+
1175
+ # 20250506 pftq: Renamed slider to Number of Context Frames and updated description
1176
+ 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.")
1177
+
1178
+ default_vae = 32
1179
+ if high_vram:
1180
+ default_vae = 128
1181
+ elif free_mem_gb>=20:
1182
+ default_vae = 64
1183
+
1184
+ 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.")
1185
+
1186
+
1187
+ 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.")
1188
+
1189
+ 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. ")
1190
+ 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.')
1191
+ with gr.Row():
1192
+ randomize_seed = gr.Checkbox(label='Randomize seed', value=True, info='If checked, the seed is always different')
1193
+ seed = gr.Slider(label="Seed", minimum=0, maximum=np.iinfo(np.int32).max, step=1, randomize=True)
1194
+ with gr.Row():
1195
+ auto_allocation = gr.Checkbox(label='Auto allocation', value=True, info='If checked, the GPU allocation time is estimated from the parameters')
1196
+ allocation_time = gr.Slider(label="GPU allocation time (in seconds)", info='lower=May abort run, higher=Quota penalty for next runs; only useful for ZeroGPU; for instance set to 88 when you have the message "You have exceeded your GPU quota (180s requested vs. 89s left)."', value=180, minimum=60, maximum=320, step=1)
1197
+
1198
+ with gr.Accordion("Debug", open=False):
1199
+ input_image_debug = gr.Image(type="numpy", label="Image Debug", height=320)
1200
+ input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)
1201
+ prompt_debug = gr.Textbox(label="Prompt Debug", value='')
1202
+ total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)
1203
+
1204
+ with gr.Column():
1205
+ warning = gr.HTML(elem_id="warning", value = "<center><big>Your computer must <u>not</u> enter into standby mode.</big><br/>On Chrome, you can force to keep a tab alive in <code>chrome://discards/</code></center>", visible = False)
1206
+ result_video = gr.Video(label="Generated Frames", autoplay=True, show_share_button=False, height=512, loop=True)
1207
+ preview_image = gr.Image(label="Next Latents", height=200, visible=False)
1208
+ progress_desc = gr.Markdown('', elem_classes='no-generating-animation')
1209
+ progress_bar = gr.HTML('', elem_classes='no-generating-animation')
1210
+
1211
+ # 20250506 pftq: Updated inputs to include num_clean_frames
1212
+ ips = [input_image, image_position, end_image, 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]
1213
+ 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]
1214
+
1215
+ with gr.Row(elem_id="text_examples", visible=False):
1216
+ gr.Examples(
1217
+ label = "Examples from text",
1218
+ examples = [
1219
+ [
1220
+ None, # input_image
1221
+ 0, # image_position
1222
+ None, # end_image
1223
+ "Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed",
1224
+ "text", # generation_mode
1225
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1226
+ True, # randomize_seed
1227
+ 42, # seed
1228
+ True, # auto_allocation
1229
+ 180, # allocation_time
1230
+ 672, # resolution
1231
+ 1, # total_second_length
1232
+ 9, # latent_window_size
1233
+ 30, # steps
1234
+ 1.0, # cfg
1235
+ 10.0, # gs
1236
+ 0.0, # rs
1237
+ 6, # gpu_memory_preservation
1238
+ False, # enable_preview
1239
+ False, # use_teacache
1240
+ 16, # mp4_crf
1241
+ 30 # fps_number
1242
+ ]
1243
+ ],
1244
+ run_on_click = True,
1245
+ fn = process,
1246
+ inputs = ips,
1247
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
1248
+ cache_examples = torch.cuda.device_count() > 0,
1249
+ )
1250
+
1251
+ with gr.Row(elem_id="image_examples", visible=False):
1252
+ gr.Examples(
1253
+ label = "Examples from image",
1254
+ examples = [
1255
+ [
1256
+ "./img_examples/Example2.webp", # input_image
1257
+ 0, # image_position
1258
+ None, # end_image
1259
+ "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",
1260
+ "image", # generation_mode
1261
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1262
+ True, # randomize_seed
1263
+ 42, # seed
1264
+ True, # auto_allocation
1265
+ 180, # allocation_time
1266
+ 672, # resolution
1267
+ 1, # total_second_length
1268
+ 9, # latent_window_size
1269
+ 30, # steps
1270
+ 1.0, # cfg
1271
+ 10.0, # gs
1272
+ 0.0, # rs
1273
+ 6, # gpu_memory_preservation
1274
+ False, # enable_preview
1275
+ False, # use_teacache
1276
+ 16, # mp4_crf
1277
+ 30 # fps_number
1278
+ ],
1279
+ [
1280
+ "./img_examples/Example1.png", # input_image
1281
+ 0, # image_position
1282
+ None, # end_image
1283
+ "A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
1284
+ "image", # generation_mode
1285
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1286
+ True, # randomize_seed
1287
+ 42, # seed
1288
+ True, # auto_allocation
1289
+ 180, # allocation_time
1290
+ 672, # resolution
1291
+ 1, # total_second_length
1292
+ 9, # latent_window_size
1293
+ 30, # steps
1294
+ 1.0, # cfg
1295
+ 10.0, # gs
1296
+ 0.0, # rs
1297
+ 6, # gpu_memory_preservation
1298
+ False, # enable_preview
1299
+ True, # use_teacache
1300
+ 16, # mp4_crf
1301
+ 30 # fps_number
1302
+ ],
1303
+ [
1304
+ "./img_examples/Example4.webp", # input_image
1305
+ 1, # image_position
1306
+ None, # end_image
1307
+ "A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
1308
+ "image", # generation_mode
1309
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1310
+ True, # randomize_seed
1311
+ 42, # seed
1312
+ True, # auto_allocation
1313
+ 180, # allocation_time
1314
+ 672, # resolution
1315
+ 1, # total_second_length
1316
+ 9, # latent_window_size
1317
+ 30, # steps
1318
+ 1.0, # cfg
1319
+ 10.0, # gs
1320
+ 0.0, # rs
1321
+ 6, # gpu_memory_preservation
1322
+ False, # enable_preview
1323
+ False, # use_teacache
1324
+ 16, # mp4_crf
1325
+ 30 # fps_number
1326
+ ],
1327
+ [
1328
+ "./img_examples/Example4.webp", # input_image
1329
+ 50, # image_position
1330
+ None, # end_image
1331
+ "A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
1332
+ "image", # generation_mode
1333
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1334
+ True, # randomize_seed
1335
+ 42, # seed
1336
+ True, # auto_allocation
1337
+ 180, # allocation_time
1338
+ 672, # resolution
1339
+ 1, # total_second_length
1340
+ 9, # latent_window_size
1341
+ 30, # steps
1342
+ 1.0, # cfg
1343
+ 10.0, # gs
1344
+ 0.0, # rs
1345
+ 6, # gpu_memory_preservation
1346
+ False, # enable_preview
1347
+ False, # use_teacache
1348
+ 16, # mp4_crf
1349
+ 30 # fps_number
1350
+ ],
1351
+ [
1352
+ "./img_examples/Example4.webp", # input_image
1353
+ 100, # image_position
1354
+ None, # end_image
1355
+ "A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
1356
+ "image", # generation_mode
1357
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1358
+ True, # randomize_seed
1359
+ 42, # seed
1360
+ True, # auto_allocation
1361
+ 180, # allocation_time
1362
+ 672, # resolution
1363
+ 1, # total_second_length
1364
+ 9, # latent_window_size
1365
+ 30, # steps
1366
+ 1.0, # cfg
1367
+ 10.0, # gs
1368
+ 0.0, # rs
1369
+ 6, # gpu_memory_preservation
1370
+ False, # enable_preview
1371
+ False, # use_teacache
1372
+ 16, # mp4_crf
1373
+ 30 # fps_number
1374
+ ],
1375
+ ],
1376
+ run_on_click = True,
1377
+ fn = process,
1378
+ inputs = ips,
1379
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
1380
+ cache_examples = torch.cuda.device_count() > 0,
1381
+ )
1382
+
1383
+ with gr.Row(elem_id="video_examples", visible=False):
1384
+ gr.Examples(
1385
+ label = "Examples from video",
1386
+ examples = [
1387
+ [
1388
+ "./img_examples/Example1.mp4", # input_video
1389
+ "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",
1390
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1391
+ True, # randomize_seed
1392
+ 42, # seed
1393
+ True, # auto_allocation
1394
+ 180, # allocation_time
1395
+ 1, # batch
1396
+ 672, # resolution
1397
+ 1, # total_second_length
1398
+ 9, # latent_window_size
1399
+ 30, # steps
1400
+ 1.0, # cfg
1401
+ 10.0, # gs
1402
+ 0.0, # rs
1403
+ 6, # gpu_memory_preservation
1404
+ False, # enable_preview
1405
+ False, # use_teacache
1406
+ False, # no_resize
1407
+ 16, # mp4_crf
1408
+ 5, # num_clean_frames
1409
+ default_vae
1410
+ ],
1411
+ [
1412
+ "./img_examples/Example1.mp4", # input_video
1413
+ "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",
1414
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1415
+ True, # randomize_seed
1416
+ 42, # seed
1417
+ True, # auto_allocation
1418
+ 180, # allocation_time
1419
+ 1, # batch
1420
+ 672, # resolution
1421
+ 1, # total_second_length
1422
+ 9, # latent_window_size
1423
+ 30, # steps
1424
+ 1.0, # cfg
1425
+ 10.0, # gs
1426
+ 0.0, # rs
1427
+ 6, # gpu_memory_preservation
1428
+ False, # enable_preview
1429
+ True, # use_teacache
1430
+ False, # no_resize
1431
+ 16, # mp4_crf
1432
+ 5, # num_clean_frames
1433
+ default_vae
1434
+ ],
1435
+ ],
1436
+ run_on_click = True,
1437
+ fn = process_video,
1438
+ inputs = ips_video,
1439
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button, warning],
1440
+ cache_examples = torch.cuda.device_count() > 0,
1441
+ )
1442
+
1443
+ gr.Examples(
1444
+ label = "✍️ Examples from text",
1445
+ examples = [
1446
+ [
1447
+ None, # input_image
1448
+ 0, # image_position
1449
+ None, # end_image
1450
+ "Overcrowed street in Japan, photorealistic, realistic, intricate details, 8k, insanely detailed",
1451
+ "text", # generation_mode
1452
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1453
+ True, # randomize_seed
1454
+ 42, # seed
1455
+ True, # auto_allocation
1456
+ 180, # allocation_time
1457
+ 672, # resolution
1458
+ 1, # total_second_length
1459
+ 9, # latent_window_size
1460
+ 30, # steps
1461
+ 1.0, # cfg
1462
+ 10.0, # gs
1463
+ 0.0, # rs
1464
+ 6, # gpu_memory_preservation
1465
+ False, # enable_preview
1466
+ False, # use_teacache
1467
+ 16, # mp4_crf
1468
+ 30 # fps_number
1469
+ ]
1470
+ ],
1471
+ run_on_click = True,
1472
+ fn = process,
1473
+ inputs = ips,
1474
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
1475
+ cache_examples = False,
1476
+ )
1477
+
1478
+ gr.Examples(
1479
+ label = "🖼️ Examples from image",
1480
+ examples = [
1481
+ [
1482
+ "./img_examples/Example1.png", # input_image
1483
+ 0, # image_position
1484
+ "A dolphin emerges from the water, photorealistic, realistic, intricate details, 8k, insanely detailed",
1485
+ "image", # generation_mode
1486
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1487
+ True, # randomize_seed
1488
+ 42, # seed
1489
+ True, # auto_allocation
1490
+ 180, # allocation_time
1491
+ 672, # resolution
1492
+ 1, # total_second_length
1493
+ 9, # latent_window_size
1494
+ 30, # steps
1495
+ 1.0, # cfg
1496
+ 10.0, # gs
1497
+ 0.0, # rs
1498
+ 6, # gpu_memory_preservation
1499
+ False, # enable_preview
1500
+ True, # use_teacache
1501
+ 16, # mp4_crf
1502
+ 30 # fps_number
1503
+ ],
1504
+ [
1505
+ "./img_examples/Example2.webp", # input_image
1506
+ 0, # image_position
1507
+ "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",
1508
+ "image", # generation_mode
1509
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1510
+ True, # randomize_seed
1511
+ 42, # seed
1512
+ True, # auto_allocation
1513
+ 180, # allocation_time
1514
+ 672, # resolution
1515
+ 2, # total_second_length
1516
+ 9, # latent_window_size
1517
+ 30, # steps
1518
+ 1.0, # cfg
1519
+ 10.0, # gs
1520
+ 0.0, # rs
1521
+ 6, # gpu_memory_preservation
1522
+ False, # enable_preview
1523
+ True, # use_teacache
1524
+ 16, # mp4_crf
1525
+ 30 # fps_number
1526
+ ],
1527
+ [
1528
+ "./img_examples/Example2.webp", # input_image
1529
+ 0, # image_position
1530
+ "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",
1531
+ "image", # generation_mode
1532
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1533
+ True, # randomize_seed
1534
+ 42, # seed
1535
+ True, # auto_allocation
1536
+ 180, # allocation_time
1537
+ 672, # resolution
1538
+ 2, # total_second_length
1539
+ 9, # latent_window_size
1540
+ 30, # steps
1541
+ 1.0, # cfg
1542
+ 10.0, # gs
1543
+ 0.0, # rs
1544
+ 6, # gpu_memory_preservation
1545
+ False, # enable_preview
1546
+ True, # use_teacache
1547
+ 16, # mp4_crf
1548
+ 30 # fps_number
1549
+ ],
1550
+ [
1551
+ "./img_examples/Example3.jpg", # input_image
1552
+ 0, # image_position
1553
+ "A boy is walking to the right, full view, full-length view, cartoon",
1554
+ "image", # generation_mode
1555
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1556
+ True, # randomize_seed
1557
+ 42, # seed
1558
+ True, # auto_allocation
1559
+ 180, # allocation_time
1560
+ 672, # resolution
1561
+ 1, # total_second_length
1562
+ 9, # latent_window_size
1563
+ 30, # steps
1564
+ 1.0, # cfg
1565
+ 10.0, # gs
1566
+ 0.0, # rs
1567
+ 6, # gpu_memory_preservation
1568
+ False, # enable_preview
1569
+ True, # use_teacache
1570
+ 16, # mp4_crf
1571
+ 30 # fps_number
1572
+ ],
1573
+ [
1574
+ "./img_examples/Example4.webp", # input_image
1575
+ 100, # image_position
1576
+ "A building starting to explode, photorealistic, realisitc, 8k, insanely detailed",
1577
+ "image", # generation_mode
1578
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1579
+ True, # randomize_seed
1580
+ 42, # seed
1581
+ True, # auto_allocation
1582
+ 180, # allocation_time
1583
+ 672, # resolution
1584
+ 1, # total_second_length
1585
+ 9, # latent_window_size
1586
+ 30, # steps
1587
+ 1.0, # cfg
1588
+ 10.0, # gs
1589
+ 0.0, # rs
1590
+ 6, # gpu_memory_preservation
1591
+ False, # enable_preview
1592
+ False, # use_teacache
1593
+ 16, # mp4_crf
1594
+ 30 # fps_number
1595
+ ]
1596
+ ],
1597
+ run_on_click = True,
1598
+ fn = process,
1599
+ inputs = ips,
1600
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning],
1601
+ cache_examples = False,
1602
+ )
1603
+
1604
+ gr.Examples(
1605
+ label = "🎥 Examples from video",
1606
+ examples = [
1607
+ [
1608
+ "./img_examples/Example1.mp4", # input_video
1609
+ "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",
1610
+ "Missing arm, long hand, unrealistic position, impossible contortion, visible bone, muscle contraction, blurred, blurry, over-smooth", # n_prompt
1611
+ True, # randomize_seed
1612
+ 42, # seed
1613
+ True, # auto_allocation
1614
+ 180, # allocation_time
1615
+ 1, # batch
1616
+ 672, # resolution
1617
+ 1, # total_second_length
1618
+ 9, # latent_window_size
1619
+ 30, # steps
1620
+ 1.0, # cfg
1621
+ 10.0, # gs
1622
+ 0.0, # rs
1623
+ 6, # gpu_memory_preservation
1624
+ False, # enable_preview
1625
+ True, # use_teacache
1626
+ False, # no_resize
1627
+ 16, # mp4_crf
1628
+ 5, # num_clean_frames
1629
+ default_vae
1630
+ ]
1631
+ ],
1632
+ run_on_click = True,
1633
+ fn = process_video,
1634
+ inputs = ips_video,
1635
+ outputs = [result_video, preview_image, progress_desc, progress_bar, start_button_video, end_button, warning],
1636
+ cache_examples = False,
1637
+ )
1638
+
1639
+ def save_preferences(preferences, value):
1640
+ preferences["generation-mode"] = value
1641
+ return preferences
1642
+
1643
+ def load_preferences(saved_prefs):
1644
+ saved_prefs = init_preferences(saved_prefs)
1645
+ return saved_prefs["generation-mode"]
1646
+
1647
+ def init_preferences(saved_prefs):
1648
+ if saved_prefs is None:
1649
+ saved_prefs = default_local_storage
1650
+ return saved_prefs
1651
+
1652
+ def check_parameters(generation_mode, input_image, input_video):
1653
+ if generation_mode == "image" and input_image is None:
1654
+ raise gr.Error("Please provide an image to extend.")
1655
+ if generation_mode == "video" and input_video is None:
1656
+ raise gr.Error("Please provide a video to extend.")
1657
+ return [gr.update(interactive=True), gr.update(visible = True)]
1658
+
1659
+ def handle_generation_mode_change(generation_mode_data):
1660
+ if generation_mode_data == "text":
1661
+ 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)]
1662
+ elif generation_mode_data == "image":
1663
+ 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)]
1664
+ elif generation_mode_data == "video":
1665
+ 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)]
1666
+
1667
+
1668
+ def handle_field_debug_change(input_image_debug_data, input_video_debug_data, prompt_debug_data, total_second_length_debug_data):
1669
+ print("handle_field_debug_change")
1670
+ input_image_debug_value[0] = input_image_debug_data
1671
+ input_video_debug_value[0] = input_video_debug_data
1672
+ prompt_debug_value[0] = prompt_debug_data
1673
+ total_second_length_debug_value[0] = total_second_length_debug_data
1674
+ return []
1675
+
1676
+ input_image_debug.upload(
1677
+ fn=handle_field_debug_change,
1678
+ inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],
1679
+ outputs=[]
1680
+ )
1681
+
1682
+ input_video_debug.upload(
1683
+ fn=handle_field_debug_change,
1684
+ inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],
1685
+ outputs=[]
1686
+ )
1687
+
1688
+ prompt_debug.change(
1689
+ fn=handle_field_debug_change,
1690
+ inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],
1691
+ outputs=[]
1692
+ )
1693
+
1694
+ total_second_length_debug.change(
1695
+ fn=handle_field_debug_change,
1696
+ inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],
1697
+ outputs=[]
1698
+ )
1699
+
1700
+ prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])
1701
+ timeless_prompt.change(fn=handle_timeless_prompt_change, inputs=[timeless_prompt], outputs=[final_prompt])
1702
+ start_button.click(fn = check_parameters, inputs = [
1703
+ generation_mode, input_image, input_video
1704
+ ], outputs = [end_button, warning], queue = False, show_progress = False).success(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button, warning], scroll_to_output = True)
1705
+ start_button_video.click(fn = check_parameters, inputs = [
1706
+ generation_mode, input_image, input_video
1707
+ ], outputs = [end_button, warning], 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, warning], scroll_to_output = True)
1708
+ end_button.click(fn=end_process)
1709
+
1710
+ generation_mode.change(fn = save_preferences, inputs = [
1711
+ local_storage,
1712
+ generation_mode,
1713
+ ], outputs = [
1714
+ local_storage
1715
+ ])
1716
+
1717
+ generation_mode.change(
1718
+ fn=handle_generation_mode_change,
1719
+ inputs=[generation_mode],
1720
+ 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]
1721
+ )
1722
+
1723
+ # Update display when the page loads
1724
+ block.load(
1725
+ fn=handle_generation_mode_change, inputs = [
1726
+ generation_mode
1727
+ ], outputs = [
1728
+ 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
1729
+ ]
1730
+ )
1731
+
1732
+ # Load saved preferences when the page loads
1733
+ block.load(
1734
+ fn=load_preferences, inputs = [
1735
+ local_storage
1736
+ ], outputs = [
1737
+ generation_mode
1738
+ ]
1739
+ )
1740
+
1741
+ block.launch(mcp_server=True, ssr_mode=False)
requirements.txt CHANGED
@@ -1,41 +1,24 @@
1
- pydantic==2.10.6
2
- fastapi==0.115.13
3
- gradio_imageslider==0.0.20
4
- gradio_client==1.10.3
5
- numpy==1.26.4
6
- requests==2.32.4
7
  sentencepiece==0.2.0
8
- tokenizers==0.19.1
9
- torchvision==0.22.0
10
- uvicorn==0.34.3
11
- wandb==0.20.1
12
- httpx==0.28.1
13
- transformers==4.43.0
14
- accelerate==1.8.0
15
- scikit-learn==1.7.0
16
- einops==0.8.1
17
- einops-exts==0.0.4
18
- timm==1.0.15
19
- openai-clip==1.0.1
20
- fsspec==2025.5.1
21
- kornia==0.8.1
22
- matplotlib==3.10.3
23
- ninja==1.11.1.4
24
- omegaconf==2.3.0
25
- opencv-python==4.11.0.86
26
- pandas==2.3.0
27
  pillow==11.2.1
28
- pytorch-lightning==2.5.1.post0
29
- PyYAML==6.0.2
30
- scipy==1.15.3
31
- tqdm==4.67.1
32
- triton==3.3.0
33
- urllib3==2.4.0
34
- webdataset==0.2.111
35
- xformers==0.0.30
36
- facexlib==0.3.0
37
- k-diffusion==0.1.1.post1
38
- diffusers==0.33.1
 
 
 
 
 
 
39
  pillow-heif==0.22.0
40
-
41
- open-clip-torch==2.24.0
 
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
13
+ torchaudio
14
+ einops
15
+ opencv-contrib-python
16
+ safetensors
17
+ huggingface_hub
18
+ decord
19
+ imageio_ffmpeg==0.6.0
20
+ sageattention==1.0.6
21
+ xformers==0.0.29.post3
22
+ bitsandbytes==0.46.0
23
  pillow-heif==0.22.0
24
+ spaces[security]