Skip to content
Python

Merge branch 'plugins' into v9

Chris Malone098e7396d671
diff --cc plugins/wan2gp-lora-multipliers-ui/plugin.py
index 0000000,157424c..5f3a77d
mode 000000,100644..100644
--- a/plugins/wan2gp-lora-multipliers-ui/plugin.py
+++ b/plugins/wan2gp-lora-multipliers-ui/plugin.py
@@@ -1,0 -1,299 +1,304 @@@
+ import gradio as gr
+ from shared.utils.plugins import WAN2GPPlugin
+
+ class LoraMultipliersUIPlugin(WAN2GPPlugin):
+ def __init__(self):
+ super().__init__()
+ self.name = "Lora Multipliers UI"
+ self.version = "1.0.0"
+ self.description = "Dynamically set lora multipliers with slider bars instead of text"
+ self.request_component("loras_multipliers")
+ self.request_component("loras_choices")
+ self.request_component("guidance_phases")
+ self.request_component("num_inference_steps")
+ self.request_component("main")
+
+ def post_ui_setup(self, components: dict) -> dict:
+ loras_multipliers = self.loras_multipliers
+ loras_choices = self.loras_choices
+ guidance_phases = self.guidance_phases
+ num_inference_steps = self.num_inference_steps
+ main_ui_block = self.main
+
+ def create_and_wire_ui():
+ MAX_LORA_SLIDERS = 15
+ MAX_STEP_SPLITS = 5
+
+ css = """
+ <style>
+ #lora_builder_main_group {
+ font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', sans-serif;
+ }
+ .lora-main-container {
+ border: 1px solid var(--border-color-primary);
+ border-radius: 8px;
+ padding: 12px;
+ margin-bottom: 0px !important;
+ background-color: var(--background-fill-secondary);
+ }
+ .lora-main-container > .gr-row {
+ margin-bottom: 8px;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .lora-step-split-container {
+ border: 1px dashed var(--border-color-accent);
+ border-radius: 6px;
+ padding: 10px;
+ margin-top: 8px;
+ }
+ .lora-main-container button {
+ padding: 4px 12px !important;
+ font-size: 1.2em !important;
+ min-width: fit-content !important;
+ flex-grow: 0;
+ background: var(--button-secondary-background-fill);
+ color: var(--button-secondary-text-color);
+ border: 1px solid var(--button-secondary-border-color);
+ }
+ .lora-main-container button:hover {
+ background: var(--button-secondary-background-fill-hover);
+ border-color: var(--button-secondary-border-color-hover);
+ }
+ .lora-step-split-container > .gr-row {
+ gap: 16px;
+ align-items: end;
+ }
+ .lora-step-split-container .form {
+ flex-grow: 1;
+ }
+ .lora-section-header h3 {
+ border-bottom: 1px solid var(--border-color-primary);
+ padding-bottom: 4px;
+ margin-top: 16px;
+ margin-bottom: 0px;
+ }
+ #lora_builder_main_group > div:first-child > h3 {
+ margin-top: 0;
+ }
+ </style>
+ """
+
+ def _build_multipliers_string(num_selected_loras, guidance_phases_val, split_counts, all_slider_values_flat, separator_index=-1):
+ textbox_strings = []
+ slider_cursor = 0
+ for i in range(MAX_LORA_SLIDERS):
+ if i < num_selected_loras:
+ num_splits_for_this_lora = split_counts[i]
+ lora_step_strings = []
+ for j in range(MAX_STEP_SPLITS):
+ phase_values_for_textbox = []
+ if j < num_splits_for_this_lora:
+ for k in range(3):
+ is_visible = (k + 1) <= guidance_phases_val
+ if is_visible:
+ phase_value = all_slider_values_flat[slider_cursor + k]
+ formatted_value = str(int(phase_value)) if phase_value == int(phase_value) else f"{phase_value:.2f}".rstrip('0').rstrip('.')
+ phase_values_for_textbox.append(formatted_value)
+
+ if phase_values_for_textbox:
+ lora_step_strings.append(";".join(phase_values_for_textbox))
+ slider_cursor += 3
+
+ if lora_step_strings:
+ textbox_strings.append(",".join(lora_step_strings))
+ else:
+ slider_cursor += MAX_STEP_SPLITS * 3
+
+ if not textbox_strings:
+ return ""
+
+ if separator_index != -1 and num_selected_loras < separator_index:
+ separator_index = -1
+
+ if separator_index > 0 and separator_index <= len(textbox_strings):
+ part1 = " ".join(textbox_strings[:separator_index])
+ part2 = " ".join(textbox_strings[separator_index:])
+ if part2:
+ return f"{part1}|{part2}"
+ else:
+ return f"{part1}|"
+ else:
+ return " ".join(textbox_strings)
+
- def update_slider_ui_and_textbox(selected_lora_indices, guidance_phases_val, current_multipliers_str, total_steps, current_split_counts, triggered_lora_index=-1):
- if triggered_lora_index != -1:
- if current_split_counts[triggered_lora_index] < MAX_STEP_SPLITS:
- current_split_counts[triggered_lora_index] += 1
- elif triggered_lora_index == -1:
- current_split_counts = [1] * MAX_LORA_SLIDERS
-
- separator_index = -1
++ def update_slider_ui_and_textbox(selected_lora_indices, guidance_phases_val, current_multipliers_str, total_steps, current_split_counts_state, triggered_lora_index=-1):
+ multipliers_per_lora = []
++ separator_index = -1
+ if current_multipliers_str:
+ if '|' in current_multipliers_str:
+ parts = current_multipliers_str.split('|')
+ loras_before_sep = [s for s in parts[0].split(' ') if s]
+ separator_index = len(loras_before_sep)
+ multipliers_per_lora = [s for s in current_multipliers_str.replace('|', ' ').split(' ') if s]
+
++ new_split_counts = [1] * MAX_LORA_SLIDERS
++ for i in range(len(multipliers_per_lora)):
++ if i < MAX_LORA_SLIDERS:
++ num_splits = len(multipliers_per_lora[i].split(','))
++ new_split_counts[i] = max(1, num_splits)
++
++ if triggered_lora_index != -1:
++ if new_split_counts[triggered_lora_index] < MAX_STEP_SPLITS:
++ new_split_counts[triggered_lora_index] += 1
++
++ current_split_counts = new_split_counts
+ ui_updates = []
+ all_slider_values_flat = []
+ num_selected_loras = len(selected_lora_indices)
+ has_separator = separator_index != -1
+ show_accelerator_header = has_separator and separator_index > 0
+ ui_updates.append(gr.update(visible=show_accelerator_header and num_selected_loras > 0))
+
+ for i in range(MAX_LORA_SLIDERS):
+ is_first_user_lora = (i == 0 and not show_accelerator_header) or (i == separator_index)
+ show_user_header_here = is_first_user_lora and num_selected_loras > i
+ ui_updates.append(gr.update(visible=show_user_header_here))
+
+ is_lora_visible = i < len(selected_lora_indices)
+ ui_updates.append(gr.update(visible=is_lora_visible))
+
+ if is_lora_visible:
+ lora_name = selected_lora_indices[i]
+ ui_updates.append(gr.update(value=f"### {lora_name}"))
+
+ num_splits_for_this_lora = current_split_counts[i]
+ steps_and_phases_str = multipliers_per_lora[i] if i < len(multipliers_per_lora) else ""
+ multipliers_per_step = steps_and_phases_str.split(',')
+
+ steps_per_split_base = total_steps
+ remainder = total_steps % num_splits_for_this_lora
+ start_step = 0
+
+ for j in range(MAX_STEP_SPLITS):
+ is_split_visible = j < num_splits_for_this_lora
+ ui_updates.append(gr.update(visible=is_split_visible))
+
+ if is_split_visible:
+ steps_in_this_split = steps_per_split_base + (1 if j < remainder else 0)
+ end_step = start_step + steps_in_this_split
+ step_title = f"**Steps {start_step + 1} to {end_step}**"
+ start_step = end_step
+ ui_updates.append(gr.update(value=step_title))
+
+ multipliers_per_phase = multipliers_per_step[j].split(';') if j < len(multipliers_per_step) else ['1.0'] * 3
+
+ for k in range(3):
+ try: phase_value = float(multipliers_per_phase[k])
+ except (ValueError, IndexError): phase_value = 1.0
+
+ is_slider_visible = (k + 1) <= guidance_phases_val
+ ui_updates.append(gr.update(visible=is_slider_visible, value=phase_value))
+ all_slider_values_flat.append(phase_value)
+ else:
+ ui_updates.extend([gr.update(value=""), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)])
+ all_slider_values_flat.extend([1.0] * 3)
+ else:
+ ui_updates.append(gr.update(value=""))
+ for _ in range(MAX_STEP_SPLITS):
+ ui_updates.extend([gr.update(visible=False), gr.update(value=""), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)])
- all_slider_values_flat.extend([1.0] * 3)
++ all_slider_values_flat.extend([1.0] * 3 * MAX_STEP_SPLITS)
+
+ effective_separator_index = separator_index
+ if effective_separator_index != -1 and len(selected_lora_indices) < effective_separator_index:
+ effective_separator_index = -1
+
+ new_textbox_value = _build_multipliers_string(len(selected_lora_indices), guidance_phases_val, current_split_counts, all_slider_values_flat, effective_separator_index)
+
+ return [effective_separator_index, current_split_counts, gr.update(value=new_textbox_value)] + ui_updates
+
+ def update_textbox_from_sliders(selected_loras, guidance_phases_val, split_counts, separator_index, *all_slider_values_flat):
+ effective_separator_index = separator_index
+ if effective_separator_index != -1 and len(selected_loras) < effective_separator_index:
+ effective_separator_index = -1
+ new_textbox_value = _build_multipliers_string(len(selected_loras), guidance_phases_val, split_counts, all_slider_values_flat, effective_separator_index)
+ return gr.update(value=new_textbox_value)
+
+ with gr.Accordion("Dynamic Lora Multipliers Adjustments", open=True) as main_accordion:
+ gr.HTML(value=css)
+ lora_separator_index = gr.State(-1)
+ lora_split_counts = gr.State([1] * MAX_LORA_SLIDERS)
+ lora_slider_ui_groups = []
+
+ update_mults_btn = gr.Button(visible=False, elem_id="lora_mults_update_btn")
+
+ with gr.Group(elem_id="lora_builder_main_group"):
+ accelerator_loras_header = gr.Markdown("<h3>Accelerator LoRAs</h3>", visible=False, elem_classes="lora-section-header")
+ for i in range(MAX_LORA_SLIDERS):
+ user_loras_header = gr.Markdown("<h3>User LoRAs</h3>", visible=False, elem_classes="lora-section-header")
+ with gr.Column(visible=False, elem_classes="lora-main-container") as lora_main_group:
+ with gr.Row(variant="compact"):
+ lora_name_md = gr.Markdown()
+ split_steps_btn = gr.Button("Split Steps")
+
+ split_groups = []
+ for j in range(MAX_STEP_SPLITS):
+ with gr.Column(visible=False, elem_classes="lora-step-split-container") as lora_step_group:
+ step_range_md = gr.Markdown()
+ with gr.Row():
+ phase1_slider = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="Phase 1", interactive=True)
+ phase2_slider = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="Phase 2", interactive=True, visible=False)
+ phase3_slider = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="Phase 3", interactive=True, visible=False)
+ split_groups.append({ "group": lora_step_group, "title": step_range_md, "sliders": [phase1_slider, phase2_slider, phase3_slider] })
+
+ lora_slider_ui_groups.append({
+ "main_group": lora_main_group,
+ "name": lora_name_md,
+ "split_button": split_steps_btn,
+ "splits": split_groups,
+ "user_header": user_loras_header
+ })
+
+ slider_ui_outputs = []
+ all_sliders_flat = []
+ slider_ui_outputs.append(accelerator_loras_header)
+ for group in lora_slider_ui_groups:
+ slider_ui_outputs.append(group["user_header"])
+ slider_ui_outputs.extend([group["main_group"], group["name"]])
+ for split in group["splits"]:
+ slider_ui_outputs.extend([split["group"], split["title"], *split["sliders"]])
+ all_sliders_flat.extend(split["sliders"])
-
- events_to_trigger_ui_update = [loras_choices.change, guidance_phases.change, num_inference_steps.change]
++
++ events_to_trigger_ui_update = [loras_choices.change, guidance_phases.change, num_inference_steps.change, loras_multipliers.change]
+ for event in events_to_trigger_ui_update:
+ event(
+ fn=update_slider_ui_and_textbox,
+ inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts],
+ outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs,
+ show_progress="hidden"
+ )
+
+ for i, group in enumerate(lora_slider_ui_groups):
+ group["split_button"].click(
+ fn=update_slider_ui_and_textbox,
+ inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts, gr.State(i)],
+ outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs,
+ show_progress="hidden"
+ )
+
+ update_mults_btn.click(
+ fn=update_textbox_from_sliders,
+ inputs=[loras_choices, guidance_phases, lora_split_counts, lora_separator_index] + all_sliders_flat,
+ outputs=[loras_multipliers],
+ show_progress="hidden"
+ )
+
+ for slider in all_sliders_flat:
+ slider.release(fn=None, js="() => { document.getElementById('lora_mults_update_btn').click() }")
+
+ main_ui_block.load(
+ fn=update_slider_ui_and_textbox,
+ inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts],
+ outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs,
+ show_progress="hidden"
+ )
+
+ return main_accordion
+
+ self.insert_after(
+ target_component_id="loras_multipliers",
+ new_component_constructor=create_and_wire_ui
+ )
+
+ return {
+ loras_multipliers: gr.update(elem_id="loras_multipliers_textbox", interactive=True)
+ }
diff --cc plugins/wan2gp-video-mask-creator/plugin.py
index 0000000,d3f37ff..423f0e8
mode 000000,100644..100644
--- a/plugins/wan2gp-video-mask-creator/plugin.py
+++ b/plugins/wan2gp-video-mask-creator/plugin.py
@@@ -1,0 -1,43 +1,64 @@@
++# plugins/wan2gp-video-mask-creator/plugin.py
++
+ import gradio as gr
+ from shared.utils.plugins import WAN2GPPlugin
-import os
-import json
-import traceback
++from preprocessing.matanyone import app as matanyone_app
+
+ class VideoMaskCreatorPlugin(WAN2GPPlugin):
+ def __init__(self):
+ super().__init__()
+ self.name = "Video Mask Creator"
- self.version = "1.0.0"
- self.description = "Create masks for your videos with Matanyone"
++ self.version = "1.2.0"
++ self.description = "Create masks for your videos with Matanyone. Now fully integrated with the plugin system."
++ self._is_active = False
++
++ self.matanyone_app = matanyone_app
++ self.vmc_event_handler = self.matanyone_app.get_vmc_event_handler()
++ self.mat_components = {}
+
+ def setup_ui(self):
- self.request_global("vmc_event_handler")
- self.request_global("gen_in_progress")
+ self.request_global("download_shared_done")
+ self.request_global("download_models")
+ self.request_global("server_config")
+ self.request_global("get_current_model_settings")
- self.request_global("matanyone_app")
++
+ self.request_component("main_tabs")
- self.request_component("tab_state")
+ self.request_component("state")
+ self.request_component("refresh_form_trigger")
- self.request_component("save_form_trigger")
++
++ self.add_tab(
++ tab_id="video_mask_creator",
++ label="Video Mask Creator",
++ component_constructor=self.create_mask_creator_ui,
++ position=2
++ )
+
+ def create_mask_creator_ui(self):
- pass
++ """Phase 1: Create UI components and store them."""
++ self.mat_components = self.matanyone_app.create_ui_components()
+
+ def post_ui_setup(self, components: dict):
- with self.main_tabs:
- with gr.Tab("Video Mask Creator", id="video_mask_creator"):
- self.matanyone_app.display(
- self.main_tabs,
- self.tab_state,
- self.state,
- self.refresh_form_trigger,
- self.server_config,
- self.get_current_model_settings
- )
++ """Phase 2: Bind all events after the entire UI is constructed."""
++ self.matanyone_app.bind_events(
++ self.mat_components,
++ self.main_tabs,
++ None,
++ self.state,
++ self.refresh_form_trigger,
++ self.server_config,
++ self.get_current_model_settings
++ )
++
++ def on_tab_select(self, state: dict) -> None:
++ print("[VideoMaskCreatorPlugin] Tab selected. Loading models...")
++ if not self.download_shared_done:
++ self.download_models()
++ self.vmc_event_handler(state, True)
++ self._is_active = True
+
- return {}
++ def on_tab_deselect(self, state: dict) -> None:
++ if not self._is_active:
++ return
++ print("[VideoMaskCreatorPlugin] Tab deselected. Unloading models...")
++ self.vmc_event_handler(state, False)
++ self._is_active = False
diff --cc preprocessing/matanyone/app.py
index 2c6a38b,443934c..a85b15e
--- a/preprocessing/matanyone/app.py
+++ b/preprocessing/matanyone/app.py
@@@ -897,470 -750,443 +897,235 @@@ def export_to_current_video_engine(stat
return 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")
++get_current_model_settings = None
++video_output_codec = "libx264_8"
++image_output_codec = "jpeg_95"
--def display(tabs, tab_state, state, refresh_form_trigger, server_config, get_current_model_settings_fn): #, vace_video_input, vace_image_input, vace_video_mask, vace_image_mask, vace_image_refs):
-- # my_tab.select(fn=load_unload_models, inputs=[], outputs=[])
-- global image_output_codec, video_output_codec, get_current_model_settings
-- get_current_model_settings = get_current_model_settings_fn
--
-- image_output_codec = server_config.get("image_output_codec", None)
-- video_output_codec = server_config.get("video_output_codec", None)
--
-- media_url = "https://github.com/pq-yang/MatAnyone/releases/download/media/"
--
-- click_brush_js = """
-- () => {
-- setTimeout(() => {
-- const brushButton = document.querySelector('button[aria-label="Brush"]');
-- if (brushButton) {
-- brushButton.click();
-- console.log('Brush button clicked');
-- } else {
-- console.log('Brush button not found');
-- }
-- }, 1000);
-- } """
--
-- # download assets
--
- gr.Markdown("<B>Mast Edition is provided by MatAnyone, VRAM optimizations & Extended Masks by DeepBeepMeep</B>")
- gr.Markdown("<B>Mast Edition is provided by MatAnyone and VRAM optimized by DeepBeepMeep</B>")
++def create_ui_components():
++ """
++ Phase 1: Create UI components and return them in a dictionary.
++ This function should have NO external dependencies from the main app.
++ """
++ gr.Markdown("<B>Mask 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.")
gr.Markdown("The Mask Generation time and the VRAM consumed are proportional to the number of frames and the resolution. So if relevant, you may reduce the number of frames in the Matanyone Settings. You will need for the moment to resize yourself the video if needed.")
-- with gr.Column( visible=True):
++ with gr.Column(visible=True) as main_column:
with gr.Row():
-- with gr.Accordion("Video Tutorial (click to expand)", open=False, elem_classes="custom-bg"):
++ with gr.Accordion("Video Tutorial (click to expand)", open=False, elem_classes="custom-bg") as video_tutorial_accordion:
with gr.Row():
with gr.Column():
gr.Markdown("### Case 1: Single Target")
gr.Video(value="preprocessing/matanyone/tutorial_single_target.mp4", elem_classes="video")
--
with gr.Column():
gr.Markdown("### Case 2: Multiple Targets")
gr.Video(value="preprocessing/matanyone/tutorial_multi_targets.mp4", elem_classes="video")
-
-
-
--
- with gr.Tabs():
+ 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.Tabs() as main_media_tabs:
with gr.TabItem("Video"):
--
-- click_state = gr.State([[],[]])
--
-- interactive_state = gr.State({
-- "inference_times": 0,
-- "negative_click_times" : 0,
-- "positive_click_times": 0,
-- "mask_save": arg_mask_save,
-- "multi_mask": {
-- "mask_names": [],
-- "masks": []
-- },
-- "track_end_number": None,
-- }
-- )
--
-- video_state = gr.State(
-- {
-- "user_name": "",
-- "video_name": "",
-- "origin_images": None,
-- "painted_images": None,
-- "masks": None,
-- "inpaint_masks": None,
-- "logits": None,
-- "select_frame_number": 0,
-- "fps": 16,
-- "audio": "",
-- }
-- )
--
-- with gr.Column( visible=True):
++ click_state_video = gr.State([[],[]])
++ interactive_state_video = gr.State({
++ "inference_times": 0, "negative_click_times" : 0, "positive_click_times": 0, "mask_save": arg_mask_save,
++ "multi_mask": { "mask_names": [], "masks": [] }, "track_end_number": None,
++ })
++ video_state = gr.State({
++ "user_name": "", "video_name": "", "origin_images": None, "painted_images": None, "masks": None, "inpaint_masks": None,
++ "logits": None, "select_frame_number": 0, "fps": 16, "audio": "",
++ })
++ with gr.Column(visible=True) as video_column:
with gr.Row():
-- with gr.Accordion('MatAnyone Settings (click to expand)', open=False):
++ with gr.Accordion('MatAnyone Settings (click to expand)', open=False) as video_settings_accordion:
with gr.Row():
-- erode_kernel_size = gr.Slider(label='Erode Kernel Size',
-- minimum=0,
-- maximum=30,
-- step=1,
-- value=10,
-- info="Erosion on the added mask",
-- interactive=True)
-- dilate_kernel_size = gr.Slider(label='Dilate Kernel Size',
-- minimum=0,
-- maximum=30,
-- step=1,
-- value=10,
-- info="Dilation on the added mask",
-- interactive=True)
--
++ erode_kernel_size_video = gr.Slider(label='Erode Kernel Size', minimum=0, maximum=30, step=1, value=10, info="Erosion on the added mask", interactive=True)
++ dilate_kernel_size_video = gr.Slider(label='Dilate Kernel Size', minimum=0, maximum=30, step=1, value=10, info="Dilation on the added mask", interactive=True)
with gr.Row():
-- image_selection_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Start Frame", info="Choose the start frame for target assignment and video matting", visible=False)
-- end_selection_slider = gr.Slider(minimum=1, maximum=300, step=1, value=81, label="Last Frame to Process", info="Last Frame to Process", visible=False)
--
-- track_pause_number_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="End frame", visible=False)
++ image_selection_slider_video = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Start Frame", info="Choose the start frame for target assignment and video matting", visible=False)
++ end_selection_slider_video = gr.Slider(minimum=1, maximum=300, step=1, value=81, label="Last Frame to Process", info="Last Frame to Process", visible=False)
++ track_pause_number_slider_video = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="End frame", visible=False)
with gr.Row():
-- point_prompt = gr.Radio(
-- choices=["Positive", "Negative"],
-- value="Positive",
-- label="Point Prompt",
-- info="Click to add positive or negative point for target mask",
-- 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, allow_custom_value=True)
- 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)
--
-- # input video
++ point_prompt_video = gr.Radio(choices=["Positive", "Negative"], value="Positive", label="Point Prompt", info="Click to add positive or negative point for target mask", interactive=True, visible=False, min_width=100, scale=1)
++ mask_dropdown_video = 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)
with gr.Row(equal_height=True):
with gr.Column(scale=2):
gr.Markdown("## Step1: Upload video")
with gr.Column(scale=2):
-- step2_title = gr.Markdown("## Step2: Add masks <small>(Several clicks then **`Add Mask`** <u>one by one</u>)</small>", visible=False)
++ step2_title_video = gr.Markdown("## Step2: Add masks <small>(Several clicks then **`Add Mask`** <u>one by one</u>)</small>", visible=False)
with gr.Row(equal_height=True):
with gr.Column(scale=2):
video_input = gr.Video(label="Input Video", elem_classes="video")
-- extract_frames_button = gr.Button(value="Load Video", interactive=True, elem_classes="new_button")
++ extract_frames_button_video = gr.Button(value="Load Video", interactive=True, elem_classes="new_button")
with gr.Column(scale=2):
video_info = gr.Textbox(label="Video Info", visible=False)
-- template_frame = gr.Image(label="Start Frame", type="pil",interactive=True, elem_id="template_frame", visible=False, elem_classes="image")
++ template_frame_video = gr.Image(label="Start Frame", type="pil",interactive=True, elem_id="template_frame_video", visible=False, elem_classes="image")
with gr.Row():
-- clear_button_click = gr.Button(value="Clear Clicks", interactive=True, visible=False, min_width=100)
-- add_mask_button = gr.Button(value="Add Mask", interactive=True, visible=False, min_width=100)
-- remove_mask_button = gr.Button(value="Remove Mask", interactive=True, visible=False, min_width=100) # no use
-- matting_button = gr.Button(value="Generate Video Matting", interactive=True, visible=False, min_width=100)
-- with gr.Row():
-- gr.Markdown("")
--
-- # output video
-- with gr.Column() as output_row: #equal_height=True
++ clear_button_click_video = gr.Button(value="Clear Clicks", interactive=True, visible=False, min_width=100)
++ add_mask_button_video = gr.Button(value="Add Mask", interactive=True, visible=False, min_width=100)
++ remove_mask_button_video = gr.Button(value="Remove Mask", interactive=True, visible=False, min_width=100)
++ matting_button_video = gr.Button(value="Generate Video Matting", interactive=True, visible=False, min_width=100)
++ with gr.Row(): gr.Markdown("")
++ with gr.Column() as output_row_video:
with gr.Row():
with gr.Column(scale=2):
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")
- export_image_mask_btn = gr.Button(value="Alpha Mask Output", visible=False, elem_classes="new_button")
+ 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):
-- export_to_vace_video_14B_btn = gr.Button("Export to current Video Input Video For Inpainting", visible= False)
-- with gr.Row(visible= True):
-- 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, state], outputs= [tabs])
- fn=teleport_to_video_tab, inputs= [tab_state], outputs= [tabs])
--
--
-- # first step: get the video information
-- extract_frames_button.click(
-- fn=get_frames_from_video,
-- inputs=[
- state, video_input, video_state, new_dim
- video_input, video_state
-- ],
- 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,
- 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,
-- foreground_video_output, alpha_video_output, foreground_output_button, export_image_mask_btn, mask_dropdown, step2_title]
-- )
--
-- # second step: select images from slider
-- image_selection_slider.release(fn=select_video_template,
-- inputs=[image_selection_slider, video_state, interactive_state],
-- outputs=[template_frame, video_state, interactive_state], api_name="select_image")
-- track_pause_number_slider.release(fn=get_end_number,
-- inputs=[track_pause_number_slider, video_state, interactive_state],
-- outputs=[template_frame, interactive_state], api_name="end_image")
--
-- # click select image to get mask using sam
-- template_frame.select(
-- fn=sam_refine,
- inputs=[state, video_state, point_prompt, click_state, interactive_state],
- inputs=[video_state, point_prompt, click_state, interactive_state],
-- outputs=[template_frame, video_state, interactive_state]
-- )
--
-- # add different mask
-- add_mask_button.click(
-- fn=add_multi_mask,
-- inputs=[video_state, interactive_state, mask_dropdown],
-- outputs=[interactive_state, mask_dropdown, template_frame, click_state]
-- )
--
-- remove_mask_button.click(
-- fn=remove_multi_mask,
-- inputs=[interactive_state, mask_dropdown],
-- outputs=[interactive_state, mask_dropdown]
-- )
--
-- # video matting
-- matting_button.click(
-- fn=show_outputs,
-- inputs=[],
-- outputs=[foreground_video_output, alpha_video_output]).then(
-- fn=video_matting,
- 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],
- inputs=[video_state, video_input, end_selection_slider, matting_type, 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]
-- )
--
-- # click to get mask
-- mask_dropdown.change(
-- fn=show_mask,
-- inputs=[video_state, interactive_state, mask_dropdown],
-- outputs=[template_frame]
-- )
--
-- # clear input
-- video_input.change(
-- fn=restart,
-- inputs=[],
-- outputs=[
-- video_state,
-- interactive_state,
- click_state,
- extract_frames_button, dummy,
- foreground_video_output, dummy, alpha_video_output,
- click_state,
- foreground_video_output, 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, dummy, 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, matting_type, 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,
-- show_progress=False)
--
-- video_input.clear(
-- fn=restart,
-- inputs=[],
-- outputs=[
-- video_state,
-- interactive_state,
-- click_state,
- extract_frames_button, dummy,
- foreground_video_output, dummy, alpha_video_output,
- foreground_video_output, 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, dummy, 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, matting_type, 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,
-- show_progress=False)
--
-- # points clear
-- clear_button_click.click(
-- fn = clear_click,
-- inputs = [video_state, click_state,],
-- outputs = [template_frame,click_state],
-- )
--
--
++ export_to_current_video_engine_btn = gr.Button("Export to Control Video Input and Video Mask Input", visible=False)
with gr.TabItem("Image"):
-- click_state = gr.State([[],[]])
--
-- interactive_state = gr.State({
-- "inference_times": 0,
-- "negative_click_times" : 0,
-- "positive_click_times": 0,
-- "mask_save": False,
-- "multi_mask": {
-- "mask_names": [],
-- "masks": []
-- },
-- "track_end_number": None,
-- }
-- )
--
-- image_state = gr.State(
-- {
-- "user_name": "",
-- "image_name": "",
-- "origin_images": None,
-- "painted_images": None,
-- "masks": None,
-- "inpaint_masks": None,
-- "logits": None,
-- "select_frame_number": 0,
-- "fps": 30
-- }
-- )
--
-- with gr.Group(elem_classes="gr-monochrome-group", visible=True):
++ click_state_image = gr.State([[],[]])
++ interactive_state_image = gr.State({
++ "inference_times": 0, "negative_click_times" : 0, "positive_click_times": 0, "mask_save": arg_mask_save,
++ "multi_mask": { "mask_names": [], "masks": [] }, "track_end_number": None,
++ })
++ image_state = gr.State({
++ "user_name": "", "image_name": "", "origin_images": None, "painted_images": None, "masks": None, "inpaint_masks": None,
++ "logits": None, "select_frame_number": 0, "fps": 30
++ })
++ with gr.Group(elem_classes="gr-monochrome-group", visible=True) as image_settings_group:
with gr.Row():
-- with gr.Accordion('MatAnyone Settings (click to expand)', open=False):
++ with gr.Accordion('MatAnyone Settings (click to expand)', open=False) as image_settings_accordion:
with gr.Row():
-- erode_kernel_size = gr.Slider(label='Erode Kernel Size',
-- minimum=0,
-- maximum=30,
-- step=1,
-- value=10,
-- info="Erosion on the added mask",
-- interactive=True)
-- dilate_kernel_size = gr.Slider(label='Dilate Kernel Size',
-- minimum=0,
-- maximum=30,
-- step=1,
-- value=10,
-- info="Dilation on the added mask",
-- interactive=True)
--
++ erode_kernel_size_image = gr.Slider(label='Erode Kernel Size', minimum=0, maximum=30, step=1, value=10, info="Erosion on the added mask", interactive=True)
++ dilate_kernel_size_image = gr.Slider(label='Dilate Kernel Size', minimum=0, maximum=30, step=1, value=10, info="Dilation on the added mask", interactive=True)
with gr.Row():
-- image_selection_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Num of Refinement Iterations", info="More iterations → More details & More time", visible=False)
-- track_pause_number_slider = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Track end frame", visible=False)
++ image_selection_slider_image = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Num of Refinement Iterations", info="More iterations → More details & More time", visible=False)
++ track_pause_number_slider_image = gr.Slider(minimum=1, maximum=100, step=1, value=1, label="Track end frame", visible=False)
with gr.Row():
-- point_prompt = gr.Radio(
-- choices=["Positive", "Negative"],
-- value="Positive",
-- label="Point Prompt",
-- info="Click to add positive or negative point for target mask",
-- 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)
--
--
-- with gr.Column():
-- # input image
++ point_prompt_image = gr.Radio(choices=["Positive", "Negative"], value="Positive", label="Point Prompt", info="Click to add positive or negative point for target mask", interactive=True, visible=False, min_width=100, scale=1)
++ mask_dropdown_image = gr.Dropdown(multiselect=True, value=[], label="Mask Selection", info="Choose 1~all mask(s) added in Step 2", visible=False)
++ with gr.Column() as image_column:
with gr.Row(equal_height=True):
with gr.Column(scale=2):
gr.Markdown("## Step1: Upload image")
with gr.Column(scale=2):
-- step2_title = gr.Markdown("## Step2: Add masks <small>(Several clicks then **`Add Mask`** <u>one by one</u>)</small>", visible=False)
++ step2_title_image = gr.Markdown("## Step2: Add masks <small>(Several clicks then **`Add Mask`** <u>one by one</u>)</small>", visible=False)
with gr.Row(equal_height=True):
with gr.Column(scale=2):
image_input = gr.Image(label="Input Image", elem_classes="image")
-- extract_frames_button = gr.Button(value="Load Image", interactive=True, elem_classes="new_button")
++ extract_frames_button_image = gr.Button(value="Load Image", interactive=True, elem_classes="new_button")
with gr.Column(scale=2):
image_info = gr.Textbox(label="Image Info", visible=False)
-- template_frame = gr.Image(type="pil", label="Start Frame", interactive=True, elem_id="template_frame", visible=False, elem_classes="image")
++ template_frame_image = gr.Image(type="pil", label="Start Frame", interactive=True, elem_id="template_frame_image", visible=False, elem_classes="image")
with gr.Row(equal_height=True, elem_classes="mask_button_group"):
-- clear_button_click = gr.Button(value="Clear Clicks", interactive=True, visible=False, elem_classes="new_button", min_width=100)
-- add_mask_button = gr.Button(value="Add Mask", interactive=True, visible=False, elem_classes="new_button", min_width=100)
-- remove_mask_button = gr.Button(value="Remove Mask", interactive=True, visible=False, elem_classes="new_button", min_width=100)
-- matting_button = gr.Button(value="Image Matting", interactive=True, visible=False, elem_classes="green_button", min_width=100)
--
-- # output 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):
- 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")
++ clear_button_click_image = gr.Button(value="Clear Clicks", interactive=True, visible=False, elem_classes="new_button", min_width=100)
++ add_mask_button_image = gr.Button(value="Add Mask", interactive=True, visible=False, elem_classes="new_button", min_width=100)
++ remove_mask_button_image = gr.Button(value="Remove Mask", interactive=True, visible=False, elem_classes="new_button", min_width=100)
++ matting_button_image = gr.Button(value="Image Matting", interactive=True, visible=False, elem_classes="green_button", min_width=100)
++ 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.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)
-
- # first step: get the image information
- extract_frames_button.click(
- fn=get_frames_from_image,
- inputs=[
- image_input, image_state
- ],
- outputs=[image_state, 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]
- )
-
- # points clear
- clear_button_click.click(
- fn = clear_click,
- inputs = [image_state, click_state,],
- outputs = [template_frame,click_state],
- )
-
-
- # second step: select images from slider
- image_selection_slider.release(fn=select_image_template,
- inputs=[image_selection_slider, image_state, interactive_state],
- outputs=[template_frame, image_state, interactive_state], api_name="select_image")
- track_pause_number_slider.release(fn=get_end_number,
- inputs=[track_pause_number_slider, image_state, interactive_state],
- outputs=[template_frame, interactive_state], api_name="end_image")
-
- # click select image to get mask using sam
- template_frame.select(
- fn=sam_refine,
- inputs=[image_state, point_prompt, click_state, interactive_state],
- outputs=[template_frame, image_state, interactive_state]
- )
-
- # add different mask
- add_mask_button.click(
- fn=add_multi_mask,
- inputs=[image_state, interactive_state, mask_dropdown],
- outputs=[interactive_state, mask_dropdown, template_frame, click_state]
- )
-
- remove_mask_button.click(
- fn=remove_multi_mask,
- inputs=[interactive_state, mask_dropdown],
- outputs=[interactive_state, mask_dropdown]
- )
-
- # image matting
- matting_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]
- )
-
- nada = gr.State({})
- # clear input
- gr.on(
- triggers=[image_input.clear], #image_input.change,
- fn=restart,
- inputs=[],
- outputs=[
- image_state,
- interactive_state,
- click_state,
- foreground_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_title
- ],
- queue=False,
- show_progress=False)
-
++
++ return locals()
++
++def bind_events(components, tabs, tab_state, state, refresh_form_trigger, server_config, get_current_model_settings_fn):
++ """Binds all event listeners for the UI components."""
++ global get_current_model_settings, video_output_codec, image_output_codec
++ get_current_model_settings = get_current_model_settings_fn
++ video_output_codec = server_config.get("video_output_codec", "libx264_8")
++ image_output_codec = server_config.get("image_output_codec", "jpeg_95")
+
- 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, 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 information
- extract_frames_button.click(
- fn=get_frames_from_image,
- inputs=[
- state, image_input, image_state, new_dim
- ],
- 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, control_image_output, image_tabs, bbox_info, export_image_btn, export_image_mask_btn, mask_dropdown, step2_title]
- )
-
- # points clear
- clear_button_click.click(
- fn = clear_click,
- inputs = [image_state, click_state,],
- outputs = [template_frame,click_state],
- )
-
-
- # second step: select images from slider
- image_selection_slider.release(fn=select_image_template,
- inputs=[image_selection_slider, image_state, interactive_state],
- outputs=[template_frame, image_state, interactive_state], api_name="select_image")
- track_pause_number_slider.release(fn=get_end_number,
- inputs=[track_pause_number_slider, image_state, interactive_state],
- outputs=[template_frame, interactive_state], api_name="end_image")
-
- # click select image to get mask using sam
- template_frame.select(
- fn=sam_refine,
- inputs=[state, image_state, point_prompt, click_state, interactive_state],
- outputs=[template_frame, image_state, interactive_state]
- )
-
- # add different mask
- add_mask_button.click(
- fn=add_multi_mask,
- inputs=[image_state, interactive_state, mask_dropdown],
- outputs=[interactive_state, mask_dropdown, template_frame, click_state]
- )
-
- remove_mask_button.click(
- fn=remove_multi_mask,
- inputs=[interactive_state, mask_dropdown],
- outputs=[interactive_state, mask_dropdown]
- )
-
- # image matting
- matting_button.click(
- fn=image_matting,
- 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({})
- # clear input
- gr.on(
- triggers=[image_input.clear], #image_input.change,
- fn=restart,
- inputs=[],
- outputs=[
- image_state,
- interactive_state,
- click_state,
- 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_title
- ],
- queue=False,
- show_progress=False)
-
++ globals().update(components)
++
++ click_brush_js = """
++ () => {
++ setTimeout(() => {
++ const brushButton = document.querySelector('button[aria-label="Brush"]');
++ if (brushButton) {
++ brushButton.click();
++ }
++ }, 1000);
++ }"""
++
++ # --- Video Tab Events ---
++ extract_frames_button_video.click(
++ fn=get_frames_from_video,
++ inputs=[state, video_input, video_state, new_dim],
++ outputs=[video_state, extract_frames_button_video, video_info, template_frame_video,
++ image_selection_slider_video, end_selection_slider_video, track_pause_number_slider_video,
++ point_prompt_video, dummy, clear_button_click_video, add_mask_button_video, matting_button_video, template_frame_video,
++ foreground_video_output, alpha_video_output, gr.Button(visible=False), gr.Button(visible=False), mask_dropdown_video, step2_title_video]
++ )
++ image_selection_slider_video.release(fn=select_video_template, inputs=[image_selection_slider_video, video_state, interactive_state_video], outputs=[template_frame_video, video_state, interactive_state_video], api_name="select_video")
++ track_pause_number_slider_video.release(fn=get_end_number, inputs=[track_pause_number_slider_video, video_state, interactive_state_video], outputs=[template_frame_video, interactive_state_video])
++ template_frame_video.select(fn=sam_refine, inputs=[state, video_state, point_prompt_video, click_state_video, interactive_state_video], outputs=[template_frame_video, video_state, interactive_state_video])
++ add_mask_button_video.click(fn=add_multi_mask, inputs=[video_state, interactive_state_video, mask_dropdown_video], outputs=[interactive_state_video, mask_dropdown_video, template_frame_video, click_state_video])
++ remove_mask_button_video.click(fn=remove_multi_mask, inputs=[interactive_state_video, mask_dropdown_video], outputs=[interactive_state_video, mask_dropdown_video])
++ matting_button_video.click(
++ fn=show_outputs, inputs=[], outputs=[foreground_video_output, alpha_video_output]
++ ).then(
++ fn=video_matting,
++ inputs=[state, video_state, mask_type, video_input, end_selection_slider_video, matting_type, new_dim, interactive_state_video, mask_dropdown_video, erode_kernel_size_video, dilate_kernel_size_video],
++ outputs=[foreground_video_output, alpha_video_output, foreground_video_output, alpha_video_output, gr.Button(visible=False), export_to_current_video_engine_btn]
++ )
++ mask_dropdown_video.change(fn=show_mask, inputs=[video_state, interactive_state_video, mask_dropdown_video], outputs=[template_frame_video])
++ video_input.change(fn=restart, inputs=[], outputs=[video_state, interactive_state_video, click_state_video, extract_frames_button_video, dummy, foreground_video_output, dummy, alpha_video_output, template_frame_video, image_selection_slider_video, end_selection_slider_video, track_pause_number_slider_video, point_prompt_video, gr.Button(visible=False), export_to_current_video_engine_btn, dummy, clear_button_click_video, add_mask_button_video, matting_button_video, template_frame_video, foreground_video_output, alpha_video_output, remove_mask_button_video, gr.Button(visible=False), gr.Button(visible=False), mask_dropdown_video, video_info, step2_title_video], queue=False, show_progress=False)
++ video_input.clear(fn=restart, inputs=[], outputs=[video_state, interactive_state_video, click_state_video, extract_frames_button_video, dummy, foreground_video_output, dummy, alpha_video_output, template_frame_video, image_selection_slider_video, end_selection_slider_video, track_pause_number_slider_video, point_prompt_video, gr.Button(visible=False), export_to_current_video_engine_btn, dummy, clear_button_click_video, add_mask_button_video, matting_button_video, template_frame_video, foreground_video_output, alpha_video_output, remove_mask_button_video, gr.Button(visible=False), gr.Button(visible=False), mask_dropdown_video, video_info, step2_title_video], queue=False, show_progress=False)
++ clear_button_click_video.click(fn=clear_click, inputs=[video_state, click_state_video], outputs=[template_frame_video, click_state_video])
++ 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(fn=teleport_to_video_tab, inputs=[gr.State({}), state], outputs=[tabs])
++
++ # --- Image Tab Events ---
++ extract_frames_button_image.click(
++ fn=get_frames_from_image,
++ inputs=[state, image_input, image_state, new_dim],
++ outputs=[image_state, extract_frames_button_image, image_info, template_frame_image,
++ image_selection_slider_image, track_pause_number_slider_image, point_prompt_image, clear_button_click_image, add_mask_button_image, matting_button_image, template_frame_image,
++ foreground_image_output, alpha_image_output, control_image_output, image_tabs, bbox_info, export_image_btn, export_image_mask_btn, mask_dropdown_image, step2_title_image]
++ )
++ clear_button_click_image.click(fn=clear_click, inputs=[image_state, click_state_image], outputs=[template_frame_image, click_state_image])
++ image_selection_slider_image.release(fn=select_image_template, inputs=[image_selection_slider_image, image_state, interactive_state_image], outputs=[template_frame_image, image_state, interactive_state_image], api_name="select_image")
++ template_frame_image.select(fn=sam_refine, inputs=[state, image_state, point_prompt_image, click_state_image, interactive_state_image], outputs=[template_frame_image, image_state, interactive_state_image])
++ add_mask_button_image.click(fn=add_multi_mask, inputs=[image_state, interactive_state_image, mask_dropdown_image], outputs=[interactive_state_image, mask_dropdown_image, template_frame_image, click_state_image])
++ remove_mask_button_image.click(fn=remove_multi_mask, inputs=[interactive_state_image, mask_dropdown_image], outputs=[interactive_state_image, mask_dropdown_image])
++ matting_button_image.click(
++ fn=image_matting,
++ inputs=[state, image_state, interactive_state_image, mask_type, matting_type, new_dim, mask_dropdown_image, erode_kernel_size_image, dilate_kernel_size_image, image_selection_slider_image],
++ 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({})
++ image_input.clear(fn=restart, inputs=[], outputs=[image_state, interactive_state_image, click_state_image, extract_frames_button_image, image_tabs, foreground_image_output, control_image_output, alpha_image_output, template_frame_image, image_selection_slider_image, image_selection_slider_image, track_pause_number_slider_image, point_prompt_image, export_image_btn, export_image_mask_btn, bbox_info, clear_button_click_image, add_mask_button_image, matting_button_image, template_frame_image, foreground_image_output, alpha_image_output, remove_mask_button_image, export_image_btn, export_image_mask_btn, mask_dropdown_image, nada, step2_title_image], queue=False, show_progress=False)
++ export_image_btn.click(fn=export_image, inputs=[state, foreground_image_output], outputs=[refresh_form_trigger]).then(fn=teleport_to_video_tab, inputs=[gr.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(fn=teleport_to_video_tab, inputs=[gr.State({}), state], outputs=[tabs]).then(fn=None, inputs=None, outputs=None, js=click_brush_js)
diff --cc shared/utils/plugins.py
index 0000000,43fcae8..cd5e69c
mode 000000,100644..100644
--- a/shared/utils/plugins.py
+++ b/shared/utils/plugins.py
@@@ -1,0 -1,419 +1,475 @@@
+ import os
+ import sys
+ import importlib
+ import importlib.util
+ import inspect
+ from typing import Dict, Any, Optional, List, Union
+ from dataclasses import dataclass
+ import gradio as gr
+ import traceback
+ import subprocess
+ import git
+ import shutil
+
+ SYSTEM_PLUGINS = [
+ "wan2gp-about",
+ "wan2gp-configuration",
+ "wan2gp-downloads",
+ "wan2gp-guides",
+ "wan2gp-plugin-manager",
+ "wan2gp-video-mask-creator",
+ ]
+
+ @dataclass
+ class InsertAfterRequest:
+ target_component_id: str
+ new_component_constructor: callable
+
+ @dataclass
+ class PluginTab:
+ id: str
+ label: str
+ component_constructor: callable
+ position: int = -1
+
+ class WAN2GPPlugin:
+ def __init__(self):
+ self.tabs: Dict[str, PluginTab] = {}
+ self.name = self.__class__.__name__
+ self.version = "1.0.0"
+ self.description = "No description provided."
+ self._component_requests: List[str] = []
+ self._global_requests: List[str] = []
+ self._insert_after_requests: List[InsertAfterRequest] = []
+ self._setup_complete = False
+ self._data_hooks: Dict[str, List[callable]] = {}
++ self.tab_ids: List[str] = []
+
+ def setup_ui(self) -> None:
+ pass
+
+ def add_tab(self, tab_id: str, label: str, component_constructor: callable, position: int = -1):
+ self.tabs[tab_id] = PluginTab(id=tab_id, label=label, component_constructor=component_constructor, position=position)
++ if tab_id not in self.tab_ids:
++ self.tab_ids.append(tab_id)
++
++ def on_tab_select(self, state: Dict[str, Any]) -> None:
++ pass
++
++ def on_tab_deselect(self, state: Dict[str, Any]) -> None:
++ pass
+
+ def request_component(self, component_id: str) -> None:
+ if component_id not in self._component_requests:
+ self._component_requests.append(component_id)
+
+ def request_global(self, global_name: str) -> None:
+ if global_name not in self._global_requests:
+ self._global_requests.append(global_name)
+
+ @property
+ def component_requests(self) -> List[str]:
+ return self._component_requests.copy()
+
+ @property
+ def global_requests(self) -> List[str]:
+ return self._global_requests.copy()
+
+ def register_data_hook(self, hook_name: str, callback: callable):
+ if hook_name not in self._data_hooks:
+ self._data_hooks[hook_name] = []
+ self._data_hooks[hook_name].append(callback)
+
+ def insert_after(self, target_component_id: str, new_component_constructor: callable) -> None:
+ if not hasattr(self, '_insert_after_requests'):
+ self._insert_after_requests = []
+ self._insert_after_requests.append(
+ InsertAfterRequest(
+ target_component_id=target_component_id,
+ new_component_constructor=new_component_constructor
+ )
+ )
+
+ def post_ui_setup(self, components: Dict[str, gr.components.Component]) -> Dict[gr.components.Component, Union[gr.update, Any]]:
+ return {}
+
+ class PluginManager:
+ def __init__(self, plugins_dir="plugins"):
+ self.plugins: Dict[str, WAN2GPPlugin] = {}
+ self.plugins_dir = plugins_dir
+ os.makedirs(self.plugins_dir, exist_ok=True)
+ if self.plugins_dir not in sys.path:
+ sys.path.insert(0, self.plugins_dir)
+ self.data_hooks: Dict[str, List[callable]] = {}
+
+ def get_plugins_info(self) -> List[Dict[str, str]]:
+ plugins_info = []
+ for dir_name in self.discover_plugins():
+ plugin_path = os.path.join(self.plugins_dir, dir_name)
+ is_system = dir_name in SYSTEM_PLUGINS
+ info = {'id': dir_name, 'name': dir_name, 'version': 'N/A', 'description': 'No description provided.', 'path': plugin_path, 'system': is_system}
+ try:
- # Use import_module, which correctly handles packages and relative imports
+ module = importlib.import_module(f"{dir_name}.plugin")
+ for name, obj in inspect.getmembers(module, inspect.isclass):
+ if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:
+ instance = obj()
+ info['name'] = instance.name
+ info['version'] = instance.version
+ info['description'] = instance.description
+ break
+ except Exception as e:
+ print(f"Could not load metadata for plugin {dir_name}: {e}")
+ plugins_info.append(info)
+
+ plugins_info.sort(key=lambda p: (not p['system'], p['name']))
+ return plugins_info
+
+ def uninstall_plugin(self, plugin_id: str):
+ if not plugin_id:
+ return "[Error] No plugin selected for uninstallation."
+
+ if plugin_id in SYSTEM_PLUGINS:
+ return f"[Error] Cannot uninstall system plugin '{plugin_id}'."
+
+ target_dir = os.path.join(self.plugins_dir, plugin_id)
+ if not os.path.isdir(target_dir):
+ return f"[Error] Plugin '{plugin_id}' directory not found."
+
+ try:
+ shutil.rmtree(target_dir)
+ return f"[Success] Plugin '{plugin_id}' uninstalled. Please restart WanGP."
+ except Exception as e:
+ return f"[Error] Failed to remove plugin '{plugin_id}': {e}"
+
+ def update_plugin(self, plugin_id: str):
+ if not plugin_id:
+ return "[Error] No plugin selected for update."
+
+ target_dir = os.path.join(self.plugins_dir, plugin_id)
+ if not os.path.isdir(os.path.join(target_dir, '.git')):
+ return f"[Error] '{plugin_id}' is not a git repository and cannot be updated automatically."
+
+ try:
+ gr.Info(f"Attempting to update '{plugin_id}'...")
+ repo = git.Repo(target_dir)
+ origin = repo.remotes.origin
+ origin.fetch()
+
+ local_commit = repo.head.commit
+ remote_commit = origin.refs[repo.active_branch.name].commit
+
+ if local_commit == remote_commit:
+ return f"[Info] Plugin '{plugin_id}' is already up to date."
+
+ origin.pull()
+
+ requirements_path = os.path.join(target_dir, 'requirements.txt')
+ if os.path.exists(requirements_path):
+ gr.Info(f"Re-installing dependencies for '{plugin_id}'...")
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', requirements_path])
+
+ return f"[Success] Plugin '{plugin_id}' updated. Please restart WanGP for changes to take effect."
+ except git.exc.GitCommandError as e:
+ return f"[Error] Git update failed for '{plugin_id}': {e.stderr}"
+ except Exception as e:
+ return f"[Error] An unexpected error occurred during update of '{plugin_id}': {str(e)}"
+
+ def reinstall_plugin(self, plugin_id: str):
+ if not plugin_id:
+ return "[Error] No plugin selected for reinstallation."
+
+ target_dir = os.path.join(self.plugins_dir, plugin_id)
+ if not os.path.isdir(target_dir):
+ return f"[Error] Plugin '{plugin_id}' not found."
+
+ git_url = None
+ if os.path.isdir(os.path.join(target_dir, '.git')):
+ try:
+ repo = git.Repo(target_dir)
+ git_url = repo.remotes.origin.url
+ except Exception as e:
+ return f"[Error] Could not get remote URL for '{plugin_id}': {e}"
+
+ if not git_url:
+ return f"[Error] Could not determine remote URL for '{plugin_id}'. Cannot reinstall."
+
+ gr.Info(f"Reinstalling '{plugin_id}'...")
+ uninstall_msg = self.uninstall_plugin(plugin_id)
+ if "[Error]" in uninstall_msg:
+ return uninstall_msg
+
+ install_msg = self.install_plugin_from_url(git_url)
+ if "[Success]" in install_msg:
+ return f"[Success] Plugin '{plugin_id}' reinstalled. Please restart WanGP."
+ else:
+ return f"[Error] Reinstallation failed during install step: {install_msg}"
+
+ def install_plugin_from_url(self, git_url: str):
+ if not git_url or not git_url.startswith("https://github.com/"):
+ return "[Error] Invalid GitHub URL."
+
+ try:
+ repo_name = git_url.split('/')[-1].replace('.git', '')
+ target_dir = os.path.join(self.plugins_dir, repo_name)
+
+ if os.path.exists(target_dir):
+ return f"[Warning] Plugin '{repo_name}' already exists. Please remove it manually to reinstall."
+
+ gr.Info(f"Cloning '{repo_name}' into '{target_dir}'...")
+ git.Repo.clone_from(git_url, target_dir)
+
+ requirements_path = os.path.join(target_dir, 'requirements.txt')
+ if os.path.exists(requirements_path):
+ gr.Info(f"Installing dependencies for '{repo_name}'...")
+ try:
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', requirements_path])
+ except subprocess.CalledProcessError as e:
+ return f"[Error] Failed to install dependencies for {repo_name}. Check console for details. Error: {e}"
+
+ setup_path = os.path.join(target_dir, 'setup.py')
+ if os.path.exists(setup_path):
+ gr.Info(f"Running setup for '{repo_name}'...")
+ try:
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-e', target_dir])
+ except subprocess.CalledProcessError as e:
+ return f"[Error] Failed to run setup.py for {repo_name}. Check console for details. Error: {e}"
+
+ init_path = os.path.join(target_dir, '__init__.py')
+ if not os.path.exists(init_path):
+ with open(init_path, 'w') as f:
+ pass
+
+ return f"[Success] Plugin '{repo_name}' installed. Please enable it in the list and restart WanGP."
+
+ except git.exc.GitCommandError as e:
+ return f"[Error] Git clone failed: {e.stderr}"
+ except Exception as e:
+ return f"[Error] An unexpected error occurred: {str(e)}"
+
+ def discover_plugins(self) -> List[str]:
+ discovered = []
+ for item in os.listdir(self.plugins_dir):
+ path = os.path.join(self.plugins_dir, item)
+ if os.path.isdir(path) and os.path.exists(os.path.join(path, '__init__.py')):
+ discovered.append(item)
+ return sorted(discovered)
+
+ def load_plugins_from_directory(self, enabled_user_plugins: List[str]) -> None:
+ plugins_to_load = SYSTEM_PLUGINS + [p for p in enabled_user_plugins if p not in SYSTEM_PLUGINS]
+
+ for plugin_dir_name in self.discover_plugins():
+ if plugin_dir_name not in plugins_to_load:
+ continue
+ try:
+ module = importlib.import_module(f"{plugin_dir_name}.plugin")
+
+ for name, obj in inspect.getmembers(module, inspect.isclass):
+ if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:
+ plugin = obj()
+ plugin.setup_ui()
+ self.plugins[plugin_dir_name] = plugin
+ for hook_name, callbacks in plugin._data_hooks.items():
+ if hook_name not in self.data_hooks:
+ self.data_hooks[hook_name] = []
+ self.data_hooks[hook_name].extend(callbacks)
+ print(f"Loaded plugin: {plugin.name} (from {plugin_dir_name})")
+ break
+ except Exception as e:
+ print(f"Error loading plugin from directory {plugin_dir_name}: {e}")
+ traceback.print_exc()
+
+ def get_all_plugins(self) -> Dict[str, WAN2GPPlugin]:
+ return self.plugins.copy()
+
+ def inject_globals(self, global_references: Dict[str, Any]) -> None:
+ for plugin_id, plugin in self.plugins.items():
+ try:
+ for global_name in plugin.global_requests:
+ if global_name in global_references:
+ setattr(plugin, global_name, global_references[global_name])
+ except Exception as e:
+ print(f" [!] ERROR injecting globals for {plugin_id}: {str(e)}")
+
+ def setup_ui(self) -> Dict[str, Dict[str, Any]]:
+ tabs = {}
+ for plugin_id, plugin in self.plugins.items():
+ try:
+ for tab_id, tab in plugin.tabs.items():
+ tabs[tab_id] = {
+ 'label': tab.label,
+ 'component_constructor': tab.component_constructor,
+ 'position': tab.position
+ }
+ except Exception as e:
+ print(f"Error in setup_ui for plugin {plugin_id}: {str(e)}")
+ return {'tabs': tabs}
+
+ def run_data_hooks(self, hook_name: str, *args, **kwargs):
+ if hook_name not in self.data_hooks:
+ return kwargs.get('configs')
+
+ callbacks = self.data_hooks[hook_name]
+ data = kwargs.get('configs')
+
+ if 'configs' in kwargs:
+ kwargs.pop('configs')
+
+ for callback in callbacks:
+ try:
+ data = callback(data, **kwargs)
+ except Exception as e:
+ print(f"[PluginManager] Error running hook '{hook_name}' from {callback.__module__}: {e}")
+ traceback.print_exc()
+ return data
+
+ def run_post_ui_setup(self, all_components: Dict[str, gr.components.Component]) -> None:
- if 'tab_state' not in all_components and 'main_tabs' in all_components:
- main_tabs = all_components.get('main_tabs')
- root_blocks = getattr(main_tabs, 'parent', None)
- if root_blocks:
- for component in getattr(root_blocks, 'children', []):
- if isinstance(component, gr.State):
- all_components['tab_state'] = component
- break
+ all_insert_requests: List[InsertAfterRequest] = []
+
+ for plugin_id, plugin in self.plugins.items():
+ try:
+ for comp_id in plugin.component_requests:
+ if comp_id in all_components:
+ setattr(plugin, comp_id, all_components[comp_id])
+
+ requested_components = {
+ comp_id: all_components[comp_id]
+ for comp_id in plugin.component_requests
+ if comp_id in all_components
+ }
+ plugin.post_ui_setup(requested_components)
- all_insert_requests.extend(getattr(plugin, '_insert_after_requests', []))
++ if hasattr(plugin, '_insert_after_requests'):
++ all_insert_requests.extend(plugin._insert_after_requests)
++ plugin._insert_after_requests.clear()
+
+ except Exception as e:
+ print(f"[PluginManager] Error in post_ui_setup for {plugin_id}: {str(e)}")
+ traceback.print_exc()
+
+ if all_insert_requests:
+ for request in all_insert_requests:
+ try:
+ target = all_components.get(request.target_component_id)
+ parent = getattr(target, 'parent', None)
+ if not target or not parent or not hasattr(parent, 'children'):
- print(f"[PluginManager] ERROR: Target '{request.target_component_id}' for insertion not found or invalid.")
++ print(f"[PluginManager] WARNING: Target '{request.target_component_id}' for insertion not found in the current UI tab context. Skipping.")
+ continue
+
+ target_index = parent.children.index(target)
+ with parent:
+ new_component = request.new_component_constructor()
+
+ newly_added = parent.children.pop(-1)
+ parent.children.insert(target_index + 1, newly_added)
+ print(f"[PluginManager] Successfully inserted component after '{request.target_component_id}'")
+
+ except Exception as e:
+ print(f"[PluginManager] Error processing insert_after for {request.target_component_id}: {str(e)}")
+
+ class WAN2GPApplication:
+ def __init__(self):
+ self.plugin_manager = PluginManager()
+ self.ui_components = {}
++ self.tab_to_plugin_map: Dict[str, WAN2GPPlugin] = {}
++ self.all_rendered_tabs: List[gr.Tab] = []
+
+ def _create_plugin_tabs(self, main_module_globals: Dict[str, Any]):
+ if not self.plugin_manager:
+ return
+ server_config = main_module_globals.get('server_config', {})
+ enabled_user_plugins = server_config.get("enabled_plugins", [])
+
+ self.plugin_manager.load_plugins_from_directory(enabled_user_plugins)
+ self.plugin_manager.inject_globals(main_module_globals)
++ early_components = {
++ name: obj for name, obj in main_module_globals.items()
++ if isinstance(obj, (gr.Blocks, gr.components.Component, gr.Row, gr.Column, gr.Tabs, gr.Group, gr.Accordion, gr.State))
++ }
++ for plugin in self.plugin_manager.get_all_plugins().values():
++ for comp_id in plugin.component_requests:
++ if comp_id in early_components:
++ setattr(plugin, comp_id, early_components[comp_id])
+
+ loaded_plugins = self.plugin_manager.get_all_plugins()
+
+ system_tabs = []
+ user_tabs = []
+
+ for plugin_id, plugin in loaded_plugins.items():
+ for tab_id, tab in plugin.tabs.items():
++ self.tab_to_plugin_map[f"plugin_{tab_id}"] = plugin
+ tab_info = {
+ 'id': tab_id,
+ 'label': tab.label,
+ 'component_constructor': tab.component_constructor,
+ 'position': tab.position
+ }
+ if plugin_id in SYSTEM_PLUGINS:
+ system_tabs.append(tab_info)
+ else:
+ user_tabs.append((plugin_id, tab_info))
+
+ system_tabs.sort(key=lambda t: (t.get('position', -1), t['label']))
+
+ sorted_user_tabs = []
+ for plugin_id in enabled_user_plugins:
+ for pid, tab_info in user_tabs:
+ if pid == plugin_id:
+ sorted_user_tabs.append(tab_info)
+
+ all_tabs_to_render = system_tabs + sorted_user_tabs
+
+ for tab_info in all_tabs_to_render:
- with gr.Tab(tab_info['label'], id=f"plugin_{tab_info['id']}"):
++ with gr.Tab(tab_info['label'], id=f"plugin_{tab_info['id']}") as rendered_tab:
+ tab_info['component_constructor']()
++ self.all_rendered_tabs.append(rendered_tab)
+
- def finalize_ui_setup(self, main_module_globals: Dict[str, Any], all_ui_components: Dict[str, Any]):
++ def _handle_tab_selection(self, state: dict, selected_tab_id: str, evt: gr.SelectData): # Add this new method
++ if not hasattr(self, 'previous_tab_id'):
++ self.previous_tab_id = None
++
++ new_tab_id = evt.value
++
++ if self.previous_tab_id == new_tab_id:
++ return
++
++ if self.previous_tab_id and self.previous_tab_id in self.tab_to_plugin_map:
++ plugin_to_deselect = self.tab_to_plugin_map[self.previous_tab_id]
++ try:
++ plugin_to_deselect.on_tab_deselect(state)
++ except Exception as e:
++ print(f"[PluginManager] Error in on_tab_deselect for plugin {plugin_to_deselect.name}: {e}")
++ traceback.print_exc()
++
++ if new_tab_id and new_tab_id in self.tab_to_plugin_map:
++ plugin_to_select = self.tab_to_plugin_map[new_tab_id]
++ try:
++ plugin_to_select.on_tab_select(state)
++ except Exception as e:
++ print(f"[PluginManager] Error in on_tab_select for plugin {plugin_to_select.name}: {e}")
++ traceback.print_exc()
++
++ self.previous_tab_id = new_tab_id
++ return new_tab_id
++
++ def finalize_ui_setup(self, main_module_globals: Dict[str, Any], all_ui_components_list: List[Dict[str, Any]]):
+ self._create_plugin_tabs(main_module_globals)
- self.ui_components = {
- name: obj for name, obj in all_ui_components.items()
- if isinstance(obj, (gr.Blocks, gr.components.Component, gr.Row, gr.Column, gr.Tabs, gr.Group, gr.Accordion))
- }
- if self.plugin_manager:
- self.plugin_manager.run_post_ui_setup(self.ui_components)
++
++ main_tabs = main_module_globals.get('main_tabs')
++ state = main_module_globals.get('state')
++ tab_state_id = gr.State(main_tabs.selected if main_tabs else None)
++
++ if main_tabs and state:
++ main_tabs.select(
++ self._handle_tab_selection,
++ inputs=[state, tab_state_id],
++ outputs=[tab_state_id],
++ show_progress="hidden"
++ )
++
++ for component_dict in all_ui_components_list:
++ if self.plugin_manager:
++ self.ui_components = {
++ name: obj for name, obj in component_dict.items()
++ if isinstance(obj, (gr.Blocks, gr.components.Component, gr.Row, gr.Column, gr.Tabs, gr.Group, gr.Accordion))
++ }
++ self.plugin_manager.run_post_ui_setup(self.ui_components)
diff --cc wgp.py
index 8ee017a,7a527ca..c7d8129
--- a/wgp.py
+++ b/wgp.py
@@@ -55,7 -50,7 +55,6 @@@ import glo
import cv2
from transformers.utils import logging
logging.set_verbosity_error
--from preprocessing.matanyone import app as matanyone_app
from tqdm import tqdm
import requests
from shared.gradio.gallery import AdvancedMediaGallery
@@@ -83,9 -78,10 +83,8 @@@ if mmgp_version != target_mmgp_version
lock = threading.Lock()
current_task_id = None
task_id = 0
--vmc_event_handler = matanyone_app.get_vmc_event_handler()
unique_id = 0
unique_id_lock = threading.Lock()
-gen_lock = threading.Lock()
offloadobj = enhancer_offloadobj = wan_model = None
reload_needed = True
@@@ -917,18 -741,18 +916,20 @@@ def add_video_task(**inputs)
queue = gen["queue"]
task_id += 1
current_task_id = task_id
+ item_color = get_queue_item_color(current_task_id)
start_image_data, end_image_data, start_image_labels, end_image_labels = get_preview_images(inputs)
-
+ plugin_data = inputs.pop('plugin_data', {})
+
queue.append({
"id": current_task_id,
+ "color": item_color,
"params": inputs.copy(),
+ "plugin_data": plugin_data,
- "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",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,
@@@ -5930,23 -5579,8 +5789,24 @@@ def process_tasks(state)
send_cmd = com_stream.output_queue.push
def generate_video_error_handler():
try:
+ import inspect
+ model_type = params.get('model_type')
+ known_defaults = {
+ 'image_refs_relative_size': 50,
+ }
+
+ for arg_name, default_value in known_defaults.items():
+ if arg_name not in params:
+ print(f"Warning: Missing argument '{arg_name}' in loaded task. Applying default value: {default_value}")
+ params[arg_name] = default_value
+ if model_type:
+ default_settings = get_default_settings(model_type)
+ expected_args = inspect.signature(generate_video).parameters.keys()
+ for arg_name in expected_args:
+ if arg_name not in params and arg_name in default_settings:
+ params[arg_name] = default_settings[arg_name]
- generate_video(task, send_cmd, **params)
+ plugin_data = task.pop('plugin_data', {})
- generate_video(task, send_cmd, plugin_data=plugin_data, **params)
++ generate_video(task, send_cmd, plugin_data=plugin_data, **params)
except Exception as e:
tb = traceback.format_exc().split('\n')[:-1]
print('\n'.join(tb))
@@@ -7204,74 -6817,52 +7072,47 @@@ def save_inputs
elif target == "state":
set_model_settings(state, model_type, cleaned_inputs)
- def download_loras():
- from huggingface_hub import snapshot_download
- yield gr.Row(visible=True), "<B><FONT SIZE=3>Please wait while the Loras are being downloaded</B></FONT>" #, *[gr.Column(visible=False)] * 2
- lora_dir = get_lora_dir("i2v")
- log_path = os.path.join(lora_dir, "log.txt")
- if not os.path.isfile(log_path):
- tmp_path = os.path.join(lora_dir, "tmp_lora_dowload")
- import glob
- snapshot_download(repo_id="DeepBeepMeep/Wan2.1", allow_patterns="loras_i2v/*", local_dir= tmp_path)
- for f in glob.glob(os.path.join(tmp_path, "loras_i2v", "*.*")):
- target_file = os.path.join(lora_dir, Path(f).parts[-1] )
- if os.path.isfile(target_file):
- os.remove(f)
- else:
- shutil.move(f, lora_dir)
- try:
- os.remove(tmp_path)
- except:
- pass
- yield gr.Row(visible=True), "<B><FONT SIZE=3>Loras have been completely downloaded</B></FONT>" #, *[gr.Column(visible=True)] * 2
-
- from datetime import datetime
- dt = datetime.today().strftime('%Y-%m-%d')
- with open( log_path, "w", encoding="utf-8") as writer:
- writer.write(f"Loras downloaded on the {dt} at {time.time()} on the {time.time()}")
- return
-
-def handle_celll_selection(state, evt: gr.SelectData):
+def handle_queue_action(state, action_string):
+ if not action_string:
+ return gr.HTML(), gr.Tabs()
+
gen = get_gen_info(state)
queue = gen.get("queue", [])
-
- if evt.index is None:
- return gr.update(), gr.update(), gr.update(visible=False)
- row_index, col_index = evt.index
- cell_value = None
- if col_index in [6, 7, 8]:
- if col_index == 6: cell_value = "↑"
- elif col_index == 7: cell_value = "↓"
- elif col_index == 8: cell_value = "✖"
- if col_index == 6:
- new_df_data = move_up(queue, [row_index])
- return new_df_data, gr.update(), gr.update(visible=False)
- elif col_index == 7:
- new_df_data = move_down(queue, [row_index])
- return new_df_data, gr.update(), gr.update(visible=False)
- elif col_index == 8:
- new_df_data = remove_task(queue, [row_index])
- gen["prompts_max"] = gen.get("prompts_max",0) - 1
+
+ try:
+ parts = action_string.split('_')
+ action = parts[0]
+ params = parts[1:]
+ except (IndexError, ValueError):
+ return gr.HTML(), gr.Tabs()
+
+ if action == "edit" or action == "silent_edit":
+ row_index = int(params[0])
+ state["editing_task_index"] = row_index
+ task_to_edit_index = row_index + 1
+
+ if task_to_edit_index < len(queue):
+ task_data = queue[task_to_edit_index]
+ if action == "edit":
+ gr.Info(f"Loading task '{task_data['prompt'][:50]}...' for editing.")
+ return update_queue_data(queue), gr.Tabs(selected="edit")
+ else:
+ gr.Warning("Task index out of bounds.")
+ return update_queue_data(queue), gr.Tabs()
+
+ elif action == "move" and len(params) == 3 and params[1] == "to":
+ old_index_str, new_index_str = params[0], params[2]
+ return move_task(queue, old_index_str, new_index_str), gr.Tabs()
+
+ elif action == "remove":
+ row_index = int(params[0])
+ new_queue_data = remove_task(queue, [row_index])
+ gen["prompts_max"] = gen.get("prompts_max", 0) - 1
update_status(state)
- return new_df_data, gr.update(), gr.update(visible=False)
- start_img_col_idx = 4
- end_img_col_idx = 5
- image_data_to_show = None
- if col_index == start_img_col_idx:
- with lock:
- row_index += 1
- if row_index < len(queue):
- image_data_to_show = queue[row_index].get('start_image_data_base64')
- names = queue[row_index].get('start_image_labels')
- elif col_index == end_img_col_idx:
- with lock:
- row_index += 1
- if row_index < len(queue):
- image_data_to_show = queue[row_index].get('end_image_data_base64')
- names = queue[row_index].get('end_image_labels')
-
- if image_data_to_show:
- value = get_modal_image( image_data_to_show[0], names[0])
- return gr.update(), gr.update(value=value), gr.update(visible=True)
- else:
- return gr.update(), gr.update(), gr.update(visible=False)
+ return new_queue_data, gr.Tabs()
+ return update_queue_data(queue), gr.Tabs()
def change_model(state, model_choice):
if model_choice == None:
@@@ -7870,8 -7396,9 +7711,9 @@@ def download_lora(state, lora_url, prog
-def generate_video_tab(update_form = False, state_dict = None, ui_defaults = None, model_family = None, model_base_type_choice = None, model_choice = None, header = None, main = None, main_tabs= None):
+def generate_video_tab(update_form = False, state_dict = None, ui_defaults = None, model_family = None, model_base_type_choice = None, model_choice = None, header = None, main = None, main_tabs= None, tab_id='generate'):
global inputs_names #, advanced
+ plugin_data = gr.State({})
if update_form:
model_filename = state_dict["model_filename"]
@@@ -7924,15 -7451,13 +7766,13 @@@
launch_multis_str = ui_defaults.get("loras_multipliers","")
launch_loras = [os.path.basename(path) for path in ui_defaults.get("activated_loras",[])]
with gr.Row():
- with gr.Column():
- with gr.Column(visible=False, elem_id="image-modal-container") as modal_container:
- with gr.Row(elem_id="image-modal-close-button-row"): #
- close_modal_button = gr.Button("❌", size="sm", scale=1)
- # modal_image_display = gr.Image(label="Full Resolution Image", interactive=False, show_label=False)
- modal_image_display = gr.HTML(label="Full Resolution Image")
- preview_column_no = gr.Text(visible=False, value=-1, elem_id="preview_column_no")
+ column_kwargs = {'elem_id': 'edit-tab-content'} if tab_id == 'edit' else {}
+ with gr.Column(**column_kwargs):
+ with gr.Column(visible=False, elem_id="image-modal-container") as modal_container:
+ modal_html_display = gr.HTML()
- # These two are for opening the modal with content
+ modal_action_input = gr.Text(elem_id="modal_action_input", visible=False)
+ modal_action_trigger = gr.Button(elem_id="modal_action_trigger", visible=False)
- # This hidden button is our new trigger for closing the modal
+ close_modal_trigger_btn = gr.Button(elem_id="modal_close_trigger_btn", visible=False)
with gr.Row(visible= True): #len(loras)>0) as presets_column:
lset_choices = compute_lset_choices(model_type, loras_presets) + [(get_new_preset_msg(advanced_ui), "")]
with gr.Column(scale=6):
@@@ -9326,463 -8778,35 +9166,15 @@@
outputs=[current_gen_column, queue_accordion]
)
-
- add_to_queue_btn.click(fn = lambda : (get_unique_id(), ""), inputs = None, outputs=[add_to_queue_trigger, mode])
- # gr.on(triggers=[add_to_queue_btn.click, add_to_queue_trigger.change],fn=validate_wizard_prompt,
- add_to_queue_trigger.change(fn=validate_wizard_prompt,
- inputs =[state, wizard_prompt_activated_var, wizard_variables_var, prompt, wizard_prompt, *prompt_vars] ,
- outputs= [prompt],
- show_progress="hidden",
- ).then(fn=save_inputs,
- inputs =[target_state] + gen_inputs,
- outputs= None
- ).then(fn=process_prompt_and_add_tasks,
- inputs = [state, model_choice],
- outputs=[queue_df, queue_accordion],
- show_progress="hidden",
- ).then(
- fn=update_status,
- inputs = [state],
- )
-
- close_modal_button.click(
- lambda: gr.update(visible=False),
- inputs=[],
- outputs=[modal_container]
- )
-
- return ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger, locals(),
- # video_guide, image_guide, video_mask, image_mask, image_refs,
- )
+ if tab_id == 'edit':
+ locals_dict = locals()
+ gen_inputs = [locals_dict[k] for k in inputs_names] + [state] + extra_inputs
- return gen_inputs
++ return gen_inputs, locals()
+ else:
- return ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger,
++ return ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger, locals(),
+ # video_guide, image_guide, video_mask, image_mask, image_refs,
- )
-
-
- def generate_download_tab(lset_name,loras_choices, state):
- with gr.Row():
- with gr.Row(scale =2):
- gr.Markdown("<I>WanGP's Lora Festival ! Press the following button to download i2v <B>Remade_AI</B> Loras collection (and bonuses Loras).")
- with gr.Row(scale =1):
- download_loras_btn = gr.Button("---> Let the Lora's Festival Start !", scale =1)
- with gr.Row(scale =1):
- gr.Markdown("")
- with gr.Row() as download_status_row:
- download_status = gr.Markdown()
-
- download_loras_btn.click(fn=download_loras, inputs=[], outputs=[download_status_row, download_status]).then(fn=refresh_lora_list, inputs=[state, lset_name,loras_choices], outputs=[lset_name, loras_choices])
-
-
- def generate_configuration_tab(state, blocks, header, model_family, model_base_type_choice, model_choice, resolution, refresh_form_trigger):
- gr.Markdown("Please click Apply Changes at the bottom so that the changes are effective. Some choices below may be locked if the app has been launched by specifying a config preset.")
- with gr.Column():
- with gr.Tabs():
- # with gr.Row(visible=advanced_ui) as advanced_row:
- with gr.Tab("General"):
- _, _, dropdown_choices = get_sorted_dropdown(displayed_model_types, None, None, False)
-
- transformer_types_choices = gr.Dropdown(
- choices= dropdown_choices,
- value= transformer_types,
- label= "Selectable Generative Models (keep empty to get All of them)",
- scale= 2,
- multiselect= True
- )
-
- model_hierarchy_type_choice = gr.Dropdown(
- choices=[
- ("Two Levels: Model Family > Models & Finetunes", 0),
- ("Three Levels: Model Family > Models > Finetunes", 1),
- ],
- value= server_config.get("model_hierarchy_type", 1),
- label= "Models Hierarchy In User Interface",
- visible=args.betatest,
- scale= 2,
- )
-
-
- fit_canvas_choice = gr.Dropdown(
- choices=[
- ("Dimensions correspond to the Pixels Budget (as the Prompt Image/Video will be Resized to match this pixels Budget, output video height or width may exceed the requested dimensions )", 0),
- ("Dimensions correspond to the Maximum Width and Height (as the Prompt Image/Video will be Resized to fit into these dimensions, the output video may be smaller)", 1),
- ("Dimensions correspond to the Output Width and Height (as the Prompt Image/Video will be Cropped to fit exactly these dimensions)", 2),
- ],
- value= server_config.get("fit_canvas", 0),
- label="Generated Video Dimensions when Prompt contains an Image or a Video",
- interactive= not lock_ui_attention
- )
-
-
- def check(mode):
- if not mode in attention_modes_installed:
- return " (NOT INSTALLED)"
- elif not mode in attention_modes_supported:
- return " (NOT SUPPORTED)"
- else:
- return ""
- attention_choice = gr.Dropdown(
- choices=[
- ("Auto : pick sage2 > sage > sdpa depending on what is installed", "auto"),
- ("Scale Dot Product Attention: default, always available", "sdpa"),
- ("Flash" + check("flash")+ ": good quality - requires additional install (usually complex to set up on Windows without WSL)", "flash"),
- ("Xformers" + check("xformers")+ ": good quality - requires additional install (usually complex, may consume less VRAM to set up on Windows without WSL)", "xformers"),
- ("Sage" + check("sage")+ ": 30% faster but slightly worse quality - requires additional install (usually complex to set up on Windows without WSL)", "sage"),
- ("Sage2/2++" + check("sage2")+ ": 40% faster but slightly worse quality - requires additional install (usually complex to set up on Windows without WSL)", "sage2")]\
- + ([("Radial" + check("radial")+ ": x? faster but ? quality - requires Sparge & Sage 2 Attn (usually complex to set up on Windows without WSL)", "radial")] if args.betatest else [])\
- + [("Sage3" + check("sage3")+ ": x2 faster but worse quality - requires additional install (usually complex to set up on Windows without WSL)", "sage3")],
- value= attention_mode,
- label="Attention Type",
- interactive= not lock_ui_attention
- )
-
-
- 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)"
- )
-
- clear_file_list_choice = gr.Dropdown(
- choices=[
- ("None", 0),
- ("Keep the last video", 1),
- ("Keep the last 5 videos", 5),
- ("Keep the last 10 videos", 10),
- ("Keep the last 20 videos", 20),
- ("Keep the last 30 videos", 30),
- ],
- value=server_config.get("clear_file_list", 5),
- label="Keep Previously Generated Videos when starting a new Generation Batch"
- )
-
- display_stats_choice = gr.Dropdown(
- choices=[
- ("Disabled", 0),
- ("Enabled", 1),
- ],
- value=server_config.get("display_stats", 0),
- label="Display in real time available RAM / VRAM and other stats (needs a restart)"
- )
-
- max_frames_multiplier_choice = gr.Dropdown(
- choices=[
- ("Default", 1),
- ("x2", 2),
- ("x3", 3),
- ("x4", 4),
- ("x5", 5),
- ("x6", 7),
- ("x7", 7),
- ],
- value=server_config.get("max_frames_multiplier", 1),
- label="Increase the Max Number of Frames (needs more RAM and VRAM, usually the longer the worse the quality, needs an App restart)"
- )
- checkpoints_paths_text = "\n".join(server_config.get("checkpoints_paths", fl.default_checkpoints_paths))
- checkpoints_paths = gr.Text(label ="Folders where Model Checkpoints are Stored. One Path per Line. First Path is Default Download Path.", value=checkpoints_paths_text,lines=3)
-
- UI_theme_choice = gr.Dropdown(
- choices=[
- ("Blue Sky", "default"),
- ("Classic Gradio", "gradio"),
- ],
- value=server_config.get("UI_theme", "default"),
- label="User Interface Theme. You will need to restart the App the see new Theme."
- )
- queue_color_scheme_choice = gr.Dropdown(
- choices=[
- ("Pastel (Unique color for each item)", "pastel"),
- ("Alternating Grey Shades", "alternating_grey"),
- ],
- value=server_config.get("queue_color_scheme", "pastel"),
- label="Queue Color Scheme"
- )
-
- with gr.Tab("Performance"):
-
- quantization_choice = gr.Dropdown(
- choices=[
- ("Scaled Int8 Quantization (recommended)", "int8"),
- ("16 bits (no quantization)", "bf16"),
- ],
- value= transformer_quantization,
- label="Transformer Model Quantization Type (if available)",
- )
-
- transformer_dtype_policy_choice = gr.Dropdown(
- choices=[
- ("Best Supported Data Type by Hardware", ""),
- ("FP16", "fp16"),
- ("BF16", "bf16"),
- ],
- value= server_config.get("transformer_dtype_policy", ""),
- label="Transformer Data Type (if available)"
- )
-
- mixed_precision_choice = gr.Dropdown(
- choices=[
- ("16 bits only, requires less VRAM", "0"),
- ("Mixed 16 / 32 bits, slightly more VRAM needed but better Quality mainly for 1.3B models", "1"),
- ],
- value= server_config.get("mixed_precision", "0"),
- label="Transformer Engine Calculation"
+ )
-
- text_encoder_quantization_choice = gr.Dropdown(
- choices=[
- ("16 bits - unquantized text encoder, better quality uses more RAM", "bf16"),
- ("8 bits - quantized text encoder, slightly worse quality but uses less RAM", "int8"),
- ],
- value= text_encoder_quantization,
- label="Text Encoder model"
- )
-
- VAE_precision_choice = gr.Dropdown(
- choices=[
- ("16 bits, requires less VRAM and faster", "16"),
- ("32 bits, requires twice more VRAM and slower but recommended with Window Sliding", "32"),
- ],
- value= server_config.get("vae_precision", "16"),
- label="VAE Encoding / Decoding precision"
- )
-
- gr.Text("Beware: when restarting the server or changing a resolution or video duration, the first step of generation for a duration / resolution may last a few minutes due to recompilation", interactive= False, show_label= False )
- compile_choice = gr.Dropdown(
- choices=[
- ("On (requires to have Triton installed)", "transformer"),
- ("Off", "" ),
- ],
- value= compile,
- label="Compile Transformer : up to 10-20% faster, useful only if multiple gens at same frames no / resolution",
- interactive= not lock_ui_compile
- )
-
- depth_anything_v2_variant_choice = gr.Dropdown(
- choices=[
- ("Large (more precise but 2x slower)", "vitl"),
- ("Big (less precise, less VRAM needed but faster)", "vitb"),
- ],
- value= server_config.get("depth_anything_v2_variant", "vitl"),
- label="Depth Anything v2 Vace Preprocessor Model type",
- )
-
- vae_config_choice = gr.Dropdown(
- choices=[
- ("Auto", 0),
- ("Disabled (faster but may require up to 22 GB of VRAM)", 1),
- ("256 x 256 : If at least 8 GB of VRAM", 2),
- ("128 x 128 : If at least 6 GB of VRAM", 3),
- ],
- value= vae_config,
- label="VAE Tiling - reduce the high VRAM requirements for VAE decoding and VAE encoding (if enabled it will be slower)"
- )
-
- boost_choice = gr.Dropdown(
- choices=[
- # ("Auto (ON if Video longer than 5s)", 0),
- ("ON", 1),
- ("OFF", 2),
- ],
- value=boost,
- label="Boost: Give a 10% speedup without losing quality at the cost of a litle VRAM (up to 1GB at max frames and resolution)"
- )
-
- profile_choice = gr.Dropdown(
- choices = memory_profile_choices,
- value= default_profile,
- label="Profile (for power users only, not needed to change it)"
- )
- preload_in_VRAM_choice = gr.Slider(0, 40000, value=server_config.get("preload_in_VRAM", 0), step=100, label="Number of MB of Models that are Preloaded in VRAM (0 will use Profile default)")
-
- release_RAM_btn = gr.Button("Force Release RAM")
- release_RAM_btn.click(fn=release_RAM)
-
- with gr.Tab("Extensions"):
- enhancer_enabled_choice = gr.Dropdown(
- choices=[
- ("Off", 0),
- ("Florence 2 1.6B + LLava 3.2 3.5B", 1),
- ("Florence 2 1.6B + LLama Joy Caption (uncensored but needs more VRAM) 9,3B", 2),
- ],
- value=server_config.get("enhancer_enabled", 0),
- label="Prompt Enhancer (if enabled, from 8 GB to 14 GB of extra models will be downloaded)"
- )
-
- enhancer_mode_choice = gr.Dropdown(
- choices=[
- ("Automatically triggered when Generating a Video", 0),
- ("On Demand Only", 1),
- ],
- value=server_config.get("enhancer_mode", 0),
- label="Prompt Enhancer Usage"
- )
-
- mmaudio_enabled_choice = gr.Dropdown(
- choices=[
- ("Off", 0),
- ("Turned On but unloaded from RAM after usage", 1),
- ("Turned On and kept in RAM for fast loading", 2),
- ],
- value=server_config.get("mmaudio_enabled", 0),
- label="MMAudio (if enabled, 10 GB of extra models will be downloaded)"
- )
-
- with gr.Tab("Outputs"):
-
- video_output_codec_choice = gr.Dropdown(
- choices=[
- ("x265 Balanced Quality (CRF 28)", 'libx265_28'),
- ("x264 Balanced Quality (Level 8)", 'libx264_8'),
- ("x265 High Quality (CRF 8)", 'libx265_8'),
- ("x264 High Quality (Level 10)", 'libx264_10'),
- ("x264 Lossless", 'libx264_lossless'),
- ],
- value=server_config.get("video_output_codec", "libx264_8"),
- label="Video Codec to use"
- )
-
- image_output_codec_choice = gr.Dropdown(
- choices=[
- ("JPEG Quality 85", 'jpeg_85'),
- ("WEBP Quality 85", 'webp_85'),
- ("JPEG Quality 95", 'jpeg_95'),
- ("WEBP Quality 95", 'webp_95'),
- ("WEBP Lossless", 'webp_lossless'),
- ("PNG Lossless", 'png'),
- ],
- value=server_config.get("image_output_codec", "jpeg_95"),
- label="Image Codec to use"
- )
-
- audio_output_codec_choice = gr.Dropdown(
- choices=[
- ("AAC 128 kbit", 'aac_128'),
- ],
- value=server_config.get("audio_output_codec", "aac_128"),
- visible = False,
- 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)
- )
-
- image_save_path_choice = gr.Textbox(
- label="Output Folder for Generated Images (need to restart app to be taken into account)",
- value=server_config.get("image_save_path", image_save_path)
- )
-
-
- with gr.Tab("Notifications"):
- gr.Markdown("### Notification Settings")
- notification_sound_enabled_choice = gr.Dropdown(
- choices=[
- ("On", 1),
- ("Off", 0),
- ],
- value=server_config.get("notification_sound_enabled", 0),
- label="Notification Sound Enabled"
- )
-
- notification_sound_volume_choice = gr.Slider(
- minimum=0,
- maximum=100,
- value=server_config.get("notification_sound_volume", 50),
- step=5,
- label="Notification Sound Volume (0 = silent, 100 = very loud)"
- )
-
-
-
- msg = gr.Markdown()
- apply_btn = gr.Button("Apply Changes")
- apply_btn.click(
- fn=apply_changes,
- inputs=[
- state,
- transformer_types_choices,
- model_hierarchy_type_choice,
- transformer_dtype_policy_choice,
- text_encoder_quantization_choice,
- VAE_precision_choice,
- mixed_precision_choice,
- video_save_path_choice,
- image_save_path_choice,
- attention_choice,
- compile_choice,
- profile_choice,
- vae_config_choice,
- metadata_choice,
- quantization_choice,
- boost_choice,
- clear_file_list_choice,
- preload_model_policy_choice,
- UI_theme_choice,
- enhancer_enabled_choice,
- enhancer_mode_choice,
- mmaudio_enabled_choice,
- fit_canvas_choice,
- preload_in_VRAM_choice,
- depth_anything_v2_variant_choice,
- notification_sound_enabled_choice,
- notification_sound_volume_choice,
- max_frames_multiplier_choice,
- display_stats_choice,
- video_output_codec_choice,
- embed_source_images_choice,
- image_output_codec_choice,
- audio_output_codec_choice,
- resolution,
- checkpoints_paths,
- queue_color_scheme_choice,
- ],
- outputs= [msg , header, model_family, model_base_type_choice, model_choice, refresh_form_trigger]
- )
-
- def generate_about_tab():
- gr.Markdown("<H2>WanGP - AI Generative Models for the GPU Poor by <B>DeepBeepMeep</B> (<A HREF='https://github.com/deepbeepmeep/Wan2GP'>GitHub</A>)</H2>")
- gr.Markdown("Many thanks to:")
- gr.Markdown("- <B>Alibaba Wan Team</B> for the best open source video generators (https://github.com/Wan-Video/Wan2.1)")
- gr.Markdown("- <B>Alibaba Vace, Multitalk and Fun Teams</B> for their incredible control net models (https://github.com/ali-vilab/VACE), (https://github.com/MeiGen-AI/MultiTalk) and (https://huggingface.co/alibaba-pai/Wan2.2-Fun-A14B-InP) ")
- gr.Markdown("- <B>Tencent</B> for the impressive Hunyuan Video models (https://github.com/Tencent-Hunyuan/HunyuanVideo)")
- gr.Markdown("- <B>Blackforest Labs</B> for the innovative Flux image generators (https://github.com/black-forest-labs/flux)")
- gr.Markdown("- <B>Alibaba Qwen Team</B> for their state of the art Qwen Image generators (https://github.com/QwenLM/Qwen-Image)")
- gr.Markdown("- <B>Lightricks</B> for their super fast LTX Video models (https://github.com/Lightricks/LTX-Video)")
- gr.Markdown("- <B>Hugging Face</B> for providing hosting for the models and developing must have open source libraries such as Tranformers, Diffusers, Accelerate and Gradio (https://huggingface.co/)")
- gr.Markdown("<BR>Huge acknowledgments to these great open source projects used in WanGP:")
- gr.Markdown("- <B>Rife</B>: temporal upsampler (https://github.com/hzwer/ECCV2022-RIFE)")
- gr.Markdown("- <B>DwPose</B>: Open Pose extractor (https://github.com/IDEA-Research/DWPose)")
- gr.Markdown("- <B>DepthAnything</B> & <B>Midas</B>: Depth extractors (https://github.com/DepthAnything/Depth-Anything-V2) and (https://github.com/isl-org/MiDaS")
- gr.Markdown("- <B>Matanyone</B> and <B>SAM2</B>: Mask Generation (https://github.com/pq-yang/MatAnyone) and (https://github.com/facebookresearch/sam2)")
- gr.Markdown("- <B>Pyannote</B>: speaker diarization (https://github.com/pyannote/pyannote-audio)")
-
- gr.Markdown("<BR>Special thanks to the following people for their support:")
- gr.Markdown("- <B>Cocktail Peanuts</B> : QA dpand simple installation via Pinokio.computer")
- gr.Markdown("- <B>Tophness</B> : created (former) multi tabs and queuing frameworks")
- gr.Markdown("- <B>AmericanPresidentJimmyCarter</B> : added original support for Skip Layer Guidance")
- gr.Markdown("- <B>Remade_AI</B> : for their awesome Loras collection")
- gr.Markdown("- <B>Reevoy24</B> : for his repackaging / completing the documentation")
- gr.Markdown("- <B>Redtash1</B> : for designing the protype of the RAM / VRAM stats viewer")
-
- def generate_info_tab():
-
-
- with open("docs/VACE.md", "r", encoding="utf-8") as reader:
- vace= reader.read()
-
- with open("docs/MODELS.md", "r", encoding="utf-8") as reader:
- models = reader.read()
-
- with open("docs/LORAS.md", "r", encoding="utf-8") as reader:
- loras = reader.read()
-
- with open("docs/FINETUNES.md", "r", encoding="utf-8") as reader:
- finetunes = reader.read()
-
- with gr.Tabs() :
- with gr.Tab("Models", id="models"):
- gr.Markdown(models)
- with gr.Tab("Loras", id="loras"):
- gr.Markdown(loras)
- with gr.Tab("Vace", id="vace"):
- gr.Markdown(vace)
- with gr.Tab("Finetunes", id="finetunes"):
- gr.Markdown(finetunes)
-
def compact_name(family_name, model_name):
if model_name.startswith(family_name):
return model_name[len(family_name):].strip()
@@@ -9981,30 -9005,35 +9373,6 @@@ def change_model_base_types(state, cur
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, state, new_tab_no):
-def set_new_tab(tab_state, new_tab_no):
-- global vmc_event_handler
--
-- tab_video_mask_creator = 2
--
-- 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(state, False)
- vmc_event_handler(False)
-- elif new_tab_no == tab_video_mask_creator:
- if not download_shared_done:
- download_models()
- vmc_event_handler(state, True)
- 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)
-- tab_state["tab_no"] = new_tab_no
-- return gr.Tabs()
--
- def select_tab(tab_state, state, evt:gr.SelectData):
-def select_tab(tab_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, state, evt.index), saveform_trigger
- return set_new_tab(tab_state, evt.index), saveform_trigger
--
def get_js():
start_quit_timer_js = """
() => {
@@@ -10123,7 -9152,7 +9491,6 @@@
return start_quit_timer_js, cancel_quit_timer_js, trigger_zip_download_js, trigger_settings_download_js, click_brush_js
def create_ui():
-- global vmc_event_handler
css = """
.postprocess div,
.postprocess span,
@@@ -10673,72 -9554,12 +10040,65 @@@
stats_element = stats_app.get_gradio_element()
with gr.Row():
- ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger
- ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger, tab_components
- ) = generate_video_tab(model_family=model_family, model_base_type_choice= model_base_type_choice, model_choice=model_choice, header=header, main = main, main_tabs =main_tabs)
- app.finalize_ui_setup(globals(), tab_components)
++ ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger, generator_tab_components
+ ) = generate_video_tab(model_family=model_family, model_base_type_choice= model_base_type_choice, model_choice=model_choice, header=header, main = main, main_tabs =main_tabs, tab_id='generate')
+ with gr.Tab("Edit", id="edit") as edit_tab:
+ edit_title_md = gr.Markdown()
- edit_tab_components = generate_video_tab(
++ edit_tab_inputs, edit_tab_components = generate_video_tab(
+ update_form=False,
+ state_dict=state.value,
+ ui_defaults=get_default_settings(transformer_type),
+ model_family=model_family,
+ model_base_type_choice=model_base_type_choice,
+ model_choice=model_choice,
+ header=header,
+ main=main,
+ main_tabs=main_tabs,
+ tab_id='edit'
+ )
+ def fill_inputs_for_edit(state):
+ editing_task_index = state.get("editing_task_index", None)
+ if editing_task_index is None:
- return [gr.update()] + [gr.update()] * len(edit_tab_components)
++ return [gr.update()] + [gr.update()] * len(edit_tab_inputs)
+
+ gen = get_gen_info(state)
+ queue = gen.get("queue", [])
+ task_to_edit_index = editing_task_index + 1
+
+ if task_to_edit_index >= len(queue):
+ gr.Warning("Task to edit not found in queue.")
+ state["editing_task_index"] = None
- return [gr.update()] + [gr.update()] * len(edit_tab_components)
++ return [gr.update()] + [gr.update()] * len(edit_tab_inputs)
+
+ task = queue[task_to_edit_index]
+ ui_defaults = task['params'].copy()
+
+ prompt_text = task.get('prompt', 'Unknown Prompt')[:80]
+ edit_title_text = f"<div align='center'><h2 style=\"font-family: 'Segoe UI', Roboto, sans-serif;\">Editing <span style='color: #4A90E2; font-weight: 400; letter-spacing: 0.5px;'>'{prompt_text}'</span></h2></div>"
+
+ image_list_keys = ['image_start', 'image_end', 'image_refs']
+ for key in image_list_keys:
+ value = ui_defaults.get(key)
+ if value is not None and not isinstance(value, list):
+ ui_defaults[key] = [value]
+
+ if ui_defaults.get('model_type') != state["model_type"]:
+ gr.Warning(f"Editing a task for a different model ({ui_defaults.get('model_type')}). Some settings may not apply.")
+
+ return [edit_title_text] + generate_video_tab(update_form=True, state_dict=state, ui_defaults=ui_defaults)
+
+ edit_tab.select(
+ fn=fill_inputs_for_edit,
+ inputs=[state],
- outputs=[edit_title_md] + edit_tab_components
++ outputs=[edit_title_md] + edit_tab_inputs
+ )
- with gr.Tab("Guides", id="info") as info_tab:
- generate_info_tab()
- with gr.Tab("Video Mask Creator", id="video_mask_creator") as video_mask_creator:
- matanyone_app.display(main_tabs, tab_state, state, refresh_form_trigger, server_config, get_current_model_settings)
- if not args.lock_config:
- with gr.Tab("Downloads", id="downloads") as downloads_tab:
- generate_download_tab(lset_name, loras_choices, state)
- with gr.Tab("Configuration", id="configuration") as configuration_tab:
- generate_configuration_tab(state, main, header, model_family, model_base_type_choice, model_choice, resolution, refresh_form_trigger)
- with gr.Tab("About"):
- generate_about_tab()
++ globals()['main_tabs'] = main_tabs
++ globals()['refresh_form_trigger'] = refresh_form_trigger
++ globals()['save_form_trigger'] = save_form_trigger
++ globals()['state'] = state
++ app.finalize_ui_setup(globals(), [generator_tab_components, edit_tab_components])
if stats_app is not None:
stats_app.setup_events(main, state)
- main_tabs.select(fn=select_tab, inputs= [tab_state, state], outputs= [main_tabs, save_form_trigger], trigger_mode="multiple")
- main_tabs.select(fn=select_tab, inputs= [tab_state], outputs= [main_tabs, save_form_trigger], trigger_mode="multiple")
return main
if __name__ == "__main__":