Python
added plugin versioning
DeepBeepMeep02d9027d5919
diff --git a/.gitignore b/.gitignoreindex 8049651..0004d85 100644--- a/.gitignore+++ b/.gitignore@@ -45,3 +45,4 @@ loras_i2v/settings/wgp_config.json+plugins_local.jsondiff --git a/README.md b/README.mdindex bcd25c2..31795ff 100644--- a/README.md+++ b/README.md@@ -40,7 +40,8 @@ WanGP Special *TTS* (Text To Speech) Release:- **Custom Output folder for Audio Gens**: you can now choose a different folder for the *Audio Outputs*- **Default Memory Profile for Audio Models**: TTS models can get very slow if you use profile 4 (being autoregressive models, they will need to load all the layers one per one to generate one single audio token then rinse & repeat). On the other hand, they dont't need as much VRAM, so you can now define a more agressive profile (3+ for instance)-*update 10.51*: new Heart Mula Finetune better at following instructions, Extra settings (cfg, top k) for TTS models, Rife v4+*update 10.51*: new Heart Mula Finetune better at following instructions, Extra settings (cfg, top k) for TTS models, Rife v4\+*update 10.52*: update plugin list and added version tracking### January 20th 2026: WanGP v10.43, The Cost Saver*GPUs are expensive, RAM is expensive, SSD are expensive, sadly we live now in a GPU & RAM poor.*diff --git a/plugins.json b/plugins.jsonindex bbb82fd..4e6409e 100644--- a/plugins.json+++ b/plugins.json@@ -1,44 +1,65 @@[{- "name": "File Gallery",- "author": "Tophness",- "version": "1.0.1",- "description": "Adds a Gallery tab that allows you to view metadata of all files in your output folders, join video frames, and more.",- "url": "https://github.com/Tophness/wan2gp-gallery.git"+ "name": "File Gallery 2",+ "author": "Tophness and Neires",+ "version": "2.0.1",+ "description": "Adds a Gallery tab that allows you to view metadata of all files in your output folders, join video frames with a single click, and more",+ "date": "",+ "wan2gp_version": "",+ "url": "https://github.com/neires/wan2gp-gallery"},{- "name": "Lora Multipliers UI",- "author": "Tophness",+ "name": "FlashVSR",+ "author": "Hakaze",+ "version": "1.0.2",+ "description": "AI-powered 4x video upscaling using FlashVSR models with Sparse SageAttention.",+ "url": "https://github.com/Hakaze/wan2gp-flashvsr",+ "date": "",+ "wan2gp_version": ""+ },+ {+ "name": "HideUI",+ "author": "MrKuenning","version": "1.0.0",- "description": "Dynamically set lora multipliers with a fast, JavaScript-powered UI.",- "url": "https://github.com/Tophness/wan2gp-lora-multipliers-ui.git"+ "description": "A plugin for WAN2GP to allow toggling UI elements.",+ "url": "https://github.com/MrKuenning/Wan2GP-HideUI",+ "date": "",+ "wan2gp_version": ""},{"name": "Lora Manager","author": "Tophness and Kovacs3d","version": "2.5.3","description": "Manage your lora files, view their CivitAi metadata, assign prompts to them, browse CivitAI, send loras and prompts to generator.",- "url": "https://github.com/Tophness/wan2gp-lora-manager.git"+ "url": "https://github.com/Tophness/wan2gp-lora-manager",+ "date": "",+ "wan2gp_version": ""},{- "name": "Training",+ "name": "Lora Multipliers UI","author": "Tophness",- "version": "1.1.6",- "description": "Integrates a Kohya-ss Musubi Tuner training tab directly into Wan2GP",- "url": "https://github.com/Tophness/wan2gp-training.git"+ "version": "1.0.0",+ "description": "Dynamically set lora multipliers with a fast, JavaScript-powered UI.",+ "url": "https://github.com/Tophness/wan2gp-lora-multipliers-ui",+ "date": "",+ "wan2gp_version": ""},{- "name": "HideUI",- "author": "MrKuenning",- "version": "1.0.0",- "description": "A plugin for WAN2GP to allow toggling UI elements.",- "url": "https://github.com/MrKuenning/Wan2GP-HideUI.git"+ "name": "Multi-Angle Prompt Helper",+ "author": "",+ "version": "1.4.0",+ "description": "Injects a prompt helper into the Video Generator UI. Outputs degree/factor text.",+ "date": "",+ "wan2gp_version": "",+ "url": "https://github.com/CodeBarrie/wan2gp-multiangle-prompt-helper"},{- "name": "FlashVSR",- "author": "Hakaze",- "version": "1.0.2",- "description": "AI-powered 4x video upscaling using FlashVSR models with Sparse SageAttention.",- "url": "https://github.com/Hakaze/wan2gp-flashvsr.git"+ "name": "Training",+ "author": "Tophness",+ "version": "1.1.6",+ "description": "Integrates a Kohya-ss Musubi Tuner training tab directly into Wan2GP",+ "url": "https://github.com/Tophness/wan2gp-training",+ "date": "",+ "wan2gp_version": ""}-]+]\ No newline at end of filediff --git a/plugins/wan2gp-downloads/plugin.py b/plugins/wan2gp-downloads/plugin.pyindex 991dbbc..57a531e 100644--- a/plugins/wan2gp-downloads/plugin.py+++ b/plugins/wan2gp-downloads/plugin.py@@ -10,10 +10,6 @@ from huggingface_hub import snapshot_downloadclass DownloadsPlugin(WAN2GPPlugin):def __init__(self):super().__init__()- self.name = "Wan i2v Loras Packs"- self.version = "1.0.0"- self.description = "Auto Download i2v Loras with special effects"- self.uninstallable = Falsedef setup_ui(self):self.request_global("get_lora_dir")diff --git a/plugins/wan2gp-downloads/plugin_info.json b/plugins/wan2gp-downloads/plugin_info.jsonnew file mode 100644index 0000000..45543fe--- /dev/null+++ b/plugins/wan2gp-downloads/plugin_info.json@@ -0,0 +1,10 @@+{+ "name": "Wan i2v Loras Packs",+ "author": "DeepBeepMeep",+ "version": "1.0.0",+ "description": "Auto Download i2v Loras with special effects",+ "date": "",+ "wan2gp_version": "",+ "uninstallable": false+}+diff --git a/plugins/wan2gp-models-manager/plugin.py b/plugins/wan2gp-models-manager/plugin.pyindex 38a59e3..a1405df 100644--- a/plugins/wan2gp-models-manager/plugin.py+++ b/plugins/wan2gp-models-manager/plugin.py@@ -11,10 +11,6 @@ from mmgp import quant_routerclass modelsManagerPlugin(WAN2GPPlugin):def __init__(self):super().__init__()- self.name = "Models Manager"- self.version = "1.0.0"- self.description = "Inspect and manage installed model dependencies"- self.uninstallable = Falseself._node_map = {}self._tree_data = []self._model_files = {}diff --git a/plugins/wan2gp-models-manager/plugin_info.json b/plugins/wan2gp-models-manager/plugin_info.jsonnew file mode 100644index 0000000..90e9d7d--- /dev/null+++ b/plugins/wan2gp-models-manager/plugin_info.json@@ -0,0 +1,10 @@+{+ "name": "Models Manager",+ "author": "DeepBeepMeep",+ "version": "1.0.0",+ "description": "Inspect and manage installed model dependencies",+ "date": "",+ "wan2gp_version": "",+ "uninstallable": false+}+diff --git a/plugins/wan2gp-plugin-manager/plugin.py b/plugins/wan2gp-plugin-manager/plugin.pyindex e34b51d..ee23a70 100644--- a/plugins/wan2gp-plugin-manager/plugin.py+++ b/plugins/wan2gp-plugin-manager/plugin.py@@ -1,12 +1,8 @@import gradio as gr-from shared.utils.plugins import WAN2GPPlugin-import osimport jsonimport traceback-from wgp import quit_application-import requests--COMMUNITY_PLUGINS_URL = "https://github.com/deepbeepmeep/Wan2GP/raw/refs/heads/main/plugins.json"+from wgp import quit_application, WanGP_version+from shared.utils.plugins import WAN2GPPlugin, compare_release_metadata, is_wangp_compatible, plugin_id_from_urlclass PluginManagerUIPlugin(WAN2GPPlugin):def __init__(self):@@ -31,9 +27,17 @@ class PluginManagerUIPlugin(WAN2GPPlugin):def _get_js_script_html(self):js_code = """() => {+ function pluginRoot() {+ if (window.gradioApp) {+ return window.gradioApp();+ }+ const app = document.querySelector('gradio-app');+ return app ? (app.shadowRoot || app) : document;+ }+function updateGradioInput(elem_id, value) {- const gradio_app = document.querySelector('gradio-app') || document;- const input = gradio_app.querySelector(`#${elem_id} textarea`);+ const root = pluginRoot();+ const input = root.querySelector(`#${elem_id} textarea, #${elem_id} input`);if (input) {input.value = value;input.dispatchEvent(new Event('input', { bubbles: true }));@@ -43,14 +47,22 @@ class PluginManagerUIPlugin(WAN2GPPlugin):}function makeSortable() {- const userPluginList = document.querySelector('#user-plugin-list');+ const root = pluginRoot();+ const userPluginList = root.querySelector('#user-plugin-list');if (!userPluginList) return;+ if (userPluginList.dataset.sortableBound === '1') return;+ userPluginList.dataset.sortableBound = '1';let draggedItem = null;userPluginList.addEventListener('dragstart', e => {draggedItem = e.target.closest('.plugin-item');if (!draggedItem) return;+ draggedItem.classList.add('dragging');+ if (e.dataTransfer) {+ e.dataTransfer.effectAllowed = 'move';+ e.dataTransfer.setData('text/plain', draggedItem.dataset.pluginId || '');+ }setTimeout(() => {if (draggedItem) draggedItem.style.opacity = '0.5';}, 0);@@ -60,6 +72,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):setTimeout(() => {if (draggedItem) {draggedItem.style.opacity = '1';+ draggedItem.classList.remove('dragging');draggedItem = null;}}, 0);@@ -67,8 +80,12 @@ class PluginManagerUIPlugin(WAN2GPPlugin):userPluginList.addEventListener('dragover', e => {e.preventDefault();+ if (e.dataTransfer) {+ e.dataTransfer.dropEffect = 'move';+ }const afterElement = getDragAfterElement(userPluginList, e.clientY);if (draggedItem) {+ if (afterElement === draggedItem) return;if (afterElement == null) {userPluginList.appendChild(draggedItem);} else {@@ -77,6 +94,10 @@ class PluginManagerUIPlugin(WAN2GPPlugin):}});+ userPluginList.addEventListener('drop', e => {+ e.preventDefault();+ });+function getDragAfterElement(container, y) {const draggableElements = [...container.querySelectorAll('.plugin-item:not(.dragging)')];return draggableElements.reduce((closest, child) => {@@ -91,6 +112,25 @@ class PluginManagerUIPlugin(WAN2GPPlugin):}}+ function observeUserPluginList() {+ const root = pluginRoot();+ if (!root) {+ setTimeout(observeUserPluginList, 400);+ return;+ }+ if (root.dataset.pluginSortableObserver === '1') {+ makeSortable();+ return;+ }+ root.dataset.pluginSortableObserver = '1';+ const observer = new MutationObserver(() => {+ makeSortable();+ });+ observer.observe(root, { childList: true, subtree: true });+ makeSortable();+ }++ setTimeout(observeUserPluginList, 200);setTimeout(makeSortable, 500);window.handlePluginAction = function(button, action) {@@ -106,7 +146,8 @@ class PluginManagerUIPlugin(WAN2GPPlugin):};window.handleSave = function(restart) {- const user_container = document.querySelector('#user-plugin-list');+ const root = pluginRoot();+ const user_container = root.querySelector('#user-plugin-list');if (!user_container) return;const user_plugins = user_container.querySelectorAll('.plugin-item');@@ -125,13 +166,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):if hasattr(self, '_community_plugins_cache') and self._community_plugins_cache is not None:return self._community_plugins_cachetry:- response = requests.get(COMMUNITY_PLUGINS_URL, timeout=10)- response.raise_for_status()- plugins = response.json()- self._community_plugins_cache = {- p.get('url', '').split('/')[-1].replace('.git', ''): p- for p in plugins if p.get('url')- }+ self._community_plugins_cache = self.app.plugin_manager.get_merged_catalog_entries(use_remote=True)return self._community_plugins_cacheexcept Exception as e:print(f"[PluginManager] Could not fetch community plugins info: {e}")@@ -142,10 +177,22 @@ class PluginManagerUIPlugin(WAN2GPPlugin):try:installed_plugin_ids = {p['id'] for p in self.app.plugin_manager.get_plugins_info()}remote_plugins = self._get_community_plugins_info()+ base_entries = self.app.plugin_manager.load_catalog_entries(use_remote=False)+ base_ids = {+ plugin_id_from_url(entry.get('url', ''))+ for entry in base_entries+ if entry.get('url')+ }community_plugins = [p for plugin_id, p in remote_plugins.items()if plugin_id not in installed_plugin_ids]+ community_plugins.sort(+ key=lambda p: (+ plugin_id_from_url(p.get('url', '')) not in base_ids,+ (p.get('name') or '').lower()+ )+ )except Exception as e:gr.Warning(f"Could not process community plugins list: {e}")@@ -157,15 +204,27 @@ class PluginManagerUIPlugin(WAN2GPPlugin):items_html = ""for plugin in community_plugins:name = plugin.get('name')- author = plugin.get('author')+ author = plugin.get('author') or "Unknown"version = plugin.get('version', 'N/A')- description = plugin.get('description')+ description = plugin.get('description') or "No description provided."url = plugin.get('url')+ wan2gp_version = plugin.get('wan2gp_version') or plugin.get('wangp_version', '')- if not all([name, author, description, url]):+ if not url:continue+ if not name:+ name = plugin_id_from_url(url) or "Unknown Plugin"safe_url = url.replace("'", "\\'")+ incompatible = not is_wangp_compatible(wan2gp_version, WanGP_version)+ incompat_html = ""+ if incompatible and wan2gp_version:+ incompat_html = (+ f"<span class='plugin-incompatible-badge' "+ f"title='Requires WanGP v{wan2gp_version}+'>"+ f"Requires WanGP v{wan2gp_version}+"+ "</span>"+ )items_html += f"""<div class="plugin-item">@@ -173,6 +232,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):<div class="plugin-header"><span class="name">{name}</span><span class="version">version {version} by {author}</span>+ {incompat_html}</div><span class="description">{description}</span></div>@@ -188,7 +248,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):plugins_info = self.app.plugin_manager.get_plugins_info()enabled_user_plugins = self.server_config.get("enabled_plugins", [])all_user_plugins_info = [p for p in plugins_info if not p.get('system')]- remote_plugins_info = self._get_community_plugins_info()+ remote_plugins_info = self.app.plugin_manager.get_merged_catalog_entries(use_remote=False)css = """<style>@@ -210,7 +270,8 @@ class PluginManagerUIPlugin(WAN2GPPlugin):.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; }+ .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; white-space: nowrap; }+ .plugin-instruction { font-size: 0.95em; color: var(--text-color-secondary); margin-bottom: 6px; }.update-available-notice {font-size: 0.9em;font-weight: 600;@@ -232,12 +293,27 @@ class PluginManagerUIPlugin(WAN2GPPlugin):border: 1px solid var(--border-color-primary);white-space: nowrap;}+ .plugin-incompatible-badge {+ font-size: 0.85em;+ font-weight: 600;+ color: var(--color-error, #b91c1c);+ background-color: rgba(185, 28, 28, 0.1);+ padding: 2px 8px;+ border-radius: 4px;+ margin-left: 8px;+ border: 1px solid rgba(185, 28, 28, 0.35);+ white-space: nowrap;+ }.plugin-item.update-available {border-left: 4px solid var(--color-accent);}+ .plugin-item.incompatible {+ border-left: 4px solid var(--color-error, #b91c1c);+ }</style>"""+ instruction_html = "<div class='plugin-instruction'>Please Select the Plugins you want to enable</div>"if not all_user_plugins_info:user_html = "<p style='text-align:center; color: var(--text-color-secondary);'>No user-installed plugins found.</p>"else:@@ -253,20 +329,35 @@ class PluginManagerUIPlugin(WAN2GPPlugin):plugin_id = plugin['id']checked = "checked" if plugin_id in enabled_user_plugins else ""uninstallable = plugin.get('uninstallable', True)+ author = plugin.get('author') or "Unknown"update_notice_html = ''- item_update_class = ''- if plugin_id in remote_plugins_info:- remote_version = remote_plugins_info[plugin_id].get('version', '0.0.0')- local_version = plugin.get('version', '0.0.0')- if remote_version > local_version:- update_notice_html = f'<span class="update-available-notice">v{remote_version} update available</span>'- item_update_class = 'update-available'+ item_classes = []+ if uninstallable and plugin_id in remote_plugins_info:+ remote_entry = remote_plugins_info[plugin_id]+ if compare_release_metadata(remote_entry, plugin) > 0:+ remote_version = remote_entry.get('version') or remote_entry.get('date') or "unknown"+ update_notice_html = (+ f'<span class="update-available-notice">New version {remote_version} is available !</span>'+ )+ item_classes.append('update-available')bundled_badge_html = ''if not uninstallable:bundled_badge_html = '<span class="plugin-bundled-badge" title="Bundled plugin, cannot be uninstalled">Bundled</span>'+ wan2gp_version = plugin.get('wan2gp_version') or plugin.get('wangp_version', '')+ incompatible = not is_wangp_compatible(wan2gp_version, WanGP_version)+ incompat_html = ''+ if incompatible and wan2gp_version:+ incompat_html = (+ f"<span class='plugin-incompatible-badge' "+ f"title='Requires WanGP v{wan2gp_version}+'>"+ f"Requires WanGP v{wan2gp_version}+"+ "</span>"+ )+ item_classes.append('incompatible')+actions_html = ""if uninstallable:actions_html = """@@ -277,7 +368,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):actions_container_html = f'<div class="plugin-item-actions">{actions_html}</div>' if actions_html else ""user_items_html += f"""- <div class="plugin-item {item_update_class}" data-plugin-id="{plugin_id}" draggable="true">+ <div class="plugin-item {' '.join(item_classes)}" data-plugin-id="{plugin_id}" draggable="true"><div class="plugin-info-container"><input type="checkbox" class="plugin-enable-checkbox" {checked}><div class="plugin-item-info">@@ -285,8 +376,9 @@ class PluginManagerUIPlugin(WAN2GPPlugin):<span class="name">{plugin['name']}</span>{update_notice_html}{bundled_badge_html}+ {incompat_html}</div>- <span class="version">version {plugin['version']} (id: {plugin['id']})</span>+ <span class="version">version {plugin['version']} by {author} (id: {plugin['id']})</span><span class="description">{plugin.get('description', 'No description provided.')}</span></div></div>@@ -295,7 +387,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):"""user_html = f'<div id="user-plugin-list">{user_items_html}</div>'- return f"{css}<div class='plugin-list'>{user_html}</div>"+ return f"{css}<div class='plugin-list'>{instruction_html}{user_html}</div>"def create_plugin_manager_ui(self):with gr.Blocks() as plugin_blocks:@@ -306,6 +398,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):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")+ self.refresh_catalog_button = gr.Button("Check for Updates", variant="secondary", size="sm", scale=0, elem_classes="stylish-save-btn")with gr.Column(scale=2, min_width=300):gr.Markdown("### Discover & Install")@@ -332,6 +425,12 @@ class PluginManagerUIPlugin(WAN2GPPlugin):self.save_plugins_button.click(fn=None, js="handleSave(false)")self.save_and_restart_button.click(fn=None, js="handleSave(true)")+ self.refresh_catalog_button.click(+ fn=self._refresh_catalog,+ inputs=[],+ outputs=[self.plugins_html_display, self.community_plugins_html],+ show_progress="full"+ )self.save_action_input.change(fn=self._handle_save_action,@@ -365,9 +464,42 @@ class PluginManagerUIPlugin(WAN2GPPlugin):community_html = self._build_community_plugins_html()return gr.update(value=installed_html), gr.update(value=community_html)+ def _refresh_catalog(self, progress=gr.Progress()):+ self.app.plugin_manager.refresh_catalog(installed_only=True, use_remote=False)+ if hasattr(self, '_community_plugins_cache'):+ del self._community_plugins_cache+ updates_available = self._count_available_updates()+ if updates_available <= 0:+ gr.Info("No Plugin Update is available")+ elif updates_available == 1:+ gr.Info("One Plugin Update is available")+ else:+ gr.Info(f"{updates_available} Plugin Updates are available")+ return self._build_plugins_html(), self._build_community_plugins_html()++ def _count_available_updates(self) -> int:+ try:+ plugins_info = self.app.plugin_manager.get_plugins_info()+ remote_plugins_info = self.app.plugin_manager.get_merged_catalog_entries(use_remote=False)+ count = 0+ for plugin in plugins_info:+ if plugin.get('system'):+ continue+ if not plugin.get('uninstallable', True):+ continue+ plugin_id = plugin.get('id')+ if not plugin_id or plugin_id not in remote_plugins_info:+ continue+ remote_entry = remote_plugins_info[plugin_id]+ if compare_release_metadata(remote_entry, plugin) > 0:+ count += 1+ return count+ except Exception:+ return 0+def _enable_plugin_after_install(self, url: str):try:- plugin_id = url.split('/')[-1].replace('.git', '')+ plugin_id = plugin_id_from_url(url)enabled_plugins = self.server_config.get("enabled_plugins", [])if plugin_id not in enabled_plugins:enabled_plugins.append(plugin_id)@@ -415,6 +547,11 @@ class PluginManagerUIPlugin(WAN2GPPlugin):was_enabled = self._enable_plugin_after_install(url)if was_enabled:result_message = result_message.replace("Please enable it", "It has been auto-enabled")+ plugin_id = plugin_id_from_url(url)+ if plugin_id:+ self.app.plugin_manager.record_plugin_metadata(plugin_id, url=url)+ if hasattr(self, '_community_plugins_cache'):+ del self._community_plugins_cachegr.Info(result_message)else:gr.Warning(result_message)diff --git a/plugins/wan2gp-sample/plugin.py b/plugins/wan2gp-sample/plugin.pyindex c87af51..017f3f6 100644--- a/plugins/wan2gp-sample/plugin.py+++ b/plugins/wan2gp-sample/plugin.py@@ -18,10 +18,6 @@ def release_GPU(state):class ConfigTabPlugin(WAN2GPPlugin):def __init__(self):super().__init__()- self.name = PlugIn_Name- self.version = "1.0.0"- self.description = "Sample Source Code to Design Plugins"- self.uninstallable = Falsedef setup_ui(self):self.request_global("get_current_model_settings")diff --git a/plugins/wan2gp-sample/plugin_info.json b/plugins/wan2gp-sample/plugin_info.jsonnew file mode 100644index 0000000..63e895c--- /dev/null+++ b/plugins/wan2gp-sample/plugin_info.json@@ -0,0 +1,9 @@+{+ "name": "Sample Plugin",+ "author": "DeepBeepMeep",+ "version": "1.0.0",+ "description": "Sample Source Code to Design Plugins",+ "date": "",+ "wan2gp_version": ""+}+diff --git a/shared/utils/plugins.py b/shared/utils/plugins.pyindex 50247a3..bd03304 100644--- a/shared/utils/plugins.py+++ b/shared/utils/plugins.py@@ -3,6 +3,8 @@ import sysimport importlibimport importlib.utilimport inspect+import re+import datetimefrom typing import Dict, Any, Optional, List, Union, Setfrom dataclasses import dataclassimport gradio as gr@@ -12,7 +14,145 @@ import gitimport shutilimport statimport json+import requestsvideo_gen_label = "Video Generator"++COMMUNITY_PLUGINS_URL = "https://github.com/deepbeepmeep/Wan2GP/raw/refs/heads/main/plugins.json"+PLUGIN_CATALOG_FILENAME = "plugins.json"+PLUGIN_LOCAL_CATALOG_FILENAME = "plugins_local.json"+PLUGIN_METADATA_FILENAME = "plugin_info.json"+PENDING_DELETIONS_KEY = "pending_plugin_deletions"++def _has_value(value: Any) -> bool:+ if value is None:+ return False+ if isinstance(value, str):+ return value.strip() != ""+ return True++def _split_github_repo(url: str) -> Optional[tuple]:+ if not isinstance(url, str):+ return None+ cleaned = url.strip()+ if not cleaned:+ return None+ cleaned = cleaned.split("?", 1)[0].split("#", 1)[0]+ if cleaned.startswith("[email protected]:"):+ cleaned = "https://github.com/" + cleaned[len("[email protected]:"):]+ cleaned = cleaned.rstrip("/")+ marker = "github.com/"+ idx = cleaned.lower().find(marker)+ if idx < 0:+ return None+ tail = cleaned[idx + len(marker):]+ parts = [part for part in tail.split("/") if part]+ if len(parts) < 2:+ return None+ owner, repo = parts[0], parts[1]+ if repo.endswith(".git"):+ repo = repo[:-4]+ if not owner or not repo:+ return None+ return owner, repo++def normalize_plugin_url(url: str) -> str:+ if not isinstance(url, str):+ return ""+ cleaned = url.strip()+ if not cleaned:+ return ""+ cleaned = cleaned.split("?", 1)[0].split("#", 1)[0]+ if cleaned.startswith("[email protected]:"):+ cleaned = "https://github.com/" + cleaned[len("[email protected]:"):]+ cleaned = cleaned.rstrip("/")+ repo_info = _split_github_repo(cleaned)+ if repo_info:+ owner, repo = repo_info+ return f"https://github.com/{owner}/{repo}"+ if cleaned.endswith(".git"):+ cleaned = cleaned[:-4]+ return cleaned.rstrip("/")++def _parse_version_parts(version: str) -> List[Any]:+ if not isinstance(version, str):+ return []+ version = version.strip()+ if not version:+ return []+ parts = re.split(r"[^0-9A-Za-z]+", version)+ tokens = []+ for part in parts:+ if not part:+ continue+ for token in re.findall(r"\d+|[A-Za-z]+", part):+ if token.isdigit():+ tokens.append((0, int(token)))+ else:+ tokens.append((1, token.lower()))+ return tokens++def compare_versions(left: str, right: str) -> int:+ left_text = left if isinstance(left, str) else ""+ right_text = right if isinstance(right, str) else ""+ left_has_digits = bool(re.search(r"\d", left_text))+ right_has_digits = bool(re.search(r"\d", right_text))+ if left_has_digits != right_has_digits:+ return 1 if left_has_digits else -1+ left_parts = _parse_version_parts(left_text)+ right_parts = _parse_version_parts(right_text)+ max_len = max(len(left_parts), len(right_parts))+ if max_len == 0:+ return 0+ filler = (0, 0)+ for idx in range(max_len):+ left_part = left_parts[idx] if idx < len(left_parts) else filler+ right_part = right_parts[idx] if idx < len(right_parts) else filler+ if left_part == right_part:+ continue+ return 1 if left_part > right_part else -1+ return 0++def _parse_date(value: Any) -> Optional[datetime.datetime]:+ if not isinstance(value, str):+ return None+ text = value.strip()+ if not text:+ return None+ if text.endswith("Z"):+ text = text[:-1] + "+00:00"+ try:+ return datetime.datetime.fromisoformat(text)+ except ValueError:+ return None++def compare_release_metadata(left: Dict[str, Any], right: Dict[str, Any]) -> int:+ left_date = _parse_date(left.get("date"))+ right_date = _parse_date(right.get("date"))+ if left_date or right_date:+ if left_date and right_date:+ if left_date != right_date:+ return 1 if left_date > right_date else -1+ elif left_date:+ return 1+ else:+ return -1+ return compare_versions(left.get("version", ""), right.get("version", ""))++def is_wangp_compatible(required_version: str, current_version: str) -> bool:+ if not _has_value(required_version):+ return True+ return compare_versions(current_version or "", required_version) >= 0++def plugin_id_from_url(url: str) -> str:+ if not isinstance(url, str):+ return ""+ repo_info = _split_github_repo(url)+ if repo_info:+ return repo_info[1]+ clean = normalize_plugin_url(url)+ if not clean:+ return ""+ return clean.split("/")[-1]def auto_install_and_enable_default_plugins(manager: 'PluginManager', wgp_globals: dict):server_config = wgp_globals.get("server_config")server_config_filename = wgp_globals.get("server_config_filename")@@ -21,13 +161,11 @@ def auto_install_and_enable_default_plugins(manager: 'PluginManager', wgp_globalprint("[Plugins] WARNING: Cannot auto-install/enable default plugins. Server config not found.")return- default_plugins = {- "wan2gp-gallery": "https://github.com/Tophness/wan2gp-gallery.git",- "wan2gp-lora-multipliers-ui": "https://github.com/Tophness/wan2gp-lora-multipliers-ui.git"- }+ default_plugins = {}config_modified = Falseenabled_plugins = server_config.get("enabled_plugins", [])+ newly_installed = []for repo_name, url in default_plugins.items():target_dir = os.path.join(manager.plugins_dir, repo_name)@@ -37,13 +175,16 @@ def auto_install_and_enable_default_plugins(manager: 'PluginManager', wgp_globalprint(f"[Plugins] Install result for {repo_name}: {result}")if "[Success]" in result:- if repo_name not in enabled_plugins:- enabled_plugins.append(repo_name)- config_modified = True+ newly_installed.append(repo_name)+ for repo_name in newly_installed:+ if repo_name in enabled_plugins:+ enabled_plugins.remove(repo_name)+ config_modified = True+if config_modified:print("[Plugins] Disabling newly installed default plugins...")- server_config["enabled_plugins"] = []+ server_config["enabled_plugins"] = enabled_pluginstry:with open(server_config_filename, 'w', encoding='utf-8') as f:json.dump(server_config, f, indent=4)@@ -59,6 +200,9 @@ SYSTEM_PLUGINS = ["wan2gp-plugin-manager","wan2gp-about",]+BUNDLED_PLUGINS = {+ "wan2gp-sample",+}USER_PLUGIN_INSERT_POSITION = 3@@ -158,6 +302,512 @@ class PluginManager:self.data_hooks: Dict[str, List[callable]] = {}self.restricted_globals: Set[str] = set()self.custom_js_snippets: List[str] = []+ self.repo_root = os.path.abspath(os.getcwd())+ self.catalog_path = os.path.join(self.repo_root, PLUGIN_CATALOG_FILENAME)+ self.local_catalog_path = os.path.join(self.repo_root, PLUGIN_LOCAL_CATALOG_FILENAME)+ self.server_config: Optional[Dict[str, Any]] = None+ self.server_config_filename: str = ""++ def set_server_config(self, server_config: Optional[Dict[str, Any]], server_config_filename: str = "") -> None:+ self.server_config = server_config if isinstance(server_config, dict) else None+ self.server_config_filename = server_config_filename or ""++ def _save_server_config(self) -> None:+ if not self.server_config or not self.server_config_filename:+ return+ try:+ with open(self.server_config_filename, "w", encoding="utf-8") as writer:+ writer.write(json.dumps(self.server_config, indent=4))+ except Exception as e:+ print(f"[PluginManager] Failed to write config file '{self.server_config_filename}': {e}")++ def _get_pending_deletions(self) -> List[str]:+ if not self.server_config:+ return []+ pending = self.server_config.get(PENDING_DELETIONS_KEY, [])+ if not isinstance(pending, list):+ return []+ cleaned = []+ for item in pending:+ if isinstance(item, str) and item.strip():+ cleaned.append(item.strip())+ return cleaned++ def _set_pending_deletions(self, pending: List[str]) -> None:+ if not self.server_config:+ return+ unique = []+ seen = set()+ for item in pending:+ if not isinstance(item, str):+ continue+ key = item.strip()+ if not key or key in seen:+ continue+ seen.add(key)+ unique.append(key)+ self.server_config[PENDING_DELETIONS_KEY] = unique+ self._save_server_config()++ def _add_pending_deletion(self, plugin_id: str) -> None:+ if not plugin_id:+ return+ pending = self._get_pending_deletions()+ if plugin_id not in pending:+ pending.append(plugin_id)+ self._set_pending_deletions(pending)++ def _clear_pending_deletion(self, plugin_id: str) -> None:+ if not plugin_id:+ return+ pending = self._get_pending_deletions()+ if plugin_id in pending:+ pending = [item for item in pending if item != plugin_id]+ self._set_pending_deletions(pending)++ def _is_cleanup_candidate(self, path: str) -> bool:+ try:+ for entry in os.scandir(path):+ name = entry.name+ if name.startswith("."):+ continue+ if entry.is_file(follow_symlinks=False):+ if name.endswith(".pyc"):+ continue+ return False+ if entry.is_dir(follow_symlinks=False):+ if name == "__pycache__":+ continue+ if not self._is_cleanup_candidate(entry.path):+ return False+ return True+ except Exception:+ return False++ def cleanup_pending_deletions(self) -> None:+ pending = self._get_pending_deletions()+ if not pending:+ return+ remaining = []+ for plugin_id in pending:+ plugin_dir = os.path.join(self.plugins_dir, plugin_id)+ if not os.path.isdir(plugin_dir):+ continue+ if self._is_cleanup_candidate(plugin_dir):+ try:+ shutil.rmtree(plugin_dir, onerror=self._remove_readonly)+ continue+ except Exception:+ remaining.append(plugin_id)+ continue+ remaining.append(plugin_id)+ self._set_pending_deletions(remaining)++ def _coerce_bool(self, value: Any, default: bool = True) -> bool:+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ lowered = value.strip().lower()+ if lowered in ("true", "1", "yes"):+ return True+ if lowered in ("false", "0", "no"):+ return False+ return default++ def _load_json_file(self, path: str) -> Optional[Any]:+ if not path or not os.path.isfile(path):+ return None+ last_error = None+ for encoding in ("utf-8", "utf-8-sig"):+ try:+ with open(path, "r", encoding=encoding) as reader:+ return json.load(reader)+ except UnicodeDecodeError as e:+ last_error = e+ continue+ except json.JSONDecodeError as e:+ last_error = e+ if encoding == "utf-8" and "UTF-8 BOM" in str(e):+ continue+ break+ except Exception as e:+ last_error = e+ break+ if last_error is not None:+ print(f"[PluginManager] Failed to read JSON from {path}: {last_error}")+ return None++ def _write_json_file(self, path: str, payload: Any) -> None:+ if not path:+ return+ try:+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ with open(path, "w", encoding="utf-8") as writer:+ json.dump(payload, writer, indent=2)+ except Exception as e:+ print(f"[PluginManager] Failed to write JSON to {path}: {e}")++ def _load_plugin_metadata(self, plugin_path: str) -> Optional[Dict[str, Any]]:+ metadata_path = os.path.join(plugin_path, PLUGIN_METADATA_FILENAME)+ payload = self._load_json_file(metadata_path)+ if not isinstance(payload, dict):+ return None+ return self._normalize_plugin_metadata(payload)++ def _normalize_plugin_metadata(self, payload: Dict[str, Any]) -> Dict[str, Any]:+ metadata = dict(payload)+ for key in ("name", "version", "description", "author", "date", "wan2gp_version"):+ value = metadata.get(key)+ if isinstance(value, str):+ metadata[key] = value.strip()+ elif value is None:+ metadata[key] = ""+ else:+ metadata[key] = str(value)+ legacy_version = metadata.get("wangp_version")+ if not _has_value(metadata.get("wan2gp_version")) and _has_value(legacy_version):+ metadata["wan2gp_version"] = str(legacy_version).strip()+ metadata.pop("wangp_version", None)+ metadata["url"] = ""+ metadata["uninstallable"] = self._coerce_bool(metadata.get("uninstallable"), default=True)+ return metadata++ def _apply_metadata_to_plugin(self, plugin: WAN2GPPlugin, metadata: Optional[Dict[str, Any]], is_system: bool) -> None:+ if not metadata:+ if is_system:+ plugin.uninstallable = False+ return+ for key in ("name", "version", "description", "author", "date", "wan2gp_version"):+ if key in metadata:+ setattr(plugin, key, metadata.get(key))+ if not _has_value(getattr(plugin, "wan2gp_version", "")) and _has_value(metadata.get("wangp_version")):+ setattr(plugin, "wan2gp_version", str(metadata.get("wangp_version")).strip())+ if "uninstallable" in metadata:+ plugin.uninstallable = self._coerce_bool(metadata.get("uninstallable"), default=True)+ if is_system:+ plugin.uninstallable = False++ def _normalize_catalog_entry(self, payload: Dict[str, Any]) -> Dict[str, Any]:+ entry = dict(payload)+ for key in ("name", "author", "version", "description", "url", "date", "wan2gp_version", "last_check"):+ value = entry.get(key)+ if key == "url":+ if isinstance(value, str):+ entry[key] = normalize_plugin_url(value)+ elif value is None:+ entry[key] = ""+ else:+ entry[key] = normalize_plugin_url(str(value))+ continue+ if isinstance(value, str):+ entry[key] = value.strip()+ elif value is None:+ entry[key] = ""+ else:+ entry[key] = str(value)+ legacy_version = entry.get("wangp_version")+ if not _has_value(entry.get("wan2gp_version")) and _has_value(legacy_version):+ entry["wan2gp_version"] = str(legacy_version).strip()+ entry.pop("wangp_version", None)+ return entry++ def _merge_entry_fields(self, primary: Dict[str, Any], secondary: Optional[Dict[str, Any]]) -> Dict[str, Any]:+ result = dict(primary) if primary else {}+ if not secondary:+ return result+ for key, value in secondary.items():+ if _has_value(result.get(key)):+ continue+ if _has_value(value):+ result[key] = value+ return result++ def _merge_catalog_entries(+ self,+ base_entries: List[Dict[str, Any]],+ local_entries: List[Dict[str, Any]],+ ) -> Dict[str, Dict[str, Any]]:+ base_map: Dict[str, Dict[str, Any]] = {}+ local_map: Dict[str, Dict[str, Any]] = {}+ for entry in base_entries:+ plugin_id = entry.get("id") or plugin_id_from_url(entry.get("url", ""))+ if not plugin_id:+ continue+ base_map[plugin_id] = self._normalize_catalog_entry(entry)+ for entry in local_entries:+ plugin_id = entry.get("id") or plugin_id_from_url(entry.get("url", ""))+ if not plugin_id:+ continue+ local_map[plugin_id] = self._normalize_catalog_entry(entry)++ merged: Dict[str, Dict[str, Any]] = {}+ all_ids = set(base_map.keys()) | set(local_map.keys())+ for plugin_id in all_ids:+ base_entry = base_map.get(plugin_id)+ local_entry = local_map.get(plugin_id)+ if base_entry and local_entry:+ comparison = compare_release_metadata(local_entry, base_entry)+ if comparison > 0:+ merged_entry = dict(local_entry)+ else:+ merged_entry = dict(base_entry)+ if _has_value(local_entry.get("last_check")):+ merged_entry["last_check"] = local_entry.get("last_check")+ merged[plugin_id] = merged_entry+ else:+ merged[plugin_id] = base_entry or local_entry+ return merged++ def _fetch_remote_catalog_entries(self) -> List[Dict[str, Any]]:+ try:+ response = requests.get(COMMUNITY_PLUGINS_URL, timeout=10)+ response.raise_for_status()+ payload = response.json()+ if isinstance(payload, list):+ return [self._normalize_catalog_entry(entry) for entry in payload if isinstance(entry, dict)]+ except Exception as e:+ print(f"[PluginManager] Could not fetch community plugins info: {e}")+ return []++ def load_catalog_entries(self, use_remote: bool = True) -> List[Dict[str, Any]]:+ entries = None # self._fetch_remote_catalog_entries() if use_remote else []+ if not entries:+ payload = self._load_json_file(self.catalog_path)+ if isinstance(payload, list):+ entries = [self._normalize_catalog_entry(entry) for entry in payload if isinstance(entry, dict)]+ return entries++ def load_local_catalog_entries(self) -> List[Dict[str, Any]]:+ payload = self._load_json_file(self.local_catalog_path)+ if isinstance(payload, list):+ return [self._normalize_catalog_entry(entry) for entry in payload if isinstance(entry, dict)]+ return []++ def get_merged_catalog_entries(self, use_remote: bool = True) -> Dict[str, Dict[str, Any]]:+ base_entries = self.load_catalog_entries(use_remote=use_remote)+ local_entries = self.load_local_catalog_entries()+ return self._merge_catalog_entries(base_entries, local_entries)++ def _build_plugin_json_url(self, url: str) -> str:+ repo_info = _split_github_repo(url)+ if not repo_info:+ return ""+ owner, repo = repo_info+ return f"https://github.com/{owner}/{repo}/raw/HEAD/{PLUGIN_METADATA_FILENAME}"++ def _fetch_plugin_json(self, url: str, quiet: bool = False) -> Optional[Dict[str, Any]]:+ plugin_json_url = self._build_plugin_json_url(url)+ if not plugin_json_url:+ return None+ try:+ response = requests.get(plugin_json_url, timeout=10)+ if response.status_code != 200:+ return None+ payload = response.json()+ if not isinstance(payload, dict):+ return None+ return self._normalize_plugin_metadata(payload)+ except Exception as e:+ if not quiet:+ print(f"[PluginManager] Could not fetch {PLUGIN_METADATA_FILENAME} for {url}: {e}")+ return None++ def _metadata_to_catalog_entry(self, metadata: Dict[str, Any]) -> Dict[str, Any]:+ entry = {}+ for key in ("name", "author", "version", "description", "date", "wan2gp_version"):+ entry[key] = metadata.get(key, "")+ return self._normalize_catalog_entry(entry)++ def _extract_catalog_metadata(self, entry: Dict[str, Any]) -> Dict[str, Any]:+ payload = {}+ for key in ("name", "author", "version", "description", "url", "date", "wan2gp_version"):+ payload[key] = entry.get(key, "")+ return self._normalize_catalog_entry(payload)++ def _find_catalog_entry(self, plugin_id: str, url: str = "", use_remote: bool = False) -> Optional[Dict[str, Any]]:+ entries = self.load_catalog_entries(use_remote=use_remote)+ target_id = plugin_id.strip().lower() if isinstance(plugin_id, str) else ""+ target_url = normalize_plugin_url(url).lower() if isinstance(url, str) else ""+ for entry in entries:+ entry_url = entry.get("url", "")+ entry_id = entry.get("id") or plugin_id_from_url(entry_url)+ entry_id = entry_id.strip().lower() if isinstance(entry_id, str) else ""+ entry_url_norm = normalize_plugin_url(entry_url).lower() if isinstance(entry_url, str) else ""+ if target_id and entry_id and entry_id == target_id:+ return self._normalize_catalog_entry(entry)+ if target_url and entry_url_norm and entry_url_norm == target_url:+ return self._normalize_catalog_entry(entry)+ return None++ def _get_git_remote_url(self, plugin_path: str) -> str:+ if not plugin_path:+ return ""+ git_dir = os.path.join(plugin_path, ".git")+ if not os.path.isdir(git_dir):+ return ""+ try:+ repo = git.Repo(plugin_path)+ if repo.remotes:+ return repo.remotes.origin.url+ except Exception:+ return ""+ return ""++ def refresh_catalog(self, installed_only: bool = True, use_remote: bool = True) -> Dict[str, int]:+ base_entries = self.load_catalog_entries(use_remote=False)+ local_entries = self.load_local_catalog_entries()+ merged_catalog = self._merge_catalog_entries(base_entries, local_entries)+ local_map: Dict[str, Dict[str, Any]] = {}+ for entry in local_entries:+ plugin_id = entry.get("id") or plugin_id_from_url(entry.get("url", ""))+ if plugin_id:+ local_map[plugin_id] = self._normalize_catalog_entry(entry)++ def _info_to_entry(info: Dict[str, Any]) -> Dict[str, Any]:+ return {+ "name": info.get("name", ""),+ "author": info.get("author", ""),+ "version": info.get("version", ""),+ "description": info.get("description", ""),+ "url": info.get("url", ""),+ "date": info.get("date", ""),+ "wan2gp_version": info.get("wan2gp_version", ""),+ }++ targets: List[Dict[str, Any]] = []+ if installed_only:+ installed_plugins = [info for info in self.get_plugins_info() if not info.get("system")]+ for info in installed_plugins:+ plugin_id = info.get("id", "")+ if not plugin_id:+ continue+ base_entry = merged_catalog.get(plugin_id, {})+ git_url = self._get_git_remote_url(info.get("path", ""))+ url = normalize_plugin_url(base_entry.get("url") or info.get("url") or git_url or "")+ if git_url and plugin_id_from_url(git_url) == plugin_id:+ url = normalize_plugin_url(git_url)+ if not _has_value(url):+ continue+ targets.append(+ {+ "id": plugin_id,+ "url": url,+ "base_entry": base_entry,+ "info_entry": _info_to_entry(info),+ }+ )+ else:+ for plugin_id, entry in merged_catalog.items():+ url = normalize_plugin_url(entry.get("url") or "")+ if not _has_value(url):+ continue+ targets.append({"id": plugin_id, "url": url, "base_entry": entry, "info_entry": {}})++ checked = 0+ updated = 0+ updates_available = 0+ for target in targets:+ plugin_id = target["id"]+ url = target["url"]+ base_entry = target.get("base_entry", {})+ info_entry = target.get("info_entry", {})+ checked += 1+ metadata = self._fetch_plugin_json(url, quiet=True)+ if not metadata:+ continue+ catalog_entry = self._metadata_to_catalog_entry(metadata)+ if _has_value(url):+ catalog_entry_url = catalog_entry.get("url", "")+ if not _has_value(catalog_entry_url) or plugin_id_from_url(catalog_entry_url) != plugin_id:+ catalog_entry["url"] = url+ catalog_entry = self._merge_entry_fields(catalog_entry, base_entry)+ if info_entry:+ catalog_entry = self._merge_entry_fields(catalog_entry, info_entry)+ catalog_entry["last_check"] = datetime.datetime.now().isoformat(timespec="seconds")+ catalog_entry = self._normalize_catalog_entry(catalog_entry)+ existing_entry = local_map.get(plugin_id, {})+ if info_entry:+ if compare_release_metadata(catalog_entry, info_entry) > 0:+ updates_available += 1+ elif existing_entry:+ if compare_release_metadata(catalog_entry, existing_entry) > 0:+ updates_available += 1+ local_map[plugin_id] = catalog_entry+ updated += 1++ if updated > 0:+ self._write_json_file(self.local_catalog_path, list(local_map.values()))+ return {"checked": checked, "updated": updated, "updates_available": updates_available}++ def record_plugin_metadata(self, plugin_id: str, url: str = "") -> bool:+ if not plugin_id:+ return False+ url = normalize_plugin_url(url)+ plugin_path = os.path.join(self.plugins_dir, plugin_id)+ metadata = self._load_plugin_metadata(plugin_path) if os.path.isdir(plugin_path) else None+ plugin_json_found = metadata is not None+ if not metadata and _has_value(url):+ metadata = self._fetch_plugin_json(url)+ plugin_json_found = metadata is not None+ if not metadata:+ plugin_info = next((info for info in self.get_plugins_info() if info.get("id") == plugin_id), None)+ if plugin_info:+ metadata = {+ "name": plugin_info.get("name", ""),+ "version": plugin_info.get("version", ""),+ "description": plugin_info.get("description", ""),+ "author": plugin_info.get("author", ""),+ "url": plugin_info.get("url", ""),+ "date": plugin_info.get("date", ""),+ "wan2gp_version": plugin_info.get("wan2gp_version", ""),+ }+ if not metadata:+ return False++ catalog_entry = self._metadata_to_catalog_entry(metadata)+ if _has_value(url):+ catalog_entry_url = catalog_entry.get("url", "")+ if not _has_value(catalog_entry_url) or plugin_id_from_url(catalog_entry_url) != plugin_id:+ catalog_entry["url"] = url++ merged_catalog = self.get_merged_catalog_entries(use_remote=False)+ catalog_entry = self._merge_entry_fields(catalog_entry, merged_catalog.get(plugin_id, {}))+ base_entry = self._find_catalog_entry(plugin_id, url=url, use_remote=False)+ if base_entry:+ catalog_entry = self._merge_entry_fields(catalog_entry, base_entry)+ if plugin_json_found:+ catalog_entry["last_check"] = datetime.datetime.now().isoformat(timespec="seconds")+ catalog_entry = self._normalize_catalog_entry(catalog_entry)++ local_entries = self.load_local_catalog_entries()+ local_map: Dict[str, Dict[str, Any]] = {}+ for entry in local_entries:+ existing_id = entry.get("id") or plugin_id_from_url(entry.get("url", ""))+ if existing_id:+ local_map[existing_id] = self._normalize_catalog_entry(entry)+ local_map[plugin_id] = catalog_entry+ self._write_json_file(self.local_catalog_path, list(local_map.values()))+ return True++ def merge_local_catalog(self) -> str:+ local_entries = self.load_local_catalog_entries()+ if not local_entries:+ return "[Info] No local catalog entries to merge."+ base_entries = self.load_catalog_entries(use_remote=False)+ merged = self._merge_catalog_entries(base_entries, local_entries)+ merged_list = []+ for entry in merged.values():+ entry.pop("last_check", None)+ merged_list.append(entry)+ merged_list.sort(key=lambda item: item.get("name", ""))+ self._write_json_file(self.catalog_path, merged_list)+ try:+ os.remove(self.local_catalog_path)+ except FileNotFoundError:+ pass+ except Exception as e:+ return f"[Warning] Catalog merged, but failed to remove {self.local_catalog_path}: {e}"+ return "[Success] Catalog merged and local overrides removed."def get_plugins_info(self) -> List[Dict[str, str]]:plugins_info = []@@ -169,22 +819,46 @@ class PluginManager:'name': dir_name,'version': 'N/A','description': 'No description provided.',+ 'author': '',+ 'url': '',+ 'date': '',+ 'wan2gp_version': '','path': plugin_path,'system': is_system,'uninstallable': True,}- try:- module = importlib.import_module(f"{dir_name}.plugin")- for name, obj in inspect.getmembers(module, inspect.isclass):- if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:- instance = obj()- info['name'] = instance.name- info['version'] = instance.version- info['description'] = instance.description- info['uninstallable'] = bool(getattr(instance, 'uninstallable', True))- break- except Exception as e:- print(f"Could not load metadata for plugin {dir_name}: {e}")+ metadata = self._load_plugin_metadata(plugin_path)+ if metadata:+ info['name'] = metadata.get('name', info['name'])+ info['version'] = metadata.get('version', info['version'])+ info['description'] = metadata.get('description', info['description'])+ info['author'] = metadata.get('author', info['author'])+ info['url'] = metadata.get('url', info['url'])+ info['date'] = metadata.get('date', info['date'])+ info['wan2gp_version'] = metadata.get('wan2gp_version', info['wan2gp_version'])+ info['uninstallable'] = bool(metadata.get('uninstallable', info['uninstallable']))+ else:+ try:+ module = importlib.import_module(f"{dir_name}.plugin")+ for name, obj in inspect.getmembers(module, inspect.isclass):+ if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:+ instance = obj()+ info['name'] = instance.name+ info['version'] = instance.version+ info['description'] = instance.description+ info['uninstallable'] = bool(getattr(instance, 'uninstallable', True))+ break+ except Exception as e:+ print(f"Could not load metadata for plugin {dir_name}: {e}")+ if is_system:+ info['uninstallable'] = False+ if info['id'] in BUNDLED_PLUGINS:+ info['uninstallable'] = False+ if not is_system:+ merged_catalog = self.get_merged_catalog_entries(use_remote=False)+ catalog_entry = merged_catalog.get(info.get("id", ""))+ if catalog_entry:+ info = self._merge_entry_fields(info, self._extract_catalog_metadata(catalog_entry))plugins_info.append(info)plugins_info.sort(key=lambda p: (not p['system'], p['name']))@@ -200,6 +874,8 @@ class PluginManager:def _is_plugin_uninstallable(self, plugin_id: str) -> bool:if plugin_id in SYSTEM_PLUGINS:return False+ if plugin_id in BUNDLED_PLUGINS:+ return Falsetry:for info in self.get_plugins_info():if info.get('id') == plugin_id:@@ -220,6 +896,7 @@ class PluginManager: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."+ self._add_pending_deletion(plugin_id)try:shutil.rmtree(target_dir, onerror=self._remove_readonly)@@ -238,13 +915,20 @@ class PluginManager:try:if progress is not None: progress(0, desc=f"Updating '{plugin_id}'...")repo = git.Repo(target_dir)+ if not repo.remotes:+ return f"[Error] Update failed: no git remote configured for '{plugin_id}'."origin = repo.remotes.originif progress is not None: progress(0.2, desc=f"Fetching updates for '{plugin_id}'...")origin.fetch()-+local_commit = repo.head.commit- remote_commit = origin.refs[repo.active_branch.name].commit+ try:+ branch_name = repo.active_branch.name+ remote_ref = origin.refs[branch_name]+ remote_commit = remote_ref.commit+ except Exception:+ return f"[Error] Update failed: could not resolve remote branch for '{plugin_id}'."if local_commit == remote_commit:return f"[Info] Plugin '{plugin_id}' is already up to date."@@ -261,7 +945,13 @@ class PluginManager:return f"[Success] Plugin '{plugin_id}' updated. Please restart WanGP for changes to take effect."except git.exc.GitCommandError as e:traceback.print_exc()- return f"[Error] Git update failed for '{plugin_id}': {e.stderr}"+ stderr = (e.stderr or str(e)).strip()+ lowered = stderr.lower()+ if any(token in lowered for token in ("not found", "repository", "could not read from remote")):+ return f"[Error] Update failed: remote repository not found or unreachable for '{plugin_id}'."+ if any(token in lowered for token in ("authentication", "access denied", "permission denied")):+ return f"[Error] Update failed: access denied to remote for '{plugin_id}'."+ return f"[Error] Git update failed for '{plugin_id}': {stderr}"except Exception as e:traceback.print_exc()return f"[Error] An unexpected error occurred during update of '{plugin_id}': {str(e)}"@@ -318,18 +1008,26 @@ class PluginManager:return f"[CRITICAL ERROR] Reinstallation failed AND could not restore backup. Plugin '{plugin_id}' is now in a broken state. Please manually rename '{backup_dir}' back to '{target_dir}'. Original error: {install_msg}. Restore error: {restore_e}"def install_plugin_from_url(self, git_url: str, progress=None):- if not git_url or not git_url.startswith("https://github.com/"):- return "[Error] Invalid GitHub URL."+ cleaned_url = normalize_plugin_url(git_url)+ if not cleaned_url or not cleaned_url.startswith("https://github.com/"):+ return "[Error] Invalid URL."try:- repo_name = git_url.split('/')[-1].replace('.git', '')+ repo_name = plugin_id_from_url(cleaned_url)+ if not repo_name:+ return "[Error] Invalid URL."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."if progress is not None: progress(0.1, desc=f"Cloning '{repo_name}'...")- git.Repo.clone_from(git_url, target_dir)+ git.Repo.clone_from(cleaned_url, target_dir)++ plugin_entry = os.path.join(target_dir, "plugin.py")+ if not os.path.isfile(plugin_entry):+ shutil.rmtree(target_dir, onerror=self._remove_readonly)+ return "[Error] Invalid Plugin."requirements_path = os.path.join(target_dir, 'requirements.txt')if os.path.exists(requirements_path):@@ -353,17 +1051,41 @@ class PluginManager:if not os.path.exists(init_path):with open(init_path, 'w') as f:pass++ self._strip_uninstallable_flag(target_dir)if progress is not None: progress(1.0, desc="Installation complete.")+ self._clear_pending_deletion(repo_name)return f"[Success] Plugin '{repo_name}' installed. Please enable it in the list and restart WanGP."except git.exc.GitCommandError as e:traceback.print_exc()- return f"[Error] Git clone failed: {e.stderr}"+ stderr = (e.stderr or str(e)).strip()+ lowered = stderr.lower()+ if any(token in lowered for token in ("not found", "repository", "fatal", "could not read from remote")):+ return "[Error] Invalid URL."+ return f"[Error] Git clone failed: {stderr}"except Exception as e:traceback.print_exc()return f"[Error] An unexpected error occurred: {str(e)}"+ def _strip_uninstallable_flag(self, plugin_dir: str) -> None:+ if not plugin_dir or not os.path.isdir(plugin_dir):+ return+ metadata_path = os.path.join(plugin_dir, PLUGIN_METADATA_FILENAME)+ payload = self._load_json_file(metadata_path)+ if not isinstance(payload, dict):+ return+ if "uninstallable" not in payload:+ return+ if not self._coerce_bool(payload.get("uninstallable"), default=True):+ payload.pop("uninstallable", None)+ try:+ with open(metadata_path, "w", encoding="utf-8") as writer:+ json.dump(payload, writer, indent=2, ensure_ascii=True)+ except Exception as e:+ print(f"[PluginManager] Failed to update {metadata_path}: {e}")+def discover_plugins(self) -> List[str]:discovered = []for item in os.listdir(self.plugins_dir):@@ -381,10 +1103,16 @@ class PluginManager:continuetry:module = importlib.import_module(f"{plugin_dir_name}.plugin")+ plugin_path = os.path.join(self.plugins_dir, plugin_dir_name)+ metadata = self._load_plugin_metadata(plugin_path)+ is_bundled = plugin_dir_name in BUNDLED_PLUGINSfor name, obj in inspect.getmembers(module, inspect.isclass):if issubclass(obj, WAN2GPPlugin) and obj != WAN2GPPlugin:plugin = obj()+ self._apply_metadata_to_plugin(plugin, metadata, plugin_dir_name in SYSTEM_PLUGINS)+ if is_bundled:+ plugin.uninstallable = Falseplugin.setup_ui()self.plugins[plugin_dir_name] = pluginif plugin.custom_js_snippets:@@ -522,9 +1250,12 @@ class WAN2GPApplication:auto_install_and_enable_default_plugins(self.plugin_manager, wgp_globals)server_config = wgp_globals.get("server_config")+ server_config_filename = wgp_globals.get("server_config_filename", "")if not server_config:print("[PluginManager] ERROR: server_config not found in globals.")return+ self.plugin_manager.set_server_config(server_config, server_config_filename)+ self.plugin_manager.cleanup_pending_deletions()self.enabled_plugins = server_config.get("enabled_plugins", [])self.plugin_manager.load_plugins_from_directory(self.enabled_plugins)diff --git a/shared/utils/utils.py b/shared/utils/utils.pyindex 5901108..c30b4cc 100644--- a/shared/utils/utils.py+++ b/shared/utils/utils.py@@ -394,6 +394,7 @@ def resize_and_remove_background(img_list, budget_width, budget_height, rm_backgdef fit_image_into_canvas(ref_img, image_size, canvas_tf_bg =127.5, device ="cpu", full_frame = False, outpainting_dims = None, return_mask = False, return_image = False):inpaint_color = to_rgb_tensor(canvas_tf_bg, device=device, dtype=torch.float) / 127.5 - 1+ inpaint_color = inpaint_color.unsqueeze(1)ref_width, ref_height = ref_img.sizeif (ref_height, ref_width) == image_size and outpainting_dims == None:diff --git a/wgp.py b/wgp.pyindex 6c4e6ec..169dac6 100644--- a/wgp.py+++ b/wgp.py@@ -85,7 +85,7 @@ AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAMECONFIG_FILENAME = "wgp_config.json"PROMPT_VARS_MAX = 10target_mmgp_version = "3.7.2"-WanGP_version = "10.51"+WanGP_version = "10.52"settings_version = 2.44max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -2024,6 +2024,21 @@ def _parse_args():default="",help="Override output directory for CLI processing (use with --process)")+ parser.add_argument(+ "--refresh-catalog",+ action="store_true",+ help="Refresh local plugin metadata for installed external plugins"+ )+ parser.add_argument(+ "--refresh-full-catalog",+ action="store_true",+ help="Refresh local plugin metadata for all catalog plugins"+ )+ parser.add_argument(+ "--merge-catalog",+ action="store_true",+ help="Merge plugins_local.json into plugins.json and remove plugins_local.json"+ )args = parser.parse_args()@@ -11213,6 +11228,27 @@ def create_ui():return mainif __name__ == "__main__":+ if args.merge_catalog:+ manager = PluginManager()+ print(manager.merge_local_catalog())+ sys.exit(0)++ if args.refresh_catalog or args.refresh_full_catalog:+ manager = PluginManager()+ installed_only = not args.refresh_full_catalog+ result = manager.refresh_catalog(installed_only=installed_only, use_remote=False)+ checked = result.get("checked", 0)+ updates_available = result.get("updates_available", 0)+ scope = "installed plugins" if installed_only else "catalog plugins"+ if updates_available <= 0:+ message = "No Plugin Update is available"+ elif updates_available == 1:+ message = "One Plugin Update is available"+ else:+ message = f"{updates_available} Plugin Updates are available"+ print(f"[Plugins] Checked {checked} {scope}. {message}.")+ sys.exit(0)+app = WAN2GPApplication()# CLI Queue Processing Mode