Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
install and run comfyui from the stablegen panel
sakalond441e87b53e0d
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.mdindex 651fe46..56b958f 100644--- a/.github/ISSUE_TEMPLATE/bug_report.md+++ b/.github/ISSUE_TEMPLATE/bug_report.md@@ -44,8 +44,8 @@ PASTE COMFYUI SERVER LOGS HERE* **ComfyUI Installation:** [e.g., Standard local install]* **GPU:** [e.g., NVIDIA RTX 3080]-* **StableGen Installation Method:** [e.g., `installer.py` (Recommended), Manual] (See `README.md`)- * If `installer.py` was used, which package was selected? [e.g., Minimal, Essential, Recommended, Complete SDXL] (See `installer.py`)+* **ComfyUI setup:** [e.g., StableGen's own, My ComfyUI folder, Remote server, Manual] (See StableGen's add-on preferences)+ * Which models are installed? [e.g., SDXL, Qwen Image 2.1, TRELLIS.2] (Preferences > Models, or `installer.py --list` on a remote server)**StableGen Parameters (if relevant):**diff --git a/README.md b/README.mdindex 0b0f898..bdadbfd 100644--- a/README.md+++ b/README.md@@ -115,20 +115,26 @@ Texturing works by projection. Each camera gets a generated view that follows th## Requirements- Blender 4.2 to 4.5, or 5.1 and later. Blender 5.0 is not supported.-- A ComfyUI server, preferably with an NVIDIA GPU: about 8 GB of VRAM for SDXL, and 16 GB or more for Qwen Image.+- ComfyUI: StableGen can install its own, use one you have, or connect to one on another machine. An NVIDIA GPU is preferred: about 8 GB of VRAM for SDXL, and 16 GB or more for Qwen Image.- Windows, Linux, or macOS on Apple Silicon.-- 10 GB to over 50 GB of disk space for models, depending on what you install.+- 10 GB to over 50 GB of disk space for models, depending on what you install, plus about 5 GB for StableGen's own ComfyUI.## Installation-1. Install [ComfyUI](https://github.com/comfyanonymous/ComfyUI#installing) and check that it runs.-2. Install the custom nodes and models StableGen uses with the installer in this repository, then restart ComfyUI:- ```bash- python installer.py <path to ComfyUI>- ```- Package 3 sets up SDXL texturing, package 13 Qwen Image 2.1, package 8 mesh generation, package 14 auto-rigging, and packages 15 to 17 the experimental architectures.-3. Download the add-on ZIP for your system (Windows x64, Linux x64 or macOS on Apple Silicon) from [Releases](https://github.com/sakalond/stablegen/releases). In Blender, open **Edit > Preferences > Get Extensions**, choose **Install from Disk** in the top-right menu, and select the ZIP.-4. In the add-on preferences, set **Output Directory** and **Server Address** (`127.0.0.1:8188` by default). Under **System > Network**, enable **Allow Online Access**.+1. Download the add-on ZIP for your system (Windows x64, Linux x64 or macOS on Apple Silicon) from [Releases](https://github.com/sakalond/stablegen/releases). In Blender, open **Edit > Preferences > Get Extensions**, choose **Install from Disk** in the top-right menu, and select the ZIP.+2. Under **System > Network**, enable **Allow Online Access**.+3. In StableGen's add-on preferences, choose where **ComfyUI** comes from:+ - **StableGen's own**: pick an install folder and press **Install ComfyUI**. StableGen sets up ComfyUI with its own Python and torch for your GPU, then starts and stops it by itself. Windows and Linux.+ - **My ComfyUI folder**: a ComfyUI you already have (portable, git or Desktop install). StableGen installs models into it and starts it when needed.+ - **Remote server**: a ComfyUI on another machine, at its server address. Install the models there with the installer (below).+4. Under **Models**, install what you need: SDXL or Qwen Image 2.1 for texturing, TRELLIS.2 for meshes, auto-rigging, PBR maps and the experimental architectures. Each shows its download size, and an interrupted download resumes.+5. Set **Output Directory**.++On a remote ComfyUI, or without Blender, run the installer on that machine and restart ComfyUI:+```bash+python installer.py <path to ComfyUI> --packages 3,8+```+Package 3 sets up SDXL texturing, package 13 Qwen Image 2.1, package 8 mesh generation, package 14 auto-rigging, and packages 15 to 17 the experimental architectures. `python installer.py --create-comfyui <folder>` sets up StableGen's own ComfyUI there.[Installation](https://github.com/sakalond/StableGen/wiki/Installation) covers every installer package, unattended installs, a remote server and manual setup.diff --git a/installer.py b/installer.pyindex e42569b..f550273 100644--- a/installer.py+++ b/installer.py@@ -1,2557 +1,17 @@#!/usr/bin/env python3-"""StableGen dependency installer: custom nodes and models for a ComfyUI server.+"""The StableGen installer lives in stablegen/setup/installer.py, so the add-on ships it. This file runs it from a+repository checkout with the same arguments:- python installer.py <ComfyUI folder> menu- python installer.py <ComfyUI folder> --packages 3,8 --yes unattended- python installer.py --list what each package installs--Needs only Python 3.8+ and Git (for custom nodes). `tqdm`, when installed, draws progress bars.-"""-import os-import sys-import argparse-import fnmatch-import hashlib-import json-import socket-import subprocess-import tempfile-import time-import glob-import re-import shutil-import urllib.error-import urllib.parse-import urllib.request-from pathlib import Path-from typing import Dict, List, Set, Any, Optional, Tuple--try:- from tqdm.auto import tqdm- TQDM_AVAILABLE = True-except ImportError:- TQDM_AVAILABLE = False--# Captured subprocess output is read as UTF-8 and child Pythons are asked to write-# it: the console codepage (cp1251 on a Russian Windows) cannot decode what pip, git-# and a Python print for a non-ASCII path, and the reader thread's crash lost the-# output (#115).-UTF8_TEXT = dict(text=True, encoding="utf-8", errors="replace")-UTF8_ENV = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1")--# --- Compatibility Patches ----# Polyfill for Path.is_junction() which requires Python 3.12+.-# comfy_env uses it but many ComfyUI installs still run Python 3.10/3.11.-_PATCH_PY310_IS_JUNCTION = (- "# -- StableGen patch: Path.is_junction polyfill for Python < 3.12 --\n"- "import pathlib as _pathlib\n"- "if not hasattr(_pathlib.Path, 'is_junction'):\n"- " import os as _os, stat as _stat\n"- " def _is_junction(self):\n"- " try:\n"- " return bool(\n"- " _os.lstat(str(self)).st_file_attributes\n"- " & _stat.FILE_ATTRIBUTE_REPARSE_POINT\n"- " )\n"- " except (OSError, AttributeError):\n"- " return False\n"- " _pathlib.Path.is_junction = _is_junction\n"- "# -- End StableGen patch --\n\n"-)--_PATCH_TRELLIS_PRESTARTUP = (- "# -- StableGen patch: Path.is_junction polyfill for Python < 3.12 --\n"- "import pathlib as _pathlib\n"- "if not hasattr(_pathlib.Path, 'is_junction'):\n"- " import os as _os, stat as _stat\n"- " def _is_junction(self):\n"- " try:\n"- " return bool(\n"- " _os.lstat(str(self)).st_file_attributes\n"- " & _stat.FILE_ATTRIBUTE_REPARSE_POINT\n"- " )\n"- " except (OSError, AttributeError):\n"- " return False\n"- " _pathlib.Path.is_junction = _is_junction\n"- "# -- End StableGen patch --\n\n"- "# -- StableGen patch: Auto-heal comfy-env site-packages isolation at startup --\n"- "try:\n"- " import importlib.util as _u, os as _os, sys as _sys\n"- " _s = _u.find_spec('comfy_env')\n"- " if _s and _s.origin:\n"- " _wrap_py = _os.path.join(_os.path.dirname(_s.origin), 'isolation', 'wrap.py')\n"- " if _os.path.exists(_wrap_py):\n"- " with open(_wrap_py, 'r', encoding='utf-8') as _f:\n"- " _code = _f.read()\n"- " if 'PYTHONNOUSERSITE' not in _code:\n"- " _anchor = ' env[\"COMFYUI_ISOLATION_WORKER\"] = \"1\"'\n"- " if _anchor in _code:\n"- " _code = _code.replace(_anchor, _anchor + '\\n env[\"PYTHONNOUSERSITE\"] = \"1\"')\n"- " with open(_wrap_py, 'w', encoding='utf-8') as _f:\n"- " _f.write(_code)\n"- " print('[StableGen] Auto-applied comfy-env user site-packages isolation patch at boot', file=_sys.stderr)\n"- "except Exception:\n"- " pass\n"- "# -- End StableGen patch --\n\n"-)--# --- comfy-env core sync ----# comfy-env runs nodes like ComfyUI-TRELLIS2 in isolated pixi environments,-# but their workers still import ComfyUI's own `comfy` package. ComfyUI core-# pins some packages exactly (e.g. comfy-aimdo, comfy-kitchen), while the-# node's comfy-env.toml asks for "*" and pixi's lock keeps whatever was current-# at install time. After a ComfyUI update the worker then fails with errors-# like "No module named 'comfy_aimdo.storage'".-#-# This module brings those pins into every isolated env of a node. The-# installer writes it into the node folder, runs it with ComfyUI's Python, and-# hooks it into the node's prestartup script so it re-checks on every ComfyUI-# start (cheap: it only reads dist-info metadata unless something is out of date).-_COMFY_ENV_SYNC_FILENAME = "stablegen_env_sync.py"-_COMFY_ENV_SYNC_SOURCE = r'''"""Keep comfy-env isolated environments in step with ComfyUI core's pinned packages.--Written by StableGen's installer. Run as:- python stablegen_env_sync.py <ComfyUI dir> <custom node dir> [--check]-or import and call sync(comfyui_dir, node_dir). Safe to run repeatedly.+ python installer.py <ComfyUI folder> --packages 3,8 --yes"""-import os-import re-import subprocess+import runpyimport sys-import tempfilefrom pathlib import Path-TAG = "[StableGen env sync]"-SKIP_DIRS = {".git", ".pixi", "node_modules", "__pycache__"}-# Captured output is read as UTF-8 and the env Pythons are asked to write it: the-# console codepage (cp1251 on a Russian Windows) cannot decode what pip prints-# for a non-ASCII path, and the reader thread's crash lost the result (#115).-UTF8_ENV = dict(os.environ, PYTHONNOUSERSITE="1", PYTHONIOENCODING="utf-8", PYTHONUTF8="1")---def _norm(name):- return re.sub(r"[-_.]+", "-", name).lower()---def _log(msg):- print(f"{TAG} {msg}", file=sys.stderr, flush=True)---try:- from packaging.specifiers import SpecifierSet-except ImportError:- try:- from pip._vendor.packaging.specifiers import SpecifierSet- except ImportError:- SpecifierSet = None---def _satisfies(version, spec):- if SpecifierSet is None: # no packaging library: only exact pins can be compared- return not spec.startswith("==") or version == spec[2:]- try:- return SpecifierSet(spec).contains(version, prereleases=True)- except Exception:- return True---def _main_version(name):- """Version installed in the Python running this module (ComfyUI's own environment)."""- from importlib import metadata- try:- return metadata.version(name)- except metadata.PackageNotFoundError:- return None---def core_requirements(comfyui_dir):- """Versioned requirements from ComfyUI's requirements.txt, as {name: specifier}.-- Workers import ComfyUI's `comfy` and `comfy_api` packages, so whatever version- rules ComfyUI core sets must hold inside isolated envs too. Unversioned lines- are skipped, and front-end/template packages (comfyui-*) only matter to the- server, not to workers.- """- req = Path(comfyui_dir) / "requirements.txt"- reqs = {}- if not req.is_file():- return reqs- for line in req.read_text(encoding="utf-8", errors="ignore").splitlines():- line = line.split("#", 1)[0].split(";", 1)[0].strip()- m = re.fullmatch(r"([A-Za-z0-9_.\-]+)(?:\[[^\]]*\])?\s*((?:[<>=!~]=?|===)\s*[^\s,]+(?:\s*,\s*(?:[<>=!~]=?)\s*[^\s,]+)*)", line)- if m and not _norm(m.group(1)).startswith("comfyui-"):- reqs[_norm(m.group(1))] = re.sub(r"\s+", "", m.group(2))- return reqs---def _target(name, spec):- """What to install for a requirement: ComfyUI's own version when it satisfies the rule."""- main = _main_version(name)- return f"{name}=={main}" if main and _satisfies(main, spec) else f"{name}{spec}"---def _workspace_root():- override = os.environ.get("COMFY_ENV_ROOT")- if override:- return Path(override)- if sys.platform == "win32":- base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")- return base / "Programs" / "comfy-env"- return Path.home() / ".ce"---def _env_name(node_dir, config_path):- """comfy-env's naming rule; used only when comfy_env itself can't be imported."""- plugin = Path(node_dir).name- for prefix in ("ComfyUI-", "ComfyUI_", "comfyui-", "comfyui_"):- if plugin.startswith(prefix):- plugin = plugin[len(prefix):]- break- clean = lambda s: re.sub(r"-+", "-", re.sub(r"[^a-z0-9-]+", "-", s.lower())).strip("-")- name = clean(plugin)- parent = Path(config_path).parent.resolve()- if parent != Path(node_dir).resolve():- suffix = clean(parent.name)- if suffix:- name = f"{name}-{suffix}" if name else suffix- return name---def env_dirs(node_dir):- """(config file, materialized env dir) for each isolated env of a node."""- node_dir = Path(node_dir)- configs = []- for root, dirs, files in os.walk(node_dir):- dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith("_env_")]- if "comfy-env.toml" in files:- configs.append(Path(root) / "comfy-env.toml")- try:- from comfy_env.environment.cache import get_env_name, get_workspace_env_dir- resolve = lambda cfg: get_workspace_env_dir(None, get_env_name(node_dir, cfg))- except Exception:- resolve = lambda cfg: _workspace_root() / "envs" / _env_name(node_dir, cfg) / ".pixi" / "envs" / "default"- return [(cfg, Path(resolve(cfg))) for cfg in configs]---def _env_python(env_dir):- exe = env_dir / ("python.exe" if sys.platform == "win32" else "bin/python")- return exe if exe.is_file() else None---def _site_packages(env_dir):- return [p for p in [env_dir / "Lib" / "site-packages", *env_dir.glob("lib/python3*/site-packages")] if p.is_dir()]---def installed_versions(env_dir):- from importlib import metadata- versions = {}- for dist in metadata.distributions(path=[str(p) for p in _site_packages(env_dir)]):- name = dist.metadata.get("Name")- if name:- versions[_norm(name)] = dist.version- return versions---def declared_packages(config_path):- """Package names listed under any *pypi-dependencies* table of a comfy-env.toml."""- names, active = set(), False- for line in Path(config_path).read_text(encoding="utf-8", errors="ignore").splitlines():- line = line.strip()- header = re.fullmatch(r"\[([^\]]+)\]", line)- if header:- active = "pypi-dependencies" in header.group(1)- continue- m = re.match(r"([A-Za-z0-9_.\-]+)\s*=", line)- if active and m:- names.add(_norm(m.group(1)))- return names---def _pip_install(python, installed, wanted):- """pip install *wanted* ({name: requirement}) into an env with every other package held at its version."""- # Hold every other package at its current version so pip can't swap the- # env's CUDA torch build or anything else while resolving.- with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as fh:- fh.write("\n".join(f"{n}=={v}" for n, v in installed.items() if n not in wanted))- constraints = fh.name- try:- # Packages pixi took from conda (e.g. av) may have no build for this- # Python that satisfies ComfyUI; pip replaces them with the PyPI wheel.- return subprocess.run(- [str(python), "-m", "pip", "install", "--disable-pip-version-check", "--no-input",- "-c", constraints, *wanted.values()],- env=UTF8_ENV, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=900)- finally:- os.unlink(constraints)---def sync(comfyui_dir, node_dir, check_only=False):- """Make the node's envs satisfy ComfyUI core's requirements. Returns a list of problems left over.-- Only packages an env already has (or declares) are touched, and only when their- version breaks ComfyUI's rule; they get the version ComfyUI's own env runs.- """- reqs = core_requirements(comfyui_dir)- if not reqs:- _log(f"no versioned requirements found in {Path(comfyui_dir) / 'requirements.txt'}; nothing to sync")- return []- problems = []- for config, env_dir in env_dirs(node_dir):- python = _env_python(env_dir)- if not python:- continue # not materialized yet; comfy-env builds it on first use- installed = installed_versions(env_dir)- relevant = installed.keys() | declared_packages(config)- wanted = {n: _target(n, s) for n, s in reqs.items()- if n in relevant and not (n in installed and _satisfies(installed[n], s))}- if not wanted:- continue- summary = ", ".join(f"{n} {installed.get(n, 'missing')} -> {t[len(n):]}" for n, t in wanted.items())- if check_only:- problems.append(f"{env_dir.parent.parent.parent.name}: {summary}")- continue- _log(f"{env_dir.parent.parent.parent.name}: {summary}")- result = _pip_install(python, installed, wanted)- after = installed_versions(env_dir)- left = [t for n, t in wanted.items() if not (n in after and _satisfies(after[n], reqs[n]))]- if result.returncode != 0 or left:- tail = (result.stderr or result.stdout).strip().splitlines()[-3:]- problems.append(f"{env_dir}: could not install {', '.join(left) or 'all packages'}: "- + " | ".join(tail))- else:- _log(f"{env_dir.parent.parent.parent.name}: up to date")- for p in problems:- _log(("OUT OF DATE " if check_only else "FAILED ") + p)- return problems---# comfy.model_base pulls in the model code (comfy.ldm, its attention module) that workers import too:-# TRELLIS.2's node scan imports comfy.lora, which imports it.-_VERIFY = (- "import sys; sys.argv = ['main.py']; sys.path[:0] = [{comfy!r}]\n"- "import comfy.model_management, comfy.utils, comfy.model_base, comfy_api.latest\n"- "print('ok')\n"-)---def _missing_requirement(output, reqs):- """The ComfyUI core requirement an import error names ("No module named 'comfy_kitchen'"), if any."""- m = re.search(r"No module named '([A-Za-z0-9_]+)", output)- name = _norm(m.group(1)) if m else None- return name if name in reqs else None---def verify(comfyui_dir, node_dir, repair=True):- """Import ComfyUI core with each env's own Python, the way the node's worker does.-- sync() only updates packages an env has or declares, so a requirement ComfyUI- core newly imports (ComfyUI 0.42 imports comfy-kitchen in its attention module)- is missing from an env built before it, and the worker then registers no nodes.- With *repair*, such a requirement is installed at core's version and the import- retried.- """- reqs = core_requirements(comfyui_dir) if repair else {}- problems = []- for _, env_dir in env_dirs(node_dir):- python = _env_python(env_dir)- if not python:- continue- added = set()- while True:- result = subprocess.run([str(python), "-c", _VERIFY.format(comfy=str(Path(comfyui_dir).resolve()))],- env=UTF8_ENV, capture_output=True, text=True, encoding="utf-8",- errors="replace", timeout=600, cwd=str(comfyui_dir))- name = (_missing_requirement((result.stderr or result.stdout), reqs)- if result.returncode != 0 else None)- if name is None or name in added:- break- added.add(name)- target = _target(name, reqs[name])- _log(f"{env_dir.parent.parent.parent.name}: ComfyUI core imports {name}, missing here -> {target}")- _pip_install(python, installed_versions(env_dir), {name: target})- if result.returncode != 0:- output = (result.stderr or result.stdout).strip()- last = output.splitlines()[-1:] or ["unknown error"]- if "WinError 1455" in output or "MemoryError" in output:- # Not an env problem: the machine is out of memory (e.g. a generation is running).- _log(f"{env_dir.parent.parent.parent.name}: could not verify, system is low on memory; "- "close other GPU/RAM-heavy programs and re-run --check")- continue- problems.append(f"{env_dir.parent.parent.parent.name}: ComfyUI core does not import: {last[0]}")- else:- _log(f"{env_dir.parent.parent.parent.name}: ComfyUI core imports cleanly")- for p in problems:- _log("FAILED " + p)- return problems---if __name__ == "__main__":- args = [a for a in sys.argv[1:] if not a.startswith("--")]- if len(args) != 2:- sys.exit(__doc__)- left = sync(args[0], args[1], check_only="--check" in sys.argv)- if not left:- left = verify(args[0], args[1], repair="--check" not in sys.argv)- sys.exit(1 if left else 0)-'''--_PATCH_COMFY_ENV_SYNC_PRESTARTUP = (- "# -- StableGen patch: keep comfy-env envs in step with ComfyUI core --\n"- "try:\n"- " import os as _os, sys as _sys\n"- " _here = _os.path.dirname(_os.path.abspath(__file__))\n"- " _sys.path.insert(0, _here)\n"- " try:\n"- " import stablegen_env_sync as _sg_env_sync\n"- " _sg_env_sync.sync(_os.path.dirname(_os.path.dirname(_here)), _here)\n"- " finally:\n"- " _sys.path.remove(_here)\n"- "except Exception as _e:\n"- " print(f'[StableGen env sync] skipped: {_e}', file=_sys.stderr)\n"- "# -- End StableGen patch --\n\n"-)--# Older StableGen releases also patched nodes/trellis_utils/ and nodes/trellis2/pipelines/ (VRAM-leak and-# temp-file fixes). Upstream replaced that code with ComfyUI's native model loading in February 2026, so those-# patches no longer have anything to apply to and were removed when the node was pinned below.--# comfy-env runs TRELLIS.2 in its isolated environment. The patches below and the pinned TRELLIS.2 commit were-# verified with this version; newer releases change the code the patches anchor on.-COMFY_ENV = "comfy-env==0.4.1"--# --- Configuration: Dependencies Data ----# Sizes are in MB. Every custom node is pinned to a commit StableGen was tested with ("commit"). A fresh clone-# checks out that commit. An existing clone at another commit is left alone with a note, unless the node sets-# "enforce_pin" (StableGen's patches depend on that exact code) or the installer runs with --update-nodes.-DEPENDENCIES: Dict[str, Dict[str, Any]] = {- # --- Custom Nodes ---- "cn_ipadapter_plus": {- "id": "cn_ipadapter_plus", "type": "node", "name": "ComfyUI IPAdapter Plus",- "git_url": "https://github.com/cubiq/ComfyUI_IPAdapter_plus.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI_IPAdapter_plus",- "commit": "a0f451a5113cf9becb0847b92884cb10cbdec0ef",- "license": "GPL-3.0", "packages": ["core"]- },- # --- Models ---- # Core Models- "model_ipadapter_plus_sdxl_vit_h": {- "id": "model_ipadapter_plus_sdxl_vit_h", "type": "model", "name": "IPAdapter Plus SDXL ViT-H",- "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors?download=true",- "target_path_relative": "models/ipadapter", "filename": "ip-adapter-plus_sdxl_vit-h.safetensors",- "license": "Apache 2.0", "size_mb": 850, "packages": ["core"]- },- "model_clip_vision_h": {- "id": "model_clip_vision_h", "type": "model", "name": "IPAdapter CLIP Vision ViT-H",- "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors",- "target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors",- "rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["core"]- },- "model_clip_vision_g": {- "id": "model_clip_vision_g", "type": "model", "name": "IPAdapter CLIP Vision ViT-G",- "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors",- "target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors",- "rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 3500, "packages": ["core"]- },- "lora_sdxl_lightning_8step": {- "id": "lora_sdxl_lightning_8step", "type": "model", "name": "SDXL Lightning 8-Step LoRA",- "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_8step_lora.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "sdxl_lightning_8step_lora.safetensors",- "license": "OpenRAIL++", "size_mb": 400, "packages": ["core"]- },- # Preset Essentials- "controlnet_depth_sdxl_preset": {- "id": "controlnet_depth_sdxl_preset", "type": "model", "name": "ControlNet Depth SDXL (for presets)",- "url": "https://huggingface.co/xinsir/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.safetensors?download=true",- "target_path_relative": "models/controlnet", "filename": "controlnet_depth_sdxl.safetensors",- "rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["preset_essentials"]- },- # Extended SDXL Optional Models- "lora_sdxl_lightning_4step": {- "id": "lora_sdxl_lightning_4step", "type": "model", "name": "SDXL Lightning 4-Step LoRA",- "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_4step_lora.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "sdxl_lightning_4step_lora.safetensors",- "license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]- },- "lora_sdxl_lightning_2step": {- "id": "lora_sdxl_lightning_2step", "type": "model", "name": "SDXL Lightning 2-Step LoRA",- "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_2step_lora.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "sdxl_lightning_2step_lora.safetensors",- "license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]- },- "lora_hyper_sdxl_8step": {- "id": "lora_hyper_sdxl_8step", "type": "model", "name": "Hyper-SDXL 8-Steps LoRA",- "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-8steps-lora.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "Hyper-SDXL-8steps-lora.safetensors",- "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]- },- "lora_hyper_sdxl_4step": {- "id": "lora_hyper_sdxl_4step", "type": "model", "name": "Hyper-SDXL 4-Steps LoRA",- "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-4steps-lora.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "Hyper-SDXL-4steps-lora.safetensors",- "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]- },- "lora_hyper_sdxl_1step": {- "id": "lora_hyper_sdxl_1step", "type": "model", "name": "Hyper-SDXL 1-Step LoRA",- "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-1step-lora.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "Hyper-SDXL-1step-lora.safetensors",- "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]- },- "controlnet_depth_sdxl_fp16_alt": {- "id": "controlnet_depth_sdxl_fp16_alt", "type": "model", "name": "ControlNet Depth SDXL fp16 (alternative)",- "url": "https://huggingface.co/diffusers/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.fp16.safetensors?download=true",- "target_path_relative": "models/controlnet", "filename": "diffusion_pytorch_model.fp16.safetensors",- "license": "OpenRAIL++", "size_mb": 2500, "packages": ["extended_optional"]- },- "controlnet_union_promax": {- "id": "controlnet_union_promax", "type": "model", "name": "ControlNet Union SDXL ProMax",- "url": "https://huggingface.co/brad-twinkl/controlnet-union-sdxl-1.0-promax/resolve/main/diffusion_pytorch_model.safetensors?download=true",- "target_path_relative": "models/controlnet", "filename": "sdxl_promax.safetensors",- "rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["extended_optional"]- },- # Checkpoints- "checkpoint_realvis_v5": {- "id": "checkpoint_realvis_v5", "type": "model", "name": "RealVisXL V5.0 fp16 Checkpoint",- "url": "https://huggingface.co/SG161222/RealVisXL_V5.0/resolve/main/RealVisXL_V5.0_fp16.safetensors?download=true",- "target_path_relative": "models/checkpoints", "filename": "RealVisXL_V5.0_fp16.safetensors",- "license": "OpenRAIL++", "size_mb": 6500, "packages": ["checkpoint_realvis"]- },- # Qwen Core- "cn_comfyui_gguf": {- "id": "cn_comfyui_gguf", "type": "node", "name": "ComfyUI GGUF Loader",- "git_url": "https://github.com/city96/ComfyUI-GGUF.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI-GGUF",- "commit": "6ea2651e7df66d7585f6ffee804b20e92fb38b8a",- "license": "Apache 2.0", "packages": ["qwen_core"],- "pip_packages": ["gguf"]- },- "model_qwen_unet_q3_k_m": {- "id": "model_qwen_unet_q3_k_m", "type": "model", "name": "Qwen Image Edit 2509 UNet (Q3_K_M)",- "url": "https://huggingface.co/QuantStack/Qwen-Image-Edit-2509-GGUF/resolve/main/Qwen-Image-Edit-2509-Q3_K_M.gguf?download=true",- "target_path_relative": "models/unet", "filename": "Qwen-Image-Edit-2509-Q3_K_M.gguf",- "license": "Apache 2.0", "size_mb": 9760, "packages": ["qwen_core"]- },- "model_qwen_vae": {- "id": "model_qwen_vae", "type": "model", "name": "Qwen Image VAE",- "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/vae/qwen_image_vae.safetensors?download=true",- "target_path_relative": "models/vae", "filename": "qwen_image_vae.safetensors",- "license": "Apache 2.0", "size_mb": 254, "packages": ["qwen_core"]- },- "model_qwen_text_encoder_fp8": {- "id": "model_qwen_text_encoder_fp8", "type": "model", "name": "Qwen 2.5 VL 7B Text Encoder (FP8)",- "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors?download=true",- "target_path_relative": "models/clip", "filename": "qwen_2.5_vl_7b_fp8_scaled.safetensors",- "license": "Apache 2.0", "size_mb": 9380, "packages": ["qwen_core"]- },- "lora_qwen_lightning_4step_edit": {- "id": "lora_qwen_lightning_4step_edit", "type": "model", "name": "Qwen Image Edit Lightning 4-Step LoRA (bf16)",- "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors",- "license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_core"]- },- # Qwen Extras- "lora_qwen_lightning_8step": {- "id": "lora_qwen_lightning_8step", "type": "model", "name": "Qwen Image Edit Lightning 8-Step LoRA (bf16)",- "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors",- "license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_extras"]- },- "lora_qwen_lightning_4step": {- "id": "lora_qwen_lightning_4step", "type": "model", "name": "Qwen Image Lightning 4-Step LoRA (bf16)",- "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Lightning-4steps-V1.0-bf16.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "Qwen-Image-Lightning-4steps-V1.0-bf16.safetensors",- "license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_extras"]- },- # Nunchaku Qwen- "cn_nunchaku": {- "id": "cn_nunchaku", "type": "node", "name": "ComfyUI Nunchaku",- "git_url": "https://github.com/nunchaku-tech/ComfyUI-nunchaku.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI-nunchaku",- "commit": "b600f879a777fdef1466c362e850f7e8c31bf89a",- "license": "Apache 2.0", "packages": ["qwen_nunchaku"],- # The engine is not the PyPI package called "nunchaku" (an unrelated project): it ships as wheels built- # per Python, torch and platform, picked with the node's own version list.- "post_install": "nunchaku_wheel",- },- "cn_qwen_lora_loader": {- "id": "cn_qwen_lora_loader", "type": "node", "name": "ComfyUI Qwen Image LoRA Loader",- "git_url": "https://github.com/ussoewwin/ComfyUI-QwenImageLoraLoader.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI-QwenImageLoraLoader",- "commit": "ccb55860b80d41835110609748000f4c64932635", # v2.6.7- "license": "Apache 2.0", "packages": ["qwen_nunchaku"]- },- "model_nunchaku_qwen": {- "id": "model_nunchaku_qwen", "type": "model", "name": "Nunchaku Qwen Image Edit 2509 (Int4)",- "url": "https://huggingface.co/nunchaku-tech/nunchaku-qwen-image-edit-2509/resolve/main/lightning-251115/svdq-int4_r128-qwen-image-edit-2509-lightning-4steps-251115.safetensors?download=true",- "target_path_relative": "models/diffusion_models", "filename": "svdq-int4_r128-qwen-image-edit-2509-lightning-4steps-251115.safetensors",- "license": "Apache 2.0", "size_mb": 12700, "packages": ["qwen_nunchaku"]- },- # --- PBR Decomposition (Marigold IID) ---- "cn_comfyui_marigold": {- "id": "cn_comfyui_marigold", "type": "node", "name": "ComfyUI-Marigold (IID/Depth/Normal)",- "git_url": "https://github.com/kijai/ComfyUI-Marigold.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI-Marigold",- "commit": "2adfec75c430b0751a98a82453dc2dd8077bca85",- "license": "GPL-3.0", "packages": ["pbr_marigold"],- "pip_packages": ["diffusers>=0.28", "accelerate", "matplotlib"] + (["triton-windows"] if sys.platform == "win32" else []),- "run_install_script": True,- },- # --- StableDelight (specular-free albedo) ---- "cn_comfyui_stabledelight": {- "id": "cn_comfyui_stabledelight", "type": "node", "name": "ComfyUI StableDelight (Delighting)",- "git_url": "https://github.com/lldacing/ComfyUI_StableDelight_ll.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI_StableDelight_ll",- "commit": "42c0463cc65554509804cbf577a1675c61499ec4",- "license": "Apache-2.0", "packages": ["pbr_stabledelight"],- "pip_packages": ["diffusers>=0.28", "accelerate", "matplotlib"] + (["triton-windows"] if sys.platform == "win32" else []),- "post_clone_patches": [- {- "file": "nodes/BaseNode.py",- "marker": "local_files_only=False",- "anchor": "local_files_only=True",- "patch": "local_files_only=False",- "mode": "replace",- },- ],- },- "model_stabledelight": {- "id": "model_stabledelight", "type": "hf_model",- "name": "StableDelight Model (yoso-delight-v0-4-base)",- "hf_repo": "Stable-X/yoso-delight-v0-4-base",- "local_dir": "Stable-X--yoso-delight-v0-4-base",- "license": "Apache-2.0", "size_mb": 3300,- "packages": ["pbr_stabledelight"],- },- # --- Marigold V2 (albedo + normals; ComfyUI core nodes, LoRAs on Qwen-Image-Edit-2509) ---- "model_marigold_v2_base": {- "id": "model_marigold_v2_base", "type": "model",- "name": "Marigold V2 base: Qwen Image Edit 2509 (int8)",- "url": "https://huggingface.co/Comfy-Org/marigold-v2-0/resolve/main/diffusion_models/qwen_image_edit_2509_int8_convrot.safetensors?download=true",- "target_path_relative": "models/diffusion_models", "filename": "qwen_image_edit_2509_int8_convrot.safetensors",- "license": "Apache 2.0", "size_mb": 19550, "packages": ["pbr_marigold_v2"],- },- **{- f"model_marigold_v2_{task}_{kind}": {- "id": f"model_marigold_v2_{task}_{kind}", "type": "model",- "name": f"Marigold V2 {task.capitalize()} {label}",- "url": f"https://huggingface.co/Comfy-Org/marigold-v2-0/resolve/main/{folder}/{filename}?download=true",- "target_path_relative": f"models/{folder}", "filename": filename,- "license": "Apache 2.0", "size_mb": size_mb, "packages": ["pbr_marigold_v2"],- }- for task in ("albedo", "normals")- for kind, label, folder, filename, size_mb in (- ("lora", "LoRA", "loras", f"marigold_v2_{task}.safetensors", 1625),- ("vae", "VAE", "vae", f"marigold_v2_{task}_vae.safetensors", 242),- ("cond", "Conditioning", "embeddings", f"marigold_v2_{task}_conditioning.safetensors", 3),- )- },- # --- TRELLIS.2 ---- "cn_trellis2": {- "id": "cn_trellis2", "type": "node", "name": "ComfyUI TRELLIS.2",- "git_url": "https://github.com/PozzettiAndrea/ComfyUI-TRELLIS2.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI-TRELLIS2",- # Verified with ComfyUI 0.37 and comfy-env 0.4.1 (October 2026). Upstream refactors- # regularly break the patches below, so move this pin only after re-testing.- "commit": "9b878516f2dc2fd873f4f6cceadba403dd12d83e",- "enforce_pin": True,- "license": "MIT (Note: textured pipeline uses NVIDIA non-commercial libs)", "packages": ["trellis2"],- # The rest of the node's requirements.txt (ComfyUI-Manager would install it). The main process- # receives the worker's meshes as trimesh objects: without it every TRELLIS.2 run fails with- # "No module named 'trimesh'" on a ComfyUI that nothing else gave trimesh.- "pip_packages": [COMFY_ENV, "comfy-sparse-attn", "comfy-3d-viewers", "trimesh[easy]"],- "clean_envs": True,- "run_install_script": True,- "post_clone_patches": [- {- "file": "__init__.py",- "marker": "StableGen patch: Path.is_junction",- "anchor": "from comfy_env import",- "patch": _PATCH_PY310_IS_JUNCTION,- },- {- "file": "prestartup_script.py",- "marker": "StableGen patch: Auto-heal comfy-env",- "anchor": "from comfy_env import",- "patch": _PATCH_TRELLIS_PRESTARTUP,- },- {- "file": "prestartup_script.py",- "marker": "StableGen patch: keep comfy-env envs in step",- "anchor": "from comfy_env import",- "patch": _PATCH_COMFY_ENV_SYNC_PRESTARTUP,- },- {- "file": "nodes/rembg/BiRefNet.py",- "marker": "StableGen patch: BiRefNet fp32",- "anchor": "self.model.eval()",- "patch": "self.model.eval()\n self.model.float() # StableGen patch: BiRefNet fp32 — avoid fp16/fp32 dtype mismatch",- "mode": "replace",- },- ]- },- # --- FLUX.2 Klein 4B ---- "model_flux2_klein_4b": {- "id": "model_flux2_klein_4b", "type": "model",- "name": "FLUX.2 Klein 4B Diffusion Model (FP8)",- "url": "https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4b-fp8/resolve/main/flux-2-klein-base-4b-fp8.safetensors?download=true",- "target_path_relative": "models/diffusion_models",- "filename": "flux-2-klein-base-4b-fp8.safetensors",- "license": "Apache 2.0", "size_mb": 4070, "packages": ["flux2_klein"],- },- "model_flux2_text_encoder": {- "id": "model_flux2_text_encoder", "type": "model",- "name": "FLUX.2 Klein Qwen 3 4B Text Encoder (bf16)",- "url": "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors?download=true",- "target_path_relative": "models/text_encoders",- "filename": "qwen_3_4b.safetensors",- "license": "Apache 2.0", "size_mb": 8050, "packages": ["flux2_klein"],- },- "model_flux2_vae": {- "id": "model_flux2_vae", "type": "model",- "name": "FLUX.2 VAE",- "url": "https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors?download=true",- "target_path_relative": "models/vae",- "filename": "flux2-vae.safetensors",- "license": "Apache 2.0", "size_mb": 321, "packages": ["flux2_klein", "fibo_edit"],- },- # --- Qwen Image 2.1 (ComfyUI core nodes; StableGen expects these text encoder and VAE file names) ---- "model_qwen21_diffusion": {- "id": "model_qwen21_diffusion", "type": "model", "name": "Qwen Image 2.1 Diffusion Model (int8)",- "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors?download=true",- "target_path_relative": "models/diffusion_models", "filename": "qwen_image_2.1_int8_convrot.safetensors",- "license": "Qwen Research License (non-commercial)", "size_mb": 7260, "packages": ["qwen_image_21"],- },- "model_qwen21_text_encoder": {- "id": "model_qwen21_text_encoder", "type": "model", "name": "Qwen Image 2.1 Text Encoder (Qwen3-VL 8B, w4a8)",- "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_w4a8.safetensors?download=true",- "target_path_relative": "models/text_encoders", "filename": "qwen3vl_8b_w4a8.safetensors",- "license": "Qwen Research License (non-commercial)", "size_mb": 6310,- "packages": ["qwen_image_21", "qwen_image_21_turbo"],- },- "model_qwen21_vae": {- "id": "model_qwen21_vae", "type": "model", "name": "Qwen Image 2.1 VAE",- "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors?download=true",- "target_path_relative": "models/vae", "filename": "qwen_image_2.1_vae_bf16.safetensors",- "license": "Qwen Research License (non-commercial)", "size_mb": 680,- "packages": ["qwen_image_21", "qwen_image_21_turbo"],- },- # --- Experimental architectures (ComfyUI core nodes, Comfy-Org repacks; file names as StableGen loads them) ---- "model_qwen21_turbo_diffusion": {- "id": "model_qwen21_turbo_diffusion", "type": "model", "name": "Qwen Image 2.1 Turbo Diffusion Model (int8)",- "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_turbo_int8_convrot.safetensors?download=true",- "target_path_relative": "models/diffusion_models", "filename": "qwen_image_2.1_turbo_int8_convrot.safetensors",- "license": "Qwen Research License (non-commercial)", "size_mb": 6920, "packages": ["qwen_image_21_turbo"],- },- "model_moss_diffusion": {- "id": "model_moss_diffusion", "type": "model", "name": "MOSS-Image Diffusion Model (int8)",- "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/diffusion_models/moss_image_sft_int8_convrot.safetensors?download=true",- "target_path_relative": "models/diffusion_models", "filename": "moss_image_sft_int8_convrot.safetensors",- "license": "Apache 2.0", "size_mb": 5162, "packages": ["moss_image"],- },- "model_moss_text_encoder": {- "id": "model_moss_text_encoder", "type": "model", "name": "MOSS-Image Text Encoder (Qwen3.5 9B, int8)",- "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/text_encoders/qwen3.5_9b_int8_convrot.safetensors?download=true",- "target_path_relative": "models/text_encoders", "filename": "qwen3.5_9b_int8_convrot.safetensors",- "license": "Apache 2.0", "size_mb": 9296, "packages": ["moss_image"],- },- "model_moss_vae": {- "id": "model_moss_vae", "type": "model", "name": "MOSS-Image VAE (FLUX.2 small)",- "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/vae/flux2-vae_small.safetensors?download=true",- "target_path_relative": "models/vae", "filename": "flux2-vae_small.safetensors",- "license": "Apache 2.0", "size_mb": 237, "packages": ["moss_image"],- },- "model_moss_depth_control": {- "id": "model_moss_depth_control", "type": "model", "name": "MOSS-Image Color/Depth Control Adapter",- "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/loras/moss_image_color_depth_control.safetensors?download=true",- "target_path_relative": "models/loras", "filename": "moss_image_color_depth_control.safetensors",- "license": "Apache 2.0", "size_mb": 298, "packages": ["moss_image"],- },- "model_fibo_diffusion": {- "id": "model_fibo_diffusion", "type": "model", "name": "FIBO 2.0 Edit Turbo Diffusion Model (int8)",- "url": "https://huggingface.co/Comfy-Org/Fibo-2.0/resolve/main/diffusion_models/fibo2_edit_turbo_int8_convrot.safetensors?download=true",- "target_path_relative": "models/diffusion_models", "filename": "fibo2_edit_turbo_int8_convrot.safetensors",- "license": "CC BY-NC 4.0 (non-commercial)", "size_mb": 8019, "packages": ["fibo_edit"],- },- "model_fibo_text_encoder": {- "id": "model_fibo_text_encoder", "type": "model", "name": "FIBO 2.0 Text Encoder (Qwen3-VL 4B, int8)",- "url": "https://huggingface.co/Comfy-Org/Fibo-2.0/resolve/main/text_encoders/qwen3vl_4b_int8_convrot.safetensors?download=true",- "target_path_relative": "models/text_encoders", "filename": "qwen3vl_4b_int8_convrot.safetensors",- "license": "CC BY-NC 4.0 (non-commercial)", "size_mb": 4633, "packages": ["fibo_edit"],- },- # --- SkinTokens auto-rigging ---- "cn_skintokens": {- "id": "cn_skintokens", "type": "node", "name": "ComfyUI StableGen SkinTokens",- "git_url": "https://github.com/sakalond/ComfyUI-StableGen-SkinTokens.git",- "target_dir_relative": "custom_nodes",- "repo_name": "ComfyUI-StableGen-SkinTokens",- "commit": "dd0a272686b77226e6702281b6fd7eb24231abe6",- "license": "GPL-3.0 (SkinTokens code and weights: MIT)", "packages": ["skintokens"],- # The node's own setup builds SkinTokens in a separate environment (vendor/skintokens_env) with its own- # PyTorch and downloads the checkpoints, so ComfyUI's Python is left untouched.- "post_install": "skintokens_runtime",- },-}--# ComfyUI node types each package provides or needs (checked by --verify against /object_info), and the ComfyUI-# core nodes a package needs, which only exist in recent ComfyUI versions (checked before installing).-PACKAGE_NODES: Dict[str, List[str]] = {- "core": ["IPAdapterUnifiedLoader", "IPAdapter"],- "qwen_core": ["UnetLoaderGGUF", "TextEncodeQwenImageEditPlus"],- "qwen_nunchaku": ["NunchakuQwenImageDiTLoader", "NunchakuQwenImageLoraLoader"],- "pbr_marigold": ["MarigoldModelLoader", "MarigoldDepthEstimation_v2"],- "pbr_stabledelight": ["LoadStableDelightModel", "ApplyStableDelight"],- "pbr_marigold_v2": ["MarigoldV2PostProcess", "ConditioningLoader"],- "trellis2": ["LoadTrellis2Models", "Trellis2ImageToShape", "Trellis2GetConditioning", "Trellis2RemoveBackground",- "Trellis2ExportTrimesh", "Trellis2Simplify", "Trellis2ShapeToTexturedMesh", "Trellis2RasterizePBR",- "Trellis2ProcessMesh"],- "flux2_klein": ["Flux2Scheduler", "EmptyFlux2LatentImage"],- "qwen_image_21": ["TextEncodeQwenImage21", "QwenImage21Cache"],- "skintokens": ["StableGenSkinTokensAutoRig"],- "qwen_image_21_turbo": ["TextEncodeQwenImage21", "QwenImage21Cache"],- "moss_image": ["MOSSImageControl", "EmptyFlux2LatentImage"],- "fibo_edit": ["TextEncodeFibo2"],-}-CORE_NODES: Dict[str, List[str]] = {- "qwen_core": ["TextEncodeQwenImageEditPlus"],- "pbr_marigold_v2": ["MarigoldV2PostProcess", "ConditioningLoader"],- "flux2_klein": ["Flux2Scheduler", "EmptyFlux2LatentImage"],- "qwen_image_21": ["TextEncodeQwenImage21", "QwenImage21Cache"],- "qwen_image_21_turbo": ["TextEncodeQwenImage21", "QwenImage21Cache"],- "moss_image": ["MOSSImageControl", "EmptyFlux2LatentImage"], # ComfyUI 0.42.3 or newer- "fibo_edit": ["TextEncodeFibo2"], # ComfyUI master from 2026-10-21-}--# Define what items each menu option entails by listing package tags-# The script will collect all unique items based on the selected package tags.-MENU_PACKAGES: Dict[str, Dict[str, Any]] = {- '1': {"name": "[MINIMAL CORE] Basic Requirements",- "tags": ["core"],- "size_gb": 7.3,- "description_suffix": "*You will still need to manually download your own SDXL checkpoint(s) and all ControlNet models for full functionality and preset usage.*"},- '2': {"name": "[ESSENTIAL] Core + Preset Essentials",- "tags": ["core", "preset_essentials"],- "size_gb": 9.8,- "description_suffix": "*All models for preset functionality. You will still need to manually download your own SDXL checkpoint(s).*"},- '3': {"name": "[RECOMMENDED] Full SDXL Setup (No Checkpoints)",- "tags": ["core", "preset_essentials", "extended_optional", "pbr_marigold", "pbr_stabledelight"],- "size_gb": 19.3,- "description_suffix": "*Downloads optional ControlNet and LoRA models + PBR decomposition nodes. You will still need to manually download your own SDXL checkpoint(s).*"},- '4': {"name": "[COMPLETE SDXL] Full SDXL Setup + RealVisXL V5.0 Checkpoint",- "tags": ["core", "preset_essentials", "extended_optional", "pbr_marigold", "pbr_stabledelight", "checkpoint_realvis"],- "size_gb": 26.3,- "description_suffix": ""},- '5': {"name": "[QWEN CORE] Models + GGUF Node",- "tags": ["qwen_core"],- "size_gb": 20.3,- "description_suffix": "*Installs Qwen Image Edit UNet, VAE, text encoder, core LoRA, and GGUF ComfyUI node.*"},- '6': {"name": "[QWEN EXTRAS] Core + Lightning LoRAs",- "tags": ["qwen_core", "qwen_extras"],- "size_gb": 22.6,- "description_suffix": "*Adds additional Qwen Lightning LoRAs on top of the Qwen core install.*"},- '7': {"name": "[QWEN NUNCHAKU] Nunchaku Nodes + Model",- "tags": ["qwen_core", "qwen_nunchaku"],- "size_gb": 33.0,- "description_suffix": "*Installs Qwen Core components plus Nunchaku nodes and the Int4 quantized model (12.7GB).*"},- '8': {"name": "[TRELLIS.2] Image-to-3D Node",- "tags": ["trellis2"],- "size_gb": 20.4,- "notice": "trellis2",- "description_suffix": "*Installs ComfyUI-TRELLIS2 custom node + isolated Python environment (~5 GB).*\n"- " *TRELLIS.2 models (~15.4 GB) are downloaded automatically from HuggingFace on first use.*\n"- " *LICENSE NOTICE: Only the 'Native (TRELLIS.2)' texture mode uses nvdiffrast/nvdiffrec*\n"- " *(NVIDIA Source Code License — non-commercial use only). Details in the TRELLIS.2 wiki page.*",- },- '9': {"name": "[PBR DECOMPOSITION] Marigold IID Node",- "tags": ["pbr_marigold"],- "size_gb": 0.01,- "description_suffix": "*Installs ComfyUI-Marigold custom node for PBR decomposition (albedo, roughness, metallic).*\n"- " *IID models (~2GB each) are downloaded automatically from HuggingFace on first use.*",- },- '10': {"name": "[PBR DECOMPOSITION] StableDelight Node + Model",- "tags": ["pbr_marigold", "pbr_stabledelight"],- "size_gb": 3.3,- "description_suffix": "*Installs ComfyUI_StableDelight_ll custom node + downloads the*\n"- " *Stable-X/yoso-delight-v0-4-base model (~3.3GB fp16) for specular-free albedo.*",- },- '11': {"name": "[DEPRECATED] FLUX.2 Klein 4B FP8 + Qwen 3 Text Encoder + VAE",- "tags": ["flux2_klein"],- "size_gb": 12.4,- "description_suffix": "*Downloads FLUX.2 Klein 4B FP8 diffusion model (~4.1GB), Qwen 3 4B text encoder bf16 (~8.0GB),*\n"- " *and FLUX.2 VAE (~0.3GB). All ComfyUI nodes are built-in (no custom nodes needed).*\n"- " *Deprecated: StableGen shows FLUX.2 Klein only with Enable Deprecated Architectures.*\n"- " *Apache 2.0 license. Requires ~13GB VRAM.*",- },- '12': {"name": "[PBR DECOMPOSITION] Marigold V2 Models (Albedo + Normals)",- "tags": ["pbr_marigold_v2"],- "size_gb": 23.3,- "description_suffix": "*Downloads Marigold V2 (Apache 2.0): the int8 Qwen Image Edit 2509 base (~19.5GB) plus albedo*\n"- " *and normals LoRAs, VAEs and conditionings. Uses ComfyUI core nodes (September 2026 or newer).*\n"- " *Roughness and metallic still need the Marigold IID node (option 9).*",- },- '13': {"name": "[QWEN IMAGE 2.1] Diffusion Model + Text Encoder + VAE",- "tags": ["qwen_image_21"],- "size_gb": 14.3,- "notice": "qwen21",- "description_suffix": "*Downloads Qwen Image 2.1 int8 (~7.3GB), the Qwen3-VL 8B text encoder (~6.3GB) and VAE*\n"- " *(~0.7GB). Uses ComfyUI core nodes (September 2026 or newer).*\n"- " *LICENSE NOTICE: Qwen Research License, non-commercial use only.*",- },- '14': {"name": "[AUTO-RIGGING] SkinTokens Node + Runtime",- "tags": ["skintokens"],- "size_gb": 9.0,- "description_suffix": "*Installs the StableGen SkinTokens node and builds SkinTokens in its own environment*\n"- " *(PyTorch, flash-attn when available, checkpoints ~1.6GB). Rigs TRELLIS.2 meshes; NVIDIA GPU.*",- },- '15': {"name": "[EXPERIMENTAL] Qwen Image 2.1 Turbo",- "tags": ["qwen_image_21_turbo"],- "size_gb": 13.9,- "notice": "qwen21",- "description_suffix": "*Downloads the Qwen Image 2.1 Turbo int8 model (~6.9GB) and, unless package 13 already did,*\n"- " *the Qwen Image 2.1 text encoder and VAE (~7.0GB). Uses ComfyUI core nodes.*\n"- " *LICENSE NOTICE: Qwen Research License, non-commercial use only.*",- },- '16': {"name": "[EXPERIMENTAL] MOSS Image + Depth Control",- "tags": ["moss_image"],- "size_gb": 15.0,- "description_suffix": "*Downloads MOSS-Image int8 (~5.2GB), its Qwen3.5 9B text encoder (~9.3GB), VAE (~0.2GB) and*\n"- " *color/depth control adapter (~0.3GB). Needs ComfyUI 0.42.3 or newer. Apache 2.0.*",- },- '17': {"name": "[EXPERIMENTAL] FIBO 2.0 Edit",- "tags": ["fibo_edit"],- "size_gb": 13.0,- "notice": "fibo",- "description_suffix": "*Downloads Bria FIBO 2.0 Edit Turbo int8 (~8.0GB), its Qwen3-VL 4B text encoder (~4.6GB) and*\n"- " *the FLUX.2 VAE (~0.3GB). Needs a ComfyUI build with core FIBO 2.0 support (master, October 2026).*\n"- " *LICENSE NOTICE: CC BY-NC 4.0, non-commercial use only.*",- },-}--LICENSE_NOTICES: Dict[str, List[str]] = {- "trellis2": [- "TRELLIS.2 THIRD-PARTY LICENSE NOTICE",- "This notice applies only to the TRELLIS.2 feature. StableGen's projection texturing is unaffected.",- "",- "ComfyUI-TRELLIS2 and the TRELLIS.2 model are MIT-licensed. The TRELLIS.2 Native texture mode uses",- "NVIDIA's nvdiffrast and nvdiffrec, licensed for 'research or evaluation purposes only and not for any",- "direct or indirect monetary gain' (Section 3.3). Only that texture mode uses them; shape-only and",- "projection texture modes do not.",- "",- "Details: https://github.com/sakalond/StableGen/wiki/TRELLIS.2-mesh-generation#third-party-licenses",- ],- "qwen21": [- "QWEN IMAGE 2.1 LICENSE NOTICE",- "Qwen Image 2.1 is released under the Qwen Research License, which allows non-commercial use only",- "(research or evaluation). Commercial use needs a separate license from the Qwen team.",- "Qwen Image Edit 2509 (packages 5-7) is Apache 2.0 and not affected.",- "",- "License: https://huggingface.co/Qwen/Qwen-Image-2.1/blob/main/LICENSE",- ],- "fibo": [- "FIBO 2.0 LICENSE NOTICE",- "Bria FIBO 2.0 is released under CC BY-NC 4.0, which allows non-commercial use only.",- "Commercial use needs an agreement with Bria.",- "",- "License: https://huggingface.co/briaai/Fibo-2.0-edit-turbo",- ],-}--# --- Helper Functions ----PYTHON_OVERRIDE: Optional[str] = None # --python-ASSUME_YES = False # --yes---def print_header(title: str):- print(f"\n{'='*10} {title} {'='*10}")--def print_separator(char='-', length=70):- print(char * length)---def ask(question: str, default_yes: bool = True, yes_answers: bool = True) -> bool:- """Ask a yes/no question. --yes answers it, unless yes_answers is False (then --yes means no)."""- if ASSUME_YES:- print(f"{question} {'yes' if yes_answers else 'no'} (--yes)")- return yes_answers- suffix = "(y/n, Enter for yes)" if default_yes else "(y/n)"- try:- answer = input(f"{question} {suffix}: ").strip().lower()- except EOFError:- return False- return answer == "y" or (default_yes and answer == "")---def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:- parser = argparse.ArgumentParser(description="StableGen dependency installer for ComfyUI.")- parser.add_argument("comfyuipath", nargs='?', default=None,- help="Your ComfyUI folder (the one with 'models' and 'custom_nodes'). Asked for if omitted.")- parser.add_argument("--packages",- help="Package numbers to install without the menu, comma-separated (e.g. 3,8). See --list.")- parser.add_argument("--yes", "-y", action="store_true",- help="Answer yes to every question, including the license notices.")- parser.add_argument("--list", action="store_true", help="List the packages and what each installs, then exit.")- parser.add_argument("--dry-run", action="store_true", help="Show what would be installed; change nothing.")- parser.add_argument("--update-nodes", action="store_true",- help="Move custom nodes that are already installed to the commits StableGen was tested with.")- parser.add_argument("--verify", action="store_true",- help="Check the installation: model files are in place and ComfyUI registers every node the "- "packages need. With --packages it runs after installing them (add --dry-run to only "- "check them); alone it checks every package that looks installed.")- parser.add_argument("--server",- help="Verify against this running ComfyUI (e.g. 127.0.0.1:8188) instead of starting one.")- parser.add_argument("--verify-timeout", type=int, default=900,- help="Seconds to wait for ComfyUI to start during --verify (default 900: the first start "- "after installing TRELLIS.2 builds its environment).")- parser.add_argument("--verify-hashes", action="store_true",- help="Check the SHA-256 of Hugging Face downloads, including files already present (slow).")- parser.add_argument("--python", help="Python executable of your ComfyUI environment (detected otherwise).")- parser.add_argument("--repair", action="store_true",- help="Repair installed TRELLIS.2 nodes without the menu: re-apply StableGen's patches and "- "sync their isolated environments with ComfyUI core. Run after updating ComfyUI or "- "the TRELLIS.2 node.")- parser.add_argument("--check", action="store_true",- help="Only report whether installed TRELLIS.2 environments are out of date; change nothing.")- return parser.parse_args(argv)---def get_comfyui_path_from_args(args: argparse.Namespace) -> Path:- comfyui_path_str = args.comfyuipath- while not comfyui_path_str:- if ASSUME_YES:- sys.exit("Error: pass the ComfyUI folder as an argument when using --yes.")- comfyui_path_str = input("Please enter the full path to your ComfyUI installation directory: ").strip().strip('"')-- comfyui_path = Path(comfyui_path_str).expanduser().resolve()-- if not comfyui_path.is_dir():- sys.exit(f"Error: ComfyUI path '{comfyui_path}' not found or not a directory.")- if not (comfyui_path / "models").is_dir() or not (comfyui_path / "custom_nodes").is_dir():- inner = comfyui_path / "ComfyUI" # the portable build's outer folder- if (inner / "models").is_dir() and (inner / "custom_nodes").is_dir():- print(f"Using the ComfyUI folder inside it: {inner}")- return inner- sys.exit(f"Error: '{comfyui_path}' does not look like a ComfyUI folder (no 'models' or 'custom_nodes').")- return comfyui_path---def python_candidates(comfyui_path: Path) -> List[Path]:- """Where ComfyUI's Python usually lives. The Windows portable build keeps it next to the ComfyUI folder, in- 'python_embeded' (sic); venvs sit inside the folder or next to it (ComfyUI Desktop uses '.venv')."""- out = []- for base in (comfyui_path.parent, comfyui_path):- for name in ("python_embeded", "python_embedded"):- out.append(base / name / "python.exe")- for base in (comfyui_path, comfyui_path.parent):- for venv in ("venv", ".venv"):- out.append(base / venv / "Scripts" / "python.exe")- out.append(base / venv / "bin" / "python")- return out---def find_comfyui_python(comfyui_path: Path) -> str:- """The Python ComfyUI runs with: --python, a portable build's embedded Python, a venv, else this Python."""- if PYTHON_OVERRIDE:- return PYTHON_OVERRIDE- for candidate in python_candidates(comfyui_path):- if candidate.is_file():- return str(candidate)- return sys.executable---_PYTHON_REPORT = (- "import sys\n"- "v = sys.version_info\n"- "print(f'{v.major}.{v.minor}.{v.micro}')\n"- "try:\n"- " import importlib.metadata as m\n"- " print(m.version('torch'))\n"- "except Exception:\n"- " print('not installed')\n"-)---def describe_python(comfyui_path: Path) -> bool:- """Print the Python the installer will use. False when none was found and this script's own Python is used."""- python = find_comfyui_python(comfyui_path)- detected = bool(PYTHON_OVERRIDE) or any(c.is_file() for c in python_candidates(comfyui_path))- try:- out = subprocess.run([python, "-c", _PYTHON_REPORT], capture_output=True, env=UTF8_ENV, timeout=120,- **UTF8_TEXT)- version, torch = (out.stdout.split() + ["?", "?"])[:2]- except (OSError, subprocess.TimeoutExpired):- version, torch = "?", "?"- print(f"ComfyUI Python: {python} (Python {version}, torch {torch})")- if not detected:- print("WARNING: ComfyUI's own Python was not found (a portable build's python_embeded or a venv), so the")- print(" Python running this installer is used. If ComfyUI runs with a different Python, re-run")- print(" with --python <path to that python>.")- return detected---def install_pip_packages(pip_packages: List[str], comfyui_path: Path, force_reinstall: bool = False) -> bool:- """Install pip packages into ComfyUI's Python environment. Returns True when all of them installed."""- python_exe = find_comfyui_python(comfyui_path)- print(f" Installing pip packages into ComfyUI Python: {python_exe}")- ok = True- for pkg in pip_packages:- print(f" pip install {pkg} ...")- try:- subprocess.run(- [python_exe, "-m", "pip", "install"] + (["--force-reinstall", "--no-deps"] if force_reinstall else []) + [pkg],- check=True,- )- print(f" Successfully installed '{pkg}'.")- except subprocess.CalledProcessError as e:- print(f" ERROR: Failed to install '{pkg}' (exit code {e.returncode}).")- print(f" You may need to install it manually: pip install {pkg}")- ok = False- except FileNotFoundError:- print(f" ERROR: Python executable not found at '{python_exe}'.")- print(f" Please install '{pkg}' manually into your ComfyUI Python environment.")- return False- return ok---def _apply_all_comfy_env_patches(comfyui_path: Path):- """Apply all comfy-env patches (platform tag, wheel fallback, site isolation, dist-info, validator)."""- _patch_comfy_env_platform_tag(comfyui_path)- _patch_comfy_env_wheel_fallback(comfyui_path)- _patch_comfy_env_user_site_isolation(comfyui_path)- _patch_comfy_env_distinfo_normalize(comfyui_path)- _patch_comfy_env_validator(comfyui_path)---def _patch_comfy_env_validator(comfyui_path: Path):- """Patch comfy-env's _validate_node_config to strip torch/torchvision instead of crashing."""- python_exe = find_comfyui_python(comfyui_path)- result = subprocess.run(- [python_exe, "-c",- "import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'toml_generator.py') if s and s.origin else '')"],- capture_output=True, env=UTF8_ENV, **UTF8_TEXT,- )- if result.returncode != 0:- print(" WARNING: Could not locate comfy_env toml_generator.py, skipping validator patch")- return-- toml_gen_path = Path(result.stdout.strip().splitlines()[-1])- if not toml_gen_path.is_file():- print(f" WARNING: {toml_gen_path} not found, skipping validator patch")- return-- content = toml_gen_path.read_text(encoding="utf-8")- marker = "# StableGen patch: bypass toml validation crash by stripping torch/torchvision"- if marker in content:- print(" comfy-env validator patch already applied")- return-- old = (- "def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"- " \"\"\"Reject node configs that try to redefine the workspace torch pin.\"\"\"\n"- " bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"- " if bad:\n"- " raise ValueError(\n"- " f\"[{name}] comfy-env.toml has {bad} under [cuda] packages. \"\n"- " \"Plain torch/torchvision/torchaudio are pinned workspace-wide \"\n"- " \"(replicated into every feature so the rattler cache dedupes). \"\n"- " \"Remove them from [cuda] packages -- keep only CUDA-only wheels there \"\n"- " \"(cumesh, flash-attn, cc_torch, nvdiffrast, etc.).\"\n"- " )"- )-- if old not in content:- old_alt = (- "def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"- " \"\"\"Reject node configs that try to redefine the workspace torch pin.\"\"\"\n"- " bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"- " if bad:\n"- " raise ValueError(\n"- " f\"[{name}] comfy-env.toml has {bad} under [cuda] packages. \"\n"- " \"Plain torch/torchvision/torchaudio are pinned workspace-wide \"\n"- " \"(replicated into every feature so the rattler cache dedupes). \"\n"- " \"Remove them from [cuda] packages -- keep only CUDA-only wheels there \"\n"- " \"(cumesh, flash-attn, cc_torch, nvdiffrast, etc.).\"\n"- " )\n"- )- if old_alt in content:- old = old_alt- else:- print(" WARNING: Could not find validator anchor in toml_generator.py (already modified?)")- return-- new = (- "def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"- " " + marker + "\n"- " bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"- " if bad:\n"- " for p in bad:\n"- " try:\n"- " cfg.cuda_packages.remove(p)\n"- " except ValueError:\n"- " pass\n"- " print(f'[comfy-env] [{name}] stripped plain torch/torchvision from [cuda] packages list', file=sys.stderr)\n"- )-- content = content.replace(old, new)- toml_gen_path.write_text(content, encoding="utf-8")- print(" Patched comfy-env _validate_node_config() to bypass invalid torch/torchvision declarations")---def _patch_comfy_env_platform_tag(comfyui_path: Path):- """Fix comfy-env 0.2.0 Linux platform tag matching bug.-- comfy-env's _platform_tag() returns "linux_x86_64" but pre-built CUDA- wheels use "manylinux_2_34_x86_64" filenames. The substring check- ``"linux_x86_64" in "manylinux_2_34_x86_64"`` fails because the glibc- version sits between "linux_" and "x86_64".-- Fix: return "linux" instead, which IS a substring of "manylinux_*".- """- python_exe = find_comfyui_python(comfyui_path)- result = subprocess.run(- [python_exe, "-c",- "import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'cuda_wheels.py') if s and s.origin else '')"],- capture_output=True, env=UTF8_ENV, **UTF8_TEXT,- )- if result.returncode != 0:- print(" WARNING: Could not locate comfy_env cuda_wheels.py, "- "skipping platform tag patch")- return-- cuda_wheels_path = Path(result.stdout.strip())- if not cuda_wheels_path.is_file():- print(f" WARNING: {cuda_wheels_path} not found, "- "skipping platform tag patch")- return-- content = cuda_wheels_path.read_text(encoding="utf-8")- marker = "# StableGen patch: linux platform tag"- if marker in content:- print(" comfy-env platform tag patch already applied")- return-- old = 'return "linux_x86_64"'- if old not in content:- print(" WARNING: Could not find platform tag to patch in "- "cuda_wheels.py (already fixed upstream?)")- return-- content = content.replace(old, f'return "linux" {marker}')- cuda_wheels_path.write_text(content, encoding="utf-8")- print(" Patched comfy-env _platform_tag() for Linux manylinux matching")---def _patch_comfy_env_wheel_fallback(comfyui_path: Path):- """Fix comfy-env get_wheel_url missing torch version fallback.-- Some packages (e.g. flash-attn) lack wheels for the exact torch version- comfy-env pins (e.g. torch 2.4 on Linux, though torch 2.5+ exist).- Patch get_wheel_url to try higher torch versions when exact match fails.- """- python_exe = find_comfyui_python(comfyui_path)- result = subprocess.run(- [python_exe, "-c",- "import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'cuda_wheels.py') if s and s.origin else '')"],- capture_output=True, env=UTF8_ENV, **UTF8_TEXT,- )- if result.returncode != 0:- print(" WARNING: Could not locate comfy_env cuda_wheels.py, "- "skipping wheel fallback patch")- return-- cuda_wheels_path = Path(result.stdout.strip())- if not cuda_wheels_path.is_file():- print(f" WARNING: {cuda_wheels_path} not found, "- "skipping wheel fallback patch")- return-- content = cuda_wheels_path.read_text(encoding="utf-8")- marker = "# StableGen patch: torch version fallback"- if marker in content:- print(" comfy-env wheel fallback patch already applied")- return-- anchor = " return None\n\n\ndef find_available_wheels"- if anchor not in content:- print(" WARNING: Could not find get_wheel_url anchor in "- "cuda_wheels.py (already fixed upstream?)")- return-- fallback = "\n".join([- " " + marker,- " _cu_re = re.compile(r'\\+cu' + cuda_short + r'torch(\\d+)')",- " for pkg_dir in _pkg_variants(package):",- " try:",- ' with urllib.request.urlopen(f"{CUDA_WHEELS_INDEX}{pkg_dir}/", timeout=10) as resp:',- ' html = resp.read().decode("utf-8")',- " except Exception: continue",- " _best_url, _best_tv = None, None",- " for match in link_pattern.finditer(html):",- " wheel_url, display = match.group(1), match.group(2)",- " _tv_m = _cu_re.search(display)",- " if not _tv_m: continue",- " _tv = int(_tv_m.group(1))",- " if _tv <= int(torch_short.replace('.', '')): continue",- " if py_tag not in display: continue",- " if platform_tag and platform_tag not in display: continue",- " if _best_tv is None or _tv < _best_tv:",- " _best_tv = _tv",- ' _best_url = wheel_url if wheel_url.startswith("http") else f"{CUDA_WHEELS_INDEX}{pkg_dir}/{wheel_url}"',- " if _best_url:",- " return _best_url",- ]) + "\n"-- content = content.replace(anchor, fallback + anchor)- cuda_wheels_path.write_text(content, encoding="utf-8")- print(" Patched comfy-env get_wheel_url() for torch version fallback")---def _patch_comfy_env_user_site_isolation(comfyui_path: Path):- """Prevent user site-packages from leaking into comfy-env workers.-- comfy-env's build_isolation_env() never sets PYTHONNOUSERSITE, so- packages installed in ~/.local/lib/pythonX.Y/site-packages/ leak into- the isolated worker subprocess. Old versions of scipy, tensorboard,- etc. from user site-packages then clash with the env's numpy 2.x.-- Fix: set PYTHONNOUSERSITE=1 in build_isolation_env() so the worker- subprocess ignores the user site-packages directory entirely.- """- python_exe = find_comfyui_python(comfyui_path)- result = subprocess.run(- [python_exe, "-c",- "import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'isolation', 'wrap.py') if s and s.origin else '')"],- capture_output=True, env=UTF8_ENV, **UTF8_TEXT,- )- if result.returncode != 0:- print(" WARNING: Could not locate comfy_env wrap.py, "- "skipping user site isolation patch")- return-- wrap_path = Path(result.stdout.strip())- if not wrap_path.is_file():- print(f" WARNING: {wrap_path} not found, "- "skipping user site isolation patch")- return-- content = wrap_path.read_text(encoding="utf-8")- marker = "# StableGen patch: block user site-packages"- if marker in content:- print(" comfy-env user site isolation patch already applied")- return-- anchor = ' env["COMFYUI_ISOLATION_WORKER"] = "1"'- if anchor not in content:- print(" WARNING: Could not find build_isolation_env anchor in "- "wrap.py (already fixed upstream?)")- return-- patch_line = f' env["PYTHONNOUSERSITE"] = "1" {marker}'- content = content.replace(anchor, anchor + "\n" + patch_line)- wrap_path.write_text(content, encoding="utf-8")- print(" Patched comfy-env build_isolation_env() to block user site-packages")---def _patch_comfy_env_distinfo_normalize(comfyui_path: Path):- """Fix any dist-info folders crashing pixi rebuilds.-- If flex_gemm or nvdiffrec-render is installed in a pixi environment, its wheel creates a- .dist-info map with an unnormalized hyphen (flex-gemm-...) which crashes- subsequent uv pip install runs due to strict PEP440 string validation.- We patch comfy_env to monkeypatch subprocess.run so this fix runs after every pip install.- """- python_exe = find_comfyui_python(comfyui_path)- result = subprocess.run(- [python_exe, "-c",- "import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'install.py') if s and s.origin else '')"],- capture_output=True, env=UTF8_ENV, **UTF8_TEXT,- )- if result.returncode != 0:- print(f" WARNING: Could not locate comfy_env install.py: {result.stderr}")- return-- install_path = Path(result.stdout.strip().splitlines()[-1])- if not install_path.is_file():- print(f" WARNING: comfy_env install.py does not exist at {install_path}")- return-- content = install_path.read_text(encoding="utf-8")- marker = "# StableGen patch v7: aggressive dist-info cleanup via subprocess monkeypatch"- if marker in content:- print(" comfy-env universal dist-info patch already applied")- return-- if "# StableGen patch" in content:- print(" Fixing previously broken comfy-env installation...")- subprocess.run([python_exe, "-m", "pip", "install", "--force-reinstall", "--no-deps", COMFY_ENV], check=True, capture_output=True)- _patch_comfy_env_platform_tag(comfyui_path)- _patch_comfy_env_wheel_fallback(comfyui_path)- _patch_comfy_env_user_site_isolation(comfyui_path)- content = install_path.read_text(encoding="utf-8")-- anchor = 'log(f"[comfy-env] build_dir={build_dir}")'- if anchor not in content:- print(f" WARNING: Could not find anchor in comfy_env install.py")- return-- # Get the correct indentation from the anchor dynamically- _indent_match = re.search(r"([ \t]*)" + re.escape(anchor), content)- _ind = _indent_match.group(1) if _indent_match else " "-- # Format patch properly- patch_lines = []-- # We use a raw string for the regex backslashes, but f-string needed for anchor/marker.- # To keep it simple, we use a normal string and .replace() instead of f-string- _raw_patch = r"""ANCHOR-MARKER-try:- _orig_subprocess_run = subprocess.run- def _patched_subprocess_run(*args, **kwargs):- _res = _orig_subprocess_run(*args, **kwargs)- try:- import sys as _sys_patch- import pathlib as _pathlib_patch- import re as _re_patch- def _fix_dist_info(_p):- if not _p.is_dir() or not _p.name.endswith(".dist-info"): return- _m = _re_patch.match(r"^([a-zA-Z0-9_\-]+?)-([0-9].*)\.dist-info$", _p.name)- if _m and "-" in _m.group(1):- _new_name = _m.group(1).replace("-", "_") + "-" + _m.group(2) + ".dist-info"- _p.rename(_p.parent / _new_name)-- for _sp in _sys_patch.path:- _sp_path = _pathlib_patch.Path(_sp)- if _sp_path.is_dir() and "site-packages" in _sp_path.name:- for _p in _sp_path.glob("*.dist-info"):- _fix_dist_info(_p)-- _sp_dir = build_dir / ".pixi" / "envs" / "default" / ("Lib" if _sys_patch.platform == "win32" else "lib")- if _sys_patch.platform != "win32":- for _p in _sp_dir.glob("python*"): _sp_dir = _p- _sp_dir = _sp_dir / "site-packages"- if _sp_dir.exists():- for _p in _sp_dir.iterdir():- _fix_dist_info(_p)- except Exception as _e:- log(f"Failed to normalize dist-info naming: {_e}")- return _res- subprocess.run = _patched_subprocess_run-except Exception as _e:- pass"""-- _raw_patch = _raw_patch.replace("ANCHOR", anchor).replace("MARKER", marker)-- for i, line in enumerate(_raw_patch.split("\n")):- if i == 0:- patch_lines.append(line)- else:- patch_lines.append(_ind + line)- patch = "\n".join(patch_lines)-- content = content.replace(anchor, patch)- install_path.write_text(content, encoding="utf-8")- print(" Patched comfy-env installation to monkeypatch subprocess.run for dist-info normalizations")---def _patch_flex_gemm_autotuner(repo_path: Path):- """Fix flex_gemm TritonPersistentCacheAutotuner for triton 3.0+.-- flex_gemm 1.0.0 passes a ``do_bench`` argument to triton's- ``Autotuner.__init__`` which was removed in triton 3.0. Drop it so- the call signature matches.- """- env_dirs = glob.glob(str(repo_path / "nodes" / "_env_*"))- if not env_dirs:- return- for env_dir in env_dirs:- matches = glob.glob(- str(Path(env_dir) / "lib" / "python*" / "site-packages"- / "flex_gemm" / "utils" / "autotuner.py"))- for autotuner_path in matches:- autotuner_path = Path(autotuner_path)- content = autotuner_path.read_text(encoding="utf-8")- marker = "# StableGen patch: drop do_bench for triton 3.0+"- if marker in content:- print(" flex_gemm autotuner patch already applied")- continue- old = (- " warmup,\n"- " rep,\n"- " use_cuda_graph,\n"- " do_bench,\n"- " )"- )- if old not in content:- print(" WARNING: Could not find do_bench in flex_gemm "- "autotuner.py (already fixed upstream?)")- continue- new = (- " warmup if warmup is not None else 25, # StableGen patch: triton 3.0 needs int\n"- " rep if rep is not None else 100,\n"- " use_cuda_graph,\n"- f" ) {marker}\n"- " if not hasattr(self, 'keys'): # StableGen patch: triton 3.0 compat\n"- " self.keys = key"- )- content = content.replace(old, new)- autotuner_path.write_text(content, encoding="utf-8")- print(" Patched flex_gemm autotuner: removed do_bench for triton 3.0+")---def run_node_install_script(item_details: Dict[str, Any], comfyui_path: Path) -> bool:- """Run a custom node's install.py to resolve all its dependencies. Returns True on success.-- Some nodes (e.g. ComfyUI-TRELLIS2) use comfy_env which manages CUDA- wheel installation from custom indices. Running their install.py- after cloning lets comfy_env handle everything automatically.-- The first attempt may fail if the auto-detected CUDA version (e.g.- 12.8) lacks wheels on the cuda-wheels index. The node's install.py- also downgrades comfy-env to 0.1.92 (via requirements.txt of both- TRELLIS2 and GeometryPack), wiping our patches from the on-disk- package. Within a single subprocess the in-memory modules survive,- but a retry needs freshly re-applied patches on disk.- """- repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]- install_script = repo_path / "install.py"- if not install_script.is_file():- print(f" WARNING: No install.py found in '{repo_path}'. Skipping dependency install.")- return True-- python_exe = find_comfyui_python(comfyui_path)- print(f" Running install.py for {item_details['name']}...")- print(f" {python_exe} {install_script}")-- try:- subprocess.run(- [python_exe, str(install_script)],- check=True,- cwd=str(repo_path),- )- print(f" Successfully ran install.py for '{item_details['name']}'.")- return True- except subprocess.CalledProcessError:- if not _uses_comfy_env(item_details):- print(f" ERROR: install.py failed. Run it manually to see why:")- print(f" cd {repo_path}")- print(f" {python_exe} install.py")- return False- # The cuda-wheels index may not have wheels for the auto-detected- # CUDA version yet (e.g. cu128). Retry with CUDA 12.4 which has- # the widest wheel coverage for flex_gemm / nvdiffrast.- #- # The first attempt's requirements.txt installs downgraded- # comfy-env on disk (patches wiped). Restore comfy-env- # with patches before retrying so the new subprocess sees them.- print(" Install failed. Restoring comfy-env + patches for retry...")- install_pip_packages([COMFY_ENV], comfyui_path, force_reinstall=True)- _apply_all_comfy_env_patches(comfyui_path)-- print(" Retrying with CUDA 12.4 fallback...")- env = os.environ.copy()- env["COMFY_ENV_CUDA_VERSION"] = "12.4"- try:- subprocess.run(- [python_exe, str(install_script)],- check=True,- cwd=str(repo_path),- env=env,- )- print(f" Successfully ran install.py for '{item_details['name']}' (CUDA 12.4 fallback).")- return True- except subprocess.CalledProcessError as e:- print(f" ERROR: install.py failed (exit code {e.returncode}).")- print(f" You may need to run it manually:")- print(f" cd {repo_path}")- print(f" {python_exe} install.py")- return False- except FileNotFoundError:- print(f" ERROR: Python executable not found at '{python_exe}'.")- return False---def _uses_comfy_env(item_details: Dict[str, Any]) -> bool:- return any("comfy-env" in p for p in item_details.get("pip_packages", []))---def sync_comfy_env_core(item_details: Dict[str, Any], comfyui_path: Path, check_only: bool = False) -> bool:- """Bring ComfyUI core's exact pins into a comfy-env node's isolated environments.-- Writes the sync module into the node folder (the prestartup patch imports it- on every ComfyUI start) and runs it once now with ComfyUI's own Python, so it- resolves env paths with the installed comfy-env. Returns True when everything- is in step.- """- repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]- if not repo_path.is_dir():- return True- module_path = repo_path / _COMFY_ENV_SYNC_FILENAME- if not module_path.is_file() or module_path.read_text(encoding="utf-8") != _COMFY_ENV_SYNC_SOURCE:- module_path.write_text(_COMFY_ENV_SYNC_SOURCE, encoding="utf-8")- python_exe = find_comfyui_python(comfyui_path)- action = "Checking" if check_only else "Syncing"- print(f" {action} {item_details['name']} isolated environment(s) with ComfyUI core requirements...")- try:- result = subprocess.run(- [python_exe, str(module_path), str(comfyui_path), str(repo_path)] + (["--check"] if check_only else []),- cwd=str(repo_path), timeout=1800,- )- except (OSError, subprocess.TimeoutExpired) as e:- print(f" WARNING: Environment sync did not complete: {e}")- return False- if result.returncode == 0:- print(" Isolated environment(s) match ComfyUI core.")- return True- print(" WARNING: Some isolated packages are still out of date (see messages above).")- print(f" Re-run with: python installer.py \"{comfyui_path}\" --repair")- return False---def repair_comfy_env_nodes(comfyui_path: Path, check_only: bool = False) -> bool:- """Re-apply StableGen's patches and env sync to every installed comfy-env node.-- Node updates (git pull, ComfyUI-Manager) overwrite patched files, and ComfyUI- updates move core's pinned packages ahead of the isolated envs; both break- TRELLIS.2 until repaired. Safe to run any number of times.- """- ok = True- for item in DEPENDENCIES.values():- if item.get("type") != "node" or not _uses_comfy_env(item):- continue- repo_path = comfyui_path / item["target_dir_relative"] / item["repo_name"]- if not repo_path.is_dir():- continue- print_separator(char='.')- print(f"{'Checking' if check_only else 'Repairing'}: {item['name']}")- if not check_only:- apply_post_clone_patches(item, comfyui_path)- ok = sync_comfy_env_core(item, comfyui_path, check_only=check_only) and ok- return ok---def apply_post_clone_patches(item_details: Dict[str, Any], comfyui_path: Path):- """Apply compatibility patches to a cloned custom node repository.-- Patches are defined in the dependency entry under 'post_clone_patches'.- Each patch dict has:- file – relative path inside the repo- marker – string checked to avoid re-applying- mode – 'insert' (default) or 'replace'-- Insert mode (default):- anchor – text before which the patch is inserted- patch – code string to insert-- Replace mode:- anchor – exact text to replace- patch – replacement text- """- patches = item_details.get("post_clone_patches")- if not patches:- return-- repo_path = (comfyui_path / item_details["target_dir_relative"]- / item_details["repo_name"])-- for p in patches:- target_file = repo_path / p["file"]- if not target_file.is_file():- print(f" WARNING: Patch target '{p['file']}' not found. Skipping.")- continue-- content = target_file.read_text(encoding="utf-8")-- # Already patched?- marker = p.get("marker", "")- if marker and marker in content:- print(f" Compat patch already applied to '{p['file']}'.")- continue-- anchor = p.get("anchor", "")- patch_code = p.get("patch", "")- mode = p.get("mode", "insert")-- if anchor and anchor in content:- if mode == "replace":- content = content.replace(anchor, patch_code, 1)- else:- content = content.replace(anchor, patch_code + anchor, 1)- target_file.write_text(content, encoding="utf-8")- print(f" Applied compat patch ({mode}) to '{p['file']}'.")- else:- print(f" WARNING: Anchor not found in '{p['file']}'. Patch skipped.")---def create_dir_if_not_exists(path: Path):- path.mkdir(parents=True, exist_ok=True)---# --- Downloads ----# Plain urllib, so the installer needs no third-party packages. Files download to '<name>.part' and are renamed-# once complete; an interrupted download resumes from the .part file on the next attempt or the next run.-USER_AGENT = "StableGen-installer"-DOWNLOAD_ATTEMPTS = 4-CHUNK = 1024 * 1024---class _RedirectRecorder(urllib.request.HTTPRedirectHandler):- """Follows redirects, keeps Hugging Face's x-linked-* headers (only the first response has them), and does not- forward an Authorization header to another host (the CDN URLs are pre-signed)."""-- def __init__(self):- super().__init__()- self.headers: Dict[str, str] = {}-- def redirect_request(self, req, fp, code, msg, headers, newurl):- for key in ("x-linked-etag", "x-linked-size"):- if headers.get(key) and key not in self.headers:- self.headers[key] = headers.get(key)- new = super().redirect_request(req, fp, code, msg, headers, newurl)- if new is not None and urllib.parse.urlparse(newurl).hostname != urllib.parse.urlparse(req.full_url).hostname:- new.remove_header("Authorization")- return new---def _open(url: str, method: str = "GET", headers: Optional[Dict[str, str]] = None, timeout: int = 60):- """Open a URL; returns (response, headers recorded on redirects). HF_TOKEN authenticates Hugging Face."""- recorder = _RedirectRecorder()- opener = urllib.request.build_opener(recorder)- request_headers = {"User-Agent": USER_AGENT}- token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")- if token and urllib.parse.urlparse(url).hostname == "huggingface.co":- request_headers["Authorization"] = f"Bearer {token}"- request_headers.update(headers or {})- response = opener.open(urllib.request.Request(url, method=method, headers=request_headers), timeout=timeout)- return response, recorder.headers---def remote_info(url: str) -> Tuple[int, Optional[str]]:- """(size in bytes or 0, SHA-256 or None) of a remote file. Hugging Face reports both for LFS files."""- try:- response, linked = _open(url, method="HEAD", timeout=30)- with response:- size = int(response.headers.get("Content-Length") or 0)- except Exception:- return 0, None- size = int(linked.get("x-linked-size") or 0) or size- etag = (linked.get("x-linked-etag") or "").strip().strip('"')- return size, (etag.lower() if re.fullmatch(r"[0-9a-fA-F]{64}", etag) else None)---def file_sha256(path: Path) -> str:- digest = hashlib.sha256()- with open(path, "rb") as f:- for block in iter(lambda: f.read(8 * CHUNK), b""):- digest.update(block)- return digest.hexdigest()---class _PlainProgress:- """Progress line for when tqdm is not installed."""-- def __init__(self, total: int, initial: int):- self.total, self.done, self.shown = total, initial, 0.0-- def update(self, n: int):- self.done += n- now = time.time()- if now - self.shown >= 1:- self.shown = now- pct = f" ({self.done / self.total:.0%})" if self.total else ""- print(f"\r {self.done / 1024**2:,.0f} / {self.total / 1024**2:,.0f} MB{pct}", end="", flush=True)-- def __enter__(self):- return self-- def __exit__(self, *exc):- print()---def _progress(name: str, total: int, initial: int):- if TQDM_AVAILABLE and total:- return tqdm(total=total, initial=initial, unit='B', unit_scale=True, unit_divisor=1024, desc=name[:40],- ascii=True)- return _PlainProgress(total, initial)---def download_url(url: str, final_path: Path, name: str, verify_hash: bool = False) -> Tuple[str, str]:- """Download url to final_path, resuming and retrying. Returns (status, message); status is 'installed',- 'present', 'warning' or 'failed'."""- final_path.parent.mkdir(parents=True, exist_ok=True)- part = final_path.with_name(final_path.name + ".part")- remote_size, remote_sha = remote_info(url)-- if final_path.exists():- local = final_path.stat().st_size- if not remote_size or local == remote_size:- if verify_hash and remote_sha:- print(f" Checking the SHA-256 of '{final_path.name}'...")- if file_sha256(final_path) == remote_sha:- return "present", "SHA-256 verified"- print(f" '{final_path.name}' does not match the published SHA-256; downloading it again.")- final_path.unlink()- else:- return "present", "" if remote_size else "server did not report a size; assumed complete"- elif local < remote_size:- print(f" '{final_path.name}' is incomplete ({local / 1024**2:,.0f} of {remote_size / 1024**2:,.0f} MB); "- f"resuming.")- if part.exists():- part.unlink()- final_path.rename(part)- else:- return "warning", (f"local file is {local:,} bytes but the server's is {remote_size:,}; left as is "- f"(delete it to download again)")-- error = ""- for attempt in range(1, DOWNLOAD_ATTEMPTS + 1):- have = part.stat().st_size if part.exists() else 0- if remote_size and have == remote_size:- break- if remote_size and have > remote_size:- part.unlink()- have = 0- try:- response, _ = _open(url, headers={"Range": f"bytes={have}-"} if have else None)- with response:- if have and response.status != 206:- have = 0 # the server ignored the range request: start over- length = int(response.headers.get("Content-Length") or 0)- total = remote_size or (have + length if length else 0)- with open(part, "ab" if have else "wb") as f, _progress(name, total, have) as bar:- while True:- block = response.read(CHUNK)- if not block:- break- f.write(block)- bar.update(len(block))- done = part.stat().st_size- if (remote_size and done < remote_size) or (not remote_size and length and done < have + length):- raise ConnectionError(f"connection closed after {done / 1024**2:,.0f} MB")- break- except urllib.error.HTTPError as e:- if e.code == 416 and have:- break # nothing left to fetch- if e.code in (401, 403):- return "failed", (f"HTTP {e.code}: access denied (a gated model needs its license accepted on "- f"Hugging Face and HF_TOKEN set)")- if e.code == 404:- return "failed", "HTTP 404: the file is no longer at this address"- error = f"HTTP {e.code}"- except (urllib.error.URLError, OSError, ConnectionError, socket.timeout) as e:- error = str(getattr(e, "reason", e))- if attempt < DOWNLOAD_ATTEMPTS:- wait = 5 * attempt- print(f" Download interrupted ({error}); retrying in {wait} s ({attempt}/{DOWNLOAD_ATTEMPTS - 1})...")- time.sleep(wait)- else:- return "failed", f"download failed after {DOWNLOAD_ATTEMPTS} attempts ({error}); run again to resume"-- size = part.stat().st_size if part.exists() else 0- if remote_size and size != remote_size:- return "failed", f"incomplete ({size:,} of {remote_size:,} bytes); run again to resume"- if verify_hash and remote_sha:- print(f" Checking the SHA-256 of '{final_path.name}'...")- if file_sha256(part) != remote_sha:- part.unlink()- return "failed", "SHA-256 mismatch; the download was deleted, run again"- os.replace(part, final_path)- return "installed", f"{size / 1024**2:,.0f} MB" + (", SHA-256 verified" if verify_hash and remote_sha else "")---def download_file(item_details: Dict[str, Any], comfyui_path: Path, verify_hash: bool = False) -> Tuple[str, str]:- url = item_details["url"]- final_filepath = comfyui_path / item_details["target_path_relative"] / item_details["filename"]- print(f" {item_details['name']} (~{item_details.get('size_mb', '?')} MB) - License: {item_details['license']}")- print(f" From: {url}")- print(f" To: {final_filepath}")- status, message = download_url(url, final_filepath, item_details['name'], verify_hash)- print(f" {status}{': ' + message if message else ''}")- return status, message---HF_REPO_PATTERNS = ["*.json", "*.txt", "*.yaml", "*.md", "*.py", "*.model", "*.fp16.safetensors", "*.fp16.bin",- "tokenizer/*"]---def _hf_repo_files(repo: str) -> List[str]:- response, _ = _open(f"https://huggingface.co/api/models/{repo}/tree/main?recursive=true", timeout=30)- with response:- entries = json.loads(response.read().decode("utf-8"))- return [e["path"] for e in entries if e.get("type") == "file"]---def download_hf_model(item_details: Dict[str, Any], comfyui_path: Path, verify_hash: bool = False) -> Tuple[str, str]:- """Download a Hugging Face diffusers repo (configs and fp16 weights) into ComfyUI/models/diffusers/<local_dir>.-- Required keys in *item_details*:- hf_repo – e.g. ``'Stable-X/yoso-delight-v0-4-base'``- local_dir – directory name under ``models/diffusers/``- """- hf_repo = item_details["hf_repo"]- target_dir = comfyui_path / "models" / "diffusers" / item_details["local_dir"]- print(f" Hugging Face model {hf_repo} (~{item_details.get('size_mb', '?')} MB) - "- f"License: {item_details.get('license', 'unknown')}")- print(f" To: {target_dir}")- try:- files = [f for f in _hf_repo_files(hf_repo)- if any(fnmatch.fnmatch(f, p) or fnmatch.fnmatch(f.split("/")[-1], p) for p in HF_REPO_PATTERNS)]- except Exception as e:- if (target_dir / "model_index.json").exists():- return "present", f"could not list the repository ({e}); kept the existing copy"- return "failed", f"could not list the repository: {e}"- statuses = []- for path in files:- url = f"https://huggingface.co/{hf_repo}/resolve/main/{urllib.parse.quote(path)}"- status, message = download_url(url, target_dir / path, path, verify_hash)- if status == "failed":- print(f" {path}: {message}")- return "failed", f"{path}: {message}"- statuses.append(status)- if "installed" in statuses:- return "installed", f"{statuses.count('installed')} of {len(files)} files downloaded"- return "present", f"{len(files)} files"---def _clean_stale_comfy_envs(repo_path: Path):- """Remove stale comfy-env virtualenvs (_env_*) from a node tree.-- comfy-env creates isolated virtualenvs named _env_<hash> based on the- comfy-env.toml dependency manifest. When the node is switched to a- different commit whose manifest lists different packages (e.g. timm- was added), the OLD _env_* dirs are never rebuilt and keep serving- outdated packages. Deleting them forces comfy-env to recreate- correct environments on the next ComfyUI startup.- """- removed = 0- for env_dir in repo_path.rglob("_env_*"):- if env_dir.is_dir():- try:- shutil.rmtree(str(env_dir))- print(f" Removed stale comfy-env '{env_dir.name}' (will be rebuilt on next launch).")- removed += 1- except Exception as e:- print(f" WARNING: Could not remove '{env_dir}': {e}")- if removed:- print(f" Cleaned {removed} stale environment(s). comfy-env will recreate them on next ComfyUI start.")---def _git(args: List[str], cwd: Path) -> subprocess.CompletedProcess:- return subprocess.run(["git"] + args, cwd=str(cwd), capture_output=True, **UTF8_TEXT)---def clone_git_repo(item_details: Dict[str, Any], comfyui_path: Path, update_nodes: bool = False) -> Tuple[str, str]:- """Clone a custom node at its tested commit, or check an existing clone. Returns (status, message)."""- git_url = item_details["git_url"]- repo_name = item_details["repo_name"]- repo_path = comfyui_path / item_details["target_dir_relative"] / repo_name- pinned = item_details.get("commit")-- try:- if repo_path.is_dir():- if not (repo_path / ".git").exists():- return "present", "installed without Git (e.g. through ComfyUI-Manager); left as is"- head = _git(["rev-parse", "HEAD"], repo_path).stdout.strip()- if not pinned or head == pinned:- return "present", f"at {head[:12]}" if head else ""- if not (item_details.get("enforce_pin") or update_nodes):- return "warning", (f"at {head[:12]}; StableGen was tested with {pinned[:12]} "- f"(re-run with --update-nodes to switch)")- print(f" Moving '{repo_name}' to the tested commit {pinned[:12]}...")- _git(["fetch", "origin"], repo_path)- checkout = _git(["checkout", pinned], repo_path)- if checkout.returncode != 0:- reason = (checkout.stderr.strip().splitlines() or ["unknown error"])[-1]- return "failed", (f"could not check out {pinned[:12]}: {reason} (commit or discard local changes "- f"in {repo_path})")- if item_details.get("clean_envs"):- _clean_stale_comfy_envs(repo_path)- return "updated", f"{head[:12]} -> {pinned[:12]}"-- create_dir_if_not_exists(repo_path.parent)- print(f" Cloning: {item_details['name']} - License: {item_details['license']}")- print(f" From: {git_url}")- print(f" To: {repo_path}")- clone = subprocess.run(['git', 'clone', git_url, str(repo_path)], cwd=str(repo_path.parent))- if clone.returncode != 0:- return "failed", "git clone failed: check your network and that the repository is public"- if pinned:- checkout = _git(["checkout", pinned], repo_path)- if checkout.returncode != 0:- return "failed", f"cloned, but the tested commit {pinned[:12]} is missing upstream"- return "installed", f"at {pinned[:12]}" if pinned else "latest commit"- except FileNotFoundError:- return "failed", "Git is not installed or not on PATH"---# --- Post-install steps for nodes that set up their own runtime ----_NUNCHAKU_WHEEL_SCRIPT = r'''"""Install the Nunchaku engine wheel matching this Python, torch and platform (StableGen installer)."""-import importlib.metadata-import importlib.util-import sys--spec = importlib.util.spec_from_file_location("nunchaku_installers", sys.argv[1])-installers = importlib.util.module_from_spec(spec)-spec.loader.exec_module(installers)--try:- dist = importlib.metadata.distribution("nunchaku")- summary = (dist.metadata.get("Summary") or "").lower()- if "piece-wise" not in summary and not dist.version.startswith("0.16"):- print(f"Nunchaku {dist.version} is already installed.")- sys.exit(0)- print(f"Replacing the unrelated PyPI package 'nunchaku' {dist.version}.")-except importlib.metadata.PackageNotFoundError:- pass--config = installers.generate_and_save_config() or installers.load_version_config()-versions = config.get("versions", [])-if not versions:- sys.exit("Could not read Nunchaku's version list.")-from packaging.version import parse-version = max(versions, key=parse)-info = installers.get_system_info()-if not info.get("torch_version"):- sys.exit("torch is not installed in this Python.")-backend = installers.get_install_backend()-for source in ("github", "huggingface", "modelscope"):- wheel = installers.construct_compatible_wheel_info(version, source, info, config)- if not wheel:- continue- try:- print(f"Installing {wheel['name']} from {source}...")- installers.install_wheel(wheel["url"], backend)- print(f"Installed Nunchaku {version}.")- sys.exit(0)- except Exception as e:- print(f" {source}: {e}")-sys.exit(f"No Nunchaku {version} wheel for Python {info['python_version']}, {info['torch_version']}, "- f"{info['platform_tag']}.")-'''---def _install_nunchaku_wheel(item_details: Dict[str, Any], comfyui_path: Path) -> Tuple[bool, str]:- repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]- installers = repo_path / "nodes" / "tools" / "installers.py"- if not installers.is_file():- return False, f"{installers} not found"- with tempfile.TemporaryDirectory() as tmp:- script = Path(tmp) / "stablegen_nunchaku_wheel.py"- script.write_text(_NUNCHAKU_WHEEL_SCRIPT, encoding="utf-8")- result = subprocess.run([find_comfyui_python(comfyui_path), str(script), str(installers)])- return result.returncode == 0, "" if result.returncode == 0 else "see the messages above"---def _install_skintokens_runtime(item_details: Dict[str, Any], comfyui_path: Path) -> Tuple[bool, str]:- repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]- script = repo_path / "install_skintokens.py"- if not script.is_file():- return False, f"{script} not found"- print(" Building the SkinTokens runtime (its own Python environment, PyTorch and checkpoints).")- print(" This takes a while the first time.")- result = subprocess.run([find_comfyui_python(comfyui_path), str(script), "--target", "managed"], cwd=str(repo_path))- return result.returncode == 0, "" if result.returncode == 0 else "see the messages above"---POST_INSTALL = {- "nunchaku_wheel": ("Nunchaku engine", _install_nunchaku_wheel),- "skintokens_runtime": ("SkinTokens runtime", _install_skintokens_runtime),-}---def install_node(item_details: Dict[str, Any], comfyui_path: Path, update_nodes: bool) -> List[Tuple[str, str, str]]:- """Clone or check a custom node, then install what it needs. Returns (name, status, message) rows."""- name = item_details["name"]- status, message = clone_git_repo(item_details, comfyui_path, update_nodes)- print(f" {status}{': ' + message if message else ''}")- rows = [(name, status, message)]- if status == "failed":- return rows- repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]- uses_env = _uses_comfy_env(item_details)- if item_details.get("pip_packages") and not install_pip_packages(item_details["pip_packages"], comfyui_path):- rows.append((f"{name}: Python packages", "failed", "pip install failed (see above)"))- # comfy-env patches go in BEFORE install.py, which needs them (e.g. the Linux platform tag for wheel lookup)- if uses_env:- _apply_all_comfy_env_patches(comfyui_path)- if item_details.get("post_clone_patches"):- apply_post_clone_patches(item_details, comfyui_path)- if item_details.get("run_install_script"):- if not run_node_install_script(item_details, comfyui_path):- rows.append((f"{name}: install.py", "failed", "the node's dependency install failed (see above)"))- _patch_flex_gemm_autotuner(repo_path)- if uses_env:- # The node's requirements.txt may pin an older comfy-env: restore the latest and re-apply the patches,- # then bring ComfyUI core's exact pins into the isolated env that install.py just solved.- print(f" Re-installing {COMFY_ENV} (overriding the node's requirements.txt)...")- install_pip_packages([COMFY_ENV], comfyui_path, force_reinstall=True)- _apply_all_comfy_env_patches(comfyui_path)- if not sync_comfy_env_core(item_details, comfyui_path):- rows.append((f"{name}: isolated environment", "warning",- "out of step with ComfyUI core; run the installer with --repair"))- hook = item_details.get("post_install")- if hook:- label, run = POST_INSTALL[hook]- ok, message = run(item_details, comfyui_path)- rows.append((f"{name}: {label}", "installed" if ok else "failed", message))- return rows---# --- Packages ----def display_menu(comfyui_path: Path):- print_header("StableGen Dependency Installer")- print(f"Target ComfyUI Directory: {comfyui_path}")- print_separator()- print("This script downloads and sets up the custom nodes and models StableGen uses.")- print("To install components by hand instead, see the manual installation guide:")- print("https://github.com/sakalond/StableGen/wiki/Manual-installation")- print_separator()- print("Download sizes are estimates. The full list of components is shown for approval before anything changes.")- print_separator()-- for key, val in MENU_PACKAGES.items():- print(f"\n{key}. {val['name']}")- print_separator(char='.')- print(f" *Approximate total download size: ~{val['size_gb']:.1f} GB*")- if val.get("description_suffix"):- print(f" {val['description_suffix']}")- print("\nq. Quit")- print_separator()---def print_package_list():- """--list: every package and the components it installs."""- for key, val in MENU_PACKAGES.items():- print(f"{key:>3}. {val['name']} (~{val['size_gb']:.1f} GB)")- for item in resolve_items([key]):- kind = {"node": "node", "model": "model", "hf_model": "model"}[item["type"]]- print(f" {kind:<5} {item['name']}")---def parse_package_choice(text: str) -> List[str]:- """'3, 8' -> ['3', '8']. Raises ValueError for unknown numbers."""- keys = [k.strip() for k in text.replace(";", ",").split(",") if k.strip()]- unknown = [k for k in keys if k not in MENU_PACKAGES]- if not keys or unknown:- raise ValueError(f"unknown package(s): {', '.join(unknown) or text!r}; choose from {', '.join(MENU_PACKAGES)}")- return list(dict.fromkeys(keys))---def tags_for(keys: List[str]) -> List[str]:- return list(dict.fromkeys(tag for key in keys for tag in MENU_PACKAGES[key]["tags"]))---def get_unique_item_ids_for_tags(selected_tags: List[str]) -> Set[str]:- return {item_id for item_id, details in DEPENDENCIES.items()- if any(tag in details["packages"] for tag in selected_tags)}---def resolve_items(keys: List[str]) -> List[Dict[str, Any]]:- """The components of the chosen packages, each once, in DEPENDENCIES order."""- ids = get_unique_item_ids_for_tags(tags_for(keys))- return [item for item_id, item in DEPENDENCIES.items() if item_id in ids]---def item_target(item: Dict[str, Any], comfyui_path: Path) -> Path:- if item["type"] == "node":- return comfyui_path / item["target_dir_relative"] / item["repo_name"]- if item["type"] == "model":- return comfyui_path / item["target_path_relative"] / item["filename"]- return comfyui_path / "models" / "diffusers" / item["local_dir"]---def item_present(item: Dict[str, Any], comfyui_path: Path) -> bool:- target = item_target(item, comfyui_path)- if item["type"] == "hf_model":- return (target / "model_index.json").exists()- return target.exists()---TAG_LABELS = {- "core": "SDXL core", "preset_essentials": "SDXL preset essentials", "extended_optional": "SDXL extras",- "checkpoint_realvis": "RealVisXL checkpoint", "qwen_core": "Qwen Image Edit core", "qwen_extras": "Qwen extras",- "qwen_nunchaku": "Qwen Nunchaku", "pbr_marigold": "Marigold IID", "pbr_stabledelight": "StableDelight",- "pbr_marigold_v2": "Marigold V2", "trellis2": "TRELLIS.2", "flux2_klein": "FLUX.2 Klein",- "qwen_image_21": "Qwen Image 2.1", "skintokens": "SkinTokens",- "qwen_image_21_turbo": "Qwen Image 2.1 Turbo", "moss_image": "MOSS Image", "fibo_edit": "FIBO 2.0 Edit",-}---def installed_tags(comfyui_path: Path) -> Tuple[List[str], Dict[str, Tuple[int, int]]]:- """For --verify without --packages: package tags with every component present, and the partly installed ones- as {tag: (present, total)}."""- complete, partial = [], {}- for tag in TAG_LABELS:- items = [item for item in DEPENDENCIES.values() if tag in item["packages"]]- present = sum(item_present(item, comfyui_path) for item in items)- if items and present == len(items):- complete.append(tag)- elif present:- partial[tag] = (present, len(items))- return complete, partial---# --- Checks before installing ----def missing_core_nodes(comfyui_path: Path, tags: List[str]) -> Dict[str, List[str]]:- """ComfyUI core nodes the packages need that this ComfyUI version does not have, by package tag."""- sources = [comfyui_path / "nodes.py"] + sorted((comfyui_path / "comfy_extras").glob("*.py"))- text = "\n".join(p.read_text(encoding="utf-8", errors="ignore") for p in sources if p.is_file())- if not text:- return {} # not a source checkout (e.g. ComfyUI Desktop): can't tell offline- missing = {}- for tag in tags:- absent = [n for n in CORE_NODES.get(tag, []) if not re.search(rf"[\"']{re.escape(n)}[\"']|class {re.escape(n)}\b", text)]- if absent:- missing[tag] = absent- return missing---ENV_SIZE_MB = {"trellis2": 5000, "skintokens": 9000}---def estimate_download_mb(items: List[Dict[str, Any]], tags: List[str], comfyui_path: Path) -> int:- """MB still to download: models that are not present yet, plus environments the nodes build."""- total = sum(item.get("size_mb", 0) for item in items- if item["type"] in ("model", "hf_model") and not item_present(item, comfyui_path))- for tag in tags:- node_items = [i for i in items if i["type"] == "node" and tag in i["packages"]]- if tag in ENV_SIZE_MB and not all(item_present(i, comfyui_path) for i in node_items):- total += ENV_SIZE_MB[tag]- return total---def trellis_python_ok(comfyui_path: Path) -> bool:- """TRELLIS.2's CUDA extensions have no wheels for Python 3.13 yet; ask before installing there."""- try:- out = subprocess.run([find_comfyui_python(comfyui_path), "-c",- "import sys; print(sys.version_info[0], sys.version_info[1])"],- capture_output=True, env=UTF8_ENV, check=True, **UTF8_TEXT)- is_313_plus = tuple(int(x) for x in out.stdout.split()) >= (3, 13)- except Exception:- is_313_plus = sys.version_info >= (3, 13)- if not is_313_plus:- return True- print_separator(char='!')- print("WARNING: TRELLIS.2 needs binary CUDA extensions (cumesh, flex_gemm, nvdiffrec, ...) that have no")- print("pre-built wheels for Python 3.13 yet; building them needs MSVC and the CUDA Toolkit.")- print("A ComfyUI with Python 3.12 (e.g. a portable build) is strongly recommended.")- print_separator(char='!')- return ask("Attempt the TRELLIS.2 installation on Python 3.13 anyway?", default_yes=False)---def show_notice(key: str) -> bool:- print_separator(char='!')- for line in LICENSE_NOTICES[key]:- print(line)- print_separator(char='!')- return ask("Acknowledge and continue?")---# --- Verification ----def _free_port() -> int:- with socket.socket() as s:- s.bind(("127.0.0.1", 0))- return s.getsockname()[1]---def _fetch_object_info(address: str, timeout: int = 15) -> Optional[Dict[str, Any]]:- try:- with urllib.request.urlopen(f"http://{address}/object_info", timeout=timeout) as response:- return json.loads(response.read().decode("utf-8"))- except Exception:- return None---def _stop_process_tree(proc: subprocess.Popen):- if proc.poll() is not None:- return- if sys.platform == "win32":- subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True)- else:- import signal- try:- os.killpg(proc.pid, signal.SIGTERM)- except OSError:- proc.terminate()- try:- proc.wait(timeout=30)- except subprocess.TimeoutExpired:- proc.kill()---def start_comfyui_for_verify(comfyui_path: Path, timeout: int) -> Tuple[Optional[Dict[str, Any]], List[str]]:- """Start ComfyUI on a free local port, read /object_info, stop it. Returns (object_info or None, custom node- folders that failed to import)."""- main_py = comfyui_path / "main.py"- if not main_py.is_file():- print(f" {main_py} not found (ComfyUI Desktop?). Start ComfyUI yourself and pass --server <address>.")- return None, []- python = find_comfyui_python(comfyui_path)- port = _free_port()- log_path = Path(tempfile.gettempdir()) / f"stablegen-verify-comfyui-{port}.log"- cmd = [python] + (["-s"] if "python_embed" in python else []) + [- str(main_py), "--listen", "127.0.0.1", "--port", str(port), "--disable-auto-launch"]- print(f" Starting ComfyUI on port {port} to read its node list (log: {log_path})...")- kwargs: Dict[str, Any] = {}- if sys.platform == "win32":- kwargs["creationflags"] = 0x00000200 | 0x08000000 # new process group, no console window- else:- kwargs["start_new_session"] = True- info = None- with open(log_path, "w", encoding="utf-8", errors="replace") as log:- proc = subprocess.Popen(cmd, cwd=str(comfyui_path), stdout=log, stderr=subprocess.STDOUT,- stdin=subprocess.DEVNULL, **kwargs)- start = time.time()- reported = 0- try:- while time.time() - start < timeout:- if proc.poll() is not None:- print(f" ComfyUI exited early (code {proc.returncode}); see the log.")- break- info = _fetch_object_info(f"127.0.0.1:{port}", timeout=5)- if info is not None:- break- elapsed = int(time.time() - start)- if elapsed - reported >= 60:- reported = elapsed- print(f" ...still starting ({elapsed} s)")- time.sleep(3)- else:- print(f" ComfyUI did not answer within {timeout} s; see the log.")- finally:- _stop_process_tree(proc)- text = log_path.read_text(encoding="utf-8", errors="replace")- failed = re.findall(r"\(IMPORT FAILED\)[^\n]*?custom_nodes[\\/]([^\\/\n]+)", text)- return info, sorted(set(failed))---def verify_installation(comfyui_path: Path, tags: List[str], server: Optional[str], timeout: int) -> bool:- print_header("Verifying the installation")- ok = True- items = [item for item in DEPENDENCIES.values() if any(t in item["packages"] for t in tags)]- for item in items:- if item["type"] == "node":- continue- target = item_target(item, comfyui_path)- if not item_present(item, comfyui_path):- print(f" MISSING {item['name']} ({target})")- ok = False- elif item["type"] == "model" and target.with_name(target.name + ".part").exists():- print(f" WARNING {item['name']}: an unfinished download is next to it")- required = list(dict.fromkeys(n for t in tags for n in PACKAGE_NODES.get(t, [])))- if not required:- return ok- if server:- info, failed = _fetch_object_info(server), []- if info is None:- print(f" Could not reach ComfyUI at {server}.")- else:- info, failed = start_comfyui_for_verify(comfyui_path, timeout)- ours = {item["repo_name"] for item in items if item["type"] == "node"}- for folder in failed:- if folder in ours:- print(f" FAILED custom node '{folder}' did not import (see the ComfyUI log)")- others = [folder for folder in failed if folder not in ours]- if others:- print(f" Note: other custom nodes failed to import (not StableGen's): {', '.join(others)}")- failed = [folder for folder in failed if folder in ours]- if info is None:- return False- missing = [n for n in required if n not in info]- for tag in tags:- absent = [n for n in PACKAGE_NODES.get(tag, []) if n in missing]- if absent:- core = set(CORE_NODES.get(tag, []))- hint = "update ComfyUI" if set(absent) <= core else "the custom node did not load"- print(f" MISSING {', '.join(absent)} ({hint})")- print(f" {len(required) - len(missing)} of {len(required)} required node types are registered.")- return ok and not missing and not failed---# --- Summary ----STATUS_LABELS = {"installed": "installed", "updated": "updated", "present": "present", "warning": "WARNING",- "failed": "FAILED"}---def print_summary(rows: List[Tuple[str, str, str]]) -> bool:- print_header("Summary")- for name, status, message in rows:- print(f" {STATUS_LABELS[status]:<10} {name}" + (f" - {message}" if message else ""))- counts = {s: sum(1 for _, st, _ in rows if st == s) for s in STATUS_LABELS}- print_separator()- print(", ".join(f"{n} {STATUS_LABELS[s].lower()}" for s, n in counts.items() if n))- return counts["failed"] == 0---# --- Main Script Logic ----def choose_packages_interactively(comfyui_path: Path) -> Optional[List[str]]:- while True:- display_menu(comfyui_path)- try:- choice = input("Enter one or more package numbers (e.g. 3 or 3,8), or q to quit: ").strip().lower()- except EOFError:- return None- if choice == 'q':- return None- try:- return parse_package_choice(choice)- except ValueError as e:- print(f"Invalid choice: {e}")---def main(argv: Optional[List[str]] = None) -> int:- global ASSUME_YES, PYTHON_OVERRIDE- args = parse_args(argv)- if args.list:- print_package_list()- return 0- ASSUME_YES = args.yes- if args.python:- if not Path(args.python).is_file():- print(f"Error: --python '{args.python}' does not exist.")- return 2- PYTHON_OVERRIDE = str(Path(args.python).resolve())- keys: Optional[List[str]] = None- if args.packages:- try:- keys = parse_package_choice(args.packages)- except ValueError as e:- print(f"Error: {e}")- return 2-- comfyui_base_path = get_comfyui_path_from_args(args)- print(f"ComfyUI: {comfyui_base_path}")- if not describe_python(comfyui_base_path) and not args.check:- if not ask("Continue with this Python?", default_yes=False):- return 1-- if args.check:- print_header("Checking TRELLIS.2 environments")- return 0 if repair_comfy_env_nodes(comfyui_base_path, check_only=True) else 1-- if args.verify and keys is None and not args.repair:- tags, partial = installed_tags(comfyui_base_path)- if partial:- print("Partly installed, not checked: " + ", ".join(- f"{TAG_LABELS[t]} ({have} of {total} components)" for t, (have, total) in partial.items()))- if not tags:- print("No StableGen package is completely installed here yet.")- return 1- print("Checking: " + ", ".join(TAG_LABELS[t] for t in tags))- return 0 if verify_installation(comfyui_base_path, tags, args.server, args.verify_timeout) else 1-- if not args.dry_run:- # Ensure all comfy-env patches are applied if comfy-env is already installed- has_comfy_env = False- try:- result = subprocess.run([find_comfyui_python(comfyui_base_path), "-c", "import comfy_env"],- capture_output=True, env=UTF8_ENV, **UTF8_TEXT)- if result.returncode == 0:- has_comfy_env = True- print(" Detected existing comfy-env installation. Ensuring all patches are applied...")- _apply_all_comfy_env_patches(comfyui_base_path)- except Exception as e:- print(f" WARNING: Could not check/patch existing comfy-env: {e}")-- # Already-installed TRELLIS.2 nodes drift out of step whenever ComfyUI or the node updates; repair them- # on every installer run.- if has_comfy_env or args.repair:- print_header("Repairing installed TRELLIS.2 nodes")- ok = repair_comfy_env_nodes(comfyui_base_path)- if args.repair:- print("Repair complete." if ok else "Repair finished with warnings (see above).")- print("Restart ComfyUI so the TRELLIS.2 worker picks up the changes.")- return 0 if ok else 1- elif args.repair:- print("--repair changes files; nothing to show in a dry run.")- return 0-- if keys is None:- keys = choose_packages_interactively(comfyui_base_path)- if keys is None:- print("Exiting installer.")- return 0-- # License notices and the Python 3.13 check can drop packages- accepted = []- answers: Dict[str, bool] = {} # a notice shared by two packages (Qwen 2.1 and Turbo) is asked once- for key in keys:- package = MENU_PACKAGES[key]- if "trellis2" in package["tags"] and not trellis_python_ok(comfyui_base_path):- print(f"Skipping package {key}.")- continue- notice = package.get("notice")- if notice and notice not in answers:- answers[notice] = show_notice(notice)- if notice and not answers[notice]:- print(f"Skipping package {key}.")- continue- accepted.append(key)- if not accepted:- print("Nothing to install.")- return 0- tags = tags_for(accepted)- items = resolve_items(accepted)-- print_separator()- for key in accepted:- print(f"Package {key}: {MENU_PACKAGES[key]['name']}")- print("Components:")- for item in items:- state = "present" if item_present(item, comfyui_base_path) else "to install"- print(f" - {item['name']} ({state})")- need_mb = estimate_download_mb(items, tags, comfyui_base_path)- free_mb = shutil.disk_usage(comfyui_base_path).free // 1024**2- print(f"Estimated download: ~{need_mb / 1024:.1f} GB; free on this drive: {free_mb / 1024:.1f} GB")-- problems = False- for tag, absent in missing_core_nodes(comfyui_base_path, tags).items():- print(f"WARNING: this ComfyUI lacks {', '.join(absent)}; update ComfyUI before using these models.")- if any(item["type"] == "node" for item in items) and shutil.which("git") is None:- print("ERROR: Git is needed to install custom nodes and was not found on PATH (https://git-scm.com).")- problems = True- if need_mb > free_mb:- print(f"ERROR: not enough free disk space ({need_mb / 1024:.1f} GB needed, {free_mb / 1024:.1f} GB free).")- problems = problems or not ask("Continue anyway?", default_yes=False, yes_answers=False)- if problems:- return 1-- if args.dry_run:- print("Dry run: nothing was changed.")- if args.verify:- return 0 if verify_installation(comfyui_base_path, tags, args.server, args.verify_timeout) else 1- return 0- if not ask("Proceed with checking/installing these components?"):- print("Installation cancelled.")- return 0-- rows: List[Tuple[str, str, str]] = []- for item_details in items:- print_separator(char='.')- print(f"Processing: {item_details['name']}")- if item_details["type"] == "node":- rows.extend(install_node(item_details, comfyui_base_path, args.update_nodes))- elif item_details["type"] == "model":- rows.append((item_details["name"],) + download_file(item_details, comfyui_base_path, args.verify_hashes))- elif item_details["type"] == "hf_model":- status, message = download_hf_model(item_details, comfyui_base_path, args.verify_hashes)- print(f" {status}{': ' + message if message else ''}")- rows.append((item_details["name"], status, message))-- ok = print_summary(rows)- node_names = {item["name"] for item in items if item["type"] == "node"}- if any(status in ("installed", "updated") and name in node_names for name, status, _ in rows):- print("Restart ComfyUI so it loads new or updated custom nodes.")- if args.verify:- ok = verify_installation(comfyui_base_path, tags, args.server, args.verify_timeout) and ok- return 0 if ok else 1-+INSTALLER = Path(__file__).resolve().parent / "stablegen" / "setup" / "installer.py"+URL = "https://raw.githubusercontent.com/sakalond/StableGen/main/stablegen/setup/installer.py"-if __name__ == "__main__":- if not TQDM_AVAILABLE:- print("NOTE: 'tqdm' is not installed, so downloads show a progress line instead of a bar.")- sys.exit(main())+if not INSTALLER.is_file():+ sys.exit(f"The StableGen installer moved. Download it on its own from\n {URL}\nand run that file instead.")+sys.argv[0] = str(INSTALLER)+runpy.run_path(str(INSTALLER), run_name="__main__")diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex 3ae2f99..a61ea11 100644--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -51,7 +51,7 @@ from .cameras import ()from .debug_tools import debug_classes as _debug_classesfrom .cameras import display as camera_display-from .core import server_monitor+from .core import server_monitor, state as core_statefrom .texturing.regression import REGRESSION_CLASSESfrom .texturing import masked_editfrom .utils import AddHDRI, ApplyModifiers, CurvesToMesh@@ -62,12 +62,16 @@ from .mesh_gen.trellis2 import (Trellis2Generate, StableGenApplyBoneDisplay,StableGenAutoRigSelectedMesh, StableGenLocalPostProcess,)+from .mesh_gen.meshtools import StableGenLato2Remeshfrom .mesh_gen.batch import (TRELLIS2_OT_BatchSelectFolder, TRELLIS2_OT_BatchGenerate,TRELLIS2_OT_BatchCancel, TRELLIS2_OT_BatchClear,TRELLIS2_OT_BatchBakeSettings,)from .dae_import import DAE_IMPORT_CLASSES+from .setup import runtime as setup_runtime+from .setup.operators import SETUP_CLASSES+from .ui.studio_setup import CLASSES as STUDIO_SETUP_CLASSES# -- Core / UI sub-packages ----------------------------------------------from .core.preferences import (@@ -202,6 +206,8 @@ classes.extend(REGRESSION_CLASSES)classes.extend(masked_edit.MASKED_EDIT_CLASSES)classes.extend(STUDIO_UI_CLASSES)classes.extend(camera_display.CLASSES)+classes.extend(SETUP_CLASSES)+classes.extend(STUDIO_SETUP_CLASSES)def register():@@ -221,11 +227,15 @@ def register():)register_studio_ui()camera_display.register()+ core_state.register()server_monitor.register()+ setup_runtime.register()def unregister():+ setup_runtime.unregister()server_monitor.unregister()+ core_state.unregister()camera_display.unregister()unregister_studio_ui()masked_edit.unregister_properties()diff --git a/stablegen/blender_manifest.toml b/stablegen/blender_manifest.tomlindex a7ffd48..64ffd3a 100644--- a/stablegen/blender_manifest.toml+++ b/stablegen/blender_manifest.toml@@ -47,5 +47,5 @@ wheels = [][permissions]-network = "Connects to a local ComfyUI server for AI generation"-files = "Saves generated textures, 3D meshes, PBR maps, and exported GIFs"+network = "Connects to ComfyUI for AI generation, and downloads ComfyUI, Python packages and models when you install them"+files = "Saves generated textures, 3D meshes, PBR maps and exported GIFs, and installs ComfyUI and models into the folders you choose"diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.pyindex b2a1ddb..4b38b48 100644--- a/stablegen/core/preferences.py+++ b/stablegen/core/preferences.py@@ -63,6 +63,37 @@ def _redraw_sidebars(self, context):area.tag_redraw()+def _comfy_setting_changed(self, context):+ """Blender saves its preferences on quit only when they are marked changed, which a change from Python (the+ StableGen panel's Setup page, a folder picker) is not; StableGen's setup choices must survive a restart."""+ context.preferences.is_dirty = True+++def _comfy_mode_changed(self, context):+ from ..setup import runtime+ _comfy_setting_changed(self, context)+ folder = runtime.comfy_folder(self)+ if folder is not None and runtime.report(folder) is None:+ runtime.refresh_status(folder)+ runtime.follow_folder(self) # the running ComfyUI is for the folder chosen before+ runtime.redraw()+++def _comfy_folder_changed(self, context):+ from ..setup import runtime+ _comfy_setting_changed(self, context)+ folder = runtime.comfy_folder(self)+ if folder is not None:+ runtime.refresh_status(folder)+ runtime.follow_folder(self)+++def _comfy_keep_running_changed(self, context):+ from ..setup import runtime+ _comfy_setting_changed(self, context)+ runtime.keep_running = self.comfy_keep_running++class StableGenAddonPreferences(bpy.types.AddonPreferences):"""Preferences for the StableGen addon."""bl_idname = ADDON_PKG@@ -214,12 +245,72 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):update=update_parameters) # type: ignore+ # ── ComfyUI setup (stablegen/setup) ──+ comfy_mode: bpy.props.EnumProperty(+ name="ComfyUI",+ description="Where StableGen's ComfyUI comes from",+ items=[+ ('OWN', "StableGen's own", "StableGen installs, starts and stops its own ComfyUI", 'PACKAGE', 0),+ ('LOCAL', "My ComfyUI folder", "A ComfyUI on this computer: StableGen installs models into it and "+ "starts and stops it", 'FILE_FOLDER', 1),+ ('REMOTE', "Remote server", "A ComfyUI running elsewhere (another machine, a cloud GPU), at the server "+ "address", 'WORLD', 2),+ ],+ default='REMOTE',+ update=_comfy_mode_changed,+ ) # type: ignore++ comfy_root: bpy.props.StringProperty(+ name="Install folder",+ description="Where StableGen keeps its own ComfyUI: about 5 GB, plus the models you install",+ default="",+ subtype='DIR_PATH',+ update=_comfy_folder_changed,+ ) # type: ignore++ comfy_local_path: bpy.props.StringProperty(+ name="ComfyUI folder",+ description="Your ComfyUI folder (the one with 'models' and 'custom_nodes'; for a portable build, the folder "+ "that contains it works too)",+ default="",+ subtype='DIR_PATH',+ update=_comfy_folder_changed,+ ) # type: ignore++ comfy_port: bpy.props.IntProperty(+ name="Port",+ description="Port StableGen starts ComfyUI on; when another program uses it, the next free one is taken",+ default=8188, min=1024, max=65500,+ update=_comfy_setting_changed,+ ) # type: ignore++ comfy_extra_args: bpy.props.StringProperty(+ name="Extra arguments",+ description="Added to ComfyUI's command line, for example --lowvram",+ default="",+ update=_comfy_setting_changed,+ ) # type: ignore++ comfy_auto_start: bpy.props.BoolProperty(+ name="Start when StableGen needs it",+ description="Start ComfyUI in the background when the StableGen sidebar opens or a generation needs it",+ default=True,+ update=_comfy_setting_changed,+ ) # type: ignore++ comfy_keep_running: bpy.props.BoolProperty(+ name="Keep running after Blender closes",+ description="Leave ComfyUI running when Blender quits; the next Blender uses it again",+ default=False,+ update=_comfy_keep_running_changed,+ ) # type: ignore+def draw(self, context):+ from ..setup import prefs_uilayout = self.layout+ prefs_ui.draw(self, layout, context)+ layout.separator()layout.prop(self, "output_dir")- row = layout.row(align=True)- row.prop(self, "server_address")- row.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')row = layout.row()row.prop(self, "use_legacy_panel")diff --git a/stablegen/core/server_api.py b/stablegen/core/server_api.pyindex 99879bc..ed3c559 100644--- a/stablegen/core/server_api.py+++ b/stablegen/core/server_api.py@@ -62,7 +62,9 @@ def confirm_server(operator, context):prefs.server_online = Truereturn Trueprefs.server_online = False- operator.report({'ERROR'}, offline_message(prefs.server_address))+ from ..setup import runtime+ note = runtime.offline_note() # the local ComfyUI is starting, or starts now+ operator.report({'WARNING'} if note else {'ERROR'}, note or offline_message(prefs.server_address))return Falsediff --git a/stablegen/core/server_monitor.py b/stablegen/core/server_monitor.pyindex 96741bc..c981166 100644--- a/stablegen/core/server_monitor.py+++ b/stablegen/core/server_monitor.py@@ -75,6 +75,9 @@ def _tick():if (_in_flight or wrapper is None or not wrapper.preferences.server_addressor not bpy.app.online_access or not _sidebar_open(context) or _busy(context)):return INTERVAL+ from ..setup import runtime+ if runtime.maybe_autostart(): # the sidebar needs the local ComfyUI StableGen runs+ return INTERVALaddress, timeout = wrapper.preferences.server_address, get_timeout('ping')_in_flight = True_run_async(lambda: check_server_availability(address, timeout=timeout),diff --git a/stablegen/core/state.py b/stablegen/core/state.pyindex f520a49..70a5522 100644--- a/stablegen/core/state.py+++ b/stablegen/core/state.py@@ -10,6 +10,7 @@ import time as _time_modimport traceback as _tracebackimport bpy # pylint: disable=import-error+from bpy.app.handlers import persistent# ── Model-list caches (populated by refresh operators) ────────────────────@@ -63,6 +64,24 @@ def _dec_pending_refreshes():# Monotonically incrementing token so we can discard stale results when the# server address changes while a request is still in-flight._async_generation = 0+# Counts opened files: a result asked for before one opened is stale too.+_load_generation = 0+++@persistent+def _file_loading(*_args):+ global _load_generation+ _load_generation += 1+++def register():+ if _file_loading not in bpy.app.handlers.load_pre:+ bpy.app.handlers.load_pre.append(_file_loading)+++def unregister():+ if _file_loading in bpy.app.handlers.load_pre:+ bpy.app.handlers.load_pre.remove(_file_loading)def _run_async(work_fn, done_fn, poll_interval=0.25, track_generation=False):@@ -79,11 +98,16 @@ def _run_async(work_fn, done_fn, poll_interval=0.25, track_generation=False):only for server-address-change callbacks where stale results must bedropped; refresh operators should leave it False so their results arenever accidentally discarded.++ A result that finishes after another file was opened is always stale:+ *done_fn* gets None, so it still clears its flags (the server check,+ the pending-refresh count) without applying the old file's data."""global _async_generationif track_generation:_async_generation += 1gen = _async_generation+ load_gen = _load_generationcontainer = {} # mutable box for the thread to deposit its result@@ -98,8 +122,8 @@ def _run_async(work_fn, done_fn, poll_interval=0.25, track_generation=False):t.start()def _poll():- # Discard result if the server address changed after we started.- if gen != _async_generation:+ # Discard result if the server address changed, or a file was opened, after we started.+ if gen != _async_generation or load_gen != _load_generation:# Still call done_fn so it can clean up (e.g. decrement# _pending_refreshes). Pass None to signal stale/no result.try:@@ -115,4 +139,5 @@ def _run_async(work_fn, done_fn, poll_interval=0.25, track_generation=False):_traceback.print_exc()return None # done- bpy.app.timers.register(_poll, first_interval=poll_interval)+ # Persistent: opening a file would otherwise drop the timer, and done_fn's clean-up with it.+ bpy.app.timers.register(_poll, first_interval=poll_interval, persistent=True)diff --git a/stablegen/setup/__init__.py b/stablegen/setup/__init__.pynew file mode 100644index 0000000..f0b4de6--- /dev/null+++ b/stablegen/setup/__init__.py@@ -0,0 +1 @@+"""Setting up ComfyUI from Blender: the installer (also a standalone CLI), the ComfyUI process and the setup UI."""diff --git a/stablegen/setup/comfy_process.py b/stablegen/setup/comfy_process.pynew file mode 100644index 0000000..1f2ccd2--- /dev/null+++ b/stablegen/setup/comfy_process.py@@ -0,0 +1,332 @@+"""The local ComfyUI StableGen starts, adopts and stops (the Own and Local server modes).++One ComfyUI per Blender: started hidden on 127.0.0.1, logged to <state>/logs/comfyui.log and recorded in+<state>/comfyui.json, so the next Blender adopts it (after a crash, or when "keep running" is on) instead of+starting a second copy. A ComfyUI that answers for the same folder is adopted, a server for another folder is left+alone and the next free port is used. StableGen only ever stops a ComfyUI it started.++No bpy here: the add-on drives it from timers and operators, and the tests run it with a fake ComfyUI.+"""+import json+import os+import socket+import subprocess+import sys+import threading+import time+import urllib.request+from pathlib import Path+from typing import List, Optional, Sequence, Tuple++from . import installer++READY_TIMEOUT = 15 * 60 # the first start after installing nodes can take minutes+PORT_SPAN = 20 # ports tried after the preferred one+LOGS_KEPT = 3+++# --- Looking at servers and processes ---+def _get_json(address: str, path: str, timeout: float):+ with urllib.request.urlopen(f"http://{address}{path}", timeout=timeout) as response:+ return json.loads(response.read().decode("utf-8"))+++def answers(address: str, timeout: float = 2.0) -> bool:+ """A ComfyUI answers at this address."""+ try:+ return "system" in _get_json(address, "/system_stats", timeout)+ except Exception:+ return False+++def server_folder(address: str, timeout: float = 2.0) -> Optional[Path]:+ """The ComfyUI folder a server runs from, or None when no ComfyUI answers there."""+ try:+ paths = _get_json(address, "/internal/folder_paths", timeout)+ except Exception:+ return None+ nodes = paths.get("custom_nodes") or []+ if nodes and isinstance(nodes[0], list): # [[paths], [extensions]] in some versions+ nodes = nodes[0]+ return Path(nodes[0]).parent if nodes else None+++def same_folder(a, b) -> bool:+ return os.path.normcase(os.path.realpath(str(a))) == os.path.normcase(os.path.realpath(str(b)))+++def port_free(port: int) -> bool:+ with socket.socket() as s:+ try:+ s.bind(("127.0.0.1", port))+ except OSError:+ return False+ return True+++def choose_port(preferred: int, folder: Path) -> Tuple[int, bool]:+ """(port, adopt): the port a ComfyUI for this folder already answers on, else the first free one."""+ for port in range(preferred, preferred + PORT_SPAN):+ found = server_folder(f"127.0.0.1:{port}")+ if found is not None and same_folder(found, folder):+ return port, True+ if found is None and port_free(port):+ return port, False+ raise RuntimeError(f"no free port between {preferred} and {preferred + PORT_SPAN - 1}")+++def pid_alive(pid: Optional[int]) -> bool:+ if not pid:+ return False+ if sys.platform == "win32":+ import ctypes+ kernel32 = ctypes.windll.kernel32+ handle = kernel32.OpenProcess(0x1000, False, int(pid)) # PROCESS_QUERY_LIMITED_INFORMATION+ if not handle:+ return False+ try:+ code = ctypes.c_ulong()+ return bool(kernel32.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == 259+ finally:+ kernel32.CloseHandle(handle)+ try:+ os.kill(int(pid), 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ return True+++def stop_pid_tree(pid: int, timeout: float = 30.0):+ """Stop a process StableGen started in an earlier session, with its children."""+ if sys.platform == "win32":+ subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)], capture_output=True)+ else:+ import signal+ for sig in (signal.SIGTERM, signal.SIGKILL):+ try:+ os.killpg(int(pid), sig)+ except OSError:+ return+ end = time.time() + timeout+ while time.time() < end and pid_alive(pid):+ time.sleep(0.2)+ if not pid_alive(pid):+ return+++def comfyui_python(folder: Path) -> Optional[str]:+ """ComfyUI's own Python for this folder (portable build, venv, .venv), never Blender's."""+ for candidate in installer.python_candidates(Path(folder)):+ if candidate.is_file():+ return str(candidate)+ return None+++_default_python: List[Optional[str]] = [] # looked up once: [path or None]+++def default_python() -> Optional[str]:+ """The Python a terminal runs as 'python' (else 'python3', else the py launcher's), as its real executable, for+ a ComfyUI that has no Python of its own: a pyenv shim or a launcher resolves to the interpreter behind it. Never+ the Microsoft Store placeholder, and never Blender's own Python."""+ if _default_python:+ return _default_python[0]+ import shutil+ commands = [[found] for found in map(shutil.which, ("python", "python3"))+ if found and "windowsapps" not in found.lower()]+ if sys.platform == "win32" and shutil.which("py"):+ commands.append([shutil.which("py"), "-3"])+ env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "PYTHONPATH")}+ hidden = {"creationflags": 0x08000000} if sys.platform == "win32" else {} # no console window+ found = None+ for command in commands:+ try:+ out = subprocess.run(command + ["-c", "import sys; print(sys.executable)"], capture_output=True, text=True,+ stdin=subprocess.DEVNULL, env=env, timeout=30, **hidden)+ except (OSError, subprocess.TimeoutExpired):+ continue+ lines = out.stdout.strip().splitlines() if out.returncode == 0 else []+ blenders = "bpy" in sys.modules and same_folder(lines[-1], sys.executable) if lines else False+ if lines and Path(lines[-1]).is_file() and not blenders:+ found = lines[-1]+ break+ _default_python.append(found)+ return found+++def python_for(folder: Path) -> Tuple[Optional[str], bool]:+ """(the Python to run this ComfyUI with, whether it is the default one rather than the folder's own)."""+ own = comfyui_python(folder)+ return (own, False) if own else (default_python(), True)+++# --- The process ---+class LocalComfyUI:+ """State: 'stopped', 'starting', 'running', 'exited' (it stopped or never answered; see message) or+ 'unresponsive' (a recorded process that is alive but no longer answers)."""++ def __init__(self, state_dir):+ self.state_dir = Path(state_dir)+ self.record_path = self.state_dir / "comfyui.json"+ self.log_path = self.state_dir / "logs" / "comfyui.log"+ self.proc: Optional[subprocess.Popen] = None # started in this session+ self.pid: Optional[int] = None # started by StableGen (this session or an earlier one)+ self.port: Optional[int] = None+ self.folder: Optional[Path] = None+ self.state = "stopped"+ self.message = ""+ self.started_at = 0.0+ self._watch: Optional[threading.Thread] = None++ @property+ def address(self) -> str:+ return f"127.0.0.1:{self.port}" if self.port else ""++ @property+ def owned(self) -> bool:+ """StableGen started it, so StableGen may stop it."""+ return self.proc is not None or self.pid is not None++ def start(self, folder, port: int = 8188, extra_args: Sequence[str] = (), env: Optional[dict] = None,+ python: Optional[str] = None) -> str:+ """Start ComfyUI for folder, or adopt the one already answering for it. Returns the address at once;+ a thread watches until it answers (state 'running') or exits."""+ folder = Path(folder)+ if self.state in ("starting", "running") and self.folder and same_folder(self.folder, folder):+ return self.address+ if self.state in ("starting", "running", "unresponsive"):+ self.stop() # the one for another folder: stopped if StableGen started it, else let go+ if not (folder / "main.py").is_file():+ raise RuntimeError(f"{folder} has no main.py, so StableGen cannot start it")+ python = python or python_for(folder)[0]+ if not python:+ raise RuntimeError(f"No Python for {folder}: it has none of its own (python_embeded, venv or .venv) and "+ f"there is no python on PATH")+ port, adopt = choose_port(port, folder)+ if adopt:+ self._adopt(port, folder)+ return self.address+ cmd = [python] + (["-s"] if "python_embed" in python else []) + [+ str(folder / "main.py"), "--listen", "127.0.0.1", "--port", str(port), "--disable-auto-launch",+ *extra_args]+ child_env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8", **(env or {}))+ for name in ("PYTHONHOME", "PYTHONPATH"): # Blender's own Python must not leak into ComfyUI's+ child_env.pop(name, None)+ kwargs = ({"creationflags": 0x00000200 | 0x08000000} if sys.platform == "win32" # new group, no window+ else {"start_new_session": True})+ self._rotate_logs()+ with open(self.log_path, "w", encoding="utf-8", errors="replace") as log:+ log.write(f"$ {' '.join(cmd)}\n")+ log.flush()+ self.proc = subprocess.Popen(cmd, cwd=str(folder), stdout=log, stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL, env=child_env, **kwargs)+ self.pid, self.port, self.folder = self.proc.pid, port, folder+ self.state, self.message, self.started_at = "starting", "", time.time()+ self._write_record()+ self._watch = threading.Thread(target=self._watch_ready, daemon=True)+ self._watch.start()+ return self.address++ def _watch_ready(self):+ proc = self.proc+ while self.proc is proc and time.time() - self.started_at < READY_TIMEOUT:+ if proc.poll() is not None:+ self._exited(f"ComfyUI stopped (exit code {proc.returncode})")+ return+ if answers(self.address):+ self.state = "running"+ return+ time.sleep(1.0)+ if self.proc is proc and self.state == "starting":+ self.stop()+ self.state, self.message = "exited", f"ComfyUI did not answer within {READY_TIMEOUT // 60} min"++ def _exited(self, message: str):+ self.state, self.message = "exited", message+ self.proc, self.pid = None, None+ self._clear_record()++ def _adopt(self, port: int, folder: Path):+ """A ComfyUI for this folder already answers on port. Ours if the record says so; one started by hand is+ used but never stopped."""+ record = self._read_record()+ ours = record and record.get("port") == port and same_folder(record.get("folder", ""), folder)+ self.proc = None+ self.pid = record["pid"] if ours and pid_alive(record.get("pid")) else None+ self.port, self.folder = port, folder+ self.state, self.message = "running", "" if self.pid else "started outside StableGen"++ def adopt_recorded(self) -> bool:+ """After Blender restarts: take over the ComfyUI an earlier session started, if it still runs."""+ record = self._read_record()+ if not record:+ return False+ if not pid_alive(record.get("pid")):+ self._clear_record()+ return False+ self.pid, self.port, self.folder = record["pid"], record["port"], Path(record["folder"])+ found = server_folder(self.address)+ if found is not None and same_folder(found, self.folder):+ self.state, self.message = "running", ""+ return True+ self.state, self.message = "unresponsive", "an earlier ComfyUI is still running but does not answer"+ return False++ def poll(self) -> str:+ """Notice a ComfyUI that stopped by itself (call from a timer)."""+ if self.state == "running":+ if self.proc is not None and self.proc.poll() is not None:+ self._exited(f"ComfyUI stopped (exit code {self.proc.returncode})")+ elif self.proc is None and self.pid and not pid_alive(self.pid):+ self._exited("ComfyUI stopped")+ elif self.proc is None and not self.pid and not answers(self.address):+ self.state, self.message = "stopped", "" # the one started by hand went away+ return self.state++ def stop(self):+ """Stop the ComfyUI StableGen started; one started outside StableGen is only let go."""+ if self.proc is not None:+ installer._stop_process_tree(self.proc)+ elif self.pid and pid_alive(self.pid):+ stop_pid_tree(self.pid)+ self.proc, self.pid = None, None+ self.state, self.message = "stopped", ""+ self._clear_record()++ def tail_log(self, lines: int = 12) -> List[str]:+ try:+ text = self.log_path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return []+ return [line for line in text.splitlines() if line.strip()][-lines:]++ # --- the record and logs ---+ def _read_record(self) -> Optional[dict]:+ try:+ return json.loads(self.record_path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None++ def _write_record(self):+ self.state_dir.mkdir(parents=True, exist_ok=True)+ self.record_path.write_text(json.dumps({"pid": self.pid, "port": self.port, "folder": str(self.folder),+ "started": self.started_at}), encoding="utf-8")++ def _clear_record(self):+ try:+ self.record_path.unlink()+ except OSError:+ pass++ def _rotate_logs(self):+ self.log_path.parent.mkdir(parents=True, exist_ok=True)+ for i in range(LOGS_KEPT - 1, 0, -1):+ older = self.log_path.with_name(f"comfyui.{i}.log")+ newer = self.log_path if i == 1 else self.log_path.with_name(f"comfyui.{i - 1}.log")+ if newer.exists():+ try:+ os.replace(newer, older)+ except OSError:+ passdiff --git a/stablegen/setup/installer.py b/stablegen/setup/installer.pynew file mode 100644index 0000000..8472e8c--- /dev/null+++ b/stablegen/setup/installer.py@@ -0,0 +1,2436 @@+#!/usr/bin/env python3+"""StableGen dependency installer: custom nodes and models for a ComfyUI server.++ python installer.py <ComfyUI folder> menu+ python installer.py <ComfyUI folder> --packages 3,8 --yes unattended+ python installer.py --list what each package installs++Needs only Python 3.8+ and Git (for custom nodes). `tqdm`, when installed, draws progress bars. The StableGen+add-on ships this file and runs it from Blender; it stays a single file so it can be downloaded on its own.++Machine-readable modes (used by the add-on; nothing asks a question in them):++ --status --json one JSON document: ComfyUI's Python, GPU, Git, and the state of every package+ --plan --json one JSON document: what installing --packages would add and change (nothing is changed)+ --events JSON lines on stdout, each prefixed '@sg ', while installing; --log FILE takes every other+ line (this script's messages and pip, git and install.py output)++Events, each {"event": <kind>, ...}:+ plan packages, items [{id, name, type, size_mb, present}], download_mb, free_mb+ item id, name, phase ('start' or 'done'); on done also status and rows [{name, status, message}]+ progress id, file, done, total (bytes; at most twice a second per file)+ error code ('args', 'path', 'python', 'git_missing', 'disk_space', 'notice'), message, plus details+ verify ok, missing_files, missing_nodes, import_failed+ summary ok, rows [{name, status, message}], restart (custom nodes changed), dry_run+Statuses are 'installed', 'updated', 'present', 'warning' and 'failed'. License notices are accepted up front+with --accept-notices (keys of LICENSE_NOTICES).+"""+import os+import sys+import argparse+import fnmatch+import hashlib+import json+import socket+import subprocess+import tempfile+import time+import re+import shutil+import urllib.error+import urllib.parse+import urllib.request+from pathlib import Path+from typing import Dict, List, Set, Any, Optional, Tuple++try:+ from tqdm.auto import tqdm+ TQDM_AVAILABLE = True+except ImportError:+ TQDM_AVAILABLE = False++# Captured subprocess output is read as UTF-8 and child Pythons are asked to write+# it: the console codepage (cp1251 on a Russian Windows) cannot decode what pip, git+# and a Python print for a non-ASCII path, and the reader thread's crash lost the+# output (#115).+UTF8_TEXT = dict(text=True, encoding="utf-8", errors="replace")+UTF8_ENV = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1")++# --- StableGen's TRELLIS.2 voxel budget node ---+# ComfyUI's native Trellis2UpsampleStage has no voxel budget yet (Comfy-Org/ComfyUI#17445); the original pipeline+# lowers the 1536 cascade until the upsampled shape fits max_num_tokens. The installer writes this node into+# custom_nodes (no Git needed) and StableGen wires its output into the upsample stage's target_resolution.+_TRELLIS2_BUDGET_NODE = r'''"""StableGen's voxel budget for ComfyUI's native TRELLIS.2 cascade (written by the StableGen installer).++The original TRELLIS.2 pipeline lowers the cascade resolution until the upsampled shape stays under a voxel budget+(max_num_tokens). ComfyUI's native Trellis2UpsampleStage has no budget yet, so StableGen wires this node's+resolution into its target_resolution. If the native helpers it reuses change, it passes the target through.+"""+import logging++from comfy_api.latest import ComfyExtension, IO+++class Trellis2TokenBudget(IO.ComfyNode):+ @classmethod+ def define_schema(cls):+ return IO.Schema(+ node_id="StableGenTrellis2TokenBudget",+ display_name="TRELLIS.2 Voxel Budget (StableGen)",+ category="model/conditioning/trellis",+ inputs=[+ IO.Latent.Input("shape_latent", tooltip="The 512 shape latent, as for Trellis2UpsampleStage."),+ IO.Vae.Input("vae"),+ IO.Int.Input("target_resolution", default=1536, min=1024, max=2048, step=128),+ IO.Int.Input("max_tokens", default=49152, min=16384, max=262144, step=4096,+ tooltip="Sparse-voxel budget of the high-resolution pass (TRELLIS.2's max_num_tokens)."),+ IO.Conditioning.Input("positive", optional=True,+ tooltip="Only for Pixal3D, whose coordinates quantize differently."),+ ],+ outputs=[IO.Int.Output(display_name="resolution"), IO.Int.Output(display_name="tokens")],+ hidden=[IO.Hidden.unique_id],+ )++ @classmethod+ def execute(cls, shape_latent, vae, target_resolution, max_tokens, positive=None):+ try:+ resolution, tokens = _budget(shape_latent, vae, target_resolution, max_tokens, positive)+ except Exception as e: # the native helpers moved: run without a budget rather than fail the job+ logging.warning(f"[StableGen] TRELLIS.2 voxel budget unavailable ({e}); using {target_resolution}")+ return IO.NodeOutput(target_resolution, 0)+ note = (f"{target_resolution} -> {resolution}: {tokens:,} voxels" if resolution != target_resolution+ else f"{resolution}: {tokens:,} voxels")+ logging.info(f"[StableGen] TRELLIS.2 voxel budget {note}")+ if cls.hidden.unique_id:+ from server import PromptServer+ PromptServer.instance.send_progress_text(note, cls.hidden.unique_id)+ return IO.NodeOutput(resolution, tokens)+++def _budget(shape_latent, vae, target_resolution, max_tokens, positive):+ import comfy.model_management+ from comfy_extras import nodes_trellis2 as T+ device = comfy.model_management.get_torch_device()+ vae.prepare_decode(shape_latent["samples"].shape)+ pixal3d = positive is not None and T._proj_pack_from_conditioning(positive) is not None+ items = T.split_batched_sparse_latent(shape_latent["samples"], shape_latent["coords"],+ shape_latent.get("coord_counts"))+ hr = []+ for feats, coords in items: # the same upsample Trellis2UpsampleStage runs, once+ coords = coords.to(device).clone()+ coords[:, 0] = 0+ slat = T.shape_norm(feats.to(device), coords)+ hr.append(vae.first_stage_model.upsample_shape(slat.to(vae.vae_dtype), upsample_times=4))+ resolution = target_resolution+ while True: # TRELLIS.2's loop: cheap, it only re-quantizes the same points+ tokens = max(T.Trellis2UpsampleStage._quantize_unique(c, 512, resolution, pixal3d).shape[0] for c in hr)+ if tokens < max_tokens or resolution <= 1024:+ return resolution, tokens+ resolution -= 128+++class StableGenTrellis2Extension(ComfyExtension):+ async def get_node_list(self):+ return [Trellis2TokenBudget]+++async def comfy_entrypoint():+ return StableGenTrellis2Extension()+'''++# --- Configuration: Dependencies Data ---+# Sizes are in MB. Every custom node is pinned to a commit StableGen was tested with ("commit"). A fresh clone+# checks out that commit. An existing clone at another commit is left alone with a note, unless the node sets+# "enforce_pin" (StableGen's patches depend on that exact code) or the installer runs with --update-nodes.+# "embedded_node" items are small nodes whose source is in this file; they are written, not cloned.+DEPENDENCIES: Dict[str, Dict[str, Any]] = {+ # --- Custom Nodes ---+ "cn_ipadapter_plus": {+ "id": "cn_ipadapter_plus", "type": "node", "name": "ComfyUI IPAdapter Plus",+ "git_url": "https://github.com/cubiq/ComfyUI_IPAdapter_plus.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI_IPAdapter_plus",+ "commit": "a0f451a5113cf9becb0847b92884cb10cbdec0ef",+ "license": "GPL-3.0", "packages": ["core"]+ },+ # --- Models ---+ # Core Models+ "model_ipadapter_plus_sdxl_vit_h": {+ "id": "model_ipadapter_plus_sdxl_vit_h", "type": "model", "name": "IPAdapter Plus SDXL ViT-H",+ "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors?download=true",+ "target_path_relative": "models/ipadapter", "filename": "ip-adapter-plus_sdxl_vit-h.safetensors",+ "license": "Apache 2.0", "size_mb": 850, "packages": ["core"]+ },+ "model_clip_vision_h": {+ "id": "model_clip_vision_h", "type": "model", "name": "IPAdapter CLIP Vision ViT-H",+ "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors",+ "target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors",+ "rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["core"]+ },+ "model_clip_vision_g": {+ "id": "model_clip_vision_g", "type": "model", "name": "IPAdapter CLIP Vision ViT-G",+ "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors",+ "target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors",+ "rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 3500, "packages": ["core"]+ },+ "lora_sdxl_lightning_8step": {+ "id": "lora_sdxl_lightning_8step", "type": "model", "name": "SDXL Lightning 8-Step LoRA",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_8step_lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "sdxl_lightning_8step_lora.safetensors",+ "license": "OpenRAIL++", "size_mb": 400, "packages": ["core"]+ },+ # Preset Essentials+ "controlnet_depth_sdxl_preset": {+ "id": "controlnet_depth_sdxl_preset", "type": "model", "name": "ControlNet Depth SDXL (for presets)",+ "url": "https://huggingface.co/xinsir/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.safetensors?download=true",+ "target_path_relative": "models/controlnet", "filename": "controlnet_depth_sdxl.safetensors",+ "rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["preset_essentials"]+ },+ # Extended SDXL Optional Models+ "lora_sdxl_lightning_4step": {+ "id": "lora_sdxl_lightning_4step", "type": "model", "name": "SDXL Lightning 4-Step LoRA",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_4step_lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "sdxl_lightning_4step_lora.safetensors",+ "license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]+ },+ "lora_sdxl_lightning_2step": {+ "id": "lora_sdxl_lightning_2step", "type": "model", "name": "SDXL Lightning 2-Step LoRA",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_2step_lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "sdxl_lightning_2step_lora.safetensors",+ "license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]+ },+ "lora_hyper_sdxl_8step": {+ "id": "lora_hyper_sdxl_8step", "type": "model", "name": "Hyper-SDXL 8-Steps LoRA",+ "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-8steps-lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Hyper-SDXL-8steps-lora.safetensors",+ "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]+ },+ "lora_hyper_sdxl_4step": {+ "id": "lora_hyper_sdxl_4step", "type": "model", "name": "Hyper-SDXL 4-Steps LoRA",+ "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-4steps-lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Hyper-SDXL-4steps-lora.safetensors",+ "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]+ },+ "lora_hyper_sdxl_1step": {+ "id": "lora_hyper_sdxl_1step", "type": "model", "name": "Hyper-SDXL 1-Step LoRA",+ "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-1step-lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Hyper-SDXL-1step-lora.safetensors",+ "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]+ },+ "controlnet_depth_sdxl_fp16_alt": {+ "id": "controlnet_depth_sdxl_fp16_alt", "type": "model", "name": "ControlNet Depth SDXL fp16 (alternative)",+ "url": "https://huggingface.co/diffusers/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.fp16.safetensors?download=true",+ "target_path_relative": "models/controlnet", "filename": "diffusion_pytorch_model.fp16.safetensors",+ "license": "OpenRAIL++", "size_mb": 2500, "packages": ["extended_optional"]+ },+ "controlnet_union_promax": {+ "id": "controlnet_union_promax", "type": "model", "name": "ControlNet Union SDXL ProMax",+ "url": "https://huggingface.co/brad-twinkl/controlnet-union-sdxl-1.0-promax/resolve/main/diffusion_pytorch_model.safetensors?download=true",+ "target_path_relative": "models/controlnet", "filename": "sdxl_promax.safetensors",+ "rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["extended_optional"]+ },+ # Checkpoints+ "checkpoint_realvis_v5": {+ "id": "checkpoint_realvis_v5", "type": "model", "name": "RealVisXL V5.0 fp16 Checkpoint",+ "url": "https://huggingface.co/SG161222/RealVisXL_V5.0/resolve/main/RealVisXL_V5.0_fp16.safetensors?download=true",+ "target_path_relative": "models/checkpoints", "filename": "RealVisXL_V5.0_fp16.safetensors",+ "license": "OpenRAIL++", "size_mb": 6500, "packages": ["checkpoint_realvis"]+ },+ # Qwen Core+ "cn_comfyui_gguf": {+ "id": "cn_comfyui_gguf", "type": "node", "name": "ComfyUI GGUF Loader",+ "git_url": "https://github.com/city96/ComfyUI-GGUF.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI-GGUF",+ "commit": "6ea2651e7df66d7585f6ffee804b20e92fb38b8a",+ "license": "Apache 2.0", "packages": ["qwen_core"],+ "pip_packages": ["gguf"]+ },+ "model_qwen_unet_q3_k_m": {+ "id": "model_qwen_unet_q3_k_m", "type": "model", "name": "Qwen Image Edit 2509 UNet (Q3_K_M)",+ "url": "https://huggingface.co/QuantStack/Qwen-Image-Edit-2509-GGUF/resolve/main/Qwen-Image-Edit-2509-Q3_K_M.gguf?download=true",+ "target_path_relative": "models/unet", "filename": "Qwen-Image-Edit-2509-Q3_K_M.gguf",+ "license": "Apache 2.0", "size_mb": 9760, "packages": ["qwen_core"]+ },+ "model_qwen_vae": {+ "id": "model_qwen_vae", "type": "model", "name": "Qwen Image VAE",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/vae/qwen_image_vae.safetensors?download=true",+ "target_path_relative": "models/vae", "filename": "qwen_image_vae.safetensors",+ "license": "Apache 2.0", "size_mb": 254, "packages": ["qwen_core"]+ },+ "model_qwen_text_encoder_fp8": {+ "id": "model_qwen_text_encoder_fp8", "type": "model", "name": "Qwen 2.5 VL 7B Text Encoder (FP8)",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors?download=true",+ "target_path_relative": "models/clip", "filename": "qwen_2.5_vl_7b_fp8_scaled.safetensors",+ "license": "Apache 2.0", "size_mb": 9380, "packages": ["qwen_core"]+ },+ "lora_qwen_lightning_4step_edit": {+ "id": "lora_qwen_lightning_4step_edit", "type": "model", "name": "Qwen Image Edit Lightning 4-Step LoRA (bf16)",+ "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors",+ "license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_core"]+ },+ # Qwen Extras+ "lora_qwen_lightning_8step": {+ "id": "lora_qwen_lightning_8step", "type": "model", "name": "Qwen Image Edit Lightning 8-Step LoRA (bf16)",+ "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors",+ "license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_extras"]+ },+ "lora_qwen_lightning_4step": {+ "id": "lora_qwen_lightning_4step", "type": "model", "name": "Qwen Image Lightning 4-Step LoRA (bf16)",+ "url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Lightning-4steps-V1.0-bf16.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Qwen-Image-Lightning-4steps-V1.0-bf16.safetensors",+ "license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_extras"]+ },+ # Nunchaku Qwen+ "cn_nunchaku": {+ "id": "cn_nunchaku", "type": "node", "name": "ComfyUI Nunchaku",+ "git_url": "https://github.com/nunchaku-tech/ComfyUI-nunchaku.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI-nunchaku",+ "commit": "b600f879a777fdef1466c362e850f7e8c31bf89a",+ "license": "Apache 2.0", "packages": ["qwen_nunchaku"],+ # The engine is not the PyPI package called "nunchaku" (an unrelated project): it ships as wheels built+ # per Python, torch and platform, picked with the node's own version list.+ "post_install": "nunchaku_wheel",+ },+ "cn_qwen_lora_loader": {+ "id": "cn_qwen_lora_loader", "type": "node", "name": "ComfyUI Qwen Image LoRA Loader",+ "git_url": "https://github.com/ussoewwin/ComfyUI-QwenImageLoraLoader.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI-QwenImageLoraLoader",+ "commit": "ccb55860b80d41835110609748000f4c64932635", # v2.6.7+ "license": "Apache 2.0", "packages": ["qwen_nunchaku"]+ },+ "model_nunchaku_qwen": {+ "id": "model_nunchaku_qwen", "type": "model", "name": "Nunchaku Qwen Image Edit 2509 (Int4)",+ "url": "https://huggingface.co/nunchaku-tech/nunchaku-qwen-image-edit-2509/resolve/main/lightning-251115/svdq-int4_r128-qwen-image-edit-2509-lightning-4steps-251115.safetensors?download=true",+ "target_path_relative": "models/diffusion_models", "filename": "svdq-int4_r128-qwen-image-edit-2509-lightning-4steps-251115.safetensors",+ "license": "Apache 2.0", "size_mb": 12700, "packages": ["qwen_nunchaku"]+ },+ # --- PBR Decomposition (Marigold IID) ---+ "cn_comfyui_marigold": {+ "id": "cn_comfyui_marigold", "type": "node", "name": "ComfyUI-Marigold (IID/Depth/Normal)",+ "git_url": "https://github.com/kijai/ComfyUI-Marigold.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI-Marigold",+ "commit": "2adfec75c430b0751a98a82453dc2dd8077bca85",+ "license": "GPL-3.0", "packages": ["pbr_marigold"],+ "pip_packages": ["diffusers>=0.28", "accelerate", "matplotlib"] + (["triton-windows"] if sys.platform == "win32" else []),+ "run_install_script": True,+ },+ # --- StableDelight (specular-free albedo) ---+ "cn_comfyui_stabledelight": {+ "id": "cn_comfyui_stabledelight", "type": "node", "name": "ComfyUI StableDelight (Delighting)",+ "git_url": "https://github.com/lldacing/ComfyUI_StableDelight_ll.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI_StableDelight_ll",+ "commit": "42c0463cc65554509804cbf577a1675c61499ec4",+ "license": "Apache-2.0", "packages": ["pbr_stabledelight"],+ "pip_packages": ["diffusers>=0.28", "accelerate", "matplotlib"] + (["triton-windows"] if sys.platform == "win32" else []),+ "post_clone_patches": [+ {+ "file": "nodes/BaseNode.py",+ "marker": "local_files_only=False",+ "anchor": "local_files_only=True",+ "patch": "local_files_only=False",+ "mode": "replace",+ },+ ],+ },+ "model_stabledelight": {+ "id": "model_stabledelight", "type": "hf_model",+ "name": "StableDelight Model (yoso-delight-v0-4-base)",+ "hf_repo": "Stable-X/yoso-delight-v0-4-base",+ "local_dir": "Stable-X--yoso-delight-v0-4-base",+ "license": "Apache-2.0", "size_mb": 3300,+ "packages": ["pbr_stabledelight"],+ },+ # --- Marigold V2 (albedo + normals; ComfyUI core nodes, LoRAs on Qwen-Image-Edit-2509) ---+ "model_marigold_v2_base": {+ "id": "model_marigold_v2_base", "type": "model",+ "name": "Marigold V2 base: Qwen Image Edit 2509 (int8)",+ "url": "https://huggingface.co/Comfy-Org/marigold-v2-0/resolve/main/diffusion_models/qwen_image_edit_2509_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/diffusion_models", "filename": "qwen_image_edit_2509_int8_convrot.safetensors",+ "license": "Apache 2.0", "size_mb": 19550, "packages": ["pbr_marigold_v2"],+ },+ **{+ f"model_marigold_v2_{task}_{kind}": {+ "id": f"model_marigold_v2_{task}_{kind}", "type": "model",+ "name": f"Marigold V2 {task.capitalize()} {label}",+ "url": f"https://huggingface.co/Comfy-Org/marigold-v2-0/resolve/main/{folder}/{filename}?download=true",+ "target_path_relative": f"models/{folder}", "filename": filename,+ "license": "Apache 2.0", "size_mb": size_mb, "packages": ["pbr_marigold_v2"],+ }+ for task in ("albedo", "normals")+ for kind, label, folder, filename, size_mb in (+ ("lora", "LoRA", "loras", f"marigold_v2_{task}.safetensors", 1625),+ ("vae", "VAE", "vae", f"marigold_v2_{task}_vae.safetensors", 242),+ ("cond", "Conditioning", "embeddings", f"marigold_v2_{task}_conditioning.safetensors", 3),+ )+ },+ # --- TRELLIS.2 (ComfyUI's native nodes, ComfyUI 0.42 or newer) ---+ "cn_trellis2_budget": {+ "id": "cn_trellis2_budget", "type": "embedded_node", "name": "StableGen TRELLIS.2 voxel budget node",+ "target_dir_relative": "custom_nodes", "repo_name": "ComfyUI-StableGen-TRELLIS2",+ "files": {"__init__.py": _TRELLIS2_BUDGET_NODE}, "stablegen_node": True,+ "license": "GPL-3.0", "packages": ["trellis2"],+ },+ "model_trellis2": {+ "id": "model_trellis2", "type": "model", "name": "TRELLIS.2 4B Diffusion Model (bf16)",+ "url": "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/diffusion_models/trellis_2_bf16.safetensors",+ "target_path_relative": "models/diffusion_models", "filename": "trellis_2_bf16.safetensors",+ "license": "MIT", "size_mb": 9860, "packages": ["trellis2"],+ },+ "model_trellis2_shape_vae": {+ "id": "model_trellis2_shape_vae", "type": "model", "name": "TRELLIS.2 Shape VAE",+ "url": "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/vae/trellis_2_shape_vae_bf16.safetensors",+ "target_path_relative": "models/vae", "filename": "trellis_2_shape_vae_bf16.safetensors",+ "license": "MIT", "size_mb": 1046, "packages": ["trellis2"],+ },+ "model_trellis2_texture_vae": {+ "id": "model_trellis2_texture_vae", "type": "model", "name": "TRELLIS.2 Texture VAE",+ "url": "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/vae/trellis_2_texture_vae_bf16.safetensors",+ "target_path_relative": "models/vae", "filename": "trellis_2_texture_vae_bf16.safetensors",+ "license": "MIT", "size_mb": 905, "packages": ["trellis2"],+ },+ "model_dino_v3": {+ "id": "model_dino_v3", "type": "model", "name": "DINOv3 ViT-L Image Encoder",+ "url": "https://huggingface.co/Comfy-Org/TRELLIS.2/resolve/main/clip_vision/dino_v3_vit_l.safetensors",+ "target_path_relative": "models/clip_vision", "filename": "dino_v3_vit_l.safetensors",+ "license": "DINOv3 License", "size_mb": 1157, "packages": ["trellis2"],+ },+ "model_birefnet": {+ "id": "model_birefnet", "type": "model", "name": "BiRefNet Background Removal",+ "url": "https://huggingface.co/Comfy-Org/BiRefNet/resolve/main/background_removal/birefnet.safetensors",+ "target_path_relative": "models/background_removal", "filename": "birefnet.safetensors",+ "license": "MIT", "size_mb": 424, "packages": ["trellis2"],+ },+ # --- FLUX.2 Klein 4B ---+ "model_flux2_klein_4b": {+ "id": "model_flux2_klein_4b", "type": "model",+ "name": "FLUX.2 Klein 4B Diffusion Model (FP8)",+ "url": "https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4b-fp8/resolve/main/flux-2-klein-base-4b-fp8.safetensors?download=true",+ "target_path_relative": "models/diffusion_models",+ "filename": "flux-2-klein-base-4b-fp8.safetensors",+ "license": "Apache 2.0", "size_mb": 4070, "packages": ["flux2_klein"],+ },+ "model_flux2_text_encoder": {+ "id": "model_flux2_text_encoder", "type": "model",+ "name": "FLUX.2 Klein Qwen 3 4B Text Encoder (bf16)",+ "url": "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors?download=true",+ "target_path_relative": "models/text_encoders",+ "filename": "qwen_3_4b.safetensors",+ "license": "Apache 2.0", "size_mb": 8050, "packages": ["flux2_klein"],+ },+ "model_flux2_vae": {+ "id": "model_flux2_vae", "type": "model",+ "name": "FLUX.2 VAE",+ "url": "https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors?download=true",+ "target_path_relative": "models/vae",+ "filename": "flux2-vae.safetensors",+ "license": "Apache 2.0", "size_mb": 321, "packages": ["flux2_klein", "fibo_edit"],+ },+ # --- Qwen Image 2.1 (ComfyUI core nodes; StableGen expects these text encoder and VAE file names) ---+ "model_qwen21_diffusion": {+ "id": "model_qwen21_diffusion", "type": "model", "name": "Qwen Image 2.1 Diffusion Model (int8)",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/diffusion_models", "filename": "qwen_image_2.1_int8_convrot.safetensors",+ "license": "Qwen Research License (non-commercial)", "size_mb": 7260, "packages": ["qwen_image_21"],+ },+ "model_qwen21_text_encoder": {+ "id": "model_qwen21_text_encoder", "type": "model", "name": "Qwen Image 2.1 Text Encoder (Qwen3-VL 8B, w4a8)",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_w4a8.safetensors?download=true",+ "target_path_relative": "models/text_encoders", "filename": "qwen3vl_8b_w4a8.safetensors",+ "license": "Qwen Research License (non-commercial)", "size_mb": 6310,+ "packages": ["qwen_image_21", "qwen_image_21_turbo"],+ },+ "model_qwen21_vae": {+ "id": "model_qwen21_vae", "type": "model", "name": "Qwen Image 2.1 VAE",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors?download=true",+ "target_path_relative": "models/vae", "filename": "qwen_image_2.1_vae_bf16.safetensors",+ "license": "Qwen Research License (non-commercial)", "size_mb": 680,+ "packages": ["qwen_image_21", "qwen_image_21_turbo"],+ },+ # --- Experimental architectures (ComfyUI core nodes, Comfy-Org repacks; file names as StableGen loads them) ---+ "model_qwen21_turbo_diffusion": {+ "id": "model_qwen21_turbo_diffusion", "type": "model", "name": "Qwen Image 2.1 Turbo Diffusion Model (int8)",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_turbo_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/diffusion_models", "filename": "qwen_image_2.1_turbo_int8_convrot.safetensors",+ "license": "Qwen Research License (non-commercial)", "size_mb": 6920, "packages": ["qwen_image_21_turbo"],+ },+ "model_moss_diffusion": {+ "id": "model_moss_diffusion", "type": "model", "name": "MOSS-Image Diffusion Model (int8)",+ "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/diffusion_models/moss_image_sft_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/diffusion_models", "filename": "moss_image_sft_int8_convrot.safetensors",+ "license": "Apache 2.0", "size_mb": 5162, "packages": ["moss_image"],+ },+ "model_moss_text_encoder": {+ "id": "model_moss_text_encoder", "type": "model", "name": "MOSS-Image Text Encoder (Qwen3.5 9B, int8)",+ "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/text_encoders/qwen3.5_9b_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/text_encoders", "filename": "qwen3.5_9b_int8_convrot.safetensors",+ "license": "Apache 2.0", "size_mb": 9296, "packages": ["moss_image"],+ },+ "model_moss_vae": {+ "id": "model_moss_vae", "type": "model", "name": "MOSS-Image VAE (FLUX.2 small)",+ "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/vae/flux2-vae_small.safetensors?download=true",+ "target_path_relative": "models/vae", "filename": "flux2-vae_small.safetensors",+ "license": "Apache 2.0", "size_mb": 237, "packages": ["moss_image"],+ },+ "model_moss_depth_control": {+ "id": "model_moss_depth_control", "type": "model", "name": "MOSS-Image Color/Depth Control Adapter",+ "url": "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/loras/moss_image_color_depth_control.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "moss_image_color_depth_control.safetensors",+ "license": "Apache 2.0", "size_mb": 298, "packages": ["moss_image"],+ },+ "model_fibo_diffusion": {+ "id": "model_fibo_diffusion", "type": "model", "name": "FIBO 2.0 Edit Turbo Diffusion Model (int8)",+ "url": "https://huggingface.co/Comfy-Org/Fibo-2.0/resolve/main/diffusion_models/fibo2_edit_turbo_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/diffusion_models", "filename": "fibo2_edit_turbo_int8_convrot.safetensors",+ "license": "CC BY-NC 4.0 (non-commercial)", "size_mb": 8019, "packages": ["fibo_edit"],+ },+ "model_fibo_text_encoder": {+ "id": "model_fibo_text_encoder", "type": "model", "name": "FIBO 2.0 Text Encoder (Qwen3-VL 4B, int8)",+ "url": "https://huggingface.co/Comfy-Org/Fibo-2.0/resolve/main/text_encoders/qwen3vl_4b_int8_convrot.safetensors?download=true",+ "target_path_relative": "models/text_encoders", "filename": "qwen3vl_4b_int8_convrot.safetensors",+ "license": "CC BY-NC 4.0 (non-commercial)", "size_mb": 4633, "packages": ["fibo_edit"],+ },+ # --- SkinTokens auto-rigging ---+ "cn_skintokens": {+ "id": "cn_skintokens", "type": "node", "name": "ComfyUI StableGen SkinTokens",+ "git_url": "https://github.com/sakalond/ComfyUI-StableGen-SkinTokens.git", "stablegen_node": True,+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI-StableGen-SkinTokens",+ "commit": "dd0a272686b77226e6702281b6fd7eb24231abe6",+ "license": "GPL-3.0 (SkinTokens code and weights: MIT)", "packages": ["skintokens"],+ # The node's own setup builds SkinTokens in a separate environment (vendor/skintokens_env) with its own+ # PyTorch and downloads the checkpoints, so ComfyUI's Python is left untouched.+ "post_install": "skintokens_runtime",+ },+ # --- LATO.2 low-poly remeshing (ComfyUI-LATO2) ---+ "cn_lato2": {+ "id": "cn_lato2", "type": "node", "name": "ComfyUI-LATO2 (LATO.2 low-poly remesh)",+ "git_url": "https://github.com/sakalond/ComfyUI-LATO2.git", "stablegen_node": True,+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI-LATO2",+ "commit": "b9056ca27e6dbdfe546de4700f98afe8c1e7bcf5",+ "license": "GPL-3.0 (LATO.2 code and weights: MIT; DINOv2: Apache 2.0)", "packages": ["lato2"],+ # The node's own setup builds LATO.2 in a separate environment (envs/lato2: PyTorch 2.8 for CUDA 12.8) with+ # uv and downloads its weights and DINOv2 into models/lato2, so ComfyUI's Python only gets uv.+ "pip_packages": ["uv"],+ "post_install": "lato2_runtime",+ "data_dirs": ["models/lato2"], # removing the package removes the weights too+ # installed once the setup's last step is done: DINOv2's checkpoint, after the environment and LATO.2's weights+ "ready": ["models/lato2/dinov2/checkpoints/*.pth"],+ },+}++# ComfyUI node types each package provides or needs (checked by --verify against /object_info), and the ComfyUI+# core nodes a package needs, which only exist in recent ComfyUI versions (checked before installing).+PACKAGE_NODES: Dict[str, List[str]] = {+ "core": ["IPAdapterUnifiedLoader", "IPAdapter"],+ "qwen_core": ["UnetLoaderGGUF", "TextEncodeQwenImageEditPlus"],+ "qwen_nunchaku": ["NunchakuQwenImageDiTLoader", "NunchakuQwenImageLoraLoader"],+ "pbr_marigold": ["MarigoldModelLoader", "MarigoldDepthEstimation_v2"],+ "pbr_stabledelight": ["LoadStableDelightModel", "ApplyStableDelight"],+ "pbr_marigold_v2": ["MarigoldV2PostProcess", "ConditioningLoader"],+ "trellis2": ["Trellis2Conditioning", "EmptyTrellis2LatentStructure", "VaeDecodeStructureTrellis2",+ "Trellis2ShapeStage", "Trellis2UpsampleStage", "VaeDecodeShapeTrellis", "Trellis2TextureStage",+ "VaeDecodeTextureTrellis", "RemeshMesh", "DecimateMesh", "MeshSmoothNormals", "UnwrapMesh",+ "BakeTextureFromVoxel", "ApplyTextureToMesh", "SaveGLB", "LoadBackgroundRemovalModel",+ "RemoveBackground", "ImageCropToMask", "StableGenTrellis2TokenBudget"],+ "flux2_klein": ["Flux2Scheduler", "EmptyFlux2LatentImage"],+ "qwen_image_21": ["TextEncodeQwenImage21", "QwenImage21Cache"],+ "skintokens": ["StableGenSkinTokensAutoRig"],+ "lato2": ["LATO2Remesh"],+ "qwen_image_21_turbo": ["TextEncodeQwenImage21", "QwenImage21Cache"],+ "moss_image": ["MOSSImageControl", "EmptyFlux2LatentImage"],+ "fibo_edit": ["TextEncodeFibo2"],+}+CORE_NODES: Dict[str, List[str]] = {+ "qwen_core": ["TextEncodeQwenImageEditPlus"],+ "trellis2": ["Trellis2Conditioning", "EmptyTrellis2LatentStructure", "VaeDecodeStructureTrellis2",+ "Trellis2ShapeStage", "Trellis2UpsampleStage", "VaeDecodeShapeTrellis", "Trellis2TextureStage",+ "VaeDecodeTextureTrellis", "RemeshMesh", "DecimateMesh", "MeshSmoothNormals", "UnwrapMesh",+ "BakeTextureFromVoxel", "ApplyTextureToMesh", "SaveGLB", "LoadBackgroundRemovalModel",+ "RemoveBackground", "ImageCropToMask"], # ComfyUI 0.42 or newer+ "pbr_marigold_v2": ["MarigoldV2PostProcess", "ConditioningLoader"],+ "flux2_klein": ["Flux2Scheduler", "EmptyFlux2LatentImage"],+ "qwen_image_21": ["TextEncodeQwenImage21", "QwenImage21Cache"],+ "qwen_image_21_turbo": ["TextEncodeQwenImage21", "QwenImage21Cache"],+ "moss_image": ["MOSSImageControl", "EmptyFlux2LatentImage"], # ComfyUI 0.42.3 or newer+ "fibo_edit": ["TextEncodeFibo2"], # ComfyUI master from 2026-10-21+}++# Define what items each menu option entails by listing package tags+# The script will collect all unique items based on the selected package tags.+MENU_PACKAGES: Dict[str, Dict[str, Any]] = {+ '1': {"name": "[MINIMAL CORE] Basic Requirements",+ "tags": ["core"],+ "size_gb": 7.3,+ "description_suffix": "*You will still need to manually download your own SDXL checkpoint(s) and all ControlNet models for full functionality and preset usage.*"},+ '2': {"name": "[ESSENTIAL] Core + Preset Essentials",+ "tags": ["core", "preset_essentials"],+ "size_gb": 9.8,+ "description_suffix": "*All models for preset functionality. You will still need to manually download your own SDXL checkpoint(s).*"},+ '3': {"name": "[RECOMMENDED] Full SDXL Setup (No Checkpoints)",+ "tags": ["core", "preset_essentials", "extended_optional", "pbr_marigold", "pbr_stabledelight"],+ "size_gb": 19.3,+ "description_suffix": "*Downloads optional ControlNet and LoRA models + PBR decomposition nodes. You will still need to manually download your own SDXL checkpoint(s).*"},+ '4': {"name": "[COMPLETE SDXL] Full SDXL Setup + RealVisXL V5.0 Checkpoint",+ "tags": ["core", "preset_essentials", "extended_optional", "pbr_marigold", "pbr_stabledelight", "checkpoint_realvis"],+ "size_gb": 26.3,+ "description_suffix": ""},+ '5': {"name": "[QWEN CORE] Models + GGUF Node",+ "tags": ["qwen_core"],+ "size_gb": 20.3,+ "description_suffix": "*Installs Qwen Image Edit UNet, VAE, text encoder, core LoRA, and GGUF ComfyUI node.*"},+ '6': {"name": "[QWEN EXTRAS] Core + Lightning LoRAs",+ "tags": ["qwen_core", "qwen_extras"],+ "size_gb": 22.6,+ "description_suffix": "*Adds the 8-step Qwen Image Edit Lightning LoRA and base Qwen Image's 4-step one. No*\n"+ " *preset uses them: the presets use the 4-step Edit LoRA, which Qwen core installs.*"},+ '7': {"name": "[QWEN NUNCHAKU] Nunchaku Nodes + Model",+ "tags": ["qwen_core", "qwen_nunchaku"],+ "size_gb": 33.0,+ "description_suffix": "*Installs Qwen Core components plus Nunchaku nodes and the Int4 quantized model (12.7GB).*"},+ '8': {"name": "[TRELLIS.2] Image-to-3D (ComfyUI's native nodes)",+ "tags": ["trellis2"],+ "size_gb": 13.1,+ "description_suffix": "*Needs ComfyUI 0.42 or newer. Installs the TRELLIS.2 4B model, its VAEs, the DINOv3 image*\n"+ " *encoder, BiRefNet background removal and StableGen's voxel-budget node. TRELLIS.2 and*\n"+ " *BiRefNet are MIT; DINOv3 is under Meta's DINOv3 License (commercial use allowed, not*\n"+ " *for military or weapons uses).*",+ },+ '9': {"name": "[PBR DECOMPOSITION] Marigold IID Node",+ "tags": ["pbr_marigold"],+ "size_gb": 0.01,+ "description_suffix": "*Installs ComfyUI-Marigold custom node for PBR decomposition (albedo, roughness, metallic).*\n"+ " *IID models (~2GB each) are downloaded automatically from HuggingFace on first use.*",+ },+ '10': {"name": "[PBR DECOMPOSITION] StableDelight Node + Model",+ "tags": ["pbr_marigold", "pbr_stabledelight"],+ "size_gb": 3.3,+ "description_suffix": "*Installs ComfyUI_StableDelight_ll custom node + downloads the*\n"+ " *Stable-X/yoso-delight-v0-4-base model (~3.3GB fp16) for specular-free albedo.*",+ },+ '11': {"name": "[DEPRECATED] FLUX.2 Klein 4B FP8 + Qwen 3 Text Encoder + VAE",+ "tags": ["flux2_klein"],+ "size_gb": 12.4,+ "description_suffix": "*Downloads FLUX.2 Klein 4B FP8 diffusion model (~4.1GB), Qwen 3 4B text encoder bf16 (~8.0GB),*\n"+ " *and FLUX.2 VAE (~0.3GB). All ComfyUI nodes are built-in (no custom nodes needed).*\n"+ " *Deprecated: StableGen shows FLUX.2 Klein only with Enable Deprecated Architectures.*\n"+ " *Apache 2.0 license. Requires ~13GB VRAM.*",+ },+ '12': {"name": "[PBR DECOMPOSITION] Marigold V2 Models (Albedo + Normals)",+ "tags": ["pbr_marigold_v2"],+ "size_gb": 23.3,+ "description_suffix": "*Downloads Marigold V2 (Apache 2.0): the int8 Qwen Image Edit 2509 base (~19.5GB) plus albedo*\n"+ " *and normals LoRAs, VAEs and conditionings. Uses ComfyUI core nodes (September 2026 or newer).*\n"+ " *Roughness and metallic still need the Marigold IID node (option 9).*",+ },+ '13': {"name": "[QWEN IMAGE 2.1] Diffusion Model + Text Encoder + VAE",+ "tags": ["qwen_image_21"],+ "size_gb": 14.3,+ "notice": "qwen21",+ "description_suffix": "*Downloads Qwen Image 2.1 int8 (~7.3GB), the Qwen3-VL 8B text encoder (~6.3GB) and VAE*\n"+ " *(~0.7GB). Uses ComfyUI core nodes (September 2026 or newer).*\n"+ " *LICENSE NOTICE: Qwen Research License, non-commercial use only.*",+ },+ '14': {"name": "[AUTO-RIGGING] SkinTokens Node + Runtime",+ "tags": ["skintokens"],+ "size_gb": 9.0,+ "description_suffix": "*Installs the StableGen SkinTokens node and builds SkinTokens in its own environment*\n"+ " *(PyTorch, flash-attn when available, checkpoints ~1.6GB). Rigs TRELLIS.2 meshes; NVIDIA GPU.*",+ },+ '15': {"name": "[EXPERIMENTAL] Qwen Image 2.1 Turbo",+ "tags": ["qwen_image_21_turbo"],+ "size_gb": 13.9,+ "notice": "qwen21",+ "description_suffix": "*Downloads the Qwen Image 2.1 Turbo int8 model (~6.9GB) and, unless package 13 already did,*\n"+ " *the Qwen Image 2.1 text encoder and VAE (~7.0GB). Uses ComfyUI core nodes.*\n"+ " *LICENSE NOTICE: Qwen Research License, non-commercial use only.*",+ },+ '16': {"name": "[EXPERIMENTAL] MOSS Image + Depth Control",+ "tags": ["moss_image"],+ "size_gb": 15.0,+ "description_suffix": "*Downloads MOSS-Image int8 (~5.2GB), its Qwen3.5 9B text encoder (~9.3GB), VAE (~0.2GB) and*\n"+ " *color/depth control adapter (~0.3GB). Needs ComfyUI 0.42.3 or newer. Apache 2.0.*",+ },+ '18': {"name": "[LATO.2] Low-Poly Remesh (ComfyUI-LATO2 node)",+ "tags": ["lato2"],+ "size_gb": 12.2,+ "description_suffix": "*Clones ComfyUI-LATO2 and runs its setup: LATO.2 in its own Python environment (PyTorch*\n"+ " *2.8, CUDA 12.8, ~8 GB, built with uv), its weights (3.4 GB) and DINOv2 (1.1 GB). Needs an*\n"+ " *NVIDIA GPU. ComfyUI's Python only gets uv. LATO.2 and its weights are MIT.*",+ },+ '17': {"name": "[EXPERIMENTAL] FIBO 2.0 Edit",+ "tags": ["fibo_edit"],+ "size_gb": 13.0,+ "notice": "fibo",+ "description_suffix": "*Downloads Bria FIBO 2.0 Edit Turbo int8 (~8.0GB), its Qwen3-VL 4B text encoder (~4.6GB) and*\n"+ " *the FLUX.2 VAE (~0.3GB). Needs a ComfyUI build with core FIBO 2.0 support (master, October 2026).*\n"+ " *LICENSE NOTICE: CC BY-NC 4.0, non-commercial use only.*",+ },+}++LICENSE_NOTICES: Dict[str, List[str]] = { # licenses that limit use (non-commercial), accepted before installing+ "qwen21": [+ "QWEN IMAGE 2.1 LICENSE NOTICE",+ "Qwen Image 2.1 is released under the Qwen Research License, which allows non-commercial use only",+ "(research or evaluation). Commercial use needs a separate license from the Qwen team.",+ "Qwen Image Edit 2509 (packages 5-7) is Apache 2.0 and not affected.",+ "",+ "License: https://huggingface.co/Qwen/Qwen-Image-2.1/blob/main/LICENSE",+ ],+ "fibo": [+ "FIBO 2.0 LICENSE NOTICE",+ "Bria FIBO 2.0 is released under CC BY-NC 4.0, which allows non-commercial use only.",+ "Commercial use needs an agreement with Bria.",+ "",+ "License: https://huggingface.co/briaai/Fibo-2.0-edit-turbo",+ ],+}++# --- Helper Functions ---+PYTHON_OVERRIDE: Optional[str] = None # --python+ASSUME_YES = False # --yes+NONINTERACTIVE = False # --events or --json: never ask, report instead+EVENTS = False # --events+ACCEPTED_NOTICES: Set[str] = set() # --accept-notices+IGNORE_DISK_SPACE = False # --ignore-disk-space+GIT_EXE = "git" # --git+CHILD_IO: Dict[str, Any] = {} # --log: where pip, git and install.py write+_EVENT_STREAM = None # the real stdout while --log takes print()+_CURRENT_ITEM = "" # the item being installed, for progress events++# Child processes that can hang (a stalled pip or git, an install.py waiting on a lock) end after these+GIT_TIMEOUT = 30 * 60+PIP_TIMEOUT = 60 * 60+SCRIPT_TIMEOUT = 2 * 60 * 60+++def emit(kind: str, **data):+ """One --events line."""+ if not EVENTS:+ return+ stream = _EVENT_STREAM or sys.stdout+ stream.write("@sg " + json.dumps({"event": kind, **data}, ensure_ascii=False) + "\n")+ stream.flush()+++def timed_out(e: subprocess.TimeoutExpired) -> str:+ return f"stopped after {int(e.timeout) // 60} min without finishing"+++def print_header(title: str):+ print(f"\n{'='*10} {title} {'='*10}")++def print_separator(char='-', length=70):+ print(char * length)+++def ask(question: str, default_yes: bool = True, yes_answers: bool = True) -> bool:+ """Ask a yes/no question. --yes answers it, unless yes_answers is False (then --yes means no)."""+ if ASSUME_YES:+ print(f"{question} {'yes' if yes_answers else 'no'} (--yes)")+ return yes_answers+ if NONINTERACTIVE:+ print(f"{question} no (nothing can answer in --events/--json mode)")+ return False+ suffix = "(y/n, Enter for yes)" if default_yes else "(y/n)"+ try:+ answer = input(f"{question} {suffix}: ").strip().lower()+ except EOFError:+ return False+ return answer == "y" or (default_yes and answer == "")+++def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="StableGen dependency installer for ComfyUI.")+ parser.add_argument("comfyuipath", nargs='?', default=None,+ help="Your ComfyUI folder (the one with 'models' and 'custom_nodes'). Asked for if omitted.")+ parser.add_argument("--packages",+ help="Package numbers to install without the menu, comma-separated (e.g. 3,8). See --list.")+ parser.add_argument("--yes", "-y", action="store_true",+ help="Answer yes to every question, including the license notices.")+ parser.add_argument("--list", action="store_true", help="List the packages and what each installs, then exit.")+ parser.add_argument("--dry-run", action="store_true", help="Show what would be installed; change nothing.")+ parser.add_argument("--update-nodes", action="store_true",+ help="Move custom nodes that are already installed to the commits StableGen was tested with.")+ parser.add_argument("--verify", action="store_true",+ help="Check the installation: model files are in place and ComfyUI registers every node the "+ "packages need. With --packages it runs after installing them (add --dry-run to only "+ "check them); alone it checks every package that looks installed.")+ parser.add_argument("--server",+ help="Verify against this running ComfyUI (e.g. 127.0.0.1:8188) instead of starting one.")+ parser.add_argument("--verify-timeout", type=int, default=900,+ help="Seconds to wait for ComfyUI to start during --verify (default 900: the first start "+ "after installing TRELLIS.2 builds its environment).")+ parser.add_argument("--verify-hashes", action="store_true",+ help="Check the SHA-256 of Hugging Face downloads, including files already present (slow).")+ parser.add_argument("--python", help="Python executable of your ComfyUI environment (detected otherwise).")+ parser.add_argument("--repair", action="store_true",+ help="No longer needed: TRELLIS.2 now runs on ComfyUI's native nodes. Kept for old scripts.")+ parser.add_argument("--check", action="store_true", help="No longer needed; kept for old scripts.")+ parser.add_argument("--accept-notices", default="",+ help="Accept these license notices without asking, comma-separated (qwen21, fibo).")+ parser.add_argument("--ignore-disk-space", action="store_true",+ help="Install even when the estimate says the drive is too full.")+ parser.add_argument("--git", help="Git executable to use (default: git on PATH).")+ parser.add_argument("--events", action="store_true",+ help="Report progress as JSON lines prefixed '@sg ' (for the StableGen add-on); never ask.")+ parser.add_argument("--log", help="With --events: write every other line (and pip, git and install.py output) "+ "to this file.")+ parser.add_argument("--status", action="store_true",+ help="Report ComfyUI's Python, GPU and the state of every package; change nothing.")+ parser.add_argument("--plan", action="store_true",+ help="Report what installing --packages would add and change in this ComfyUI; change nothing.")+ parser.add_argument("--json", action="store_true", help="With --status or --plan: print one JSON document.")+ parser.add_argument("--create-comfyui", metavar="FOLDER",+ help="Install StableGen's own ComfyUI into FOLDER (its own Python, torch for this GPU and a "+ "tested ComfyUI release), or repair and update the one there. Then install packages "+ "into FOLDER/ComfyUI as usual.")+ return parser.parse_args(argv)+++def get_comfyui_path_from_args(args: argparse.Namespace) -> Path:+ comfyui_path_str = args.comfyuipath+ while not comfyui_path_str:+ if ASSUME_YES or NONINTERACTIVE:+ sys.exit("Error: pass the ComfyUI folder as an argument when using --yes, --events or --json.")+ comfyui_path_str = input("Please enter the full path to your ComfyUI installation directory: ").strip().strip('"')++ comfyui_path = Path(comfyui_path_str).expanduser().resolve()++ if not comfyui_path.is_dir():+ sys.exit(f"Error: ComfyUI path '{comfyui_path}' not found or not a directory.")+ if not (comfyui_path / "models").is_dir() or not (comfyui_path / "custom_nodes").is_dir():+ inner = comfyui_path / "ComfyUI" # the portable build's outer folder+ if (inner / "models").is_dir() and (inner / "custom_nodes").is_dir():+ print(f"Using the ComfyUI folder inside it: {inner}")+ return inner+ sys.exit(f"Error: '{comfyui_path}' does not look like a ComfyUI folder (no 'models' or 'custom_nodes').")+ return comfyui_path+++def python_candidates(comfyui_path: Path) -> List[Path]:+ """Where ComfyUI's Python usually lives. The Windows portable build keeps it next to the ComfyUI folder, in+ 'python_embeded' (sic); venvs sit inside the folder or next to it (ComfyUI Desktop uses '.venv')."""+ out = []+ for base in (comfyui_path.parent, comfyui_path):+ for name in ("python_embeded", "python_embedded"):+ out.append(base / name / "python.exe")+ for base in (comfyui_path, comfyui_path.parent):+ for venv in ("venv", ".venv"):+ out.append(base / venv / "Scripts" / "python.exe")+ out.append(base / venv / "bin" / "python")+ return out+++def find_comfyui_python(comfyui_path: Path) -> str:+ """The Python ComfyUI runs with: --python, a portable build's embedded Python, a venv, else this Python."""+ if PYTHON_OVERRIDE:+ return PYTHON_OVERRIDE+ for candidate in python_candidates(comfyui_path):+ if candidate.is_file():+ return str(candidate)+ return sys.executable+++_PYTHON_REPORT = (+ "import sys\n"+ "v = sys.version_info\n"+ "print(f'{v.major}.{v.minor}.{v.micro}')\n"+ "try:\n"+ " import importlib.metadata as m\n"+ " print(m.version('torch'))\n"+ "except Exception:\n"+ " print('not installed')\n"+)+++def describe_python(comfyui_path: Path) -> bool:+ """Print the Python the installer will use. False when none was found and this script's own Python is used."""+ python = find_comfyui_python(comfyui_path)+ detected = bool(PYTHON_OVERRIDE) or any(c.is_file() for c in python_candidates(comfyui_path))+ try:+ out = subprocess.run([python, "-c", _PYTHON_REPORT], capture_output=True, env=UTF8_ENV, timeout=120,+ **UTF8_TEXT)+ version, torch = (out.stdout.split() + ["?", "?"])[:2]+ except (OSError, subprocess.TimeoutExpired):+ version, torch = "?", "?"+ print(f"ComfyUI Python: {python} (Python {version}, torch {torch})")+ if not detected:+ print("WARNING: ComfyUI's own Python was not found (a portable build's python_embeded or a venv), so the")+ print(" Python running this installer is used. If ComfyUI runs with a different Python, re-run")+ print(" with --python <path to that python>.")+ return detected+++def install_pip_packages(pip_packages: List[str], comfyui_path: Path, force_reinstall: bool = False) -> bool:+ """Install pip packages into ComfyUI's Python environment. Returns True when all of them installed."""+ python_exe = find_comfyui_python(comfyui_path)+ print(f" Installing pip packages into ComfyUI Python: {python_exe}")+ ok = True+ for pkg in pip_packages:+ print(f" pip install {pkg} ...")+ try:+ subprocess.run(+ [python_exe, "-m", "pip", "install"] + (["--force-reinstall", "--no-deps"] if force_reinstall else []) + [pkg],+ check=True, timeout=PIP_TIMEOUT, **CHILD_IO,+ )+ print(f" Successfully installed '{pkg}'.")+ except subprocess.CalledProcessError as e:+ print(f" ERROR: Failed to install '{pkg}' (exit code {e.returncode}).")+ print(f" You may need to install it manually: pip install {pkg}")+ ok = False+ except subprocess.TimeoutExpired as e:+ print(f" ERROR: pip install {pkg} {timed_out(e)}.")+ ok = False+ except FileNotFoundError:+ print(f" ERROR: Python executable not found at '{python_exe}'.")+ print(f" Please install '{pkg}' manually into your ComfyUI Python environment.")+ return False+ return ok+++def run_node_install_script(item_details: Dict[str, Any], comfyui_path: Path) -> bool:+ """Run a custom node's install.py to resolve its dependencies. Returns True on success."""+ repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]+ install_script = repo_path / "install.py"+ if not install_script.is_file():+ print(f" WARNING: No install.py found in '{repo_path}'. Skipping dependency install.")+ return True++ python_exe = find_comfyui_python(comfyui_path)+ print(f" Running install.py for {item_details['name']}...")+ print(f" {python_exe} {install_script}")+ try:+ subprocess.run([python_exe, str(install_script)], check=True, cwd=str(repo_path), timeout=SCRIPT_TIMEOUT,+ **CHILD_IO)+ print(f" Successfully ran install.py for '{item_details['name']}'.")+ return True+ except subprocess.CalledProcessError as e:+ print(f" ERROR: install.py failed (exit code {e.returncode}). Run it manually to see why:")+ print(f" cd {repo_path}")+ print(f" {python_exe} install.py")+ except subprocess.TimeoutExpired as e:+ print(f" ERROR: install.py {timed_out(e)}.")+ except FileNotFoundError:+ print(f" ERROR: Python executable not found at '{python_exe}'.")+ return False+++def apply_post_clone_patches(item_details: Dict[str, Any], comfyui_path: Path):+ """Apply compatibility patches to a cloned custom node repository.++ Patches are defined in the dependency entry under 'post_clone_patches'.+ Each patch dict has:+ file – relative path inside the repo+ marker – string checked to avoid re-applying+ mode – 'insert' (default) or 'replace'++ Insert mode (default):+ anchor – text before which the patch is inserted+ patch – code string to insert++ Replace mode:+ anchor – exact text to replace+ patch – replacement text+ """+ patches = item_details.get("post_clone_patches")+ if not patches:+ return++ repo_path = (comfyui_path / item_details["target_dir_relative"]+ / item_details["repo_name"])++ for p in patches:+ target_file = repo_path / p["file"]+ if not target_file.is_file():+ print(f" WARNING: Patch target '{p['file']}' not found. Skipping.")+ continue++ content = target_file.read_text(encoding="utf-8")++ # Already patched?+ marker = p.get("marker", "")+ if marker and marker in content:+ print(f" Compat patch already applied to '{p['file']}'.")+ continue++ anchor = p.get("anchor", "")+ patch_code = p.get("patch", "")+ mode = p.get("mode", "insert")++ if anchor and anchor in content:+ if mode == "replace":+ content = content.replace(anchor, patch_code, 1)+ else:+ content = content.replace(anchor, patch_code + anchor, 1)+ target_file.write_text(content, encoding="utf-8")+ print(f" Applied compat patch ({mode}) to '{p['file']}'.")+ else:+ print(f" WARNING: Anchor not found in '{p['file']}'. Patch skipped.")+++def create_dir_if_not_exists(path: Path):+ path.mkdir(parents=True, exist_ok=True)+++# --- Downloads ---+# Plain urllib, so the installer needs no third-party packages. Files download to '<name>.part' and are renamed+# once complete; an interrupted download resumes from the .part file on the next attempt or the next run.+USER_AGENT = "StableGen-installer"+DOWNLOAD_ATTEMPTS = 4+CHUNK = 1024 * 1024+++class _RedirectRecorder(urllib.request.HTTPRedirectHandler):+ """Follows redirects, keeps Hugging Face's x-linked-* headers (only the first response has them), and does not+ forward an Authorization header to another host (the CDN URLs are pre-signed)."""++ def __init__(self):+ super().__init__()+ self.headers: Dict[str, str] = {}++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ for key in ("x-linked-etag", "x-linked-size"):+ if headers.get(key) and key not in self.headers:+ self.headers[key] = headers.get(key)+ new = super().redirect_request(req, fp, code, msg, headers, newurl)+ if new is not None and urllib.parse.urlparse(newurl).hostname != urllib.parse.urlparse(req.full_url).hostname:+ new.remove_header("Authorization")+ return new+++def _open(url: str, method: str = "GET", headers: Optional[Dict[str, str]] = None, timeout: int = 60):+ """Open a URL; returns (response, headers recorded on redirects). HF_TOKEN authenticates Hugging Face."""+ recorder = _RedirectRecorder()+ opener = urllib.request.build_opener(recorder)+ request_headers = {"User-Agent": USER_AGENT}+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")+ if token and urllib.parse.urlparse(url).hostname == "huggingface.co":+ request_headers["Authorization"] = f"Bearer {token}"+ request_headers.update(headers or {})+ response = opener.open(urllib.request.Request(url, method=method, headers=request_headers), timeout=timeout)+ return response, recorder.headers+++def remote_info(url: str) -> Tuple[int, Optional[str]]:+ """(size in bytes or 0, SHA-256 or None) of a remote file. Hugging Face reports both for LFS files."""+ try:+ response, linked = _open(url, method="HEAD", timeout=30)+ with response:+ size = int(response.headers.get("Content-Length") or 0)+ except Exception:+ return 0, None+ size = int(linked.get("x-linked-size") or 0) or size+ etag = (linked.get("x-linked-etag") or "").strip().strip('"')+ return size, (etag.lower() if re.fullmatch(r"[0-9a-fA-F]{64}", etag) else None)+++def file_sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with open(path, "rb") as f:+ for block in iter(lambda: f.read(8 * CHUNK), b""):+ digest.update(block)+ return digest.hexdigest()+++class _PlainProgress:+ """Progress line for when tqdm is not installed."""++ def __init__(self, total: int, initial: int):+ self.total, self.done, self.shown = total, initial, 0.0++ def update(self, n: int):+ self.done += n+ now = time.time()+ if now - self.shown >= 1:+ self.shown = now+ pct = f" ({self.done / self.total:.0%})" if self.total else ""+ print(f"\r {self.done / 1024**2:,.0f} / {self.total / 1024**2:,.0f} MB{pct}", end="", flush=True)++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ print()+++class _EventProgress:+ """--events: progress events for one file, at most twice a second."""++ def __init__(self, name: str, total: int, initial: int):+ self.name, self.total, self.done, self.shown = name, total, initial, 0.0++ def update(self, n: int):+ self.done += n+ now = time.time()+ if now - self.shown >= 0.5:+ self.shown = now+ emit("progress", id=_CURRENT_ITEM, file=self.name, done=self.done, total=self.total)++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ emit("progress", id=_CURRENT_ITEM, file=self.name, done=self.done, total=self.total)+++def _progress(name: str, total: int, initial: int):+ if EVENTS:+ return _EventProgress(name, total, initial)+ if TQDM_AVAILABLE and total:+ return tqdm(total=total, initial=initial, unit='B', unit_scale=True, unit_divisor=1024, desc=name[:40],+ ascii=True)+ return _PlainProgress(total, initial)+++def download_url(url: str, final_path: Path, name: str, verify_hash: bool = False) -> Tuple[str, str]:+ """Download url to final_path, resuming and retrying. Returns (status, message); status is 'installed',+ 'present', 'warning' or 'failed'."""+ final_path.parent.mkdir(parents=True, exist_ok=True)+ part = final_path.with_name(final_path.name + ".part")+ remote_size, remote_sha = remote_info(url)++ adopted = False # resuming a file this installer did not write: it may not be the start of this one+ if final_path.exists():+ local = final_path.stat().st_size+ if not model_file_complete(final_path) and (not remote_size or local == remote_size):+ print(f" '{final_path.name}' is damaged (shorter than its header says); downloading it again.")+ final_path.unlink()+ elif not remote_size or local == remote_size:+ if verify_hash and remote_sha:+ print(f" Checking the SHA-256 of '{final_path.name}'...")+ if file_sha256(final_path) == remote_sha:+ return "present", "SHA-256 verified"+ print(f" '{final_path.name}' does not match the published SHA-256; downloading it again.")+ final_path.unlink()+ else:+ return "present", "" if remote_size else "server did not report a size; assumed complete"+ elif local < remote_size:+ print(f" '{final_path.name}' is incomplete ({local / 1024**2:,.0f} of {remote_size / 1024**2:,.0f} MB); "+ f"resuming.")+ if part.exists():+ part.unlink()+ final_path.rename(part)+ adopted = True+ else:+ return "warning", (f"local file is {local:,} bytes but the server's is {remote_size:,}; left as is "+ f"(delete it to download again)")++ error = ""+ for attempt in range(1, DOWNLOAD_ATTEMPTS + 1):+ have = part.stat().st_size if part.exists() else 0+ if remote_size and have == remote_size:+ break+ if remote_size and have > remote_size:+ part.unlink()+ have = 0+ try:+ response, _ = _open(url, headers={"Range": f"bytes={have}-"} if have else None)+ with response:+ if have and response.status != 206:+ have = 0 # the server ignored the range request: start over+ length = int(response.headers.get("Content-Length") or 0)+ total = remote_size or (have + length if length else 0)+ with open(part, "ab" if have else "wb") as f, _progress(name, total, have) as bar:+ while True:+ block = response.read(CHUNK)+ if not block:+ break+ f.write(block)+ bar.update(len(block))+ done = part.stat().st_size+ if (remote_size and done < remote_size) or (not remote_size and length and done < have + length):+ raise ConnectionError(f"connection closed after {done / 1024**2:,.0f} MB")+ break+ except urllib.error.HTTPError as e:+ if e.code == 416 and have:+ break # nothing left to fetch+ if e.code in (401, 403):+ return "failed", (f"HTTP {e.code}: access denied (a gated model needs its license accepted on "+ f"Hugging Face and HF_TOKEN set)")+ if e.code == 404:+ return "failed", "HTTP 404: the file is no longer at this address"+ error = f"HTTP {e.code}"+ except (urllib.error.URLError, OSError, ConnectionError, socket.timeout) as e:+ error = str(getattr(e, "reason", e))+ if attempt < DOWNLOAD_ATTEMPTS:+ wait = 5 * attempt+ print(f" Download interrupted ({error}); retrying in {wait} s ({attempt}/{DOWNLOAD_ATTEMPTS - 1})...")+ time.sleep(wait)+ else:+ return "failed", f"download failed after {DOWNLOAD_ATTEMPTS} attempts ({error}); run again to resume"++ size = part.stat().st_size if part.exists() else 0+ if remote_size and size != remote_size:+ return "failed", f"incomplete ({size:,} of {remote_size:,} bytes); run again to resume"+ checked = (verify_hash or adopted) and bool(remote_sha)+ if checked:+ print(f" Checking the SHA-256 of '{final_path.name}'...")+ if file_sha256(part) != remote_sha:+ part.unlink()+ return "failed", "SHA-256 mismatch; the download was deleted, run again"+ os.replace(part, final_path)+ return "installed", f"{size / 1024**2:,.0f} MB" + (", SHA-256 verified" if checked else "")+++def download_file(item_details: Dict[str, Any], comfyui_path: Path, verify_hash: bool = False) -> Tuple[str, str]:+ url = item_details["url"]+ final_filepath = comfyui_path / item_details["target_path_relative"] / item_details["filename"]+ print(f" {item_details['name']} (~{item_details.get('size_mb', '?')} MB) - License: {item_details['license']}")+ print(f" From: {url}")+ print(f" To: {final_filepath}")+ status, message = download_url(url, final_filepath, item_details['name'], verify_hash)+ print(f" {status}{': ' + message if message else ''}")+ return status, message+++HF_REPO_PATTERNS = ["*.json", "*.txt", "*.yaml", "*.md", "*.py", "*.model", "*.fp16.safetensors", "*.fp16.bin",+ "tokenizer/*"]+++def _hf_repo_files(repo: str) -> List[str]:+ response, _ = _open(f"https://huggingface.co/api/models/{repo}/tree/main?recursive=true", timeout=30)+ with response:+ entries = json.loads(response.read().decode("utf-8"))+ return [e["path"] for e in entries if e.get("type") == "file"]+++def download_hf_model(item_details: Dict[str, Any], comfyui_path: Path, verify_hash: bool = False) -> Tuple[str, str]:+ """Download a Hugging Face diffusers repo (configs and fp16 weights) into ComfyUI/models/diffusers/<local_dir>.++ Required keys in *item_details*:+ hf_repo – e.g. ``'Stable-X/yoso-delight-v0-4-base'``+ local_dir – directory name under ``models/diffusers/``+ """+ hf_repo = item_details["hf_repo"]+ target_dir = comfyui_path / "models" / "diffusers" / item_details["local_dir"]+ print(f" Hugging Face model {hf_repo} (~{item_details.get('size_mb', '?')} MB) - "+ f"License: {item_details.get('license', 'unknown')}")+ print(f" To: {target_dir}")+ try:+ files = [f for f in _hf_repo_files(hf_repo)+ if any(fnmatch.fnmatch(f, p) or fnmatch.fnmatch(f.split("/")[-1], p) for p in HF_REPO_PATTERNS)]+ except Exception as e:+ if (target_dir / "model_index.json").exists():+ return "present", f"could not list the repository ({e}); kept the existing copy"+ return "failed", f"could not list the repository: {e}"+ statuses = []+ for path in files:+ url = f"https://huggingface.co/{hf_repo}/resolve/main/{urllib.parse.quote(path)}"+ status, message = download_url(url, target_dir / path, path, verify_hash)+ if status == "failed":+ print(f" {path}: {message}")+ return "failed", f"{path}: {message}"+ statuses.append(status)+ if "installed" in statuses:+ return "installed", f"{statuses.count('installed')} of {len(files)} files downloaded"+ return "present", f"{len(files)} files"+++def _git(args: List[str], cwd: Path) -> subprocess.CompletedProcess:+ return subprocess.run([GIT_EXE] + args, cwd=str(cwd), capture_output=True, timeout=GIT_TIMEOUT, **UTF8_TEXT)+++def _rmtree(path: Path):+ """shutil.rmtree that also removes Git's read-only object files on Windows."""+ def make_writable(func, p, _exc):+ os.chmod(p, 0o700)+ func(p)+ if sys.version_info >= (3, 12):+ shutil.rmtree(str(path), onexc=make_writable)+ else:+ shutil.rmtree(str(path), onerror=make_writable)+++def clone_git_repo(item_details: Dict[str, Any], comfyui_path: Path, update_nodes: bool = False) -> Tuple[str, str]:+ """Clone a custom node at its tested commit, or check an existing clone. Returns (status, message)."""+ git_url = item_details["git_url"]+ repo_name = item_details["repo_name"]+ repo_path = comfyui_path / item_details["target_dir_relative"] / repo_name+ pinned = item_details.get("commit")++ try:+ if repo_path.is_dir():+ if not (repo_path / ".git").exists():+ return "present", "installed without Git (e.g. through ComfyUI-Manager); left as is"+ head = _git(["rev-parse", "HEAD"], repo_path).stdout.strip()+ if not pinned or head == pinned:+ return "present", f"at {head[:12]}" if head else ""+ if not (item_details.get("enforce_pin") or update_nodes):+ return "warning", (f"at {head[:12]}; StableGen was tested with {pinned[:12]} "+ f"(re-run with --update-nodes to switch)")+ print(f" Moving '{repo_name}' to the tested commit {pinned[:12]}...")+ _git(["fetch", "origin"], repo_path)+ checkout = _git(["checkout", pinned], repo_path)+ if checkout.returncode != 0:+ reason = (checkout.stderr.strip().splitlines() or ["unknown error"])[-1]+ return "failed", (f"could not check out {pinned[:12]}: {reason} (commit or discard local changes "+ f"in {repo_path})")+ return "updated", f"{head[:12]} -> {pinned[:12]}"++ create_dir_if_not_exists(repo_path.parent)+ print(f" Cloning: {item_details['name']} - License: {item_details['license']}")+ print(f" From: {git_url}")+ print(f" To: {repo_path}")+ # Clone next to the target and move it in only when complete: an interrupted clone must not leave a+ # folder that later runs take for an installed node+ staging = repo_path.with_name(f".{repo_name}.stablegen-clone")+ if staging.exists():+ _rmtree(staging)+ clone = subprocess.run([GIT_EXE, 'clone', git_url, str(staging)], cwd=str(repo_path.parent),+ timeout=GIT_TIMEOUT, **CHILD_IO)+ if clone.returncode != 0:+ if staging.exists():+ _rmtree(staging)+ return "failed", "git clone failed: check your network and that the repository is public"+ if pinned:+ checkout = _git(["checkout", pinned], staging)+ if checkout.returncode != 0:+ _rmtree(staging)+ return "failed", f"cloned, but the tested commit {pinned[:12]} is missing upstream"+ staging.rename(repo_path)+ return "installed", f"at {pinned[:12]}" if pinned else "latest commit"+ except FileNotFoundError:+ return "failed", "Git is not installed or not on PATH"+ except subprocess.TimeoutExpired as e:+ return "failed", f"git {timed_out(e)}"+++# --- Post-install steps for nodes that set up their own runtime ---+_NUNCHAKU_WHEEL_SCRIPT = r'''"""Install the Nunchaku engine wheel matching this Python, torch and platform (StableGen installer)."""+import importlib.metadata+import importlib.util+import sys++spec = importlib.util.spec_from_file_location("nunchaku_installers", sys.argv[1])+installers = importlib.util.module_from_spec(spec)+spec.loader.exec_module(installers)++try:+ dist = importlib.metadata.distribution("nunchaku")+ summary = (dist.metadata.get("Summary") or "").lower()+ if "piece-wise" not in summary and not dist.version.startswith("0.16"):+ print(f"Nunchaku {dist.version} is already installed.")+ sys.exit(0)+ print(f"Replacing the unrelated PyPI package 'nunchaku' {dist.version}.")+except importlib.metadata.PackageNotFoundError:+ pass++config = installers.generate_and_save_config() or installers.load_version_config()+versions = config.get("versions", [])+if not versions:+ sys.exit("Could not read Nunchaku's version list.")+from packaging.version import parse+version = max(versions, key=parse)+info = installers.get_system_info()+if not info.get("torch_version"):+ sys.exit("torch is not installed in this Python.")+backend = installers.get_install_backend()+for source in ("github", "huggingface", "modelscope"):+ wheel = installers.construct_compatible_wheel_info(version, source, info, config)+ if not wheel:+ continue+ try:+ print(f"Installing {wheel['name']} from {source}...")+ installers.install_wheel(wheel["url"], backend)+ print(f"Installed Nunchaku {version}.")+ sys.exit(0)+ except Exception as e:+ print(f" {source}: {e}")+sys.exit(f"No Nunchaku {version} wheel for Python {info['python_version']}, {info['torch_version']}, "+ f"{info['platform_tag']}.")+'''+++def _install_nunchaku_wheel(item_details: Dict[str, Any], comfyui_path: Path) -> Tuple[bool, str]:+ repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]+ installers = repo_path / "nodes" / "tools" / "installers.py"+ if not installers.is_file():+ return False, f"{installers} not found"+ with tempfile.TemporaryDirectory() as tmp:+ script = Path(tmp) / "stablegen_nunchaku_wheel.py"+ script.write_text(_NUNCHAKU_WHEEL_SCRIPT, encoding="utf-8")+ try:+ result = subprocess.run([find_comfyui_python(comfyui_path), str(script), str(installers)],+ timeout=PIP_TIMEOUT, **CHILD_IO)+ except subprocess.TimeoutExpired as e:+ return False, timed_out(e)+ return result.returncode == 0, "" if result.returncode == 0 else "see the messages above"+++def scripts_first_env(comfyui_path: Path) -> Dict[str, str]:+ """The environment for a node's setup script: ComfyUI's Python's own scripts folder first on PATH, so a tool+ pip installed there (uv) runs as itself, not through a launcher shim. pyenv-win's shims are .bat files whose+ arguments pass through cmd, which reads the '<' in 'numpy<2.3' as an input redirection."""+ env = dict(UTF8_ENV)+ try:+ out = subprocess.run([find_comfyui_python(comfyui_path), "-c", "import sysconfig; print(sysconfig.get_path('scripts'))"],+ capture_output=True, env=UTF8_ENV, timeout=60, **UTF8_TEXT)+ scripts = out.stdout.strip().splitlines()[-1] if out.returncode == 0 and out.stdout.strip() else ""+ except (OSError, subprocess.TimeoutExpired):+ scripts = ""+ if scripts and Path(scripts).is_dir():+ env["PATH"] = scripts + os.pathsep + env.get("PATH", "")+ return env+++def _install_skintokens_runtime(item_details: Dict[str, Any], comfyui_path: Path) -> Tuple[bool, str]:+ repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]+ script = repo_path / "install_skintokens.py"+ if not script.is_file():+ return False, f"{script} not found"+ print(" Building the SkinTokens runtime (its own Python environment, PyTorch and checkpoints).")+ print(" This takes a while the first time.")+ try:+ result = subprocess.run([find_comfyui_python(comfyui_path), str(script), "--target", "managed"],+ cwd=str(repo_path), timeout=SCRIPT_TIMEOUT,+ env=scripts_first_env(comfyui_path), **CHILD_IO)+ except subprocess.TimeoutExpired as e:+ return False, timed_out(e)+ return result.returncode == 0, "" if result.returncode == 0 else "see the messages above"+++def _install_lato2_runtime(item_details: Dict[str, Any], comfyui_path: Path) -> Tuple[bool, str]:+ repo_path = comfyui_path / item_details["target_dir_relative"] / item_details["repo_name"]+ script = repo_path / "install_lato2.py"+ if not script.is_file():+ return False, f"{script} not found"+ print(" Building the LATO.2 runtime (its own Python environment and PyTorch) and downloading its weights.")+ print(" This takes a while the first time (about 12 GB).")+ try:+ result = subprocess.run([find_comfyui_python(comfyui_path), str(script)],+ cwd=str(repo_path), timeout=SCRIPT_TIMEOUT,+ env=scripts_first_env(comfyui_path), **CHILD_IO)+ except subprocess.TimeoutExpired as e:+ return False, timed_out(e)+ return result.returncode == 0, "" if result.returncode == 0 else "see the messages above"+++POST_INSTALL = {+ "nunchaku_wheel": ("Nunchaku engine", _install_nunchaku_wheel),+ "skintokens_runtime": ("SkinTokens runtime", _install_skintokens_runtime),+ "lato2_runtime": ("LATO.2 runtime", _install_lato2_runtime),+}+++def install_embedded_node(item_details: Dict[str, Any], comfyui_path: Path) -> Tuple[str, str]:+ """Write a node StableGen ships inside this installer (no Git needed). Returns (status, message)."""+ folder = item_target(item_details, comfyui_path)+ existed = folder.is_dir()+ changed = []+ for relative, text in item_details["files"].items():+ target = folder / relative+ if target.is_file() and target.read_text(encoding="utf-8") == text:+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(text, encoding="utf-8")+ changed.append(relative)+ if not changed:+ return "present", ""+ return ("updated" if existed else "installed"), f"wrote {', '.join(changed)} in {folder}"+++def install_node(item_details: Dict[str, Any], comfyui_path: Path, update_nodes: bool) -> List[Tuple[str, str, str]]:+ """Clone or check a custom node, then install what it needs. Returns (name, status, message) rows."""+ name = item_details["name"]+ status, message = clone_git_repo(item_details, comfyui_path, update_nodes)+ print(f" {status}{': ' + message if message else ''}")+ rows = [(name, status, message)]+ if status == "failed":+ return rows+ if item_details.get("pip_packages") and not install_pip_packages(item_details["pip_packages"], comfyui_path):+ rows.append((f"{name}: Python packages", "failed", "pip install failed (see above)"))+ if item_details.get("post_clone_patches"):+ apply_post_clone_patches(item_details, comfyui_path)+ if item_details.get("run_install_script") and not run_node_install_script(item_details, comfyui_path):+ rows.append((f"{name}: install.py", "failed", "the node's dependency install failed (see above)"))+ hook = item_details.get("post_install")+ if hook:+ label, run = POST_INSTALL[hook]+ ok, message = run(item_details, comfyui_path)+ rows.append((f"{name}: {label}", "installed" if ok else "failed", message))+ return rows+++# --- Packages ---+def display_menu(comfyui_path: Path):+ print_header("StableGen Dependency Installer")+ print(f"Target ComfyUI Directory: {comfyui_path}")+ print_separator()+ print("This script downloads and sets up the custom nodes and models StableGen uses.")+ print("To install components by hand instead, see the manual installation guide:")+ print("https://github.com/sakalond/StableGen/wiki/Manual-installation")+ print_separator()+ print("Download sizes are estimates. The full list of components is shown for approval before anything changes.")+ print_separator()++ for key, val in MENU_PACKAGES.items():+ print(f"\n{key}. {val['name']}")+ print_separator(char='.')+ print(f" *Approximate total download size: ~{val['size_gb']:.1f} GB*")+ if val.get("description_suffix"):+ print(f" {val['description_suffix']}")+ print("\nq. Quit")+ print_separator()+++def print_package_list():+ """--list: every package and the components it installs."""+ for key, val in MENU_PACKAGES.items():+ print(f"{key:>3}. {val['name']} (~{val['size_gb']:.1f} GB)")+ for item in resolve_items([key]):+ kind = {"node": "node", "embedded_node": "node", "model": "model", "hf_model": "model"}[item["type"]]+ print(f" {kind:<5} {item['name']}")+++def parse_package_choice(text: str) -> List[str]:+ """'3, 8' -> ['3', '8']. Package tags ('trellis2') work too. Raises ValueError for unknown ones."""+ keys = [k.strip() for k in text.replace(";", ",").split(",") if k.strip()]+ unknown = [k for k in keys if k not in MENU_PACKAGES and k not in TAG_LABELS]+ if not keys or unknown:+ raise ValueError(f"unknown package(s): {', '.join(unknown) or text!r}; choose from {', '.join(MENU_PACKAGES)} "+ f"or a package tag ({', '.join(TAG_LABELS)})")+ return list(dict.fromkeys(keys))+++def package_info(key: str) -> Dict[str, Any]:+ """A menu package ('8'), or a package tag ('trellis2') as a package of its own: the add-on installs by tag."""+ if key in MENU_PACKAGES:+ return MENU_PACKAGES[key]+ notices = [p["notice"] for p in MENU_PACKAGES.values() if p.get("notice") and key in p["tags"]]+ size_mb = sum(i.get("size_mb", 0) for i in DEPENDENCIES.values() if key in i["packages"]) + ENV_SIZE_MB.get(key, 0)+ return {"name": TAG_LABELS[key], "tags": [key], "size_gb": round(size_mb / 1024, 1),+ **({"notice": notices[0]} if notices else {})}+++def tags_for(keys: List[str]) -> List[str]:+ return list(dict.fromkeys(tag for key in keys for tag in package_info(key)["tags"]))+++def get_unique_item_ids_for_tags(selected_tags: List[str]) -> Set[str]:+ return {item_id for item_id, details in DEPENDENCIES.items()+ if any(tag in details["packages"] for tag in selected_tags)}+++def resolve_items(keys: List[str]) -> List[Dict[str, Any]]:+ """The components of the chosen packages, each once, in DEPENDENCIES order."""+ ids = get_unique_item_ids_for_tags(tags_for(keys))+ return [item for item_id, item in DEPENDENCIES.items() if item_id in ids]+++def item_target(item: Dict[str, Any], comfyui_path: Path) -> Path:+ if item["type"] in ("node", "embedded_node"):+ return comfyui_path / item["target_dir_relative"] / item["repo_name"]+ if item["type"] == "model":+ return comfyui_path / item["target_path_relative"] / item["filename"]+ return comfyui_path / "models" / "diffusers" / item["local_dir"]+++def item_present(item: Dict[str, Any], comfyui_path: Path) -> bool:+ target = item_target(item, comfyui_path)+ if item["type"] == "hf_model":+ return (target / "model_index.json").exists()+ if item["type"] == "embedded_node":+ return all((target / relative).is_file() for relative in item["files"])+ if item["type"] == "model":+ return target.exists() and model_file_complete(target)+ # a node whose setup builds more than its clone counts once that is done ("ready": globs under the ComfyUI folder)+ return target.exists() and all(any(comfyui_path.glob(pattern)) for pattern in item.get("ready", []))+++_COMPLETE: Dict[Tuple[str, int, int], bool] = {}+++def model_file_complete(path: Path) -> bool:+ """False for a .safetensors file shorter than its own header says: a download cut short, or a copy that stopped.+ Other formats are taken as complete. Remembered per size and modification time."""+ if path.suffix != ".safetensors":+ return True+ try:+ stat = path.stat()+ except OSError:+ return False+ key = (str(path), stat.st_size, stat.st_mtime_ns)+ if key not in _COMPLETE:+ _COMPLETE[key] = _safetensors_complete(path, stat.st_size)+ return _COMPLETE[key]+++def _safetensors_complete(path: Path, size: int) -> bool:+ """A safetensors file is an 8-byte header length, a JSON header and the tensors' bytes at the offsets it lists."""+ try:+ with open(path, "rb") as f:+ length = int.from_bytes(f.read(8), "little")+ if not 0 < length <= 100 * 1024**2 or 8 + length > size:+ return False+ header = json.loads(f.read(length))+ except (OSError, ValueError):+ return False+ end = max((entry["data_offsets"][1] for name, entry in header.items()+ if name != "__metadata__" and isinstance(entry, dict) and "data_offsets" in entry), default=0)+ return size >= 8 + length + end+++TAG_LABELS = {+ "core": "SDXL core", "preset_essentials": "SDXL preset essentials", "extended_optional": "SDXL extras",+ "checkpoint_realvis": "RealVisXL checkpoint", "qwen_core": "Qwen Image Edit core", "qwen_extras": "Qwen extras",+ "qwen_nunchaku": "Qwen Nunchaku", "pbr_marigold": "Marigold IID", "pbr_stabledelight": "StableDelight",+ "pbr_marigold_v2": "Marigold V2", "trellis2": "TRELLIS.2", "flux2_klein": "FLUX.2 Klein",+ "qwen_image_21": "Qwen Image 2.1", "skintokens": "SkinTokens",+ "qwen_image_21_turbo": "Qwen Image 2.1 Turbo", "moss_image": "MOSS Image", "fibo_edit": "FIBO 2.0 Edit",+ "lato2": "LATO.2",+}+++def installed_tags(comfyui_path: Path) -> Tuple[List[str], Dict[str, Tuple[int, int]]]:+ """For --verify without --packages: package tags with every component present, and the partly installed ones+ as {tag: (present, total)}."""+ complete, partial = [], {}+ for tag in TAG_LABELS:+ items = [item for item in DEPENDENCIES.values() if tag in item["packages"]]+ present = sum(item_present(item, comfyui_path) for item in items)+ if items and present == len(items):+ complete.append(tag)+ elif present:+ partial[tag] = (present, len(items))+ return complete, partial+++# --- Checks before installing ---+def missing_core_nodes(comfyui_path: Path, tags: List[str]) -> Dict[str, List[str]]:+ """ComfyUI core nodes the packages need that this ComfyUI version does not have, by package tag."""+ sources = [comfyui_path / "nodes.py"] + sorted((comfyui_path / "comfy_extras").glob("*.py"))+ text = "\n".join(p.read_text(encoding="utf-8", errors="ignore") for p in sources if p.is_file())+ if not text:+ return {} # not a source checkout (e.g. ComfyUI Desktop): can't tell offline+ missing = {}+ for tag in tags:+ absent = [n for n in CORE_NODES.get(tag, []) if not re.search(rf"[\"']{re.escape(n)}[\"']|class {re.escape(n)}\b", text)]+ if absent:+ missing[tag] = absent+ return missing+++ENV_SIZE_MB = {"skintokens": 9000, "lato2": 12500}+++def estimate_download_mb(items: List[Dict[str, Any]], tags: List[str], comfyui_path: Path) -> int:+ """MB still to download: models that are not present yet, plus environments the nodes build."""+ total = sum(item.get("size_mb", 0) for item in items+ if item["type"] in ("model", "hf_model") and not item_present(item, comfyui_path))+ for tag in tags:+ node_items = [i for i in items if i["type"] == "node" and tag in i["packages"]]+ if tag in ENV_SIZE_MB and not all(item_present(i, comfyui_path) for i in node_items):+ total += ENV_SIZE_MB[tag]+ return total+++def show_notice(key: str) -> bool:+ print_separator(char='!')+ for line in LICENSE_NOTICES[key]:+ print(line)+ print_separator(char='!')+ if key in ACCEPTED_NOTICES:+ print("Accepted (--accept-notices).")+ return True+ if NONINTERACTIVE and not ASSUME_YES:+ emit("error", code="notice", key=key, lines=LICENSE_NOTICES[key],+ message=f"the '{key}' license notice was not accepted (--accept-notices {key})")+ return False+ return ask("Acknowledge and continue?")+++# --- Verification ---+def _free_port() -> int:+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _fetch_object_info(address: str, timeout: int = 15) -> Optional[Dict[str, Any]]:+ try:+ with urllib.request.urlopen(f"http://{address}/object_info", timeout=timeout) as response:+ return json.loads(response.read().decode("utf-8"))+ except Exception:+ return None+++def _stop_process_tree(proc: subprocess.Popen):+ if proc.poll() is not None:+ return+ if sys.platform == "win32":+ subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True)+ else:+ import signal+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ except OSError:+ proc.terminate()+ try:+ proc.wait(timeout=30)+ except subprocess.TimeoutExpired:+ proc.kill()+++def start_comfyui_for_verify(comfyui_path: Path, timeout: int) -> Tuple[Optional[Dict[str, Any]], List[str]]:+ """Start ComfyUI on a free local port, read /object_info, stop it. Returns (object_info or None, custom node+ folders that failed to import)."""+ main_py = comfyui_path / "main.py"+ if not main_py.is_file():+ print(f" {main_py} not found (ComfyUI Desktop?). Start ComfyUI yourself and pass --server <address>.")+ return None, []+ python = find_comfyui_python(comfyui_path)+ port = _free_port()+ log_path = Path(tempfile.gettempdir()) / f"stablegen-verify-comfyui-{port}.log"+ cmd = [python] + (["-s"] if "python_embed" in python else []) + [+ str(main_py), "--listen", "127.0.0.1", "--port", str(port), "--disable-auto-launch"]+ print(f" Starting ComfyUI on port {port} to read its node list (log: {log_path})...")+ kwargs: Dict[str, Any] = {}+ if sys.platform == "win32":+ kwargs["creationflags"] = 0x00000200 | 0x08000000 # new process group, no console window+ else:+ kwargs["start_new_session"] = True+ info = None+ with open(log_path, "w", encoding="utf-8", errors="replace") as log:+ proc = subprocess.Popen(cmd, cwd=str(comfyui_path), stdout=log, stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL, **kwargs)+ start = time.time()+ reported = 0+ try:+ while time.time() - start < timeout:+ if proc.poll() is not None:+ print(f" ComfyUI exited early (code {proc.returncode}); see the log.")+ break+ info = _fetch_object_info(f"127.0.0.1:{port}", timeout=5)+ if info is not None:+ break+ elapsed = int(time.time() - start)+ if elapsed - reported >= 60:+ reported = elapsed+ print(f" ...still starting ({elapsed} s)")+ time.sleep(3)+ else:+ print(f" ComfyUI did not answer within {timeout} s; see the log.")+ finally:+ _stop_process_tree(proc)+ text = log_path.read_text(encoding="utf-8", errors="replace")+ failed = re.findall(r"\(IMPORT FAILED\)[^\n]*?custom_nodes[\\/]([^\\/\n]+)", text)+ return info, sorted(set(failed))+++def verify_installation(comfyui_path: Path, tags: List[str], server: Optional[str], timeout: int) -> bool:+ print_header("Verifying the installation")+ ok = True+ missing_files: List[str] = []+ items = [item for item in DEPENDENCIES.values() if any(t in item["packages"] for t in tags)]+ for item in items:+ if item["type"] in ("node", "embedded_node"):+ continue+ target = item_target(item, comfyui_path)+ if not item_present(item, comfyui_path):+ print(f" MISSING {item['name']} ({target})")+ missing_files.append(str(target))+ ok = False+ elif item["type"] == "model" and target.with_name(target.name + ".part").exists():+ print(f" WARNING {item['name']}: an unfinished download is next to it")+ required = list(dict.fromkeys(n for t in tags for n in PACKAGE_NODES.get(t, [])))+ if not required:+ emit("verify", ok=ok, missing_files=missing_files, missing_nodes=[], import_failed=[])+ return ok+ if server:+ info, failed = _fetch_object_info(server), []+ if info is None:+ print(f" Could not reach ComfyUI at {server}.")+ else:+ info, failed = start_comfyui_for_verify(comfyui_path, timeout)+ ours = {item["repo_name"] for item in items if item["type"] in ("node", "embedded_node")}+ for folder in failed:+ if folder in ours:+ print(f" FAILED custom node '{folder}' did not import (see the ComfyUI log)")+ others = [folder for folder in failed if folder not in ours]+ if others:+ print(f" Note: other custom nodes failed to import (not StableGen's): {', '.join(others)}")+ failed = [folder for folder in failed if folder in ours]+ if info is None:+ emit("verify", ok=False, missing_files=missing_files, missing_nodes=required, import_failed=failed,+ message="ComfyUI did not answer")+ return False+ missing = [n for n in required if n not in info]+ emit("verify", ok=ok and not missing and not failed, missing_files=missing_files, missing_nodes=missing,+ import_failed=failed)+ for tag in tags:+ absent = [n for n in PACKAGE_NODES.get(tag, []) if n in missing]+ if absent:+ core = set(CORE_NODES.get(tag, []))+ hint = "update ComfyUI" if set(absent) <= core else "the custom node did not load"+ print(f" MISSING {', '.join(absent)} ({hint})")+ print(f" {len(required) - len(missing)} of {len(required)} required node types are registered.")+ return ok and not missing and not failed+++# --- StableGen's own ComfyUI (--create-comfyui) ---+# A private ComfyUI built with uv: its own Python, torch for this GPU and a tested ComfyUI release, all inside one+# folder. Each step records what it installed in stablegen-comfyui.json and is skipped while that is in place, so+# running it again repairs a broken install, and moves an old one to the pins below.+UV_VERSION = "0.13.1"+UV_ASSETS = { # platform -> (release asset, SHA-256, MB)+ "win32": ("uv-x86_64-pc-windows-msvc.zip", "3b2661a463a5baea7f5076ea2b25ab71d77f36a6c0d809e5350651792f80a672", 15),+ "linux": ("uv-x86_64-unknown-linux-gnu.tar.gz",+ "eadd9d27c134ab5ac1ffd4473b97a741407f3ea238288f03121fc4deddf90220", 16),+ "darwin": ("uv-aarch64-apple-darwin.tar.gz", "cfe454573412ff7380d15fc7dae5997ab53ffce72fce0a78e91ddbc84001acd2", 14),+}+# Windows has no Git of its own; elsewhere the system's is used+MINGIT_VERSION = "2.56.0.2"+MINGIT = ("https://github.com/git-for-windows/git/releases/download/v2.56.0.windows.2/MinGit-2.56.0.2-64-bit.zip",+ "da35e72aa21c005a5a0d298cfbae110bc1609a815730ea0dde84b01a1b3cd3be", 38)+COMFYUI_GIT = "https://github.com/Comfy-Org/ComfyUI.git"+COMFYUI_TAG, COMFYUI_COMMIT = "v0.43.0", "426f5eea52a7ece1dd599fff4cb6cd1f352ddd24" # has every CORE_NODES entry+PYTHON_VERSION = "3.12"+TORCH_PINS = ["torch==2.9.0", "torchvision==0.24.0", "torchaudio==2.9.0"]+OWN_MARKER = "stablegen-comfyui.json"+++def nvidia_driver() -> Optional[Tuple[int, int]]:+ """The NVIDIA driver version, or None without an NVIDIA GPU."""+ exe = shutil.which("nvidia-smi")+ if not exe:+ return None+ try:+ out = subprocess.run([exe, "--query-gpu=driver_version", "--format=csv,noheader"], capture_output=True,+ timeout=60, **UTF8_TEXT).stdout+ except (OSError, subprocess.TimeoutExpired):+ return None+ match = re.match(r"\s*(\d+)\.(\d+)", out or "")+ return (int(match.group(1)), int(match.group(2))) if match else None+++def torch_backend(driver: Optional[Tuple[int, int]]) -> str:+ """The newest CUDA build this NVIDIA driver runs (CUDA 13 needs driver 580), else uv's own pick (ROCm, CPU,+ Apple's MPS)."""+ if driver is None:+ return "auto"+ return "cu130" if driver >= (580, 0) else "cu128" if driver >= (570, 0) else "cu126"+++def own_python(comfy: Path) -> Path:+ return comfy / ".venv" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")+++def _uv_env(root: Path) -> Dict[str, str]:+ env = dict(UTF8_ENV, UV_PYTHON_INSTALL_DIR=str(root / "tools" / "python"), UV_CACHE_DIR=str(root / "cache" / "uv"),+ UV_NO_CONFIG="1", UV_PYTHON_PREFERENCE="only-managed", UV_PYTHON_DOWNLOADS="automatic")+ for name in ("VIRTUAL_ENV", "PYTHONHOME", "PYTHONPATH", "CONDA_PREFIX"):+ env.pop(name, None)+ return env+++def _run_step(cmd: List[str], env: Dict[str, str], timeout: int, cwd: Optional[Path] = None) -> Tuple[str, str]:+ print(f" $ {' '.join(cmd)}")+ try:+ result = subprocess.run(cmd, env=env, timeout=timeout, cwd=str(cwd) if cwd else None,+ stdin=subprocess.DEVNULL, **CHILD_IO)+ except subprocess.TimeoutExpired as e:+ return "failed", timed_out(e)+ except OSError as e:+ return "failed", str(e)+ return ("installed", "") if result.returncode == 0 else ("failed", f"exit code {result.returncode}; see the log")+++def _fetch_pinned(url: str, sha: str, target: Path, name: str) -> Tuple[str, str]:+ """Download a release archive and check it against its pinned SHA-256."""+ status, message = download_url(url, target, name)+ if status == "failed":+ return status, message+ if file_sha256(target) != sha:+ target.unlink()+ return "failed", f"{target.name} does not match its published SHA-256; deleted, run again"+ return "installed", ""+++def _extract(archive: Path, target: Path):+ import tarfile+ import zipfile+ if target.exists():+ _rmtree(target)+ target.mkdir(parents=True)+ if archive.suffix == ".zip":+ with zipfile.ZipFile(archive) as z:+ z.extractall(target)+ else:+ with tarfile.open(archive) as t:+ t.extractall(target, **({"filter": "data"} if sys.version_info >= (3, 12) else {}))+++def create_comfyui(root: Path, dry_run: bool = False) -> int:+ """--create-comfyui: StableGen's own ComfyUI in root/ComfyUI, with uv, Python and Git in root/tools."""+ global GIT_EXE, _CURRENT_ITEM+ root = root.expanduser().resolve()+ comfy, tools = root / "ComfyUI", root / "tools"+ if sys.platform not in UV_ASSETS:+ return _fail("platform", f"StableGen cannot set up its own ComfyUI on {sys.platform}")+ root.mkdir(parents=True, exist_ok=True)+ marker_path = root / OWN_MARKER+ try:+ marker = json.loads(marker_path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ marker = {}+ uv_asset, uv_sha, uv_mb = UV_ASSETS[sys.platform]+ uv_exe = tools / "uv" / ("uv.exe" if sys.platform == "win32" else "uv")+ backend = torch_backend(nvidia_driver())+ torch_id = f"{' '.join(TORCH_PINS)} {backend}"+ python = own_python(comfy)+ requirements = comfy / "requirements.txt"+ windows = sys.platform == "win32"+ git_exe = tools / "git" / "cmd" / "git.exe"++ def head() -> Optional[str]:+ if not (comfy / ".git").exists() or not git_executable():+ return None+ try:+ return _git(["rev-parse", "HEAD"], comfy).stdout.strip() or None+ except (OSError, subprocess.TimeoutExpired):+ return None++ # (id, name, MB to download, already in place?)+ if windows:+ GIT_EXE = str(git_exe) if git_exe.is_file() else GIT_EXE+ steps = [+ ("uv", f"uv {UV_VERSION}", uv_mb, marker.get("uv") == UV_VERSION and uv_exe.is_file()),+ ("git", f"Git {MINGIT_VERSION}" if windows else "Git", MINGIT[2] if windows else 0,+ (marker.get("git") == MINGIT_VERSION and git_exe.is_file()) if windows else bool(shutil.which("git"))),+ ("comfyui", f"ComfyUI {COMFYUI_TAG}", 120, head() == COMFYUI_COMMIT),+ ("python", f"Python {PYTHON_VERSION}", 40, marker.get("python") == PYTHON_VERSION and python.is_file()),+ ("torch", f"torch {TORCH_PINS[0].split('==')[1]} ({backend})", 2800,+ marker.get("torch") == torch_id and python.is_file()),+ ("requirements", "ComfyUI's Python packages", 500,+ python.is_file() and requirements.is_file() and marker.get("requirements") == file_sha256(requirements)),+ ]+ need_mb = sum(mb for _, _, mb, present in steps if not present)+ free_mb = shutil.disk_usage(root).free // 1024**2+ print_header("StableGen's own ComfyUI")+ print(f"Folder: {root} (download ~{need_mb / 1024:.1f} GB; {free_mb / 1024:.1f} GB free)")+ emit("plan", packages=["comfyui"], download_mb=need_mb, free_mb=free_mb,+ items=[{"id": i, "name": n, "type": "step", "size_mb": mb, "present": p} for i, n, mb, p in steps])+ # torch and the packages take about three times their download once installed+ if need_mb * 3 > free_mb and not IGNORE_DISK_SPACE:+ message = f"not enough free disk space (~{need_mb * 3 / 1024:.0f} GB needed, {free_mb / 1024:.1f} GB free)"+ if NONINTERACTIVE or not ask(f"{message}. Continue anyway?", default_yes=False, yes_answers=False):+ return _fail("disk_space", message, need_mb=need_mb * 3, free_mb=free_mb)+ if dry_run:+ print("Dry run: nothing was changed.")+ emit("summary", ok=True, rows=[], restart=False, dry_run=True)+ return 0++ env = _uv_env(root)+ rows: List[Tuple[str, str, str]] = []+ for step_id, name, _mb, present in steps:+ _CURRENT_ITEM = step_id+ emit("item", id=step_id, name=name, phase="start")+ print_separator(char='.')+ print(f"Step: {name}")+ if present:+ status, message = "present", ""+ elif step_id == "uv":+ archive = tools / "downloads" / uv_asset+ status, message = _fetch_pinned(f"https://github.com/astral-sh/uv/releases/download/{UV_VERSION}/"+ f"{uv_asset}", uv_sha, archive, uv_asset)+ if status != "failed":+ _extract(archive, tools / "uv-unpacked")+ found = next((tools / "uv-unpacked").rglob(uv_exe.name), None)+ if found is None:+ status, message = "failed", f"no {uv_exe.name} in {uv_asset}"+ else:+ uv_exe.parent.mkdir(parents=True, exist_ok=True)+ os.replace(found, uv_exe)+ os.chmod(uv_exe, 0o755)+ _rmtree(tools / "uv-unpacked")+ marker["uv"] = UV_VERSION+ elif step_id == "git":+ if windows:+ archive = tools / "downloads" / Path(MINGIT[0]).name+ status, message = _fetch_pinned(MINGIT[0], MINGIT[1], archive, archive.name)+ if status != "failed":+ _extract(archive, tools / "git")+ GIT_EXE = str(git_exe)+ marker["git"] = MINGIT_VERSION+ else:+ status, message = "failed", "Git is not installed (for example: sudo apt install git)"+ elif step_id == "comfyui":+ item = {"name": "ComfyUI", "git_url": COMFYUI_GIT, "target_dir_relative": ".", "repo_name": "ComfyUI",+ "commit": COMFYUI_COMMIT, "enforce_pin": True, "license": "GPL-3.0"}+ status, message = clone_git_repo(item, root)+ elif step_id == "python":+ status, message = _run_step([str(uv_exe), "venv", "--seed", "--clear", "--python", PYTHON_VERSION,+ str(comfy / ".venv")], env, PIP_TIMEOUT)+ if status == "installed":+ marker["python"] = PYTHON_VERSION+ elif step_id == "torch":+ status, message = _run_step([str(uv_exe), "pip", "install", "--python", str(python), *TORCH_PINS,+ f"--torch-backend={backend}"], env, PIP_TIMEOUT)+ if status == "installed":+ marker["torch"] = torch_id+ else:+ constraints = root / "torch-constraints.txt" # ComfyUI's unpinned torch must stay the build above+ constraints.write_text("\n".join(TORCH_PINS) + "\n", encoding="utf-8")+ status, message = _run_step([str(uv_exe), "pip", "install", "--python", str(python), "-r",+ str(requirements), "-c", str(constraints), f"--torch-backend={backend}"],+ env, PIP_TIMEOUT)+ if status == "installed":+ marker["requirements"] = file_sha256(requirements)+ print(f" {status}{': ' + message if message else ''}")+ rows.append((name, status, message))+ emit("item", id=step_id, name=name, phase="done", status=status,+ rows=[{"name": name, "status": status, "message": message}])+ marker_path.write_text(json.dumps(dict(marker, comfyui=COMFYUI_TAG, root=str(root)), indent=1),+ encoding="utf-8")+ if status == "failed":+ break+ _CURRENT_ITEM = ""+ ok = print_summary(rows) and len(rows) == len(steps)+ emit("summary", ok=ok, rows=[{"name": n, "status": s, "message": m} for n, s, m in rows], restart=True,+ dry_run=False)+ if ok:+ print(f"ComfyUI is ready in {comfy}. Install packages into it with: installer.py \"{comfy}\" --packages ...")+ return 0 if ok else 1+++# --- Reports for the add-on (--status, --plan) ---+_ENV_REPORT = (+ "import json, sys\n"+ "import importlib.metadata as m\n"+ "v = sys.version_info\n"+ "r = {'version': f'{v.major}.{v.minor}.{v.micro}', 'torch': None, 'cuda': None, 'gpu': None, 'vram_mb': None,\n"+ " 'packages': {}}\n"+ "for name in sys.argv[1:]:\n"+ " try:\n"+ " r['packages'][name] = m.version(name)\n"+ " except Exception:\n"+ " pass\n"+ "try:\n"+ " import torch\n"+ " r['torch'], r['cuda'] = torch.__version__, torch.version.cuda\n"+ " if torch.cuda.is_available():\n"+ " p = torch.cuda.get_device_properties(0)\n"+ " r['gpu'], r['vram_mb'] = p.name, p.total_memory // 2**20\n"+ " elif getattr(torch.backends, 'mps', None) and torch.backends.mps.is_available():\n"+ " r['gpu'] = 'Apple GPU (MPS)'\n"+ "except Exception as e:\n"+ " r['torch_error'] = str(e)[:300]\n"+ "print(json.dumps(r))\n"+)+++def probe_environment(comfyui_path: Path, distributions: List[str] = ()) -> Dict[str, Any]:+ """ComfyUI's Python: version, torch, CUDA, GPU and the installed versions of `distributions`."""+ python = find_comfyui_python(comfyui_path)+ report: Dict[str, Any] = {"path": python,+ "detected": bool(PYTHON_OVERRIDE) or any(c.is_file() for c in python_candidates(comfyui_path))}+ try:+ out = subprocess.run([python, "-c", _ENV_REPORT, *distributions], capture_output=True, env=UTF8_ENV,+ timeout=300, **UTF8_TEXT)+ lines = out.stdout.strip().splitlines()+ report.update(json.loads(lines[-1]) if out.returncode == 0 and lines else+ {"error": (out.stderr.strip().splitlines() or ["no output"])[-1]})+ except (OSError, subprocess.TimeoutExpired, ValueError) as e:+ report["error"] = str(e)+ return report+++def git_executable() -> Optional[str]:+ return GIT_EXE if Path(GIT_EXE).is_file() else shutil.which(GIT_EXE)+++MODEL_TYPES = ("model", "hf_model")+NODE_TYPES = ("node", "embedded_node")+++def removed_with_package(item: Dict[str, Any], nodes: str) -> bool:+ """Whether removing a package deletes this item. Models always; nodes with nodes='all' (a ComfyUI StableGen+ built), or StableGen's own nodes with nodes='stablegen' (someone's own ComfyUI, where the other nodes may+ predate StableGen and serve other workflows)."""+ return item["type"] in MODEL_TYPES or item["type"] in NODE_TYPES and (+ nodes == "all" or nodes == "stablegen" and bool(item.get("stablegen_node")))+++def removal_plan(comfyui_path: Path, tags: List[str], busy_tags: List[str] = (), nodes: str = "") -> List[Path]:+ """What removing these package tags deletes: their model files, Hugging Face model folders and unfinished+ downloads, and the nodes the nodes policy names (removed_with_package). Anything they share stays while another+ package still uses it: one with something of its own on disk, or one being installed (busy_tags). Only paths+ inside the ComfyUI folder."""+ candidates = [i for i in DEPENDENCIES.values() if removed_with_package(i, nodes) and set(i["packages"]) & set(tags)]+ in_use = set(busy_tags) - set(tags)+ for item in DEPENDENCIES.values():+ if removed_with_package(item, nodes) and item not in candidates and item_present(item, comfyui_path):+ in_use |= set(item["packages"])+ root = os.path.normcase(os.path.realpath(str(comfyui_path)))+ paths = []+ for item in candidates:+ if set(item["packages"]) & in_use:+ continue+ target = item_target(item, comfyui_path)+ # a node's setup may download into data_dirs (LATO.2's weights in models/lato2): they go with the node+ extra = [comfyui_path / d for d in item.get("data_dirs", [])] if item["type"] in NODE_TYPES else []+ for path in ((target, Path(str(target) + ".part")) if item["type"] in MODEL_TYPES else (target, *extra)):+ inside = os.path.normcase(os.path.realpath(str(path))).startswith(root + os.sep)+ if inside and path.exists():+ paths.append(path)+ return paths+++def unfinished_downloads(items: List[Dict[str, Any]], comfyui_path: Path) -> List[str]:+ """.part files of these models: downloads that stopped and resume on the next run (a Hugging Face model's are+ inside its folder)."""+ parts = [Path(str(item_target(i, comfyui_path)) + ".part") for i in items if i["type"] == "model"]+ found = [str(p) for p in parts if p.exists()]+ for item in items:+ folder = item_target(item, comfyui_path)+ if item["type"] == "hf_model" and folder.is_dir():+ found += sorted(str(p) for p in folder.rglob("*.part"))+ return found+++def status_report(comfyui_path: Path) -> Dict[str, Any]:+ """--status: everything the add-on shows about this ComfyUI, read without changing anything. 'packages' has+ the menu packages and 'tags' every package tag on its own (what the add-on installs)."""+ return {"comfyui": str(comfyui_path), "main_py": (comfyui_path / "main.py").is_file(),+ "python": probe_environment(comfyui_path), "git": git_executable(), **package_report(comfyui_path)}+++def package_report(comfyui_path: Path) -> Dict[str, Any]:+ """The part of --status about the packages and free space: files only, so the add-on also reads it in-process+ whenever its model lists refresh (ComfyUI's Python is not run)."""+ packages = {}+ for key, package in [*MENU_PACKAGES.items(), *((tag, package_info(tag)) for tag in TAG_LABELS)]:+ items = resolve_items([key])+ present = sum(item_present(i, comfyui_path) for i in items)+ packages[key] = {+ "name": package["name"], "tags": package["tags"], "size_gb": package["size_gb"],+ "notice": package.get("notice"), "present": present, "total": len(items),+ "models_present": sum(item_present(i, comfyui_path) for i in items if i["type"] in MODEL_TYPES),+ "models_total": sum(i["type"] in MODEL_TYPES for i in items),+ "state": "installed" if present == len(items) else "partial" if present else "missing",+ "download_mb": estimate_download_mb(items, package["tags"], comfyui_path),+ "missing_core_nodes": sorted({n for ns in missing_core_nodes(comfyui_path, package["tags"]).values()+ for n in ns}),+ "unfinished": unfinished_downloads(items, comfyui_path),+ }+ return {"free_mb": shutil.disk_usage(comfyui_path).free // 1024**2,+ "packages": {k: v for k, v in packages.items() if k in MENU_PACKAGES},+ "tags": {k: v for k, v in packages.items() if k in TAG_LABELS}}+++def _distribution(spec: str) -> str:+ """'trimesh[easy]>=4' -> 'trimesh'."""+ return re.match(r"[A-Za-z0-9_.\-]+", spec.strip()).group(0)+++def plan_report(comfyui_path: Path, keys: List[str]) -> Dict[str, Any]:+ """--plan: what installing these packages would add to and change in this ComfyUI. Nothing is changed."""+ items = resolve_items(keys)+ tags = tags_for(keys)+ nodes, pip, patches, steps, models = [], [], [], [], []+ git = git_executable()+ for item in items:+ target = item_target(item, comfyui_path)+ if item["type"] == "embedded_node":+ same = all((target / r).is_file() and (target / r).read_text(encoding="utf-8") == text+ for r, text in item["files"].items())+ nodes.append({"id": item["id"], "name": item["name"], "path": str(target),+ "action": "keep" if same else "update" if target.is_dir() else "write",+ "commit": None, "head": None, "license": item.get("license")})+ continue+ if item["type"] != "node":+ part = target.with_name(target.name + ".part")+ state = ("present" if item_present(item, comfyui_path) else+ "resume" if item["type"] == "model" and part.exists() else "download")+ models.append({"id": item["id"], "name": item["name"], "path": str(target),+ "size_mb": item.get("size_mb", 0), "state": state, "license": item.get("license")})+ continue+ pinned = item.get("commit")+ head = None+ if not target.is_dir():+ action = "clone"+ elif not (target / ".git").exists():+ action = "keep" # installed without Git; left as is+ else:+ if git:+ try:+ head = _git(["rev-parse", "HEAD"], target).stdout.strip() or None+ except (OSError, subprocess.TimeoutExpired):+ head = None+ action = ("keep" if not pinned or head == pinned else+ "move to pin" if item.get("enforce_pin") else "different commit")+ nodes.append({"id": item["id"], "name": item["name"], "path": str(target), "action": action,+ "commit": pinned, "head": head, "license": item.get("license")})+ for spec in item.get("pip_packages", []):+ pip.append({"spec": spec, "distribution": _distribution(spec), "for": item["name"]})+ for p in item.get("post_clone_patches", []):+ patches.append({"node": item["name"], "file": p["file"]})+ if item.get("run_install_script"):+ steps.append({"node": item["name"], "step": "runs the node's install.py"})+ if item.get("post_install"):+ steps.append({"node": item["name"], "step": POST_INSTALL[item["post_install"]][0]})+ env = probe_environment(comfyui_path, sorted({p["distribution"] for p in pip}))+ for p in pip:+ p["installed"] = env.get("packages", {}).get(p["distribution"])+ return {"comfyui": str(comfyui_path), "packages": keys,+ "notices": list(dict.fromkeys(package_info(k)["notice"] for k in keys if package_info(k).get("notice"))),+ "nodes": nodes, "pip": pip, "patches": patches, "steps": steps, "models": models,+ "changes_python": bool(pip or steps), "git_missing": bool(nodes) and git is None,+ "python": {k: env.get(k) for k in ("path", "detected", "version", "torch", "error")},+ "download_mb": estimate_download_mb(items, tags, comfyui_path),+ "free_mb": shutil.disk_usage(comfyui_path).free // 1024**2,+ "missing_core_nodes": missing_core_nodes(comfyui_path, tags)}+++def print_json(document: Dict[str, Any]):+ stream = _EVENT_STREAM or sys.stdout+ stream.write(json.dumps(document, indent=1, ensure_ascii=False) + "\n")+ stream.flush()+++# --- Summary ---+STATUS_LABELS ={"installed": "installed", "updated": "updated", "present": "present", "warning": "WARNING",+ "failed": "FAILED"}+++def print_summary(rows: List[Tuple[str, str, str]]) -> bool:+ print_header("Summary")+ for name, status, message in rows:+ print(f" {STATUS_LABELS[status]:<10} {name}" + (f" - {message}" if message else ""))+ counts = {s: sum(1 for _, st, _ in rows if st == s) for s in STATUS_LABELS}+ print_separator()+ print(", ".join(f"{n} {STATUS_LABELS[s].lower()}" for s, n in counts.items() if n))+ return counts["failed"] == 0+++# --- Main Script Logic ---+def choose_packages_interactively(comfyui_path: Path) -> Optional[List[str]]:+ while True:+ display_menu(comfyui_path)+ try:+ choice = input("Enter one or more package numbers (e.g. 3 or 3,8), or q to quit: ").strip().lower()+ except EOFError:+ return None+ if choice == 'q':+ return None+ try:+ return parse_package_choice(choice)+ except ValueError as e:+ print(f"Invalid choice: {e}")+++def main(argv: Optional[List[str]] = None) -> int:+ """The CLI. --events/--json switch to the machine-readable modes; --log moves every other line to a file."""+ global ASSUME_YES, PYTHON_OVERRIDE, NONINTERACTIVE, EVENTS, ACCEPTED_NOTICES, IGNORE_DISK_SPACE, GIT_EXE+ global CHILD_IO, _EVENT_STREAM, _CURRENT_ITEM+ args = parse_args(argv)+ if args.list:+ print_package_list()+ return 0+ EVENTS = args.events+ NONINTERACTIVE = args.events or args.json+ ACCEPTED_NOTICES = {k.strip() for k in args.accept_notices.split(",") if k.strip()}+ IGNORE_DISK_SPACE = args.ignore_disk_space+ if args.git:+ GIT_EXE = str(Path(args.git).resolve())+ # node install scripts and pip (git+ URLs) look for git on PATH too+ path = str(Path(GIT_EXE).parent) + os.pathsep + os.environ.get("PATH", "")+ os.environ["PATH"] = UTF8_ENV["PATH"] = path+ saved = sys.stdout, sys.stderr+ log = None+ try:+ if NONINTERACTIVE:+ _EVENT_STREAM = sys.stdout+ if args.log:+ Path(args.log).parent.mkdir(parents=True, exist_ok=True)+ log = open(args.log, "a", encoding="utf-8", errors="replace", buffering=1)+ sys.stdout = sys.stderr = log+ CHILD_IO = {"stdout": log, "stderr": subprocess.STDOUT}+ elif args.json:+ sys.stdout = sys.stderr # the JSON document is the only thing on stdout+ return _main(args)+ finally:+ sys.stdout, sys.stderr = saved+ if log:+ log.close()+ # in-process callers (tests, the add-on reading reports) get the defaults back+ NONINTERACTIVE = EVENTS = IGNORE_DISK_SPACE = False+ ACCEPTED_NOTICES, CHILD_IO, _EVENT_STREAM, _CURRENT_ITEM, GIT_EXE = set(), {}, None, "", "git"+++def _fail(code: str, message: str, exit_code: int = 1, **details) -> int:+ """An error that ends the run: printed, and reported as an event or JSON document."""+ print(f"ERROR: {message}")+ emit("error", code=code, message=message, **details)+ if NONINTERACTIVE and not EVENTS:+ print_json({"error": code, "message": message, **details})+ return exit_code+++def _main(args: argparse.Namespace) -> int:+ global ASSUME_YES, PYTHON_OVERRIDE, _CURRENT_ITEM+ ASSUME_YES = args.yes+ if args.create_comfyui:+ return create_comfyui(Path(args.create_comfyui), dry_run=args.dry_run)+ if args.python:+ if not Path(args.python).is_file():+ return _fail("python", f"--python '{args.python}' does not exist.", 2)+ PYTHON_OVERRIDE = str(Path(args.python).resolve())+ keys: Optional[List[str]] = None+ if args.packages:+ try:+ keys = parse_package_choice(args.packages)+ except ValueError as e:+ return _fail("args", str(e), 2)+ if NONINTERACTIVE and keys is None and not (args.status or args.verify or args.repair or args.check):+ return _fail("args", "--events and --plan need --packages", 2)++ try:+ comfyui_base_path = get_comfyui_path_from_args(args)+ except SystemExit as e:+ if not NONINTERACTIVE:+ raise+ return _fail("path", str(e.code).replace("Error: ", ""))+ print(f"ComfyUI: {comfyui_base_path}")+ if args.status:+ print_json(status_report(comfyui_base_path))+ return 0+ if args.plan:+ print_json(plan_report(comfyui_base_path, keys))+ return 0+ if not describe_python(comfyui_base_path) and not args.check:+ if NONINTERACTIVE:+ return _fail("python", "ComfyUI's own Python was not found; pass --python")+ if not ask("Continue with this Python?", default_yes=False):+ return 1++ if args.check or args.repair:+ print("Nothing to check or repair: StableGen now uses ComfyUI's native TRELLIS.2 nodes, which have no "+ "environment of their own. The old ComfyUI-TRELLIS2 custom node can be deleted from custom_nodes.")+ return 0++ if args.verify and keys is None:+ tags, partial = installed_tags(comfyui_base_path)+ if partial:+ print("Partly installed, not checked: " + ", ".join(+ f"{TAG_LABELS[t]} ({have} of {total} components)" for t, (have, total) in partial.items()))+ if not tags:+ print("No StableGen package is completely installed here yet.")+ return 1+ print("Checking: " + ", ".join(TAG_LABELS[t] for t in tags))+ return 0 if verify_installation(comfyui_base_path, tags, args.server, args.verify_timeout) else 1++ if keys is None:+ keys = choose_packages_interactively(comfyui_base_path)+ if keys is None:+ print("Exiting installer.")+ return 0++ # License notices can drop packages+ accepted = []+ answers: Dict[str, bool] = {} # a notice shared by two packages (Qwen 2.1 and Turbo) is asked once+ for key in keys:+ package = package_info(key)+ notice = package.get("notice")+ if notice and notice not in answers:+ answers[notice] = show_notice(notice)+ if notice and not answers[notice]:+ print(f"Skipping package {key}.")+ continue+ accepted.append(key)+ refused = NONINTERACTIVE and len(accepted) < len(keys) # reported as error events above+ if not accepted:+ print("Nothing to install.")+ emit("summary", ok=not refused, rows=[], restart=False, dry_run=args.dry_run)+ return 1 if refused else 0+ tags = tags_for(accepted)+ items = resolve_items(accepted)++ print_separator()+ for key in accepted:+ print(f"Package {key}: {package_info(key)['name']}")+ print("Components:")+ for item in items:+ state = "present" if item_present(item, comfyui_base_path) else "to install"+ print(f" - {item['name']} ({state})")+ need_mb = estimate_download_mb(items, tags, comfyui_base_path)+ free_mb = shutil.disk_usage(comfyui_base_path).free // 1024**2+ print(f"Estimated download: ~{need_mb / 1024:.1f} GB; free on this drive: {free_mb / 1024:.1f} GB")+ emit("plan", packages=accepted, download_mb=need_mb, free_mb=free_mb,+ items=[{"id": i["id"], "name": i["name"], "type": i["type"], "size_mb": i.get("size_mb", 0),+ "present": item_present(i, comfyui_base_path)} for i in items])++ for tag, absent in missing_core_nodes(comfyui_base_path, tags).items():+ print(f"WARNING: this ComfyUI lacks {', '.join(absent)}; update ComfyUI before using these models.")+ if any(item["type"] == "node" for item in items) and git_executable() is None:+ return _fail("git_missing", "Git is needed to install custom nodes and was not found on PATH "+ "(https://git-scm.com).")+ if need_mb > free_mb:+ message = f"not enough free disk space ({need_mb / 1024:.1f} GB needed, {free_mb / 1024:.1f} GB free)"+ if IGNORE_DISK_SPACE:+ print(f"WARNING: {message}; continuing (--ignore-disk-space).")+ elif NONINTERACTIVE:+ return _fail("disk_space", message, need_mb=need_mb, free_mb=free_mb)+ else:+ print(f"ERROR: {message}.")+ if not ask("Continue anyway?", default_yes=False, yes_answers=False):+ return 1++ if args.dry_run:+ print("Dry run: nothing was changed.")+ emit("summary", ok=not refused, rows=[], restart=False, dry_run=True)+ if args.verify:+ return 0 if verify_installation(comfyui_base_path, tags, args.server, args.verify_timeout) else 1+ return 1 if refused else 0+ if not NONINTERACTIVE and not ask("Proceed with checking/installing these components?"):+ print("Installation cancelled.")+ return 0++ rows: List[Tuple[str, str, str]] = []+ for item_details in items:+ print_separator(char='.')+ print(f"Processing: {item_details['name']}")+ _CURRENT_ITEM = item_details["id"]+ emit("item", id=item_details["id"], name=item_details["name"], phase="start")+ if item_details["type"] == "node":+ item_rows = install_node(item_details, comfyui_base_path, args.update_nodes)+ elif item_details["type"] == "embedded_node":+ item_rows = [(item_details["name"],) + install_embedded_node(item_details, comfyui_base_path)]+ elif item_details["type"] == "model":+ item_rows = [(item_details["name"],) + download_file(item_details, comfyui_base_path, args.verify_hashes)]+ else:+ status, message = download_hf_model(item_details, comfyui_base_path, args.verify_hashes)+ print(f" {status}{': ' + message if message else ''}")+ item_rows = [(item_details["name"], status, message)]+ rows.extend(item_rows)+ statuses = [status for _, status, _ in item_rows]+ worst = next((s for s in ("failed", "warning", "updated", "installed") if s in statuses), "present")+ emit("item", id=item_details["id"], name=item_details["name"], phase="done", status=worst,+ rows=[{"name": n, "status": s, "message": m} for n, s, m in item_rows])+ _CURRENT_ITEM = ""++ ok = print_summary(rows) and not refused+ node_names = {item["name"] for item in items if item["type"] in ("node", "embedded_node")}+ restart = any(status in ("installed", "updated") and name in node_names for name, status, _ in rows)+ if restart:+ print("Restart ComfyUI so it loads new or updated custom nodes.")+ emit("summary", ok=ok, rows=[{"name": n, "status": s, "message": m} for n, s, m in rows], restart=restart,+ dry_run=False)+ if args.verify:+ ok = verify_installation(comfyui_base_path, tags, args.server, args.verify_timeout) and ok+ return 0 if ok else 1+++if __name__ == "__main__":+ # stdout carries only JSON in the machine-readable modes+ if not TQDM_AVAILABLE and not {"--events", "--json", "--status", "--plan"} & set(sys.argv):+ print("NOTE: 'tqdm' is not installed, so downloads show a progress line instead of a bar.")+ sys.exit(main())diff --git a/stablegen/setup/jobs.py b/stablegen/setup/jobs.pynew file mode 100644index 0000000..0d514cc--- /dev/null+++ b/stablegen/setup/jobs.py@@ -0,0 +1,209 @@+"""The installer, run in the background for the add-on: reports (--status, --plan) and installs (--events), one+install at a time, with the events turned into state the preferences draw. No bpy here.++Blender's own Python runs the installer (it only needs the standard library); --python always names ComfyUI's,+or the installer would fall back to Blender's.+"""+import json+import subprocess+import sys+import threading+import time+from collections import deque+from pathlib import Path+from typing import Any, Deque, Dict, List, Optional++from . import installer++INSTALLER = Path(__file__).with_name("installer.py")+TEXT = dict(text=True, encoding="utf-8", errors="replace")+SPEED_WINDOW = 8.0 # seconds the download speed averages over+++def installer_command(*args: str, python: Optional[str] = None) -> List[str]:+ return [python or sys.executable, "-I", "-u", str(INSTALLER), *args]+++def _hidden() -> Dict[str, Any]:+ return ({"creationflags": 0x00000200 | 0x08000000} if sys.platform == "win32" # new group, no window+ else {"start_new_session": True})+++def run_report(args: List[str], timeout: float = 600, python: Optional[str] = None) -> Dict[str, Any]:+ """Run --status or --plan (blocking; call it on a thread) and return its JSON document. Failures come back+ as {"error": code, "message": text}."""+ try:+ result = subprocess.run(installer_command(*args, "--json", python=python), capture_output=True,+ stdin=subprocess.DEVNULL, timeout=timeout, **TEXT, **_hidden())+ except (OSError, subprocess.TimeoutExpired) as e:+ return {"error": "run", "message": str(e)}+ try:+ return json.loads(result.stdout)+ except ValueError:+ lines = (result.stderr or result.stdout).strip().splitlines()+ return {"error": "run", "message": lines[-1] if lines else f"exit code {result.returncode}"}+++class InstallerJob:+ """One installer run with --events. start() returns at once; a thread reads the events."""++ def __init__(self, title: str, args: List[str], log_path, python: Optional[str] = None, kind: str = "install",+ folder: str = "", tags: Optional[List[str]] = None):+ self.title = title+ self.kind = kind # 'install' (packages) or 'create' (StableGen's own ComfyUI)+ self.folder = folder # the ComfyUI folder it works on+ self.tags = list(tags or [])+ self.log_path = Path(log_path)+ self.cmd = installer_command(*args, "--events", "--log", str(self.log_path), python=python)+ self.items: Dict[str, Dict[str, Any]] = {} # id -> name, type, size_mb, present, phase, status, ...+ self.order: List[str] = []+ self.current: Optional[str] = None+ self.errors: List[Dict[str, Any]] = []+ self.summary: Optional[Dict[str, Any]] = None+ self.verify: Optional[Dict[str, Any]] = None+ self.download_mb = 0+ self.returncode: Optional[int] = None+ self.cancelled = False+ self.started = 0.0+ self.finished = 0.0+ self.proc: Optional[subprocess.Popen] = None+ self._thread: Optional[threading.Thread] = None+ self.bytes_done = 0 # downloaded in this run (what a resumed .part already had doesn't count)+ self._last_done: Dict[tuple, int] = {}+ self._samples: Deque[tuple] = deque() # (monotonic time, bytes_done) over the last SPEED_WINDOW++ @property+ def running(self) -> bool:+ return self.proc is not None and self.returncode is None++ @property+ def ok(self) -> bool:+ return (self.returncode == 0 and not self.errors and not self.cancelled+ and bool(self.summary and self.summary.get("ok")))++ def start(self):+ self.log_path.parent.mkdir(parents=True, exist_ok=True)+ self.started = time.time()+ self.proc = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL, **TEXT, **_hidden())+ self._thread = threading.Thread(target=self._read, daemon=True)+ self._thread.start()+ return self++ def _read(self):+ for line in self.proc.stdout:+ if line.startswith("@sg "):+ try:+ self.handle(json.loads(line[4:]))+ except ValueError:+ pass+ self.returncode = self.proc.wait()+ self.finished = time.time()++ def handle(self, event: Dict[str, Any]):+ kind = event.get("event")+ if kind == "plan":+ self.download_mb = event.get("download_mb", 0)+ for item in event.get("items", []):+ self.items[item["id"]] = dict(item, phase="waiting", status=None, done=0, total=0, file="")+ self.order.append(item["id"])+ elif kind == "item":+ item = self.items.setdefault(event["id"], {"name": event.get("name", event["id"]), "size_mb": 0,+ "present": False, "done": 0, "total": 0, "file": ""})+ item["phase"] = event["phase"]+ if event["phase"] == "start":+ self.current = event["id"]+ else:+ item["status"], item["rows"] = event.get("status"), event.get("rows", [])+ if self.current == event["id"]:+ self.current = None+ elif kind == "progress":+ item = self.items.get(event.get("id"))+ if item is not None:+ item["done"], item["total"], item["file"] = event["done"], event["total"], event.get("file", "")+ key = (event.get("id"), event.get("file", ""))+ last = self._last_done.get(key)+ if last is not None and event["done"] >= last:+ self.bytes_done += event["done"] - last+ self._last_done[key] = event["done"]+ now = time.monotonic()+ self._samples.append((now, self.bytes_done))+ while self._samples and now - self._samples[0][0] > SPEED_WINDOW:+ self._samples.popleft()+ elif kind == "error":+ self.errors.append(event)+ elif kind == "summary":+ self.summary = event+ elif kind == "verify":+ self.verify = event++ def cancel(self):+ if self.running:+ self.cancelled = True+ installer._stop_process_tree(self.proc)++ def wait(self, timeout: Optional[float] = None) -> Optional[int]:+ if self._thread:+ self._thread.join(timeout)+ return self.returncode++ # --- for drawing ---+ def progress(self) -> float:+ """0..1 over what this run downloads: finished items plus the current file's share of its item."""+ sizes = {i: max(1, item.get("size_mb", 0)) for i, item in self.items.items() if not item.get("present")}+ total = sum(sizes.values())+ if not total:+ return 1.0 if self.returncode is not None else 0.0+ done = 0.0+ for i, size in sizes.items():+ item = self.items[i]+ if item["phase"] == "done":+ done += size+ elif i == self.current and item.get("total"):+ done += size * min(1.0, item["done"] / item["total"])+ return min(1.0, done / total)++ def speed(self) -> Optional[float]:+ """Bytes per second over the last SPEED_WINDOW seconds, falling while nothing arrives; None before a+ download has reported twice (git, pip and the checks don't report progress)."""+ if not self.running or len(self._samples) < 2 or time.monotonic() - self._samples[-1][0] > SPEED_WINDOW:+ return None+ start_time, start_bytes = self._samples[0]+ elapsed = max(time.monotonic(), self._samples[-1][0]) - start_time+ return (self._samples[-1][1] - start_bytes) / elapsed if elapsed > 0.5 else None++ def total_mb(self) -> float:+ return sum(i.get("size_mb", 0) for i in self.items.values() if not i.get("present"))++ def size_text(self) -> str:+ """'5.1 of 14.3 GB' over the whole run, or 'Preparing…' before its plan arrives."""+ total = self.total_mb()+ return f"{self.progress() * total / 1024:.1f} of {total / 1024:.1f} GB" if total else "Preparing…"++ def rate_text(self) -> str:+ """'42 MB/s · 4 min left' while downloading, else ''."""+ speed = self.speed()+ if not speed:+ return ""+ left = self.total_mb() * 1024**2 * (1 - self.progress()) / speed+ rate = f"{speed / 1024**2:.0f} MB/s" if speed >= 10 * 1024**2 else f"{speed / 1024**2:.1f} MB/s"+ when = (f"{int(left // 3600)} h {int(left % 3600 // 60)} min left" if left >= 3600 else+ f"{left / 60:.0f} min left" if left >= 90 else "under a minute left" if left >= 5 else "")+ return f"{rate} · {when}" if when else rate++ def status_line(self) -> str:+ if self.cancelled:+ return "Cancelled; downloads resume next time"+ if self.errors:+ return self.errors[0].get("message", "failed")+ if self.returncode is not None:+ failed = [r for r in (self.summary or {}).get("rows", []) if r["status"] == "failed"]+ if failed:+ return f"{failed[0]['name']}: {failed[0]['message']}"+ return "Done" if self.ok else f"Stopped (exit code {self.returncode})"+ item = self.items.get(self.current)+ if not item:+ return "Preparing…"+ if item.get("total"):+ return f"{item['name']}: {item['done'] / 1024**3:.1f} of {item['total'] / 1024**3:.1f} GB"+ return f"{item['name']}…"diff --git a/stablegen/setup/operators.py b/stablegen/setup/operators.pynew file mode 100644index 0000000..2bf4cc0--- /dev/null+++ b/stablegen/setup/operators.py@@ -0,0 +1,367 @@+"""Operators behind the ComfyUI section of StableGen's preferences."""+import bpy # pylint: disable=import-error++from . import runtime+++class STABLEGEN_OT_comfy_start(bpy.types.Operator):+ """Start ComfyUI hidden in the background (or connect to the one already running for this folder)"""+ bl_idname = "stablegen.comfy_start"+ bl_label = "Start ComfyUI"++ @classmethod+ def poll(cls, context):+ if runtime.comfy().state in ('starting', 'running'):+ cls.poll_message_set("ComfyUI is already running")+ return False+ return True++ def execute(self, context):+ if runtime.comfy().state == 'unresponsive':+ runtime.stop()+ error = runtime.start()+ if error:+ self.report({'ERROR'}, error)+ return {'CANCELLED'}+ self.report({'INFO'}, f"Starting ComfyUI at {runtime.comfy().address}")+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_stop(bpy.types.Operator):+ """Stop the ComfyUI StableGen started (one started outside StableGen keeps running)"""+ bl_idname = "stablegen.comfy_stop"+ bl_label = "Stop ComfyUI"++ @classmethod+ def poll(cls, context):+ return runtime.comfy().state in ('starting', 'running', 'unresponsive')++ def execute(self, context):+ owned = runtime.comfy().owned+ runtime.stop()+ if owned:+ context.preferences.addons[runtime.ADDON_PKG].preferences.server_online = False+ self.report({'INFO'}, "ComfyUI stopped" if owned else "Disconnected; that ComfyUI was not started by StableGen")+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_restart(bpy.types.Operator):+ """Restart the ComfyUI StableGen started, so it loads nodes installed since it started"""+ bl_idname = "stablegen.comfy_restart"+ bl_label = "Restart ComfyUI"++ @classmethod+ def poll(cls, context):+ if not runtime.comfy().owned:+ cls.poll_message_set("StableGen didn't start this ComfyUI, so it won't restart it: restart it yourself")+ return False+ return True++ def execute(self, context):+ runtime.stop()+ context.preferences.addons[runtime.ADDON_PKG].preferences.server_online = False+ error = runtime.start()+ if error:+ self.report({'ERROR'}, error)+ return {'CANCELLED'}+ runtime.restart_needed = None+ self.report({'INFO'}, f"Restarting ComfyUI at {runtime.comfy().address}")+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_open_log(bpy.types.Operator):+ """Open the log of the last installer run or ComfyUI start"""+ bl_idname = "stablegen.comfy_open_log"+ bl_label = "Open Log"++ which: bpy.props.EnumProperty(items=[('COMFYUI', "ComfyUI", ""), ('INSTALL', "Install", "")],+ default='COMFYUI') # type: ignore++ def execute(self, context):+ if self.which == 'INSTALL' and runtime.job:+ path = runtime.job.log_path+ else:+ path = runtime.comfy().log_path+ if not path.is_file():+ self.report({'WARNING'}, "No log yet")+ return {'CANCELLED'}+ bpy.ops.wm.path_open(filepath=str(path))+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_refresh(bpy.types.Operator):+ """Read again which models are installed and which Python and GPU ComfyUI uses"""+ bl_idname = "stablegen.comfy_refresh"+ bl_label = "Refresh"++ def execute(self, context):+ if runtime.comfy_folder() is None:+ self.report({'WARNING'}, "Choose the ComfyUI folder first")+ return {'CANCELLED'}+ runtime.refresh_status()+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_install(bpy.types.Operator):+ """Download and install these models and the nodes they need into ComfyUI; while another install runs, it waits+ in the queue"""+ bl_idname = "stablegen.comfy_install"+ bl_label = "Install"++ tags: bpy.props.StringProperty(options={'HIDDEN'}) # type: ignore++ @classmethod+ def poll(cls, context):+ if runtime.job and runtime.job.running and runtime.job.kind == "create":+ cls.poll_message_set("StableGen's own ComfyUI is still installing")+ return False+ if runtime.comfy_folder() is None:+ cls.poll_message_set("Choose the ComfyUI folder first")+ return False+ return True++ def execute(self, context):+ if not bpy.app.online_access:+ self.report({'ERROR'}, "Allow online access in Blender's preferences (System) to download models")+ return {'CANCELLED'}+ runtime.begin_install([t for t in self.tags.split(",") if t])+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_remove(bpy.types.Operator):+ """Delete it from ComfyUI: its models and unfinished downloads, and in StableGen's own ComfyUI its nodes.+ What another installed package uses stays; in your own ComfyUI folder the nodes stay too"""+ bl_idname = "stablegen.comfy_remove"+ bl_label = "Remove"++ tags: bpy.props.StringProperty(options={'HIDDEN'}) # type: ignore+ title: bpy.props.StringProperty(options={'HIDDEN'}) # type: ignore++ @classmethod+ def poll(cls, context):+ if runtime.job and runtime.job.running and runtime.job.kind == "create":+ cls.poll_message_set("StableGen's own ComfyUI is still installing")+ return False+ return True++ def invoke(self, context, event):+ if runtime.busy_tags() & set(self._tags()):+ self.report({'WARNING'}, "It is installing or in the queue; cancel that first")+ return {'CANCELLED'}+ paths = runtime.removable(self._tags())+ if not paths:+ self.report({'INFO'}, "Nothing of it to remove: another installed package uses its files")+ return {'CANCELLED'}+ from .packages import size_text+ size = size_text(sum(runtime.path_size(p) for p in paths) / 1024**2)+ nodes = sum(p.parent.name == "custom_nodes" for p in paths)+ files = len(paths) - nodes+ unfinished = sum(p.suffix == ".part" for p in paths)+ parts = ([f"{files} model file{'s' if files != 1 else ''}" + (f" ({unfinished} unfinished)" if unfinished+ else "")] if files else [])+ parts += [f"{nodes} node{'s' if nodes != 1 else ''}"] if nodes else []+ kept = runtime.kept_nodes(self._tags(), paths)+ stays = " Its other nodes stay." if kept and nodes else " Its nodes stay." if kept else ""+ return context.window_manager.invoke_confirm(+ self, event, title=f"Remove {self.title or 'it'}?",+ message=f"Deletes {' and '.join(parts)}, {size}.{stays}", confirm_text="Remove", icon='WARNING')++ def execute(self, context):+ removed, failed = runtime.remove(self._tags())+ from .packages import size_text+ if failed:+ self.report({'WARNING'}, f"Removed {size_text(removed / 1024**2)}; {len(failed)} in use by ComfyUI "+ f"stayed (stop it and remove again)")+ else:+ self.report({'INFO'}, f"Removed {size_text(removed / 1024**2)}")+ return {'FINISHED'}++ def _tags(self):+ return [t for t in self.tags.split(",") if t]+++class STABLEGEN_OT_comfy_unqueue(bpy.types.Operator):+ """Take it out of the install queue"""+ bl_idname = "stablegen.comfy_unqueue"+ bl_label = "Remove from Queue"++ tags: bpy.props.StringProperty(options={'HIDDEN'}) # type: ignore++ def execute(self, context):+ runtime.unqueue([t for t in self.tags.split(",") if t])+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_confirm_install(bpy.types.Operator):+ """Accept the license notices and changes listed above and start installing"""+ bl_idname = "stablegen.comfy_confirm_install"+ bl_label = "Install"++ def execute(self, context):+ error = runtime.confirm_install()+ if error:+ self.report({'ERROR'}, error)+ return {'CANCELLED'}+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_cancel_review(bpy.types.Operator):+ """Don't install"""+ bl_idname = "stablegen.comfy_cancel_review"+ bl_label = "Cancel"++ def execute(self, context):+ runtime.cancel_review()+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_create(bpy.types.Operator):+ """Download and set up StableGen's own ComfyUI in the install folder: uv, Python 3.12, torch for your GPU and a+ tested ComfyUI release. Running it again repairs or updates it"""+ bl_idname = "stablegen.comfy_create"+ bl_label = "Install ComfyUI"++ @classmethod+ def poll(cls, context):+ if runtime.job and runtime.job.running:+ cls.poll_message_set("An install is running")+ return False+ if not context.preferences.addons[runtime.ADDON_PKG].preferences.comfy_root:+ cls.poll_message_set("Choose the install folder first")+ return False+ return True++ def execute(self, context):+ error = runtime.create_own()+ if error:+ self.report({'ERROR'}, error)+ return {'CANCELLED'}+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_choose_folder(bpy.types.Operator):+ """Choose the folder"""+ bl_idname = "stablegen.comfy_choose_folder"+ bl_label = "Choose Folder"+ bl_options = {'INTERNAL'}++ target: bpy.props.EnumProperty(items=[('ROOT', "Install folder", "Where StableGen keeps its own ComfyUI"),+ ('LOCAL', "ComfyUI folder", "Your ComfyUI folder")],+ default='ROOT', options={'HIDDEN'}) # type: ignore+ directory: bpy.props.StringProperty(subtype='DIR_PATH') # type: ignore++ def invoke(self, context, event):+ p = context.preferences.addons[runtime.ADDON_PKG].preferences+ self.directory = p.comfy_root if self.target == 'ROOT' else p.comfy_local_path+ context.window_manager.fileselect_add(self)+ return {'RUNNING_MODAL'}++ def execute(self, context):+ p = context.preferences.addons[runtime.ADDON_PKG].preferences+ setattr(p, "comfy_root" if self.target == 'ROOT' else "comfy_local_path", self.directory)+ runtime.redraw()+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_set_address(bpy.types.Operator):+ """Set the address of the ComfyUI server"""+ bl_idname = "stablegen.comfy_set_address"+ bl_label = "ComfyUI Server"+ bl_options = {'INTERNAL'}++ address: bpy.props.StringProperty(name="Address", description="Host and port, for example 127.0.0.1:8188") # type: ignore++ def invoke(self, context, event):+ self.address = context.preferences.addons[runtime.ADDON_PKG].preferences.server_address+ return context.window_manager.invoke_props_dialog(self)++ def execute(self, context):+ context.preferences.addons[runtime.ADDON_PKG].preferences.server_address = self.address.strip()+ context.preferences.is_dirty = True # saved on quit, like a change in the preferences+ runtime.redraw()+ return {'FINISHED'}+++class STABLEGEN_OT_dismiss_setup_card(bpy.types.Operator):+ """Hide the setup card; the server address stays where it is (change it in StableGen's preferences)"""+ bl_idname = "stablegen.dismiss_setup_card"+ bl_label = "I have a server"++ def execute(self, context):+ from ..ui import studio_tips+ from .prefs_ui import SETUP_CARD+ studio_tips.dismiss(SETUP_CARD)+ runtime.redraw()+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_copy_install_command(bpy.types.Operator):+ """Copy the command that installs this model on the server: run it there with installer.py from the StableGen+ repository"""+ bl_idname = "stablegen.comfy_copy_install_command"+ bl_label = "Copy Install Command"++ tags: bpy.props.StringProperty(options={'HIDDEN'}) # type: ignore++ def execute(self, context):+ command = f'python installer.py "<ComfyUI folder>" --packages {self.tags}'+ context.window_manager.clipboard = command+ self.report({'INFO'}, f"Copied: {command} (run it on the server)")+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_use_server_folder(bpy.types.Operator):+ """Let StableGen install models into the ComfyUI running on this computer: use its folder (Use my ComfyUI+ folder) and open the setup"""+ bl_idname = "stablegen.comfy_use_server_folder"+ bl_label = "Use This ComfyUI's Folder"++ def execute(self, context):+ from .comfy_process import server_folder+ p = context.preferences.addons[runtime.ADDON_PKG].preferences+ folder = server_folder(p.server_address)+ if folder is not None:+ p.comfy_local_path = str(folder)+ p.comfy_mode = 'LOCAL'+ from ..ui import studio+ for session in studio._sessions.values():+ session.setup_change = True # the choices stay open, to confirm the folder with Use+ bpy.ops.stablegen.open_setup()+ if folder is None:+ self.report({'WARNING'}, "Couldn't ask this ComfyUI for its folder: choose it")+ return {'FINISHED'}+++class STABLEGEN_OT_comfy_cancel_install(bpy.types.Operator):+ """Stop this install; finished files stay, downloads resume the next time, and the queue goes on"""+ bl_idname = "stablegen.comfy_cancel_install"+ bl_label = "Cancel Install"++ @classmethod+ def poll(cls, context):+ return bool(runtime.job and runtime.job.running)++ def execute(self, context):+ runtime.cancel_job()+ return {'FINISHED'}+++SETUP_CLASSES = (+ STABLEGEN_OT_comfy_start,+ STABLEGEN_OT_comfy_stop,+ STABLEGEN_OT_comfy_restart,+ STABLEGEN_OT_comfy_open_log,+ STABLEGEN_OT_comfy_refresh,+ STABLEGEN_OT_comfy_install,+ STABLEGEN_OT_comfy_remove,+ STABLEGEN_OT_comfy_unqueue,+ STABLEGEN_OT_comfy_confirm_install,+ STABLEGEN_OT_comfy_cancel_review,+ STABLEGEN_OT_comfy_create,+ STABLEGEN_OT_comfy_choose_folder,+ STABLEGEN_OT_comfy_set_address,+ STABLEGEN_OT_dismiss_setup_card,+ STABLEGEN_OT_comfy_copy_install_command,+ STABLEGEN_OT_comfy_use_server_folder,+ STABLEGEN_OT_comfy_cancel_install,+)diff --git a/stablegen/setup/packages.py b/stablegen/setup/packages.pynew file mode 100644index 0000000..fb96fd1--- /dev/null+++ b/stablegen/setup/packages.py@@ -0,0 +1,136 @@+"""The models the setup offers to install: rows grouped by what they are for, each one or more installer package+tags (installer.py installs by tag), with the licenses their files come under. Also the tags each architecture+needs, for the missing-model hint. No bpy here."""+import sys+from typing import Dict, Iterator, List, Optional, Sequence, Tuple++from . import installer++# Packages whose nodes only build on NVIDIA's CUDA: not offered on macOS+CUDA_ONLY = {"qwen_nunchaku", "skintokens", "lato2"}++ROWS: Tuple[Tuple[str, Tuple[str, ...], str, str], ...] = (+ # group, tags, model, what it does+ ("Texturing", ("core", "preset_essentials", "checkpoint_realvis"), "SDXL", "fast, fits 8 GB GPUs"),+ ("Texturing", ("extended_optional",), "SDXL extras", "more LoRAs and ControlNets"),+ ("Texturing", ("qwen_image_21",), "Qwen Image 2.1", "best quality"),+ ("Texturing", ("qwen_core",), "Qwen Image Edit", "2509 GGUF Q3_K_M"),+ # the presets use Qwen Image Edit's own 4-step LoRA; these are the 8-step one, to pick by hand, and base Qwen Image's+ ("Texturing", ("qwen_extras",), "Qwen Image Edit Lightning", "optional 8-step LoRAs"),+ ("Texturing", ("qwen_nunchaku",), "Qwen Image Edit Nunchaku", "4-bit, for smaller GPUs"),+ ("Experimental", ("qwen_image_21_turbo",), "Qwen Image 2.1 Turbo", "few-step sampling"),+ ("Experimental", ("moss_image",), "MOSS Image", "with depth control"),+ ("Experimental", ("fibo_edit",), "FIBO 2.0 Edit", "Bria's edit model"),+ ("Deprecated", ("flux2_klein",), "FLUX.2 Klein", "no longer supported"),+ ("3D, maps and rigging", ("trellis2",), "TRELLIS.2", "image to 3D"),+ ("3D, maps and rigging", ("pbr_marigold", "pbr_stabledelight"), "Marigold + StableDelight", "PBR maps"),+ ("3D, maps and rigging", ("pbr_marigold_v2",), "Marigold V2", "albedo and normal maps"),+ ("3D, maps and rigging", ("skintokens",), "SkinTokens", "auto-rigging"),+ ("3D, maps and rigging", ("lato2",), "LATO.2", "low-poly remesh"),+)++# What each architecture needs on the server (a checkpoint of the user's own counts for SDXL)+ARCH_TAGS: Dict[str, Tuple[str, ...]] = {+ 'sdxl': ("core", "preset_essentials"),+ 'qwen_image_edit': ("qwen_core",),+ 'qwen_image_21': ("qwen_image_21",),+ 'qwen_image_21_turbo': ("qwen_image_21_turbo",),+ 'moss_image': ("moss_image",),+ 'fibo_edit': ("fibo_edit",),+ 'flux2_klein': ("flux2_klein",),+ 'trellis2': ("trellis2",),+}++# The installer's license notes, short enough for a row; None leaves one out+LICENSE_NAMES = {+ "Qwen Research License (non-commercial)": "Qwen Research, non-commercial",+ "CC BY-NC 4.0 (non-commercial)": "CC BY-NC 4.0, non-commercial",+ "Apache-2.0": "Apache 2.0",+ "DINOv3 License": "DINOv3",+ "GPL-3.0 (SkinTokens code and weights: MIT)": "MIT",+ "GPL-3.0 (LATO.2 code and weights: MIT; DINOv2: Apache 2.0)": "MIT + Apache 2.0",+ "Unknown (User to verify)": None,+}+LICENSE_SHARE = 0.05 # a license under 5% of a row's download is left out (the notices cover the details)+++def visible_rows(deprecated: bool = False, experimental: bool = True,+ platform: str = sys.platform) -> Iterator[Tuple[str, Tuple[str, ...], str, str]]:+ for group, tags, title, purpose in ROWS:+ if (group == "Deprecated" and not deprecated) or (group == "Experimental" and not experimental):+ continue+ if platform == "darwin" and CUDA_ONLY & set(tags):+ continue+ yield group, tags, title, purpose+++def license_text(tags: Sequence[str]) -> str:+ """'MIT + DINOv3': the licenses of a row's model files, largest share first (its nodes' when it has none)."""+ items = [i for i in installer.DEPENDENCIES.values() if set(i["packages"]) & set(tags)]+ models = [i for i in items if i["type"] in ("model", "hf_model")] or items+ shares: Dict[str, float] = {}+ for item in models:+ name = LICENSE_NAMES.get(item["license"], item["license"].split(" (")[0])+ if name:+ shares[name] = shares.get(name, 0) + max(1, item.get("size_mb", 0))+ total = sum(shares.values()) or 1+ names = [n for n, mb in sorted(shares.items(), key=lambda kv: -kv[1]) if mb / total >= LICENSE_SHARE]+ return " + ".join(names[:2])+++def row_state(tags: Sequence[str], report: Optional[dict]) -> Dict[str, object]:+ """'installed', 'partial', 'missing' or 'unknown' (no report yet), with the sizes to show and the unfinished+ downloads (.part files) a partial one left."""+ entries = [(report or {}).get("tags", {}).get(t) for t in tags]+ if not report or any(e is None for e in entries):+ return {"state": "unknown", "download_mb": 0, "size_mb": 0, "missing_core_nodes": [], "unfinished": []}+ states = {e["state"] for e in entries}+ state = "installed" if states == {"installed"} else "missing" if states == {"missing"} else "partial"+ unfinished: List[str] = list(dict.fromkeys(path for e in entries for path in e.get("unfinished", [])))+ models_present = sum(e.get("models_present", 0) for e in entries)+ only_nodes = all(e["state"] == "missing" or (e.get("models_total", 0) and not e.get("models_present", 0))+ for e in entries)+ if state == "partial" and only_nodes and not unfinished:+ state = "missing" # only its nodes are there (already in the ComfyUI, or left after removing it)+ return {"state": state,+ "download_mb": sum(e["download_mb"] for e in entries),+ "size_mb": sum(e["size_gb"] for e in entries) * 1024,+ "missing_core_nodes": sorted({n for e in entries for n in e.get("missing_core_nodes", [])}),+ "unfinished": unfinished, "models_present": models_present}+++def missing_for_architecture(architecture: str, report: Optional[dict]) -> Optional[Tuple[Tuple[str, ...], str]]:+ """(tags, title) to install when this architecture's packages are not complete in report, else None."""+ tags = ARCH_TAGS.get(architecture)+ if not tags or not report or row_state(tags, report)["state"] in ("installed", "unknown"):+ return None+ title = next((t for _, row_tags, t, _ in ROWS if set(tags) <= set(row_tags)), architecture)+ return tags, title+++def removable_state(tags: Sequence[str], state: Dict[str, object], nodes: str = "") -> bool:+ """A row with something to remove on disk: models or unfinished downloads, or nodes the nodes policy removes+ (installer.removed_with_package)."""+ if state.get("models_present") or state["unfinished"]:+ return True+ return state["state"] in ("installed", "partial") and any(+ i["type"] in installer.NODE_TYPES and installer.removed_with_package(i, nodes)+ for i in installer.DEPENDENCIES.values() if set(i["packages"]) & set(tags))+++def queue_text(place: int) -> str:+ """'next', '2nd in line', ...: where a queued install waits (0 is next)."""+ if place == 0:+ return "next"+ n = place + 1+ return f"{n}{'th' if 10 <= n % 100 <= 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')} in line"+++def size_text(mb: float) -> str:+ return f"{mb / 1024:.1f} GB" if mb >= 1024 else f"{max(1, round(mb))} MB"+++def meta_text(purpose: str, tags: Sequence[str], size_mb: float) -> str:+ """'Image to 3D · MIT + DINOv3 · 13.1 GB': what a row does, its license and its size."""+ parts = [purpose[:1].upper() + purpose[1:], license_text(tags)] + ([size_text(size_mb)] if size_mb else [])+ return " · ".join(p for p in parts if p)diff --git a/stablegen/setup/prefs_ui.py b/stablegen/setup/prefs_ui.pynew file mode 100644index 0000000..ec0db38--- /dev/null+++ b/stablegen/setup/prefs_ui.py@@ -0,0 +1,422 @@+"""The ComfyUI and Models sections of StableGen's preferences (layout A of ref/setup-ui-20261103).++Where ComfyUI comes from (StableGen's own, a folder of the user's, or a remote server), its status with Start and+Stop, and the models to install with their progress. The install waiting for review lists its license notices+and, for a ComfyUI of the user's, what it changes in that ComfyUI's Python.++Drawn with Blender's own widgets the way its preference pages are: collapsible sub-panels, a label column on the+left, secondary text greyed, compact buttons on the right, and the models in two columns.+"""+from . import installer, packages, runtime++STATE_TEXT = {'stopped': ("Stopped", 'RADIOBUT_OFF'), 'starting': ("Starting…", 'SORTTIME'),+ 'running': ("Running", 'CHECKMARK'), 'exited': ("Stopped unexpectedly", 'ERROR'),+ 'unresponsive': ("Not answering", 'ERROR')}+GROUP_ICONS = {"Texturing": 'IMAGE_DATA', "Experimental": 'EXPERIMENTAL', "Deprecated": 'IMAGE_DATA',+ "3D, maps and rigging": 'MESH_CUBE'}+ROW_ICONS = {"trellis2": 'MESH_CUBE', "pbr_marigold": 'NODE_MATERIAL', "pbr_marigold_v2": 'NODE_MATERIAL',+ "skintokens": 'ARMATURE_DATA', "lato2": 'MOD_REMESH'}+LEFT_GROUPS, RIGHT_GROUPS = ("Texturing", "Experimental", "Deprecated"), ("3D, maps and rigging",)+SPLIT = 0.22 # the label column's share of the section+WIDTH = 36 # the section's width in UI units: a wide Preferences window must not spread it out+++def draw(p, layout, context):+ header, body = layout.panel("stablegen_setup_comfyui", default_closed=False)+ header.label(text="ComfyUI", icon='NETWORK_DRIVE')+ if body is None:+ return+ col = _container(body)+ _value(col, "Use").prop(p, "comfy_mode", expand=True)++ if p.comfy_mode == 'REMOTE':+ row = _value(col, "Server address")+ row.prop(p, "server_address", text="")+ row.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')+ _note(col, "Install models on that machine with installer.py from the StableGen repository.")+ return++ if p.comfy_mode == 'LOCAL':+ _value(col, "ComfyUI folder").prop(p, "comfy_local_path", text="")+ folder = runtime.comfy_folder(p)+ if folder is None:+ if p.comfy_local_path:+ _note(col, "No ComfyUI here: choose the folder with 'models' and 'custom_nodes'.", icon='ERROR',+ alert=True)+ return+ else:+ _value(col, "Install folder").prop(p, "comfy_root", text="")+ folder = runtime.comfy_folder(p)+ job = runtime.job if runtime.job is not None and runtime.job.kind == "create" else None+ if folder is None or (job is not None and (job.running or not job.ok)):+ _draw_own_install(col, p, job, ready=folder is not None)+ if folder is None:+ return+ elif runtime.own_outdated(p):+ right = _value(col)+ right.label(text=f"StableGen now uses ComfyUI {installer.COMFYUI_TAG}", icon='INFO')+ right.operator("stablegen.comfy_create", text="Update", icon='FILE_REFRESH')++ _draw_environment(col, folder)+ _draw_server(col, p)+ if p.use_legacy_panel: # the StableGen panel's Setup page has the models otherwise+ _draw_models(layout, p, folder)+ else:+ row = _value(col, "Models")+ row.alignment = 'LEFT'+ row.operator("stablegen.open_setup", text="Install models in the StableGen panel", icon='PACKAGE')+++# --- layout helpers ---+def _container(layout):+ """A fixed-width column at the left of a sub-panel."""+ row = layout.row()+ row.alignment = 'LEFT'+ col = row.column()+ col.ui_units_x = WIDTH+ return col+++def _value(col, label=""):+ """A row in the value column, with an optional label in the label column (like a property)."""+ split = col.split(factor=SPLIT)+ left = split.row()+ left.alignment = 'RIGHT'+ left.label(text=label)+ return split.row()+++def _note(col, text, icon='NONE', alert=False):+ """Secondary text under the field it belongs to."""+ row = _value(col)+ row.active = alert+ row.alert = alert+ row.label(text=text, icon=icon)+++def _right(layout):+ row = layout.row(align=True)+ row.alignment = 'RIGHT'+ return row+++# --- ComfyUI ---+def _free_space_text(path_text):+ """'79 GB free on E:' for the nearest existing folder of path_text."""+ import shutil+ from pathlib import Path+ import bpy+ path = Path(bpy.path.abspath(path_text)).expanduser()+ while not path.exists() and path.parent != path:+ path = path.parent+ try:+ free = shutil.disk_usage(path).free / 1024**3+ except OSError:+ return ""+ return f"{free:.0f} GB free on {path.anchor.rstrip(chr(92)) or path.anchor}"+++def _draw_own_install(col, p, job, ready):+ """Installing StableGen's own ComfyUI: what it takes, then the steps while it runs."""+ if job is not None and job.running:+ right = _value(col, "Installing")+ right.progress(factor=job.progress(), text=job.status_line())+ right.operator("stablegen.comfy_cancel_install", text="", icon='X')+ steps = _value(col).column(align=True)+ for step_id in job.order:+ item = job.items[step_id]+ done = item.get("status") in ('installed', 'present')+ row = steps.row()+ row.active = done or step_id == job.current+ row.label(text=item["name"], icon='CHECKMARK' if done else 'ERROR' if item.get("status") == 'failed'+ else 'SORTTIME' if step_id == job.current else 'RADIOBUT_OFF')+ return+ if job is not None and not job.ok:+ right = _value(col)+ right.alert = True+ right.label(text=job.status_line(), icon='ERROR')+ right.operator("stablegen.comfy_open_log", text="Log", icon='TEXT').which = 'INSTALL'+ if ready:+ return+ space = _free_space_text(p.comfy_root) if p.comfy_root else ""+ _note(col, f"ComfyUI {installer.COMFYUI_TAG}, Python {installer.PYTHON_VERSION} and torch for your GPU: about "+ f"5 GB, plus the models you add below." + (f" {space}." if space else ""))+ row = _value(col)+ row.alignment = 'LEFT'+ row.scale_y = 1.3+ row.operator("stablegen.comfy_create", text="Retry" if job is not None else "Install ComfyUI", icon='IMPORT')+++def _draw_environment(col, folder):+ report = runtime.ensure_report(folder)+ if report is None or report.get("loading"):+ _note(col, "Reading ComfyUI's Python and installed models…", icon='SORTTIME')+ elif "error" in report:+ _note(col, report.get("message", "Could not read this ComfyUI"), icon='ERROR', alert=True)+ else:+ py = report.get("python", {})+ parts = [f"Python {py.get('version', '?')}", f"torch {py.get('torch') or 'not installed'}"]+ if py.get("gpu"):+ parts.append(f"{py['gpu']}" + (f" · {round(py['vram_mb'] / 1024)} GB" if py.get("vram_mb") else ""))+ _note(col, " · ".join(parts))+ if py.get("default"):+ _note(col, f"The default python on PATH (this folder has none of its own): {py.get('path')}")+++def _draw_server(col, p):+ c = runtime.comfy()+ text, icon = STATE_TEXT.get(c.state, (c.state, 'QUESTION'))+ if c.state in ('running', 'starting'):+ text += f" on {c.address}"+ if not c.owned:+ text += " (started outside StableGen)"+ elif c.message:+ text += f": {c.message}"+ box = _value(col, "Status").box()+ row = box.row()+ row.alert = c.state in ('exited', 'unresponsive')+ row.label(text=text, icon=icon)+ buttons = _right(row)+ buttons.operator("stablegen.comfy_open_log", text="Log", icon='TEXT').which = 'COMFYUI'+ if c.state in ('running', 'starting', 'unresponsive'):+ buttons.operator("stablegen.comfy_stop", text="Stop", icon='PAUSE')+ else:+ buttons.operator("stablegen.comfy_start", text="Restart" if c.state == 'exited' else "Start", icon='PLAY')+ folder = runtime.comfy_folder(p)+ if runtime.restart_needed and folder is not None and runtime.restart_needed == str(folder) and not c.owned:+ note = box.row()+ note.alert = True+ note.label(text="Restart ComfyUI so it loads the nodes just installed (StableGen didn't start it)",+ icon='ERROR')+ options = _value(col, "Options").column(align=True)+ options.prop(p, "comfy_auto_start")+ options.prop(p, "comfy_keep_running")+ header, advanced = col.panel("stablegen_setup_advanced", default_closed=True)+ header.label(text="Port and arguments")+ if advanced is not None:+ _value(advanced, "Port").prop(p, "comfy_port", text="")+ _value(advanced, "Extra arguments").prop(p, "comfy_extra_args", text="")+++# --- Models ---+def _draw_models(layout, p, folder):+ report = runtime.report(folder)+ rows = list(packages.visible_rows(p.enable_deprecated_architectures, p.enable_experimental_architectures))+ states = {tags: packages.row_state(tags, report) for _, tags, _, _ in rows}+ header, body = layout.panel("stablegen_setup_models", default_closed=False)+ header.label(text="Models", icon='PACKAGE')+ summary = _right(header)+ if report and "tags" in report:+ installed = sum(s["size_mb"] for s in states.values() if s["state"] == "installed")+ info = summary.row()+ info.active = False+ free = f"{report['free_mb'] / 1024:.0f} GB free"+ info.label(text=f"{packages.size_text(installed)} installed · {free}" if installed else free)+ summary.operator("stablegen.comfy_refresh", text="", icon='FILE_REFRESH', emboss=False)+ if body is None:+ return++ job = runtime.job+ if job is not None and job.kind == "install" and job.folder == str(folder) and not job.running and not job.ok:+ row = body.row()+ row.alert = True+ row.label(text=f"{job.title}: {job.status_line()}", icon='ERROR')+ _right(row).operator("stablegen.comfy_open_log", text="Log", icon='TEXT').which = 'INSTALL'+ if runtime.review is not None and runtime.review["folder"] == str(folder):+ _draw_review(body, runtime.review)++ installing = set(job.tags) if job is not None and job.running else set()+ columns = body.split(factor=0.5)+ for column, groups in ((columns.column(), LEFT_GROUPS), (columns.column(), RIGHT_GROUPS)):+ for group in groups:+ members = [r for r in rows if r[0] == group]+ if not members:+ continue+ heading = column.row()+ heading.active = False+ heading.label(text=group)+ box = column.box()+ for i, (_, tags, title, purpose) in enumerate(members):+ if i:+ box.separator(factor=0.4)+ _model_row(box, tags, title, purpose, states[tags], job if installing & set(tags) else None)+ column.separator()+++def _model_row(box, tags, title, purpose, state, job):+ split = box.split(factor=0.64)+ text = split.column(align=True)+ text.label(text=title, icon=ROW_ICONS.get(tags[0], 'IMAGE_DATA'))+ right = _right(split)+ if job is not None:+ rate = job.rate_text()+ text.progress(factor=job.progress(), text=f"{round(job.progress() * 100)}% · {job.size_text()}" + (+ f" · {rate}" if rate else ""))+ right.operator("stablegen.comfy_cancel_install", text="", icon='X')+ return+ place = runtime.queued(list(tags))+ if place is not None:+ meta = text.row()+ meta.active = False+ meta.label(text=f"Queued · {packages.queue_text(place)}", icon='SORTTIME')+ right.operator("stablegen.comfy_unqueue", text="", icon='X').tags = ",".join(tags)+ return+ size = state["size_mb"] if state["state"] == "installed" else state["download_mb"]+ meta = text.row()+ meta.active = False+ meta.label(text=packages.meta_text(purpose, tags, size), icon='BLANK1')+ if state["missing_core_nodes"]:+ warn = text.row()+ warn.alert = True+ warn.label(text="Needs a newer ComfyUI", icon='ERROR')+ if packages.removable_state(tags, state, runtime.node_policy()):+ op = right.operator("stablegen.comfy_remove", text="", icon='TRASH')+ op.tags, op.title = ",".join(tags), title+ if state["state"] == "installed":+ done = right.row()+ done.active = False+ done.label(text="Installed", icon='CHECKMARK')+ elif state["state"] != "unknown":+ op = right.operator("stablegen.comfy_install", text="Finish" if state["state"] == "partial" else "Install",+ icon='IMPORT')+ op.tags = ",".join(tags)+++def _wrapped(layout, text, width=96):+ line = ""+ for word in text.split():+ if len(line) + len(word) + 1 > width:+ layout.label(text=line)+ line = word+ else:+ line = f"{line} {word}".strip()+ if line:+ layout.label(text=line)+++def _draw_review(layout, review):+ inner = layout.box()+ titles = ", ".join(installer.package_info(t)["name"] for t in review["tags"])+ inner.label(text=f"Install {titles}", icon='IMPORT')+ plan = review.get("plan")+ if plan is None:+ inner.label(text="Checking what this changes in your ComfyUI…", icon='SORTTIME')+ elif "error" in plan:+ inner.label(text=plan.get("message", "Could not check this ComfyUI"), icon='ERROR')+ elif runtime.needs_review(plan):+ col = inner.column(align=True)+ col.label(text="Changes to your ComfyUI's Python:", icon='ERROR')+ for pip in plan.get("pip", []):+ installed = f" (you have {pip['installed']})" if pip.get("installed") else " (new)"+ col.label(text=f"{pip['spec']}{installed}", icon='BLANK1')+ for step in plan.get("steps", []):+ col.label(text=f"{step['node']}: {step['step']}", icon='BLANK1')+ for node in plan.get("nodes", []):+ if node["action"] in ("move to pin", "different commit"):+ col.label(text=f"{node['name']}: kept at your commit" if node["action"] == "different commit"+ else f"{node['name']}: moved to the commit StableGen was tested with", icon='BLANK1')+ note = col.row()+ note.active = False+ note.label(text="Your package versions are saved first, to roll back from.", icon='INFO')+ for key in review["notices"]:+ col = inner.column(align=True)+ for line in installer.LICENSE_NOTICES.get(key, []):+ if line:+ _wrapped(col, line)+ row = _right(inner)+ row.enabled = plan is not None # StableGen's own ComfyUI has an empty plan: nothing of the user's changes+ row.operator("stablegen.comfy_cancel_review", text="Cancel")+ row.operator("stablegen.comfy_confirm_install",+ text=runtime.accept_label(review), icon='CHECKMARK')+++# --- the sidebar ---+SETUP_CARD = 'setup_card'+++HINT_OPERATORS = ("stablegen.comfy_install", "stablegen.comfy_cancel_install", "stablegen.comfy_copy_install_command",+ "stablegen.comfy_use_server_folder", "stablegen.comfy_unqueue")+LOOPBACK = ("127.0.0.1", "localhost", "[::1]")+++def model_hint(context):+ """When the chosen architecture's model isn't on the ComfyUI StableGen uses, what to say and offer, else None:+ kind 'missing' a local ComfyUI without it: Install, with its download size+ kind 'installing' its install is running: progress and detail ('5.1 of 14.3 GB · 42 MB/s · 4 min left')+ kind 'queued' it waits for the install that runs: where in the queue ('next', '2nd in line')+ kind 'server' a server without it: run installer.py there (copy the command), or for a ComfyUI on+ this machine, use its folder so StableGen can install it+ A local ComfyUI is read from its status report; a server from the model list StableGen already fetched."""+ p = runtime.prefs()+ architecture = context.scene.architecture_mode+ if runtime.local_mode(p):+ folder = runtime.comfy_folder(p)+ report = runtime.ensure_report(folder)+ missing = packages.missing_for_architecture(architecture, report)+ if not missing:+ return None+ tags, title = missing+ job = runtime.job+ if job is not None and job.running and set(job.tags) & set(tags):+ rate = job.rate_text()+ return {'kind': 'installing', 'tags': tags, 'title': title, 'text': f"Installing {title}",+ 'progress': job.progress(), 'detail': job.size_text() + (f" · {rate}" if rate else "")}+ place = runtime.queued(list(tags))+ if place is not None:+ return {'kind': 'queued', 'tags': tags, 'title': title, 'text': f"{title} is queued",+ 'detail': packages.queue_text(place)}+ size = packages.size_text(packages.row_state(tags, report)["download_mb"])+ return {'kind': 'missing', 'tags': tags, 'title': title, 'text': f"{title} isn't installed",+ 'button': f"Install · {size}", 'size': size}+ tags = packages.ARCH_TAGS.get(architecture)+ if not p.server_online or not tags or architecture == 'trellis2': # TRELLIS.2 has no model list to check+ return None+ from ..core import state+ if context.scene.model_name != 'NONE_FOUND' or state._cached_checkpoint_architecture != architecture:+ return None+ title = next((t for _, row_tags, t, _ in packages.ROWS if set(tags) <= set(row_tags)), architecture)+ local = p.server_address.split("//")[-1].rsplit(":", 1)[0].lower() in LOOPBACK+ return {'kind': 'server', 'tags': tags, 'title': title, 'local': local,+ 'text': f"{title} isn't on your ComfyUI" if local else f"{title} isn't on the server",+ 'button': "Set up" if local else "Copy command"}+++def draw_panel_notices(layout, context):+ """The sidebar's part of the setup: a first-run card that opens these preferences, and a note with an Install+ button when the chosen model is not on the ComfyUI. Top-level boxes with an INFO or ERROR label, so the+ StableGen panel shows them on every page (it draws the model note itself, under Architecture)."""+ from ..ui import studio_tips+ p = runtime.prefs()+ if (p.comfy_mode == 'REMOTE' and not p.server_online and p.server_address == "127.0.0.1:8188"+ and not studio_tips.dismissed(SETUP_CARD)):+ box = layout.box()+ box.label(text="ComfyUI isn't set up yet", icon='INFO')+ box.label(text="StableGen can install its own, use yours, or connect to a server.")+ row = box.row(align=True)+ row.operator("stablegen.open_setup", text="Set up ComfyUI", icon='PREFERENCES')+ row.operator("stablegen.dismiss_setup_card", text="I have a server")+ return+ hint = model_hint(context)+ if hint is None:+ return+ box = layout.box()+ tags = ",".join(hint['tags'])+ if hint['kind'] == 'installing':+ # a label, not a progress bar: the panel's progress bars are generation progress+ row = box.row(align=True)+ row.label(text=f"{hint['text']} · {round(hint['progress'] * 100)}% ({hint['detail']})", icon='INFO')+ row.operator("stablegen.comfy_cancel_install", text="", icon='X')+ elif hint['kind'] == 'queued':+ row = box.row(align=True)+ row.label(text=f"{hint['text']} ({hint['detail']})", icon='INFO')+ row.operator("stablegen.comfy_unqueue", text="", icon='X').tags = tags+ elif hint['kind'] == 'missing':+ box.label(text=hint['text'] + " in your ComfyUI", icon='ERROR')+ box.operator("stablegen.comfy_install", text=hint['button'], icon='IMPORT').tags = tags+ else:+ box.label(text=hint['text'], icon='ERROR')+ if hint['local']:+ box.operator("stablegen.comfy_use_server_folder", text="Let StableGen install it", icon='IMPORT')+ else:+ box.operator("stablegen.comfy_copy_install_command", text="Copy the install command",+ icon='COPYDOWN').tags = tagsdiff --git a/stablegen/setup/runtime.py b/stablegen/setup/runtime.pynew file mode 100644index 0000000..109b712--- /dev/null+++ b/stablegen/setup/runtime.py@@ -0,0 +1,636 @@+"""This Blender session's setup state: the local ComfyUI, the installer job, the last status report of each+ComfyUI folder and the install waiting for review. A timer redraws the preferences and sidebars while something+runs, notices ComfyUI coming up (then checks the server like the refresh button) or stopping, and refreshes the+package list after an install.++ComfyUI keeps running across add-on reloads (the next registration adopts it); Blender quitting stops it unless+"keep running" is on.+"""+import atexit+import json+import os+import shlex+import shutil+import subprocess+import sys+import time+from pathlib import Path+from typing import List, Optional++import bpy # pylint: disable=import-error++from ..core import ADDON_PKG+from . import installer+from .comfy_process import LocalComfyUI, python_for, same_folder+from .jobs import InstallerJob, run_report++TICK = 0.5+IDLE_TICK = 5.0+REPORT_TIMEOUT = 660 # jobs.run_report gives up after 600 s++_comfy: Optional[LocalComfyUI] = None+job: Optional[InstallerJob] = None+reports = {} # str(folder) -> --status report, {"loading": True} while it runs+review: Optional[dict] = None # the install waiting for its notices/changes to be accepted+queue: List[dict] = [] # accepted installs waiting for the running one, each as review had it+_restart_after_queue = False # an install added nodes: restart ComfyUI once the queue is empty+restart_needed: Optional[str] = None # the folder whose running ComfyUI (not StableGen's) must restart for new nodes+keep_running = False # mirrors the preference, which atexit can no longer read+_last_state = "stopped"+_job_seen_done = True+++def _run_async(work, done):+ """work() on a thread, then done(result) on the main thread. Not core.state's helper: that one drops results+ when the server address changes meanwhile, which starting ComfyUI does."""+ import threading+ box = {}++ def worker():+ try:+ box["result"] = work()+ except Exception as e: # report it like a failed run+ box["result"] = {"error": "run", "message": str(e)}++ thread = threading.Thread(target=worker, daemon=True)+ thread.start()++ def poll():+ if thread.is_alive():+ return 0.25+ done(box.get("result"))+ return None++ # persistent: opening a .blend while it runs (the status read takes a while) must not drop the result+ bpy.app.timers.register(poll, first_interval=0.25, persistent=True)+++# --- paths and preferences ---+def prefs():+ return bpy.context.preferences.addons[ADDON_PKG].preferences+++def state_dir() -> Path:+ try:+ folder = bpy.utils.extension_path_user(ADDON_PKG, create=True)+ except ValueError: # legacy add-on installs have no extension user folder+ folder = bpy.utils.user_resource('CONFIG', path=ADDON_PKG, create=True)+ return Path(folder) / "setup"+++def resolve_folder(path: str) -> Optional[Path]:+ """The ComfyUI folder at path (also the outer folder of a portable build), or None."""+ if not path:+ return None+ base = Path(bpy.path.abspath(path)).expanduser()+ for candidate in (base, base / "ComfyUI"):+ if (candidate / "models").is_dir() and (candidate / "custom_nodes").is_dir():+ return candidate+ return None+++def own_folder(p=None) -> Optional[Path]:+ p = p or prefs()+ return Path(bpy.path.abspath(p.comfy_root)).expanduser() / "ComfyUI" if p.comfy_root else None+++def own_marker(p=None) -> dict:+ """What --create-comfyui recorded about StableGen's own ComfyUI (empty when there is none)."""+ folder = own_folder(p)+ try:+ return json.loads((folder.parent / installer.OWN_MARKER).read_text(encoding="utf-8")) if folder else {}+ except (OSError, ValueError):+ return {}+++def own_ready(p=None) -> bool:+ """Every step of --create-comfyui finished (a half-made one has main.py but no torch yet)."""+ folder, marker = own_folder(p), own_marker(p)+ return bool(folder and all(marker.get(k) for k in ("uv", "python", "torch", "requirements"))+ and installer.own_python(folder).is_file())+++def own_outdated(p=None) -> bool:+ """This StableGen pins a newer ComfyUI or torch than the own ComfyUI has."""+ marker = own_marker(p)+ return bool(marker) and (marker.get("comfyui") != installer.COMFYUI_TAG+ or not str(marker.get("torch", "")).startswith(" ".join(installer.TORCH_PINS)))+++def comfy_folder(p=None) -> Optional[Path]:+ """The ComfyUI StableGen runs and installs into, in the Own and Local modes."""+ p = p or prefs()+ if p.comfy_mode == 'LOCAL':+ return resolve_folder(p.comfy_local_path)+ if p.comfy_mode == 'OWN':+ return own_folder(p) if own_ready(p) else None+ return None+++def local_mode(p=None) -> bool:+ return (p or prefs()).comfy_mode in ('LOCAL', 'OWN')+++def comfy() -> LocalComfyUI:+ global _comfy+ if _comfy is None:+ _comfy = LocalComfyUI(state_dir())+ _comfy.adopt_recorded()+ return _comfy+++# --- ComfyUI ---+def start(p=None) -> str:+ """Start (or adopt) the local ComfyUI. Returns an error message, or '' when it is starting."""+ p = p or prefs()+ folder = comfy_folder(p)+ if folder is None:+ return "Choose the ComfyUI folder in StableGen's preferences first"+ try:+ address = comfy().start(folder, port=p.comfy_port, extra_args=shlex.split(p.comfy_extra_args),+ env=own_environment(p))+ except (RuntimeError, OSError, ValueError) as e:+ return str(e)+ if p.server_address != address:+ p.server_address = address+ ensure_timer()+ return ""+++def stop():+ comfy().stop()+ redraw()+++def own_git(p) -> Optional[Path]:+ """The Git that StableGen's own ComfyUI was set up with (Windows has none of its own)."""+ if p.comfy_mode != 'OWN' or not p.comfy_root:+ return None+ exe = Path(bpy.path.abspath(p.comfy_root)) / "tools" / "git" / "cmd" / (+ "git.exe" if sys.platform == "win32" else "git")+ return exe if exe.is_file() else None+++def own_environment(p) -> Optional[dict]:+ """Git on PATH for StableGen's own ComfyUI (ComfyUI-Manager and node installs use it)."""+ git = own_git(p)+ return {"PATH": str(git.parent) + os.pathsep + os.environ.get("PATH", "")} if git else None+++def choosing() -> bool:+ """The StableGen panel's Setup page is open on its choices (Change): trying them restarts nothing until Use."""+ from ..ui import studio+ return any(getattr(s, 'setup_change', False) and s.page == 'SETUP' for s in studio._sessions.values())+++def follow_folder(p=None) -> str:+ """After the mode or folder changes: the ComfyUI StableGen runs (or adopted) for another folder is replaced by+ the chosen folder's, so the model lists come from the ComfyUI the setup shows. Nothing changes while it is+ stopped, or when no other local folder is chosen yet (a server, or a folder still to pick). Returns an error+ or ''."""+ p = p or prefs()+ c = comfy()+ folder = comfy_folder(p) if local_mode(p) else None+ if folder is None or c.folder is None or c.state not in ('starting', 'running', 'unresponsive') or choosing():+ return ""+ if same_folder(c.folder, folder):+ return ""+ print(f"[StableGen] Switching from the ComfyUI in {c.folder} to the one in {folder}.")+ p.server_online = False+ error = start(p) # stops the other one (or lets it go, if StableGen didn't start it)+ redraw()+ return error+++def maybe_autostart() -> bool:+ """Start the local ComfyUI because StableGen needs it. Only from 'stopped': after a crash the user restarts it."""+ p = prefs()+ follow_folder(p)+ if not (local_mode(p) and p.comfy_auto_start and comfy().state == 'stopped' and comfy_folder(p)):+ return False+ if job and job.running:+ return False+ return not start(p)+++def offline_note() -> Optional[str]:+ """What to tell an operator that needs the server while the local ComfyUI is not up yet."""+ p = prefs()+ if not local_mode(p):+ return None+ state = comfy().state+ if state == 'starting':+ return "ComfyUI is still starting; try again in a moment"+ if maybe_autostart():+ return "Starting ComfyUI; try again when the status line says it is running"+ if state == 'exited':+ return f"ComfyUI stopped ({comfy().message}); restart it from the StableGen panel"+ return None+++# --- reports and installs ---+def report(folder: Optional[Path]) -> Optional[dict]:+ return reports.get(str(folder)) if folder else None+++def refresh_status(folder: Optional[Path] = None):+ """Read --status for the folder in the background (installed packages, Python, GPU)."""+ folder = folder or comfy_folder()+ if folder is None:+ return+ python, default = python_for(folder)+ if python is None:+ reports[str(folder)] = {"error": "python", "message": "No Python for this ComfyUI: it has none of its own "+ "(python_embeded, venv or .venv) and there is no "+ "python on PATH"}+ redraw()+ return+ reports[str(folder)] = {"loading": True, "since": time.time()}+ redraw()+ key = str(folder)++ def done(result):+ if result is not None and "python" in result:+ result["python"]["default"] = default # the python on PATH, as the folder has none of its own+ _report_done(key, result)+ _run_async(lambda: run_report([key, "--status", "--python", python]), done)+++def _report_done(key, result):+ reports[key] = result if result is not None else {"error": "run", "message": "the status check did not finish"}+ redraw()+++def _unread(current: Optional[dict]) -> bool:+ """No report yet, or a read that never came back (it gives up after REPORT_TIMEOUT)."""+ return current is None or (current.get("loading", False) and time.time() - current.get("since", 0) > REPORT_TIMEOUT)+++def ensure_report(folder: Optional[Path]) -> Optional[dict]:+ """The report for this folder, starting to read it when there is none yet: nothing may have read it since+ Blender started or the folder was chosen."""+ if folder is not None and _unread(report(folder)):+ refresh_status(folder)+ return report(folder)+++def refresh_models(folder: Optional[Path] = None):+ """Read again which models are installed, from the files alone (in-process, without ComfyUI's Python), and+ keep the rest of the report. With no report yet, read all of it."""+ folder = folder or comfy_folder()+ if folder is None:+ return+ key = str(folder)+ current = reports.get(key)+ if current is None or "tags" not in current:+ if _unread(current) or not current.get("loading"):+ refresh_status(folder)+ return++ def done(result):+ if result is not None and "tags" in reports.get(key, {}):+ reports[key] = {**reports[key], **result}+ redraw()+ _run_async(lambda: installer.package_report(folder), done)+++def notices_for(tags: List[str]) -> List[str]:+ return list(dict.fromkeys(installer.package_info(t)["notice"] for t in tags+ if installer.package_info(t).get("notice")))+++def begin_install(tags: List[str]):+ """Install these package tags, after the user accepts their license notices and, for a ComfyUI of their own,+ the changes to its Python (both shown in the preferences)."""+ global review+ p = prefs()+ folder = comfy_folder(p)+ python = python_for(folder)[0] if folder else None+ review = {"tags": list(tags), "folder": str(folder), "python": python, "notices": notices_for(tags),+ "plan": None if p.comfy_mode == 'LOCAL' else {}}+ if p.comfy_mode == 'LOCAL' and python:+ current = review+ _run_async(lambda: run_report([str(folder), "--plan", "--packages", ",".join(tags), "--python", python]),+ lambda plan: _plan_done(current, plan))+ elif not review["notices"]:+ confirm_install()+ redraw()+++def _plan_done(pending, plan):+ if review is not pending:+ return+ pending["plan"] = plan or {"error": "run", "message": "the check did not finish"}+ if not pending["notices"] and not needs_review(pending["plan"]):+ confirm_install()+ redraw()+++def needs_review(plan: Optional[dict]) -> bool:+ """A plan worth showing: it changes ComfyUI's Python or moves a node someone may have updated."""+ if not plan or "error" in plan:+ return bool(plan)+ return bool(plan.get("changes_python") or any(n["action"] in ("move to pin", "different commit")+ for n in plan.get("nodes", [])))+++def cancel_review():+ global review+ review = None+ redraw()+++def confirm_install() -> str:+ """Start the reviewed install, or queue it behind the running one. Returns an error message or ''."""+ global review+ pending, review = review, None+ if not pending:+ return ""+ if not bpy.app.online_access:+ return "Allow online access in Blender's preferences (System) to download models"+ if not pending["python"]:+ return "No Python for this ComfyUI: none of its own, and no python on PATH"+ if job and job.running:+ if job.kind == "create":+ return "StableGen's own ComfyUI is still installing"+ if queued(pending["tags"]) is None and not set(job.tags) & set(pending["tags"]):+ queue.append(pending)+ redraw()+ return ""+ return _start_install(pending)+++def accept_label(pending: dict) -> str:+ """The review's button: 'Accept and install', or 'Queue' when another install runs."""+ verb = "queue" if job is not None and job.running else "install"+ return f"Accept and {verb}" if pending["notices"] else verb.capitalize()+++def queued(tags: List[str]) -> Optional[int]:+ """Where these tags wait in the queue (0 is next), or None."""+ return next((i for i, entry in enumerate(queue) if set(entry["tags"]) & set(tags)), None)+++def unqueue(tags: List[str]):+ queue[:] = [entry for entry in queue if not set(entry["tags"]) & set(tags)]+ redraw()+++def _start_next():+ """The next queued install for the ComfyUI in use; ones for a folder no longer chosen are dropped."""+ folder = comfy_folder()+ while queue:+ pending = queue.pop(0)+ if folder is not None and pending["folder"] == str(folder) and not _start_install(pending):+ return True+ return False+++def _start_install(pending: dict) -> str:+ global job, _job_seen_done+ folder = Path(pending["folder"])+ args = [str(folder), "--packages", ",".join(pending["tags"]), "--python", pending["python"]]+ if pending["notices"]:+ args += ["--accept-notices", ",".join(pending["notices"])]+ git = own_git(prefs())+ if git:+ args += ["--git", str(git)]+ stamp = time.strftime("%Y%m%d-%H%M%S")+ if needs_review(pending.get("plan")):+ snapshot(pending["python"], pending.get("plan") or {}, state_dir() / "snapshots" / f"{stamp}.txt")+ titles = ", ".join(installer.package_info(t)["name"] for t in pending["tags"])+ job = InstallerJob(titles, args, state_dir() / "logs" / f"install-{stamp}-{pending['tags'][0]}.log",+ folder=str(folder), tags=pending["tags"])+ job.start()+ _job_seen_done = False+ ensure_timer()+ redraw()+ return ""+++def busy_tags() -> set:+ """The tags the running install or the queue will write."""+ tags = set(job.tags) if job is not None and job.running else set()+ for entry in queue:+ tags |= set(entry["tags"])+ return tags+++def node_policy(p=None) -> str:+ """Which nodes removing a package takes (installer.removed_with_package): all of them in StableGen's own ComfyUI,+ only StableGen's own nodes in someone's own, where the others may predate StableGen."""+ return "all" if (p or prefs()).comfy_mode == 'OWN' else "stablegen"+++def removable(tags: List[str]) -> List[Path]:+ """What removing these tags deletes (installer.removal_plan): their models, Hugging Face folders and unfinished+ downloads (and nodes, in StableGen's own ComfyUI), without the ones another package still uses."""+ folder = comfy_folder()+ return (installer.removal_plan(folder, list(tags), sorted(busy_tags()), nodes=node_policy())+ if folder is not None else [])+++def kept_nodes(tags: List[str], removing: List[Path]) -> List[Path]:+ """The nodes of these tags on disk that removing them leaves (ones from elsewhere, in someone's own ComfyUI)."""+ folder = comfy_folder()+ if folder is None:+ return []+ targets = [installer.item_target(i, folder) for i in installer.DEPENDENCIES.values()+ if i["type"] in installer.NODE_TYPES and set(i["packages"]) & set(tags)]+ return [t for t in targets if t.exists() and t not in removing]+++def path_size(path: Path) -> int:+ return sum(p.stat().st_size for p in path.rglob("*") if p.is_file()) if path.is_dir() else path.stat().st_size+++def remove(tags: List[str]):+ """Delete them; returns (bytes removed, paths that could not be deleted, such as a model ComfyUI has open).+ Not while an install or the queue includes them."""+ if busy_tags() & set(tags):+ return 0, []+ removed, failed = 0, []+ nodes = comfy_folder() / "custom_nodes"+ for path in removable(tags):+ try:+ size = path_size(path)+ if path.parent == nodes:+ # renamed first, so a node in use fails whole instead of half deleted; ComfyUI skips '.disabled'+ gone = path.with_name(f"{path.name}.removing-{int(time.time())}.disabled")+ path.rename(gone)+ shutil.rmtree(gone, ignore_errors=True)+ if gone.exists():+ failed.append(str(gone))+ elif path.is_dir():+ shutil.rmtree(path)+ else:+ path.unlink()+ removed += size+ except OSError:+ failed.append(str(path))+ refresh_models()+ if prefs().server_online and bpy.ops.stablegen.refresh_checkpoint_list.poll():+ bpy.ops.stablegen.refresh_checkpoint_list('INVOKE_DEFAULT') # the removed checkpoints leave the list+ return removed, failed+++def create_own() -> str:+ """Install (or repair, or update) StableGen's own ComfyUI in the install folder. Returns an error or ''."""+ global job, _job_seen_done+ p = prefs()+ if not p.comfy_root:+ return "Choose the install folder first"+ if job and job.running:+ return "Another install is still running"+ if not bpy.app.online_access:+ return "Allow online access in Blender's preferences (System) to download ComfyUI"+ c = comfy()+ if c.owned and c.state in ('running', 'starting'):+ c.stop() # its Python is about to change+ root = Path(bpy.path.abspath(p.comfy_root)).expanduser()+ stamp = time.strftime("%Y%m%d-%H%M%S")+ job = InstallerJob("StableGen's own ComfyUI", ["--create-comfyui", str(root)],+ state_dir() / "logs" / f"create-{stamp}.log", kind="create", folder=str(root / "ComfyUI"))+ job.start()+ _job_seen_done = False+ ensure_timer()+ redraw()+ return ""+++def snapshot(python: str, plan: dict, path: Path):+ """Package versions and node commits before an install changes a ComfyUI of the user's, to roll back from."""+ path.parent.mkdir(parents=True, exist_ok=True)+ try:+ freeze = subprocess.run([python, "-m", "pip", "freeze"], capture_output=True, timeout=120,+ text=True, encoding="utf-8", errors="replace").stdout+ except (OSError, subprocess.TimeoutExpired) as e:+ freeze = f"# pip freeze failed: {e}\n"+ nodes = "".join(f"# {n['path']} at {n.get('head') or '?'}\n" for n in plan.get("nodes", []))+ path.write_text(f"# Before installing {', '.join(plan.get('packages', []))} into {plan.get('comfyui', '')}\n"+ f"# Roll back with: \"{python}\" -m pip install -r \"{path}\"\n{nodes}{freeze}", encoding="utf-8")+++def cancel_job():+ if job:+ job.cancel()+ redraw()+++# --- timer and redraws ---+def redraw():+ wm = getattr(bpy.context, "window_manager", None)+ if wm is None:+ return+ for window in wm.windows:+ for area in window.screen.areas:+ if area.type in ('PREFERENCES', 'VIEW_3D'):+ area.tag_redraw()+++def ensure_timer():+ if not bpy.app.timers.is_registered(_tick):+ bpy.app.timers.register(_tick, first_interval=TICK, persistent=True)+++def _tick():+ global _last_state, _job_seen_done, restart_needed+ try:+ c = comfy()+ state = c.poll() if c.state == 'running' else c.state+ if state != _last_state:+ if state != 'running':+ restart_needed = None # it stopped or went away: the next start loads the new nodes+ if state == 'running':+ print(f"[StableGen] ComfyUI is running at {c.address}.")+ if bpy.ops.stablegen.check_server_status.poll():+ bpy.ops.stablegen.check_server_status('INVOKE_DEFAULT')+ elif state == 'exited':+ print(f"[StableGen] {c.message}.")+ _last_state = state+ redraw()+ busy = state == 'starting' or (job is not None and job.running)+ if job is not None and not job.running and not _job_seen_done:+ _job_seen_done = True+ _install_finished(job)+ if busy:+ redraw()+ return TICK+ return IDLE_TICK if state == 'running' else None+ except Exception as e: # a timer must not raise; it would be dropped+ print(f"[StableGen] Setup timer: {e}")+ return IDLE_TICK+++def _install_finished(finished: InstallerJob):+ print(f"[StableGen] Install {'finished' if finished.ok else 'stopped'}: {finished.status_line()}")+ folder = Path(finished.folder)+ if finished.kind == "create":+ if finished.ok and comfy_folder() == folder:+ refresh_status(folder)+ if prefs().comfy_auto_start:+ start()+ redraw()+ return+ global _restart_after_queue, restart_needed+ _restart_after_queue |= bool(finished.summary and finished.summary.get("restart"))+ if _start_next(): # cancelling one install leaves the rest of the queue to go on+ refresh_models(folder) # the finished one shows as installed while the next downloads+ redraw()+ return+ refresh_status(folder)+ c = comfy()+ restart, _restart_after_queue = _restart_after_queue, False+ if restart and c.owned and c.state == 'running' and c.folder and str(c.folder) == str(folder):+ print("[StableGen] Restarting ComfyUI so it loads the new nodes.")+ c.stop()+ start()+ elif restart and c.state == 'running':+ # StableGen never stops a ComfyUI it didn't start: the Setup page asks for the restart instead+ restart_needed = str(folder)+ print("[StableGen] Restart ComfyUI so it loads the new nodes (StableGen did not start it).")+ if c.state == 'running' and bpy.ops.stablegen.check_server_status.poll():+ bpy.ops.stablegen.check_server_status('INVOKE_DEFAULT') # new models in the lists+ redraw()+++def _on_exit():+ c = _comfy+ if c is not None and c.owned and not keep_running:+ c.stop()+ if job is not None and job.running:+ job.cancel()+++def _startup():+ global keep_running, _last_state+ try:+ p = prefs()+ keep_running = p.comfy_keep_running+ if local_mode(p):+ c = comfy()+ _last_state = c.state+ if c.state == 'running':+ if p.server_address != c.address:+ p.server_address = c.address+ ensure_timer()+ folder = comfy_folder(p)+ if folder:+ refresh_status(folder)+ follow_folder(p) # the recorded ComfyUI may be for the folder chosen before+ except Exception as e:+ print(f"[StableGen] Setup start-up: {e}")+ return None+++def register():+ atexit.register(_on_exit)+ if not bpy.app.background:+ bpy.app.timers.register(_startup, first_interval=1.0, persistent=True) # Blender's start-up file loads after this+++def unregister():+ atexit.unregister(_on_exit)+ for timer in (_tick, _startup):+ if bpy.app.timers.is_registered(timer):+ bpy.app.timers.unregister(timer)diff --git a/stablegen/ui/model_units.py b/stablegen/ui/model_units.pyindex b657782..f888e0e 100644--- a/stablegen/ui/model_units.py+++ b/stablegen/ui/model_units.py@@ -223,6 +223,9 @@ class RefreshCheckpointList(bpy.types.Operator):server_address = prefs.preferences.server_addressarchitecture = getattr(context.scene, "model_architecture", "sdxl")+ from ..setup import runtime as setup_runtime+ if setup_runtime.local_mode(prefs.preferences):+ setup_runtime.refresh_models() # the panel's Install line follows the same refreshdef _bg_work():model_list = Nonediff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.pyindex 865987e..0d15de3 100644--- a/stablegen/ui/panel.py+++ b/stablegen/ui/panel.py@@ -212,6 +212,8 @@ class StableGenPanel(bpy.types.Panel):and scene.trellis2_generate_from == 'prompt'):box.prop(scene, "trellis2_initial_image_arch")return+ from ..setup.prefs_ui import draw_panel_notices+ draw_panel_notices(layout, context)config_error_message = Noneif not os.path.exists(addon_prefs.output_dir):@@ -276,7 +278,20 @@ class StableGenPanel(bpy.types.Panel):) if not trellis2_op and not comfy_tex_op else Noneif config_error_message:- if config_error_message == "ComfyUI offline":+ from ..setup import runtime as setup_runtime+ if config_error_message == "ComfyUI offline" and setup_runtime.local_mode(addon_prefs):+ # StableGen runs this ComfyUI: say what it is doing and offer Start instead of a refresh+ state = setup_runtime.comfy().state+ split = action_row.split(factor=0.85, align=True)+ split.operator("object.trellis2_generate", text={+ 'starting': "Starting ComfyUI…", 'running': "Connecting to ComfyUI…",+ 'exited': "ComfyUI stopped unexpectedly"}.get(state, "Cannot generate: ComfyUI stopped"),+ icon="SORTTIME" if state in ('starting', 'running') else "ERROR")+ if state not in ('starting', 'running'):+ split.operator("stablegen.comfy_start", text="", icon='PLAY')+ else:+ split.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')+ elif config_error_message == "ComfyUI offline":split = action_row.split(factor=0.85, align=True)split.operator("object.trellis2_generate", text="Cannot generate: " + config_error_message, icon="ERROR")split.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')@@ -531,7 +546,20 @@ class StableGenPanel(bpy.types.Panel):status_row.label(text=scene.sg_masked_status)elif config_error_message:# Split the row to have the error message/disabled button and the refresh button- if config_error_message == "ComfyUI offline":+ from ..setup import runtime as setup_runtime+ if config_error_message == "ComfyUI offline" and setup_runtime.local_mode(addon_prefs):+ # StableGen runs this ComfyUI: say what it is doing and offer Start instead of a refresh+ state = setup_runtime.comfy().state+ split = action_row.split(factor=0.85, align=True)+ split.operator("object.test_stable", text={+ 'starting': "Starting ComfyUI…", 'running': "Connecting to ComfyUI…",+ 'exited': "ComfyUI stopped unexpectedly"}.get(state, "Cannot generate: ComfyUI stopped"),+ icon="SORTTIME" if state in ('starting', 'running') else "ERROR")+ if state not in ('starting', 'running'):+ split.operator("stablegen.comfy_start", text="", icon='PLAY')+ else:+ split.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')+ elif config_error_message == "ComfyUI offline":split = action_row.split(factor=0.85, align=True) # Adjust factor as neededsplit.operator("object.test_stable", text="Cannot generate: " + config_error_message, icon="ERROR") # Use ERROR icon# Use the operator from __init__.pydiff --git a/stablegen/ui/studio.py b/stablegen/ui/studio.pyindex a0d8195..dac3e70 100644--- a/stablegen/ui/studio.py+++ b/stablegen/ui/studio.py@@ -24,14 +24,17 @@ from . import studio_help as help_textfrom . import studio_actions as action_stylefrom . import studio_lora as lorafrom . import studio_tips as tips+from . import studio_setup as setup_pagefrom .presentation import Layout, Control, Section, STRUCTURAL_PROPERTIES, TOOL_SECTIONSfrom .studio_text import TextBuffer, wrapfrom .studio_widgets import (Painter, FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP,- TEXT_LINE_HEIGHT, TEXT_PADDING, font_size)+ TEXT_LINE_HEIGHT, TEXT_PADDING, color, font_size)from .presets import (PRESETS, PRESET_MODEL_NAMES, PRESET_VARIANTS, PRESET_WORKFLOWS,preset_label as _preset_label, preset_model as _preset_model,preset_workflow as _preset_workflow, strip_word as _strip)from ..utils import sg_modal_active+from ..cameras import visibility+from ..setup import prefs_ui as setup_prefs, runtime as setup_runtimefrom ..core import ADDON_PKG, legacy_panel_enabledfrom ..core.generation_status import WAITING_STAGESfrom ..core.architectures import ARCHITECTURE_ITEMS, QWEN_ARCHITECTURES, architecture_status@@ -1593,7 +1596,7 @@ class StudioSession:return PAGES + [('TOOLS', 'Tools')]def more_menu(self, rect):- available = {self.section_page(s) for s in self.document.sections}+ available = {self.section_page(s) for s in self.document.sections} | {'SETUP'}primary = dict(self.pages())self.menu = {'anchor': rect, 'items': [(key, name, '') for key, name in MORE if key in available and key not in primary],'query': '', 'binding': None, 'index': 0, 'scroll': 0}@@ -1662,6 +1665,7 @@ class StudioSession:corners='RIGHT' if i == len(buttons) - 1 else 'NONE')button_x += button_widthy += max(left, right)+ y = setup_page.draw_model_hint(self, p, x, y, width)pages = self.pages() + [('MORE', 'More')]p.outline(x, y, width, 28, 'card', 'section_border', 4)compact = width < 360@@ -1793,20 +1797,60 @@ class StudioSession:primary = model.action(self.document, 'object.test_stable', 'object.stablegen_regenerate','object.trellis2_generate', 'object.trellis2_batch_generate', 'stablegen.masked_edit')disabled_reason = ''+ # the server line's dot: green while ComfyUI answers, blue while it starts or is checked+ dot = 'ok' if prefs.server_online else 'accent' if checking_server else 'warning'+ comfy = None # the ComfyUI StableGen runs, while it doesn't answer yetif primary:text = primary.control.kwargs.get('text', '')if any(word in text.lower() for word in ('cannot', 'enable online', 'select an image')):disabled_reason = text.replace('Cannot generate: ', '').replace('Cannot edit: ', '')if prefs.server_address and not prefs.server_online and not checking_server:disabled_reason = 'ComfyUI offline · ' + prefs.server_address+ if setup_runtime.local_mode(prefs): # StableGen runs this ComfyUI: say what it is doing+ comfy = setup_runtime.comfy()+ disabled_reason = {+ 'starting': f'Starting ComfyUI… {int(time.time() - comfy.started_at)} s',+ 'running': 'Connecting to ComfyUI…', 'exited': 'ComfyUI stopped unexpectedly',+ 'unresponsive': 'ComfyUI is not answering'}.get(comfy.state, 'ComfyUI stopped')+ dot = {'starting': 'accent', 'running': 'accent', 'exited': 'warning',+ 'unresponsive': 'warning'}.get(comfy.state, 'muted')scope = 'TRELLIS.2 · Shape and texture' if native else f'{len(selected)} selected views' if selected else f'{count} views · ' + ('Selected objects' if scene.texture_objects == 'selected' else 'All visible objects')- p.text('Checking server…' if checking_server else disabled_reason or ('Reproject changes before baking' if self.dirty_projection else scope), x, y, 10,- 'warning' if disabled_reason or self.dirty_projection else 'muted', width - 64)- if selected and not native:+ # Start, or Log and Restart, on the line itself while StableGen's ComfyUI isn't up+ commands = []+ if comfy is not None and comfy.state in ('exited', 'unresponsive'):+ commands = [('footer-comfy-log', 'Log', 'document', ('operator', 'stablegen.comfy_open_log', {'which': 'COMFYUI'}),+ 'Open the ComfyUI log'),+ ('footer-comfy-restart', 'Restart', 'reset', ('operator', 'stablegen.comfy_start', {}),+ 'Start ComfyUI again')]+ elif comfy is not None and comfy.state not in ('starting', 'running'):+ commands = [('footer-comfy-start', 'Start', 'play', ('operator', 'stablegen.comfy_start', {}),+ 'Start ComfyUI in the background')]+ line_right = x + width+ for key, label, icon, action, hint in reversed(commands):+ button_width = p.measure(label, 10) + 30+ line_right -= button_width+ with _viewport(self):+ available = model.operator(action[1]).poll() and not self.busy+ p.button(key, (line_right, y - 3, button_width, 18), label, action, icon=icon, enabled=available,+ hover=self.hovered(key), hint=hint, text_size=10)+ # a ComfyUI that is stopped or starting is no fault: its line stays muted+ quiet = comfy is not None and comfy.state in ('stopped', 'starting', 'running')+ p.rect(x, y + 4, 7, 7, dot, 3.5)+ p.text('Checking server…' if checking_server else disabled_reason or ('Reproject changes before baking' if self.dirty_projection else scope), x + 13, y, 10,+ 'warning' if (disabled_reason or self.dirty_projection) and not quiet else 'muted',+ line_right - x - 19 if commands else width - 77)+ if commands:+ pass+ elif selected and not native:p.button('all-views', (x + width - 65, y - 3, 65, 18), 'All views', self.clear_camera_selection,enabled=not self.busy, hint='Clear only the selected cameras; retain selected meshes')else:p.text(f'Seed {scene.trellis2_seed if native else scene.seed}', x + width - 64, y, 10, 'muted', 64)+ if comfy is not None and comfy.state == 'starting':+ # ComfyUI doesn't say how far along it is: a bar that slows as it fills+ elapsed = time.time() - comfy.started_at+ p.rect(x, y + 15, width, 2, 'line', 1)+ p.rect(x, y + 15, width * min(.95, 1 - .5 ** (elapsed / 20)), 2, 'accent', 1)y += 20if decision:for i, item in enumerate(decision):@@ -1818,6 +1862,8 @@ class StudioSession:label = 'Generate asset' if native else 'Regenerate selected views' if c.args[0] == 'object.stablegen_regenerate' else 'Edit painted selection' if c.args[0] == 'stablegen.masked_edit' else 'Generate textures'with _viewport(self):available = primary.enabled and not disabled_reason and model.operator(c.args[0]).poll()+ # StableGen's own ComfyUI has its commands on the line above; refresh only once it runs+ refresh_server = refresh_server and (comfy is None or comfy.state == 'running')refresh_width = 34 if refresh_server else 0p.button('generate', (x, y, width - refresh_width, 28), label, ('operator', c.args[0], c.properties),icon='play', style='primary', enabled=available and not self.busy and not checking_server,@@ -2639,8 +2685,10 @@ class StudioSession:self.card_bounds = {}p.panel()x, width = 12, p.width - 24+ setup_page.open_first_run(self)top = self.draw_header(p, x, width)- bottom = self.draw_footer(p, x, width)+ # the setup page has nothing to generate: its cards take the whole height+ bottom = p.height - 6 if self.page == 'SETUP' else self.draw_footer(p, x, width)narrow = width < cards.SIDE_BY_SIDE_WIDTHif narrow and not tips.dismissed(tips.WIDEN_HINT):bottom = self.draw_widen_hint(p, x, width, bottom)@@ -2649,8 +2697,14 @@ class StudioSession:offset = self.scroll.get(self.page, 0)y = top + 12 - offsetfor node in self.document.notices:+ # the model hint is drawn under Architecture, and the setup page shows what the first-run card says+ if node.has_operator(*setup_prefs.HINT_OPERATORS) or (+ self.page == 'SETUP' and node.has_operator('stablegen.open_setup')):+ continuey = self.draw_node(p, node, x, y, width, 'notices')- if self.page == 'GENERATE':+ if self.page == 'SETUP':+ y = setup_page.draw(self, p, x, y, width)+ elif self.page == 'GENERATE':y = self.draw_generate(p, x, y, width)elif self.page == 'CAMERAS':y = self.draw_cameras(p, x, y, width)diff --git a/stablegen/ui/studio_setup.py b/stablegen/ui/studio_setup.pynew file mode 100644index 0000000..e70f26f--- /dev/null+++ b/stablegen/ui/studio_setup.py@@ -0,0 +1,522 @@+"""The ComfyUI setup page of the StableGen panel (layout B of ref/setup-ui-20261103).++Where ComfyUI comes from, installing StableGen's own, its status with Start and Stop, and the models with their+install progress. It draws the state of stablegen/setup/runtime.py in the panel's own style and runs the same+operators as the preferences section, which stays as the place for the port and extra arguments.+"""+import bpy++from . import studio_cards as cards+from . import studio_tips as tips+from .studio_text import wrap+from .studio_widgets import CONTROL_GAP, CONTROL_HEIGHT, FONT_SIZE, font_size+from ..setup import installer, packages, prefs_ui, runtime++OPENED = 'setup_page_opened' # the page opens by itself once, on the first run+MODES = (+ ('OWN', "Install StableGen's own", "Recommended",+ "About 5 GB. Nothing else to install, and it starts and stops by itself."),+ ('LOCAL', "Use my ComfyUI folder", "", "Adds StableGen's nodes and models to your install."),+ ('REMOTE', "Connect to a server", "", "ComfyUI on another machine or a cloud GPU."),+)+MODE_NAMES = {'OWN': "StableGen's own", 'LOCAL': "Your ComfyUI folder", 'REMOTE': "Remote server"}+STATES = {'stopped': ("Stopped", 'muted'), 'starting': ("Starting…", 'accent'), 'running': ("Running", 'ok'),+ 'exited': ("Stopped unexpectedly", 'warning'), 'unresponsive': ("Not answering", 'warning')}+ROW_ICONS = {"trellis2": 'cube', "pbr_marigold": 'layers', "pbr_marigold_v2": 'layers', "skintokens": 'rig',+ "lato2": 'modifier'}+# Shown at once; the rest sit under "More"+PRIMARY = {"core", "qwen_image_21", "qwen_core", "trellis2", "pbr_marigold", "skintokens", "lato2"}+ROW_HEIGHT = 40+++def needed(prefs=None) -> bool:+ """ComfyUI is not set up: nothing configured, or the folder of a local mode is missing."""+ p = prefs or runtime.prefs()+ if p.comfy_mode == 'REMOTE':+ return not p.server_online and p.server_address == "127.0.0.1:8188"+ return runtime.comfy_folder(p) is None+++def open_first_run(session):+ """Show this page once when ComfyUI is not set up yet."""+ if session.page != 'SETUP' and not tips.dismissed(OPENED) and needed():+ tips.dismiss(OPENED)+ session.page = 'SETUP'+++def draw(session, p, x, y, width):+ prefs = runtime.prefs()+ folder = runtime.comfy_folder(prefs)+ y = _card(p, 'ComfyUI', 'server', x, y, width,+ lambda cx, cy, cw: _comfy(session, p, prefs, folder, cx, cy, cw))+ review = runtime.review+ if review is not None and folder is not None and review["folder"] == str(folder):+ y = _card(p, 'Install ' + ", ".join(installer.package_info(t)["name"] for t in review["tags"]), 'download',+ x, y + 12, width, lambda cx, cy, cw: _review(session, p, review, cx, cy, cw))+ if folder is not None:+ report = runtime.ensure_report(folder)+ aside = f"{report['free_mb'] / 1024:.0f} GB free" if report and "free_mb" in report else ""+ y = _card(p, 'Models', 'layers', x, y + 12, width,+ lambda cx, cy, cw: _models(session, p, prefs, folder, report, cx, cy, cw), aside=aside,+ refresh=lambda: session.call('stablegen.comfy_refresh'))+ return y+++# --- pieces ---+def _card(p, title, icon, x, y, width, body, aside='', refresh=None):+ start = y+ p.begin_group()+ y = cards.heading(p, title, x + 12, y + 11, width - 24, icon)+ right = x + width - 12+ if refresh:+ p.button('setup-refresh', (right - 22, y - 26, 22, CONTROL_HEIGHT), '', refresh, icon='reset',+ hint='Read again which models are installed')+ right -= 28+ if aside:+ p.text(aside, right - p.measure(aside, 10), y - 22, 10, 'muted')+ p.rect(x + 12, y - 3, width - 24, 1, 'divider')+ y = body(x + 12, y + 6, width - 24) + 8+ p.end_group((x, start, width, y - start), 'subbox', 'section_border', 3)+ return y+++def _note(p, text, x, y, width, tint='secondary'):+ for _, _, line in wrap(text, width, lambda value: p.measure(value, 10)):+ p.text(line, x, y, 10, tint)+ y += 14+ return y+++def _field(session, p, key, label, value, x, y, width, action, *, icon='folder', hint=''):+ """A read-only field whose value changes through a dialog (a folder picker, an address)."""+ p.text(label, x, y, FONT_SIZE, 'text', width)+ y += 17+ hover = session.hovered(key)+ p.outline(x, y, width, CONTROL_HEIGHT, 'field', 'hover_border' if hover else 'line', 4)+ p.text(p.fit(value or 'Not set', width - 40), x + 8, y + 4, FONT_SIZE, 'field_text' if value else 'muted',+ width - 40)+ p.icon(icon, x + width - 22, y + 4, 14, 'secondary')+ p.target(key, (x, y, width, CONTROL_HEIGHT), action, True, hint)+ return y + CONTROL_HEIGHT + CONTROL_GAP + 2+++def _option(session, p, key, title, tag, description, selected, x, y, width, action):+ """One way to get ComfyUI: a radio row with a title and a line of explanation."""+ lines = wrap(description, width - 44, lambda value: p.measure(value, 10))+ height = 28 + 14 * len(lines)+ hover = session.hovered(key)+ p.outline(x, y, width, height, 'selected' if selected else 'hover_soft' if hover else 'card',+ 'accent' if selected else 'hover_border' if hover else 'line', 5)+ cy = y + 10+ p.rect(x + 11, cy + 1, 12, 12, 'accent' if selected else 'secondary', 6)+ p.rect(x + 12, cy + 2, 10, 10, 'selected' if selected else 'card', 5)+ if selected:+ p.rect(x + 14, cy + 4, 6, 6, 'accent', 3)+ p.text(title, x + 32, cy, FONT_SIZE, 'text', width - 44)+ if tag:+ p.text(tag, x + 32 + p.measure(title) + 8, cy + 1, 10, 'accent')+ for i, (_, _, line) in enumerate(lines):+ p.text(line, x + 32, cy + 17 + i * 14, 10, 'secondary')+ p.target(key, (x, y, width, height), action, True, '')+ return y + height + 6+++def _status(session, p, prefs, x, y, width):+ c = runtime.comfy()+ text, tint = STATES.get(c.state, (c.state, 'muted'))+ detail = ""+ if c.state in ('running', 'starting'):+ detail = c.address + ("" if c.owned else " · started outside StableGen")+ report = runtime.report(runtime.comfy_folder(prefs))+ gpu = ((report or {}).get("python") or {}).get("gpu")+ if gpu and c.state == 'running':+ detail += " · " + gpu.replace("NVIDIA GeForce ", "")+ elif c.message:+ detail = c.message+ height = 30+ p.outline(x, y, width, height, 'card', 'line', 5)+ p.rect(x + 10, y + 12, 7, 7, tint, 3.5)+ p.text(text, x + 24, y + 8, FONT_SIZE, 'text')+ button_width = 58+ p.text(p.fit(detail, width - 40 - p.measure(text) - button_width - 30, 10), x + 30 + p.measure(text), y + 9, 10,+ 'muted')+ bx = x + width - button_width - 4+ if c.state in ('running', 'starting', 'unresponsive'):+ p.button('setup-stop', (bx, y + 4, button_width, CONTROL_HEIGHT), 'Stop',+ lambda: session.call('stablegen.comfy_stop'), icon='stop', style='outlined',+ hint='Stop ComfyUI' if c.owned else 'Disconnect; StableGen did not start this ComfyUI')+ else:+ p.button('setup-start', (bx, y + 4, button_width, CONTROL_HEIGHT), 'Restart' if c.state == 'exited' else 'Start',+ lambda: session.call('stablegen.comfy_start'), icon='play', style='outlined',+ hint='Start ComfyUI in the background')+ y += height + 4+ folder = runtime.comfy_folder(prefs)+ if runtime.restart_needed and folder is not None and runtime.restart_needed == str(folder) and not c.owned:+ y = _note(p, "Restart ComfyUI so it loads the nodes just installed. StableGen didn't start it, so it won't "+ "restart it.", x, y + 2, width, 'warning') + 6+ if c.state in ('exited', 'unresponsive'):+ p.button('setup-log', (x, y, 80, CONTROL_HEIGHT), 'Show log',+ lambda: session.call('stablegen.comfy_open_log', {'which': 'COMFYUI'}), icon='document')+ y += CONTROL_HEIGHT + 2+ for key, prop, label in (('setup-auto', 'comfy_auto_start', 'Start when needed, stop with Blender'),+ ('setup-keep', 'comfy_keep_running', 'Keep running after Blender closes')):+ p.switch(key, (x, y, width, CONTROL_HEIGHT), label, getattr(prefs, prop),+ lambda prop=prop: _toggle(session, prefs, prop), hover=session.hovered(key))+ y += CONTROL_HEIGHT + CONTROL_GAP+ return y+++def _toggle(session, prefs, prop):+ setattr(prefs, prop, not getattr(prefs, prop))+ session.area.tag_redraw()+++def _set_mode(session, prefs, mode):+ prefs.comfy_mode = mode # while changing, the choice stays open until Use, Install or Connect+ session.area.tag_redraw()+++def _comfy(session, p, prefs, folder, x, y, width):+ job = runtime.job if runtime.job is not None and runtime.job.kind == "create" else None+ if job is not None and job.running:+ return _own_progress(session, p, job, x, y, width)+ configured = folder is not None or (prefs.comfy_mode == 'REMOTE' and not needed(prefs))+ if configured and not getattr(session, 'setup_change', False):+ where = (str(folder) if folder is not None else prefs.server_address)+ p.text(MODE_NAMES[prefs.comfy_mode], x, y, FONT_SIZE, 'text', width - 70)+ p.button('setup-change', (x + width - 64, y - 4, 64, CONTROL_HEIGHT), 'Change',+ lambda: _change(session), style='quiet', hint='Choose where ComfyUI comes from')+ y = _note(p, where, x, y + 17, width - 70, 'muted') + 6+ python = (runtime.report(folder) or {}).get("python") or {} if folder is not None else {}+ if python.get("default"): # no Python of its own: it runs with the python on PATH+ y = _note(p, f"Runs with the default python: {python.get('path')}", x, y - 4, width, 'muted') + 6+ if prefs.comfy_mode == 'OWN' and runtime.own_outdated(prefs):+ y = _note(p, f"This StableGen uses ComfyUI {installer.COMFYUI_TAG}.", x, y, width - 90, 'warning')+ p.button('setup-update', (x + width - 84, y - 18, 84, CONTROL_HEIGHT), 'Update',+ lambda: session.call('stablegen.comfy_create'), icon='download', style='outlined')+ y += 6+ if prefs.comfy_mode == 'REMOTE':+ return _note(p, "Install models on that machine with installer.py from the StableGen repository.",+ x, y, width)+ return _status(session, p, prefs, x, y, width)++ for mode, title, tag, description in MODES:+ y = _option(session, p, 'setup-mode:' + mode, title, tag, description, prefs.comfy_mode == mode, x, y, width,+ lambda mode=mode: _set_mode(session, prefs, mode))+ y += 4+ if prefs.comfy_mode == 'OWN':+ y = _field(session, p, 'setup-root', 'Install folder', prefs.comfy_root, x, y, width,+ lambda: session.call('stablegen.comfy_choose_folder', {'target': 'ROOT'}),+ hint='Where StableGen keeps its own ComfyUI')+ if folder is not None: # already installed there: use it, or repair it+ installed = f"Installed · ComfyUI {runtime.own_marker(prefs).get('comfyui', '')}".rstrip()+ p.icon('check', x, y + 1, 12, 'ok')+ p.text(installed, x + 18, y, 10, 'ok', width - 110)+ p.button('setup-repair', (x + width - 84, y - 4, 84, CONTROL_HEIGHT), 'Repair',+ lambda: session.call('stablegen.comfy_create'), icon='reset', style='quiet',+ hint='Check every part and download what is missing or broken')+ return _use(session, p, "Use StableGen's own", x, y + 22, width)+ if prefs.comfy_root:+ space = _free_space(prefs.comfy_root)+ if space:+ y = _note(p, space, x, y - 2, width, 'muted') + 4+ if job is not None and not job.ok:+ y = _note(p, job.status_line(), x, y, width, 'warning') + 4+ p.button('setup-install', (x, y + 4, width, 28), 'Retry' if job is not None else 'Install ComfyUI',+ lambda: session.call('stablegen.comfy_create'), icon='download', style='primary',+ enabled=bool(prefs.comfy_root), hint='Download ComfyUI, Python and torch for your GPU')+ return y + 36+ if prefs.comfy_mode == 'LOCAL':+ y = _field(session, p, 'setup-local', 'ComfyUI folder', prefs.comfy_local_path, x, y, width,+ lambda: session.call('stablegen.comfy_choose_folder', {'target': 'LOCAL'}),+ hint="Your ComfyUI folder, with 'models' and 'custom_nodes'")+ if folder is not None:+ return _use(session, p, "Use this folder", x, y + 2, width)+ if prefs.comfy_local_path:+ y = _note(p, "No ComfyUI here: choose the folder with 'models' and 'custom_nodes'.", x, y, width,+ 'warning')+ return y+ y = _field(session, p, 'setup-address', 'Server address', prefs.server_address, x, y, width,+ lambda: session.call('stablegen.comfy_set_address'), icon='rename',+ hint='Address and port of the ComfyUI server')+ p.button('setup-connect', (x, y + 2, width, 26), 'Connect', lambda: _connect(session),+ icon='reset', style='outlined')+ return y + 32+++def _use(session, p, label, x, y, width):+ """Leave the choices for the status of the ComfyUI just chosen."""+ p.button('setup-use', (x, y + 4, width, 28), label, lambda: _done(session), icon='check', style='primary')+ return y + 36+++def _done(session):+ session.setup_change = False+ error = runtime.follow_folder() # the running ComfyUI was for the folder chosen before+ if error:+ session.tell(error)+ session.area.tag_redraw()+++def _connect(session):+ session.call('stablegen.check_server_status')+ _done(session)+++def _change(session):+ session.setup_change = True # trying the choices restarts nothing until Use (runtime.choosing)+ session.area.tag_redraw()+++def _own_progress(session, p, job, x, y, width):+ p.text('Installing ComfyUI', x, y, FONT_SIZE, 'text')+ pct = f"{job.progress():.0%}"+ p.text(pct, x + width - p.measure(pct, 10), y + 1, 10, 'muted')+ y += 22+ for step_id in job.order:+ item = job.items[step_id]+ done = item.get("status") in ('installed', 'present')+ current = step_id == job.current+ failed = item.get("status") == 'failed'+ p.icon('check' if done else 'x' if failed else 'download' if current else 'minus', x, y, 13,+ 'ok' if done else 'warning' if failed else 'accent' if current else 'muted')+ p.text(item["name"], x + 20, y, FONT_SIZE, 'secondary' if done else 'text' if current else 'muted',+ width - 110)+ if current and item.get("total"):+ size = f"{item['done'] / 1024**3:.1f} of {item['total'] / 1024**3:.1f} GB"+ else:+ size = packages.size_text(item.get("size_mb", 0)) if item.get("size_mb") else ""+ p.text(size, x + width - p.measure(size, 10), y + 1, 10, 'muted')+ y += 18+ if current and item.get("total"):+ p.rect(x + 20, y - 1, width - 20, 3, 'line', 1)+ p.rect(x + 20, y - 1, (width - 20) * min(1, item["done"] / item["total"]), 3, 'blue', 1)+ y += 6+ y += 4+ y = _note(p, "You can keep working while it installs.", x, y + 4, width - 90, 'muted')+ p.button('setup-cancel', (x + width - 80, y - 18, 80, CONTROL_HEIGHT), 'Cancel',+ lambda: session.call('stablegen.comfy_cancel_install'), icon='x', style='outlined')+ return y + 8+++def _models(session, p, prefs, folder, report, x, y, width):+ if report is None or report.get("loading"):+ return _note(p, "Reading which models are installed…", x, y, width, 'muted')+ if "error" in report:+ return _note(p, report.get("message", "Could not read this ComfyUI"), x, y, width, 'warning')+ job = runtime.job+ if job is not None and job.kind == "install" and job.folder == str(folder) and not job.running and not job.ok:+ y = _note(p, f"{job.title}: {job.status_line()}", x, y, width - 90, 'warning')+ p.button('setup-install-log', (x + width - 84, y - 18, 84, CONTROL_HEIGHT), 'Show log',+ lambda: session.call('stablegen.comfy_open_log', {'which': 'INSTALL'}), icon='document')+ y += 8+ rows = list(packages.visible_rows(prefs.enable_deprecated_architectures, prefs.enable_experimental_architectures))+ more = getattr(session, 'setup_more', False)+ shown = [r for r in rows if more or PRIMARY & set(r[1])]+ hidden = [r for r in rows if not PRIMARY & set(r[1])]+ group = None+ for row_group, tags, title, purpose in shown:+ if row_group != group:+ group = row_group+ p.text(group, x, y + (4 if y else 0), 10, 'muted')+ y += 22+ y = _model_row(session, p, tags, title, purpose, packages.row_state(tags, report), job, x, y, width)+ if hidden:+ label = 'Fewer models' if more else f'More · {len(hidden)} models'+ p.button('setup-more', (x, y + 4, width, CONTROL_HEIGHT), label,+ lambda: _more(session), icon='up' if more else 'down', style='quiet')+ y += CONTROL_HEIGHT + 8+ return y+++def _more(session):+ session.setup_more = not getattr(session, 'setup_more', False)+ session.area.tag_redraw()+++def _model_row(session, p, tags, title, purpose, state, job, x, y, width):+ installing = job is not None and job.running and set(job.tags) & set(tags)+ place = runtime.queued(list(tags))+ p.rect(x, y - 4, width, 1, 'divider')+ p.icon(ROW_ICONS.get(tags[0], 'image'), x, y + 6, 14, 'secondary')+ tx, right = x + 24, 86+ p.text(p.fit(title, width - 24 - right), tx, y + 2, FONT_SIZE, 'text')+ joined = ",".join(tags)+ if installing:+ rate = job.rate_text()+ meta = f"{job.progress():.0%} · {job.size_text()}" + (f" · {rate}" if rate else "")+ p.text(p.fit(meta, width - 24 - 32, 10), tx, y + 18, 10, 'accent')+ p.rect(tx, y + 32, width - 24 - 32, 3, 'line', 1)+ p.rect(tx, y + 32, (width - 24 - 32) * job.progress(), 3, 'blue', 1)+ p.button('setup-cancel-install', (x + width - 26, y + 6, 26, CONTROL_HEIGHT), '',+ lambda: session.call('stablegen.comfy_cancel_install'), icon='x',+ hint='Cancel this install; finished files stay, downloads resume next time, and the queue goes on')+ return y + ROW_HEIGHT+ if place is not None:+ p.text(f"Queued · {packages.queue_text(place)}", tx, y + 18, 10, 'accent')+ p.button('setup-unqueue:' + tags[0], (x + width - 26, y + 6, 26, CONTROL_HEIGHT), '',+ lambda: session.call('stablegen.comfy_unqueue', {'tags': joined}), icon='x',+ hint='Take it out of the queue')+ return y + ROW_HEIGHT+ size = state["size_mb"] if state["state"] == "installed" else state["download_mb"]+ creating = job is not None and job.running and job.kind == "create"+ queueing = job is not None and job.running and not creating+ trash = 28 if packages.removable_state(tags, state, runtime.node_policy()) else 0+ p.text(p.fit(packages.meta_text(purpose, tags, size), width - 24 - right - trash, 10), tx, y + 18, 10, 'muted')+ if state["missing_core_nodes"]:+ p.text("Needs a newer ComfyUI", tx, y + 31, 10, 'warning')+ if state["state"] == "installed":+ p.icon('check', x + width - 74 - trash, y + 7, 12, 'ok')+ p.text('Installed', x + width - 58 - trash, y + 6, 10, 'ok')+ elif state["state"] != "unknown":+ p.button('setup-install:' + tags[0], (x + width - 80, y + 4, 80, CONTROL_HEIGHT),+ 'Finish' if state["state"] == "partial" else 'Install',+ lambda: session.call('stablegen.comfy_install', {'tags': joined}), icon='download',+ style='outlined', enabled=not creating,+ hint="StableGen's own ComfyUI is still installing" if creating else+ f'Add it to the queue ({packages.size_text(state["download_mb"])})' if queueing else+ f'Download {packages.size_text(state["download_mb"])} into ComfyUI')+ if trash:+ tx_trash = x + width - 24 if state["state"] == "installed" else x + width - 80 - trash+ p.button('setup-remove:' + tags[0], (tx_trash, y + 4, 24, CONTROL_HEIGHT), '',+ lambda: session.call('stablegen.comfy_remove', {'tags': joined, 'title': title}), icon='trash',+ enabled=not creating, hint="Remove it: delete its models and unfinished downloads" + (+ " and its nodes" if runtime.node_policy() == "all" else+ "; nodes from elsewhere stay, other workflows may use them")+ + ". What another installed package uses stays")+ return y + ROW_HEIGHT + (10 if state["missing_core_nodes"] else 0)+++def _review(session, p, review, x, y, width):+ plan = review.get("plan")+ if plan is None:+ y = _note(p, "Checking what this changes in your ComfyUI…", x, y, width, 'muted') + 4+ elif "error" in plan:+ y = _note(p, plan.get("message", "Could not check this ComfyUI"), x, y, width, 'warning') + 4+ elif runtime.needs_review(plan):+ p.text("Changes your ComfyUI's Python", x, y, 10, 'warning')+ y += 16+ lines = [f"{pip['spec']}" + (f" (you have {pip['installed']})" if pip.get("installed") else " (new)")+ for pip in plan.get("pip", [])]+ lines += [f"{s['node']}: {s['step']}" for s in plan.get("steps", [])]+ lines += [f"{n['name']}: moved to the tested commit" for n in plan.get("nodes", [])+ if n["action"] == "move to pin"]+ for line in lines:+ p.rect(x, y, 2, 14, 'warning', 1)+ p.text(p.fit(line, width - 12, 10), x + 10, y, 10, 'secondary')+ y += 16+ y = _note(p, "Your package versions are saved first, to roll back from.", x, y + 4, width, 'muted') + 6+ for key in review["notices"]:+ y = _notice(p, installer.LICENSE_NOTICES.get(key, []), x, y, width) + 6+ ready = plan is not None+ button = 132 if review["notices"] else 80+ p.button('setup-review-cancel', (x + width - button - 88, y + 4, 80, 26), 'Cancel',+ lambda: session.call('stablegen.comfy_cancel_review'), style='outlined')+ p.button('setup-review-accept', (x + width - button, y + 4, button, 26),+ runtime.accept_label(review),+ lambda: session.call('stablegen.comfy_confirm_install'), icon='check', style='primary', enabled=ready)+ return y + 34+++def _notice(p, lines, x, y, width):+ """A license notice: the CLI wraps its lines by hand, so each paragraph is joined and wrapped to the card. The+ first line is its title, which the card already says."""+ paragraphs, current = [], []+ for line in lines[1:]:+ if line:+ current.append(line)+ elif current:+ paragraphs.append(" ".join(current))+ current = []+ if current:+ paragraphs.append(" ".join(current))+ for text in paragraphs:+ y = _note(p, text, x, y, width, 'secondary') + 6+ return y+++HINT_HEIGHT = 28 # the tab switcher's: the line is drawn like its selected tab+HINT_ACTIONS = { # what the button of a missing model does: icon, operator, hint+ 'missing': ('download', 'stablegen.comfy_install', 'Download it into your ComfyUI; you can keep working'),+ 'server-local': ('download', 'stablegen.comfy_use_server_folder',+ "Use this ComfyUI's folder, so StableGen can install models into it"),+ 'server': ('clone', 'stablegen.comfy_copy_install_command',+ 'Copy the installer.py command that installs it; run it on the server'),+}+++def draw_model_hint(session, p, x, y, width):+ """The line under Architecture when the chosen model isn't on the ComfyUI, drawn like the tab switcher's+ selected tab: amber with Install as its right segment, then blue while it waits in the queue and with the+ download's progress along its bottom. The Setup page lists the models instead."""+ hint = prefs_ui.model_hint(bpy.context) if session.page != 'SETUP' else None+ if hint is None:+ return y+ h = HINT_HEIGHT+ text_y = y + (h - font_size(FONT_SIZE)) / 2 - 1+ if hint['kind'] in ('installing', 'queued'):+ installing = hint['kind'] == 'installing'+ p.outline(x, y, width, h, 'tab_selected', 'accent', 4)+ p.icon('download', x + 9, y + 7, 13, 'accent')+ detail = p.fit(hint['detail'], width * .55, 10)+ detail_x = x + width - 32 - p.measure(detail, 10)+ p.text(p.fit(hint['text'], detail_x - x - 40), x + 30, text_y, FONT_SIZE, 'accent')+ p.text(detail, detail_x, text_y + 1, 10, 'secondary')+ if installing:+ p.rect(x + 1, y + h - 3, (width - 2) * min(1, hint['progress']), 2, 'accent')+ p.button('hint-cancel', (x + width - 27, y + 3, 24, h - 6), '',+ lambda: session.call('stablegen.comfy_cancel_install'), icon='x',+ hint='Cancel the install; finished files stay, and downloads resume next time')+ else:+ p.button('hint-cancel', (x + width - 27, y + 3, 24, h - 6), '',+ lambda: session.call('stablegen.comfy_unqueue', {'tags': ",".join(hint['tags'])}), icon='x',+ hint='Take it out of the queue')+ return y + h + 8+ kind = 'server-local' if hint['kind'] == 'server' and hint['local'] else hint['kind']+ icon, operator, tip = HINT_ACTIONS[kind]+ properties = {} if kind == 'server-local' else {'tags': ",".join(hint['tags'])}+ running = runtime.job if runtime.job is not None and runtime.job.running else None+ enabled = not (kind == 'missing' and running is not None and running.kind == "create")+ if kind == 'missing' and running is not None and enabled:+ tip = 'Add it to the queue: it downloads after the install that runs'+ label = hint['button']+ segment = min(p.measure(label) + 40, width * .5)+ sx = x + width - segment+ p.outline(x, y, width, h, 'warning_tab', 'warning', 4)+ if enabled and session.hovered('hint-action'):+ p.rect(sx, y + 1, segment - 1, h - 2, 'warning_strong', 3, corners='RIGHT')+ p.rect(sx, y + 1, 1, h - 2, 'warning') # divided like the switcher's tabs+ p.icon('warning', x + 9, y + 7, 13, 'warning')+ p.text(p.fit(hint['text'], sx - x - 40), x + 30, text_y, FONT_SIZE, 'warning')+ tint = 'warning' if enabled else 'disabled'+ label_x = sx + (segment - p.measure(label) - 17) / 2+ p.icon(icon, label_x, y + 7, 13, tint)+ p.text(label, label_x + 17, text_y, FONT_SIZE, tint)+ p.target('hint-action', (sx, y, segment, h), lambda: session.call(operator, properties), enabled,+ tip if enabled else "StableGen's own ComfyUI is still installing")+ return y + h + 8+++def _free_space(path_text):+ from ..setup.prefs_ui import _free_space_text+ return _free_space_text(path_text)+++class SG_OT_OpenSetup(bpy.types.Operator):+ """Open the ComfyUI setup: the Setup page of the StableGen panel, or the preferences with the legacy panel"""+ bl_idname = 'stablegen.open_setup'+ bl_label = 'Set up ComfyUI'+ bl_options = {'INTERNAL'}++ def execute(self, context):+ from . import studio+ sessions = [s for s in studio._sessions.values() if getattr(s, 'alive', True)]+ if not sessions:+ bpy.ops.preferences.addon_show('INVOKE_DEFAULT', module=runtime.ADDON_PKG)+ return {'FINISHED'}+ for session in sessions:+ session.navigate('SETUP')+ return {'FINISHED'}+++CLASSES = (SG_OT_OpenSetup,)diff --git a/stablegen/ui/studio_widgets.py b/stablegen/ui/studio_widgets.pyindex 983e36b..9c9eaa2 100644--- a/stablegen/ui/studio_widgets.py+++ b/stablegen/ui/studio_widgets.py@@ -72,8 +72,18 @@ ICON_PATHS = {'rig': [[(10, 2), (10, 9), (4, 6)], [(10, 9), (17, 5)], [(10, 9), (6, 19)], [(10, 9), (16, 18)]],'graph': [[(2, 2), (2, 18), (19, 18)], [(4, 14), (8, 8), (12, 11), (18, 3)]],'shield': [[(10, 2), (18, 5), (17, 13), (10, 19), (3, 13), (2, 5), (10, 2)]],+ 'rename': [[(3, 18), (3, 14), (14, 3), (18, 7), (7, 18), (3, 18)], [(12, 5), (16, 9)]],+ 'server': [[(3, 3), (18, 3), (18, 9), (3, 9), (3, 3)], [(3, 12), (18, 12), (18, 18), (3, 18), (3, 12)],+ [(11, 6), (15, 6)], [(11, 15), (15, 15)]],+ 'image': [[(2, 3), (19, 3), (19, 18), (2, 18), (2, 3)], [(2, 15), (7, 10), (11, 14), (14, 11), (19, 16)]],+ 'cube': [[(10, 2), (18, 6), (18, 15), (10, 19), (2, 15), (2, 6), (10, 2)], [(2, 6), (10, 10), (18, 6)],+ [(10, 10), (10, 19)]],+ 'trash': [[(3, 5), (18, 5)], [(8, 5), (8, 2.5), (13, 2.5), (13, 5)], [(5, 5), (6, 19), (15, 19), (16, 5)],+ [(8.5, 9), (8.5, 15.5)], [(12.5, 9), (12.5, 15.5)]],+ 'warning': [[(10.5, 2), (19.5, 18.5), (1.5, 18.5), (10.5, 2)], [(10.5, 8), (10.5, 12.5)]],}-ICON_CIRCLES = {'camera': (10.5, 11, 4), 'eye': (10, 10, 2.5), 'search': (9, 9, 6)}+ICON_CIRCLES = {'camera': (10.5, 11, 4), 'eye': (10, 10, 2.5), 'search': (9, 9, 6), 'server': (6.5, 6, 1),+ 'image': (14, 7.5, 1.6), 'warning': (10.5, 15.5, .6)}# Filled convex shapes, such as arrowheads that would blur into a thin stroke.ICON_FILLS = {'reset': [head for _, head in _SYNC]}ICON_PAD = 2@@ -335,7 +345,7 @@ COLORS = {key: color(value) for key, value in {'raised': '545454', 'line': '494949', 'divider': '464646', 'text': 'e6e6e6','secondary': 'c4c4c4', 'muted': '999999', 'accent': '8fa6ca','blue': '4772b3', 'on_accent': 'ffffff', 'hover': '545454', 'disabled': '787878',- 'warning': 'c0a673', 'selected': '404c5e', 'card': '353535',+ 'warning': 'c0a673', 'selected': '404c5e', 'card': '353535', 'ok': '7dba82','text_selected': '4a4a4a', 'number_selected': '6e6e6e','cursor': '71a8ff', 'switch_off': '545454', 'switch_knob': 'ffffff','outer_edge': '494949',@@ -381,6 +391,7 @@ def theme_colors(context):card = _over(getattr(ui, 'panel_sub_back', (0, 0, 0, .12)), panel)subbox = _mix(card, field_back, .2)section_border = _mix(border, text, .075)+ warning = _mix(_rgba(getattr(ui.wcol_state, 'warning', COLORS['warning'])), text, .35)return {'panel': panel, 'field': field_back, 'field_text': _rgba(field.text),'number': _over(number.inner, panel), 'number_text': _rgba(number.text),@@ -409,7 +420,10 @@ def theme_colors(context):'dependency_rail': _mix(panel, text, .23),'text_selected': _over(field.item, field_back),'number_selected': _mix(_over(number.inner, panel), _rgba(number.text), .18),- 'warning': _mix(_rgba(getattr(ui.wcol_state, 'warning', COLORS['warning'])), text, .35),+ 'warning': warning,+ # a model that isn't installed: the tab switcher's selected tab in amber, and its hovered segment+ 'warning_tab': _mix(card, warning, .17), 'warning_strong': _mix(panel, warning, .3),+ 'ok': _mix(COLORS['ok'], text, .2), # installed, running: the theme has no success color'switch_off': _over(ui.wcol_toggle.inner, panel), 'switch_knob': _rgba(ui.wcol_option.item),'switch_off_hover': _mix(_over(ui.wcol_toggle.inner, panel), text, .14),'tooltip': _over(ui.wcol_tooltip.inner, panel),