Python
move plugin manager tab and functionality from wgp.py to a plugin
Chris Malonef4e7b004b68b
diff --git a/plugins/wan2gp-plugin-manager/__init__.py b/plugins/wan2gp-plugin-manager/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/plugins/wan2gp-plugin-manager/plugin.py b/plugins/wan2gp-plugin-manager/plugin.pynew file mode 100644index 0000000..1586bfd--- /dev/null+++ b/plugins/wan2gp-plugin-manager/plugin.py@@ -0,0 +1,240 @@+import gradio as gr+from shared.utils.plugins import WAN2GPPlugin+import os+import json+import traceback+from wgp import quit_application++class PluginManagerUIPlugin(WAN2GPPlugin):+ def __init__(self):+ super().__init__()+ self.name = "Plugin Manager UI"+ self.version = "1.4.3"++ def setup_ui(self):+ self.request_global("app")+ self.request_global("server_config")+ self.request_global("server_config_filename")+ self.request_component("main")++ self.add_tab(+ tab_id="plugin_manager_tab",+ label="Plugins",+ component_constructor=self.create_plugin_manager_ui,+ position=2+ )++ def _get_js_script_html(self):+ js_code = """+ () => {+ function updateGradioInput(elem_id, value) {+ const gradio_app = document.querySelector('gradio-app') || document;+ const input = gradio_app.querySelector(`#${elem_id} textarea`);+ if (input) {+ input.value = value;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ return true;+ }+ return false;+ }++ window.handlePluginAction = function(button, action) {+ const pluginItem = button.closest('.plugin-item');+ const pluginId = pluginItem.dataset.pluginId;+ const payload = JSON.stringify({ action: action, plugin_id: pluginId });+ updateGradioInput('plugin_action_input', payload);+ };++ window.handleSave = function(restart) {+ const container = document.querySelector('.plugin-list');+ if (!container) return;+ const checkboxes = container.querySelectorAll('.plugin-enable-checkbox:checked');+ const enabledIds = Array.from(checkboxes).map(cb => cb.closest('.plugin-item').dataset.pluginId);++ const payload = JSON.stringify({ restart: restart, enabled_plugins: enabledIds });+ updateGradioInput('save_action_input', payload);+ };+ }+ """+ return f"{js_code}"++ def _build_plugins_html(self):+ plugins_info = self.app.plugin_manager.get_plugins_info()+ enabled_plugins = self.server_config.get("enabled_plugins", [])++ if not plugins_info:+ return "<p style='text-align:center; color: var(--text-color-secondary);'>No plugins found.</p>"++ items_html = ""+ for plugin in plugins_info:+ plugin_id = plugin['id']+ checked = "checked" if plugin_id in enabled_plugins else ""+ items_html += f"""+ <div class="plugin-item" data-plugin-id="{plugin_id}">+ <div class="plugin-info-container">+ <input type="checkbox" class="plugin-enable-checkbox" {checked}>+ <div class="plugin-item-info">+ <span class="name">{plugin['name']}</span>+ <span class="version">version {plugin['version']} (id: {plugin_id})</span>+ </div>+ </div>+ <div class="plugin-item-actions">+ <button class="plugin-action-btn" onclick="handlePluginAction(this, 'update')">Update</button>+ <button class="plugin-action-btn" onclick="handlePluginAction(this, 'reinstall')">Reinstall</button>+ <button class="plugin-action-btn" onclick="handlePluginAction(this, 'uninstall')">Uninstall</button>+ </div>+ </div>+ """++ css = """+ <style>+ .plugin-list { display: flex; flex-direction: column; gap: 12px; }+ .plugin-item { display: flex; flex-wrap: wrap; gap: 12px; justify-content: space-between; align-items: center; padding: 16px; border: 1px solid var(--border-color-primary); border-radius: 12px; background-color: var(--background-fill-secondary); transition: box-shadow 0.2s ease-in-out; }+ .plugin-item:hover { box-shadow: var(--shadow-drop-lg); }+ .plugin-info-container { display: flex; align-items: center; gap: 16px; flex-grow: 1; }+ .plugin-item-info { display: flex; flex-direction: column; gap: 2px; }+ .plugin-item-info .name { font-weight: 600; font-size: 1.1em; color: var(--text-color-primary); font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', sans-serif; }+ .plugin-item-info .version { font-size: 0.9em; color: var(--text-color-secondary); }+ .plugin-item-actions { display: flex; gap: 8px; flex-shrink: 0; align-items: center; }+ .plugin-action-btn { display: inline-flex; align-items: center; justify-content: center; margin: 0 !important; border: 1px solid var(--button-secondary-border-color, #ccc) !important; background: var(--button-secondary-background-fill, #f0f0f0) !important; color: var(--button-secondary-text-color) !important; padding: 4px 12px !important; border-radius: 4px !important; cursor: pointer; font-weight: 500; }+ .plugin-action-btn:hover { background: var(--button-secondary-background-fill-hover, #e0e0e0) !important; transform: translateY(-1px); box-shadow: var(--shadow-drop); }+ .plugin-enable-checkbox { -webkit-appearance: none; appearance: none; position: relative; width: 22px; height: 22px; border-radius: 4px; border: 2px solid var(--border-color-primary); background-color: var(--background-fill-primary); cursor: pointer; display: inline-block; vertical-align: middle; box-sizing: border-box; transition: all 0.2s ease; }+ .plugin-enable-checkbox:hover { border-color: var(--color-accent); }+ .plugin-enable-checkbox:checked { background-color: var(--color-accent); border-color: var(--color-accent); }+ .plugin-enable-checkbox:checked::after { content: '✔'; position: absolute; color: white; font-size: 16px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%); }+ .save-buttons-container { justify-content: flex-start; margin-top: 20px !important; gap: 12px; }+ .stylish-save-btn { font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', sans-serif !important; font-weight: 600 !important; font-size: 1.05em !important; padding: 10px 20px !important; }+ </style>+ """++ return f"{css}<div class='plugin-list'>{items_html}</div>"++ def create_plugin_manager_ui(self):+ with gr.Blocks() as plugin_blocks:+ with gr.Row(equal_height=False, variant='panel'):+ with gr.Column(scale=2, min_width=600):+ gr.Markdown("### Installed Plugins")+ self.plugins_html_display = gr.HTML(self._build_plugins_html)+ with gr.Row(elem_classes="save-buttons-container"):+ self.save_plugins_button = gr.Button("Save", variant="secondary", size="sm", scale=0, elem_classes="stylish-save-btn")+ self.save_and_restart_button = gr.Button("Save and Restart", variant="primary", size="sm", scale=0, elem_classes="stylish-save-btn")+ with gr.Column(scale=2, min_width=300):+ gr.Markdown("### Install New Plugin")+ gr.Markdown("Enter the URL of a GitHub repository containing a Wan2GP plugin.")+ with gr.Group():+ self.plugin_url_textbox = gr.Textbox(label="GitHub URL", placeholder="https://github.com/user/wan2gp-plugin-repo")+ self.install_plugin_button = gr.Button("Download and Install")+ with gr.Column(visible=False):+ self.plugin_action_input = gr.Textbox(elem_id="plugin_action_input")+ self.save_action_input = gr.Textbox(elem_id="save_action_input")++ return plugin_blocks++ def _refresh_ui(self):+ return gr.update(value=self._build_plugins_html())++ def _save_plugin_settings(self, enabled_plugins: list):+ self.server_config["enabled_plugins"] = enabled_plugins+ with open(self.server_config_filename, "w", encoding="utf-8") as writer:+ writer.write(json.dumps(self.server_config, indent=4))+ gr.Info("Plugin settings saved. Please restart WanGP for changes to take effect.")+ return self._refresh_ui()++ def _save_and_restart(self, enabled_plugins: list):+ self.server_config["enabled_plugins"] = enabled_plugins+ with open(self.server_config_filename, "w", encoding="utf-8") as writer:+ writer.write(json.dumps(self.server_config, indent=4))+ gr.Info("Settings saved. Restarting application...")+ quit_application()++ def _handle_save_action(self, payload_str: str):+ if not payload_str:+ return self._refresh_ui()+ try:+ payload = json.loads(payload_str)+ enabled_plugins = payload.get("enabled_plugins", [])+ if payload.get("restart", False):+ self._save_and_restart(enabled_plugins)+ return self._refresh_ui()+ else:+ return self._save_plugin_settings(enabled_plugins)+ except (json.JSONDecodeError, TypeError):+ gr.Warning("Could not process save action due to invalid data.")+ return self._refresh_ui()++ def _install_plugin_and_refresh(self, url, progress=gr.Progress()):+ progress(0, desc="Starting installation...")+ result_message = self.app.plugin_manager.install_plugin_from_url(url)+ if "[Success]" in result_message:+ gr.Info(result_message)+ else:+ gr.Warning(result_message)+ return self._refresh_ui(), ""++ def _handle_plugin_action_from_json(self, payload_str: str):+ if not payload_str:+ return self._refresh_ui()+ try:+ payload = json.loads(payload_str)+ action = payload.get("action")+ plugin_id = payload.get("plugin_id")+ if not action or not plugin_id:+ raise ValueError("Action and plugin_id are required.")+ result_message = ""+ if action == 'uninstall':+ result_message = self.app.plugin_manager.uninstall_plugin(plugin_id)+ current_enabled = self.server_config.get("enabled_plugins", [])+ if plugin_id in current_enabled:+ current_enabled.remove(plugin_id)+ self.server_config["enabled_plugins"] = current_enabled+ with open(self.server_config_filename, "w", encoding="utf-8") as writer:+ writer.write(json.dumps(self.server_config, indent=4))+ elif action == 'update':+ result_message = self.app.plugin_manager.update_plugin(plugin_id)+ elif action == 'reinstall':+ result_message = self.app.plugin_manager.reinstall_plugin(plugin_id)++ if "[Success]" in result_message:+ gr.Info(result_message)+ elif "[Error]" in result_message or "[Warning]" in result_message:+ gr.Warning(result_message)+ else:+ gr.Info(result_message)+ except (json.JSONDecodeError, ValueError) as e:+ gr.Warning(f"Could not perform plugin action: {e}")+ return self._refresh_ui()++ def post_ui_setup(self, components: dict):+ js=self._get_js_script_html()+ self.main.load(+ fn=self._refresh_ui,+ inputs=[],+ outputs=[self.plugins_html_display],+ js=js+ )+ self.save_plugins_button.click(+ fn=None, js="handleSave(false)"+ )+ self.save_and_restart_button.click(+ fn=None, js="handleSave(true)"+ )++ self.save_action_input.change(+ fn=self._handle_save_action,+ inputs=[self.save_action_input],+ outputs=[self.plugins_html_display]+ )++ self.plugin_action_input.change(+ fn=self._handle_plugin_action_from_json,+ inputs=[self.plugin_action_input],+ outputs=[self.plugins_html_display]+ )++ self.install_plugin_button.click(+ fn=self._install_plugin_and_refresh,+ inputs=[self.plugin_url_textbox],+ outputs=[self.plugins_html_display, self.plugin_url_textbox]+ )++ return {}\ No newline at end of filediff --git a/shared/utils/plugins.py b/shared/utils/plugins.pyindex a785138..367ac2c 100644--- a/shared/utils/plugins.py+++ b/shared/utils/plugins.py@@ -1,5 +1,6 @@import osimport sys+import importlibimport importlib.utilimport inspectfrom typing import Dict, Any, Optional, List, Union@@ -8,6 +9,7 @@ import gradio as grimport tracebackimport subprocessimport git+import shutil@dataclassclass InsertAfterRequest:@@ -77,8 +79,106 @@ class PluginManager:self.plugins: Dict[str, WAN2GPPlugin] = {}self.plugins_dir = plugins_diros.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)+ info = {'id': dir_name, 'name': dir_name, 'version': 'N/A', 'path': plugin_path}+ 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+ break+ except Exception as e:+ print(f"Could not load metadata for plugin {dir_name}: {e}")+ plugins_info.append(info)+ return plugins_info++ def uninstall_plugin(self, plugin_id: str):+ if not plugin_id:+ return "[Error] No plugin selected for uninstallation."+ 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."@@ -130,9 +230,6 @@ class PluginManager:return sorted(discovered)def load_plugins_from_directory(self, enabled_plugins: List[str]) -> None:- if self.plugins_dir not in sys.path:- sys.path.insert(0, self.plugins_dir)-for plugin_dir_name in self.discover_plugins():if plugin_dir_name not in enabled_plugins:continuediff --git a/wgp.py b/wgp.pyindex 364dee7..13c0062 100644--- a/wgp.py+++ b/wgp.py@@ -1827,7 +1827,7 @@ if not Path(server_config_filename).is_file():"profile" : profile_type.LowRAM_LowVRAM,"preload_model_policy": [],"UI_theme": "default",- "enabled_plugins": ["wan2gp-gallery", "wan2gp-lora-multipliers-ui"]+ "enabled_plugins": ["wan2gp-gallery", "wan2gp-lora-multipliers-ui", "wan2gp-plugin-manager"]}with open(server_config_filename, "w", encoding="utf-8") as writer:@@ -1837,7 +1837,7 @@ else:text = reader.read()server_config = json.loads(text)if "enabled_plugins" not in server_config:- server_config["enabled_plugins"] = ["wan2gp-gallery", "wan2gp-lora-multipliers-ui"]+ server_config["enabled_plugins"] = ["wan2gp-gallery", "wan2gp-lora-multipliers-ui", "wan2gp-plugin-manager"]# Deprecated modelsfor path in ["wan2.1_Vace_1.3B_preview_bf16.safetensors", "sky_reels2_diffusion_forcing_1.3B_bf16.safetensors","sky_reels2_diffusion_forcing_720p_14B_bf16.safetensors",@@ -8899,65 +8899,6 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non# video_guide, image_guide, video_mask, image_mask, image_refs,)-def generate_plugins_tab():- if not app.plugin_manager:- gr.Markdown("## Plugin Manager could not be initialized.")- return-- def save_plugin_settings(enabled_plugins):- global server_config- server_config["enabled_plugins"] = enabled_plugins- with open(server_config_filename, "w", encoding="utf-8") as writer:- writer.write(json.dumps(server_config, indent=4))- gr.Info("Plugin settings saved. Please restart WanGP to apply changes.")- return gr.update(value=enabled_plugins)-- def install_plugin(url, progress=gr.Progress()):- progress(0, desc="Starting installation...")- result_message = app.plugin_manager.install_plugin_from_url(url)-- if "[Success]" in result_message:- gr.Info(result_message)- else:- gr.Warning(result_message)-- all_plugins = app.plugin_manager.discover_plugins()- enabled_plugins_val = server_config.get("enabled_plugins", [])- return gr.update(choices=all_plugins, value=enabled_plugins_val), ""-- all_plugins = app.plugin_manager.discover_plugins()- enabled_plugins = server_config.get("enabled_plugins", [])-- with gr.Column():- gr.Markdown("## Plugin Management")- gr.Markdown("Enable or disable plugins below. **A restart of the WanGP application is required for changes to take effect.**")-- with gr.Group():- enabled_plugins_checkboxes = gr.CheckboxGroup(- choices=all_plugins, value=enabled_plugins, label="Available Plugins"- )- save_plugins_button = gr.Button("Save Settings", variant="primary")-- gr.Markdown("---")- gr.Markdown("## Install New Plugin")- gr.Markdown("Enter the URL of a GitHub repository containing a Wan2GP plugin. The plugin will be downloaded into your `plugins` directory.")-- with gr.Group():- plugin_url_textbox = gr.Textbox(label="GitHub URL", placeholder="https://github.com/user/wan2gp-plugin-repo")- install_plugin_button = gr.Button("Download and Install Plugin")-- save_plugins_button.click(- fn=save_plugin_settings,- inputs=[enabled_plugins_checkboxes],- outputs=[enabled_plugins_checkboxes]- )-- install_plugin_button.click(- fn=install_plugin,- inputs=[plugin_url_textbox],- outputs=[enabled_plugins_checkboxes, plugin_url_textbox]- )-def generate_download_tab(lset_name,loras_choices, state):with gr.Row():@@ -9976,8 +9917,6 @@ def create_ui():( state, loras_choices, lset_name, resolution, refresh_form_trigger, save_form_trigger, tab_components# video_guide, image_guide, video_mask, image_mask, image_refs,) = generate_video_tab(model_family=model_family, model_choice=model_choice, header=header, main = main, main_tabs =main_tabs)- with gr.Tab("Plugins", id="plugins"):- generate_plugins_tab()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: