Skip to content
Python

improve performance of plugin system and plugins

Chris Maloneaa0bcf3e88bd
diff --git a/plugins/wan2gp-gallery/plugin.py b/plugins/wan2gp-gallery/plugin.py
index 3be9ee7..ce0f8a9 100644
--- a/plugins/wan2gp-gallery/plugin.py
+++ b/plugins/wan2gp-gallery/plugin.py
@@ -149,29 +149,69 @@ class GalleryPlugin(WAN2GPPlugin):
sliderContainer.addEventListener('touchend', handleInteractionEnd);
}
- const observer = new MutationObserver((mutationsList) => {
- for(const mutation of mutationsList) {
- if (mutation.type === 'childList') {
- document.querySelectorAll('.video-joiner-player').forEach(player => {
- if (!player.dataset.initialized) {
- const containerId = player.id;
- const { sliderId, fps } = player.dataset;
- if (containerId && sliderId && !isNaN(parseFloat(fps))) {
- setupVideoFrameSeeker(containerId, sliderId, parseFloat(fps));
- player.dataset.initialized = 'true';
- }
+ function setupScopedObserver(observerName, rootSelector, targetSelector, callback) {
+ if (!window.scopedObservers) {
+ window.scopedObservers = new Map();
+ }
+ if (window.scopedObservers.has(observerName)) {
+ return;
+ }
+
+ const startObserving = () => {
+ const rootElement = document.querySelector(rootSelector);
+ if (!rootElement) {
+ // Retry if the root element isn't available yet (e.g., during Gradio startup).
+ setTimeout(startObserving, 250);
+ return;
+ }
+
+ const processNode = (node) => {
+ if (node.matches && node.matches(targetSelector)) {
+ callback(node);
+ }
+ if (node.querySelectorAll) {
+ node.querySelectorAll(targetSelector).forEach(callback);
+ }
+ };
+
+ processNode(rootElement);
+
+ const observer = new MutationObserver((mutationsList) => {
+ for (const mutation of mutationsList) {
+ if (mutation.type === 'childList') {
+ mutation.addedNodes.forEach(processNode);
}
- });
+ }
+ });
+
+ observer.observe(rootElement, { childList: true, subtree: true });
+ window.scopedObservers.set(observerName, observer);
+ };
+
+ startObserving();
+ }
+
+ setupScopedObserver(
+ 'GalleryVideoSeeker',
+ '#gallery_tab_container',
+ '.video-joiner-player',
+ (playerNode) => {
+ if (!playerNode.dataset.initialized) {
+ const containerId = playerNode.id;
+ const { sliderId, fps } = playerNode.dataset;
+ if (containerId && sliderId && !isNaN(parseFloat(fps))) {
+ setupVideoFrameSeeker(containerId, sliderId, parseFloat(fps));
+ playerNode.dataset.initialized = 'true';
+ }
}
}
- });
- observer.observe(document.body, { childList: true, subtree: true });
+ );
}
"""
with gr.Blocks() as gallery_blocks:
gr.HTML(value=f"<style>{css}</style>")
gallery_blocks.load(fn=None, js=js)
- with gr.Column():
+ with gr.Column(elem_id="gallery_tab_container"):
with gr.Row():
self.refresh_gallery_files_btn = gr.Button("Refresh Files")
with gr.Row(elem_id="gallery-layout"):
diff --git a/plugins/wan2gp-lora-multipliers-ui/plugin.py b/plugins/wan2gp-lora-multipliers-ui/plugin.py
index 5f3a77d..5cd15d8 100644
--- a/plugins/wan2gp-lora-multipliers-ui/plugin.py
+++ b/plugins/wan2gp-lora-multipliers-ui/plugin.py
@@ -1,5 +1,6 @@
import gradio as gr
from shared.utils.plugins import WAN2GPPlugin
+import time
class LoraMultipliersUIPlugin(WAN2GPPlugin):
def __init__(self):
@@ -142,43 +143,48 @@ class LoraMultipliersUIPlugin(WAN2GPPlugin):
new_split_counts[triggered_lora_index] += 1
current_split_counts = new_split_counts
- ui_updates = []
+
+ 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))
-
+ ui_updates[accelerator_loras_header] = gr.update(visible=show_accelerator_header and num_selected_loras > 0)
+
for i in range(MAX_LORA_SLIDERS):
+ group_data = lora_slider_ui_groups[i]
+ is_lora_visible = i < num_selected_loras
+
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))
+ ui_updates[group_data["user_header"]] = gr.update(visible=show_user_header_here)
+ ui_updates[group_data["main_group"]] = 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}"))
+ ui_updates[group_data["name"]] = 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):
+ split_data = group_data["splits"][j]
is_split_visible = j < num_splits_for_this_lora
- ui_updates.append(gr.update(visible=is_split_visible))
+ ui_updates[split_data["group"]] = 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))
+ ui_updates[split_data["title"]] = gr.update(value=step_title)
multipliers_per_phase = multipliers_per_step[j].split(';') if j < len(multipliers_per_step) else ['1.0'] * 3
@@ -187,24 +193,19 @@ class LoraMultipliersUIPlugin(WAN2GPPlugin):
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))
+ ui_updates[split_data["sliders"][k]] = 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 * MAX_STEP_SPLITS)
effective_separator_index = separator_index
- if effective_separator_index != -1 and len(selected_lora_indices) < effective_separator_index:
+ if effective_separator_index != -1 and num_selected_loras < 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
+ new_textbox_value = _build_multipliers_string(num_selected_loras, 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
@@ -248,30 +249,40 @@ class LoraMultipliersUIPlugin(WAN2GPPlugin):
"user_header": user_loras_header
})
- slider_ui_outputs = []
+ slider_ui_outputs_flat = []
all_sliders_flat = []
- slider_ui_outputs.append(accelerator_loras_header)
+ slider_ui_outputs_flat.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"]])
+ slider_ui_outputs_flat.append(group["user_header"])
+ slider_ui_outputs_flat.extend([group["main_group"], group["name"]])
for split in group["splits"]:
- slider_ui_outputs.extend([split["group"], split["title"], *split["sliders"]])
+ slider_ui_outputs_flat.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, loras_multipliers.change]
+ def unpack_dict_updates_fn(*args, **kwargs):
+ state_outs_and_dict = update_slider_ui_and_textbox(*args, **kwargs)
+ states = state_outs_and_dict[:-1]
+ updates_dict = state_outs_and_dict[-1]
+
+ unpacked_list = []
+ for component in slider_ui_outputs_flat:
+ unpacked_list.append(updates_dict.get(component, gr.update()))
+ return states + unpacked_list
+
+ events_to_trigger_ui_update = [loras_choices.change, guidance_phases.change, num_inference_steps.change, loras_multipliers.blur]
for event in events_to_trigger_ui_update:
event(
- fn=update_slider_ui_and_textbox,
+ fn=unpack_dict_updates_fn,
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,
+ outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
show_progress="hidden"
)
for i, group in enumerate(lora_slider_ui_groups):
group["split_button"].click(
- fn=update_slider_ui_and_textbox,
+ fn=unpack_dict_updates_fn,
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,
+ outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
show_progress="hidden"
)
@@ -283,12 +294,29 @@ class LoraMultipliersUIPlugin(WAN2GPPlugin):
)
for slider in all_sliders_flat:
- slider.release(fn=None, js="() => { document.getElementById('lora_mults_update_btn').click() }")
+ slider.release(fn=None, js="""
+ () => {
+ if (!window.wgpLoraUIDebouncedUpdate) {
+ const debounce = (func, delay) => {
+ let timeout;
+ return (...args) => {
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func.apply(this, args), delay);
+ };
+ };
+ window.wgpLoraUIDebouncedUpdate = debounce(() => {
+ const btn = document.getElementById('lora_mults_update_btn');
+ if (btn) btn.click();
+ }, 200);
+ }
+ window.wgpLoraUIDebouncedUpdate();
+ }
+ """)
main_ui_block.load(
- fn=update_slider_ui_and_textbox,
+ fn=unpack_dict_updates_fn,
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,
+ outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
show_progress="hidden"
)
diff --git a/shared/utils/plugins.py b/shared/utils/plugins.py
index cd5e69c..14c5ed1 100644
--- a/shared/utils/plugins.py
+++ b/shared/utils/plugins.py
@@ -50,8 +50,9 @@ class WAN2GPPlugin:
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 post_ui_setup(self, components: Dict[str, gr.components.Component]) -> Dict[gr.components.Component, Union[gr.update, Any]]:
+ return {}
def on_tab_select(self, state: Dict[str, Any]) -> None:
pass
@@ -323,6 +324,14 @@ class PluginManager:
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():
@@ -337,9 +346,7 @@ class PluginManager:
if comp_id in all_components
}
plugin.post_ui_setup(requested_components)
- if hasattr(plugin, '_insert_after_requests'):
- all_insert_requests.extend(plugin._insert_after_requests)
- plugin._insert_after_requests.clear()
+ all_insert_requests.extend(getattr(plugin, '_insert_after_requests', []))
except Exception as e:
print(f"[PluginManager] Error in post_ui_setup for {plugin_id}: {str(e)}")
@@ -351,7 +358,7 @@ class PluginManager:
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] WARNING: Target '{request.target_component_id}' for insertion not found in the current UI tab context. Skipping.")
+ print(f"[PluginManager] ERROR: Target '{request.target_component_id}' for insertion not found or invalid.")
continue
target_index = parent.children.index(target)
@@ -384,11 +391,6 @@ class WAN2GPApplication:
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 = []
@@ -419,9 +421,8 @@ class WAN2GPApplication:
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']}") as rendered_tab:
+ with gr.Tab(tab_info['label'], id=f"plugin_{tab_info['id']}"):
tab_info['component_constructor']()
- self.all_rendered_tabs.append(rendered_tab)
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'):
@@ -430,7 +431,7 @@ class WAN2GPApplication:
new_tab_id = evt.value
if self.previous_tab_id == new_tab_id:
- return
+ return new_tab_id
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]
@@ -451,25 +452,11 @@ class WAN2GPApplication:
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]]):
+ def finalize_ui_setup(self, main_module_globals: Dict[str, Any], all_ui_components: Dict[str, Any]):
self._create_plugin_tabs(main_module_globals)
-
- 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)
\ No newline at end of file
+ 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)
\ No newline at end of file
diff --git a/wgp.py b/wgp.py
index c7d8129..4582453 100644
--- a/wgp.py
+++ b/wgp.py
@@ -9169,7 +9169,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
if tab_id == 'edit':
locals_dict = locals()
gen_inputs = [locals_dict[k] for k in inputs_names] + [state] + extra_inputs
- return gen_inputs, locals()
+ return gen_inputs
else:
return ( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger, locals(),
# video_guide, image_guide, video_mask, image_mask, image_refs,
@@ -10008,8 +10008,7 @@ def create_ui():
if (path.some(hit)) e.stopImmediatePropagation();
}, { capture: true, passive: true });
- }
-
+ }
"""
if server_config.get("display_stats", 0) == 1:
from shared.utils.stats import SystemStatsApp
@@ -10044,7 +10043,7 @@ def create_ui():
) = 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_inputs, edit_tab_components = generate_video_tab(
+ edit_tab_inputs = generate_video_tab(
update_form=False,
state_dict=state.value,
ui_defaults=get_default_settings(transformer_type),
@@ -10096,7 +10095,7 @@ def create_ui():
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])
+ app.finalize_ui_setup(globals(), generator_tab_components)
if stats_app is not None:
stats_app.setup_events(main, state)
return main