Python
matanyone++ and input images stored in out videos
DeepBeepMeep00744c24b039
diff --cc models/wan/alpha/utils.pyindex 066fe4d,0000000..8bc5a8amode 100644,000000..100644--- a/models/wan/alpha/utils.py+++ b/models/wan/alpha/utils.py@@@ -1,80 -1,0 +1,93 @@@+import torchvision+from PIL import Image, ImageDraw+import imageio+import cv2+import torch+import numpy as np+import zipfile++def render_video(tensor_fgr,+ tensor_pha,+ nrow=8,+ normalize=True,+ value_range=(-1, 1)):-++ def to_tensor(arr_list):++ tensor_list= [torch.from_numpy(arr).float().div_(127.5).sub_(1) for arr in arr_list]++ tensor_list = torch.stack(tensor_list, dim = 0).permute(3,0,1,2).unsqueeze(0)++ return tensor_list++++ if not torch.is_tensor(tensor_fgr):++ tensor_fgr = to_tensor(tensor_fgr)++ if not torch.is_tensor(tensor_pha):++ tensor_pha = to_tensor(tensor_pha)+++ tensor_fgr = tensor_fgr.clamp(min(value_range), max(value_range))+ tensor_fgr = torch.stack([+ torchvision.utils.make_grid(+ u, nrow=nrow, normalize=normalize, value_range=value_range)+ for u in tensor_fgr.unbind(2)+ ],+ dim=1).permute(1, 2, 3, 0)+ tensor_fgr = (tensor_fgr * 255).type(torch.uint8).cpu()++ tensor_pha = tensor_pha.clamp(min(value_range), max(value_range))+ tensor_pha = torch.stack([+ torchvision.utils.make_grid(+ u, nrow=nrow, normalize=normalize, value_range=value_range)+ for u in tensor_pha.unbind(2)+ ],+ dim=1).permute(1, 2, 3, 0)+ tensor_pha = (tensor_pha * 255).type(torch.uint8).cpu()++ frames = []+ frames_fgr = []+ frames_pha = []+ for frame_fgr, frame_pha in zip(tensor_fgr.numpy(), tensor_pha.numpy()):- frame_pha = (0.0 + frame_pha[:,:,0:1] + frame_pha[:,:,1:2] + frame_pha[:,:,2:3]) / 3.++ if frame_pha.shape[-1] == 1:++ frame_pha = frame_pha[:,:,0]++ else:++ frame_pha = (0.0 + frame_pha[:,:,0:1] + frame_pha[:,:,1:2] + frame_pha[:,:,2:3]) / 3.+ frame = np.concatenate([frame_fgr[:,:,::-1], frame_pha.astype(np.uint8)], axis=2)+ frames.append(frame)+ frames_fgr.append(frame_fgr)+ frames_pha.append(frame_pha)++ def create_checkerboard(size=30, pattern_size=(830, 480), color1=(140, 140, 140), color2=(113, 113, 113)):+ img = Image.new('RGB', (pattern_size[0], pattern_size[1]), color1)+ draw = ImageDraw.Draw(img)+ for i in range(0, pattern_size[0], size):+ for j in range(0, pattern_size[1], size):+ if (i + j) // size % 2 == 0:+ draw.rectangle([i, j, i+size, j+size], fill=color2)+ return img++ def blender_background(frame_rgba, checkerboard):+ alpha_channel = frame_rgba[:, :, 3:] / 255.+ checkerboard = np.array(checkerboard)+ checkerboard = cv2.resize(checkerboard, (frame_rgba.shape[1], frame_rgba.shape[0]))++ frame_rgb = frame_rgba[:, :, :3] * alpha_channel + checkerboard * (1-alpha_channel)+ return frame_rgb.astype(np.uint8)[:,:,::-1]++ checkerboard = create_checkerboard()+ video_checkerboard = [torch.from_numpy(blender_background(f, checkerboard).copy()).float().div_(127.5).sub_(1) for f in frames]+ video_checkerboard = torch.stack(video_checkerboard ).permute(3, 0, 1, 2)+ return video_checkerboard, frames++def from_BRGA_numpy_to_RGBA_torch(video):+ video = [torch.from_numpy(f.copy()).float().div_(127.5).sub_(1) for f in video]+ video = torch.stack(video).permute(3, 0, 1, 2)+ video[[0, 2], ...] = video[[2, 0], ...]+ return video++def write_zip_file(zip_path, frames):++ # frames in BGRA format+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:+ for idx, img in enumerate(frames):+ success, buffer = cv2.imencode(".png", img)+ if not success:+ print(f"Failed to encode image {idx}, skipping...")+ continue++ filename = f"img_{idx:03d}.png"+ zipf.writestr(filename, buffer.tobytes())diff --cc preprocessing/matanyone/app.pyindex 443934c,a5d5570..2c6a38b--- a/preprocessing/matanyone/app.py+++ b/preprocessing/matanyone/app.py@@@ -12,6 -12,6 +12,7 @@@ import torcimport torch.nn.functional as Fimport numpy as npimport gradio as gr++from datetime import datetimefrom .tools.painter import mask_painterfrom .tools.interact_tools import SamControlerfrom .tools.misc import get_device@@@ -22,7 -22,6 +23,9 @@@ from .matanyone.inference.inference_corfrom .matanyone_wrapper import matanyonefrom shared.utils.audio_video import save_video, save_imagefrom mmgp import offload+from shared.utils import files_locator as fl++from shared.utils.utils import truncate_for_filesystem, sanitize_file_name, process_images_multithread, calculate_new_dimensions, get_default_workers++from shared.utils.process_locks import acquire_GPU_ressources, release_GPU_ressources, any_GPU_process_runningarg_device = "cuda"arg_sam_model_type="vit_h"@@@ -35,6 -34,6 +38,46 @@@ matanyone_in_GPU = Falsbfloat16_supported = False# SAM generatorimport copy++GPU_process_was_running = False++def acquire_GPU(state):++ global GPU_process_was_running++ GPU_process_was_running = any_GPU_process_running(state, "matanyone")++ acquire_GPU_ressources(state, "matanyone", "MatAnyone", gr= gr)++def release_GPU(state):++ release_GPU_ressources(state, "matanyone")++ if GPU_process_was_running:++ global matanyone_in_GPU, model_in_GPU++ if model_in_GPU:++ model.samcontroler.sam_controler.model.to("cpu")++ model_in_GPU = False++ if matanyone_in_GPU:++ matanyone_model.to("cpu")++ matanyone_in_GPU = False++++++def perform_spatial_upsampling(frames, new_dim):++ if new_dim =="":++ return frames++ h, w = frames[0].shape[:2]++++ from shared.utils.utils import resize_lanczos++ pos = new_dim.find(" ")++ fit_into_canvas = "Outer" in new_dim++ new_dim = new_dim[:pos]++ if new_dim == "1080p":++ canvas_w, canvas_h = 1920, 1088++ elif new_dim == "720p":++ canvas_w, canvas_h = 1280, 720++ else:++ canvas_w, canvas_h = 832, 480++ h, w = calculate_new_dimensions(canvas_h, canvas_w, h, w, fit_into_canvas=fit_into_canvas, block_size= 16 )++++++ def upsample_frames(frame):++ return np.array(Image.fromarray(frame).resize((w,h), resample=Image.Resampling.LANCZOS))++++ output_frames = process_images_multithread(upsample_frames, frames, "upsample", wrap_in_list = False, max_workers=get_default_workers(), in_place=True)++ return output_framesclass MaskGenerator():def __init__(self, sam_checkpoint, device):@@@ -64,7 -63,7 +107,7 @@@ def get_prompt(click_state, click_input}return prompt--def get_frames_from_image(image_input, image_state):++def get_frames_from_image(state, image_input, image_state, new_dim):"""Args:video_path:str@@@ -75,7 -74,7 +118,11 @@@if image_input is None:gr.Info("Please select an Image file")-- return [gr.update()] * 17++ return [gr.update()] * 20++++++ if len(new_dim) > 0:++ image_input = perform_spatial_upsampling([image_input], new_dim)[0]user_name = time.time()frames = [image_input] * 2 # hardcode: mimic a video with 2 frames@@@ -90,27 -89,27 +137,32 @@@"logits": [None]*len(frames),"select_frame_number": 0,"last_frame_numer": 0,-- "fps": None++ "fps": None,++ "new_dim": new_dim,}image_info = "Image Name: N/A,\nFPS: N/A,\nTotal Frames: {},\nImage Size:{}".format(len(frames), image_size)++ acquire_GPU(state)set_image_encoder_patch()-- select_SAM()++ select_SAM(state)model.samcontroler.sam_controler.reset_image()model.samcontroler.sam_controler.set_image(image_state["origin_images"][0])torch.cuda.empty_cache()-- return image_state, image_info, image_state["origin_images"][0], \++ release_GPU(state)++++ return image_state, gr.update(interactive=False), image_info, image_state["origin_images"][0], \gr.update(visible=True, maximum=10, value=10), gr.update(visible=False, maximum=len(frames), value=len(frames)), \gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True),\gr.update(visible=True), gr.update(visible=False), \++ gr.update(visible=False), gr.update(), \gr.update(visible=False), gr.update(value="", visible=False), gr.update(visible=False), \gr.update(visible=False), gr.update(visible=True), \gr.update(visible=True)# extract frames from upload video--def get_frames_from_video(video_input, video_state):++def get_frames_from_video(state, video_input, video_state, new_dim):"""Args:video_path:str@@@ -120,10 -119,10 +172,8 @@@"""if video_input is None:gr.Info("Please select a Video file")-- return [gr.update()] * 18---- while model == None:-- time.sleep(1)++ return [gr.update()] * 19++video_path = video_inputframes = []@@@ -155,6 -154,6 +205,10 @@@print("read_frame_source:{} error. {}\n".format(video_path, str(e)))image_size = (frames[0].shape[0],frames[0].shape[1])++ if len(new_dim) > 0:++ frames = perform_spatial_upsampling(frames, new_dim)++ image_size = (frames[0].shape[0],frames[0].shape[1])++# resize if resolution too bigif image_size[0]>=1280 and image_size[0]>=1280:scale = 1080 / min(image_size)@@@ -176,15 -175,15 +230,18 @@@"select_frame_number": 0,"last_frame_number": 0,"fps": fps,-- "audio": audio_path++ "audio": audio_path,++ "new_dim": new_dim,}video_info = "Video Name: {},\nFPS: {},\nTotal Frames: {},\nImage Size:{}".format(video_state["video_name"], round(video_state["fps"], 0), len(frames), image_size)++ acquire_GPU(state)set_image_encoder_patch()-- select_SAM()++ select_SAM(state)model.samcontroler.sam_controler.reset_image()model.samcontroler.sam_controler.set_image(video_state["origin_images"][0])torch.cuda.empty_cache()-- return video_state, video_info, video_state["origin_images"][0], \++ release_GPU(state)++ return video_state, gr.update(interactive=False), video_info, video_state["origin_images"][0], \gr.update(visible=True, maximum=len(frames), value=1), gr.update(visible=True, maximum=len(frames), value=len(frames)), gr.update(visible=False, maximum=len(frames), value=len(frames)), \gr.update(visible=True), gr.update(visible=True), gr.update(visible=True), \gr.update(visible=True), gr.update(visible=True),\@@@ -315,7 -314,7 +372,7 @@@ def set_image_encoder_patch()image_encoder_block.patched = True# use sam to get the mask--def sam_refine(video_state, point_prompt, click_state, interactive_state, evt:gr.SelectData ): #++def sam_refine(state, video_state, point_prompt, click_state, interactive_state, evt:gr.SelectData ): #"""Args:template_frame: PIL.Image@@@ -329,7 -328,7 +386,8 @@@coordinate = "[[{},{},0]]".format(evt.index[0], evt.index[1])interactive_state["negative_click_times"] += 1-- select_SAM()++ acquire_GPU(state)++ select_SAM(state)# prompt for sam modelset_image_encoder_patch()model.samcontroler.sam_controler.reset_image()@@@ -348,10 -347,10 +406,15 @@@video_state["painted_images"][video_state["select_frame_number"]] = painted_imagetorch.cuda.empty_cache()++ release_GPU(state)return painted_image, video_state, interactive_statedef add_multi_mask(video_state, interactive_state, mask_dropdown):-- mask = video_state["masks"][video_state["select_frame_number"]]++ masks = video_state["masks"]++ if video_state["masks"] is None:++ gr.Info("Matanyone Session Lost. Please reload a Video")++ return [gr.update()]*4++ mask = masks[video_state["select_frame_number"]]interactive_state["multi_mask"]["masks"].append(mask)interactive_state["multi_mask"]["mask_names"].append("mask_{:03d}".format(len(interactive_state["multi_mask"]["masks"])))mask_dropdown.append("mask_{:03d}".format(len(interactive_state["multi_mask"]["masks"])))@@@ -360,6 -359,6 +423,11 @@@return interactive_state, gr.update(choices=interactive_state["multi_mask"]["mask_names"], value=mask_dropdown), select_frame, [[],[]]def clear_click(video_state, click_state):++ masks = video_state["masks"]++ if video_state["masks"] is None:++ gr.Info("Matanyone Session Lost. Please reload a Video")++ return [gr.update()]*2++click_state = [[],[]]template_frame = video_state["origin_images"][video_state["select_frame_number"]]return template_frame, click_state@@@ -406,8 -405,8 +474,21 @@@ def mask_to_xyxy_box(mask)box = [int(x) for x in box]return box++def get_dim_file_suffix(new_dim):++ if not " " in new_dim: return ""++ pos = new_dim.find(" ")++ return new_dim[:pos]++# image matting--def image_matting(video_state, interactive_state, mask_dropdown, erode_kernel_size, dilate_kernel_size, refine_iter):++def image_matting(state, video_state, interactive_state, mask_type, matting_type, new_new_dim, mask_dropdown, erode_kernel_size, dilate_kernel_size, refine_iter):++ if video_state["masks"] is None:++ gr.Info("Matanyone Session Lost. Please reload an Image")++ return [gr.update(visible=False)]*12++++ new_dim = video_state.get("new_dim", "")++ if new_new_dim != new_dim:++ gr.Info(f"You have changed the Input / Output Dimensions after loading the Video into Matanyone. The output dimension will be the ones when loading the image ({'original' if len(new_dim) == 0 else new_dim})")++matanyone_processor = InferenceCore(matanyone_model, cfg=matanyone_model.cfg)if interactive_state["track_end_number"]:following_frames = video_state["origin_images"][video_state["select_frame_number"]:interactive_state["track_end_number"]]@@@ -429,36 -428,36 +510,61 @@@# operation errorif len(np.unique(template_mask))==1:template_mask[0][0]=1-- select_matanyone()++ acquire_GPU(state)++ select_matanyone(state)foreground, alpha = matanyone(matanyone_processor, following_frames, template_mask*255, r_erode=erode_kernel_size, r_dilate=dilate_kernel_size, n_warmup=refine_iter)torch.cuda.empty_cache()++ release_GPU(state)---- foreground_mat = False++ foreground_mat = matting_type == "Foreground"-- output_frames = []-- for frame_origin, frame_alpha in zip(following_frames, alpha):-- if foreground_mat:-- frame_alpha[frame_alpha > 127] = 255-- frame_alpha[frame_alpha <= 127] = 0-- else:-- frame_temp = frame_alpha.copy()-- frame_alpha[frame_temp > 127] = 0-- frame_alpha[frame_temp <= 127] = 255------ output_frame = np.bitwise_and(frame_origin, 255-frame_alpha)-- frame_grey = frame_alpha.copy()-- frame_grey[frame_alpha == 255] = 255-- output_frame += frame_grey-- output_frames.append(output_frame)-- foreground = output_frames---- foreground_output = Image.fromarray(foreground[-1])-- alpha_output = alpha[-1][:,:,0]-- frame_temp = alpha_output.copy()-- alpha_output[frame_temp > 127] = 0-- alpha_output[frame_temp <= 127] = 255++ foreground_output = None++ foreground_title = "Image with Background"++ alpha_title = "Alpha Mask Image Output"++++ if mask_type == "wangp":++ white_image = np.full_like(following_frames[-1], 255, dtype=np.uint8)++ alpha_output = alpha[-1] if foreground_mat else 255 - alpha[-1]++ output_frame = (white_image.astype(np.uint16) * (255 - alpha_output.astype(np.uint16)) +++ following_frames[-1].astype(np.uint16) * alpha_output.astype(np.uint16))++ output_frame = output_frame // 255++ output_frame = output_frame.astype(np.uint8)++ foreground_output = output_frame++ control_output = following_frames[-1]++ alpha_output = alpha_output[:,:,0]++++ foreground_title = "Image without Background" if foreground_mat else "Image with Background"++ control_title = "Control Image"++ allow_export = True++ control_output = following_frames[-1]++ tab_label = "Control Image & Mask"++ elif mask_type == "greenscreen":++ green_image = np.zeros_like(following_frames[-1], dtype=np.uint8)++ green_image[:, :, 1] = 255++ alpha_output = alpha[-1] if foreground_mat else 255 - alpha[-1]++++ output_frame = (following_frames[-1].astype(np.uint16) * (255 - alpha_output.astype(np.uint16)) +++ green_image.astype(np.uint16) * alpha_output.astype(np.uint16))++ output_frame = output_frame // 255++ output_frame = output_frame.astype(np.uint8)++ control_output = output_frame++ alpha_output = alpha_output[:,:,0]++ control_title = "Green Screen Output"++ tab_label = "Green Screen"++ allow_export = False++ elif mask_type == "alpha":++ alpha_output = alpha[-1] if foreground_mat else 255 - alpha[-1]++ from models.wan.alpha.utils import render_video, from_BRGA_numpy_to_RGBA_torch++ from shared.utils.utils import convert_tensor_to_image++ _, BGRA_frames = render_video(following_frames[-1:], [alpha_output])++ RGBA_image = from_BRGA_numpy_to_RGBA_torch(BGRA_frames).squeeze(1)++ control_output = convert_tensor_to_image(RGBA_image)++ alpha_output = alpha_output[:,:,0]++ control_title = "RGBA Output"++ tab_label = "RGBA"++ allow_export = False++++bbox_info = mask_to_xyxy_box(alpha_output)h = alpha_output.shape[0]w = alpha_output.shape[1]@@@ -468,13 -467,13 +574,16 @@@bbox_info = [str(int(bbox_info[0]/ w * 100 )), str(int(bbox_info[1]/ h * 100 )), str(int(bbox_info[2]/ w * 100 )), str(int(bbox_info[3]/ h * 100 )) ]bbox_info = ":".join(bbox_info)alpha_output = Image.fromarray(alpha_output)-- # return gr.update(value=foreground_output, visible= True), gr.update(value=alpha_output, visible= True), gr.update(value=bbox_info, visible= True), gr.update(visible=True), gr.update(visible=True)-- return foreground_output, alpha_output, gr.update(visible = True), gr.update(visible = True), gr.update(value=bbox_info, visible= True), gr.update(visible=True), gr.update(visible=True)++ return gr.update(visible=True, selected =0), gr.update(label=tab_label, visible=True), gr.update(visible = foreground_output is not None), foreground_output, control_output, alpha_output, gr.update(visible=foreground_output is not None, label=foreground_title),gr.update(visible=True, label=control_title), gr.update(visible=True, label=alpha_title), gr.update(value=bbox_info, visible= True), gr.update(visible=allow_export), gr.update(visible=allow_export)++# video matting--def video_matting(video_state,video_input, end_slider, matting_type, interactive_state, mask_dropdown, erode_kernel_size, dilate_kernel_size):-- matanyone_processor = InferenceCore(matanyone_model, cfg=matanyone_model.cfg)++def video_matting(state, video_state, mask_type, video_input, end_slider, matting_type, new_new_dim, interactive_state, mask_dropdown, erode_kernel_size, dilate_kernel_size):++ if video_state["masks"] is None:++ gr.Info("Matanyone Session Lost. Please reload a Video")++ return [gr.update(visible=False)]*6++# if interactive_state["track_end_number"]:# following_frames = video_state["origin_images"][video_state["select_frame_number"]:interactive_state["track_end_number"]]# else:@@@ -493,69 -492,69 +602,86 @@@else:template_mask = video_state["masks"][video_state["select_frame_number"]]fps = video_state["fps"]--++ new_dim = video_state.get("new_dim", "")++ if new_new_dim != new_dim:++ gr.Info(f"You have changed the Input / Output Dimensions after loading the Video into Matanyone. The output dimension will be the ones when loading the video ({'original' if len(new_dim) == 0 else new_dim})")audio_path = video_state["audio"]# operation errorif len(np.unique(template_mask))==1:template_mask[0][0]=1-- select_matanyone()++ acquire_GPU(state)++ select_matanyone(state)++ matanyone_processor = InferenceCore(matanyone_model, cfg=matanyone_model.cfg)foreground, alpha = matanyone(matanyone_processor, following_frames, template_mask*255, r_erode=erode_kernel_size, r_dilate=dilate_kernel_size)torch.cuda.empty_cache()-- output_frames = []++ release_GPU(state)foreground_mat = matting_type == "Foreground"++ alpha_title = "Alpha Mask Video Output"++ alpha_suffix = "_alpha"++ output_frames = []new_alpha = []-- if not foreground_mat:-- for frame_alpha in alpha:-- frame_temp = frame_alpha.copy()-- frame_alpha[frame_temp > 127] = 0-- frame_alpha[frame_temp <= 127] = 255-- new_alpha.append(frame_alpha)-- else:-- for frame_alpha in alpha:-- frame_alpha[frame_alpha > 127] = 255-- frame_alpha[frame_alpha <= 127] = 0++ BGRA_frames = None++ if mask_type == "" or mask_type == "wangp":++ if not foreground_mat:++ alpha = [255 - frame_alpha for frame_alpha in alpha ]++ output_frames = following_frames++ foreground_title = "Original Video Input"++ foreground_suffix = ""++ allow_export = True++ elif mask_type == "greenscreen":++ green_image = np.zeros_like(following_frames[0], dtype=np.uint8)++ green_image[:, :, 1] = 255++ for frame_origin, frame_alpha in zip(following_frames, alpha):++ if not foreground_mat:++ frame_alpha = 255 - frame_alpha++++ output_frame = (frame_origin.astype(np.uint16) * (255 - frame_alpha.astype(np.uint16)) +++ green_image.astype(np.uint16) * frame_alpha.astype(np.uint16))++ output_frame = output_frame // 255++ output_frame = output_frame.astype(np.uint8)++ output_frames.append(output_frame)new_alpha.append(frame_alpha)-- alpha = new_alpha---- # for frame_origin, frame_alpha in zip(following_frames, alpha):-- # if foreground_mat:-- # frame_alpha[frame_alpha > 127] = 255-- # frame_alpha[frame_alpha <= 127] = 0-- # else:-- # frame_temp = frame_alpha.copy()-- # frame_alpha[frame_temp > 127] = 0-- # frame_alpha[frame_temp <= 127] = 255---- # output_frame = np.bitwise_and(frame_origin, 255-frame_alpha)-- # frame_grey = frame_alpha.copy()-- # frame_grey[frame_alpha == 255] = 127-- # output_frame += frame_grey-- # output_frames.append(output_frame)-- foreground = following_frames++ alpha = new_alpha++ foreground_title = "Green Screen Output"++ foreground_suffix = "_greenscreen"++ allow_export = False++ elif mask_type == "alpha":++ if not foreground_mat:++ alpha = [255 - frame_alpha for frame_alpha in alpha ]++ from models.wan.alpha.utils import render_video++ output_frames, BGRA_frames = render_video(following_frames, alpha)++ foreground_title = "Checkboard Output"++ foreground_suffix = "_RGBA"++ allow_export = Falseif not os.path.exists("mask_outputs"):os.makedirs("mask_outputs")file_name= video_state["video_name"]file_name = ".".join(file_name.split(".")[:-1])++ time_flag = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d-%Hh%Mm%Ss")++ file_name = f"{file_name}_{time_flag}"++ if len(new_dim) > 0: file_name += "_" + get_dim_file_suffix(new_dim)from shared.utils.audio_video import extract_audio_tracks, combine_video_with_audio_tracks, cleanup_temp_audio_filessource_audio_tracks, audio_metadata = extract_audio_tracks(video_input, verbose= offload.default_verboseLevel )-- output_fg_path = f"./mask_outputs/{file_name}_fg.mp4"-- output_fg_temp_path = f"./mask_outputs/{file_name}_fg_tmp.mp4"++ output_fg_path = f"./mask_outputs/{file_name}{foreground_suffix}.mp4"++ output_fg_temp_path = f"./mask_outputs/{file_name}{foreground_suffix}_tmp.mp4"if len(source_audio_tracks) == 0:-- foreground_output = save_video(foreground,output_fg_path , fps=fps, codec_type= video_output_codec)++ foreground_output = save_video(output_frames, output_fg_path , fps=fps, codec_type= video_output_codec)else:-- foreground_output_tmp = save_video(foreground, output_fg_temp_path , fps=fps, codec_type= video_output_codec)++ foreground_output_tmp = save_video(output_frames, output_fg_temp_path , fps=fps, codec_type= video_output_codec)combine_video_with_audio_tracks(output_fg_temp_path, source_audio_tracks, output_fg_path, audio_metadata=audio_metadata)cleanup_temp_audio_files(source_audio_tracks)os.remove(foreground_output_tmp)foreground_output = output_fg_path-- alpha_output = save_video(alpha, "./mask_outputs/{}_alpha.mp4".format(file_name), fps=fps, codec_type= video_output_codec)---- return foreground_output, alpha_output, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)++ alpha_output = save_video(alpha, f"./mask_outputs/{file_name}{alpha_suffix}.mp4", fps=fps, codec_type= video_output_codec)++ if BGRA_frames is not None:++ from models.wan.alpha.utils import write_zip_file++ write_zip_file(f"./mask_outputs/{file_name}{foreground_suffix}.zip", BGRA_frames)++ return foreground_output, alpha_output, gr.update(visible=True, label=foreground_title), gr.update(visible=True, label=alpha_title), gr.update(visible=allow_export), gr.update(visible=allow_export)def show_outputs():@@@ -609,7 -608,7 +735,8 @@@ def generate_video_from_frames(frames,return video_temp_path# reset all states for a new input--def restart():++++def get_default_states():return {"user_name": "","video_name": "",@@@ -630,7 -629,7 +757,10 @@@"masks": []},"track_end_number": None,-- }, [[],[]], None, None, \++ }, [[],[]]++++def restart():++ return *(get_default_states()), gr.update(interactive=True), gr.update(visible=False), None, None, None, \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=False), 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=False), gr.update(visible=False), gr.update(visible=False), \@@@ -645,8 -644,8 +775,10 @@@# matanyone_model.to(arg_device)--def select_matanyone():++def select_matanyone(state):global matanyone_in_GPU, model_in_GPU++ if matanyone_model is None:++ load_unload_models(state, True, True)if matanyone_in_GPU: returnmodel.samcontroler.sam_controler.model.to("cpu")model_in_GPU = False@@@ -654,8 -653,8 +786,10 @@@matanyone_model.to(arg_device)matanyone_in_GPU = True--def select_SAM():++def select_SAM(state):global matanyone_in_GPU, model_in_GPU++ if matanyone_model is None:++ load_unload_models(state, True, True)if model_in_GPU: returnmatanyone_model.to("cpu")matanyone_in_GPU = False@@@ -663,16 -662,16 +797,27 @@@model.samcontroler.sam_controler.model.to(arg_device)model_in_GPU = True--def load_unload_models(selected):-- global model_loaded++load_in_progress = False++++def load_unload_models(state = None, selected = True, force = False):++ global model_loaded, load_in_progressglobal modelglobal matanyone_model, matanyone_processor, matanyone_in_GPU , model_in_GPU, bfloat16_supported++if selected:++ if (not force) and any_GPU_process_running(state, "matanyone"):++ return++++ if load_in_progress:++ while model == None:++ time.sleep(1)++ return# print("Matanyone Tab Selected")-- if model_loaded:++ if model_loaded or load_in_progress:pass# load_sam()else:++ load_in_progress = True# args, defined in track_anything.pysam_checkpoint_url_dict = {'vit_h': "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth",@@@ -706,6 -705,6 +851,8 @@@matanyone_in_GPU = Falsematanyone_processor = InferenceCore(matanyone_model, cfg=matanyone_model.cfg)model_loaded = True++ load_in_progress = False++else:# print("Matanyone Tab UnSelected")import gc@@@ -724,7 -723,7 +871,7 @@@ def get_vmc_event_handler()def export_image(state, image_output):ui_settings = get_current_model_settings(state)-- image_refs = ui_settings["image_refs"]++ image_refs = ui_settings.get("image_refs", None)if image_refs == None:image_refs =[]image_refs.append( image_output)@@@ -734,7 -733,7 +881,7 @@@def export_image_mask(state, image_input, image_mask):ui_settings = get_current_model_settings(state)-- ui_settings["image_guide"] = Image.fromarray(image_input)++ ui_settings["image_guide"] = image_inputui_settings["image_mask"] = image_maskgr.Info("Input Image & Mask transferred to Current Image Generator")@@@ -750,9 -749,9 +897,9 @@@ def export_to_current_video_engine(statreturn time.time()--def teleport_to_video_tab(tab_state):++def teleport_to_video_tab(tab_state, state):from wgp import set_new_tab-- set_new_tab(tab_state, 0)++ set_new_tab(tab_state, state, 0)return gr.Tabs(selected="video_gen")@@@ -781,7 -780,7 +928,7 @@@ def display(tabs, tab_state, state, ref# download assets-- gr.Markdown("<B>Mast Edition is provided by MatAnyone and VRAM optimized by DeepBeepMeep</B>")++ gr.Markdown("<B>Mast Edition is provided by MatAnyone, VRAM optimizations & Extended Masks by DeepBeepMeep</B>")gr.Markdown("If you have some trouble creating the perfect mask, be aware of these tips:")gr.Markdown("- Using the Matanyone Settings you can also define Negative Point Prompts to remove parts of the current selection.")gr.Markdown("- Sometime it is very hard to fit everything you want in a single mask, it may be much easier to combine multiple independent sub Masks before producing the Matting : each sub Mask is created by selecting an area of an image and by clicking the Add Mask button. Sub masks can then be enabled / disabled in the Matanyone settings.")@@@ -799,8 -798,8 +946,36 @@@gr.Markdown("### Case 2: Multiple Targets")gr.Video(value="preprocessing/matanyone/tutorial_multi_targets.mp4", elem_classes="video")----++ with gr.Row():++ new_dim= gr.Dropdown(++ choices=[++ ("Original Dimensions", ""),++ ("1080p - Pixels Budgets", "1080p - Pixels Budget"),++ ("720p - Pixels Budgets", "720p - Pixels Budget"),++ ("480p - Pixels Budgets", "480p - Pixels Budget"),++ ("1080p - Outer Frame", "1080p - Outer Frame"),++ ("720p - Outer Frame", "720p - Outer Frame"),++ ("480p - Outer Frame", "480p - Outer Frame"),++ ], label = "Resize Input / Output", value = ""++ )++++ mask_type= gr.Dropdown(++ choices=[++ ("Grey with Alpha (used by WanGP)", "wangp"),++ ("Green Screen", "greenscreen"),++ ("RGB With Alpha Channel (local Zip file)", "alpha")++ ], label = "Mask Type", value = "wangp"++ )++++ matting_type = gr.Radio(++ choices=["Foreground", "Background"],++ value="Foreground",++ label="Type of Video Matting to Generate",++ scale=1)++++++ with gr.Row(visible=False):++ dummy = gr.Text()with gr.Tabs():with gr.TabItem("Video"):@@@ -869,16 -868,16 +1044,7 @@@visible=False,min_width=100,scale=1)-- matting_type = gr.Radio(-- choices=["Foreground", "Background"],-- value="Foreground",-- label="Matting Type",-- info="Type of Video Matting to Generate",-- interactive=True,-- visible=False,-- min_width=100,-- scale=1)-- mask_dropdown = gr.Dropdown(multiselect=True, value=[], label="Mask Selection", info="Choose 1~all mask(s) added in Step 2", visible=False, scale=2)++ mask_dropdown = gr.Dropdown(multiselect=True, value=[], label="Mask Selection", info="Choose 1~all mask(s) added in Step 2", visible=False, scale=2, allow_custom_value=True)# input videowith gr.Row(equal_height=True):@@@ -908,7 -907,7 +1074,7 @@@foreground_video_output = gr.Video(label="Original Video Input", visible=False, elem_classes="video")foreground_output_button = gr.Button(value="Black & White Video Output", visible=False, elem_classes="new_button")with gr.Column(scale=2):-- alpha_video_output = gr.Video(label="B & W Mask Video Output", visible=False, elem_classes="video")++ alpha_video_output = gr.Video(label="Mask Video Output", visible=False, elem_classes="video")export_image_mask_btn = gr.Button(value="Alpha Mask Output", visible=False, elem_classes="new_button")with gr.Row():with gr.Row(visible= False):@@@ -917,17 -916,17 +1083,17 @@@export_to_current_video_engine_btn = gr.Button("Export to Control Video Input and Video Mask Input", visible= False)export_to_current_video_engine_btn.click( fn=export_to_current_video_engine, inputs= [state, foreground_video_output, alpha_video_output], outputs= [refresh_form_trigger]).then( #video_prompt_video_guide_trigger,-- fn=teleport_to_video_tab, inputs= [tab_state], outputs= [tabs])++ fn=teleport_to_video_tab, inputs= [tab_state, state], outputs= [tabs])# first step: get the video informationextract_frames_button.click(fn=get_frames_from_video,inputs=[-- video_input, video_state++ state, video_input, video_state, new_dim],-- outputs=[video_state, video_info, template_frame,-- image_selection_slider, end_selection_slider, track_pause_number_slider, point_prompt, matting_type, clear_button_click, add_mask_button, matting_button, template_frame,++ outputs=[video_state, extract_frames_button, video_info, template_frame,++ image_selection_slider, end_selection_slider, track_pause_number_slider, point_prompt, dummy, clear_button_click, add_mask_button, matting_button, template_frame,foreground_video_output, alpha_video_output, foreground_output_button, export_image_mask_btn, mask_dropdown, step2_title])@@@ -942,7 -941,7 +1108,7 @@@# click select image to get mask using samtemplate_frame.select(fn=sam_refine,-- inputs=[video_state, point_prompt, click_state, interactive_state],++ inputs=[state, video_state, point_prompt, click_state, interactive_state],outputs=[template_frame, video_state, interactive_state])@@@ -965,7 -964,7 +1131,7 @@@inputs=[],outputs=[foreground_video_output, alpha_video_output]).then(fn=video_matting,-- inputs=[video_state, video_input, end_selection_slider, matting_type, interactive_state, mask_dropdown, erode_kernel_size, dilate_kernel_size],++ inputs=[state, video_state, mask_type, video_input, end_selection_slider, matting_type, new_dim, interactive_state, mask_dropdown, erode_kernel_size, dilate_kernel_size],outputs=[foreground_video_output, alpha_video_output,foreground_video_output, alpha_video_output, export_to_vace_video_14B_btn, export_to_current_video_engine_btn])@@@ -983,10 -982,10 +1149,11 @@@outputs=[video_state,interactive_state,-- click_state,-- foreground_video_output, alpha_video_output,++ click_state,++ extract_frames_button, dummy,++ foreground_video_output, dummy, alpha_video_output,template_frame,-- image_selection_slider, end_selection_slider, track_pause_number_slider,point_prompt, export_to_vace_video_14B_btn, export_to_current_video_engine_btn, matting_type, clear_button_click,++ image_selection_slider, end_selection_slider, track_pause_number_slider,point_prompt, export_to_vace_video_14B_btn, export_to_current_video_engine_btn, dummy, clear_button_click,add_mask_button, matting_button, template_frame, foreground_video_output, alpha_video_output, remove_mask_button, foreground_output_button, export_image_mask_btn, mask_dropdown, video_info, step2_title],queue=False,@@@ -999,9 -998,9 +1166,10 @@@video_state,interactive_state,click_state,-- foreground_video_output, alpha_video_output,++ extract_frames_button, dummy,++ foreground_video_output, dummy, alpha_video_output,template_frame,-- image_selection_slider , end_selection_slider, track_pause_number_slider,point_prompt, export_to_vace_video_14B_btn, export_to_current_video_engine_btn, matting_type, clear_button_click,++ image_selection_slider , end_selection_slider, track_pause_number_slider,point_prompt, export_to_vace_video_14B_btn, export_to_current_video_engine_btn, dummy, clear_button_click,add_mask_button, matting_button, template_frame, foreground_video_output, alpha_video_output, remove_mask_button, foreground_output_button, export_image_mask_btn, mask_dropdown, video_info, step2_title],queue=False,@@@ -1102,31 -1101,31 +1270,36 @@@matting_button = gr.Button(value="Image Matting", interactive=True, visible=False, elem_classes="green_button", min_width=100)# output image-- with gr.Row(equal_height=True):-- foreground_image_output = gr.Image(type="pil", label="Foreground Output", visible=False, elem_classes="image")-- alpha_image_output = gr.Image(type="pil", label="Mask", visible=False, elem_classes="image")++ with gr.Tabs(visible = False) as image_tabs:++ with gr.TabItem("Control Image & Mask", visible = False) as image_first_tab:++ with gr.Row(equal_height=True):++ control_image_output = gr.Image(type="pil", label="Control Image", visible=False, elem_classes="image")++ alpha_image_output = gr.Image(type="pil", label="Mask", visible=False, elem_classes="image")++ with gr.Row():++ export_image_mask_btn = gr.Button(value="Set to Control Image & Mask", visible=False, elem_classes="new_button")++ with gr.TabItem("Reference Image", visible = False) as image_second_tab:++ with gr.Row():++ foreground_image_output = gr.Image(type="pil", label="Foreground Output", visible=False, elem_classes="image")++ with gr.Row():++ export_image_btn = gr.Button(value="Add to current Reference Images", visible=False, elem_classes="new_button")++with gr.Row(equal_height=True):bbox_info = gr.Text(label ="Mask BBox Info (Left:Top:Right:Bottom)", visible = False, interactive= False)-- with gr.Row():-- # with gr.Row():-- export_image_btn = gr.Button(value="Add to current Reference Images", visible=False, elem_classes="new_button")-- # with gr.Column(scale=2, visible= True):-- export_image_mask_btn = gr.Button(value="Set to Control Image & Mask", visible=False, elem_classes="new_button")export_image_btn.click( fn=export_image, inputs= [state, foreground_image_output], outputs= [refresh_form_trigger]).then( #video_prompt_video_guide_trigger,-- fn=teleport_to_video_tab, inputs= [tab_state], outputs= [tabs])-- export_image_mask_btn.click( fn=export_image_mask, inputs= [state, image_input, alpha_image_output], outputs= [refresh_form_trigger]).then( #video_prompt_video_guide_trigger,-- fn=teleport_to_video_tab, inputs= [tab_state], outputs= [tabs]).then(fn=None, inputs=None, outputs=None, js=click_brush_js)++ fn=teleport_to_video_tab, inputs= [tab_state, state], outputs= [tabs])++ export_image_mask_btn.click( fn=export_image_mask, inputs= [state, control_image_output, alpha_image_output], outputs= [refresh_form_trigger]).then( #video_prompt_video_guide_trigger,++ fn=teleport_to_video_tab, inputs= [tab_state, state], outputs= [tabs]).then(fn=None, inputs=None, outputs=None, js=click_brush_js)# first step: get the image informationextract_frames_button.click(fn=get_frames_from_image,inputs=[-- image_input, image_state++ state, image_input, image_state, new_dim],-- outputs=[image_state, image_info, template_frame,++ outputs=[image_state, extract_frames_button, image_info, template_frame,image_selection_slider, track_pause_number_slider,point_prompt, clear_button_click, add_mask_button, matting_button, template_frame,-- foreground_image_output, alpha_image_output, bbox_info, export_image_btn, export_image_mask_btn, mask_dropdown, step2_title]++ foreground_image_output, alpha_image_output, control_image_output, image_tabs, bbox_info, export_image_btn, export_image_mask_btn, mask_dropdown, step2_title])# points clear@@@ -1148,7 -1147,7 +1321,7 @@@# click select image to get mask using samtemplate_frame.select(fn=sam_refine,-- inputs=[image_state, point_prompt, click_state, interactive_state],++ inputs=[state, image_state, point_prompt, click_state, interactive_state],outputs=[template_frame, image_state, interactive_state])@@@ -1168,8 -1167,8 +1341,8 @@@# image mattingmatting_button.click(fn=image_matting,-- inputs=[image_state, interactive_state, mask_dropdown, erode_kernel_size, dilate_kernel_size, image_selection_slider],-- outputs=[foreground_image_output, alpha_image_output,foreground_image_output, alpha_image_output,bbox_info, export_image_btn, export_image_mask_btn]++ inputs=[state, image_state, interactive_state, mask_type, matting_type, new_dim, mask_dropdown, erode_kernel_size, dilate_kernel_size, image_selection_slider],++ outputs=[image_tabs, image_first_tab, image_second_tab, foreground_image_output, control_image_output, alpha_image_output, foreground_image_output, control_image_output, alpha_image_output, bbox_info, export_image_btn, export_image_mask_btn])nada = gr.State({})@@@ -1182,7 -1181,7 +1355,8 @@@image_state,interactive_state,click_state,-- foreground_image_output, alpha_image_output,++ extract_frames_button, image_tabs,++ foreground_image_output, control_image_output, alpha_image_output,template_frame,image_selection_slider, image_selection_slider, track_pause_number_slider,point_prompt, export_image_btn, export_image_mask_btn, bbox_info, clear_button_click,add_mask_button, matting_button, template_frame, foreground_image_output, alpha_image_output, remove_mask_button, export_image_btn, export_image_mask_btn, mask_dropdown, nada, step2_titlediff --cc requirements.txtindex 4fa1e10,9b2c6ee..c8294cb--- a/requirements.txt+++ b/requirements.txt@@@ -48,7 -48,7 +48,7 @@@ pydantic==2.10.# Math & modelingtorchdiffeq>=0.2.5tensordict>=0.6.1- mmgp==3.6.3-mmgp==3.6.0++mmgp==3.6.4peft==0.15.0matplotlibdiff --cc shared/utils/audio_video.pyindex 3f59cc7,f7f1922..5bf35df--- a/shared/utils/audio_video.py+++ b/shared/utils/audio_video.py@@@ -265,6 -273,17 +265,7 @@@ def save_video(tensorwriter.append_data(frame)writer.close()-- # Embed source images if provided and container supports it- if source_images and container in ['mkv', 'mp4']:- try:- if container == 'mp4':- cache_file = embed_source_images_metadata_mp4(cache_file, source_images)- else: # mkv- cache_file = embed_source_images_metadata(cache_file, source_images)- except Exception as e:- print(f"Warning: Failed to embed source images: {e}")-++return cache_fileexcept Exception as e:diff --cc shared/utils/process_locks.pyindex 0000000,0000000..8def3ebnew file mode 100644--- /dev/null+++ b/shared/utils/process_locks.py@@@ -1,0 -1,0 +1,74 @@@++import time++import threading++import torch++++gen_lock = threading.Lock()++++def get_gen_info(state):++ cache = state.get("gen", None)++ if cache == None:++ cache = dict()++ state["gen"] = cache++ return cache++++def any_GPU_process_running(state, process_id):++ gen = get_gen_info(state)++#"process:" + process_id++ with gen_lock:++ process_status = gen.get("process_status", None)++ return process_status is not None++++def acquire_GPU_ressources(state, process_id, process_name, gr = None):++ gen = get_gen_info(state)++ original_process_status = None++ while True:++ with gen_lock:++ process_hierarchy = gen.get("process_hierarchy", None)++ if process_hierarchy is None:++ process_hierarchy = dict()++ gen["process_hierarchy"]= process_hierarchy++++ process_status = gen.get("process_status", None)++ if process_status is None:++ original_process_status = process_status++ gen["process_status"] = "process:" + process_id++ break++ elif process_status == "process:main":++ original_process_status = process_status++ gen["process_status"] = "request:" + process_id++ gen["pause_msg"] = f"Generation Suspended while using {process_name}"++ break++ elif process_status == "process:" + process_id:++ break++ time.sleep(0.1)++++ if original_process_status is not None:++ total_wait = 0++ wait_time = 0.1++ wait_msg_displayed = False++ while True:++ with gen_lock:++ process_status = gen.get("process_status", None)++ if process_status == "process:" + process_id: break++ if process_status is None:++ # handle case when main process has finished at some point in between the last check and now++ gen["process_status"] = "process:" + process_id++ break++++ total_wait += wait_time++ if round(total_wait,2) >= 5 and gr is not None and not wait_msg_displayed:++ wait_msg_displayed = True++ gr.Info(f"Process {process_name} is Suspended while waiting that GPU Ressources become available")++++ time.sleep(wait_time)++++ with gen_lock:++ process_hierarchy[process_id] = original_process_status++ torch.cuda.synchronize()++++def release_GPU_ressources(state, process_id):++ gen = get_gen_info(state)++ torch.cuda.synchronize()++ with gen_lock:++ process_hierarchy = gen.get("process_hierarchy", {})++ gen["process_status"] = process_hierarchy.get(process_id, None)diff --cc shared/utils/utils.pyindex 77e4410,43c2443..4c781c9--- a/shared/utils/utils.py+++ b/shared/utils/utils.py@@@ -17,6 -17,6 +17,7 @@@ import oimport tempfileimport subprocessimport json++import timefrom functools import lru_cacheos.environ["U2NET_HOME"] = os.path.join(os.getcwd(), "ckpts", "rembg")@@@ -76,7 -76,7 +77,13 @@@ def get_file_creation_date(file_path)stat = os.stat(file_path)return datetime.fromtimestamp(stat.st_birthtime if hasattr(stat, 'st_birthtime') else stat.st_mtime)--def truncate_for_filesystem(s, max_bytes=255):++def sanitize_file_name(file_name, rep =""):++ return file_name.replace("/",rep).replace("\\",rep).replace(":",rep).replace("|",rep).replace("?",rep).replace("<",rep).replace(">",rep).replace("\"",rep).replace("\n",rep).replace("\r",rep)++++def truncate_for_filesystem(s, max_bytes=None):++ if max_bytes is None:++ max_bytes = 50 if os.name == 'nt'else 100++if len(s.encode('utf-8')) <= max_bytes: return sl, r = 0, len(s)while l < r:@@@ -85,6 -85,6 +92,48 @@@else: r = m - 1return s[:l]++def get_default_workers():++ return os.cpu_count()/ 2++++def process_images_multithread(image_processor, items, process_type, wrap_in_list = True, max_workers: int = os.cpu_count()/ 2, in_place = False) :++ if not items:++ return []++++ import concurrent.futures++ start_time = time.time()++ # print(f"Preprocessus:{process_type} started")++ if process_type in ["prephase", "upsample"]:++ if wrap_in_list :++ items_list = [ [img] for img in items]++ else:++ items_list = items++ if max_workers == 1:++ results = []++ for idx, item in enumerate(items):++ item = image_processor(item)++ results.append(item)++ if wrap_in_list: items_list[idx] = None++ if in_place: items[idx] = item[0] if wrap_in_list else item++ else:++ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:++ futures = {executor.submit(image_processor, img): idx for idx, img in enumerate(items_list)}++ results = [None] * len(items_list)++ for future in concurrent.futures.as_completed(futures):++ idx = futures[future]++ results[idx] = future.result()++ if wrap_in_list: items_list[idx] = None++ if in_place:++ items[idx] = results[idx][0] if wrap_in_list else results[idx]++++ if wrap_in_list:++ results = [ img[0] for img in results]++ else:++ results= image_processor(items)++++ end_time = time.time()++ # print(f"duration:{end_time-start_time:.1f}")++++ return results@lru_cache(maxsize=100)def get_video_info(video_path):global video_info_cache@@@ -205,12 -205,12 +254,11 @@@ def get_outpainting_full_area_dimensionframe_width = int(frame_width * (100 + outpainting_left + outpainting_right) / 100)return frame_height, frame_width--def rgb_bw_to_rgba_mask(img, thresh=127):-- a = img.convert('L').point(lambda p: 255 if p > thresh else 0) # alpha-- out = Image.new('RGBA', img.size, (255, 255, 255, 0)) # white, transparent-- out.putalpha(a) # white where alpha=255-- return out--++def rgb_bw_to_rgba_mask(img, thresh=127):++ arr = np.array(img.convert('L'))++ alpha = (arr > thresh).astype(np.uint8) * 255++ rgba = np.dstack([np.full_like(alpha, 255)] * 3 + [alpha])++ return Image.fromarray(rgba, 'RGBA')def get_outpainting_frame_location(final_height, final_width, outpainting_dims, block_size = 8):diff --cc shared/utils/video_metadata.pyindex 0000000,9a8ad45..229dbb5mode 000000,100644..100644--- a/shared/utils/video_metadata.py+++ b/shared/utils/video_metadata.py@@@ -1,0 -1,166 +1,512 @@@+ """+ Video Metadata Utilities++ This module provides functionality to read and write JSON metadata to video files.+ - MP4: Uses mutagen to store metadata in ©cmt tag+ - MKV: Uses FFmpeg to store metadata in comment/description tags+ """++ import json+ import subprocess+ import os+ import shutil++import tempfile+++def _convert_image_to_bytes(img):++ """++ Convert various image formats to bytes suitable for MP4 cover art.++++ Args:++ img: Can be:++ - PIL Image object++ - File path (str)++ - bytes++++ Returns:++ tuple: (image_bytes, image_format)++ - image_bytes: Binary image data++ - image_format: AtomDataType constant (JPEG or PNG)++ """++ from mutagen.mp4 import AtomDataType++ from PIL import Image++ import io++ import os++++ try:++ # If it's already bytes, detect format and return++ if isinstance(img, bytes):++ # Detect format from magic numbers++ if img.startswith(b'\x89PNG'):++ return img, AtomDataType.PNG++ else:++ return img, AtomDataType.JPEG++++ # If it's a file path, read and convert++ if isinstance(img, str):++ if not os.path.exists(img):++ print(f"Warning: Image file not found: {img}")++ return None, None++++ # Determine format from extension++ ext = os.path.splitext(img)[1].lower()++++ # Open with PIL for conversion++ pil_img = Image.open(img)++++ # Convert to RGB if necessary (handles RGBA, P, etc.)++ if pil_img.mode not in ('RGB', 'L'):++ if pil_img.mode == 'RGBA':++ # Create white background for transparency++ background = Image.new('RGB', pil_img.size, (255, 255, 255))++ background.paste(pil_img, mask=pil_img.split()[3])++ pil_img = background++ else:++ pil_img = pil_img.convert('RGB')++++ # Save to bytes++ img_bytes = io.BytesIO()++++ # Use PNG for lossless formats, JPEG for others++ if ext in ['.png', '.bmp', '.tiff', '.tif']:++ pil_img.save(img_bytes, format='PNG')++ img_format = AtomDataType.PNG++ else:++ pil_img.save(img_bytes, format='JPEG', quality=95)++ img_format = AtomDataType.JPEG++++ return img_bytes.getvalue(), img_format++++ # If it's a PIL Image++ if isinstance(img, Image.Image):++ # Convert to RGB if necessary++ if img.mode not in ('RGB', 'L'):++ if img.mode == 'RGBA':++ background = Image.new('RGB', img.size, (255, 255, 255))++ background.paste(img, mask=img.split()[3])++ img = background++ else:++ img = img.convert('RGB')++++ # Save to bytes (prefer PNG for quality)++ img_bytes = io.BytesIO()++ img.save(img_bytes, format='PNG')++ return img_bytes.getvalue(), AtomDataType.PNG++++ print(f"Warning: Unsupported image type: {type(img)}")++ return None, None++++ except Exception as e:++ print(f"Error converting image to bytes: {e}")++ return None, None+-def save_metadata_to_mp4(file_path, metadata_dict):++def embed_source_images_metadata_mp4(file, source_images):++ from mutagen.mp4 import MP4, MP4Cover, AtomDataType++ import json++ import os++++ if not source_images:++ return file++++ try:++++ # Convert source images to cover art and build metadata++ cover_data = []++ image_metadata = {} # Maps tag to list of {index, filename, extension}++++ # Process each source image type++ for img_tag, img_data in source_images.items():++ if img_data is None:++ continue++++ tag_images = []++++ # Normalize to list for uniform processing++ img_list = img_data if isinstance(img_data, list) else [img_data]++++ for img in img_list:++ if img is not None:++ cover_bytes, image_format = _convert_image_to_bytes(img)++ if cover_bytes:++ # Extract filename and extension++ if isinstance(img, str) and os.path.exists(img):++ filename = os.path.basename(img)++ extension = os.path.splitext(filename)[1]++ else:++ # PIL Image or unknown - infer from format++ extension = '.png' if image_format == AtomDataType.PNG else '.jpg'++ filename = f"{img_tag}{extension}"++++ tag_images.append({++ 'index': len(cover_data),++ 'filename': filename,++ 'extension': extension++ })++ cover_data.append(MP4Cover(cover_bytes, image_format))++++ if tag_images:++ image_metadata[img_tag] = tag_images++++ if cover_data:++ file.tags['----:com.apple.iTunes:EMBEDDED_IMAGES'] = cover_data++ # Store the complete metadata as JSON++ file.tags['----:com.apple.iTunes:IMAGE_METADATA'] = json.dumps(image_metadata).encode('utf-8')++ # print(f"Successfully embedded {len(cover_data)} cover images")++ # print(f"Image tags: {list(image_metadata.keys())}")++++ except Exception as e:++ print(f"Failed to embed cover art with mutagen: {e}")++ print(f"This might be due to image format or MP4 file structure issues")++++ return file++++++def save_metadata_to_mp4(file_path, metadata_dict, source_images = None):+ """+ Save JSON metadata to MP4 file using mutagen.++ Args:+ file_path (str): Path to MP4 file+ metadata_dict (dict): Metadata dictionary to save++ Returns:+ bool: True if successful, False otherwise+ """+ try:+ from mutagen.mp4 import MP4+ file = MP4(file_path)+ file.tags['©cmt'] = [json.dumps(metadata_dict)]++ if source_images is not None:++ embed_source_images_metadata_mp4(file, source_images)+ file.save()+ return True+ except Exception as e:+ print(f"Error saving metadata to MP4 {file_path}: {e}")+ return False+++ def save_metadata_to_mkv(file_path, metadata_dict):+ """+ Save JSON metadata to MKV file using FFmpeg.++ Args:+ file_path (str): Path to MKV file+ metadata_dict (dict): Metadata dictionary to save++ Returns:+ bool: True if successful, False otherwise+ """+ try:+ # Create temporary file with metadata+ temp_path = file_path.replace('.mkv', '_temp_with_metadata.mkv')++ # Use FFmpeg to add metadata while preserving ALL streams (including attachments)+ ffmpeg_cmd = [+ 'ffmpeg', '-y', '-i', file_path,+ '-metadata', f'comment={json.dumps(metadata_dict)}',+ '-map', '0', # Map all streams from input (including attachments)+ '-c', 'copy', # Copy streams without re-encoding+ temp_path+ ]++ result = subprocess.run(ffmpeg_cmd, capture_output=True, text=True)++ if result.returncode == 0:+ # Replace original with metadata version+ shutil.move(temp_path, file_path)+ return True+ else:+ print(f"Warning: Failed to add metadata to MKV file: {result.stderr}")+ # Clean up temp file if it exists+ if os.path.exists(temp_path):+ os.remove(temp_path)+ return False++ except Exception as e:+ print(f"Error saving metadata to MKV {file_path}: {e}")+ return False++-def save_metadata_to_video(file_path, metadata_dict):++++def save_video_metadata(file_path, metadata_dict, source_images= None):+ """+ Save JSON metadata to video file (auto-detects MP4 vs MKV).++ Args:+ file_path (str): Path to video file+ metadata_dict (dict): Metadata dictionary to save++ Returns:+ bool: True if successful, False otherwise+ """+++ if file_path.endswith('.mp4'):- return save_metadata_to_mp4(file_path, metadata_dict)++ return save_metadata_to_mp4(file_path, metadata_dict, source_images)+ elif file_path.endswith('.mkv'):+ return save_metadata_to_mkv(file_path, metadata_dict)+ else:+ return False+++ def read_metadata_from_mp4(file_path):+ """+ Read JSON metadata from MP4 file using mutagen.++ Args:+ file_path (str): Path to MP4 file++ Returns:+ dict or None: Metadata dictionary if found, None otherwise+ """+ try:+ from mutagen.mp4 import MP4+ file = MP4(file_path)+ tags = file.tags['©cmt'][0]+ return json.loads(tags)+ except Exception:+ return None+++ def read_metadata_from_mkv(file_path):+ """+ Read JSON metadata from MKV file using ffprobe.++ Args:+ file_path (str): Path to MKV file++ Returns:+ dict or None: Metadata dictionary if found, None otherwise+ """+ try:+ # Try to get metadata using ffprobe+ result = subprocess.run([+ 'ffprobe', '-v', 'quiet', '-print_format', 'json',+ '-show_format', file_path+ ], capture_output=True, text=True)++ if result.returncode == 0:+ probe_data = json.loads(result.stdout)+ format_tags = probe_data.get('format', {}).get('tags', {})++ # Look for our metadata in various possible tag locations+ for tag_key in ['comment', 'COMMENT', 'description', 'DESCRIPTION']:+ if tag_key in format_tags:+ try:+ return json.loads(format_tags[tag_key])+ except:+ continue+ return None+ except Exception:+ return None+++ def read_metadata_from_video(file_path):+ """+ Read JSON metadata from video file (auto-detects MP4 vs MKV).++ Args:+ file_path (str): Path to video file++ Returns:+ dict or None: Metadata dictionary if found, None otherwise+ """+ if file_path.endswith('.mp4'):+ return read_metadata_from_mp4(file_path)+ elif file_path.endswith('.mkv'):+ return read_metadata_from_mkv(file_path)+ else:+ return None+++def _extract_mp4_cover_art(video_path, output_dir = None):++ """++ Extract cover art from MP4 files using mutagen with proper tag association.++++ Args:++ video_path (str): Path to the MP4 file++ output_dir (str): Directory to save extracted images++++ Returns:++ dict: Dictionary mapping tags to lists of extracted image file paths++ Format: {tag_name: [path1, path2, ...], ...}++ """++ try:++ from mutagen.mp4 import MP4++ import json++++ file = MP4(video_path)++++ if file.tags is None or '----:com.apple.iTunes:EMBEDDED_IMAGES' not in file.tags:++ return {}++++ cover_art = file.tags['----:com.apple.iTunes:EMBEDDED_IMAGES']++++ # Retrieve the image metadata++ metadata_data = file.tags.get('----:com.apple.iTunes:IMAGE_METADATA')++++ if metadata_data:++ # Deserialize metadata and extract with original filenames++ image_metadata = json.loads(metadata_data[0].decode('utf-8'))++ extracted_files = {}++++ for tag, tag_images in image_metadata.items():++ extracted_files[tag] = []++++ for img_info in tag_images:++ cover_idx = img_info['index']++++ if cover_idx >= len(cover_art):++ continue++ if output_dir is None: output_dir = _create_temp_dir()++ os.makedirs(output_dir, exist_ok=True)++++ cover = cover_art[cover_idx]++++ # Use original filename++ filename = img_info['filename']++ output_file = os.path.join(output_dir, filename)++++ # Handle duplicate filenames by adding suffix++ if os.path.exists(output_file):++ base, ext = os.path.splitext(filename)++ counter = 1++ while os.path.exists(output_file):++ filename = f"{base}_{counter}{ext}"++ output_file = os.path.join(output_dir, filename)++ counter += 1++++++ # Write cover art to file++ with open(output_file, 'wb') as f:++ f.write(cover)++++ if os.path.exists(output_file):++ extracted_files[tag].append(output_file)++++ return extracted_files++++ else:++ # Fallback: Extract all images with generic naming++ print(f"Warning: No IMAGE_METADATA found in {video_path}, using generic extraction")++ extracted_files = {'unknown': []}++++ for i, cover in enumerate(cover_art):++ if output_dir is None: output_dir = _create_temp_dir()++ os.makedirs(output_dir, exist_ok=True)++++ filename = f"cover_art_{i}.jpg"++ output_file = os.path.join(output_dir, filename)++++ with open(output_file, 'wb') as f:++ f.write(cover)++++ if os.path.exists(output_file):++ extracted_files['unknown'].append(output_file)++++ return extracted_files++++ except Exception as e:++ print(f"Error extracting cover art from MP4: {e}")++ return {}++++def _create_temp_dir():++ temp_dir = tempfile.mkdtemp()++ os.makedirs(temp_dir, exist_ok=True)++ return temp_dir++++def extract_source_images(video_path, output_dir = None):++++ # Handle MP4 files with mutagen++ if video_path.lower().endswith('.mp4'):++ return _extract_mp4_cover_art(video_path, output_dir)++ if output_dir is None:++ output_dir = _create_temp_dir()++++ # Handle MKV files with ffmpeg (existing logic)++ try:++ # First, probe the video to find attachment streams (attached pics)++ probe_cmd = [++ 'ffprobe', '-v', 'quiet', '-print_format', 'json',++ '-show_streams', video_path++ ]++++ result = subprocess.run(probe_cmd, capture_output=True, text=True, check=True)++ import json as json_module++ probe_data = json_module.loads(result.stdout)++++ # Find attachment streams (attached pics)++ attachment_streams = []++ for i, stream in enumerate(probe_data.get('streams', [])):++ # Check for attachment streams in multiple ways:++ # 1. Traditional attached_pic flag++ # 2. Video streams with image-like metadata (filename, mimetype)++ # 3. MJPEG codec which is commonly used for embedded images++ is_attached_pic = stream.get('disposition', {}).get('attached_pic', 0) == 1++++ # Check for image metadata in video streams (our case after metadata embedding)++ tags = stream.get('tags', {})++ has_image_metadata = (++ 'FILENAME' in tags and tags['FILENAME'].lower().endswith(('.jpg', '.jpeg', '.png')) or++ 'filename' in tags and tags['filename'].lower().endswith(('.jpg', '.jpeg', '.png')) or++ 'MIMETYPE' in tags and tags['MIMETYPE'].startswith('image/') or++ 'mimetype' in tags and tags['mimetype'].startswith('image/')++ )++++ # Check for MJPEG codec (common for embedded images)++ is_mjpeg = stream.get('codec_name') == 'mjpeg'++++ if (stream.get('codec_type') == 'video' and++ (is_attached_pic or (has_image_metadata and is_mjpeg))):++ attachment_streams.append(i)++++ if not attachment_streams:++ return []++++ # Extract each attachment stream++ extracted_files = []++ used_filenames = set() # Track filenames to avoid collisions++++ for stream_idx in attachment_streams:++ # Get original filename from metadata if available++ stream_info = probe_data['streams'][stream_idx]++ tags = stream_info.get('tags', {})++ original_filename = (++ tags.get('filename') or++ tags.get('FILENAME') or++ f'attachment_{stream_idx}.png'++ )++++ # Clean filename for filesystem++ safe_filename = os.path.basename(original_filename)++ if not safe_filename.lower().endswith(('.jpg', '.jpeg', '.png')):++ safe_filename += '.png'++++ # Handle filename collisions++ base_name, ext = os.path.splitext(safe_filename)++ counter = 0++ final_filename = safe_filename++ while final_filename in used_filenames:++ counter += 1++ final_filename = f"{base_name}_{counter}{ext}"++ used_filenames.add(final_filename)++++ output_file = os.path.join(output_dir, final_filename)++++ # Extract the attachment stream++ extract_cmd = [++ 'ffmpeg', '-y', '-i', video_path,++ '-map', f'0:{stream_idx}', '-frames:v', '1',++ output_file++ ]++++ try:++ subprocess.run(extract_cmd, capture_output=True, text=True, check=True)++ if os.path.exists(output_file):++ extracted_files.append(output_file)++ except subprocess.CalledProcessError as e:++ print(f"Failed to extract attachment {stream_idx} from {os.path.basename(video_path)}: {e.stderr}")++++ return extracted_files++++ except subprocess.CalledProcessError as e:++ print(f"Error extracting source images from {os.path.basename(video_path)}: {e.stderr}")++ return []++diff --cc wgp.pyindex fd1d6a9,6e714ad..b8a4020--- a/wgp.py+++ b/wgp.py@@@ -1,11 -1,11 +1,13 @@@--import os++import os, sysos.environ["GRADIO_LANG"] = "en"# # os.environ.pop("TORCH_LOGS", None) # make sure no env var is suppressing/overriding# os.environ["TORCH_LOGS"]= "recompiles"import torch._logging as tlog# tlog.set_logs(recompiles=True, guards=True, graph_breaks=True)++p = os.path.dirname(os.path.abspath(__file__))++if p not in sys.path:++ sys.path.insert(0, p)import time--import sysimport threadingimport argparsefrom mmgp import offload, safetensors2, profile_type@@@ -27,10 -27,9 +29,13 @@@ from shared.utils.utils import calculatfrom shared.utils.utils import has_video_file_extension, has_image_file_extensionfrom shared.utils.audio_video import extract_audio_tracks, combine_video_with_audio_tracks, combine_and_concatenate_video_with_audio_tracks, cleanup_temp_audio_files, save_video, save_imagefrom shared.utils.audio_video import save_image_metadata, read_image_metadata++from shared.utils.video_metadata import save_video_metadatafrom shared.match_archi import match_nvidia_architecturefrom shared.attention import get_attention_modes, get_supported_attention_modes-from huggingface_hub import hf_hub_download, snapshot_download++from shared.utils.utils import truncate_for_filesystem, sanitize_file_name, process_images_multithread, get_default_workers++from shared.utils.process_locks import acquire_GPU_ressources, release_GPU_ressources, gen_lock+from huggingface_hub import hf_hub_download, snapshot_download+from shared.utils import files_locator as flimport torchimport gcimport traceback@@@ -63,11 -61,12 +68,12 @@@ from collections import defaultdicglobal_queue_ref = []AUTOSAVE_FILENAME = "queue.zip"PROMPT_VARS_MAX = 10- target_mmgp_version = "3.6.3"- WanGP_version = "8.996"--target_mmgp_version = "3.6.0"-WanGP_version = "8.9"-settings_version = 2.38++target_mmgp_version = "3.6.4"++WanGP_version = "9.0"+settings_version = 2.39max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None++image_names_list = ["image_start", "image_end", "image_refs"]from importlib.metadata import versionmmgp_version = version("mmgp")@@@ -80,7 -79,7 +86,6 @@@ task_id =vmc_event_handler = matanyone_app.get_vmc_event_handler()unique_id = 0unique_id_lock = threading.Lock()--gen_lock = threading.Lock()offloadobj = enhancer_offloadobj = wan_model = Nonereload_needed = True@@@ -303,10 -280,10 +308,11 @@@ def process_prompt_and_add_tasks(statereturn ret()inputs["prompt"] = ", ".join(prompt)add_video_task(**inputs)-- gen["prompts_max"] = 1 + gen.get("prompts_max",0)++ new_prompts_count = gen["prompts_max"] = 1 + gen.get("prompts_max",0)state["validate_success"] = 1queue= gen.get("queue", [])-- return ret()++ return update_queue_data(queue), gr.update(open=True) if new_prompts_count > 1 else gr.update()++if hasattr(model_handler, "validate_generative_settings"):error = model_handler.validate_generative_settings(model_type, model_def, inputs)@@@ -705,9 -676,9 +711,7 @@@gen["prompts_max"] = new_prompts_countstate["validate_success"] = 1queue= gen.get("queue", [])-- first_time_in_queue = state.get("first_time_in_queue", True)-- state["first_time_in_queue"] = True-- return update_queue_data(queue, first_time_in_queue), gr.update(open=True) if new_prompts_count > 1 else gr.update()++ return update_queue_data(queue), gr.update(open=True) if new_prompts_count > 1 else gr.update()def get_preview_images(inputs):inputs_to_query = ["image_start", "video_source", "image_end", "video_guide", "image_guide", "video_mask", "image_mask", "image_refs" ]@@@ -750,10 -721,10 +754,10 @@@ def add_video_task(**inputs)queue.append({"id": current_task_id,"params": inputs.copy(),- "repeats": inputs["repeat_generation"],- "length": inputs["video_length"], # !!!- "steps": inputs["num_inference_steps"],- "prompt": inputs["prompt"],+ "repeats": inputs.get("repeat_generation",1),- "length": inputs.get("video_length",1),- "steps": inputs.get("num_inference_steps",1),++ "length": inputs.get("video_length",0) or 0,++ "steps": inputs.get("num_inference_steps",0) or 0,+ "prompt": inputs.get("prompt", ""),"start_image_labels": start_image_labels,"end_image_labels": end_image_labels,"start_image_data": start_image_data,@@@ -1377,7 -1348,7 +1381,7 @@@ def get_queue_table(queue)"✖"])return data--def update_queue_data(queue, first_time_in_queue =False):++def update_queue_data(queue):update_global_queue_ref(queue)data = get_queue_table(queue)@@@ -2703,35 -2652,8 +2709,33 @@@ def download_models(model_filename = Nooffload.default_verboseLevel = verbose_level--def sanitize_file_name(file_name, rep =""):-- return file_name.replace("/",rep).replace("\\",rep).replace(":",rep).replace("|",rep).replace("?",rep).replace("<",rep).replace(">",rep).replace("\"",rep).replace("\n",rep).replace("\r",rep)++def check_loras_exist(model_type, loras_choices_files, download = False, send_cmd = None):+ lora_dir = get_lora_dir(model_type)+ missing_local_loras = []+ missing_remote_loras = []+ for lora_file in loras_choices_files:+ local_path = os.path.join(lora_dir, os.path.basename(lora_file))+ if not os.path.isfile(local_path):+ url = loras_url_cache.get(local_path, None)+ if url is not None:+ if download:+ if send_cmd is not None:+ send_cmd("status", f'Downloading Lora {os.path.basename(lora_file)}...')+ try:+ download_file(url, local_path)+ except:+ missing_remote_loras.append(lora_file)+ else:+ missing_local_loras.append(lora_file)++ error = ""+ if len(missing_local_loras) > 0:+ error += f"The following Loras files are missing or invalid: {missing_local_loras}."+ if len(missing_remote_loras) > 0:+ error += f"The following Loras files could not be downloaded: {missing_remote_loras}."++ return errordef extract_preset(model_type, lset_name, loras):loras_choices = []@@@ -3150,15 -3078,12 +3157,15 @@@ def apply_changes( statereset_prompt_enhancer()if all(change in ["attention_mode", "vae_config", "boost", "save_path", "metadata_type", "clear_file_list", "fit_canvas", "depth_anything_v2_variant","notification_sound_enabled", "notification_sound_volume", "mmaudio_enabled", "max_frames_multiplier", "display_stats",- "video_output_codec", "image_output_codec", "audio_output_codec", "checkpoints_paths", "model_hierarchy_type"] for change in changes ):- "video_output_codec", "video_container", "embed_source_images", "image_output_codec", "audio_output_codec"] for change in changes ):++ "video_output_codec", "video_container", "embed_source_images", "image_output_codec", "audio_output_codec", "checkpoints_paths", "model_hierarchy_type"] for change in changes ):model_family = gr.Dropdown()+ model_base_type = gr.Dropdown()model_choice = gr.Dropdown()+ if "model_hierarchy_type" in changes:+ model_family, model_base_type, model_choice = generate_dropdown_model_list(model_type)else:reload_needed = True- model_family, model_choice = generate_dropdown_model_list(transformer_type)+ model_family, model_base_type, model_choice = generate_dropdown_model_list(model_type)header = generate_header(state["model_type"], compile=compile, attention_mode= attention_mode)mmaudio_enabled = server_config["mmaudio_enabled"] > 0@@@ -3189,11 -3114,11 +3196,11 @@@ def build_callback(state, pipe, send_cmif in_pause:send_cmd("progress", [0, pause_msg])while True:-- time.sleep(1)++ time.sleep(0.1)with gen_lock:process_status = gen.get("process_status", None)if process_status == "process:main": break--++ force_refresh = Truerefresh_id = gen.get("refresh", -1)if force_refresh or step_idx >= 0:pass@@@ -3763,35 -3688,35 +3770,7 @@@ def get_preprocessor(process_type, inpareturn anno_ins--def process_images_multithread(image_processor, items, process_type, wrap_in_list = True, max_workers: int = os.cpu_count()/ 2) :-- if not items:-- return []---- import concurrent.futures-- start_time = time.time()-- # print(f"Preprocessus:{process_type} started")-- if process_type in ["prephase", "upsample"]:-- if wrap_in_list :-- items = [ [img] for img in items]-- if max_workers == 1:-- results = [image_processor(img) for img in items]-- else:-- with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:-- futures = {executor.submit(image_processor, img): idx for idx, img in enumerate(items)}-- results = [None] * len(items)-- for future in concurrent.futures.as_completed(futures):-- idx = futures[future]-- results[idx] = future.result()---- if wrap_in_list:-- results = [ img[0] for img in results]-- else:-- results= image_processor(items)---- end_time = time.time()-- # print(f"duration:{end_time-start_time:.1f}")-- return resultsdef extract_faces_from_video_with_mask(input_video_path, input_mask_path, max_frames, start_frame, target_fps, size = 512):if not input_video_path or max_frames <= 0:@@@ -3849,8 -3774,8 +3828,6 @@@save_one_video(f"faces.mp4", saved_faces_frames, fps=target_fps, quality=8, macro_block_size=None)return face_tensor--def get_default_workers():-- return os.cpu_count()/ 2def preprocess_video_with_mask(input_video_path, input_mask_path, height, width, max_frames, start_frame=0, fit_canvas = None, fit_crop = False, target_fps = 16, block_size= 16, expand_scale = 2, process_type = "inpaint", process_type2 = None, to_bbox = False, RGB_Mask = False, negate_mask = False, process_outside_mask = None, inpaint_color = 127, outpainting_dims = None, proc_no = 1):@@@ -3951,6 -3876,6 +3928,7 @@@if len(mask.shape) == 3 and mask.shape[2] == 3:mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)++ _, mask = cv2.threshold(mask, 127.5, 255, cv2.THRESH_BINARY)original_mask = mask.copy()if expand_scale != 0:kernel_size = abs(expand_scale)@@@ -3958,7 -3883,7 +3936,6 @@@op_expand = cv2.dilate if expand_scale > 0 else cv2.erodemask = op_expand(mask, kernel, iterations=3)-- _, mask = cv2.threshold(mask, 127.5, 255, cv2.THRESH_BINARY)if to_bbox and np.sum(mask == 255) > 0 : #or Truex0, y0, x1, y1 = mask_to_xyxy_box(mask)mask = mask * 0@@@ -3978,7 -3903,7 +3955,7 @@@else:return (target_frame, None, None)max_workers = get_default_workers()-- proc_lists = process_images_multithread(prep_prephase, [frame_idx for frame_idx in range(num_frames)], "prephase", wrap_in_list= False, max_workers=max_workers)++ proc_lists = process_images_multithread(prep_prephase, [frame_idx for frame_idx in range(num_frames)], "prephase", wrap_in_list= False, max_workers=max_workers, in_place= True)proc_list, proc_list_outside, proc_mask = [None] * len(proc_lists), [None] * len(proc_lists), [None] * len(proc_lists)for frame_idx, frame_group in enumerate(proc_lists):proc_list[frame_idx], proc_list_outside[frame_idx], proc_mask[frame_idx] = frame_group@@@ -4175,7 -4100,7 +4152,7 @@@ def perform_spatial_upsampling(sample,frames_to_upsample = [sample[:, i] for i in range( sample.shape[1]) ]def upsample_frames(frame):return resize_lanczos(frame, h, w).unsqueeze(1)-- sample = torch.cat(process_images_multithread(upsample_frames, frames_to_upsample, "upsample", wrap_in_list = False, max_workers=get_default_workers()), dim=1)++ sample = torch.cat(process_images_multithread(upsample_frames, frames_to_upsample, "upsample", wrap_in_list = False, max_workers=get_default_workers(), in_place=True), dim=1)frames_to_upsample = Nonereturn sample@@@ -4349,12 -4271,10 +4326,13 @@@ def edit_videofile_list.append(new_video_path)file_settings_list.append(configs)- if configs != None:- from mutagen.mp4 import MP4- file = MP4(new_video_path)- file.tags['©cmt'] = [json.dumps(configs)]- file.save()-+ if configs != None:- from shared.utils.video_metadata import save_metadata_to_mp4- save_metadata_to_mp4(new_video_path, configs)-++ from shared.utils.video_metadata import extract_source_images, save_video_metadata++ temp_images_path = get_available_filename(save_path, video_source, force_extension= ".temp")++ embedded_images = extract_source_images(video_source, temp_images_path)++ save_video_metadata(new_video_path, configs, embedded_images)++ if os.path.isdir(temp_images_path):++ shutil.rmtree(temp_images_path, ignore_errors= True)send_cmd("output")seed = set_seed(-1)if has_already_audio:@@@ -4492,34 -4411,34 +4470,7 @@@ def enhance_prompt(state, prompt, promppipe = {}download_models()-- gen = get_gen_info(state)-- original_process_status = None-- while True:-- with gen_lock:-- process_status = gen.get("process_status", None)-- if process_status is None:-- original_process_status = process_status-- gen["process_status"] = "process:prompt_enhancer"-- break-- elif process_status == "process:main":-- original_process_status = process_status-- gen["process_status"] = "request:prompt_enhancer"-- gen["pause_msg"] = "Generation Suspended while using Prompt Enhancer"-- break-- elif process_status == "process:prompt_enhancer":-- break-- time.sleep(1)---- if original_process_status is not None:-- while True:-- with gen_lock:-- process_status = gen.get("process_status", None)-- if process_status == "process:prompt_enhancer": break-- if process_status is None:-- # handle case when main process has finished at some point in between the last check and now-- gen["process_status"] = "process:prompt_enhancer"-- break-- time.sleep(0.1)++ acquire_GPU_ressources(state, "prompt_enhancer", "Prompt Enhancer")if enhancer_offloadobj is None:profile = init_pipe(pipe, kwargs, override_profile)@@@ -4542,8 -4461,8 +4493,7 @@@enhanced_prompt = process_prompt_enhancer(prompt_enhancer, [one_prompt], start_images, original_image_refs, is_image, seed )except Exception as e:enhancer_offloadobj.unload_all()-- with gen_lock:-- gen["process_status"] = original_process_status++ release_GPU_ressources(state, "prompt_enhancer")raise gr.Error(e)if enhanced_prompt is not None:enhanced_prompt = enhanced_prompt[0].replace("\n", "").replace("\r", "")@@@ -4551,8 -4470,8 +4501,8 @@@enhanced_prompts.append(enhanced_prompt)enhancer_offloadobj.unload_all()-- with gen_lock:-- gen["process_status"] = original_process_status++++ release_GPU_ressources(state, "prompt_enhancer")prompt = '\n'.join(enhanced_prompts)if num_prompts > 1:@@@ -5484,19 -5395,20 +5434,19 @@@ def generate_videotime_flag = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d-%Hh%Mm%Ss")save_prompt = original_prompts[0]-- from shared.utils.utils import truncate_for_filesystem- extension = "jpg" if is_image else "mp4"-- if os.name == 'nt':- file_name = f"{time_flag}_seed{seed}_{sanitize_file_name(truncate_for_filesystem(save_prompt,50)).strip()}.{extension}"+ if is_image:+ extension = "jpg"else:- file_name = f"{time_flag}_seed{seed}_{sanitize_file_name(truncate_for_filesystem(save_prompt,100)).strip()}.{extension}"+ container = server_config.get("video_container", "mp4")+ extension = container+- if os.name == 'nt':- file_name = f"{time_flag}_seed{seed}_{sanitize_file_name(truncate_for_filesystem(save_prompt,50)).strip()}.{extension}"- else:- file_name = f"{time_flag}_seed{seed}_{sanitize_file_name(truncate_for_filesystem(save_prompt,100)).strip()}.{extension}"++ file_name = f"{time_flag}_seed{seed}_{sanitize_file_name(truncate_for_filesystem(save_prompt)).strip()}.{extension}"video_path = os.path.join(save_path, file_name)any_mmaudio = MMAudio_setting != 0 and server_config.get("mmaudio_enabled", 0) != 0 and sample.shape[1] >=fps-+ if BGRA_frames is not None:+ from models.wan.alpha.utils import write_zip_file+ write_zip_file(os.path.splitext(video_path)[0] + ".zip", BGRA_frames)+ BGRA_frames = Noneif is_image:image_path = os.path.join(image_save_path, file_name)sample = sample.transpose(1,0) #c f h w -> f c h w@@@ -5508,8 -5420,9 +5458,8 @@@video_path= new_image_pathelif len(control_audio_tracks) > 0 or len(source_audio_tracks) > 0 or output_new_audio_filepath is not None or any_mmaudio or output_new_audio_data is not None or audio_source is not None:video_path = os.path.join(save_path, file_name)- save_path_tmp = video_path[:-4] + "_tmp.mp4"- save_video( tensor=sample[None], save_file=save_path_tmp, fps=output_fps, nrow=1, normalize=True, value_range=(-1, 1), codec_type = server_config.get("video_output_codec", None))- container = server_config.get("video_container", "mp4")+ save_path_tmp = video_path.rsplit('.', 1)[0] + f"_tmp.{container}"- save_video( tensor=sample[None], save_file=save_path_tmp, fps=output_fps, nrow=1, normalize=True, value_range=(-1, 1), codec_type = server_config.get("video_output_codec", None), container=server_config.get("video_container", "mp4"))++ save_video( tensor=sample[None], save_file=save_path_tmp, fps=output_fps, nrow=1, normalize=True, value_range=(-1, 1), codec_type = server_config.get("video_output_codec", None), container=container)output_new_audio_temp_filepath = Nonenew_audio_from_start = reset_control_aligmentsource_audio_duration = source_video_frames_count / fps@@@ -5536,7 -5449,11 +5486,7 @@@if output_new_audio_temp_filepath is not None: os.remove(output_new_audio_temp_filepath)else:- save_video( tensor=sample[None], save_file=video_path, fps=output_fps, nrow=1, normalize=True, value_range=(-1, 1), codec_type= server_config.get("video_output_codec", None))- # Prepare source images for embedding if enabled- from shared.utils.source_image_embedding import prepare_source_images_dict- source_images = prepare_source_images_dict(server_config, image_start, image_end, image_refs)-- save_video( tensor=sample[None], save_file=video_path, fps=output_fps, nrow=1, normalize=True, value_range=(-1, 1), codec_type= server_config.get("video_output_codec", None), container=server_config.get("video_container", "mp4"), source_images=source_images)++ save_video( tensor=sample[None], save_file=video_path, fps=output_fps, nrow=1, normalize=True, value_range=(-1, 1), codec_type= server_config.get("video_output_codec", None), container= container)end_time = time.time()@@@ -5557,7 -5474,7 +5507,8 @@@inputs.update({"transformer_loras_filenames" : transformer_loras_filenames,"transformer_loras_multipliers" : transformer_loras_multipliers-- })++ })++ embedded_images = {img_name: inputs[img_name] for img_name in image_names_list } if server_config.get("embed_source_images", False) else Noneconfigs = prepare_inputs_dict("metadata", inputs, model_type)if sliding_window: configs["window_no"] = window_noconfigs["prompt"] = "\n".join(original_prompts)@@@ -5575,10 -5492,11 +5526,7 @@@if is_image:save_image_metadata(path, configs)else:- from mutagen.mp4 import MP4- file = MP4(path)- file.tags['©cmt'] = [json.dumps(configs)]- file.save()- from shared.utils.video_metadata import save_metadata_to_video- try:- save_metadata_to_video(path, configs)- except Exception as e:- print(f"Error adding metadata to MKV file {path}: {e}")++ save_video_metadata(path, configs, embedded_images)if is_image:print(f"New image saved to Path: "+ path)else:@@@ -5586,7 -5504,7 +5534,7 @@@with lock:file_list.append(path)file_settings_list.append(configs if no > 0 else configs.copy())--++ embedded_images = None# Play notification sound for single videotry:if server_config.get("notification_sound_enabled", 0):@@@ -5696,7 -5614,7 +5644,7 @@@ def process_tasks(state)if process_status is None or process_status == "process:main":gen["process_status"] = "process:main"break-- time.sleep(1)++ time.sleep(0.1)def release_gen():with gen_lock:@@@ -6648,6 -6525,16 +6596,21 @@@ def export_settings(state)return text_base64, sanitize_file_name(model_type + "_" + datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d-%Hh%Mm%Ss") + ".json")-def extract_and_apply_source_images(file_path, state):- """UI glue: get state, call module, set state. ALL logic is in source_image_embedding module."""- from shared.utils.source_image_embedding import extract_and_apply_to_settings- current_settings = get_model_settings(state, state["model_type"]) or {}- updated_settings, applied_count = extract_and_apply_to_settings(file_path, current_settings)- if applied_count > 0:- set_model_settings(state, state["model_type"], updated_settings)++def extract_and_apply_source_images(file_path, current_settings):++ from shared.utils.video_metadata import extract_source_images++ if not os.path.isfile(file_path): return 0++ extracted_files = extract_source_images(file_path)++ if not extracted_files: return 0++ applied_count = 0++ for name in image_names_list:++ if name in extracted_files:++ img = extracted_files[name]++ img = img if isinstance(img,list) else [img]++ applied_count += len(img)++ current_settings[name] = img+ return applied_count++def use_video_settings(state, input_file_list, choice):gen = get_gen_info(state)file_list, file_settings_list = get_file_list(state, input_file_list)@@@ -6666,13 -6553,23 +6629,20 @@@defaults = get_default_settings(model_type) if defaults == None else defaultsdefaults.update(configs)prompt = configs.get("prompt", "")-- # Extract and apply embedded source images from video files- extracted_images = extract_and_apply_source_images(file_name, state)--- set_model_settings(state, model_type, defaults)-- # Update info message to include source image extraction++if has_image_file_extension(file_name):++ set_model_settings(state, model_type, defaults)gr.Info(f"Settings Loaded from Image with prompt '{prompt[:100]}'")-- else:- gr.Info(f"Settings Loaded from Video with prompt '{prompt[:100]}'")++ elif has_video_file_extension(file_name):++ extracted_images = extract_and_apply_source_images(file_name, defaults)++ set_model_settings(state, model_type, defaults)+ info_msg = f"Settings Loaded from Video with prompt '{prompt[:100]}'"+ if extracted_images:- info_msg += f" + {extracted_images} source image(s) extracted"++ info_msg += f" + {extracted_images} source {'image' if extracted_images == 1 else 'images'} extracted"+ gr.Info(info_msg)+if models_compatible:- return gr.update(), gr.update(), str(time.time())+ return gr.update(), gr.update(), gr.update(), str(time.time())else:return *generate_dropdown_model_list(model_type), gr.update()else:@@@ -7171,6 -7015,6 +7148,21 @@@ def refresh_video_prompt_type_image_refimg_rel_size_visible = visible and model_def.get("any_image_refs_relative_size", False)return video_prompt_type, gr.update(visible = visible),gr.update(visible = rm_bg_visible), gr.update(visible = img_rel_size_visible), gr.update(visible = visible and "F" in video_prompt_type_image_refs), gr.update(visible= ("F" in video_prompt_type_image_refs or "K" in video_prompt_type_image_refs or "V" in video_prompt_type) and any_outpainting )++def update_image_mask_guide(state, image_mask_guide):++ img = image_mask_guide["background"]++ if img.mode != 'RGBA':++ return image_mask_guide++++ arr = np.array(img)++ rgb = Image.fromarray(arr[..., :3], 'RGB')++ alpha_gray = np.repeat(arr[..., 3:4], 3, axis=2)++ alpha_gray = 255 - alpha_gray++ alpha_rgb = Image.fromarray(alpha_gray, 'RGB')++++ image_mask_guide = {"background" : rgb, "composite" : None, "layers": [rgb_bw_to_rgba_mask(alpha_rgb)]}++++ return image_mask_guide++def switch_image_guide_editor(image_mode, old_video_prompt_type , video_prompt_type, old_image_mask_guide_value, old_image_guide_value, old_image_mask_value ):if image_mode == 0: return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)mask_in_old = "A" in old_video_prompt_type and not "U" in old_video_prompt_type@@@ -8488,15 -8319,15 +8480,17 @@@ def generate_video_tab(update_form = Fawith gr.Accordion("Video Info and Late Post Processing & Audio Remuxing", open=False) as video_info_accordion:with gr.Tabs() as video_info_tabs:++ default_visibility_false = {} if update_form else {"visible" : False}++ default_visibility_true = {} if update_form else {"visible" : True}++with gr.Tab("Information", id="video_info"):-- default_visibility = {} if update_form else {"visible" : False}video_info = gr.HTML(visible=True, min_height=100, value=get_default_video_info())-- with gr.Row(**default_visibility) as video_buttons_row:++ with gr.Row(**default_visibility_false) as video_buttons_row:video_info_extract_settings_btn = gr.Button("Extract Settings", min_width= 1, size ="sm")video_info_to_video_source_btn = gr.Button("To Video Source", min_width= 1, size ="sm", visible = any_video_source)video_info_to_control_video_btn = gr.Button("To Control Video", min_width= 1, size ="sm", visible = any_control_video )video_info_eject_video_btn = gr.Button("Eject Video", min_width= 1, size ="sm")-- with gr.Row(**default_visibility) as image_buttons_row:++ with gr.Row(**default_visibility_false) as image_buttons_row:video_info_extract_image_settings_btn = gr.Button("Extract Settings", min_width= 1, size ="sm")video_info_to_start_image_btn = gr.Button("To Start Image", size ="sm", min_width= 1, visible = any_start_image )video_info_to_end_image_btn = gr.Button("To End Image", size ="sm", min_width= 1, visible = any_end_image)@@@ -8512,20 -8343,20 +8506,21 @@@video_info_postprocessing_btn = gr.Button("Apply Postprocessing", size ="sm", visible=True)video_info_eject_video2_btn = gr.Button("Eject Video", size ="sm", visible=True)with gr.Tab("Audio Remuxing", id= "audio_remuxing", visible = True) as audio_remuxing_tab:++with gr.Group(elem_classes= "postprocess"):with gr.Column(visible = server_config.get("mmaudio_enabled", 0) != 0) as PP_MMAudio_col:with gr.Row():PP_MMAudio_setting = gr.Dropdown(choices=[("Add Custom Audio Sountrack", 0), ("Use MMAudio to generate a Soundtrack based on the Video", 1), ],-- value=0, visible=True, scale = 1, label="MMAudio", show_label= False, elem_classes= "postprocess",++ visible=True, scale = 1, label="MMAudio", show_label= False, elem_classes= "postprocess", **({} if update_form else {"value" : 0 }))-- with gr.Column(visible = False) as PP_MMAudio_row:++ with gr.Column(**default_visibility_false) as PP_MMAudio_row:with gr.Row():PP_MMAudio_prompt = gr.Text("", label="Prompt (1 or 2 keywords)", elem_classes= "postprocess")PP_MMAudio_neg_prompt = gr.Text("", label="Negative Prompt (1 or 2 keywords)", elem_classes= "postprocess")PP_MMAudio_seed = gr.Slider(-1, 999999999, value=-1, step=1, label="Seed (-1 for random)")PP_repeat_generation = gr.Slider(1, 25.0, value=1, step=1, label="Number of Sample Videos to Generate")-- with gr.Row(visible = True) as PP_custom_audio_row:++ with gr.Row(**default_visibility_true) as PP_custom_audio_row:PP_custom_audio = gr.Audio(label = "Soundtrack", type="filepath", show_download_button= True,)with gr.Row():video_info_remux_audio_btn = gr.Button("Remux Audio", size ="sm", visible=True)@@@ -8586,7 -8417,7 +8581,7 @@@apg_col, audio_prompt_type_sources, audio_prompt_type_remux, audio_prompt_type_remux_row,video_guide_outpainting_col,video_guide_outpainting_top, video_guide_outpainting_bottom, video_guide_outpainting_left, video_guide_outpainting_right,video_guide_outpainting_checkbox, video_guide_outpainting_row, show_advanced, video_info_to_control_video_btn, video_info_to_video_source_btn, sample_solver_row,-- video_buttons_row, image_buttons_row, video_postprocessing_tab, audio_remuxing_tab, PP_MMAudio_row, PP_custom_audio_row,++ video_buttons_row, image_buttons_row, video_postprocessing_tab, audio_remuxing_tab, PP_MMAudio_setting, PP_MMAudio_row, PP_custom_audio_row,video_info_to_start_image_btn, video_info_to_end_image_btn, video_info_to_reference_image_btn, video_info_to_image_guide_btn, video_info_to_image_mask_btn,NAG_col, remove_background_sound , speakers_locations_row, embedded_guidance_row, guidance_phases_row, guidance_row, resolution_group, cfg_free_guidance_col, control_net_weights_row, guide_selection_row, image_mode_tabs,min_frames_if_references_col, video_prompt_type_alignment, prompt_enhancer_btn, tab_inpaint, tab_t2v] + image_start_extra + image_end_extra + image_refs_extra # presets_column,@@@ -8617,7 -8448,7 +8612,7 @@@# video_prompt_type_video_guide_alt.input(fn=refresh_video_prompt_type_video_guide_alt, inputs = [state, video_prompt_type, video_prompt_type_video_guide_alt, image_mode, image_mask_guide, image_guide, image_mask], outputs = [video_prompt_type, video_guide, image_guide, image_refs_row, denoising_strength, video_mask, mask_expand, image_mask_guide, image_guide, image_mask, keep_frames_video_guide ], show_progress="hidden")video_prompt_type_video_custom_dropbox.input(fn= refresh_video_prompt_type_video_custom_dropbox, inputs=[state, video_prompt_type, video_prompt_type_video_custom_dropbox], outputs = video_prompt_type)video_prompt_type_video_custom_checkbox.input(fn= refresh_video_prompt_type_video_custom_checkbox, inputs=[state, video_prompt_type, video_prompt_type_video_custom_checkbox], outputs = video_prompt_type)--++ # image_mask_guide.upload(fn=update_image_mask_guide, inputs=[state, image_mask_guide], outputs=[image_mask_guide], show_progress="hidden")video_prompt_type_video_mask.input(fn=refresh_video_prompt_type_video_mask, inputs = [state, video_prompt_type, video_prompt_type_video_mask, image_mode, image_mask_guide, image_guide, image_mask], outputs = [video_prompt_type, video_mask, image_mask_guide, image_guide, image_mask, mask_expand], show_progress="hidden")video_prompt_type_alignment.input(fn=refresh_video_prompt_type_alignment, inputs = [state, video_prompt_type, video_prompt_type_alignment], outputs = [video_prompt_type])multi_prompts_gen_type.select(fn=refresh_prompt_labels, inputs=[multi_prompts_gen_type, image_mode], outputs=[prompt, wizard_prompt, image_end], show_progress="hidden")@@@ -9051,15 -8857,15 +9046,6 @@@ def generate_configuration_tab(state, b)-- metadata_choice = gr.Dropdown(-- choices=[-- ("Export JSON files", "json"),-- ("Embed metadata (Exif tag)", "metadata"),-- ("Neither", "none")-- ],-- value=server_config.get("metadata_type", "metadata"),-- label="Metadata Handling"-- )preload_model_policy_choice = gr.CheckboxGroup([("Preload Model while Launching the App","P"), ("Preload Model while Switching Model", "S"), ("Unload Model when Queue is Done", "U")],value=server_config.get("preload_model_policy",[]),label="RAM Loading / Unloading Model Policy (in any case VRAM will be freed once the queue has been processed)"@@@ -9279,6 -9089,6 +9265,23 @@@label="Audio Codec to use")++++ metadata_choice = gr.Dropdown(++ choices=[++ ("Export JSON files", "json"),++ ("Embed metadata (Exif tag)", "metadata"),++ ("Neither", "none")++ ],++ value=server_config.get("metadata_type", "metadata"),++ label="Metadata Handling"++ )++++ embed_source_images_choice = gr.Checkbox(++ value=server_config.get("embed_source_images", False),++ label="Embed Source Images",++ info="Saves i2v source images inside MP4 files"++ )++video_save_path_choice = gr.Textbox(label="Output Folder for Generated Videos (need to restart app to be taken into account)",value=server_config.get("save_path", save_path)@@@ -9573,36 -9268,9 +9577,36 @@@ def change_model_family(state, current_last_model_per_family = state.get("last_model_per_family", {})model_type = last_model_per_family.get(current_model_family, "")if len(model_type) == "" or model_type not in [choice[1] for choice in dropdown_choices] : model_type = dropdown_choices[0][1]- return gr.Dropdown(choices= dropdown_choices, value = model_type )-def set_new_tab(tab_state, new_tab_no):+ if three_levels_hierarchy:+ parent_model_type = get_parent_model_type(model_type)+ dropdown_choices = [ (*tup, get_parent_model_type(tup[1])) for tup in dropdown_choices]+ dropdown_base_types_choices, finetunes_dict = create_models_hierarchy(dropdown_choices)+ dropdown_choices = finetunes_dict[parent_model_type ]+ model_finetunes_visible = len(dropdown_choices) > 1+ else:+ parent_model_type = get_base_model_type(model_type)+ model_finetunes_visible = True+ dropdown_base_types_choices = list({get_base_model_type(model[1]) for model in dropdown_choices})++ return gr.Dropdown(choices= dropdown_base_types_choices, value = parent_model_type, scale=3 if model_finetunes_visible else 7), gr.Dropdown(choices= dropdown_choices, value = model_type, visible = model_finetunes_visible )++def change_model_base_types(state, current_model_family, model_base_type_choice):+ if not three_levels_hierarchy: return gr.update()+ dropdown_types= transformer_types if len(transformer_types) > 0 else displayed_model_types+ current_family_name = families_infos[current_model_family][1]+ dropdown_choices = [ (compact_name(current_family_name, get_model_name(model_type)), model_type, model_base_type_choice) for model_type in dropdown_types if get_parent_model_type(model_type) == model_base_type_choice and get_model_family(model_type, for_ui= True) == current_model_family]+ dropdown_choices = sorted(dropdown_choices, key=lambda c: c[0])+ _, finetunes_dict = create_models_hierarchy(dropdown_choices)+ dropdown_choices = finetunes_dict[model_base_type_choice ]+ model_finetunes_visible = len(dropdown_choices) > 1+ last_model_per_type = state.get("last_model_per_type", {})+ model_type = last_model_per_type.get(model_base_type_choice, "")+ if len(model_type) == "" or model_type not in [choice[1] for choice in dropdown_choices] : model_type = dropdown_choices[0][1]++ return gr.update(scale=3 if model_finetunes_visible else 7), gr.Dropdown(choices= dropdown_choices, value = model_type, visible=model_finetunes_visible )+- def set_new_tab(tab_state, new_tab_no):++def set_new_tab(tab_state, state, new_tab_no):global vmc_event_handlertab_video_mask_creator = 2@@@ -9610,26 -9278,26 +9614,21 @@@old_tab_no = tab_state.get("tab_no",0)# print(f"old tab {old_tab_no}, new tab {new_tab_no}")if old_tab_no == tab_video_mask_creator:-- vmc_event_handler(False)++ vmc_event_handler(state, False)elif new_tab_no == tab_video_mask_creator:-- if gen_in_progress:-- gr.Info("Unable to access this Tab while a Generation is in Progress. Please come back later")-- tab_state["tab_no"] = 0-- return gr.Tabs(selected="video_gen")-- else:-- if not download_shared_done:-- download_models()-- vmc_event_handler(True)++ if not download_shared_done:++ download_models()++ vmc_event_handler(state, True)tab_state["tab_no"] = new_tab_noreturn gr.Tabs()--def select_tab(tab_state, evt:gr.SelectData):++def select_tab(tab_state, state, evt:gr.SelectData):old_tab_no = tab_state.get("tab_no",0)if old_tab_no == 0:saveform_trigger = get_unique_id()else:saveform_trigger = gr.update()-- return set_new_tab(tab_state, evt.index), saveform_trigger++ return set_new_tab(tab_state, state, evt.index), saveform_triggerdef get_js():start_quit_timer_js = """@@@ -10166,7 -9803,7 +10165,7 @@@ def create_ui()generate_about_tab()if stats_app is not None:stats_app.setup_events(main, state)-- main_tabs.select(fn=select_tab, inputs= [tab_state], outputs= [main_tabs, save_form_trigger], trigger_mode="multiple")++ main_tabs.select(fn=select_tab, inputs= [tab_state, state], outputs= [main_tabs, save_form_trigger], trigger_mode="multiple")return mainif __name__ == "__main__":