Skip to content
Python

added tab targeting system for plugins, made lora multiplier ui plugin use it

Chris Malone55bdfe43a12c
diff --git a/plugins/wan2gp-lora-multipliers-ui/plugin.py b/plugins/wan2gp-lora-multipliers-ui/plugin.py
index 2674da6..806edf0 100644
--- a/plugins/wan2gp-lora-multipliers-ui/plugin.py
+++ b/plugins/wan2gp-lora-multipliers-ui/plugin.py
@@ -1,13 +1,15 @@
import gradio as gr
from shared.utils.plugins import WAN2GPPlugin
-import time
+import json
+import traceback
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.version = "1.0.9"
+ self.description = "Dynamically set lora multipliers with a fast, JavaScript-powered UI."
+ self.target_tabs = ['generate', 'edit']
self.request_component("loras_multipliers")
self.request_component("loras_choices")
self.request_component("guidance_phases")
@@ -15,338 +17,323 @@ class LoraMultipliersUIPlugin(WAN2GPPlugin):
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: 1em !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_state, split_lora_index=-1, rejoin_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 = list(current_split_counts_state)
-
- if split_lora_index == -1 and rejoin_lora_index == -1:
- 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 split_lora_index != -1:
- if new_split_counts[split_lora_index] < MAX_STEP_SPLITS:
- new_split_counts[split_lora_index] += 1
- elif rejoin_lora_index != -1:
- if new_split_counts[rejoin_lora_index] > 1:
- new_split_counts[rejoin_lora_index] -= 1 # Decrement instead of resetting
-
- 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[accelerator_loras_header] = gr.update(visible=show_accelerator_header and num_selected_loras > 0)
+ tab_id = components.get('__tab_id__', 'unknown_tab')
+
+ try:
+ loras_multipliers = components["loras_multipliers"]
+ loras_choices = components["loras_choices"]
+ guidance_phases = components["guidance_phases"]
+ num_inference_steps = components["num_inference_steps"]
+ main_ui_block = components["main"]
+
+ def create_and_wire_ui():
+ container_id = f"lora_multiplier_ui_container_{tab_id}"
+ update_btn_id = f"lora_mults_update_btn_{tab_id}"
+ hidden_input_id = f"lora_mults_hidden_input_{tab_id}"
+ js_renderer_func = f"wgpLoraUIRenderer_{tab_id}"
- 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[group_data["user_header"]] = gr.update(visible=show_user_header_here)
-
- ui_updates[group_data["main_group"]] = gr.update(visible=is_lora_visible)
+ css = f"""
+ <style>
+ #{container_id} {{ 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: 8px !important; background-color: var(--background-fill-secondary); }}
+ .lora-main-container .gr-row {{ margin-bottom: 8px; justify-content: space-between; align-items: center; }}
+ .lora-main-container .gr-row h3 {{ margin-top: 0; margin-bottom: 10;}}
+ .lora-step-split-container {{ border: 1px dashed var(--border-color-accent); border-radius: 6px; padding: 10px; margin-top: 8px; }}
+ .lora-slider-row {{ display: flex; gap: 16px; align-items: end; }}
+ .lora-main-container button, .lora-main-container .wgp-lora-button {{ padding: 4px 12px !important; font-size: 1em !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); border-radius: 4px; cursor: pointer; }}
+ .lora-main-container button:hover, .lora-main-container .wgp-lora-button:hover {{ background: var(--button-secondary-background-fill-hover); border-color: var(--button-secondary-border-color-hover); }}
+ .lora-section-header h3 {{ border-bottom: 1px solid var(--border-color-primary); padding-bottom: 4px; margin-top: 16px; margin-bottom: 8px; }}
+ #{container_id} > .lora-section-header:first-child h3 {{
+ margin-top: 0;
+ }}
+ .lora-main-container > h3:first-child {{ margin-top: 0; }}
+ .lora-slider-group {{ flex: 1; }}
+ .lora-slider-group label {{ display: block; color: var(--body-text-color); font-size: 0.9em; margin-bottom: 4px; }}
+ .lora-slider-group input[type=range] {{ width: 100%; }}
+ .hidden {{ display: none !important; }}
+ </style>
+ """
- if is_lora_visible:
- lora_name = selected_lora_indices[i]
- ui_updates[group_data["name"]] = gr.update(value=f"### {lora_name}")
-
- num_splits_for_this_lora = current_split_counts[i]
-
- ui_updates[group_data["split_button"]] = gr.update(visible=(num_splits_for_this_lora < MAX_STEP_SPLITS))
- ui_updates[group_data["rejoin_button"]] = gr.update(visible=(num_splits_for_this_lora > 1))
+ main_js_script = f"""
+ () => {{
+ const debounce = (func, delay) => {{
+ let timeout;
+ return (...args) => {{
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func.apply(this, args), delay);
+ }};
+ }};
+
+ const updatePythonTextbox = debounce(() => {{
+ const container = document.getElementById('{container_id}');
+ if (!container) return;
+
+ const loras = Array.from(container.querySelectorAll('.lora-main-container'));
+ const textboxStrings = [];
+
+ for (const loraEl of loras) {{
+ const splits = Array.from(loraEl.querySelectorAll('.lora-step-split-container'));
+ const loraStepStrings = [];
+ for (const splitEl of splits) {{
+ const sliders = Array.from(splitEl.querySelectorAll('input[type=range]'));
+ const phaseValues = sliders
+ .filter(s => !s.closest('.lora-slider-group').classList.contains('hidden'))
+ .map(s => {{
+ const val = parseFloat(s.value);
+ return val % 1 === 0 ? String(val) : val.toFixed(2).replace(/\\.?0+$/, '');
+ }});
+ if (phaseValues.length > 0) {{
+ loraStepStrings.push(phaseValues.join(';'));
+ }}
+ }}
+ if (loraStepStrings.length > 0) {{
+ textboxStrings.push(loraStepStrings.join(','));
+ }}
+ }}
+
+ const separatorIndex = parseInt(container.dataset.separatorIndex || '-1');
+ let finalString = "";
+ if (separatorIndex > 0 && separatorIndex <= textboxStrings.length) {{
+ const part1 = textboxStrings.slice(0, separatorIndex).join(' ');
+ const part2 = textboxStrings.slice(separatorIndex).join(' ');
+ finalString = part1 + '|' + part2;
+ }} else {{
+ finalString = textboxStrings.join(' ');
+ }}
- steps_and_phases_str = multipliers_per_lora[i] if i < len(multipliers_per_lora) else ""
- multipliers_per_step = steps_and_phases_str.split(',')
+ const hiddenInput = document.querySelector('#{hidden_input_id} textarea');
+ const updateButton = document.getElementById('{update_btn_id}');
+ if (hiddenInput && updateButton) {{
+ hiddenInput.value = finalString;
+ hiddenInput.dispatchEvent(new Event('input', {{ bubbles: true }}));
+ updateButton.click();
+ }}
+ }}, 200);
+
+ function createSlider(phase, value, isVisible) {{
+ const container = document.createElement('div');
+ container.className = 'lora-slider-group';
+ if (!isVisible) container.classList.add('hidden');
+ container.innerHTML = `<label>Phase ${{phase}}</label><input type="range" min="0" max="1" step="0.05" value="${{value}}">`;
+ container.querySelector('input[type="range"]').addEventListener('input', updatePythonTextbox);
+ return container;
+ }}
+
+ function createStepSplit(loraIndex, splitIndex, values, guidancePhases, stepText) {{
+ const splitContainer = document.createElement('div');
+ splitContainer.className = 'lora-step-split-container';
+ const sliderRow = document.createElement('div');
+ sliderRow.className = 'lora-slider-row';
+ const title = document.createElement('div');
+ title.className = 'lora-split-title';
+ title.innerHTML = `<strong>${{stepText}}</strong>`;
+ splitContainer.appendChild(title);
+ for (let i = 0; i < 3; i++) {{
+ const isVisible = (i + 1) <= guidancePhases;
+ const sliderValue = values[i] !== undefined ? values[i] : 1.0;
+ sliderRow.appendChild(createSlider(i + 1, sliderValue, isVisible));
+ }}
+ splitContainer.appendChild(sliderRow);
+ return splitContainer;
+ }}
+
+ function updateRejoinVisibility(loraContainer) {{
+ const splits = loraContainer.querySelectorAll('.lora-step-split-container');
+ const rejoinBtn = loraContainer.querySelector('.rejoin-btn');
+ if (rejoinBtn) {{ rejoinBtn.style.display = splits.length > 1 ? 'inline-block' : 'none'; }}
+ }}
+
+ function handleSplit(e) {{
+ const loraIndex = parseInt(e.target.dataset.loraIndex);
+ const loraContainer = document.getElementById(`lora-container-{tab_id}-${{loraIndex}}`);
+ const newSplit = createStepSplit(loraIndex, -1, [1.0, 1.0, 1.0], window.wgp_guidance_phases_{tab_id}, "");
+ loraContainer.appendChild(newSplit);
+ recalculateStepRanges(loraContainer);
+ updateRejoinVisibility(loraContainer);
+ updatePythonTextbox();
+ }}
+
+ function handleRejoin(e) {{
+ const loraIndex = parseInt(e.target.dataset.loraIndex);
+ const loraContainer = document.getElementById(`lora-container-{tab_id}-${{loraIndex}}`);
+ const splits = loraContainer.querySelectorAll('.lora-step-split-container');
+ if (splits.length > 1) {{
+ splits[splits.length - 1].remove();
+ recalculateStepRanges(loraContainer);
+ updateRejoinVisibility(loraContainer);
+ updatePythonTextbox();
+ }}
+ }}
+
+ function recalculateStepRanges(loraContainer) {{
+ const totalSteps = window.wgp_total_steps_{tab_id} || 1;
+ const splits = loraContainer.querySelectorAll('.lora-step-split-container');
+ const numSplits = splits.length;
+ if (numSplits === 0) return;
+ const stepsPerSplit = Math.floor(totalSteps / numSplits);
+ const remainder = totalSteps % numSplits;
+ let startStep = 0;
+ splits.forEach((split, i) => {{
+ const stepsInThisSplit = stepsPerSplit + (i < remainder ? 1 : 0);
+ const endStep = startStep + stepsInThisSplit;
+ const titleStrong = split.querySelector('.lora-split-title strong');
+ if(titleStrong) {{
+ const displayEnd = Math.max(startStep + 1, endStep);
+ titleStrong.textContent = `Steps ${{startStep + 1}} to ${{displayEnd}}`;
+ }}
+ startStep = endStep;
+ }});
+ }}
+
+ window.{js_renderer_func} = (jsonData) => {{
+ let data;
+ try {{ data = JSON.parse(jsonData); }} catch (e) {{ return; }}
+ if (!data) return;
+ const container = document.getElementById('{container_id}');
+ if (!container) return;
+ container.innerHTML = '';
+ window.wgp_guidance_phases_{tab_id} = data.guidance_phases;
+ window.wgp_total_steps_{tab_id} = data.total_steps;
+ container.dataset.separatorIndex = data.separator_index;
+
+ if(data.separator_index > 0 && data.loras.length > 0) {{
+ container.innerHTML += '<div class="lora-section-header"><h3>Accelerator LoRAs</h3></div>';
+ }}
+
+ data.loras.forEach((lora, i) => {{
+ if ((data.separator_index === -1 && i === 0) || data.separator_index === i) {{
+ container.innerHTML += '<div class="lora-section-header"><h3>User LoRAs</h3></div>';
+ }}
+ const loraContainer = document.createElement('div');
+ loraContainer.className = 'lora-main-container';
+ loraContainer.id = `lora-container-{tab_id}-${{i}}`;
+ loraContainer.innerHTML = `<div class="gr-row"><h3>${{lora.name}}</h3><div style="display:flex; gap: 8px;"><button class="wgp-lora-button split-btn" data-lora-index="${{i}}" type="button">Split Steps</button><button class="wgp-lora-button rejoin-btn" data-lora-index="${{i}}" type="button" style="display:none;">Rejoin Step</button></div></div>`;
+ lora.splits.forEach((split) => {{
+ loraContainer.appendChild(createStepSplit(i, -1, split.values, data.guidance_phases, ""));
+ }});
+ container.appendChild(loraContainer);
+ recalculateStepRanges(loraContainer);
+ updateRejoinVisibility(loraContainer);
+ loraContainer.querySelector('.split-btn').addEventListener('click', handleSplit);
+ loraContainer.querySelector('.rejoin-btn').addEventListener('click', handleRejoin);
+ }});
+ }};
+ }}
+ """
+
+ def update_ui_data_from_python(selected_lora_names, multipliers_str, guidance_phases_val, total_steps):
+ try:
+ lora_names = selected_lora_names if selected_lora_names else []
+ num_selected_loras = len(lora_names)
+
+ all_stale_multipliers = [s for s in (multipliers_str or "").replace('|', ' ').split(' ') if s]
+ num_stale_multipliers = len(all_stale_multipliers)
- steps_per_split_base = total_steps
- remainder = total_steps % num_splits_for_this_lora
- start_step = 0
+ is_desynced = num_selected_loras != num_stale_multipliers
- for j in range(MAX_STEP_SPLITS):
- split_data = group_data["splits"][j]
- is_split_visible = j < num_splits_for_this_lora
- 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[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
-
- 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[split_data["sliders"][k]] = gr.update(visible=is_slider_visible, value=phase_value)
- all_slider_values_flat.append(phase_value)
+ original_accelerator_count = 0
+ if multipliers_str and '|' in multipliers_str:
+ parts = multipliers_str.split('|')
+ original_accelerator_count = len([s for s in parts[0].split(' ') if s])
+
+ if is_desynced:
+ multipliers_per_lora_str = ["1.0"] * num_selected_loras
+ num_removed = num_stale_multipliers - num_selected_loras
+ if num_removed > 0:
+ new_separator_index = original_accelerator_count - num_removed
else:
- all_slider_values_flat.extend([1.0] * 3)
- else:
- ui_updates[group_data["split_button"]] = gr.update(visible=False)
- ui_updates[group_data["rejoin_button"]] = 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 num_selected_loras < effective_separator_index:
- effective_separator_index = -1
-
- 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
- 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()
- with gr.Row():
- split_steps_btn = gr.Button("Split Steps")
- rejoin_steps_btn = gr.Button("Rejoin Step", visible=False)
-
- 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] })
+ new_separator_index = original_accelerator_count
+
+ if new_separator_index <= 0 or new_separator_index >= num_selected_loras:
+ new_separator_index = -1
+
+ else:
+ multipliers_per_lora_str = all_stale_multipliers
+ new_separator_index = original_accelerator_count if original_accelerator_count > 0 else -1
+
+ loras_data = []
+ for i, lora_name in enumerate(lora_names):
+ lora_obj = {"name": lora_name, "splits": []}
+ steps_and_phases_str = multipliers_per_lora_str[i]
- lora_slider_ui_groups.append({
- "main_group": lora_main_group,
- "name": lora_name_md,
- "split_button": split_steps_btn,
- "rejoin_button": rejoin_steps_btn,
- "splits": split_groups,
- "user_header": user_loras_header
- })
-
- slider_ui_outputs_flat = []
- all_sliders_flat = []
- slider_ui_outputs_flat.append(accelerator_loras_header)
- for group in lora_slider_ui_groups:
- slider_ui_outputs_flat.append(group["user_header"])
- slider_ui_outputs_flat.extend([group["main_group"], group["name"], group["split_button"], group["rejoin_button"]])
- for split in group["splits"]:
- slider_ui_outputs_flat.extend([split["group"], split["title"], *split["sliders"]])
- all_sliders_flat.extend(split["sliders"])
-
- 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=unpack_dict_updates_fn,
- inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts, gr.State(-1), gr.State(-1)],
- outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
+ for step_str in steps_and_phases_str.split(','):
+ phase_values = []
+ phase_strs = step_str.split(';')
+ for k in range(3):
+ try:
+ phase_values.append(float(phase_strs[k]))
+ except (ValueError, IndexError):
+ phase_values.append(1.0)
+ lora_obj["splits"].append({"values": phase_values})
+ loras_data.append(lora_obj)
+
+ payload = {
+ "loras": loras_data,
+ "guidance_phases": guidance_phases_val,
+ "total_steps": total_steps or 1,
+ "separator_index": new_separator_index,
+ }
+
+ return json.dumps(payload)
+ except Exception:
+ traceback.print_exc()
+ return "{}"
+
+ def update_textbox_from_js(new_value):
+ return gr.update(value=new_value)
+
+ with gr.Accordion("Dynamic Lora Multipliers", open=True) as main_accordion:
+ gr.HTML(value=css)
+ gr.HTML(f"<div id='{container_id}'></div>")
+
+ with gr.Row(visible=False):
+ hidden_input = gr.Text(elem_id=hidden_input_id)
+ update_button = gr.Button(elem_id=update_btn_id)
+
+ ui_data_json = gr.Text(elem_id=f"ui_data_json_{tab_id}", visible=False)
+
+ main_ui_block.load(fn=None, js=main_js_script)
+
+ ui_data_json.change(
+ fn=None,
+ inputs=[ui_data_json],
+ js=f"(jsonData) => {{ if(window.{js_renderer_func}) window.{js_renderer_func}(jsonData); }}",
show_progress="hidden"
)
- for i, group in enumerate(lora_slider_ui_groups):
- group["split_button"].click(
- fn=unpack_dict_updates_fn,
- inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts, gr.State(i), gr.State(-1)],
- outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
+ input_components = [loras_choices, loras_multipliers, guidance_phases, num_inference_steps]
+
+ main_ui_block.load(
+ fn=update_ui_data_from_python,
+ inputs=input_components,
+ outputs=[ui_data_json],
show_progress="hidden"
)
- group["rejoin_button"].click(
- fn=unpack_dict_updates_fn,
- inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts, gr.State(-1), gr.State(i)],
- outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
+
+ events_to_trigger = [loras_choices.change, guidance_phases.change, num_inference_steps.change, loras_multipliers.blur]
+ for event_fn in events_to_trigger:
+ event_fn(
+ fn=update_ui_data_from_python,
+ inputs=input_components,
+ outputs=[ui_data_json],
+ show_progress="hidden"
+ )
+
+ update_button.click(
+ fn=update_textbox_from_js,
+ inputs=[hidden_input],
+ outputs=[loras_multipliers],
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"
- )
+ return main_accordion
- for slider in all_sliders_flat:
- 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=unpack_dict_updates_fn,
- inputs=[loras_choices, guidance_phases, loras_multipliers, num_inference_steps, lora_split_counts, gr.State(-1), gr.State(-1)],
- outputs=[lora_separator_index, lora_split_counts, loras_multipliers] + slider_ui_outputs_flat,
- show_progress="hidden"
+ self.insert_after(
+ target_component_id="loras_multipliers",
+ new_component_constructor=create_and_wire_ui
)
-
- 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)
- }
\ No newline at end of file
+ except Exception:
+ traceback.print_exc()
+
+ return {}
\ No newline at end of file
diff --git a/shared/utils/plugins.py b/shared/utils/plugins.py
index 3481c32..f04fd0d 100644
--- a/shared/utils/plugins.py
+++ b/shared/utils/plugins.py
@@ -44,6 +44,7 @@ class WAN2GPPlugin:
self._setup_complete = False
self._data_hooks: Dict[str, List[callable]] = {}
self.tab_ids: List[str] = []
+ self.target_tabs: Optional[List[str]] = None
def setup_ui(self) -> None:
pass
@@ -90,9 +91,6 @@ class WAN2GPPlugin:
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"):
@@ -262,7 +260,12 @@ class PluginManager:
if plugin_dir_name not in plugins_to_load:
continue
try:
- module = importlib.import_module(f"{plugin_dir_name}.plugin")
+ # Reload the module to pick up code changes without restarting the whole app
+ module_name = f"{plugin_dir_name}.plugin"
+ if module_name in sys.modules:
+ importlib.reload(sys.modules[module_name])
+
+ module = importlib.import_module(module_name)
for name, obj in inspect.getmembers(module, inspect.isclass):
if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:
@@ -324,61 +327,75 @@ class PluginManager:
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] = []
+ def run_post_ui_setup(self, all_tab_components: List[Dict[str, Any]]) -> None:
+ for tab_components in all_tab_components:
+ tab_id = tab_components.get('__tab_id__')
+ if not tab_id:
+ print("[PluginManager] WARNING: A tab component dictionary is missing '__tab_id__'. Skipping.")
+ continue
- 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', []))
-
- except Exception as e:
- print(f"[PluginManager] Error in post_ui_setup for {plugin_id}: {str(e)}")
- traceback.print_exc()
+ tab_insert_requests: List[InsertAfterRequest] = []
+
+ for plugin_id, plugin in self.plugins.items():
+ target_tabs = getattr(plugin, 'target_tabs', None)
+ if target_tabs is not None and tab_id not in target_tabs:
+ continue
- if all_insert_requests:
- for request in all_insert_requests:
+ if not all(comp_id in tab_components for comp_id in plugin.component_requests):
+ continue
+
+ original_attrs = {}
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.")
- continue
-
- target_index = parent.children.index(target)
- with parent:
- new_component = request.new_component_constructor()
+ # Temporarily set attributes for the current tab's context
+ for comp_id in plugin.component_requests:
+ if hasattr(plugin, comp_id):
+ original_attrs[comp_id] = getattr(plugin, comp_id)
+ setattr(plugin, comp_id, tab_components[comp_id])
+
+ requested_components = { comp_id: tab_components[comp_id] for comp_id in plugin.component_requests }
+ requested_components['__tab_id__'] = tab_id
+
+ plugin._insert_after_requests = []
+ plugin.post_ui_setup(requested_components)
+ tab_insert_requests.extend(getattr(plugin, '_insert_after_requests', []))
- 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)}")
+ print(f"[PluginManager] Error in post_ui_setup for {plugin_id} on tab '{tab_id}': {str(e)}")
+ traceback.print_exc()
+ finally:
+ # Clean up attributes to prevent state leakage
+ for comp_id in plugin.component_requests:
+ if hasattr(plugin, comp_id):
+ delattr(plugin, comp_id)
+ # Restore any original attributes that were overwritten
+ for comp_id, value in original_attrs.items():
+ setattr(plugin, comp_id, value)
+
+ if tab_insert_requests:
+ for request in tab_insert_requests:
+ try:
+ target = tab_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 on tab '{tab_id}': Target '{request.target_component_id}' for insertion not found or invalid.")
+ 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}' on tab '{tab_id}'")
+
+ except Exception as e:
+ print(f"[PluginManager] Error processing insert_after for {request.target_component_id} on tab '{tab_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:
@@ -388,10 +405,7 @@ class WAN2GPApplication:
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))
- }
+
loaded_plugins = self.plugin_manager.get_all_plugins()
system_tabs = []
@@ -425,14 +439,14 @@ class WAN2GPApplication:
with gr.Tab(tab_info['label'], id=f"plugin_{tab_info['id']}"):
tab_info['component_constructor']()
- def _handle_tab_selection(self, state: dict, selected_tab_id: str, evt: gr.SelectData): # Add this new method
+ def _handle_tab_selection(self, state: dict, evt: gr.SelectData):
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 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]
@@ -451,13 +465,19 @@ class WAN2GPApplication:
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: Dict[str, Any]):
+ def finalize_ui_setup(self, main_module_globals: Dict[str, Any], all_tab_components: 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))
- }
+
+ main_tabs = main_module_globals.get('main_tabs')
+ state = main_module_globals.get('state')
+ if main_tabs and state:
+ main_tabs.select(
+ self._handle_tab_selection,
+ inputs=[state],
+ outputs=None,
+ show_progress="hidden"
+ )
+
if self.plugin_manager:
- self.plugin_manager.run_post_ui_setup(self.ui_components)
\ No newline at end of file
+ self.plugin_manager.run_post_ui_setup(all_tab_components)
\ No newline at end of file
diff --git a/wgp.py b/wgp.py
index 01eb373..3231317 100644
--- a/wgp.py
+++ b/wgp.py
@@ -9121,7 +9121,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
inputs=None,
outputs=[current_gen_column, queue_accordion]
)
-
+ locals()['__tab_id__'] = tab_id
return locals()
def compact_name(family_name, model_name):
@@ -10035,6 +10035,7 @@ def create_ui():
cancel_btn.click(fn=cancel_edit, inputs=[state], outputs=[main_tabs, edit_tab])
silent_cancel_btn.click(fn=silent_cancel_edit, inputs=[state], outputs=[main_tabs, js_trigger_index, edit_tab])
+
generator_tab_components['queue_action_trigger'].click(
fn=handle_queue_action,
inputs=[generator_tab_components['state'], generator_tab_components['queue_action_input']],
@@ -10045,7 +10046,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)
+ app.finalize_ui_setup(globals(), [generator_tab_components, edit_tab_components])
if stats_app is not None:
stats_app.setup_events(main, state)
return main