Download viser_backend.py from SignerX/SignerX-inference-webui: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/datasets/SignerX/SignerX-inference-webui/resolve/main/viser_backend.py
- Command line
-
hf download hf://datasets/SignerX/SignerX-inference-webui/viser_backend.py
-
curl -L -o viser_backend.py https://huggingface.co/datasets/SignerX/SignerX-inference-webui/resolve/main/viser_backend.py
16.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| ControlWave Viser Backend - 最小化核心 | |
| 只提供Viser实例和插件加载功能 | |
| """ | |
| import time | |
| import importlib | |
| import importlib.util | |
| import sys | |
| from pathlib import Path | |
| from typing import Dict, Any, Optional | |
| import threading | |
| import viser | |
| class WaveVisualizationServer: | |
| """最小化的Viser服务器 - 只负责启动和插件管理""" | |
| def __init__(self, port: int = 8081): | |
| self.port = port | |
| self.server = None | |
| self.plugins = {} | |
| self.plugin_aliases = {} | |
| self.is_running = False | |
| self.plugin_dropdown = None # 插件选择下拉框 | |
| self.plugin_folders = {} # 存储每个插件的GUI文件夹 | |
| self.current_plugin = None # 当前活动的插件 | |
| self.plugin_names = {} # 存储插件ID到显示名称的映射 | |
| print(f"🔧 Viser 后端初始化 (端口: {port})") | |
| def start_server(self, background_mode=True): | |
| """启动Viser服务器""" | |
| if self.is_running: | |
| print("⚠️ Viser服务器已在运行") | |
| return self.server | |
| try: | |
| # 创建Viser服务器 | |
| self.server = viser.ViserServer(host="0.0.0.0", port=self.port) | |
| self.server.gui.configure_theme(titlebar_content=None, control_layout="collapsible") | |
| self.is_running = True | |
| # 设置基础场景 | |
| self.setup_basic_scene() | |
| # 创建GUI插件选择器 | |
| self._create_plugin_selector() | |
| # 加载所有插件后端 | |
| self._load_plugin_backends() | |
| print(f"✅ Viser服务器启动成功 (端口: {self.port})") | |
| print(f"📦 已加载 {len(self.plugins)} 个插件后端") | |
| if background_mode: | |
| # 后台模式 - 在新线程中运行 | |
| def server_loop(): | |
| try: | |
| while self.is_running: | |
| time.sleep(0.01) | |
| except Exception as e: | |
| print(f"❌ 服务器循环错误: {e}") | |
| thread = threading.Thread(target=server_loop, daemon=True) | |
| thread.start() | |
| return self.server | |
| else: | |
| # 前台模式 - 阻塞运行 | |
| try: | |
| while self.is_running: | |
| time.sleep(0.01) | |
| except KeyboardInterrupt: | |
| print("\n👋 关闭 Viser 后端...") | |
| except Exception as e: | |
| print(f"❌ 启动Viser服务器失败: {e}") | |
| self.is_running = False | |
| raise | |
| def setup_basic_scene(self): | |
| """设置基础场景 - 最小化,不添加额外元素""" | |
| # 设置默认的深蓝色背景 | |
| if self.server: | |
| # 创建深蓝色背景图像(Viser使用背景图像而不是背景颜色) | |
| import numpy as np | |
| bg_color = [13, 13, 38] # 深蓝黑色 | |
| width, height = 1920, 1080 | |
| solid_color_image = np.full((height, width, 3), bg_color, dtype=np.uint8) | |
| self.server.scene.set_background_image(solid_color_image, format="png") | |
| # 当客户端连接时也设置背景 | |
| def handle_client_connect(client): | |
| print("🔗 客户端已连接,设置背景") | |
| # 重新设置背景确保显示 | |
| solid_color_image = np.full((height, width, 3), bg_color, dtype=np.uint8) | |
| self.server.scene.set_background_image(solid_color_image, format="png") | |
| def _create_plugin_selector(self): | |
| """创建GUI插件选择器""" | |
| if self.server: | |
| # 创建下拉框,初始时至少有一个选项 | |
| self.plugin_dropdown = self.server.gui.add_dropdown( | |
| "当前插件", | |
| options=["无插件"], # 初始选项 | |
| initial_value="无插件" | |
| ) | |
| # 监听下拉框变化 | |
| def on_plugin_select(event): | |
| plugin_name = self.plugin_dropdown.value | |
| # 找到对应的插件ID | |
| plugin_id = None | |
| for pid, pname in self.plugin_names.items(): | |
| if pname == plugin_name: | |
| plugin_id = pid | |
| break | |
| if plugin_id: | |
| self._switch_plugin_gui(plugin_id) | |
| print("📁 已创建插件选择下拉框") | |
| def _load_plugin_backends(self): | |
| """自动加载所有插件后端""" | |
| plugins_dir = Path("plugins") | |
| if not plugins_dir.exists(): | |
| print("⚠️ 插件目录不存在") | |
| return | |
| # 添加plugins目录到Python路径 | |
| if str(plugins_dir.absolute()) not in sys.path: | |
| sys.path.insert(0, str(plugins_dir.absolute())) | |
| for plugin_dir in sorted(plugins_dir.iterdir()): | |
| if plugin_dir.is_dir() and not plugin_dir.name.startswith('.'): | |
| self._load_single_plugin(plugin_dir) | |
| def _load_single_plugin(self, plugin_dir: Path): | |
| """加载单个插件""" | |
| plugin_name = plugin_dir.name | |
| # 查找后端文件(按优先级) | |
| backend_files = ["viser_backend.py", "backend.py", "plugin_backend.py"] | |
| for backend_file in backend_files: | |
| backend_path = plugin_dir / backend_file | |
| if backend_path.exists(): | |
| try: | |
| # 动态导入模块 | |
| module_name = f"plugins.{plugin_name}.{backend_file[:-3]}" | |
| spec = importlib.util.spec_from_file_location(module_name, backend_path) | |
| if spec and spec.loader: | |
| module = importlib.util.module_from_spec(spec) | |
| sys.modules[module_name] = module | |
| spec.loader.exec_module(module) | |
| # 查找并初始化插件类 | |
| plugin_instance = None | |
| # 尝试不同的类名 | |
| class_names = ['PluginBackend', 'Backend', f'{plugin_name.title()}Backend'] | |
| for class_name in class_names: | |
| if hasattr(module, class_name): | |
| plugin_class = getattr(module, class_name) | |
| plugin_instance = plugin_class(self) | |
| break | |
| if plugin_instance: | |
| canonical_id = getattr(plugin_instance, 'name', None) or plugin_name | |
| canonical_id = canonical_id.strip() if isinstance(canonical_id, str) else plugin_name | |
| canonical_id = canonical_id or plugin_name | |
| if canonical_id in self.plugins and self.plugins[canonical_id] is not plugin_instance: | |
| print(f"⚠️ 插件标识 {canonical_id} 已存在,使用目录名 {plugin_name}") | |
| canonical_id = plugin_name | |
| self.plugins[canonical_id] = plugin_instance | |
| self._register_plugin_aliases(canonical_id, plugin_name) | |
| print(f"✅ 加载插件后端: {plugin_name}") | |
| # 为插件创建GUI文件夹 | |
| self._create_plugin_gui(plugin_name, plugin_instance, canonical_id) | |
| else: | |
| print(f"⚠️ 插件 {plugin_name} 没有找到后端类") | |
| except Exception as e: | |
| print(f"❌ 加载插件后端失败 {plugin_name}: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| break | |
| def _register_plugin_aliases(self, canonical_id: str, plugin_name: str): | |
| """记录插件可能的别名,兼容不同大小写或命名风格""" | |
| alias_candidates = set() | |
| for value in (canonical_id, plugin_name): | |
| if not value: | |
| continue | |
| alias_candidates.add(value) | |
| alias_candidates.add(value.lower()) | |
| alias_candidates.add(value.replace('_', '-')) | |
| alias_candidates.add(value.replace('-', '_')) | |
| for alias in alias_candidates: | |
| if alias: | |
| self.plugin_aliases[alias] = canonical_id | |
| def _normalize_plugin_id(self, plugin_id: Optional[str]) -> Optional[str]: | |
| """将不同写法的插件ID映射到标准ID""" | |
| if not plugin_id: | |
| return None | |
| if plugin_id in self.plugin_aliases: | |
| return self.plugin_aliases[plugin_id] | |
| lowered = plugin_id.lower() | |
| return self.plugin_aliases.get(lowered, plugin_id) | |
| def _create_plugin_gui(self, plugin_name: str, plugin_instance, canonical_id: str): | |
| """为插件创建GUI文件夹""" | |
| if not self.server: | |
| return | |
| # 获取插件显示名称 | |
| display_name = getattr(plugin_instance, 'display_name', None) | |
| if not display_name: | |
| # 尝试从插件目录的config.json读取 | |
| config_path = Path("plugins") / plugin_name / "config.json" | |
| if config_path.exists(): | |
| try: | |
| import json | |
| with open(config_path, 'r', encoding='utf-8') as f: | |
| config = json.load(f) | |
| display_name = config.get('name', plugin_name.replace('-', ' ').title()) | |
| except: | |
| display_name = plugin_name.replace('-', ' ').title() | |
| else: | |
| display_name = plugin_name.replace('-', ' ').title() | |
| # 保存映射 | |
| primary_id = canonical_id or plugin_name | |
| self.plugin_names[primary_id] = display_name | |
| # 创建GUI文件夹 | |
| folder = self.server.gui.add_folder(f"{display_name} Controls") | |
| self.plugin_folders[primary_id] = folder | |
| # 默认隐藏 | |
| folder.visible = False | |
| # 让插件在自己的文件夹中设置GUI | |
| if hasattr(plugin_instance, 'setup_gui'): | |
| with folder: | |
| plugin_instance.setup_gui() | |
| # 更新下拉框选项 | |
| if self.plugin_dropdown: | |
| options = list(self.plugin_names.values()) | |
| if options: # 确保有选项 | |
| self.plugin_dropdown.options = options | |
| # 如果是第一个插件,设为默认值 | |
| if len(options) == 1: | |
| self.plugin_dropdown.value = display_name | |
| folder.visible = True | |
| self.current_plugin = plugin_name | |
| # 如果之前是"无插件",自动切换到第一个插件 | |
| elif self.plugin_dropdown.value == "无插件" and options: | |
| self.plugin_dropdown.value = options[0] | |
| folder.visible = True | |
| self.current_plugin = plugin_name | |
| print(f"🏷️ 为插件 {plugin_name} 创建了GUI文件夹") | |
| def handle_message(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]: | |
| """路由消息到对应插件""" | |
| plugin_id = message.get('plugin') | |
| canonical_id = self._normalize_plugin_id(plugin_id) | |
| action = message.get('action') | |
| # 处理切换插件的特殊消息 | |
| if canonical_id == 'viser_backend' and action == 'switch_plugin': | |
| plugin_to_switch = message.get('data', {}).get('plugin_id') | |
| return self.switch_active_plugin(plugin_to_switch) | |
| if not canonical_id: | |
| return {"error": "No plugin specified"} | |
| if canonical_id in self.plugins: | |
| try: | |
| return self.plugins[canonical_id].handle_message(message) | |
| except Exception as e: | |
| print(f"❌ 插件 {canonical_id} 处理消息失败: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return {"error": str(e)} | |
| else: | |
| available_plugins = list(self.plugins.keys()) | |
| return { | |
| "error": f"Plugin not found: {plugin_id}", | |
| "available_plugins": available_plugins | |
| } | |
| def switch_active_plugin(self, plugin_id: str) -> Dict[str, Any]: | |
| """切换当前活动的插件""" | |
| canonical_id = self._normalize_plugin_id(plugin_id) | |
| print(f"🎯 切换到插件: {canonical_id}") | |
| if not canonical_id or canonical_id not in self.plugins: | |
| return {"error": f"Plugin not found: {plugin_id}"} | |
| # 切换GUI | |
| self._switch_plugin_gui(canonical_id) | |
| # 更新下拉框值 | |
| if self.plugin_dropdown and canonical_id in self.plugin_names: | |
| self.plugin_dropdown.value = self.plugin_names[canonical_id] | |
| return {"status": "success", "active_plugin": canonical_id} | |
| def _switch_plugin_gui(self, plugin_id: str): | |
| """内部方法:切换插件GUI""" | |
| canonical_id = self._normalize_plugin_id(plugin_id) | |
| if not canonical_id: | |
| return | |
| # 隐藏所有插件的GUI | |
| for pid, folder in self.plugin_folders.items(): | |
| folder.visible = False | |
| # 调用on_deactivate | |
| if pid == self.current_plugin and pid != canonical_id: | |
| plugin = self.plugins.get(pid) | |
| if plugin and hasattr(plugin, 'on_deactivate'): | |
| plugin.on_deactivate() | |
| # 显示新插件的GUI | |
| if canonical_id in self.plugin_folders: | |
| self.plugin_folders[canonical_id].visible = True | |
| # 记录当前插件 | |
| self.current_plugin = canonical_id | |
| # 调用on_activate | |
| plugin = self.plugins.get(canonical_id) | |
| if plugin and hasattr(plugin, 'on_activate'): | |
| plugin.on_activate() | |
| def get_plugin(self, plugin_name: str): | |
| """获取插件实例""" | |
| canonical_id = self._normalize_plugin_id(plugin_name) | |
| return self.plugins.get(canonical_id) | |
| def shutdown(self): | |
| """关闭服务器""" | |
| print("🔄 正在关闭Viser服务器...") | |
| self.is_running = False | |
| # 通知所有插件关闭 | |
| for plugin_name, plugin in self.plugins.items(): | |
| if hasattr(plugin, 'shutdown'): | |
| try: | |
| plugin.shutdown() | |
| except Exception as e: | |
| print(f"⚠️ 关闭插件 {plugin_name} 时出错: {e}") | |
| # 清理Viser资源 | |
| if self.server: | |
| try: | |
| self.server.scene.reset() | |
| except: | |
| pass | |
| self.server = None | |
| print("✅ Viser服务器已关闭") | |
| # 全局实例管理 | |
| _viser_instance = None | |
| _viser_lock = threading.Lock() | |
| def get_viser_server(port: int = 8081) -> WaveVisualizationServer: | |
| """获取或创建 Viser 服务器实例""" | |
| global _viser_instance | |
| with _viser_lock: | |
| if _viser_instance is None: | |
| _viser_instance = WaveVisualizationServer(port) | |
| _viser_instance.start_server(background_mode=True) | |
| return _viser_instance | |
| def shutdown_viser_server(): | |
| """关闭 Viser 服务器""" | |
| global _viser_instance | |
| with _viser_lock: | |
| if _viser_instance: | |
| _viser_instance.shutdown() | |
| _viser_instance = None | |
| # 简单的测试 | |
| if __name__ == "__main__": | |
| server = WaveVisualizationServer() | |
| server.start_server(background_mode=False) | |