Skip to content
Python

add plugin manager and plugin tab

Chris Malone5a79508f8530
diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md
index a2dc614..596c6b5 100644
--- a/docs/PLUGINS.md
+++ b/docs/PLUGINS.md
@@ -1,35 +1,81 @@
# Wan2GP Plugin System
-This system allows you to extend and customize the Wan2GP user interface and functionality without modifying the core application code. This document will guide you through the process of creating your own plugins.
+This system allows you to extend and customize the Wan2GP user interface and functionality without modifying the core application code. This document will guide you through the process of creating and installing your own plugins.
## Table of Contents
-1. [Getting Started](#getting-started)
-2. [Plugin API Reference](#plugin-api-reference)
+1. [Plugin Structure](#plugin-structure)
+2. [Getting Started: Creating a Plugin](#getting-started-creating-a-plugin)
+3. [Plugin Distribution and Installation](#plugin-distribution-and-installation)
+4. [Plugin API Reference](#plugin-api-reference)
* [The `WAN2GPPlugin` Class](#the-wan2gpplugin-class)
* [Core Methods](#core-methods)
-3. [Examples](#examples)
+5. [Examples](#examples)
* [Example 1: Creating a New Tab](#example-1-creating-a-new-tab)
* [Example 2: Modifying an Existing Component](#example-2-modifying-an-existing-component)
* [Example 3: Advanced UI Injection and Interaction](#example-3-advanced-ui-injection-and-interaction)
* [Example 4: Accessing Global Functions and Variables](#example-4-accessing-global-functions-and-variables)
-4. [Finding Component IDs](#finding-component-ids)
+ * [Example 5: Using Helper Modules (Relative Imports)](#example-5-using-helper-modules-relative-imports)
+6. [Finding Component IDs](#finding-component-ids)
-## Getting Started
+## Plugin Structure
-1. **Create a Python File**: Your plugin will be a single Python file located in the `plugins/` directory.
-2. **Define a Plugin Class**: Inside your file, create a class that inherits from `WAN2GPPlugin`.
-3. **Implement Your Logic**: Use the methods provided by the `WAN2GPPlugin` base class to add tabs, interact with existing components, and define new functionality.
+Plugins are no longer single files. They are now standard Python packages (folders) located within the main `plugins/` directory. This structure allows for multiple files, dependencies, and proper packaging.
-The application will automatically discover and load any valid plugin file from the `plugins/` directory upon startup.
+A valid plugin folder must contain at a minimum:
+* `__init__.py`: An empty file that tells Python to treat the directory as a package.
+* `plugin.py`: The main file containing your class that inherits from `WAN2GPPlugin`.
+
+A complete plugin folder typically looks like this:
+
+```
+plugins/
+└── my-awesome-plugin/
+ ├── __init__.py # (Required, can be empty) Makes this a Python package.
+ ├── plugin.py # (Required) Main plugin logic and class definition.
+ ├── requirements.txt # (Optional) Lists pip dependencies for your plugin.
+ ├── setup.py # (Optional) For more complex installation or packaging.
+ └── ... # Other helper .py files, assets, etc.
+```
+
+## Getting Started: Creating a Plugin
+
+1. **Create a Plugin Folder**: Inside the main `plugins/` directory, create a new folder for your plugin (e.g., `my-awesome-plugin`).
+
+2. **Create Core Files**:
+ * Inside `my-awesome-plugin/`, create an empty file named `__init__.py`.
+ * Create another file named `plugin.py`. This will be the entry point for your plugin.
+
+3. **Define a Plugin Class**: In `plugin.py`, create a class that inherits from `WAN2GPPlugin`.
+
+4. **Add Dependencies (Optional)**: If your plugin requires external Python libraries (e.g., `numpy`), list them in a `requirements.txt` file inside your plugin folder. These will be installed automatically when a user installs your plugin via the UI.
+
+5. **Enable and Test**:
+ * Start Wan2GP.
+ * Go to the **Plugins** tab.
+ * You should see your new plugin (`my-awesome-plugin`) in the list.
+ * Check the box to enable it and click "Save Settings".
+ * **Restart the Wan2GP application.** Your plugin will now be active.
+
+## Plugin Distribution and Installation
+
+#### Packaging for Distribution
+To share your plugin, simply upload your entire plugin folder (e.g., `my-awesome-plugin/`) to a public GitHub repository.
+
+#### Installing from the UI
+Users can install your plugin directly from the Wan2GP interface:
+1. Go to the **Plugins** tab.
+2. Under "Install New Plugin," paste the full URL of your plugin's GitHub repository.
+3. Click "Download and Install Plugin."
+4. The system will clone the repository, install any dependencies from `requirements.txt`, and run `setup.py` if present.
+5. The new plugin will appear in the "Available Plugins" list. The user must then enable it and restart the application.
## Plugin API Reference
### The `WAN2GPPlugin` Class
-
-Every plugin must define a class that inherits from `WAN2GPPlugin`.
+Every plugin must define its main class in `plugin.py` inheriting from `WAN2GPPlugin`.
```python
-# in plugins/my_awesome_plugin.py
+# in plugins/my-awesome-plugin/plugin.py
from shared.utils.plugins import WAN2GPPlugin
import gradio as gr
@@ -42,69 +88,52 @@ class MyAwesomePlugin(WAN2GPPlugin):
```
### Core Methods
-
These are the methods you can override or call to build your plugin.
#### `setup_ui(self)`
-This method is called during the initial UI construction phase. It's the primary place to declare new tabs or request access to components and globals you'll need later.
-
-* **`self.add_tab(tab_id, label, component_constructor, position)`**: Adds a new top-level tab to the main UI.
- * `tab_id` (str): A unique identifier for your tab.
- * `label` (str): The text that will appear on the tab.
- * `component_constructor` (callable): A function that creates the Gradio interface for this tab. It should return a Gradio `Blocks` instance.
- * `position` (int, optional): The desired position of the tab (e.g., `1` for the second position).
+This method is called when your plugin is first loaded. It's the place to declare new tabs or request access to components and globals.
-* **`self.request_component(component_id)`**: Requests access to an existing Gradio component from the main application.
- * `component_id` (str): The `elem_id` of the Gradio component you want to interact with.
- * The requested component will be injected as an attribute of your plugin instance (e.g., `self.loras_multipliers`) and will be available in the `post_ui_setup` method.
-
-* **`self.request_global(global_name)`**: Requests access to a global variable or function from the main application scope (`wgp.py`).
- * `global_name` (str): The name of the global variable/function.
- * The requested global will be injected as an attribute of your plugin instance (e.g., `self.server_config`).
+* **`self.add_tab(tab_id, label, component_constructor, position)`**: Adds a new top-level tab.
+* **`self.request_component(component_id)`**: Requests access to an existing Gradio component. The component will be available as an attribute (e.g., `self.loras_multipliers`) in `post_ui_setup`.
+* **`self.request_global(global_name)`**: Requests access to a global variable or function from the main application. The global will be available as an attribute (e.g., `self.server_config`).
#### `post_ui_setup(self, components)`
-This method is executed after the entire main UI has been built. It's the place to wire up event listeners and make initial modifications to components.
-
-* `components` (dict): A dictionary containing the Gradio components you requested with `self.request_component`.
-* **Return Value**: The method should return a dictionary where keys are Gradio component objects and values are `gr.update(...)` instances. This is used to modify the initial state of components when the UI loads.
+This method runs after the entire main UI has been built. Use it to wire up events and make initial modifications.
-```python
-def post_ui_setup(self, components: dict):
- # Get the component you requested
- loras_multipliers_textbox = components.get("loras_multipliers")
-
- # Change the initial value of the textbox on UI load
- return {
- loras_multipliers_textbox: gr.update(value="Value set by a plugin!")
- }
-```
+* `components` (dict): A dictionary of the components you requested.
+* **Return Value**: Can be used to update components on load, but it's now recommended to use `self.insert_after` for UI changes and wire events directly.
#### `self.insert_after(target_component_id, new_component_constructor)`
-Call this method inside `post_ui_setup` to dynamically inject your own UI elements into the main application's layout.
+Call this inside `post_ui_setup` to dynamically inject UI elements.
* `target_component_id` (str): The `elem_id` of the existing component after which your new UI will be inserted.
-* `new_component_constructor` (callable): A function that creates and returns the new Gradio component(s). This function will be executed within the proper Gradio `Blocks` context.
+* `new_component_constructor` (callable): A function that creates and returns the new Gradio component(s).
## Examples
### Example 1: Creating a New Tab
-This plugin adds a new tab with a simple "Hello World" interface. This is based on `example_plugin.py`.
+**File Structure:**
+```
+plugins/
+└── greeter_plugin/
+ ├── __init__.py
+ └── plugin.py
+```
+
+**Code:**
```python
-# in plugins/greeter_plugin.py
+# in plugins/greeter_plugin/plugin.py
import gradio as gr
from shared.utils.plugins import WAN2GPPlugin
class GreeterPlugin(WAN2GPPlugin):
-
def __init__(self):
super().__init__()
self.name = "Greeter Plugin"
self.version = "1.0.0"
- # setup_ui is called first
def setup_ui(self):
- # We declare that we want to add a tab
self.add_tab(
tab_id="greeter_tab",
label="Greeter",
@@ -112,7 +141,6 @@ class GreeterPlugin(WAN2GPPlugin):
position=2 # Place it as the 3rd tab
)
- # This function builds the UI for our tab
def create_greeter_ui(self):
with gr.Blocks() as demo:
gr.Markdown("## A Simple Greeter")
@@ -130,10 +158,18 @@ class GreeterPlugin(WAN2GPPlugin):
```
### Example 2: Modifying an Existing Component
-This plugin demonstrates how to change the value of an existing component (`loras_multipliers`) and insert a new HTML component directly after it. This is based on `lora_setter_plugin.py`.
+**File Structure:**
+```
+plugins/
+└── simple_modifier_plugin/
+ ├── __init__.py
+ └── plugin.py
+```
+
+**Code:**
```python
-# in plugins/simple_modifier_plugin.py
+# in plugins/simple_modifier_plugin/plugin.py
import gradio as gr
from shared.utils.plugins import WAN2GPPlugin
@@ -144,143 +180,147 @@ class SimpleModifierPlugin(WAN2GPPlugin):
self.version = "1.0.0"
def setup_ui(self):
- # Request access to the loras_multipliers textbox
self.request_component("loras_multipliers")
def post_ui_setup(self, components: dict):
- # Get the component we requested in setup_ui
- loras_multipliers_textbox = components.get("loras_multipliers")
- if loras_multipliers_textbox is None:
+ # The component is now an attribute of self
+ if not hasattr(self, 'loras_multipliers'):
return {}
- # This function will create our new component
def create_inserted_component():
- return gr.HTML(
- value="<div style='padding: 10px; background: #eee; border: 1px solid #ccc;'>"
- "This HTML block was inserted by a plugin!"
- "</div>"
- )
+ return gr.HTML(value="<div style='padding: 10px; background: #eee;'>Inserted by a plugin!</div>")
- # Schedule the insertion to happen after the UI is built
self.insert_after(
target_component_id="loras_multipliers",
new_component_constructor=create_inserted_component
)
- # Return a dictionary to update the component's initial value
+ # To update the component on load, you can also wire into the main 'load' event
+ # but for simplicity, the original return method is shown here.
return {
- loras_multipliers_textbox: gr.update(value="Hello from the Simple Modifier plugin!")
+ self.loras_multipliers: gr.update(value="Hello from the Simple Modifier plugin!")
}
```
### Example 3: Advanced UI Injection and Interaction
-This example, inspired by `lora_multipliers_ui.py`, shows a more complex use case: injecting a full UI panel and wiring its events to both existing and new components.
+**File Structure:**
+```
+plugins/
+└── advanced_ui_plugin/
+ ├── __init__.py
+ └── plugin.py
+```
+
+**Code:**
```python
-# in plugins/advanced_ui_plugin.py
+# in plugins/advanced_ui_plugin/plugin.py
import gradio as gr
from shared.utils.plugins import WAN2GPPlugin
class AdvancedUIPlugin(WAN2GPPlugin):
- def __init__(self):
- super().__init__()
- self.name = "Advanced UI Plugin"
- self.version = "1.0.0"
-
def setup_ui(self):
- # Request components we want to interact with
self.request_component("loras_multipliers")
self.request_component("loras_choices")
- self.request_component("main") # The main Gradio Blocks instance
+ self.request_component("main")
def post_ui_setup(self, components: dict):
- loras_multipliers_textbox = components.get("loras_multipliers")
- loras_choices_dropdown = components.get("loras_choices")
- main_ui = components.get("main")
-
- # This function defines our new UI and its logic
def create_and_wire_advanced_ui():
- with gr.Accordion("Advanced Plugin Panel", open=True):
+ with gr.Accordion("Advanced Plugin Panel", open=True) as panel:
info_md = gr.Markdown("This panel is inserted by a plugin.")
copy_btn = gr.Button("Copy selected LoRAs to multiplier textbox")
- # Event handling for our new component
def copy_lora_names(selected_loras):
return ", ".join(selected_loras)
copy_btn.click(
fn=copy_lora_names,
- inputs=[loras_choices_dropdown],
- outputs=[loras_multipliers_textbox]
+ inputs=[self.loras_choices],
+ outputs=[self.loras_multipliers]
)
-
- # Event handling for an existing component
- def on_main_load(choices):
- print(f"Plugin sees that UI has loaded with these choices: {choices}")
+ return panel
- main_ui.load(fn=on_main_load, inputs=[loras_choices_dropdown])
-
- return info_md.parent # Return the Accordion
-
- # Insert our new UI
self.insert_after(
target_component_id="loras_multipliers",
new_component_constructor=create_and_wire_advanced_ui
)
-
- return {} # No initial updates needed
```
### Example 4: Accessing Global Functions and Variables
-This example, inspired by `gallery.py`, shows how to request and use functions and variables from the main application.
+**File Structure:**
+```
+plugins/
+└── global_access_plugin/
+ ├── __init__.py
+ └── plugin.py
+```
+
+**Code:**
```python
-# in plugins/global_access_plugin.py
+# in plugins/global_access_plugin/plugin.py
import gradio as gr
from shared.utils.plugins import WAN2GPPlugin
class GlobalAccessPlugin(WAN2GPPlugin):
- def __init__(self):
- super().__init__()
- self.name = "Global Access Plugin"
-
def setup_ui(self):
- # Request access to a global variable (a dictionary)
self.request_global("server_config")
- # Request access to a global function
self.request_global("get_video_info")
-
- self.add_tab(
- tab_id="global_access_tab",
- label="Global Access",
- component_constructor=self.create_ui
- )
+ self.add_tab("global_access_tab", "Global Access", self.create_ui)
def create_ui(self):
with gr.Blocks() as demo:
- gr.Markdown("## Accessing Globals")
video_input = gr.Video(label="Upload a video")
info_output = gr.JSON(label="Video Info")
- # This function will be called by the button click
def analyze_video(video_path):
- if not video_path:
- return "Upload a video first."
-
- # Access the globals requested in setup_ui
+ if not video_path: return "Upload a video."
save_path = self.server_config.get("save_path", "outputs")
fps, w, h, frames = self.get_video_info(video_path)
-
- return {
- "save_path_from_config": save_path,
- "fps": fps,
- "dimensions": f"{w}x{h}",
- "frame_count": frames
- }
+ return {"save_path": save_path, "fps": fps, "dimensions": f"{w}x{h}"}
analyze_btn = gr.Button("Analyze Video")
analyze_btn.click(fn=analyze_video, inputs=[video_input], outputs=[info_output])
+ return demo
+```
+
+### Example 5: Using Helper Modules (Relative Imports)
+This example shows how to organize your code into multiple files within your plugin package.
+
+**File Structure:**
+```
+plugins/
+└── helper_plugin/
+ ├── __init__.py
+ ├── plugin.py
+ └── helpers.py
+```
+
+**Code:**
+```python
+# in plugins/helper_plugin/helpers.py
+def format_greeting(name: str) -> str:
+ """A helper function in a separate file."""
+ if not name:
+ return "Hello, mystery person!"
+ return f"A very special hello to {name.upper()}!"
+
+# in plugins/helper_plugin/plugin.py
+import gradio as gr
+from shared.utils.plugins import WAN2GPPlugin
+from .helpers import format_greeting # <-- Relative import works!
+
+class HelperPlugin(WAN2GPPlugin):
+ def setup_ui(self):
+ self.add_tab("helper_tab", "Helper Example", self.create_ui)
+
+ def create_ui(self):
+ with gr.Blocks() as demo:
+ name_input = gr.Textbox(label="Name")
+ output = gr.Textbox(label="Formatted Greeting")
+ btn = gr.Button("Greet with Helper")
+ btn.click(fn=format_greeting, inputs=[name_input], outputs=[output])
return demo
```
@@ -288,8 +328,5 @@ class GlobalAccessPlugin(WAN2GPPlugin):
To interact with an existing component, you need its `elem_id`. You can find these IDs by:
-1. **Inspecting the Source Code**: Look through `wgp.py` and other UI-related files for Gradio components defined with an `elem_id`, for example:
- ```python
- self.loras_multipliers = gr.Textbox(elem_id="loras_multipliers", ...)
- ```
-2. **Browser Developer Tools**: If an `elem_id` is not explicitly set, you can run Wan2GP, open your browser's developer tools (usually by pressing F12), and inspect the HTML to find the ID of the element you want to target. Gradio components are often wrapped in a `<div>` with an ID.
\ No newline at end of file
+1. **Inspecting the Source Code**: Look through `wgp.py` and other UI-related files for Gradio components defined with an `elem_id`.
+2. **Browser Developer Tools**: If an `elem_id` is not set, run Wan2GP, open your browser's developer tools (F12), and inspect the HTML to find the ID of the element you want to target.
\ No newline at end of file
diff --git a/plugins/wan2gp-gallery/__init__.py b/plugins/wan2gp-gallery/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/plugins/gallery_utils.py b/plugins/wan2gp-gallery/gallery_utils.py
similarity index 100%
rename from plugins/gallery_utils.py
rename to plugins/wan2gp-gallery/gallery_utils.py
diff --git a/plugins/gallery.py b/plugins/wan2gp-gallery/plugin.py
similarity index 99%
rename from plugins/gallery.py
rename to plugins/wan2gp-gallery/plugin.py
index befd2ca..1387bb0 100644
--- a/plugins/gallery.py
+++ b/plugins/wan2gp-gallery/plugin.py
@@ -5,7 +5,7 @@ import re
from PIL import Image
import gc
-from plugins.gallery_utils import get_thumbnails_in_batch_windows
+from .gallery_utils import get_thumbnails_in_batch_windows
class GalleryPlugin(WAN2GPPlugin):
def __init__(self):
diff --git a/plugins/wan2gp-lora-multipliers-ui/__init__.py b/plugins/wan2gp-lora-multipliers-ui/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/plugins/lora_multipliers_ui.py b/plugins/wan2gp-lora-multipliers-ui/plugin.py
similarity index 100%
rename from plugins/lora_multipliers_ui.py
rename to plugins/wan2gp-lora-multipliers-ui/plugin.py
diff --git a/shared/utils/plugins.py b/shared/utils/plugins.py
index c079d57..727e183 100644
--- a/shared/utils/plugins.py
+++ b/shared/utils/plugins.py
@@ -6,6 +6,13 @@ from typing import Dict, Any, Optional, List, Union
from dataclasses import dataclass
import gradio as gr
import traceback
+import subprocess
+try:
+ import git
+except ImportError:
+ print("Git not found. Installing...")
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'gitpython'])
+ import git
@dataclass
class InsertAfterRequest:
@@ -38,9 +45,11 @@ class WAN2GPPlugin:
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()
@@ -63,53 +72,82 @@ class WAN2GPPlugin:
return {}
class PluginManager:
- def __init__(self):
+ def __init__(self, plugins_dir="plugins"):
self.plugins: Dict[str, WAN2GPPlugin] = {}
- self._load_builtin_plugins()
+ self.plugins_dir = plugins_dir
+ os.makedirs(self.plugins_dir, exist_ok=True)
- def _load_builtin_plugins(self) -> None:
- pass
-
- def load_plugin(self, plugin_path: str) -> bool:
+ 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:
- module_name = os.path.splitext(os.path.basename(plugin_path))[0]
-
- spec = importlib.util.spec_from_file_location(f"wan2gp_plugins.{module_name}", plugin_path)
- if spec is None or spec.loader is None:
- print(f"Error: Could not load plugin {plugin_path}")
- return False
-
- module = importlib.util.module_from_spec(spec)
- sys.modules[module_name] = module
- spec.loader.exec_module(module)
-
- for name, obj in inspect.getmembers(module, inspect.isclass):
- if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:
- plugin = obj()
- plugin.setup_ui()
- self.plugins[module_name] = plugin
- print(f"Loaded plugin: {plugin.name}")
- return True
- return False
+ 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:
- print(f"Error loading plugin {plugin_path}: {str(e)}")
- import traceback
- traceback.print_exc()
- return False
-
- def load_plugins_from_directory(self, directory: str) -> None:
- if not os.path.isdir(directory):
- os.makedirs(directory, exist_ok=True)
- return
-
- for filename in os.listdir(directory):
- if filename.endswith('.py') and not filename.startswith('_'):
- self.load_plugin(os.path.join(directory, filename))
-
- def get_plugin(self, plugin_id: str) -> Optional[WAN2GPPlugin]:
- return self.plugins.get(plugin_id)
-
+ 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_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:
+ 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
+ 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()
@@ -124,7 +162,6 @@ class PluginManager:
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():
@@ -135,9 +172,6 @@ class PluginManager:
}
except Exception as e:
print(f"Error in setup_ui for plugin {plugin_id}: {str(e)}")
- import traceback
- traceback.print_exc()
-
return {'tabs': tabs}
def run_post_ui_setup(self, all_components: Dict[str, gr.components.Component]) -> None:
@@ -154,83 +188,45 @@ class PluginManager:
for comp_id in plugin.component_requests
if comp_id in all_components
}
-
- updates = plugin.post_ui_setup(requested_components)
- if updates:
- for component, update_instruction in updates.items():
- new_value = None
- if isinstance(update_instruction, dict) and update_instruction.get("__type__") == "update":
- if 'value' in update_instruction:
- new_value = update_instruction['value']
- elif isinstance(update_instruction, gr.components.Component):
- if hasattr(update_instruction, 'value'):
- print(f"Warning: Plugin '{plugin.name}' is returning a new component instance for a value update. Please use gr.update(value=...) instead.")
- new_value = getattr(update_instruction, 'value')
- else:
- new_value = update_instruction
-
- if new_value is not None:
- component.value = new_value
-
+ plugin.post_ui_setup(requested_components)
all_insert_requests.extend(getattr(plugin, '_insert_after_requests', []))
- getattr(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:
- target_id = request.target_component_id
- constructor = request.new_component_constructor
-
try:
- if target_id not in all_components:
- print(f"[PluginManager] ERROR: Target '{target_id}' for insertion not found.")
- continue
-
- target = all_components[target_id]
+ target = all_components.get(request.target_component_id)
parent = getattr(target, 'parent', None)
- if parent is None or not hasattr(parent, 'children'):
+ 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
-
- children = list(parent.children)
- target_index = children.index(target)
-
+
+ target_index = parent.children.index(target)
with parent:
- new_component = constructor()
-
- newly_added_component = parent.children.pop(-1)
- parent.children.insert(target_index + 1, newly_added_component)
-
- print(f"[PluginManager] Successfully inserted {type(new_component).__name__} after {target_id}")
+ 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 {target_id}: {str(e)}")
- import traceback
- traceback.print_exc()
+ print(f"[PluginManager] Error processing insert_after for {request.target_component_id}: {str(e)}")
class WAN2GPApplication:
def __init__(self):
- self.plugin_manager = None
+ self.plugin_manager = PluginManager()
self.ui_components = {}
- def initialize_plugin_manager(self) -> None:
- try:
- self.plugin_manager = PluginManager()
- plugins_dir = os.path.join(os.getcwd(), "plugins")
- os.makedirs(plugins_dir, exist_ok=True)
- self.plugin_manager.load_plugins_from_directory(plugins_dir)
- except Exception as e:
- print(f"Error initializing plugin manager: {str(e)}")
- traceback.print_exc()
-
def _create_plugin_tabs(self, main_module_globals: Dict[str, Any]):
- self.initialize_plugin_manager()
if not self.plugin_manager:
return
-
+ server_config = main_module_globals.get('server_config', {})
+ enabled_plugins = server_config.get("enabled_plugins", [])
+ self.plugin_manager.load_plugins_from_directory(enabled_plugins)
self.plugin_manager.inject_globals(main_module_globals)
-
plugin_ui = self.plugin_manager.setup_ui()
plugin_tabs = plugin_ui.get('tabs', {})
diff --git a/wgp.py b/wgp.py
index aefa23a..7c15a20 100644
--- a/wgp.py
+++ b/wgp.py
@@ -1824,7 +1824,8 @@ if not Path(server_config_filename).is_file():
"vae_config": 0,
"profile" : profile_type.LowRAM_LowVRAM,
"preload_model_policy": [],
- "UI_theme": "default"
+ "UI_theme": "default",
+ "enabled_plugins": ["wan2gp-gallery", "wan2gp-lora-multipliers-ui"]
}
with open(server_config_filename, "w", encoding="utf-8") as writer:
@@ -1833,6 +1834,8 @@ else:
with open(server_config_filename, "r", encoding="utf-8") as reader:
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"]
# Deprecated models
for 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",
@@ -8883,6 +8886,65 @@ 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():
@@ -9901,6 +9963,8 @@ 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: