Spaces:
Paused
Paused
Adapt the code
Browse files13 unmodified lines1415161718192086 unmodified lines107108109110111112113114400 unmodified lines51551651751851952052152252352413 unmodified lines538539540541542543544545546547548549550551552553554555222 unmodified lines7787797807817827837847857867877887897907917927937947957967977987998008018028038048058 unmodified lines8148158168178188198208218228238248258268278288298303 unmodified lines8348358368378388398408418428433 unmodified lines8478488498508518528538548558568578588598608618628639 unmodified lines87387487587687787887988088188288388488588688788888989089189289389489589689789872 unmodified lines9719729739749759769779789793 unmodified lines98398498598698798898950 unmodified lines10401041104210431044104510461047104810491050105112 unmodified lines1064106510661067106810691070107128 unmodified lines110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911402 unmodified lines1143114411451146114711481149115034 unmodified lines11851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122613 unmodified linesimport argparseimport randomimport mathimport time# 20250506 pftq: Added for video input loadingimport decord# 20250506 pftq: Added for progress bars in video_encode86 unmodified linesoutputs_folder = './outputs/'os.makedirs(outputs_folder, exist_ok=True)input_image_debug_value = input_video_debug_value = prompt_debug_value = total_second_length_debug_value = Nonedef check_parameters(generation_mode, input_image, input_video):if generation_mode == "image" and input_image is None:raise gr.Error("Please provide an image to extend.")400 unmodified linesreturndef get_duration(input_image, prompt, generation_mode, n_prompt, randomize_seed, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):global total_second_length_debug_valueif total_second_length_debug_value is not None:return min(total_second_length_debug_value * 60 * 10, 600)return total_second_length * 6013 unmodified linesuse_teacache=False,mp4_crf=16):global stream, input_image_debug_value, prompt_debug_value, total_second_length_debug_valueif torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')return None, None, None, None, None, Noneif input_image_debug_value is not None or prompt_debug_value is not None or total_second_length_debug_value is not None:input_image = input_image_debug_valueprompt = prompt_debug_valuetotal_second_length = total_second_length_debug_valueinput_image_debug_value = prompt_debug_value = total_second_length_debug_value = Noneif randomize_seed:seed = random.randint(0, np.iinfo(np.int32).max)222 unmodified linesclean_latent_4x_indices=clean_latent_4x_indices,callback=callback,)start = time.time()total_generated_latent_frames += int(generated_latents.shape[2])history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)end = time.time()secondes = int(end - start)print("1 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()if not high_vram:offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)load_model_as_complete(vae, target_device=gpu)end = time.time()secondes = int(end - start)print("2 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]end = time.time()secondes = int(end - start)print("3 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()if history_pixels is None:history_pixels = vae_decode(real_history_latents, vae).cpu()8 unmodified linescurrent_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)end = time.time()secondes = int(end - start)print("4 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()if not high_vram:unload_complete_models()end = time.time()secondes = int(end - start)print("5 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')3 unmodified lines# 20250508 pftq: Save prompt to mp4 metadata commentsset_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}");print(f"Prompt saved to mp4 metadata comments: {output_filename}")end = time.time()secondes = int(end - start)print("6 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()# 20250506 pftq: Clean up previous partial filesif previous_video is not None and os.path.exists(previous_video):3 unmodified linesexcept Exception as e:print(f"Error deleting previous partial video {previous_video}: {e}")previous_video = output_filenameend = time.time()secondes = int(end - start)print("7 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))start = time.time()print(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')stream.output_queue.push(('file', output_filename))end = time.time()secondes = int(end - start)print("8 ££££££££££££££££££££££££££££££££££££££££ " + str(secondes))seed = (seed + 1) % np.iinfo(np.int32).max9 unmodified linesreturndef 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):global total_second_length_debug_valueif total_second_length_debug_value is not None:return min(total_second_length_debug_value * 60 * 10, 600)return total_second_length * 60 * 2# 20250506 pftq: Modified process to pass clean frame count, etc from video_encode@spaces.GPU(duration=get_duration_video)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):global stream, high_vram, input_video_debug_value, prompt_debug_value, total_second_length_debug_valueif torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')return None, None, None, None, None, Noneif input_video_debug_value is not None or prompt_debug_value is not None or total_second_length_debug_value is not None:input_video = input_video_debug_valueprompt = prompt_debug_valuetotal_second_length = total_second_length_debug_valueinput_video_debug_value = prompt_debug_value = total_second_length_debug_value = Noneif randomize_seed:seed = random.randint(0, np.iinfo(np.int32).max)72 unmodified linesif torch.cuda.device_count() == 0:with gr.Row():gr.HTML("""<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>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.</big></big></big></p>""")gr.HTML(title_html)3 unmodified linestext_to_video_hint = gr.HTML("I discourage to use the Text-to-Video feature. You should rather generate an image with Flux and use Image-to-Video. You will save time.", visible=False)input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)input_video = gr.Video(sources='upload', label="Input Video", height=320, visible=False)prompt = gr.Textbox(label="Prompt", value='', info='Use ; to separate in time', placeholder="The creature starts to move, fast motion, fixed camera")prompt_number = gr.Slider(label="Timed prompt number", minimum=0, maximum=1000, value=0, step=1, info='Not for video extension')prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])50 unmodified linesmp4_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. ")with gr.Accordion("Debug", open=False):input_image_debug = gr.Image(type="numpy", label="Image Debug", height=320)input_video_debug = gr.Video(sources='upload', label="Input Video Debug", height=320)prompt_debug = gr.Textbox(label="Prompt Debug", value='')total_second_length_debug = gr.Slider(label="Additional Video Length to Generate (Seconds) Debug", minimum=1, maximum=120, value=1, step=0.1)with gr.Column():preview_image = gr.Image(label="Next Latents", height=200, visible=False)result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)12 unmodified lines], outputs = [], 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])end_button.click(fn=end_process)with gr.Row(elem_id="image_examples", visible=False):gr.Examples(examples = [["./img_examples/Example1.png", # input_image28 unmodified lines6, # gpu_memory_preservationFalse, # use_teacache16 # mp4_crf],["./img_examples/Example1.png", # input_image"We are sinking, photorealistic, realistic, intricate details, 8k, insanely detailed","image", # generation_mode"Missing arm, unrealistic position, blurred, blurry", # n_promptTrue, # randomize_seed42, # seed1, # total_second_length9, # latent_window_size25, # steps1.0, # cfg10.0, # gs0.0, # rs6, # gpu_memory_preservationFalse, # use_teacache16 # mp4_crf],["./img_examples/Example1.png", # input_image"A boat is passing, photorealistic, realistic, intricate details, 8k, insanely detailed","image", # generation_mode"Missing arm, unrealistic position, blurred, blurry", # n_promptTrue, # randomize_seed42, # seed1, # total_second_length9, # latent_window_size25, # steps1.0, # cfg10.0, # gs0.0, # rs6, # gpu_memory_preservationFalse, # use_teacache16 # mp4_crf],],run_on_click = True,fn = process,2 unmodified linescache_examples = torch.cuda.device_count() > 0,)with gr.Row(elem_id="video_examples", visible=False):gr.Examples(examples = [["./img_examples/Example1.mp4", # input_video34 unmodified linesreturn [gr.update(visible = False), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = True)]def handle_field_debug_change(input_image_debug_data, input_video_debug_data, prompt_debug_data, total_second_length_debug_data):global input_image_debug_value, input_video_debug_value, prompt_debug_value, total_second_length_debug_valueinput_image_debug_value = input_image_debug_datainput_video_debug_value = input_video_debug_dataprompt_debug_value = prompt_debug_datatotal_second_length_debug_value = total_second_length_debug_datareturn []generation_mode.change(fn=handle_generation_mode_change,inputs=[generation_mode],outputs=[text_to_video_hint, input_image, input_video, start_button, start_button_video])input_image_debug.upload(fn=handle_field_debug_change,inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],outputs=[])input_video_debug.upload(fn=handle_field_debug_change,inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],outputs=[])prompt_debug.change(fn=handle_field_debug_change,inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],outputs=[])total_second_length_debug.change(fn=handle_field_debug_change,inputs=[input_image_debug, input_video_debug, prompt_debug, total_second_length_debug],outputs=[])block.launch(mcp_server=False, ssr_mode=False)13 unmodified lines14151617181986 unmodified lines106107108109110111400 unmodified lines51251351451551651713 unmodified lines531532533534535536537538539540541542222 unmodified lines7657667677687697707717727737747757767777787798 unmodified lines7887897907917927937947957963 unmodified lines8008018028038048053 unmodified lines8098108118128138148158168178189 unmodified lines82882983083183283383483583683783883984084184284384472 unmodified lines9179189199209219229239249253 unmodified lines92993093193293393493550 unmodified lines98698798898999099112 unmodified lines100410051006100710081009101028 unmodified lines10391040104110421043104410452 unmodified lines104810491050105110521053105434 unmodified lines108910901091109210931094109510961097109813 unmodified linesimport argparseimport randomimport math# 20250506 pftq: Added for video input loadingimport decord# 20250506 pftq: Added for progress bars in video_encode86 unmodified linesoutputs_folder = './outputs/'os.makedirs(outputs_folder, exist_ok=True)def check_parameters(generation_mode, input_image, input_video):if generation_mode == "image" and input_image is None:raise gr.Error("Please provide an image to extend.")400 unmodified linesreturndef get_duration(input_image, prompt, generation_mode, n_prompt, randomize_seed, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache, mp4_crf):return total_second_length * 6013 unmodified linesuse_teacache=False,mp4_crf=16):global streamif torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')return None, None, None, None, None, Noneif randomize_seed:seed = random.randint(0, np.iinfo(np.int32).max)222 unmodified linesclean_latent_4x_indices=clean_latent_4x_indices,callback=callback,)total_generated_latent_frames += int(generated_latents.shape[2])history_latents = torch.cat([history_latents, generated_latents.to(history_latents)], dim=2)if not high_vram:offload_model_from_device_for_memory_preservation(transformer, target_device=gpu, preserved_memory_gb=8)load_model_as_complete(vae, target_device=gpu)real_history_latents = history_latents[:, :, -total_generated_latent_frames:, :, :]if history_pixels is None:history_pixels = vae_decode(real_history_latents, vae).cpu()8 unmodified linescurrent_pixels = vae_decode(real_history_latents[:, :, -section_latent_frames:], vae).cpu()history_pixels = soft_append_bcthw(history_pixels, current_pixels, overlapped_frames)if not high_vram:unload_complete_models()output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4')3 unmodified lines# 20250508 pftq: Save prompt to mp4 metadata commentsset_mp4_comments_imageio_ffmpeg(output_filename, f"Prompt: {prompt} | Negative Prompt: {n_prompt}");print(f"Prompt saved to mp4 metadata comments: {output_filename}")# 20250506 pftq: Clean up previous partial filesif previous_video is not None and os.path.exists(previous_video):3 unmodified linesexcept Exception as e:print(f"Error deleting previous partial video {previous_video}: {e}")previous_video = output_filenameprint(f'Decoded. Current latent shape {real_history_latents.shape}; pixel shape {history_pixels.shape}')stream.output_queue.push(('file', output_filename))seed = (seed + 1) % np.iinfo(np.int32).max9 unmodified linesreturndef 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):return total_second_length * 60 * 2# 20250506 pftq: Modified process to pass clean frame count, etc from video_encode@spaces.GPU(duration=get_duration_video)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):global streamif torch.cuda.device_count() == 0:gr.Warning('Set this space to GPU config to make it work.')return None, None, None, None, None, Noneif randomize_seed:seed = random.randint(0, np.iinfo(np.int32).max)72 unmodified linesif torch.cuda.device_count() == 0:with gr.Row():gr.HTML("""<p style="background-color: red;"><big><big><big><b>⚠️To use FramePack, <a href="?duplicate=true">duplicate this space</a> and set a GPU with 30 GB VRAM.</b>You can't use FramePack directly here because this space runs on a CPU, which is not enough for FramePack. Please provide <a href="discussions/new">feedback</a> if you have issues.</big></big></big></p>""")gr.HTML(title_html)3 unmodified linestext_to_video_hint = gr.HTML("I discourage to use the Text-to-Video feature. You should rather generate an image with Flux and use Image-to-Video. You will save time.", visible=False)input_image = gr.Image(sources='upload', type="numpy", label="Image", height=320)input_video = gr.Video(sources='upload', label="Input Video", height=320, visible=False)prompt = gr.Textbox(label="Prompt", value='', info='Use ; to separate in time', placeholder="The creature starts to move, fast motion, focus motion, consistent arm, consistent position, fixed camera")prompt_number = gr.Slider(label="Timed prompt number", minimum=0, maximum=1000, value=0, step=1, info='Not for video extension')prompt_number.change(fn=handle_prompt_number_change, inputs=[], outputs=[])50 unmodified linesmp4_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. ")with gr.Column():preview_image = gr.Image(label="Next Latents", height=200, visible=False)result_video = gr.Video(label="Finished Frames", autoplay=True, show_share_button=False, height=512, loop=True)12 unmodified lines], outputs = [], 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])end_button.click(fn=end_process)gr.Examples(examples = [["./img_examples/Example1.png", # input_image28 unmodified lines6, # gpu_memory_preservationFalse, # use_teacache16 # mp4_crf]],run_on_click = True,fn = process,2 unmodified linescache_examples = torch.cuda.device_count() > 0,)gr.Examples(examples = [["./img_examples/Example1.mp4", # input_video34 unmodified linesreturn [gr.update(visible = False), gr.update(visible = False), gr.update(visible = True), gr.update(visible = False), gr.update(visible = True)]generation_mode.change(fn=handle_generation_mode_change,inputs=[generation_mode],outputs=[text_to_video_hint, input_image, input_video, start_button, start_button_video])block.launch(mcp_server=False, ssr_mode=False)
app.py+8-136