diff --git a/comfyui_manager/__init__.py b/comfyui_manager/__init__.py
index 01089fdd..aba770e5 100644
--- a/comfyui_manager/__init__.py
+++ b/comfyui_manager/__init__.py
@@ -11,13 +11,20 @@ def prestartup():
def start():
logging.info('[START] ComfyUI-Manager')
- from .glob import manager_server # noqa: F401
- from .glob import share_3rdparty # noqa: F401
- from .glob import cm_global # noqa: F401
+ from .common import cm_global # noqa: F401
- if os.environ.get('ENABLE_LEGACY_COMFYUI_MANAGER_FRONT', 'false') == 'true':
- import nodes
- nodes.EXTENSION_WEB_DIRS['comfyui-manager-legacy'] = os.path.join(os.path.dirname(__file__), 'js')
+ should_show_legacy_manager_front = os.environ.get('ENABLE_LEGACY_COMFYUI_MANAGER_FRONT', 'false') == 'true' or ENABLE_LEGACY_COMFYUI_MANAGER_FRONT_DEFAULT
+ if not args.disable_manager and should_show_legacy_manager_front:
+ try:
+ from .legacy import manager_server # noqa: F401
+ from .legacy import share_3rdparty # noqa: F401
+ import nodes
+ nodes.EXTENSION_WEB_DIRS['comfyui-manager-legacy'] = os.path.join(os.path.dirname(__file__), 'js')
+ except Exception as e:
+ print("Error enabling legacy ComfyUI Manager frontend:", e)
+ else:
+ from .glob import manager_server # noqa: F401
+ from .glob import share_3rdparty # noqa: F401
def should_be_disabled(fullpath:str) -> bool:
diff --git a/comfyui_manager/cm-cli.py b/comfyui_manager/cm-cli.py
index a3006807..8a3f49ed 100644
--- a/comfyui_manager/cm-cli.py
+++ b/comfyui_manager/cm-cli.py
@@ -15,7 +15,7 @@ import git
import importlib
-import manager_util
+from .common import manager_util
# read env vars
# COMFYUI_FOLDERS_BASE_PATH is not required in cm-cli.py
@@ -35,10 +35,11 @@ if not os.path.exists(os.path.join(comfy_path, 'folder_paths.py')):
import utils.extra_config
-from .glob import cm_global
+from .common import cm_global
from .glob import manager_core as core
+from .common import context
from .glob.manager_core import unified_manager
-from .glob import cnr_utils
+from .common import cnr_utils
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
@@ -84,7 +85,7 @@ def read_downgrade_blacklist():
try:
import configparser
config = configparser.ConfigParser(strict=False)
- config.read(core.manager_config.path)
+ config.read(context.manager_config_path)
default_conf = config['default']
if 'downgrade_blacklist' in default_conf:
@@ -145,17 +146,17 @@ class Ctx:
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
- core.update_user_directory(user_directory)
+ context.update_user_directory(user_directory)
- if os.path.exists(core.manager_pip_overrides_path):
- with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
+ if os.path.exists(context.manager_pip_overrides_path):
+ with open(context.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
if sys.version_info < (3, 13):
cm_global.pip_overrides = {'numpy': 'numpy<2'}
- if os.path.exists(core.manager_pip_blacklist_path):
- with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
+ if os.path.exists(context.manager_pip_blacklist_path):
+ with open(context.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
@@ -168,15 +169,15 @@ class Ctx:
@staticmethod
def get_startup_scripts_path():
- return os.path.join(core.manager_startup_script_path, "install-scripts.txt")
+ return os.path.join(context.manager_startup_script_path, "install-scripts.txt")
@staticmethod
def get_restore_snapshot_path():
- return os.path.join(core.manager_startup_script_path, "restore-snapshot.json")
+ return os.path.join(context.manager_startup_script_path, "restore-snapshot.json")
@staticmethod
def get_snapshot_path():
- return core.manager_snapshot_path
+ return context.manager_snapshot_path
@staticmethod
def get_custom_nodes_paths():
@@ -701,7 +702,7 @@ def reinstall(
cmd_ctx.set_channel_mode(channel, mode)
cmd_ctx.set_no_deps(no_deps)
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for_each_nodes(nodes, act=reinstall_node)
pip_fixer.fix_broken()
@@ -755,7 +756,7 @@ def update(
if 'all' in nodes:
asyncio.run(auto_save_snapshot())
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for x in nodes:
if x.lower() in ['comfyui', 'comfy', 'all']:
@@ -856,7 +857,7 @@ def fix(
if 'all' in nodes:
asyncio.run(auto_save_snapshot())
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for_each_nodes(nodes, fix_node, allow_all=True)
pip_fixer.fix_broken()
@@ -1133,7 +1134,7 @@ def restore_snapshot(
print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
exit(1)
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
try:
asyncio.run(core.restore_snapshot(snapshot_path, extras))
except Exception:
@@ -1165,7 +1166,7 @@ def restore_dependencies(
total = len(node_paths)
i = 1
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for x in node_paths:
print("----------------------------------------------------------------------------------------------------")
print(f"Restoring [{i}/{total}]: {x}")
@@ -1184,7 +1185,7 @@ def post_install(
):
path = os.path.expanduser(path)
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
unified_manager.execute_install_script('', path, instant_execution=True)
pip_fixer.fix_broken()
@@ -1228,7 +1229,7 @@ def install_deps(
print(f"[bold red]Invalid json file: {deps}[/bold red]")
exit(1)
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for k in json_obj['custom_nodes'].keys():
state = core.simple_check_custom_node(k)
if state == 'installed':
diff --git a/comfyui_manager/common/__init__.py b/comfyui_manager/common/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/comfyui_manager/glob/cm_global.py b/comfyui_manager/common/cm_global.py
similarity index 100%
rename from comfyui_manager/glob/cm_global.py
rename to comfyui_manager/common/cm_global.py
diff --git a/comfyui_manager/glob/cnr_utils.py b/comfyui_manager/common/cnr_utils.py
similarity index 97%
rename from comfyui_manager/glob/cnr_utils.py
rename to comfyui_manager/common/cnr_utils.py
index bb4845a3..10fad45d 100644
--- a/comfyui_manager/glob/cnr_utils.py
+++ b/comfyui_manager/common/cnr_utils.py
@@ -6,7 +6,7 @@ import time
from dataclasses import dataclass
from typing import List
-from . import manager_core
+from . import context
from . import manager_util
import requests
@@ -48,9 +48,9 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
# Get ComfyUI version tag
if is_desktop:
# extract version from pyproject.toml instead of git tag
- comfyui_ver = manager_core.get_current_comfyui_ver() or 'unknown'
+ comfyui_ver = context.get_current_comfyui_ver() or 'unknown'
else:
- comfyui_ver = manager_core.get_comfyui_tag() or 'unknown'
+ comfyui_ver = context.get_comfyui_tag() or 'unknown'
if is_desktop:
if is_windows:
diff --git a/comfyui_manager/common/context.py b/comfyui_manager/common/context.py
new file mode 100644
index 00000000..1d190814
--- /dev/null
+++ b/comfyui_manager/common/context.py
@@ -0,0 +1,109 @@
+import sys
+import os
+import logging
+from . import manager_util
+import toml
+import git
+
+
+# read env vars
+comfy_path: str = os.environ.get('COMFYUI_PATH')
+comfy_base_path = os.environ.get('COMFYUI_FOLDERS_BASE_PATH')
+
+if comfy_path is None:
+ try:
+ comfy_path = os.path.abspath(os.path.dirname(sys.modules['__main__'].__file__))
+ os.environ['COMFYUI_PATH'] = comfy_path
+ except:
+ logging.error("[ComfyUI-Manager] environment variable 'COMFYUI_PATH' is not specified.")
+ exit(-1)
+
+if comfy_base_path is None:
+ comfy_base_path = comfy_path
+
+channel_list_template_path = os.path.join(manager_util.comfyui_manager_path, 'channels.list.template')
+git_script_path = os.path.join(manager_util.comfyui_manager_path, "git_helper.py")
+
+manager_files_path = None
+manager_config_path = None
+manager_channel_list_path = None
+manager_startup_script_path:str = None
+manager_snapshot_path = None
+manager_pip_overrides_path = None
+manager_pip_blacklist_path = None
+manager_components_path = None
+manager_batch_history_path = None
+
+def update_user_directory(user_dir):
+ global manager_files_path
+ global manager_config_path
+ global manager_channel_list_path
+ global manager_startup_script_path
+ global manager_snapshot_path
+ global manager_pip_overrides_path
+ global manager_pip_blacklist_path
+ global manager_components_path
+ global manager_batch_history_path
+
+ manager_files_path = os.path.abspath(os.path.join(user_dir, 'default', 'ComfyUI-Manager'))
+ if not os.path.exists(manager_files_path):
+ os.makedirs(manager_files_path)
+
+ manager_snapshot_path = os.path.join(manager_files_path, "snapshots")
+ if not os.path.exists(manager_snapshot_path):
+ os.makedirs(manager_snapshot_path)
+
+ manager_startup_script_path = os.path.join(manager_files_path, "startup-scripts")
+ if not os.path.exists(manager_startup_script_path):
+ os.makedirs(manager_startup_script_path)
+
+ manager_config_path = os.path.join(manager_files_path, 'config.ini')
+ manager_channel_list_path = os.path.join(manager_files_path, 'channels.list')
+ manager_pip_overrides_path = os.path.join(manager_files_path, "pip_overrides.json")
+ manager_pip_blacklist_path = os.path.join(manager_files_path, "pip_blacklist.list")
+ manager_components_path = os.path.join(manager_files_path, "components")
+ manager_util.cache_dir = os.path.join(manager_files_path, "cache")
+ manager_batch_history_path = os.path.join(manager_files_path, "batch_history")
+
+ if not os.path.exists(manager_util.cache_dir):
+ os.makedirs(manager_util.cache_dir)
+
+ if not os.path.exists(manager_batch_history_path):
+ os.makedirs(manager_batch_history_path)
+
+try:
+ import folder_paths
+ update_user_directory(folder_paths.get_user_directory())
+
+except Exception:
+ # fallback:
+ # This case is only possible when running with cm-cli, and in practice, this case is not actually used.
+ update_user_directory(os.path.abspath(manager_util.comfyui_manager_path))
+
+
+def get_current_comfyui_ver():
+ """
+ Extract version from pyproject.toml
+ """
+ toml_path = os.path.join(comfy_path, 'pyproject.toml')
+ if not os.path.exists(toml_path):
+ return None
+ else:
+ try:
+ with open(toml_path, "r", encoding="utf-8") as f:
+ data = toml.load(f)
+
+ project = data.get('project', {})
+ return project.get('version')
+ except:
+ return None
+
+
+def get_comfyui_tag():
+ try:
+ with git.Repo(comfy_path) as repo:
+ return repo.git.describe('--tags')
+ except:
+ return None
+
+
diff --git a/comfyui_manager/glob/enums.py b/comfyui_manager/common/enums.py
similarity index 100%
rename from comfyui_manager/glob/enums.py
rename to comfyui_manager/common/enums.py
diff --git a/comfyui_manager/glob/git_helper.py b/comfyui_manager/common/git_helper.py
similarity index 100%
rename from comfyui_manager/glob/git_helper.py
rename to comfyui_manager/common/git_helper.py
diff --git a/comfyui_manager/glob/git_utils.py b/comfyui_manager/common/git_utils.py
similarity index 100%
rename from comfyui_manager/glob/git_utils.py
rename to comfyui_manager/common/git_utils.py
diff --git a/comfyui_manager/glob/manager_downloader.py b/comfyui_manager/common/manager_downloader.py
similarity index 100%
rename from comfyui_manager/glob/manager_downloader.py
rename to comfyui_manager/common/manager_downloader.py
diff --git a/comfyui_manager/glob/manager_util.py b/comfyui_manager/common/manager_util.py
similarity index 100%
rename from comfyui_manager/glob/manager_util.py
rename to comfyui_manager/common/manager_util.py
diff --git a/comfyui_manager/glob/node_package.py b/comfyui_manager/common/node_package.py
similarity index 100%
rename from comfyui_manager/glob/node_package.py
rename to comfyui_manager/common/node_package.py
diff --git a/comfyui_manager/glob/security_check.py b/comfyui_manager/common/security_check.py
similarity index 100%
rename from comfyui_manager/glob/security_check.py
rename to comfyui_manager/common/security_check.py
diff --git a/comfyui_manager/glob/__init__.py b/comfyui_manager/glob/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/comfyui_manager/glob/manager_core.py b/comfyui_manager/glob/manager_core.py
index 5792d0a6..fcc96106 100644
--- a/comfyui_manager/glob/manager_core.py
+++ b/comfyui_manager/glob/manager_core.py
@@ -23,7 +23,6 @@ import yaml
import zipfile
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed
-import toml
orig_print = print
@@ -32,13 +31,15 @@ from packaging import version
import uuid
-from . import cm_global
-from . import cnr_utils
-from . import manager_util
-from . import git_utils
-from . import manager_downloader
-from .node_package import InstalledNodePackage
-from .enums import NetworkMode, SecurityLevel, DBMode
+from ..common import cm_global
+from ..common import cnr_utils
+from ..common import manager_util
+from ..common import git_utils
+from ..common import manager_downloader
+from ..common.node_package import InstalledNodePackage
+from ..common.enums import NetworkMode, SecurityLevel, DBMode
+from ..common import context
+
version_code = [4, 0]
version_str = f"V{version_code[0]}.{version_code[1]}" + (f'.{version_code[2]}' if len(version_code) > 2 else '')
@@ -77,32 +78,6 @@ def get_custom_nodes_paths():
return [custom_nodes_path]
-def get_comfyui_tag():
- try:
- repo = git.Repo(comfy_path)
- return repo.git.describe('--tags')
- except:
- return None
-
-
-def get_current_comfyui_ver():
- """
- Extract version from pyproject.toml
- """
- toml_path = os.path.join(comfy_path, 'pyproject.toml')
- if not os.path.exists(toml_path):
- return None
- else:
- try:
- with open(toml_path, "r", encoding="utf-8") as f:
- data = toml.load(f)
-
- project = data.get('project', {})
- return project.get('version')
- except:
- return None
-
-
def get_script_env():
new_env = os.environ.copy()
git_exe = get_config().get('git_exe')
@@ -110,10 +85,10 @@ def get_script_env():
new_env['GIT_EXE_PATH'] = git_exe
if 'COMFYUI_PATH' not in new_env:
- new_env['COMFYUI_PATH'] = comfy_path
+ new_env['COMFYUI_PATH'] = context.comfy_path
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
- new_env['COMFYUI_FOLDERS_BASE_PATH'] = comfy_path
+ new_env['COMFYUI_FOLDERS_BASE_PATH'] = context.comfy_path
return new_env
@@ -137,10 +112,10 @@ def check_invalid_nodes():
import folder_paths
except:
try:
- sys.path.append(comfy_path)
+ sys.path.append(context.comfy_path)
import folder_paths
except:
- raise Exception(f"Invalid COMFYUI_FOLDERS_BASE_PATH: {comfy_path}")
+ raise Exception(f"Invalid COMFYUI_FOLDERS_BASE_PATH: {context.comfy_path}")
def check(root):
global invalid_nodes
@@ -735,6 +710,8 @@ class UnifiedManager:
return latest
async def reload(self, cache_mode, dont_wait=True, update_cnr_map=True):
+ import folder_paths
+
self.custom_node_map_cache = {}
self.cnr_inactive_nodes = {} # node_id -> node_version -> fullpath
self.nightly_inactive_nodes = {} # node_id -> fullpath
@@ -868,7 +845,7 @@ class UnifiedManager:
else:
if os.path.exists(requirements_path) and not no_deps:
print("Install: pip packages")
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
lines = manager_util.robust_readlines(requirements_path)
for line in lines:
package_name = remap_pip_package(line.strip())
@@ -890,7 +867,7 @@ class UnifiedManager:
return res
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps):
- script_path = os.path.join(manager_startup_script_path, "install-scripts.txt")
+ script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
with open(script_path, "a") as file:
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable]
file.write(f"{obj}\n")
@@ -1296,7 +1273,7 @@ class UnifiedManager:
print(f"Download: git clone '{clone_url}'")
if not instant_execution and platform.system() == 'Windows':
- res = manager_funcs.run_script([sys.executable, git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
+ res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone repo: {clone_url}")
else:
@@ -1577,10 +1554,10 @@ def get_channel_dict():
if channel_dict is None:
channel_dict = {}
- if not os.path.exists(manager_channel_list_path):
- shutil.copy(channel_list_template_path, manager_channel_list_path)
+ if not os.path.exists(context.manager_channel_list_path):
+ shutil.copy(context.channel_list_template_path, context.manager_channel_list_path)
- with open(manager_channel_list_path, 'r') as file:
+ with open(context.manager_channel_list_path, 'r') as file:
channels = file.read()
for x in channels.split('\n'):
channel_info = x.split("::")
@@ -1644,18 +1621,18 @@ def write_config():
'db_mode': get_config()['db_mode'],
}
- directory = os.path.dirname(manager_config_path)
+ directory = os.path.dirname(context.manager_config_path)
if not os.path.exists(directory):
os.makedirs(directory)
- with open(manager_config_path, 'w') as configfile:
+ with open(context.manager_config_path, 'w') as configfile:
config.write(configfile)
def read_config():
try:
config = configparser.ConfigParser(strict=False)
- config.read(manager_config_path)
+ config.read(context.manager_config_path)
default_conf = config['default']
manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
@@ -1775,10 +1752,10 @@ def switch_to_default_branch(repo):
def reserve_script(repo_path, install_cmds):
- if not os.path.exists(manager_startup_script_path):
- os.makedirs(manager_startup_script_path)
+ if not os.path.exists(context.manager_startup_script_path):
+ os.makedirs(context.manager_startup_script_path)
- script_path = os.path.join(manager_startup_script_path, "install-scripts.txt")
+ script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
with open(script_path, "a") as file:
obj = [repo_path] + install_cmds
file.write(f"{obj}\n")
@@ -1833,11 +1810,11 @@ def try_install_script(url, repo_path, install_cmd, instant_execution=False):
# use subprocess to avoid file system lock by git (Windows)
def __win_check_git_update(path, do_fetch=False, do_update=False):
if do_fetch:
- command = [sys.executable, git_script_path, "--fetch", path]
+ command = [sys.executable, context.git_script_path, "--fetch", path]
elif do_update:
- command = [sys.executable, git_script_path, "--pull", path]
+ command = [sys.executable, context.git_script_path, "--pull", path]
else:
- command = [sys.executable, git_script_path, "--check", path]
+ command = [sys.executable, context.git_script_path, "--check", path]
new_env = get_script_env()
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=get_default_custom_nodes_path(), env=new_env)
@@ -1891,7 +1868,7 @@ def __win_check_git_update(path, do_fetch=False, do_update=False):
def __win_check_git_pull(path):
- command = [sys.executable, git_script_path, "--pull", path]
+ command = [sys.executable, context.git_script_path, "--pull", path]
process = subprocess.Popen(command, env=get_script_env(), cwd=get_default_custom_nodes_path())
process.wait()
@@ -1907,7 +1884,7 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
else:
if os.path.exists(requirements_path) and not no_deps:
print("Install: pip packages")
- pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
with open(requirements_path, "r") as requirements_file:
for line in requirements_file:
#handle comments
@@ -2143,7 +2120,7 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
clone_url = git_utils.get_url_for_clone(url)
if not instant_execution and platform.system() == 'Windows':
- res = manager_funcs.run_script([sys.executable, git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
+ res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
@@ -2305,7 +2282,7 @@ def gitclone_uninstall(files):
url = url[:-1]
try:
for custom_nodes_dir in get_custom_nodes_paths():
- dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
+ dir_name:str = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
dir_path = os.path.join(custom_nodes_dir, dir_name)
# safety check
@@ -2353,7 +2330,7 @@ def gitclone_set_active(files, is_disable):
url = url[:-1]
try:
for custom_nodes_dir in get_custom_nodes_paths():
- dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
+ dir_name:str = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
dir_path = os.path.join(custom_nodes_dir, dir_name)
# safety check
@@ -2626,7 +2603,7 @@ async def get_current_snapshot(custom_nodes_only = False):
await unified_manager.get_custom_nodes('default', 'cache')
# Get ComfyUI hash
- repo_path = comfy_path
+ repo_path = context.comfy_path
comfyui_commit_hash = None
if not custom_nodes_only:
@@ -2702,7 +2679,7 @@ async def save_snapshot_with_postfix(postfix, path=None, custom_nodes_only = Fal
date_time_format = now.strftime("%Y-%m-%d_%H-%M-%S")
file_name = f"{date_time_format}_{postfix}"
- path = os.path.join(manager_snapshot_path, f"{file_name}.json")
+ path = os.path.join(context.manager_snapshot_path, f"{file_name}.json")
else:
file_name = path.replace('\\', '/').split('/')[-1]
file_name = file_name.split('.')[-2]
@@ -3284,7 +3261,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
def get_comfyui_versions(repo=None):
if repo is None:
- repo = git.Repo(comfy_path)
+ repo = git.Repo(context.comfy_path)
try:
remote = get_remote_name(repo)
@@ -3318,7 +3295,7 @@ def get_comfyui_versions(repo=None):
def switch_comfyui(tag):
- repo = git.Repo(comfy_path)
+ repo = git.Repo(context.comfy_path)
if tag == 'nightly':
repo.git.checkout('master')
diff --git a/comfyui_manager/glob/manager_server.py b/comfyui_manager/glob/manager_server.py
index 99d5f9d7..34e120ba 100644
--- a/comfyui_manager/glob/manager_server.py
+++ b/comfyui_manager/glob/manager_server.py
@@ -19,9 +19,10 @@ import asyncio
from collections import deque
from . import manager_core as core
-from . import manager_util
-from . import cm_global
-from . import manager_downloader
+from ..common import manager_util
+from ..common import cm_global
+from ..common import manager_downloader
+from ..common import context
logging.info(f"### Loading: ComfyUI-Manager ({core.version_str})")
@@ -160,10 +161,10 @@ class ManagerFuncsInComfyUI(core.ManagerFuncs):
core.manager_funcs = ManagerFuncsInComfyUI()
-from .manager_downloader import download_url, download_url_with_agent
+from comfyui_manager.common.manager_downloader import download_url, download_url_with_agent
-core.comfy_path = os.path.dirname(folder_paths.__file__)
-core.js_path = os.path.join(core.comfy_path, "web", "extensions")
+context.comfy_path = os.path.dirname(folder_paths.__file__)
+core.js_path = os.path.join(context.comfy_path, "web", "extensions")
local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
@@ -214,7 +215,7 @@ def print_comfyui_version():
is_detached = repo.head.is_detached
current_branch = repo.active_branch.name
- comfyui_tag = core.get_comfyui_tag()
+ comfyui_tag = context.get_comfyui_tag()
try:
if not os.environ.get('__COMFYUI_DESKTOP_VERSION__') and core.comfy_ui_commit_datetime.date() < core.comfy_ui_required_commit_datetime.date():
@@ -428,7 +429,7 @@ class TaskBatch:
def finalize(self):
if self.batch_id is not None:
- batch_path = os.path.join(core.manager_batch_history_path, self.batch_id+".json")
+ batch_path = os.path.join(context.manager_batch_history_path, self.batch_id+".json")
json_obj = {
"batch": self.batch_json,
"nodepack_result": self.nodepack_result,
@@ -810,7 +811,7 @@ async def queue_batch(request):
@routes.get("/v2/manager/queue/history_list")
async def get_history_list(request):
- history_path = core.manager_batch_history_path
+ history_path = context.manager_batch_history_path
try:
files = [os.path.join(history_path, f) for f in os.listdir(history_path) if os.path.isfile(os.path.join(history_path, f))]
@@ -827,7 +828,7 @@ async def get_history_list(request):
async def get_history(request):
try:
json_name = request.rel_url.query["id"]+'.json'
- batch_path = os.path.join(core.manager_batch_history_path, json_name)
+ batch_path = os.path.join(context.manager_batch_history_path, json_name)
with open(batch_path, 'r', encoding='utf-8') as file:
json_str = file.read()
@@ -1136,7 +1137,7 @@ async def fetch_externalmodel_list(request):
@PromptServer.instance.routes.get("/v2/snapshot/getlist")
async def get_snapshot_list(request):
- items = [f[:-5] for f in os.listdir(core.manager_snapshot_path) if f.endswith('.json')]
+ items = [f[:-5] for f in os.listdir(context.manager_snapshot_path) if f.endswith('.json')]
items.sort(reverse=True)
return web.json_response({'items': items}, content_type='application/json')
@@ -1150,7 +1151,7 @@ async def remove_snapshot(request):
try:
target = request.rel_url.query["target"]
- path = os.path.join(core.manager_snapshot_path, f"{target}.json")
+ path = os.path.join(context.manager_snapshot_path, f"{target}.json")
if os.path.exists(path):
os.remove(path)
@@ -1168,12 +1169,12 @@ async def restore_snapshot(request):
try:
target = request.rel_url.query["target"]
- path = os.path.join(core.manager_snapshot_path, f"{target}.json")
+ path = os.path.join(context.manager_snapshot_path, f"{target}.json")
if os.path.exists(path):
- if not os.path.exists(core.manager_startup_script_path):
- os.makedirs(core.manager_startup_script_path)
+ if not os.path.exists(context.manager_startup_script_path):
+ os.makedirs(context.manager_startup_script_path)
- target_path = os.path.join(core.manager_startup_script_path, "restore-snapshot.json")
+ target_path = os.path.join(context.manager_startup_script_path, "restore-snapshot.json")
shutil.copy(path, target_path)
logging.info(f"Snapshot restore scheduled: `{target}`")
@@ -1729,7 +1730,7 @@ async def get_notice(request):
if version_tag is not None:
markdown_content += f"
ComfyUI: {version_tag} [Desktop]"
else:
- version_tag = core.get_comfyui_tag()
+ version_tag = context.get_comfyui_tag()
if version_tag is None:
markdown_content += f"
ComfyUI: {core.comfy_ui_revision}[{comfy_ui_hash[:6]}]({core.comfy_ui_commit_datetime.date()})"
else:
@@ -1806,15 +1807,15 @@ async def save_component(request):
name = data['name']
workflow = data['workflow']
- if not os.path.exists(core.manager_components_path):
- os.mkdir(core.manager_components_path)
+ if not os.path.exists(context.manager_components_path):
+ os.mkdir(context.manager_components_path)
if 'packname' in workflow and workflow['packname'] != '':
sanitized_name = manager_util.sanitize_filename(workflow['packname']) + '.pack'
else:
sanitized_name = manager_util.sanitize_filename(name) + '.json'
- filepath = os.path.join(core.manager_components_path, sanitized_name)
+ filepath = os.path.join(context.manager_components_path, sanitized_name)
components = {}
if os.path.exists(filepath):
with open(filepath) as f:
@@ -1831,14 +1832,14 @@ async def save_component(request):
@routes.post("/v2/manager/component/loads")
async def load_components(request):
- if os.path.exists(core.manager_components_path):
+ if os.path.exists(context.manager_components_path):
try:
- json_files = [f for f in os.listdir(core.manager_components_path) if f.endswith('.json')]
- pack_files = [f for f in os.listdir(core.manager_components_path) if f.endswith('.pack')]
+ json_files = [f for f in os.listdir(context.manager_components_path) if f.endswith('.json')]
+ pack_files = [f for f in os.listdir(context.manager_components_path) if f.endswith('.pack')]
components = {}
for json_file in json_files + pack_files:
- file_path = os.path.join(core.manager_components_path, json_file)
+ file_path = os.path.join(context.manager_components_path, json_file)
with open(file_path, 'r') as file:
try:
# When there is a conflict between the .pack and the .json, the pack takes precedence and overrides.
@@ -1926,7 +1927,7 @@ async def default_cache_update():
threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
-if not os.path.exists(core.manager_config_path):
+if not os.path.exists(context.manager_config_path):
core.get_config()
core.write_config()
diff --git a/comfyui_manager/glob/share_3rdparty.py b/comfyui_manager/glob/share_3rdparty.py
index e6d31ba4..64f68623 100644
--- a/comfyui_manager/glob/share_3rdparty.py
+++ b/comfyui_manager/glob/share_3rdparty.py
@@ -1,4 +1,5 @@
import mimetypes
+from ..common import context
from . import manager_core as core
import os
@@ -66,10 +67,10 @@ async def share_option(request):
def get_openart_auth():
- if not os.path.exists(os.path.join(core.manager_files_path, ".openart_key")):
+ if not os.path.exists(os.path.join(context.manager_files_path, ".openart_key")):
return None
try:
- with open(os.path.join(core.manager_files_path, ".openart_key"), "r") as f:
+ with open(os.path.join(context.manager_files_path, ".openart_key"), "r") as f:
openart_key = f.read().strip()
return openart_key if openart_key else None
except:
@@ -77,10 +78,10 @@ def get_openart_auth():
def get_matrix_auth():
- if not os.path.exists(os.path.join(core.manager_files_path, "matrix_auth")):
+ if not os.path.exists(os.path.join(context.manager_files_path, "matrix_auth")):
return None
try:
- with open(os.path.join(core.manager_files_path, "matrix_auth"), "r") as f:
+ with open(os.path.join(context.manager_files_path, "matrix_auth"), "r") as f:
matrix_auth = f.read()
homeserver, username, password = matrix_auth.strip().split("\n")
if not homeserver or not username or not password:
@@ -95,10 +96,10 @@ def get_matrix_auth():
def get_comfyworkflows_auth():
- if not os.path.exists(os.path.join(core.manager_files_path, "comfyworkflows_sharekey")):
+ if not os.path.exists(os.path.join(context.manager_files_path, "comfyworkflows_sharekey")):
return None
try:
- with open(os.path.join(core.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
+ with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
share_key = f.read()
if not share_key.strip():
return None
@@ -108,10 +109,10 @@ def get_comfyworkflows_auth():
def get_youml_settings():
- if not os.path.exists(os.path.join(core.manager_files_path, ".youml")):
+ if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
return None
try:
- with open(os.path.join(core.manager_files_path, ".youml"), "r") as f:
+ with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
youml_settings = f.read().strip()
return youml_settings if youml_settings else None
except:
@@ -119,7 +120,7 @@ def get_youml_settings():
def set_youml_settings(settings):
- with open(os.path.join(core.manager_files_path, ".youml"), "w") as f:
+ with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
f.write(settings)
@@ -136,7 +137,7 @@ async def api_get_openart_auth(request):
async def api_set_openart_auth(request):
json_data = await request.json()
openart_key = json_data['openart_key']
- with open(os.path.join(core.manager_files_path, ".openart_key"), "w") as f:
+ with open(os.path.join(context.manager_files_path, ".openart_key"), "w") as f:
f.write(openart_key)
return web.Response(status=200)
@@ -179,14 +180,14 @@ async def api_get_comfyworkflows_auth(request):
@PromptServer.instance.routes.post("/v2/manager/set_esheep_workflow_and_images")
async def set_esheep_workflow_and_images(request):
json_data = await request.json()
- with open(os.path.join(core.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
+ with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
json.dump(json_data, file, indent=4)
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_esheep_workflow_and_images")
async def get_esheep_workflow_and_images(request):
- with open(os.path.join(core.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
+ with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
data = json.load(file)
return web.Response(status=200, text=json.dumps(data))
@@ -195,12 +196,12 @@ def set_matrix_auth(json_data):
homeserver = json_data['homeserver']
username = json_data['username']
password = json_data['password']
- with open(os.path.join(core.manager_files_path, "matrix_auth"), "w") as f:
+ with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
f.write("\n".join([homeserver, username, password]))
def set_comfyworkflows_auth(comfyworkflows_sharekey):
- with open(os.path.join(core.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
+ with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
f.write(comfyworkflows_sharekey)
diff --git a/comfyui_manager/legacy/__init__.py b/comfyui_manager/legacy/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/comfyui_manager/legacy/manager_core.py b/comfyui_manager/legacy/manager_core.py
new file mode 100644
index 00000000..b763391e
--- /dev/null
+++ b/comfyui_manager/legacy/manager_core.py
@@ -0,0 +1,3248 @@
+"""
+description:
+ `manager_core` contains the core implementation of the management functions in ComfyUI-Manager.
+"""
+
+import json
+import logging
+import os
+import sys
+import subprocess
+import re
+import shutil
+import configparser
+import platform
+from datetime import datetime
+
+import git
+from git.remote import RemoteProgress
+from urllib.parse import urlparse
+from tqdm.auto import tqdm
+import time
+import yaml
+import zipfile
+import traceback
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+orig_print = print
+
+from rich import print
+from packaging import version
+
+import uuid
+
+from ..common import cm_global
+from ..common import cnr_utils
+from ..common import manager_util
+from ..common import git_utils
+from ..common import manager_downloader
+from ..common.node_package import InstalledNodePackage
+from ..common.enums import NetworkMode, SecurityLevel, DBMode
+from ..common import context
+
+
+version_code = [4, 0]
+version_str = f"V{version_code[0]}.{version_code[1]}" + (f'.{version_code[2]}' if len(version_code) > 2 else '')
+
+
+DEFAULT_CHANNEL = "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main"
+
+
+default_custom_nodes_path = None
+
+
+class InvalidChannel(Exception):
+ def __init__(self, channel):
+ self.channel = channel
+ super().__init__(channel)
+
+
+def get_default_custom_nodes_path():
+ global default_custom_nodes_path
+ if default_custom_nodes_path is None:
+ try:
+ import folder_paths
+ default_custom_nodes_path = folder_paths.get_folder_paths("custom_nodes")[0]
+ except:
+ default_custom_nodes_path = os.path.abspath(os.path.join(manager_util.comfyui_manager_path, '..'))
+
+ return default_custom_nodes_path
+
+
+def get_custom_nodes_paths():
+ try:
+ import folder_paths
+ return folder_paths.get_folder_paths("custom_nodes")
+ except:
+ custom_nodes_path = os.path.abspath(os.path.join(manager_util.comfyui_manager_path, '..'))
+ return [custom_nodes_path]
+
+
+def get_script_env():
+ new_env = os.environ.copy()
+ git_exe = get_config().get('git_exe')
+ if git_exe is not None:
+ new_env['GIT_EXE_PATH'] = git_exe
+
+ if 'COMFYUI_PATH' not in new_env:
+ new_env['COMFYUI_PATH'] = context.comfy_path
+
+ if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
+ new_env['COMFYUI_FOLDERS_BASE_PATH'] = context.comfy_path
+
+ return new_env
+
+
+invalid_nodes = {}
+
+
+def extract_base_custom_nodes_dir(x:str):
+ if os.path.dirname(x).endswith('.disabled'):
+ return os.path.dirname(os.path.dirname(x))
+ elif x.endswith('.disabled'):
+ return os.path.dirname(x)
+ else:
+ return os.path.dirname(x)
+
+
+def check_invalid_nodes():
+ global invalid_nodes
+
+ try:
+ import folder_paths
+ except:
+ try:
+ sys.path.append(context.comfy_path)
+ import folder_paths
+ except:
+ raise Exception(f"Invalid COMFYUI_FOLDERS_BASE_PATH: {context.comfy_path}")
+
+ def check(root):
+ global invalid_nodes
+
+ subdirs = [d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))]
+ for subdir in subdirs:
+ if subdir in ['.disabled', '__pycache__']:
+ continue
+
+ package = unified_manager.installed_node_packages.get(subdir)
+ if not package:
+ continue
+
+ if not package.isValid():
+ invalid_nodes[subdir] = package.fullpath
+
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
+ for x in node_paths:
+ check(x)
+
+ disabled_dir = os.path.join(x, '.disabled')
+ if os.path.exists(disabled_dir):
+ check(disabled_dir)
+
+ if len(invalid_nodes):
+ print("\n-------------------- ComfyUI-Manager invalid nodes notice ----------------")
+ print("\nNodes requiring reinstallation have been detected:\n(Directly delete the corresponding path and reinstall.)\n")
+
+ for x in invalid_nodes.values():
+ print(x)
+
+ print("\n---------------------------------------------------------------------------\n")
+
+
+cached_config = None
+js_path = None
+
+comfy_ui_required_revision = 1930
+comfy_ui_required_commit_datetime = datetime(2024, 1, 24, 0, 0, 0)
+
+comfy_ui_revision = "Unknown"
+comfy_ui_commit_datetime = datetime(1900, 1, 1, 0, 0, 0)
+
+channel_dict = None
+valid_channels = {'default', 'local'}
+channel_list = None
+
+
+def remap_pip_package(pkg):
+ if pkg in cm_global.pip_overrides:
+ res = cm_global.pip_overrides[pkg]
+ print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
+ return res
+ else:
+ return pkg
+
+
+def is_blacklisted(name):
+ name = name.strip()
+
+ pattern = r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
+ match = re.search(pattern, name)
+
+ if match:
+ name = match.group(1)
+
+ if name in cm_global.pip_blacklist:
+ return True
+
+ if name in cm_global.pip_downgrade_blacklist:
+ pips = manager_util.get_installed_packages()
+
+ if match is None:
+ if name in pips:
+ return True
+ elif match.group(2) in ['<=', '==', '<', '~=']:
+ if name in pips:
+ if manager_util.StrictVersion(pips[name]) >= manager_util.StrictVersion(match.group(3)):
+ return True
+
+ return False
+
+
+def is_installed(name):
+ name = name.strip()
+
+ if name.startswith('#'):
+ return True
+
+ pattern = r'([^<>!~=]+)([<>!~=]=?)([0-9.a-zA-Z]*)'
+ match = re.search(pattern, name)
+
+ if match:
+ name = match.group(1)
+
+ if name in cm_global.pip_blacklist:
+ return True
+
+ if name in cm_global.pip_downgrade_blacklist:
+ pips = manager_util.get_installed_packages()
+
+ if match is None:
+ if name in pips:
+ return True
+ elif match.group(2) in ['<=', '==', '<', '~=']:
+ if name in pips:
+ if manager_util.StrictVersion(pips[name]) >= manager_util.StrictVersion(match.group(3)):
+ print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
+ return True
+
+ pkg = manager_util.get_installed_packages().get(name.lower())
+ if pkg is None:
+ return False # update if not installed
+
+ if match is None:
+ return True # don't update if version is not specified
+
+ if match.group(2) in ['>', '>=']:
+ if manager_util.StrictVersion(pkg) < manager_util.StrictVersion(match.group(3)):
+ return False
+ elif manager_util.StrictVersion(pkg) > manager_util.StrictVersion(match.group(3)):
+ print(f"[SKIP] Downgrading pip package isn't allowed: {name.lower()} (cur={pkg})")
+
+ if match.group(2) == '==':
+ if manager_util.StrictVersion(pkg) < manager_util.StrictVersion(match.group(3)):
+ return False
+
+ if match.group(2) == '~=':
+ if manager_util.StrictVersion(pkg) == manager_util.StrictVersion(match.group(3)):
+ return False
+
+ return name.lower() in manager_util.get_installed_packages()
+
+
+def normalize_channel(channel):
+ if channel == 'local':
+ return channel
+ elif channel is None:
+ return None
+ elif channel.startswith('https://'):
+ return channel
+ elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
+ return channel
+
+ tmp_dict = get_channel_dict()
+ channel_url = tmp_dict.get(channel)
+ if channel_url:
+ return channel_url
+
+ raise InvalidChannel(channel)
+
+
+class ManagedResult:
+ def __init__(self, action):
+ self.action = action
+ self.items = []
+ self.result = True
+ self.to_path = None
+ self.msg = None
+ self.target = None
+ self.postinstall = lambda: True
+ self.ver = None
+
+ def append(self, item):
+ self.items.append(item)
+
+ def fail(self, msg):
+ self.result = False
+ self.msg = msg
+ return self
+
+ def with_target(self, target):
+ self.target = target
+ return self
+
+ def with_msg(self, msg):
+ self.msg = msg
+ return self
+
+ def with_postinstall(self, postinstall):
+ self.postinstall = postinstall
+ return self
+
+ def with_ver(self, ver):
+ self.ver = ver
+ return self
+
+
+class UnifiedManager:
+ def __init__(self):
+ self.installed_node_packages: dict[str, InstalledNodePackage] = {}
+
+ self.cnr_inactive_nodes = {} # node_id -> node_version -> fullpath
+ self.nightly_inactive_nodes = {} # node_id -> fullpath
+ self.unknown_inactive_nodes = {} # node_id -> repo url * fullpath
+ self.active_nodes = {} # node_id -> node_version * fullpath
+ self.unknown_active_nodes = {} # node_id -> repo url * fullpath
+ self.cnr_map = {} # node_id -> cnr info
+ self.repo_cnr_map = {} # repo_url -> cnr info
+ self.custom_node_map_cache = {} # (channel, mode) -> augmented custom node list json
+ self.processed_install = set()
+
+ def get_module_name(self, x):
+ info = self.active_nodes.get(x)
+ if info is None:
+ for url, fullpath in self.unknown_active_nodes.values():
+ if url == x:
+ return os.path.basename(fullpath)
+ else:
+ return os.path.basename(info[1])
+
+ return None
+
+ def get_cnr_by_repo(self, url):
+ return self.repo_cnr_map.get(git_utils.normalize_url(url))
+
+ def resolve_unspecified_version(self, node_name, guess_mode=None):
+ if guess_mode == 'active':
+ # priority:
+ # 1. CNR/nightly active nodes
+ # 2. unknown
+ # 3. Fail
+
+ if node_name in self.cnr_map:
+ version_spec = self.get_from_cnr_active_nodes(node_name)
+
+ if version_spec is None:
+ if node_name in self.unknown_active_nodes:
+ version_spec = "unknown"
+ else:
+ return None
+
+ elif node_name in self.unknown_active_nodes:
+ version_spec = "unknown"
+ else:
+ return None
+
+ elif guess_mode == 'inactive':
+ # priority:
+ # 1. CNR latest in inactive
+ # 2. nightly
+ # 3. unknown
+ # 4. Fail
+
+ if node_name in self.cnr_map:
+ latest = self.get_from_cnr_inactive_nodes(node_name)
+
+ if latest is not None:
+ version_spec = str(latest[0])
+ else:
+ if node_name in self.nightly_inactive_nodes:
+ version_spec = "nightly"
+ else:
+ version_spec = "unknown"
+
+ elif node_name in self.unknown_inactive_nodes:
+ version_spec = "unknown"
+ else:
+ return None
+
+ else:
+ # priority:
+ # 1. CNR latest in world
+ # 2. unknown
+
+ if node_name in self.cnr_map:
+ version_spec = self.cnr_map[node_name]['latest_version']['version']
+ else:
+ version_spec = "unknown"
+
+ return version_spec
+
+ def resolve_node_spec(self, node_name, guess_mode=None):
+ """
+ resolve to 'node_name, version_spec' from version string
+
+ version string:
+ node_name@latest
+ node_name@nightly
+ node_name@unknown
+ node_name@
+ node_name
+
+ if guess_mode is 'active' or 'inactive'
+ return can be 'None' based on state check
+ otherwise
+ return 'unknown' version when failed to guess
+ """
+
+ spec = node_name.split('@')
+
+ if len(spec) == 2:
+ node_name = spec[0]
+ version_spec = spec[1]
+
+ if version_spec == 'latest':
+ if node_name not in self.cnr_map:
+ print(f"ERROR: '{node_name}' is not a CNR node.")
+ return None
+ else:
+ version_spec = self.cnr_map[node_name]['latest_version']['version']
+
+ elif guess_mode in ['active', 'inactive']:
+ node_name = spec[0]
+ version_spec = self.resolve_unspecified_version(node_name, guess_mode=guess_mode)
+ if version_spec is None:
+ return None
+ else:
+ node_name = spec[0]
+ version_spec = self.resolve_unspecified_version(node_name)
+ if version_spec is None:
+ return None
+
+ return node_name, version_spec, len(spec) > 1
+
+ def resolve_from_path(self, fullpath):
+ url = git_utils.git_url(fullpath)
+ if url:
+ url = git_utils.normalize_url(url)
+
+ cnr = self.get_cnr_by_repo(url)
+ commit_hash = git_utils.get_commit_hash(fullpath)
+ if cnr:
+ cnr_utils.generate_cnr_id(fullpath, cnr['id'])
+ return {'id': cnr['id'], 'cnr': cnr, 'ver': 'nightly', 'hash': commit_hash}
+ else:
+ url = os.path.basename(url)
+ if url.endswith('.git'):
+ url = url[:-4]
+ return {'id': url, 'ver': 'unknown', 'hash': commit_hash}
+ else:
+ info = cnr_utils.read_cnr_info(fullpath)
+
+ if info:
+ cnr = self.cnr_map.get(info['id'])
+ if cnr:
+ # normalize version
+ # for example: 2.5 -> 2.5.0
+ ver = str(manager_util.StrictVersion(info['version']))
+ return {'id': cnr['id'], 'cnr': cnr, 'ver': ver}
+ else:
+ return {'id': info['id'], 'ver': info['version']}
+ else:
+ return None
+
+ def update_cache_at_path(self, fullpath):
+ node_package = InstalledNodePackage.from_fullpath(fullpath, self.resolve_from_path)
+ self.installed_node_packages[node_package.id] = node_package
+
+ if node_package.is_disabled and node_package.is_unknown:
+ url = git_utils.git_url(node_package.fullpath)
+ if url is not None:
+ url = git_utils.normalize_url(url)
+ self.unknown_inactive_nodes[node_package.id] = (url, node_package.fullpath)
+
+ if node_package.is_disabled and node_package.is_nightly:
+ self.nightly_inactive_nodes[node_package.id] = node_package.fullpath
+
+ if node_package.is_enabled and not node_package.is_unknown:
+ self.active_nodes[node_package.id] = node_package.version, node_package.fullpath
+
+ if node_package.is_enabled and node_package.is_unknown:
+ url = git_utils.git_url(node_package.fullpath)
+ if url is not None:
+ url = git_utils.normalize_url(url)
+ self.unknown_active_nodes[node_package.id] = (url, node_package.fullpath)
+
+ if node_package.is_from_cnr and node_package.is_disabled:
+ self.add_to_cnr_inactive_nodes(node_package.id, node_package.version, node_package.fullpath)
+
+ def is_updatable(self, node_id):
+ cur_ver = self.get_cnr_active_version(node_id)
+ latest_ver = self.cnr_map[node_id]['latest_version']['version']
+
+ if cur_ver and latest_ver:
+ return self.safe_version(latest_ver) > self.safe_version(cur_ver)
+
+ return False
+
+ def fetch_or_pull_git_repo(self, is_pull=False):
+ updated = set()
+ failed = set()
+
+ def check_update(node_name, fullpath, ver_spec):
+ try:
+ if is_pull:
+ is_updated, success = git_repo_update_check_with(fullpath, do_update=True)
+ else:
+ is_updated, success = git_repo_update_check_with(fullpath, do_fetch=True)
+
+ return f"{node_name}@{ver_spec}", is_updated, success
+ except Exception:
+ traceback.print_exc()
+
+ return f"{node_name}@{ver_spec}", False, False
+
+ with ThreadPoolExecutor() as executor:
+ futures = []
+
+ for k, v in self.unknown_active_nodes.items():
+ futures.append(executor.submit(check_update, k, v[1], 'unknown'))
+
+ for k, v in self.active_nodes.items():
+ if v[0] == 'nightly':
+ futures.append(executor.submit(check_update, k, v[1], 'nightly'))
+
+ for future in as_completed(futures):
+ item, is_updated, success = future.result()
+
+ if is_updated:
+ updated.add(item)
+
+ if not success:
+ failed.add(item)
+
+ return dict(updated=list(updated), failed=list(failed))
+
+ def is_enabled(self, node_id, version_spec=None):
+ """
+ 1. true if node_id@ is enabled
+ 2. true if node_id@ is enabled and version_spec==None
+ 3. false otherwise
+
+ remark: latest version_spec is not allowed. Must be resolved before call.
+ """
+ if version_spec == "cnr":
+ return self.get_cnr_active_version(node_id) not in [None, 'nightly']
+ elif version_spec == 'unknown' and self.is_unknown_active(node_id):
+ return True
+ elif version_spec is not None and self.get_cnr_active_version(node_id) == version_spec:
+ return True
+ elif version_spec is None and (node_id in self.active_nodes or node_id in self.unknown_active_nodes):
+ return True
+ return False
+
+ def is_disabled(self, node_id, version_spec=None):
+ """
+ 1. node_id@unknown is disabled if version_spec is @unknown
+ 2. node_id@nightly is disabled if version_spec is @nightly
+ 4. node_id@ is disabled if version_spec is not None
+ 5. not exists (active node_id) if version_spec is None
+
+ remark: latest version_spec is not allowed. Must be resolved before call.
+ """
+ if version_spec == "unknown":
+ return node_id in self.unknown_inactive_nodes
+ elif version_spec == "nightly":
+ return node_id in self.nightly_inactive_nodes
+ elif version_spec == "cnr":
+ res = self.cnr_inactive_nodes.get(node_id, None)
+ if res is None:
+ return False
+
+ res = [x for x in res.keys() if x != 'nightly']
+ return len(res) > 0
+ elif version_spec is not None:
+ return version_spec in self.cnr_inactive_nodes.get(node_id, [])
+
+ if node_id in self.nightly_inactive_nodes:
+ return True
+ elif node_id in self.unknown_inactive_nodes:
+ return True
+
+ target = self.cnr_inactive_nodes.get(node_id, None)
+ if target is not None and target == version_spec:
+ return True
+
+ return False
+
+ def is_registered_in_cnr(self, node_id):
+ return node_id in self.cnr_map
+
+ def get_cnr_active_version(self, node_id):
+ res = self.active_nodes.get(node_id)
+ if res:
+ return res[0]
+ else:
+ return None
+
+ def is_unknown_active(self, node_id):
+ return node_id in self.unknown_active_nodes
+
+ def add_to_cnr_inactive_nodes(self, node_id, ver, fullpath):
+ ver_map = self.cnr_inactive_nodes.get(node_id)
+ if ver_map is None:
+ ver_map = {}
+ self.cnr_inactive_nodes[node_id] = ver_map
+
+ ver_map[ver] = fullpath
+
+ def get_from_cnr_active_nodes(self, node_id):
+ ver_path = self.active_nodes.get(node_id)
+ if ver_path is None:
+ return None
+
+ return ver_path[0]
+
+ def get_from_cnr_inactive_nodes(self, node_id, ver=None):
+ ver_map = self.cnr_inactive_nodes.get(node_id)
+ if ver_map is None:
+ return None
+
+ if ver is not None:
+ return ver_map.get(ver)
+
+ latest = None
+ for k, v in ver_map.items():
+ if latest is None:
+ latest = self.safe_version(k), v
+ continue
+
+ cur_ver = self.safe_version(k)
+ if cur_ver > latest[0]:
+ latest = cur_ver, v
+
+ return latest
+
+ async def reload(self, cache_mode, dont_wait=True, update_cnr_map=True):
+ import folder_paths
+
+ self.custom_node_map_cache = {}
+ self.cnr_inactive_nodes = {} # node_id -> node_version -> fullpath
+ self.nightly_inactive_nodes = {} # node_id -> fullpath
+ self.unknown_inactive_nodes = {} # node_id -> repo url * fullpath
+ self.unknown_active_nodes = {} # node_id -> repo url * fullpath
+ self.active_nodes = {} # node_id -> node_version * fullpath
+
+ if get_config()['network_mode'] != 'public' or manager_util.is_manager_pip_package():
+ dont_wait = True
+
+ if update_cnr_map:
+ # reload 'cnr_map' and 'repo_cnr_map'
+ cnrs = await cnr_utils.get_cnr_data(cache_mode=cache_mode=='cache', dont_wait=dont_wait)
+
+ for x in cnrs:
+ self.cnr_map[x['id']] = x
+ if 'repository' in x:
+ normalized_url = git_utils.normalize_url(x['repository'])
+ self.repo_cnr_map[normalized_url] = x
+
+ # reload node status info from custom_nodes/*
+ for custom_nodes_path in folder_paths.get_folder_paths('custom_nodes'):
+ for x in os.listdir(custom_nodes_path):
+ fullpath = os.path.join(custom_nodes_path, x)
+ if os.path.isdir(fullpath):
+ if x not in ['__pycache__', '.disabled']:
+ self.update_cache_at_path(fullpath)
+
+ # reload node status info from custom_nodes/.disabled/*
+ for custom_nodes_path in folder_paths.get_folder_paths('custom_nodes'):
+ disabled_dir = os.path.join(custom_nodes_path, '.disabled')
+ if os.path.exists(disabled_dir):
+ for x in os.listdir(disabled_dir):
+ fullpath = os.path.join(disabled_dir, x)
+ if os.path.isdir(fullpath):
+ self.update_cache_at_path(fullpath)
+
+ @staticmethod
+ async def load_nightly(channel, mode):
+ if channel is None:
+ return {}
+
+ res = {}
+
+ channel_url = normalize_channel(channel)
+ if channel_url:
+ if mode not in ['remote', 'local', 'cache']:
+ print(f"[bold red]ERROR: Invalid mode is specified `--mode {mode}`[/bold red]", file=sys.stderr)
+ return {}
+
+ # validate channel - only the channel set by the user is allowed.
+ if channel_url not in valid_channels:
+ logging.error(f'[ComfyUI-Manager] An invalid channel was used: {channel_url}')
+ raise InvalidChannel(channel_url)
+
+ json_obj = await get_data_by_mode(mode, 'custom-node-list.json', channel_url=channel_url)
+ for x in json_obj['custom_nodes']:
+ try:
+ for y in x['files']:
+ if 'github.com' in y and not (y.endswith('.py') or y.endswith('.js')):
+ repo_name = y.split('/')[-1]
+ res[repo_name] = (x, False)
+
+ if 'id' in x:
+ if x['id'] not in res:
+ res[x['id']] = (x, True)
+ except:
+ logging.error(f"[ComfyUI-Manager] broken item:{x}")
+
+ return res
+
+ async def get_custom_nodes(self, channel, mode):
+ if channel is None and mode is None:
+ channel = 'default'
+ mode = 'cache'
+
+ channel = normalize_channel(channel)
+ cache = self.custom_node_map_cache.get((channel, mode)) # CNR/nightly should always be based on the default channel.
+
+ if cache is not None:
+ return cache
+
+ channel = normalize_channel(channel)
+ nodes = await self.load_nightly(channel, mode)
+
+ res = {}
+ added_cnr = set()
+ for v in nodes.values():
+ v = v[0]
+ if len(v['files']) == 1:
+ cnr = self.get_cnr_by_repo(v['files'][0])
+ if cnr:
+ if 'latest_version' not in cnr:
+ v['cnr_latest'] = '0.0.0'
+ else:
+ v['cnr_latest'] = cnr['latest_version']['version']
+ v['id'] = cnr['id']
+ v['author'] = cnr['publisher']['name']
+ v['title'] = cnr['name']
+ v['description'] = cnr['description']
+ v['health'] = '-'
+ if 'repository' in cnr:
+ v['repository'] = cnr['repository']
+ added_cnr.add(cnr['id'])
+ node_id = v['id']
+ else:
+ node_id = v['files'][0].split('/')[-1]
+ v['repository'] = v['files'][0]
+ res[node_id] = v
+ elif len(v['files']) > 1:
+ res[v['files'][0]] = v # A custom node composed of multiple url is treated as a single repository with one representative path
+
+ self.custom_node_map_cache[(channel, mode)] = res
+ return res
+
+ @staticmethod
+ def safe_version(ver_str):
+ try:
+ return version.parse(ver_str)
+ except:
+ return version.parse("0.0.0")
+
+ def execute_install_script(self, url, repo_path, instant_execution=False, lazy_mode=False, no_deps=False):
+ install_script_path = os.path.join(repo_path, "install.py")
+ requirements_path = os.path.join(repo_path, "requirements.txt")
+
+ res = True
+ if lazy_mode:
+ install_cmd = ["#LAZY-INSTALL-SCRIPT", sys.executable]
+ return try_install_script(url, repo_path, install_cmd)
+ else:
+ if os.path.exists(requirements_path) and not no_deps:
+ print("Install: pip packages")
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
+ lines = manager_util.robust_readlines(requirements_path)
+ for line in lines:
+ package_name = remap_pip_package(line.strip())
+ if package_name and not package_name.startswith('#') and package_name not in self.processed_install:
+ self.processed_install.add(package_name)
+ install_cmd = manager_util.make_pip_cmd(["install", package_name])
+ if package_name.strip() != "" and not package_name.startswith('#'):
+ res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
+
+ pip_fixer.fix_broken()
+
+ if os.path.exists(install_script_path) and install_script_path not in self.processed_install:
+ self.processed_install.add(install_script_path)
+ print("Install: install script")
+ install_cmd = [sys.executable, "install.py"]
+ return res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
+
+ return res
+
+ def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps):
+ script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
+ with open(script_path, "a") as file:
+ obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable]
+ file.write(f"{obj}\n")
+
+ print(f"Installation reserved: {target}")
+
+ return True
+
+ def unified_fix(self, node_id, version_spec, instant_execution=False, no_deps=False):
+ """
+ fix dependencies
+ """
+
+ result = ManagedResult('fix')
+
+ if version_spec == 'unknown':
+ info = self.unknown_active_nodes.get(node_id)
+ else:
+ info = self.active_nodes.get(node_id)
+
+ if info is None or not os.path.exists(info[1]):
+ return result.fail(f'not found: {node_id}@{version_spec}')
+
+ self.execute_install_script(node_id, info[1], instant_execution=instant_execution, no_deps=no_deps)
+
+ return result
+
+ def cnr_switch_version(self, node_id, version_spec=None, instant_execution=False, no_deps=False, return_postinstall=False):
+ if instant_execution:
+ return self.cnr_switch_version_instant(node_id, version_spec, instant_execution, no_deps, return_postinstall)
+ else:
+ return self.cnr_switch_version_lazy(node_id, version_spec, no_deps, return_postinstall)
+
+ def cnr_switch_version_lazy(self, node_id, version_spec=None, no_deps=False, return_postinstall=False):
+ """
+ switch between cnr version (lazy mode)
+ """
+
+ result = ManagedResult('switch-cnr')
+
+ node_info = cnr_utils.install_node(node_id, version_spec)
+ if node_info is None or not node_info.download_url:
+ return result.fail(f'not available node: {node_id}@{version_spec}')
+
+ version_spec = node_info.version
+
+ if self.active_nodes[node_id][0] == version_spec:
+ return ManagedResult('skip').with_msg("Up to date")
+
+ zip_url = node_info.download_url
+ from_path = self.active_nodes[node_id][1]
+ target = node_id
+ to_path = os.path.join(get_default_custom_nodes_path(), target)
+
+ def postinstall():
+ return self.reserve_cnr_switch(target, zip_url, from_path, to_path, no_deps)
+
+ if return_postinstall:
+ return result.with_postinstall(postinstall)
+ else:
+ if not postinstall():
+ return result.fail(f"Failed to execute install script: {node_id}@{version_spec}")
+
+ return result
+
+ def cnr_switch_version_instant(self, node_id, version_spec=None, instant_execution=True, no_deps=False, return_postinstall=False):
+ """
+ switch between cnr version
+ """
+
+ # 1. download
+ result = ManagedResult('switch-cnr')
+
+ node_info = cnr_utils.install_node(node_id, version_spec)
+ if node_info is None or not node_info.download_url:
+ return result.fail(f'not available node: {node_id}@{version_spec}')
+
+ version_spec = node_info.version
+
+ if self.active_nodes[node_id][0] == version_spec:
+ return ManagedResult('skip').with_msg("Up to date")
+
+ archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
+ download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
+ manager_downloader.basic_download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
+
+ # 2. extract files into
+ install_path = self.active_nodes[node_id][1]
+ extracted = manager_util.extract_package_as_zip(download_path, install_path)
+ os.remove(download_path)
+
+ if extracted is None:
+ if len(os.listdir(install_path)) == 0:
+ shutil.rmtree(install_path)
+
+ return result.fail(f'Empty archive file: {node_id}@{version_spec}')
+
+ # 3. calculate garbage files (.tracking - extracted)
+ tracking_info_file = os.path.join(install_path, '.tracking')
+ prev_files = set()
+ with open(tracking_info_file, 'r') as f:
+ for line in f:
+ prev_files.add(line.strip())
+ garbage = prev_files.difference(extracted)
+ garbage = [os.path.join(install_path, x) for x in garbage]
+
+ # 4-1. remove garbage files
+ for x in garbage:
+ if os.path.isfile(x):
+ os.remove(x)
+
+ # 4-2. remove garbage dir if empty
+ for x in garbage:
+ if os.path.isdir(x):
+ if not os.listdir(x):
+ os.rmdir(x)
+
+ # 5. create .tracking file
+ tracking_info_file = os.path.join(install_path, '.tracking')
+ with open(tracking_info_file, "w", encoding='utf-8') as file:
+ file.write('\n'.join(list(extracted)))
+
+ # 6. post install
+ result.target = version_spec
+
+ def postinstall():
+ res = self.execute_install_script(f"{node_id}@{version_spec}", install_path, instant_execution=instant_execution, no_deps=no_deps)
+ return res
+
+ if return_postinstall:
+ return result.with_postinstall(postinstall)
+ else:
+ if not postinstall():
+ return result.fail(f"Failed to execute install script: {node_id}@{version_spec}")
+
+ return result
+
+ def unified_enable(self, node_id: str, version_spec=None):
+ """
+ priority if version_spec == None
+ 1. CNR latest in disk
+ 2. nightly
+ 3. unknown
+
+ remark: latest version_spec is not allowed. Must be resolved before call.
+ """
+
+ result = ManagedResult('enable')
+
+ if 'comfyui-manager' in node_id.lower():
+ return result.fail(f"ignored: enabling '{node_id}'")
+
+ if version_spec is None:
+ version_spec = self.resolve_unspecified_version(node_id, guess_mode='inactive')
+ if version is None:
+ return result.fail(f'Specified inactive node not exists: {node_id}')
+
+ if self.is_enabled(node_id, version_spec):
+ return ManagedResult('skip').with_msg('Already enabled')
+
+ if not self.is_disabled(node_id, version_spec):
+ return ManagedResult('skip').with_msg('Not installed')
+
+ from_path = None
+ to_path = None
+
+ if version_spec == 'unknown':
+ repo_and_path = self.unknown_inactive_nodes.get(node_id)
+ if repo_and_path is None:
+ return result.fail(f'Specified inactive node not exists: {node_id}@unknown')
+ from_path = repo_and_path[1]
+
+ base_path = extract_base_custom_nodes_dir(from_path)
+ to_path = os.path.join(base_path, node_id)
+ elif version_spec == 'nightly':
+ self.unified_disable(node_id, False)
+ from_path = self.nightly_inactive_nodes.get(node_id)
+ if from_path is None:
+ return result.fail(f'Specified inactive node not exists: {node_id}@nightly')
+ base_path = extract_base_custom_nodes_dir(from_path)
+ to_path = os.path.join(base_path, node_id)
+ elif version_spec is not None:
+ self.unified_disable(node_id, False)
+ cnr_info = self.cnr_inactive_nodes.get(node_id)
+
+ if cnr_info is None or len(cnr_info) == 0:
+ return result.fail(f'Specified inactive cnr node not exists: {node_id}')
+
+ if version_spec == "cnr":
+ version_spec = next(iter(cnr_info))
+
+ if version_spec not in cnr_info:
+ return result.fail(f'Specified inactive node not exists: {node_id}@{version_spec}')
+
+ from_path = cnr_info[version_spec]
+ base_path = extract_base_custom_nodes_dir(from_path)
+ to_path = os.path.join(base_path, node_id)
+
+ if from_path is None or not os.path.exists(from_path):
+ return result.fail(f'Specified inactive node path not exists: {from_path}')
+
+ # move from disk
+ shutil.move(from_path, to_path)
+
+ # update cache
+ if version_spec == 'unknown':
+ self.unknown_active_nodes[node_id] = self.unknown_inactive_nodes[node_id][0], to_path
+ del self.unknown_inactive_nodes[node_id]
+ return result.with_target(to_path)
+ elif version_spec == 'nightly':
+ del self.nightly_inactive_nodes[node_id]
+ else:
+ del self.cnr_inactive_nodes[node_id][version_spec]
+
+ self.active_nodes[node_id] = version_spec, to_path
+ return result.with_target(to_path)
+
+ def unified_disable(self, node_id: str, is_unknown):
+ result = ManagedResult('disable')
+
+ if 'comfyui-manager' in node_id.lower():
+ return result.fail(f"ignored: disabling '{node_id}'")
+
+ if is_unknown:
+ version_spec = 'unknown'
+ else:
+ version_spec = None
+
+ if not self.is_enabled(node_id, version_spec):
+ if not self.is_disabled(node_id, version_spec):
+ return ManagedResult('skip').with_msg('Not installed')
+ else:
+ return ManagedResult('skip').with_msg('Already disabled')
+
+ if is_unknown:
+ repo_and_path = self.unknown_active_nodes.get(node_id)
+
+ if repo_and_path is None or not os.path.exists(repo_and_path[1]):
+ return result.fail(f'Specified active node not exists: {node_id}')
+
+ base_path = extract_base_custom_nodes_dir(repo_and_path[1])
+ to_path = os.path.join(base_path, '.disabled', node_id)
+
+ shutil.move(repo_and_path[1], to_path)
+ result.append((repo_and_path[1], to_path))
+
+ self.unknown_inactive_nodes[node_id] = repo_and_path[0], to_path
+ del self.unknown_active_nodes[node_id]
+
+ return result
+
+ ver_and_path = self.active_nodes.get(node_id)
+
+ if ver_and_path is None or not os.path.exists(ver_and_path[1]):
+ return result.fail(f'Specified active node not exists: {node_id}')
+
+ base_path = extract_base_custom_nodes_dir(ver_and_path[1])
+
+ # NOTE: A disabled node may have multiple versions, so preserve it using the `@ suffix`.
+ to_path = os.path.join(base_path, '.disabled', f"{node_id}@{ver_and_path[0].replace('.', '_')}")
+ shutil.move(ver_and_path[1], to_path)
+ result.append((ver_and_path[1], to_path))
+
+ if ver_and_path[0] == 'nightly':
+ self.nightly_inactive_nodes[node_id] = to_path
+ else:
+ self.add_to_cnr_inactive_nodes(node_id, ver_and_path[0], to_path)
+
+ del self.active_nodes[node_id]
+
+ return result
+
+ def unified_uninstall(self, node_id: str, is_unknown: bool):
+ """
+ Remove whole installed custom nodes including inactive nodes
+ """
+ result = ManagedResult('uninstall')
+
+ if 'comfyui-manager' in node_id.lower():
+ return result.fail(f"ignored: uninstalling '{node_id}'")
+
+ if is_unknown:
+ # remove from actives
+ repo_and_path = self.unknown_active_nodes.get(node_id)
+
+ is_removed = False
+
+ if repo_and_path is not None and os.path.exists(repo_and_path[1]):
+ rmtree(repo_and_path[1])
+ result.append(repo_and_path[1])
+ del self.unknown_active_nodes[node_id]
+
+ is_removed = True
+
+ # remove from inactives
+ repo_and_path = self.unknown_inactive_nodes.get(node_id)
+
+ if repo_and_path is not None and os.path.exists(repo_and_path[1]):
+ rmtree(repo_and_path[1])
+ result.append(repo_and_path[1])
+ del self.unknown_inactive_nodes[node_id]
+
+ is_removed = True
+
+ if is_removed:
+ return result
+ else:
+ return ManagedResult('skip')
+
+ # remove from actives
+ ver_and_path = self.active_nodes.get(node_id)
+
+ if ver_and_path is not None and os.path.exists(ver_and_path[1]):
+ try_rmtree(node_id, ver_and_path[1])
+ result.items.append(ver_and_path)
+ del self.active_nodes[node_id]
+
+ # remove from nightly inactives
+ fullpath = self.nightly_inactive_nodes.get(node_id)
+ if fullpath is not None and os.path.exists(fullpath):
+ try_rmtree(node_id, fullpath)
+ result.items.append(('nightly', fullpath))
+ del self.nightly_inactive_nodes[node_id]
+
+ # remove from cnr inactives
+ ver_map = self.cnr_inactive_nodes.get(node_id)
+ if ver_map is not None:
+ for key, fullpath in ver_map.items():
+ try_rmtree(node_id, fullpath)
+ result.items.append((key, fullpath))
+ del self.cnr_inactive_nodes[node_id]
+
+ if len(result.items) == 0:
+ return ManagedResult('skip').with_msg('Not installed')
+
+ return result
+
+ def cnr_install(self, node_id: str, version_spec=None, instant_execution=False, no_deps=False, return_postinstall=False):
+ result = ManagedResult('install-cnr')
+
+ if 'comfyui-manager' in node_id.lower():
+ return result.fail(f"ignored: installing '{node_id}'")
+
+ node_info = cnr_utils.install_node(node_id, version_spec)
+ if node_info is None or not node_info.download_url:
+ return result.fail(f'not available node: {node_id}@{version_spec}')
+
+ archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
+ download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
+
+ # re-download. I cannot trust existing file.
+ if os.path.exists(download_path):
+ os.remove(download_path)
+
+ # install_path
+ install_path = os.path.join(get_default_custom_nodes_path(), node_id)
+ if os.path.exists(install_path):
+ return result.fail(f'Install path already exists: {install_path}')
+
+ manager_downloader.download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
+ os.makedirs(install_path, exist_ok=True)
+ extracted = manager_util.extract_package_as_zip(download_path, install_path)
+ os.remove(download_path)
+ result.to_path = install_path
+
+ if extracted is None:
+ shutil.rmtree(install_path)
+ return result.fail(f'Empty archive file: {node_id}@{version_spec}')
+
+ # create .tracking file
+ tracking_info_file = os.path.join(install_path, '.tracking')
+ with open(tracking_info_file, "w", encoding='utf-8') as file:
+ file.write('\n'.join(extracted))
+
+ result.target = version_spec
+
+ def postinstall():
+ return self.execute_install_script(node_id, install_path, instant_execution=instant_execution, no_deps=no_deps)
+
+ if return_postinstall:
+ return result.with_postinstall(postinstall)
+ else:
+ if not postinstall():
+ return result.fail(f"Failed to execute install script: {node_id}@{version_spec}")
+
+ return result
+
+ def repo_install(self, url: str, repo_path: str, instant_execution=False, no_deps=False, return_postinstall=False):
+ result = ManagedResult('install-git')
+ result.append(url)
+
+ if 'comfyui-manager' in url.lower():
+ return result.fail(f"ignored: installing '{url}'")
+
+ if not is_valid_url(url):
+ return result.fail(f"Invalid git url: {url}")
+
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ # Clone the repository from the remote URL
+ clone_url = git_utils.get_url_for_clone(url)
+ print(f"Download: git clone '{clone_url}'")
+
+ if not instant_execution and platform.system() == 'Windows':
+ res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
+ if res != 0:
+ return result.fail(f"Failed to clone repo: {clone_url}")
+ else:
+ repo = git.Repo.clone_from(clone_url, repo_path, recursive=True, progress=GitProgress())
+ repo.git.clear_cache()
+ repo.close()
+
+ def postinstall():
+ return self.execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
+
+ if return_postinstall:
+ return result.with_postinstall(postinstall)
+ else:
+ if not postinstall():
+ return result.fail(f"Failed to execute install script: {url}")
+
+ except Exception as e:
+ traceback.print_exc()
+ return result.fail(f"Install(git-clone) error[2]: {url} / {e}")
+
+ print("Installation was successful.")
+ return result
+
+ def repo_update(self, repo_path, instant_execution=False, no_deps=False, return_postinstall=False):
+ result = ManagedResult('update-git')
+
+ if not os.path.exists(os.path.join(repo_path, '.git')):
+ return result.fail(f'Path not found: {repo_path}')
+
+ # version check
+ with git.Repo(repo_path) as repo:
+ if repo.head.is_detached:
+ if not switch_to_default_branch(repo):
+ return result.fail(f"Failed to switch to default branch: {repo_path}")
+
+ current_branch = repo.active_branch
+ branch_name = current_branch.name
+
+ if current_branch.tracking_branch() is None:
+ print(f"[ComfyUI-Manager] There is no tracking branch ({current_branch})")
+ remote_name = get_remote_name(repo)
+ else:
+ remote_name = current_branch.tracking_branch().remote_name
+
+ if remote_name is None:
+ return result.fail(f"Failed to get remote when installing: {repo_path}")
+
+ remote = repo.remote(name=remote_name)
+
+ try:
+ remote.fetch()
+ except Exception as e:
+ if 'detected dubious' in str(e):
+ print(f"[ComfyUI-Manager] Try fixing 'dubious repository' error on '{repo_path}' repository")
+ safedir_path = repo_path.replace('\\', '/')
+ subprocess.run(['git', 'config', '--global', '--add', 'safe.directory', safedir_path])
+ try:
+ remote.fetch()
+ except Exception:
+ print("\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n"
+ "-----------------------------------------------------------------------------------------\n"
+ f'git config --global --add safe.directory "{safedir_path}"\n'
+ "-----------------------------------------------------------------------------------------\n")
+
+ commit_hash = repo.head.commit.hexsha
+ if f'{remote_name}/{branch_name}' in repo.refs:
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
+ else:
+ return result.fail(f"Not updatable branch: {branch_name}")
+
+ if commit_hash != remote_commit_hash:
+ git_pull(repo_path)
+
+ if len(repo.remotes) > 0:
+ url = repo.remotes[0].url
+ else:
+ url = "unknown repo"
+
+ def postinstall():
+ return self.execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
+
+ if return_postinstall:
+ return result.with_postinstall(postinstall)
+ else:
+ if not postinstall():
+ return result.fail(f"Failed to execute install script: {url}")
+
+ return result
+ else:
+ return ManagedResult('skip').with_msg('Up to date')
+
+ def unified_update(self, node_id, version_spec=None, instant_execution=False, no_deps=False, return_postinstall=False):
+ orig_print(f"\x1b[2K\rUpdating: {node_id}", end='')
+
+ if version_spec is None:
+ version_spec = self.resolve_unspecified_version(node_id, guess_mode='active')
+
+ if version_spec is None:
+ return ManagedResult('update').fail(f'Update not available: {node_id}@{version_spec}').with_ver(version_spec)
+
+ if version_spec == 'nightly':
+ return self.repo_update(self.active_nodes[node_id][1], instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall).with_target('nightly').with_ver('nightly')
+ elif version_spec == 'unknown':
+ return self.repo_update(self.unknown_active_nodes[node_id][1], instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall).with_target('unknown').with_ver('unknown')
+ else:
+ return self.cnr_switch_version(node_id, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall).with_ver('cnr')
+
+ async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False):
+ """
+ priority if version_spec == None
+ 1. CNR latest
+ 2. unknown
+
+ remark: latest version_spec is not allowed. Must be resolved before call.
+ """
+
+ if 'comfyui-manager' in node_id.lower():
+ return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
+
+ repo_url = None
+ if version_spec is None:
+ if self.is_enabled(node_id):
+ return ManagedResult('skip')
+ elif self.is_disabled(node_id):
+ return self.unified_enable(node_id)
+ else:
+ version_spec = self.resolve_unspecified_version(node_id)
+
+ if version_spec == 'unknown' or version_spec == 'nightly':
+ try:
+ custom_nodes = await self.get_custom_nodes(channel, mode)
+ except InvalidChannel as e:
+ return ManagedResult('fail').fail(f'Invalid channel is used: {e.channel}')
+
+ the_node = custom_nodes.get(node_id)
+ if the_node is not None:
+ if version_spec == 'unknown':
+ repo_url = the_node['files'][0]
+ else: # nightly
+ repo_url = the_node['repository']
+ else:
+ result = ManagedResult('install')
+ return result.fail(f"Node '{node_id}@{version_spec}' not found in [{channel}, {mode}]")
+
+ if self.is_enabled(node_id, version_spec):
+ return ManagedResult('skip').with_target(f"{node_id}@{version_spec}")
+
+ elif self.is_disabled(node_id, version_spec):
+ return self.unified_enable(node_id, version_spec)
+
+ elif version_spec == 'unknown' or version_spec == 'nightly':
+ to_path = os.path.abspath(os.path.join(get_default_custom_nodes_path(), node_id))
+
+ if version_spec == 'nightly':
+ # disable cnr nodes
+ if self.is_enabled(node_id, 'cnr'):
+ self.unified_disable(node_id, False)
+
+ # use `repo name` as a dir name instead of `cnr id` if system added nodepack (i.e. publisher is null)
+ cnr = self.cnr_map.get(node_id)
+
+ if cnr is not None and cnr.get('publisher') is None:
+ repo_name = os.path.basename(git_utils.normalize_url(repo_url))
+ to_path = os.path.abspath(os.path.join(get_default_custom_nodes_path(), repo_name))
+
+ res = self.repo_install(repo_url, to_path, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
+ if res.result:
+ if version_spec == 'unknown':
+ self.unknown_active_nodes[node_id] = repo_url, to_path
+ elif version_spec == 'nightly':
+ cnr_utils.generate_cnr_id(to_path, node_id)
+ self.active_nodes[node_id] = 'nightly', to_path
+ else:
+ return res
+
+ return res.with_target(version_spec)
+
+ if self.is_enabled(node_id, 'nightly'):
+ # disable nightly nodes
+ self.unified_disable(node_id, False) # NOTE: don't return from here
+
+ if self.is_disabled(node_id, version_spec):
+ # enable and return if specified version is disabled
+ return self.unified_enable(node_id, version_spec)
+
+ if self.is_disabled(node_id, "cnr"):
+ # enable and switch version if cnr is disabled (not specified version)
+ self.unified_enable(node_id, "cnr")
+ return self.cnr_switch_version(node_id, version_spec, no_deps=no_deps, return_postinstall=return_postinstall)
+
+ if self.is_enabled(node_id, "cnr"):
+ return self.cnr_switch_version(node_id, version_spec, no_deps=no_deps, return_postinstall=return_postinstall)
+
+ res = self.cnr_install(node_id, version_spec, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
+ if res.result:
+ self.active_nodes[node_id] = version_spec, res.to_path
+
+ return res
+
+
+unified_manager = UnifiedManager()
+
+
+def identify_node_pack_from_path(fullpath):
+ module_name = os.path.basename(fullpath)
+ if module_name.endswith('.git'):
+ module_name = module_name[:-4]
+
+ repo_url = git_utils.git_url(fullpath)
+ if repo_url is None:
+ # cnr
+ cnr = cnr_utils.read_cnr_info(fullpath)
+ if cnr is not None:
+ return module_name, cnr['version'], cnr['id'], None
+
+ return None
+ else:
+ # nightly or unknown
+ cnr_id = cnr_utils.read_cnr_id(fullpath)
+ commit_hash = git_utils.get_commit_hash(fullpath)
+
+ github_id = git_utils.normalize_to_github_id(repo_url)
+ if github_id is None:
+ try:
+ github_id = os.path.basename(repo_url)
+ except:
+ logging.warning(f"[ComfyUI-Manager] unexpected repo url: {repo_url}")
+ github_id = module_name
+
+ if cnr_id is not None:
+ return module_name, commit_hash, cnr_id, github_id
+ else:
+ return module_name, commit_hash, '', github_id
+
+
+def get_installed_node_packs():
+ res = {}
+
+ for x in get_custom_nodes_paths():
+ for y in os.listdir(x):
+ if y == '__pycache__' or y == '.disabled':
+ continue
+
+ fullpath = os.path.join(x, y)
+ info = identify_node_pack_from_path(fullpath)
+ if info is None:
+ continue
+
+ is_disabled = not y.endswith('.disabled')
+
+ res[info[0]] = { 'ver': info[1], 'cnr_id': info[2], 'aux_id': info[3], 'enabled': is_disabled }
+
+ disabled_dirs = os.path.join(x, '.disabled')
+ if os.path.exists(disabled_dirs):
+ for y in os.listdir(disabled_dirs):
+ if y == '__pycache__':
+ continue
+
+ fullpath = os.path.join(disabled_dirs, y)
+ info = identify_node_pack_from_path(fullpath)
+ if info is None:
+ continue
+
+ res[info[0]] = { 'ver': info[1], 'cnr_id': info[2], 'aux_id': info[3], 'enabled': False }
+
+ return res
+
+
+def refresh_channel_dict():
+ if channel_dict is None:
+ get_channel_dict()
+
+
+def get_channel_dict():
+ global channel_dict
+ global valid_channels
+
+ if channel_dict is None:
+ channel_dict = {}
+
+ if not os.path.exists(context.manager_channel_list_path):
+ shutil.copy(context.channel_list_template_path, context.manager_channel_list_path)
+
+ with open(context.manager_channel_list_path, 'r') as file:
+ channels = file.read()
+ for x in channels.split('\n'):
+ channel_info = x.split("::")
+ if len(channel_info) == 2:
+ channel_dict[channel_info[0]] = channel_info[1]
+ valid_channels.add(channel_info[1])
+
+ return channel_dict
+
+
+def get_channel_list():
+ global channel_list
+
+ if channel_list is None:
+ channel_list = []
+ for k, v in get_channel_dict().items():
+ channel_list.append(f"{k}::{v}")
+
+ return channel_list
+
+
+class ManagerFuncs:
+ def __init__(self):
+ pass
+
+ def get_current_preview_method(self):
+ return "none"
+
+ def run_script(self, cmd, cwd='.'):
+ if len(cmd) > 0 and cmd[0].startswith("#"):
+ print(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
+ return 0
+
+ subprocess.check_call(cmd, cwd=cwd, env=get_script_env())
+
+ return 0
+
+
+manager_funcs = ManagerFuncs()
+
+
+def write_config():
+ config = configparser.ConfigParser(strict=False)
+
+ config['default'] = {
+ 'preview_method': manager_funcs.get_current_preview_method(),
+ 'git_exe': get_config()['git_exe'],
+ 'use_uv': get_config()['use_uv'],
+ 'channel_url': get_config()['channel_url'],
+ 'share_option': get_config()['share_option'],
+ 'bypass_ssl': get_config()['bypass_ssl'],
+ "file_logging": get_config()['file_logging'],
+ 'component_policy': get_config()['component_policy'],
+ 'update_policy': get_config()['update_policy'],
+ 'windows_selector_event_loop_policy': get_config()['windows_selector_event_loop_policy'],
+ 'model_download_by_agent': get_config()['model_download_by_agent'],
+ 'downgrade_blacklist': get_config()['downgrade_blacklist'],
+ 'security_level': get_config()['security_level'],
+ 'always_lazy_install': get_config()['always_lazy_install'],
+ 'network_mode': get_config()['network_mode'],
+ 'db_mode': get_config()['db_mode'],
+ }
+
+ directory = os.path.dirname(context.manager_config_path)
+ if not os.path.exists(directory):
+ os.makedirs(directory)
+
+ with open(context.manager_config_path, 'w') as configfile:
+ config.write(configfile)
+
+
+def read_config():
+ try:
+ config = configparser.ConfigParser(strict=False)
+ config.read(context.manager_config_path)
+ default_conf = config['default']
+ manager_util.use_uv = default_conf['use_uv'].lower() == 'true' if 'use_uv' in default_conf else False
+
+ def get_bool(key, default_value):
+ return default_conf[key].lower() == 'true' if key in default_conf else False
+
+ return {
+ 'http_channel_enabled': get_bool('http_channel_enabled', False),
+ 'preview_method': default_conf.get('preview_method', manager_funcs.get_current_preview_method()).lower(),
+ 'git_exe': default_conf.get('git_exe', ''),
+ 'use_uv': get_bool('use_uv', False),
+ 'channel_url': default_conf.get('channel_url', DEFAULT_CHANNEL),
+ 'default_cache_as_channel_url': get_bool('default_cache_as_channel_url', False),
+ 'share_option': default_conf.get('share_option', 'all').lower(),
+ 'bypass_ssl': get_bool('bypass_ssl', False),
+ 'file_logging': get_bool('file_logging', True),
+ 'component_policy': default_conf.get('component_policy', 'workflow').lower(),
+ 'update_policy': default_conf.get('update_policy', 'stable-comfyui').lower(),
+ 'windows_selector_event_loop_policy': get_bool('windows_selector_event_loop_policy', False),
+ 'model_download_by_agent': get_bool('model_download_by_agent', False),
+ 'downgrade_blacklist': default_conf.get('downgrade_blacklist', '').lower(),
+ 'always_lazy_install': get_bool('always_lazy_install', False),
+ 'network_mode': default_conf.get('network_mode', NetworkMode.PUBLIC.value).lower(),
+ 'security_level': default_conf.get('security_level', SecurityLevel.NORMAL.value).lower(),
+ 'db_mode': default_conf.get('db_mode', DBMode.CACHE.value).lower(),
+ }
+
+ except Exception:
+ manager_util.use_uv = False
+ return {
+ 'http_channel_enabled': False,
+ 'preview_method': manager_funcs.get_current_preview_method(),
+ 'git_exe': '',
+ 'use_uv': False,
+ 'channel_url': DEFAULT_CHANNEL,
+ 'default_cache_as_channel_url': False,
+ 'share_option': 'all',
+ 'bypass_ssl': False,
+ 'file_logging': True,
+ 'component_policy': 'workflow',
+ 'update_policy': 'stable-comfyui',
+ 'windows_selector_event_loop_policy': False,
+ 'model_download_by_agent': False,
+ 'downgrade_blacklist': '',
+ 'always_lazy_install': False,
+ 'network_mode': NetworkMode.OFFLINE.value,
+ 'security_level': SecurityLevel.NORMAL.value,
+ 'db_mode': DBMode.CACHE.value,
+ }
+
+
+def get_config():
+ global cached_config
+
+ if cached_config is None:
+ cached_config = read_config()
+ if cached_config['http_channel_enabled']:
+ print("[ComfyUI-Manager] Warning: http channel enabled, make sure server in secure env")
+
+ return cached_config
+
+
+def get_remote_name(repo):
+ available_remotes = [remote.name for remote in repo.remotes]
+ if 'origin' in available_remotes:
+ return 'origin'
+ elif 'upstream' in available_remotes:
+ return 'upstream'
+ elif len(available_remotes) > 0:
+ return available_remotes[0]
+
+ if not available_remotes:
+ print(f"[ComfyUI-Manager] No remotes are configured for this repository: {repo.working_dir}")
+ else:
+ print(f"[ComfyUI-Manager] Available remotes in '{repo.working_dir}': ")
+ for remote in available_remotes:
+ print(f"- {remote}")
+
+ return None
+
+
+def switch_to_default_branch(repo):
+ remote_name = get_remote_name(repo)
+
+ try:
+ if remote_name is None:
+ return False
+
+ default_branch = repo.git.symbolic_ref(f'refs/remotes/{remote_name}/HEAD').replace(f'refs/remotes/{remote_name}/', '')
+ repo.git.checkout(default_branch)
+ return True
+ except:
+ # try checkout master
+ # try checkout main if failed
+ try:
+ repo.git.checkout(repo.heads.master)
+ return True
+ except:
+ try:
+ if remote_name is not None:
+ repo.git.checkout('-b', 'master', f'{remote_name}/master')
+ return True
+ except:
+ try:
+ repo.git.checkout(repo.heads.main)
+ return True
+ except:
+ try:
+ if remote_name is not None:
+ repo.git.checkout('-b', 'main', f'{remote_name}/main')
+ return True
+ except:
+ pass
+
+ print("[ComfyUI Manager] Failed to switch to the default branch")
+ return False
+
+
+def reserve_script(repo_path, install_cmds):
+ if not os.path.exists(context.manager_startup_script_path):
+ os.makedirs(context.manager_startup_script_path)
+
+ script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
+ with open(script_path, "a") as file:
+ obj = [repo_path] + install_cmds
+ file.write(f"{obj}\n")
+
+
+def try_rmtree(title, fullpath):
+ try:
+ shutil.rmtree(fullpath)
+ except Exception as e:
+ logging.warning(f"[ComfyUI-Manager] An error occurred while deleting '{fullpath}', so it has been scheduled for deletion upon restart.\nEXCEPTION: {e}")
+ reserve_script(title, ["#LAZY-DELETE-NODEPACK", fullpath])
+
+
+def try_install_script(url, repo_path, install_cmd, instant_execution=False):
+ if not instant_execution and (
+ (len(install_cmd) > 0 and install_cmd[0].startswith('#')) or platform.system() == "Windows" or get_config()['always_lazy_install']
+ ):
+ reserve_script(repo_path, install_cmd)
+ return True
+ else:
+ if len(install_cmd) == 5 and install_cmd[2:4] == ['pip', 'install']:
+ if is_blacklisted(install_cmd[4]):
+ print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[4]}'")
+ return True
+ elif len(install_cmd) == 6 and install_cmd[3:5] == ['pip', 'install']: # uv mode
+ if is_blacklisted(install_cmd[5]):
+ print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[5]}'")
+ return True
+
+ print(f"\n## ComfyUI-Manager: EXECUTE => {install_cmd}")
+ code = manager_funcs.run_script(install_cmd, cwd=repo_path)
+
+ if platform.system() != "Windows":
+ try:
+ if not os.environ.get('__COMFYUI_DESKTOP_VERSION__') and comfy_ui_commit_datetime.date() < comfy_ui_required_commit_datetime.date():
+ print("\n\n###################################################################")
+ print(f"[WARN] ComfyUI-Manager: Your ComfyUI version ({comfy_ui_revision})[{comfy_ui_commit_datetime.date()}] is too old. Please update to the latest version.")
+ print("[WARN] The extension installation feature may not work properly in the current installed ComfyUI version on Windows environment.")
+ print("###################################################################\n\n")
+ except:
+ pass
+
+ if code != 0:
+ if url is None:
+ url = os.path.dirname(repo_path)
+ print(f"install script failed: {url}")
+ return False
+
+ return True
+
+
+# use subprocess to avoid file system lock by git (Windows)
+def __win_check_git_update(path, do_fetch=False, do_update=False):
+ if do_fetch:
+ command = [sys.executable, context.git_script_path, "--fetch", path]
+ elif do_update:
+ command = [sys.executable, context.git_script_path, "--pull", path]
+ else:
+ command = [sys.executable, context.git_script_path, "--check", path]
+
+ new_env = get_script_env()
+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=get_default_custom_nodes_path(), env=new_env)
+ output, _ = process.communicate()
+ output = output.decode('utf-8').strip()
+
+ if 'detected dubious' in output:
+ # fix and try again
+ safedir_path = path.replace('\\', '/')
+ try:
+ print(f"[ComfyUI-Manager] Try fixing 'dubious repository' error on '{safedir_path}' repo")
+ process = subprocess.Popen(['git', 'config', '--global', '--add', 'safe.directory', safedir_path], env=new_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ output, _ = process.communicate()
+
+ process = subprocess.Popen(command, env=new_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ output, _ = process.communicate()
+ output = output.decode('utf-8').strip()
+ except Exception:
+ print('[ComfyUI-Manager] failed to fixing')
+
+ if 'detected dubious' in output:
+ print(f'\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n'
+ f'-----------------------------------------------------------------------------------------\n'
+ f'git config --global --add safe.directory "{safedir_path}"\n'
+ f'-----------------------------------------------------------------------------------------\n')
+
+ if do_update:
+ if "CUSTOM NODE PULL: Success" in output:
+ process.wait()
+ print(f"\x1b[2K\rUpdated: {path}")
+ return True, True # updated
+ elif "CUSTOM NODE PULL: None" in output:
+ process.wait()
+ return False, True # there is no update
+ else:
+ print(f"\x1b[2K\rUpdate error: {path}")
+ process.wait()
+ return False, False # update failed
+ else:
+ if "CUSTOM NODE CHECK: True" in output:
+ process.wait()
+ return True, True
+ elif "CUSTOM NODE CHECK: False" in output:
+ process.wait()
+ return False, True
+ else:
+ print(f"\x1b[2K\rFetch error: {path}")
+ print(f"\n{output}\n")
+ process.wait()
+ return False, True
+
+
+def __win_check_git_pull(path):
+ command = [sys.executable, context.git_script_path, "--pull", path]
+ process = subprocess.Popen(command, env=get_script_env(), cwd=get_default_custom_nodes_path())
+ process.wait()
+
+
+def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=False, no_deps=False):
+ # import ipdb; ipdb.set_trace()
+ install_script_path = os.path.join(repo_path, "install.py")
+ requirements_path = os.path.join(repo_path, "requirements.txt")
+
+ if lazy_mode:
+ install_cmd = ["#LAZY-INSTALL-SCRIPT", sys.executable]
+ try_install_script(url, repo_path, install_cmd)
+ else:
+ if os.path.exists(requirements_path) and not no_deps:
+ print("Install: pip packages")
+ pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), context.comfy_path, context.manager_files_path)
+ with open(requirements_path, "r") as requirements_file:
+ for line in requirements_file:
+ #handle comments
+ if '#' in line:
+ if line.strip()[0] == '#':
+ print("Line is comment...skipping")
+ continue
+ else:
+ line = line.split('#')[0].strip()
+
+ package_name = remap_pip_package(line.strip())
+
+ if package_name and not package_name.startswith('#'):
+ if '--index-url' in package_name:
+ s = package_name.split('--index-url')
+ install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
+ else:
+ install_cmd = manager_util.make_pip_cmd(["install", package_name])
+
+ if package_name.strip() != "" and not package_name.startswith('#'):
+ try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
+ pip_fixer.fix_broken()
+
+ if os.path.exists(install_script_path):
+ print("Install: install script")
+ install_cmd = [sys.executable, "install.py"]
+ try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
+
+ return True
+
+
+def git_repo_update_check_with(path, do_fetch=False, do_update=False, no_deps=False):
+ """
+
+ perform update check for git custom node
+ and fetch or update if flag is on
+
+ :param path: path to git custom node
+ :param do_fetch: do fetch during check
+ :param do_update: do update during check
+ :param no_deps: don't install dependencies
+ :return: update state * success
+ """
+ if do_fetch:
+ orig_print(f"\x1b[2K\rFetching: {path}", end='')
+ elif do_update:
+ orig_print(f"\x1b[2K\rUpdating: {path}", end='')
+
+ # Check if the path is a git repository
+ if not os.path.exists(os.path.join(path, '.git')):
+ raise ValueError(f'[ComfyUI-Manager] Not a valid git repository: {path}')
+
+ if platform.system() == "Windows":
+ updated, success = __win_check_git_update(path, do_fetch, do_update)
+ if updated and success:
+ execute_install_script(None, path, lazy_mode=True, no_deps=no_deps)
+ return updated, success
+ else:
+ # Fetch the latest commits from the remote repository
+ repo = git.Repo(path)
+
+ remote_name = get_remote_name(repo)
+
+ if remote_name is None:
+ raise ValueError(f"No remotes are configured for this repository: {path}")
+
+ remote = repo.remote(name=remote_name)
+
+ if not do_update and repo.head.is_detached:
+ if do_fetch:
+ remote.fetch()
+
+ return True, True # detached branch is treated as updatable
+
+ if repo.head.is_detached:
+ if not switch_to_default_branch(repo):
+ raise ValueError(f"Failed to switch detached branch to default branch: {path}")
+
+ current_branch = repo.active_branch
+ branch_name = current_branch.name
+
+ # Get the current commit hash
+ commit_hash = repo.head.commit.hexsha
+
+ if do_fetch or do_update:
+ remote.fetch()
+
+ if do_update:
+ if repo.is_dirty():
+ print(f"\nSTASH: '{path}' is dirty.")
+ repo.git.stash()
+
+ if f'{remote_name}/{branch_name}' not in repo.refs:
+ if not switch_to_default_branch(repo):
+ raise ValueError(f"Failed to switch to default branch while updating: {path}")
+
+ current_branch = repo.active_branch
+ branch_name = current_branch.name
+
+ if f'{remote_name}/{branch_name}' in repo.refs:
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
+ else:
+ return False, False
+
+ if commit_hash == remote_commit_hash:
+ repo.close()
+ return False, True
+
+ try:
+ remote.pull()
+ repo.git.submodule('update', '--init', '--recursive')
+ new_commit_hash = repo.head.commit.hexsha
+
+ if commit_hash != new_commit_hash:
+ execute_install_script(None, path, no_deps=no_deps)
+ print(f"\x1b[2K\rUpdated: {path}")
+ return True, True
+ else:
+ return False, False
+
+ except Exception as e:
+ print(f"\nUpdating failed: {path}\n{e}", file=sys.stderr)
+ return False, False
+
+ if repo.head.is_detached:
+ repo.close()
+ return True, True
+
+ # Get commit hash of the remote branch
+ current_branch = repo.active_branch
+ branch_name = current_branch.name
+
+ if f'{remote_name}/{branch_name}' in repo.refs:
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
+ else:
+ return True, True # Assuming there's an update if it's not the default branch.
+
+ # Compare the commit hashes to determine if the local repository is behind the remote repository
+ if commit_hash != remote_commit_hash:
+ # Get the commit dates
+ commit_date = repo.head.commit.committed_datetime
+ remote_commit_date = repo.refs[f'{remote_name}/{branch_name}'].object.committed_datetime
+
+ # Compare the commit dates to determine if the local repository is behind the remote repository
+ if commit_date < remote_commit_date:
+ repo.close()
+ return True, True
+
+ repo.close()
+
+ return False, True
+
+
+class GitProgress(RemoteProgress):
+ def __init__(self):
+ super().__init__()
+ self.pbar = tqdm()
+
+ def update(self, op_code, cur_count, max_count=None, message=''):
+ self.pbar.total = max_count
+ self.pbar.n = cur_count
+ self.pbar.pos = 0
+ self.pbar.refresh()
+
+
+def is_valid_url(url):
+ try:
+ # Check for HTTP/HTTPS URL format
+ result = urlparse(url)
+ if all([result.scheme, result.netloc]):
+ return True
+ finally:
+ # Check for SSH git URL format
+ pattern = re.compile(r"^(.+@|ssh://).+:.+$")
+ if pattern.match(url):
+ return True
+ return False
+
+
+async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=False):
+ await unified_manager.reload('cache')
+ await unified_manager.get_custom_nodes('default', 'cache')
+
+ print(f"{msg_prefix}Install: {url}")
+
+ result = ManagedResult('install-git')
+
+ if not is_valid_url(url):
+ return result.fail(f"Invalid git url: '{url}'")
+
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ cnr = unified_manager.get_cnr_by_repo(url)
+ if cnr:
+ cnr_id = cnr['id']
+ return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache')
+ else:
+ repo_name = os.path.splitext(os.path.basename(url))[0]
+
+ # NOTE: Keep original name as possible if unknown node
+ # node_dir = f"{repo_name}@unknown"
+ node_dir = repo_name
+
+ repo_path = os.path.join(get_default_custom_nodes_path(), node_dir)
+
+ if os.path.exists(repo_path):
+ return result.fail(f"Already exists: '{repo_path}'")
+
+ for custom_nodes_dir in get_custom_nodes_paths():
+ disabled_repo_path1 = os.path.join(custom_nodes_dir, '.disabled', node_dir)
+ disabled_repo_path2 = os.path.join(custom_nodes_dir, repo_name+'.disabled') # old style
+
+ if os.path.exists(disabled_repo_path1):
+ return result.fail(f"Already exists (disabled): '{disabled_repo_path1}'")
+
+ if os.path.exists(disabled_repo_path2):
+ return result.fail(f"Already exists (disabled): '{disabled_repo_path2}'")
+
+ print(f"CLONE into '{repo_path}'")
+
+ # Clone the repository from the remote URL
+ clone_url = git_utils.get_url_for_clone(url)
+
+ if not instant_execution and platform.system() == 'Windows':
+ res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
+ if res != 0:
+ return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
+ else:
+ repo = git.Repo.clone_from(clone_url, repo_path, recursive=True, progress=GitProgress())
+ repo.git.clear_cache()
+ repo.close()
+
+ execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
+ print("Installation was successful.")
+ return result.with_target(repo_path)
+
+ except Exception as e:
+ traceback.print_exc()
+ print(f"Install(git-clone) error[1]: {url} / {e}", file=sys.stderr)
+ return result.fail(f"Install(git-clone)[1] error: {url} / {e}")
+
+
+def git_pull(path):
+ # Check if the path is a git repository
+ if not os.path.exists(os.path.join(path, '.git')):
+ raise ValueError('Not a git repository')
+
+ # Pull the latest changes from the remote repository
+ if platform.system() == "Windows":
+ return __win_check_git_pull(path)
+ else:
+ repo = git.Repo(path)
+
+ if repo.is_dirty():
+ print(f"STASH: '{path}' is dirty.")
+ repo.git.stash()
+
+ if repo.head.is_detached:
+ if not switch_to_default_branch(repo):
+ raise ValueError(f"Failed to switch to default branch while pulling: {path}")
+
+ current_branch = repo.active_branch
+ remote_name = current_branch.tracking_branch().remote_name
+ remote = repo.remote(name=remote_name)
+
+ remote.pull()
+ repo.git.submodule('update', '--init', '--recursive')
+
+ repo.close()
+
+ return True
+
+
+async def get_data_by_mode(mode, filename, channel_url=None):
+ if channel_url in get_channel_dict():
+ channel_url = get_channel_dict()[channel_url]
+
+ try:
+ local_uri = os.path.join(manager_util.comfyui_manager_path, filename)
+
+ if mode == "local":
+ json_obj = await manager_util.get_data(local_uri)
+ else:
+ if channel_url is None:
+ uri = get_config()['channel_url'] + '/' + filename
+ else:
+ uri = channel_url + '/' + filename
+
+ cache_uri = str(manager_util.simple_hash(uri))+'_'+filename
+ cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
+
+ if get_config()['network_mode'] == 'offline' or manager_util.is_manager_pip_package():
+ # offline network mode
+ if os.path.exists(cache_uri):
+ json_obj = await manager_util.get_data(cache_uri)
+ else:
+ local_uri = os.path.join(manager_util.comfyui_manager_path, filename)
+ if os.path.exists(local_uri):
+ json_obj = await manager_util.get_data(local_uri)
+ else:
+ json_obj = {} # fallback
+ else:
+ # public network mode
+ if mode == "cache" and manager_util.is_file_created_within_one_day(cache_uri):
+ json_obj = await manager_util.get_data(cache_uri)
+ else:
+ json_obj = await manager_util.get_data(uri)
+ with manager_util.cache_lock:
+ with open(cache_uri, "w", encoding='utf-8') as file:
+ json.dump(json_obj, file, indent=4, sort_keys=True)
+ except Exception as e:
+ print(f"[ComfyUI-Manager] Due to a network error, switching to local mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
+ uri = os.path.join(manager_util.comfyui_manager_path, filename)
+ json_obj = await manager_util.get_data(uri)
+
+ return json_obj
+
+
+def gitclone_fix(files, instant_execution=False, no_deps=False):
+ print(f"Try fixing: {files}")
+ for url in files:
+ if not is_valid_url(url):
+ print(f"Invalid git url: '{url}'")
+ return False
+
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ repo_name = os.path.splitext(os.path.basename(url))[0]
+ repo_path = os.path.join(get_default_custom_nodes_path(), repo_name)
+
+ if os.path.exists(repo_path+'.disabled'):
+ repo_path = repo_path+'.disabled'
+
+ if not execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps):
+ return False
+
+ except Exception as e:
+ print(f"Fix(git-clone) error: {url} / {e}", file=sys.stderr)
+ return False
+
+ print(f"Attempt to fixing '{files}' is done.")
+ return True
+
+
+def pip_install(packages):
+ install_cmd = ['#FORCE'] + manager_util.make_pip_cmd(["install", '-U']) + packages
+ try_install_script('pip install via manager', '..', install_cmd)
+
+
+def rmtree(path):
+ retry_count = 3
+
+ while True:
+ try:
+ retry_count -= 1
+
+ if platform.system() == "Windows":
+ manager_funcs.run_script(['attrib', '-R', path + '\\*', '/S'])
+ shutil.rmtree(path)
+
+ return True
+
+ except Exception as ex:
+ print(f"ex: {ex}")
+ time.sleep(3)
+
+ if retry_count < 0:
+ raise ex
+
+ print(f"Uninstall retry({retry_count})")
+
+
+def gitclone_uninstall(files):
+ import os
+
+ print(f"Uninstall: {files}")
+ for url in files:
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ for custom_nodes_dir in get_custom_nodes_paths():
+ dir_name:str = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
+ dir_path = os.path.join(custom_nodes_dir, dir_name)
+
+ # safety check
+ if dir_path == '/' or dir_path[1:] == ":/" or dir_path == '':
+ print(f"Uninstall(git-clone) error: invalid path '{dir_path}' for '{url}'")
+ return False
+
+ install_script_path = os.path.join(dir_path, "uninstall.py")
+ disable_script_path = os.path.join(dir_path, "disable.py")
+ if os.path.exists(install_script_path):
+ uninstall_cmd = [sys.executable, "uninstall.py"]
+ code = manager_funcs.run_script(uninstall_cmd, cwd=dir_path)
+
+ if code != 0:
+ print(f"An error occurred during the execution of the uninstall.py script. Only the '{dir_path}' will be deleted.")
+ elif os.path.exists(disable_script_path):
+ disable_script = [sys.executable, "disable.py"]
+ code = manager_funcs.run_script(disable_script, cwd=dir_path)
+ if code != 0:
+ print(f"An error occurred during the execution of the disable.py script. Only the '{dir_path}' will be deleted.")
+
+ if os.path.exists(dir_path):
+ rmtree(dir_path)
+ elif os.path.exists(dir_path + ".disabled"):
+ rmtree(dir_path + ".disabled")
+ except Exception as e:
+ print(f"Uninstall(git-clone) error: {url} / {e}", file=sys.stderr)
+ return False
+
+ print("Uninstallation was successful.")
+ return True
+
+
+def gitclone_set_active(files, is_disable):
+ import os
+
+ if is_disable:
+ action_name = "Disable"
+ else:
+ action_name = "Enable"
+
+ print(f"{action_name}: {files}")
+ for url in files:
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ for custom_nodes_dir in get_custom_nodes_paths():
+ dir_name:str = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
+ dir_path = os.path.join(custom_nodes_dir, dir_name)
+
+ # safety check
+ if dir_path == '/' or dir_path[1:] == ":/" or dir_path == '':
+ print(f"{action_name}(git-clone) error: invalid path '{dir_path}' for '{url}'")
+ return False
+
+ if is_disable:
+ current_path = dir_path
+ base_path = extract_base_custom_nodes_dir(current_path)
+ new_path = os.path.join(base_path, ".disabled", dir_name)
+
+ if not os.path.exists(current_path):
+ continue
+ else:
+ current_path1 = os.path.join(get_default_custom_nodes_path(), ".disabled", dir_name)
+ current_path2 = dir_path + ".disabled"
+
+ if os.path.exists(current_path1):
+ current_path = current_path1
+ elif os.path.exists(current_path2):
+ current_path = current_path2
+ else:
+ continue
+
+ base_path = extract_base_custom_nodes_dir(current_path)
+ new_path = os.path.join(base_path, dir_name)
+
+ shutil.move(current_path, new_path)
+
+ if is_disable:
+ if os.path.exists(os.path.join(new_path, "disable.py")):
+ disable_script = [sys.executable, "disable.py"]
+ try_install_script(url, new_path, disable_script)
+ else:
+ if os.path.exists(os.path.join(new_path, "enable.py")):
+ enable_script = [sys.executable, "enable.py"]
+ try_install_script(url, new_path, enable_script)
+
+ break # for safety
+
+ except Exception as e:
+ print(f"{action_name}(git-clone) error: {url} / {e}", file=sys.stderr)
+ return False
+
+ print(f"{action_name} was successful.")
+ return True
+
+
+def gitclone_update(files, instant_execution=False, skip_script=False, msg_prefix="", no_deps=False):
+ import os
+
+ print(f"{msg_prefix}Update: {files}")
+ for url in files:
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ for custom_nodes_dir in get_default_custom_nodes_path():
+ repo_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
+ repo_path = os.path.join(custom_nodes_dir, repo_name)
+
+ if os.path.exists(repo_path+'.disabled'):
+ repo_path = repo_path+'.disabled'
+
+ elif os.path.exists(os.path.join(get_default_custom_nodes_path(), "disabled", repo_name)):
+ repo_path = os.path.join(get_default_custom_nodes_path(), "disabled", repo_name)
+
+ if not os.path.exists(repo_path):
+ continue
+
+ git_pull(repo_path)
+
+ if not skip_script:
+ if instant_execution:
+ if not execute_install_script(url, repo_path, lazy_mode=False, instant_execution=True, no_deps=no_deps):
+ return False
+ else:
+ if not execute_install_script(url, repo_path, lazy_mode=True, no_deps=no_deps):
+ return False
+
+ break # for safety
+
+ except Exception as e:
+ print(f"Update(git-clone) error: {url} / {e}", file=sys.stderr)
+ return False
+
+ if not skip_script:
+ print("Update was successful.")
+ return True
+
+
+def update_to_stable_comfyui(repo_path):
+ try:
+ repo = git.Repo(repo_path)
+ try:
+ repo.git.checkout(repo.heads.master)
+ except:
+ logging.error(f"[ComfyUI-Manager] Failed to checkout 'master' branch.\nrepo_path={repo_path}\nAvailable branches:")
+ for branch in repo.branches:
+ logging.error('\t'+branch.name)
+ return "fail", None
+
+ versions, current_tag, _ = get_comfyui_versions(repo)
+
+ if len(versions) == 0 or (len(versions) == 1 and versions[0] == 'nightly'):
+ logging.info("[ComfyUI-Manager] Unable to update to the stable ComfyUI version.")
+ return "fail", None
+
+ if versions[0] == 'nightly':
+ latest_tag = versions[1]
+ else:
+ latest_tag = versions[0]
+
+ if current_tag == latest_tag:
+ return "skip", None
+ else:
+ logging.info(f"[ComfyUI-Manager] Updating ComfyUI: {current_tag} -> {latest_tag}")
+ repo.git.checkout(latest_tag)
+ return 'updated', latest_tag
+ except:
+ traceback.print_exc()
+ return "fail", None
+
+
+def update_path(repo_path, instant_execution=False, no_deps=False):
+ if not os.path.exists(os.path.join(repo_path, '.git')):
+ return "fail"
+
+ # version check
+ repo = git.Repo(repo_path)
+
+ is_switched = False
+ if repo.head.is_detached:
+ if not switch_to_default_branch(repo):
+ return "fail"
+ else:
+ is_switched = True
+
+ current_branch = repo.active_branch
+ branch_name = current_branch.name
+
+ if current_branch.tracking_branch() is None:
+ print(f"[ComfyUI-Manager] There is no tracking branch ({current_branch})")
+ remote_name = get_remote_name(repo)
+ else:
+ remote_name = current_branch.tracking_branch().remote_name
+ remote = repo.remote(name=remote_name)
+
+ try:
+ remote.fetch()
+ except Exception as e:
+ if 'detected dubious' in str(e):
+ print(f"[ComfyUI-Manager] Try fixing 'dubious repository' error on '{repo_path}' repository")
+ safedir_path = repo_path.replace('\\', '/')
+ subprocess.run(['git', 'config', '--global', '--add', 'safe.directory', safedir_path])
+ try:
+ remote.fetch()
+ except Exception:
+ print(f"\n[ComfyUI-Manager] Failed to fixing repository setup. Please execute this command on cmd: \n"
+ f"-----------------------------------------------------------------------------------------\n"
+ f'git config --global --add safe.directory "{safedir_path}"\n'
+ f"-----------------------------------------------------------------------------------------\n")
+ return "fail"
+
+ commit_hash = repo.head.commit.hexsha
+
+ if f'{remote_name}/{branch_name}' in repo.refs:
+ remote_commit_hash = repo.refs[f'{remote_name}/{branch_name}'].object.hexsha
+ else:
+ return "fail"
+
+ if commit_hash != remote_commit_hash:
+ git_pull(repo_path)
+ execute_install_script("ComfyUI", repo_path, instant_execution=instant_execution, no_deps=no_deps)
+ return "updated"
+ elif is_switched:
+ return "updated"
+ else:
+ return "skipped"
+
+
+def lookup_customnode_by_url(data, target):
+ for x in data['custom_nodes']:
+ if target in x['files']:
+ for custom_nodes_dir in get_custom_nodes_paths():
+ dir_name = os.path.splitext(os.path.basename(target))[0].replace(".git", "")
+ dir_path = os.path.join(custom_nodes_dir, dir_name)
+ if os.path.exists(dir_path):
+ x['installed'] = 'True'
+ else:
+ disabled_path1 = os.path.join(custom_nodes_dir, '.disabled', dir_name)
+ disabled_path2 = dir_path + ".disabled"
+
+ if os.path.exists(disabled_path1) or os.path.exists(disabled_path2):
+ x['installed'] = 'Disabled'
+ else:
+ continue
+
+ return x
+
+ return None
+
+
+def lookup_installed_custom_nodes_legacy(repo_name):
+ base_paths = get_custom_nodes_paths()
+
+ for base_path in base_paths:
+ repo_path = os.path.join(base_path, repo_name)
+ if os.path.exists(repo_path):
+ return True, repo_path
+ elif os.path.exists(repo_path + '.disabled'):
+ return False, repo_path
+
+ return None
+
+
+def simple_check_custom_node(url):
+ dir_name = os.path.splitext(os.path.basename(url))[0].replace(".git", "")
+ dir_path = os.path.join(get_default_custom_nodes_path(), dir_name)
+ if os.path.exists(dir_path):
+ return 'installed'
+ elif os.path.exists(dir_path+'.disabled'):
+ return 'disabled'
+
+ return 'not-installed'
+
+
+def check_state_of_git_node_pack_single(item, do_fetch=False, do_update_check=True, do_update=False):
+ if item['version'] == 'unknown':
+ dir_path = unified_manager.unknown_active_nodes.get(item['id'])[1]
+ elif item['version'] == 'nightly':
+ dir_path = unified_manager.active_nodes.get(item['id'])[1]
+ else:
+ # skip CNR nodes
+ dir_path = None
+
+ if dir_path and os.path.exists(dir_path):
+ if do_update_check:
+ try:
+ update_state, success = git_repo_update_check_with(dir_path, do_fetch, do_update)
+ if (do_update_check or do_update) and update_state:
+ item['update-state'] = 'true'
+ elif do_update and not success:
+ item['update-state'] = 'fail'
+ except Exception:
+ print(f"[ComfyUI-Manager] Failed to check state of the git node pack: {dir_path}")
+
+
+def get_installed_pip_packages():
+ # extract pip package infos
+ cmd = manager_util.make_pip_cmd(['freeze'])
+ pips = subprocess.check_output(cmd, text=True).split('\n')
+
+ res = {}
+ for x in pips:
+ if x.strip() == "":
+ continue
+
+ if ' @ ' in x:
+ spec_url = x.split(' @ ')
+ res[spec_url[0]] = spec_url[1]
+ else:
+ res[x] = ""
+
+ return res
+
+
+async def get_current_snapshot(custom_nodes_only = False):
+ await unified_manager.reload('cache')
+ await unified_manager.get_custom_nodes('default', 'cache')
+
+ # Get ComfyUI hash
+ repo_path = context.comfy_path
+
+ comfyui_commit_hash = None
+ if not custom_nodes_only:
+ if os.path.exists(os.path.join(repo_path, '.git')):
+ repo = git.Repo(repo_path)
+ comfyui_commit_hash = repo.head.commit.hexsha
+
+ git_custom_nodes = {}
+ cnr_custom_nodes = {}
+ file_custom_nodes = []
+
+ # Get custom nodes hash
+ for custom_nodes_dir in get_custom_nodes_paths():
+ paths = os.listdir(custom_nodes_dir)
+
+ disabled_path = os.path.join(custom_nodes_dir, '.disabled')
+ if os.path.exists(disabled_path):
+ for x in os.listdir(disabled_path):
+ paths.append(os.path.join(disabled_path, x))
+
+ for path in paths:
+ if path in ['.disabled', '__pycache__']:
+ continue
+
+ fullpath = os.path.join(custom_nodes_dir, path)
+
+ if os.path.isdir(fullpath):
+ is_disabled = path.endswith(".disabled") or os.path.basename(os.path.dirname(fullpath)) == ".disabled"
+
+ try:
+ info = unified_manager.resolve_from_path(fullpath)
+
+ if info is None:
+ continue
+
+ if info['ver'] not in ['nightly', 'latest', 'unknown']:
+ if is_disabled:
+ continue # don't restore disabled state of CNR node.
+
+ cnr_custom_nodes[info['id']] = info['ver']
+ else:
+ commit_hash = git_utils.get_commit_hash(fullpath)
+ url = git_utils.git_url(fullpath)
+ git_custom_nodes[url] = dict(hash=commit_hash, disabled=is_disabled)
+ except:
+ print(f"Failed to extract snapshots for the custom node '{path}'.")
+
+ elif path.endswith('.py'):
+ is_disabled = path.endswith(".py.disabled")
+ filename = os.path.basename(path)
+ item = {
+ 'filename': filename,
+ 'disabled': is_disabled
+ }
+
+ file_custom_nodes.append(item)
+
+ pip_packages = None if custom_nodes_only else get_installed_pip_packages()
+
+ return {
+ 'comfyui': comfyui_commit_hash,
+ 'git_custom_nodes': git_custom_nodes,
+ 'cnr_custom_nodes': cnr_custom_nodes,
+ 'file_custom_nodes': file_custom_nodes,
+ 'pips': pip_packages,
+ }
+
+
+async def save_snapshot_with_postfix(postfix, path=None, custom_nodes_only = False):
+ if path is None:
+ now = datetime.now()
+
+ date_time_format = now.strftime("%Y-%m-%d_%H-%M-%S")
+ file_name = f"{date_time_format}_{postfix}"
+
+ path = os.path.join(context.manager_snapshot_path, f"{file_name}.json")
+ else:
+ file_name = path.replace('\\', '/').split('/')[-1]
+ file_name = file_name.split('.')[-2]
+
+ snapshot = await get_current_snapshot(custom_nodes_only)
+ if path.endswith('.json'):
+ with open(path, "w") as json_file:
+ json.dump(snapshot, json_file, indent=4)
+
+ return file_name + '.json'
+
+ elif path.endswith('.yaml'):
+ with open(path, "w") as yaml_file:
+ snapshot = {'custom_nodes': snapshot}
+ yaml.dump(snapshot, yaml_file, allow_unicode=True)
+
+ return path
+
+
+async def extract_nodes_from_workflow(filepath, mode='local', channel_url='default'):
+ # prepare json data
+ workflow = None
+ if filepath.endswith('.json'):
+ with open(filepath, "r", encoding="UTF-8", errors="ignore") as json_file:
+ try:
+ workflow = json.load(json_file)
+ except:
+ print(f"Invalid workflow file: {filepath}")
+ exit(-1)
+
+ elif filepath.endswith('.png'):
+ from PIL import Image
+ with Image.open(filepath) as img:
+ if 'workflow' not in img.info:
+ print(f"The specified .png file doesn't have a workflow: {filepath}")
+ exit(-1)
+ else:
+ try:
+ workflow = json.loads(img.info['workflow'])
+ except:
+ print(f"This is not a valid .png file containing a ComfyUI workflow: {filepath}")
+ exit(-1)
+
+ if workflow is None:
+ print(f"Invalid workflow file: {filepath}")
+ exit(-1)
+
+ # extract nodes
+ used_nodes = set()
+
+ def extract_nodes(sub_workflow):
+ for x in sub_workflow['nodes']:
+ node_name = x.get('type')
+
+ # skip virtual nodes
+ if node_name in ['Reroute', 'Note']:
+ continue
+
+ if node_name is not None and not (node_name.startswith('workflow/') or node_name.startswith('workflow>')):
+ used_nodes.add(node_name)
+
+ if 'nodes' in workflow:
+ extract_nodes(workflow)
+
+ if 'extra' in workflow:
+ if 'groupNodes' in workflow['extra']:
+ for x in workflow['extra']['groupNodes'].values():
+ extract_nodes(x)
+
+ # lookup dependent custom nodes
+ ext_map = await get_data_by_mode(mode, 'extension-node-map.json', channel_url)
+
+ rext_map = {}
+ preemption_map = {}
+ patterns = []
+ for k, v in ext_map.items():
+ if k == 'https://github.com/comfyanonymous/ComfyUI':
+ for x in v[0]:
+ if x not in preemption_map:
+ preemption_map[x] = []
+
+ preemption_map[x] = k
+ continue
+
+ for x in v[0]:
+ if x not in rext_map:
+ rext_map[x] = []
+
+ rext_map[x].append(k)
+
+ if 'preemptions' in v[1]:
+ for x in v[1]['preemptions']:
+ if x not in preemption_map:
+ preemption_map[x] = []
+
+ preemption_map[x] = k
+
+ if 'nodename_pattern' in v[1]:
+ patterns.append((v[1]['nodename_pattern'], k))
+
+ # identify used extensions
+ used_exts = set()
+ unknown_nodes = set()
+
+ for node_name in used_nodes:
+ ext = preemption_map.get(node_name)
+
+ if ext is None:
+ ext = rext_map.get(node_name)
+ if ext is not None:
+ ext = ext[0]
+
+ if ext is None:
+ for pat_ext in patterns:
+ if re.search(pat_ext[0], node_name):
+ ext = pat_ext[1]
+ break
+
+ if ext == 'https://github.com/comfyanonymous/ComfyUI':
+ pass
+ elif ext is not None:
+ used_exts.add(ext)
+ else:
+ unknown_nodes.add(node_name)
+
+ return used_exts, unknown_nodes
+
+
+def unzip(model_path):
+ if not os.path.exists(model_path):
+ print(f"[ComfyUI-Manager] unzip: File not found: {model_path}")
+ return False
+
+ base_dir = os.path.dirname(model_path)
+ filename = os.path.basename(model_path)
+ target_dir = os.path.join(base_dir, filename[:-4])
+
+ os.makedirs(target_dir, exist_ok=True)
+
+ with zipfile.ZipFile(model_path, 'r') as zip_ref:
+ zip_ref.extractall(target_dir)
+
+ # Check if there's only one directory inside the target directory
+ contents = os.listdir(target_dir)
+ if len(contents) == 1 and os.path.isdir(os.path.join(target_dir, contents[0])):
+ nested_dir = os.path.join(target_dir, contents[0])
+ # Move each file and sub-directory in the nested directory up to the target directory
+ for item in os.listdir(nested_dir):
+ shutil.move(os.path.join(nested_dir, item), os.path.join(target_dir, item))
+ # Remove the now empty nested directory
+ os.rmdir(nested_dir)
+
+ os.remove(model_path)
+ return True
+
+
+def map_to_unified_keys(json_obj):
+ res = {}
+ for k, v in json_obj.items():
+ cnr = unified_manager.get_cnr_by_repo(k)
+ if cnr:
+ res[cnr['id']] = v
+ else:
+ res[k] = v
+
+ return res
+
+
+async def get_unified_total_nodes(channel, mode, regsitry_cache_mode='cache'):
+ await unified_manager.reload(regsitry_cache_mode)
+
+ res = await unified_manager.get_custom_nodes(channel, mode)
+
+ # collect pure cnr ids (i.e. not exists in custom-node-list.json)
+ # populate state/updatable field to non-pure cnr nodes
+ cnr_ids = set(unified_manager.cnr_map.keys())
+ for k, v in res.items():
+ # resolve cnr_id from repo url
+ files_in_json = v.get('files', [])
+ cnr_id = None
+ if len(files_in_json) == 1:
+ cnr = unified_manager.get_cnr_by_repo(files_in_json[0])
+ if cnr:
+ cnr_id = cnr['id']
+
+ if cnr_id is not None:
+ # cnr or nightly version
+ cnr_ids.remove(cnr_id)
+ updatable = False
+ cnr = unified_manager.cnr_map[cnr_id]
+
+ if cnr_id in invalid_nodes:
+ v['invalid-installation'] = True
+
+ if cnr_id in unified_manager.active_nodes:
+ # installed
+ v['state'] = 'enabled'
+ if unified_manager.active_nodes[cnr_id][0] != 'nightly':
+ updatable = unified_manager.is_updatable(cnr_id)
+ else:
+ updatable = False
+ v['active_version'] = unified_manager.active_nodes[cnr_id][0]
+ v['version'] = v['active_version']
+
+ if cm_global.try_call(api="cm.is_import_failed_extension", name=unified_manager.active_nodes[cnr_id][1]):
+ v['import-fail'] = True
+
+ elif cnr_id in unified_manager.cnr_inactive_nodes:
+ # disabled
+ v['state'] = 'disabled'
+ cnr_ver = unified_manager.get_from_cnr_inactive_nodes(cnr_id)
+ if cnr_ver is not None:
+ v['version'] = str(cnr_ver[0])
+ else:
+ v['version'] = '0'
+
+ elif cnr_id in unified_manager.nightly_inactive_nodes:
+ # disabled
+ v['state'] = 'disabled'
+ v['version'] = 'nightly'
+ else:
+ # not installed
+ v['state'] = 'not-installed'
+
+ if 'version' not in v:
+ v['version'] = cnr['latest_version']['version']
+
+ v['update-state'] = 'true' if updatable else 'false'
+ else:
+ # unknown version
+ v['version'] = 'unknown'
+
+ if unified_manager.is_enabled(k, 'unknown'):
+ v['state'] = 'enabled'
+ v['active_version'] = 'unknown'
+
+ if cm_global.try_call(api="cm.is_import_failed_extension", name=unified_manager.unknown_active_nodes[k][1]):
+ v['import-fail'] = True
+
+ elif unified_manager.is_disabled(k, 'unknown'):
+ v['state'] = 'disabled'
+ else:
+ v['state'] = 'not-installed'
+
+ # add items for pure cnr nodes
+ if normalize_channel(channel) == DEFAULT_CHANNEL:
+ # Don't show CNR nodes unless default channel
+ for cnr_id in cnr_ids:
+ cnr = unified_manager.cnr_map[cnr_id]
+ author = cnr['publisher']['name']
+ title = cnr['name']
+ reference = f"https://registry.comfy.org/nodes/{cnr['id']}"
+ repository = cnr.get('repository', '')
+ install_type = "cnr"
+ description = cnr.get('description', '')
+
+ ver = None
+ active_version = None
+ updatable = False
+ import_fail = None
+ if cnr_id in unified_manager.active_nodes:
+ # installed
+ state = 'enabled'
+ updatable = unified_manager.is_updatable(cnr_id)
+ active_version = unified_manager.active_nodes[cnr['id']][0]
+ ver = active_version
+
+ if cm_global.try_call(api="cm.is_import_failed_extension", name=unified_manager.active_nodes[cnr_id][1]):
+ import_fail = True
+
+ elif cnr['id'] in unified_manager.cnr_inactive_nodes:
+ # disabled
+ state = 'disabled'
+ elif cnr['id'] in unified_manager.nightly_inactive_nodes:
+ # disabled
+ state = 'disabled'
+ ver = 'nightly'
+ else:
+ # not installed
+ state = 'not-installed'
+
+ if ver is None:
+ ver = cnr['latest_version']['version']
+
+ item = dict(author=author, title=title, reference=reference, repository=repository, install_type=install_type,
+ description=description, state=state, updatable=updatable, version=ver)
+
+ if active_version:
+ item['active_version'] = active_version
+
+ if import_fail:
+ item['import-fail'] = True
+
+ res[cnr_id] = item
+
+ return res
+
+
+def populate_github_stats(node_packs, json_obj_github):
+ for k, v in node_packs.items():
+ try:
+ url = v['reference']
+ if url in json_obj_github:
+ v['stars'] = json_obj_github[url]['stars']
+ v['last_update'] = json_obj_github[url]['last_update']
+ v['trust'] = json_obj_github[url]['author_account_age_days'] > 600
+ else:
+ v['stars'] = -1
+ v['last_update'] = -1
+ v['trust'] = False
+ except:
+ logging.error(f"[ComfyUI-Manager] DB item is broken:\n{v}")
+
+
+def populate_favorites(node_packs, json_obj_extras):
+ favorites = set(json_obj_extras['favorites'])
+
+ for k, v in node_packs.items():
+ if v.get('version') != 'unknown':
+ if k in favorites:
+ v['is_favorite'] = True
+
+
+async def restore_snapshot(snapshot_path, git_helper_extras=None):
+ cloned_repos = []
+ checkout_repos = []
+ enabled_repos = []
+ disabled_repos = []
+ skip_node_packs = []
+ switched_node_packs = []
+ installed_node_packs = []
+ failed = []
+
+ await unified_manager.reload('cache')
+ await unified_manager.get_custom_nodes('default', 'cache')
+
+ cnr_repo_map = {}
+ for k, v in unified_manager.repo_cnr_map.items():
+ cnr_repo_map[v['id']] = k
+
+ print("Restore snapshot.")
+
+ postinstalls = []
+
+ with open(snapshot_path, 'r', encoding="UTF-8") as snapshot_file:
+ if snapshot_path.endswith('.json'):
+ info = json.load(snapshot_file)
+ elif snapshot_path.endswith('.yaml'):
+ info = yaml.load(snapshot_file, Loader=yaml.SafeLoader)
+ info = info['custom_nodes']
+
+ # for cnr restore
+ cnr_info = info.get('cnr_custom_nodes')
+ if cnr_info is not None:
+ # disable not listed cnr nodes
+ todo_disable = []
+ todo_checkout = []
+
+ for k, v in unified_manager.active_nodes.items():
+ if 'comfyui-manager' in k:
+ continue
+
+ if v[0] != 'nightly':
+ if k not in cnr_info:
+ todo_disable.append(k)
+ else:
+ cnr_ver = cnr_info[k]
+ if v[1] != cnr_ver:
+ todo_checkout.append((k, cnr_ver))
+ else:
+ skip_node_packs.append(k)
+
+ for x in todo_disable:
+ unified_manager.unified_disable(x, False)
+ disabled_repos.append(x)
+
+ for x in todo_checkout:
+ ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
+ if ps.action == 'switch-cnr' and ps.result:
+ switched_node_packs.append(f"{x[0]}@{x[1]}")
+ elif ps.action == 'skip':
+ skip_node_packs.append(f"{x[0]}@{x[1]}")
+ elif not ps.result:
+ failed.append(f"{x[0]}@{x[1]}")
+
+ # install listed cnr nodes
+ for k, v in cnr_info.items():
+ if 'comfyui-manager' in k:
+ continue
+
+ ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
+ if ps.action == 'install-cnr' and ps.result:
+ installed_node_packs.append(f"{k}@{v}")
+
+ if ps is not None and ps.result:
+ if hasattr(ps, 'postinstall'):
+ postinstalls.append(ps.postinstall)
+ else:
+ print("cm-cli: unexpected [0001]")
+
+ # for nightly restore
+ _git_info = info.get('git_custom_nodes')
+ git_info = {}
+
+ # normalize github repo
+ for k, v in _git_info.items():
+ # robust filter out comfyui-manager while restoring snapshot
+ if 'comfyui-manager' in k.lower():
+ continue
+
+ norm_k = git_utils.normalize_url(k)
+ git_info[norm_k] = v
+
+ if git_info is not None:
+ todo_disable = []
+ todo_enable = []
+ todo_checkout = []
+ processed_urls = []
+
+ for k, v in unified_manager.active_nodes.items():
+ if 'comfyui-manager' in k:
+ continue
+
+ if v[0] == 'nightly' and cnr_repo_map.get(k):
+ repo_url = cnr_repo_map.get(k)
+ normalized_url = git_utils.normalize_url(repo_url)
+
+ if normalized_url not in git_info:
+ todo_disable.append(k)
+ else:
+ commit_hash = git_info[normalized_url]['hash']
+ todo_checkout.append((v[1], commit_hash))
+
+ for k, v in unified_manager.nightly_inactive_nodes.items():
+ if 'comfyui-manager' in k:
+ continue
+
+ if cnr_repo_map.get(k):
+ repo_url = cnr_repo_map.get(k)
+ normalized_url = git_utils.normalize_url(repo_url)
+
+ if normalized_url in git_info:
+ commit_hash = git_info[normalized_url]['hash']
+ todo_enable.append((k, commit_hash))
+ processed_urls.append(normalized_url)
+
+ for x in todo_disable:
+ unified_manager.unified_disable(x, False)
+ disabled_repos.append(x)
+
+ for x in todo_enable:
+ res = unified_manager.unified_enable(x[0], 'nightly')
+
+ is_switched = False
+ if res and res.target:
+ is_switched = repo_switch_commit(res.target, x[1])
+
+ if is_switched:
+ checkout_repos.append(f"{x[0]}@{x[1]}")
+ else:
+ enabled_repos.append(x[0])
+
+ for x in todo_checkout:
+ is_switched = repo_switch_commit(x[0], x[1])
+
+ if is_switched:
+ checkout_repos.append(f"{x[0]}@{x[1]}")
+
+ for x in git_info.keys():
+ normalized_url = git_utils.normalize_url(x)
+ cnr = unified_manager.repo_cnr_map.get(normalized_url)
+ if cnr is not None:
+ pack_id = cnr['id']
+ res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=False)
+ if res.action == 'install-git' and res.result:
+ cloned_repos.append(pack_id)
+ elif res.action == 'skip':
+ skip_node_packs.append(pack_id)
+ elif not res.result:
+ failed.append(pack_id)
+ processed_urls.append(x)
+
+ for x in processed_urls:
+ if x in git_info:
+ del git_info[x]
+
+ # for unknown restore
+ todo_disable = []
+ todo_enable = []
+ todo_checkout = []
+ processed_urls = []
+
+ for k2, v2 in unified_manager.unknown_active_nodes.items():
+ repo_url = resolve_giturl_from_path(v2[1])
+
+ if repo_url is None:
+ continue
+
+ normalized_url = git_utils.normalize_url(repo_url)
+
+ if normalized_url not in git_info:
+ todo_disable.append(k2)
+ else:
+ commit_hash = git_info[normalized_url]['hash']
+ todo_checkout.append((k2, commit_hash))
+ processed_urls.append(normalized_url)
+
+ for k2, v2 in unified_manager.unknown_inactive_nodes.items():
+ repo_url = resolve_giturl_from_path(v2[1])
+
+ if repo_url is None:
+ continue
+
+ normalized_url = git_utils.normalize_url(repo_url)
+
+ if normalized_url in git_info:
+ commit_hash = git_info[normalized_url]['hash']
+ todo_enable.append((k2, commit_hash))
+ processed_urls.append(normalized_url)
+
+ for x in todo_disable:
+ unified_manager.unified_disable(x, True)
+ disabled_repos.append(x)
+
+ for x in todo_enable:
+ res = unified_manager.unified_enable(x[0], 'unknown')
+
+ is_switched = False
+ if res and res.target:
+ is_switched = repo_switch_commit(res.target, x[1])
+
+ if is_switched:
+ checkout_repos.append(f"{x[0]}@{x[1]}")
+ else:
+ enabled_repos.append(x[0])
+
+ for x in todo_checkout:
+ is_switched = repo_switch_commit(x[0], x[1])
+
+ if is_switched:
+ checkout_repos.append(f"{x[0]}@{x[1]}")
+ else:
+ skip_node_packs.append(x[0])
+
+ for x in processed_urls:
+ if x in git_info:
+ del git_info[x]
+
+ for repo_url in git_info.keys():
+ repo_name = os.path.basename(repo_url)
+ if repo_name.endswith('.git'):
+ repo_name = repo_name[:-4]
+
+ to_path = os.path.join(get_default_custom_nodes_path(), repo_name)
+ unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=False)
+ cloned_repos.append(repo_name)
+
+ # print summary
+ for x in cloned_repos:
+ print(f"[ INSTALLED ] {x}")
+ for x in installed_node_packs:
+ print(f"[ INSTALLED ] {x}")
+ for x in checkout_repos:
+ print(f"[ CHECKOUT ] {x}")
+ for x in switched_node_packs:
+ print(f"[ SWITCHED ] {x}")
+ for x in enabled_repos:
+ print(f"[ ENABLED ] {x}")
+ for x in disabled_repos:
+ print(f"[ DISABLED ] {x}")
+ for x in skip_node_packs:
+ print(f"[ SKIPPED ] {x}")
+ for x in failed:
+ print(f"[ FAILED ] {x}")
+
+ # if is_failed:
+ # print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
+
+
+def get_comfyui_versions(repo=None):
+ if repo is None:
+ repo = git.Repo(context.comfy_path)
+
+ try:
+ remote = get_remote_name(repo)
+ repo.remotes[remote].fetch()
+ except:
+ logging.error("[ComfyUI-Manager] Failed to fetch ComfyUI")
+
+ versions = [x.name for x in repo.tags if x.name.startswith('v')]
+
+ # nearest tag
+ versions = sorted(versions, key=lambda v: repo.git.log('-1', '--format=%ct', v), reverse=True)
+ versions = versions[:4]
+
+ current_tag = repo.git.describe('--tags')
+
+ if current_tag not in versions:
+ versions = sorted(versions + [current_tag], key=lambda v: repo.git.log('-1', '--format=%ct', v), reverse=True)
+ versions = versions[:4]
+
+ main_branch = repo.heads.master
+ latest_commit = main_branch.commit
+ latest_tag = repo.git.describe('--tags', latest_commit.hexsha)
+
+ if latest_tag != versions[0]:
+ versions.insert(0, 'nightly')
+ else:
+ versions[0] = 'nightly'
+ current_tag = 'nightly'
+
+ return versions, current_tag, latest_tag
+
+
+def switch_comfyui(tag):
+ repo = git.Repo(context.comfy_path)
+
+ if tag == 'nightly':
+ repo.git.checkout('master')
+ tracking_branch = repo.active_branch.tracking_branch()
+ remote_name = tracking_branch.remote_name
+ repo.remotes[remote_name].pull()
+ print("[ComfyUI-Manager] ComfyUI version is switched to the latest 'master' version")
+ else:
+ repo.git.checkout(tag)
+ print(f"[ComfyUI-Manager] ComfyUI version is switched to '{tag}'")
+
+
+def resolve_giturl_from_path(fullpath):
+ """
+ resolve giturl path of unclassified custom node based on remote url in .git/config
+ """
+ git_config_path = os.path.join(fullpath, '.git', 'config')
+
+ if not os.path.exists(git_config_path):
+ return "unknown"
+
+ config = configparser.ConfigParser(strict=False)
+ config.read(git_config_path)
+
+ for k, v in config.items():
+ if k.startswith('remote ') and 'url' in v:
+ return v['url'].replace("git@github.com:", "https://github.com/")
+
+ return None
+
+
+def repo_switch_commit(repo_path, commit_hash):
+ try:
+ repo = git.Repo(repo_path)
+ if repo.head.commit.hexsha == commit_hash:
+ return False
+
+ repo.git.checkout(commit_hash)
+ return True
+ except:
+ return None
diff --git a/comfyui_manager/legacy/manager_server.py b/comfyui_manager/legacy/manager_server.py
new file mode 100644
index 00000000..448a5150
--- /dev/null
+++ b/comfyui_manager/legacy/manager_server.py
@@ -0,0 +1,1937 @@
+import traceback
+
+import folder_paths
+import locale
+import subprocess # don't remove this
+import concurrent
+import nodes
+import os
+import sys
+import threading
+import re
+import shutil
+import git
+from datetime import datetime
+
+from server import PromptServer
+import logging
+import asyncio
+from collections import deque
+
+from . import manager_core as core
+from ..common import manager_util
+from ..common import cm_global
+from ..common import manager_downloader
+from ..common import context
+
+
+logging.info(f"### Loading: ComfyUI-Manager ({core.version_str})")
+
+if not manager_util.is_manager_pip_package():
+ network_mode_description = "offline"
+else:
+ network_mode_description = core.get_config()['network_mode']
+logging.info("[ComfyUI-Manager] network_mode: " + network_mode_description)
+
+comfy_ui_hash = "-"
+comfyui_tag = None
+
+SECURITY_MESSAGE_MIDDLE_OR_BELOW = "ERROR: To use this action, a security_level of `middle or below` is required. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
+SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
+SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
+SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
+
+routes = PromptServer.instance.routes
+
+def handle_stream(stream, prefix):
+ stream.reconfigure(encoding=locale.getpreferredencoding(), errors='replace')
+ for msg in stream:
+ if prefix == '[!]' and ('it/s]' in msg or 's/it]' in msg) and ('%|' in msg or 'it [' in msg):
+ if msg.startswith('100%'):
+ print('\r' + msg, end="", file=sys.stderr),
+ else:
+ print('\r' + msg[:-1], end="", file=sys.stderr),
+ else:
+ if prefix == '[!]':
+ print(prefix, msg, end="", file=sys.stderr)
+ else:
+ print(prefix, msg, end="")
+
+
+from comfy.cli_args import args
+import latent_preview
+
+def is_loopback(address):
+ import ipaddress
+ try:
+ return ipaddress.ip_address(address).is_loopback
+ except ValueError:
+ return False
+
+is_local_mode = is_loopback(args.listen)
+
+
+model_dir_name_map = {
+ "checkpoints": "checkpoints",
+ "checkpoint": "checkpoints",
+ "unclip": "checkpoints",
+ "text_encoders": "text_encoders",
+ "clip": "text_encoders",
+ "vae": "vae",
+ "lora": "loras",
+ "t2i-adapter": "controlnet",
+ "t2i-style": "controlnet",
+ "controlnet": "controlnet",
+ "clip_vision": "clip_vision",
+ "gligen": "gligen",
+ "upscale": "upscale_models",
+ "embedding": "embeddings",
+ "embeddings": "embeddings",
+ "unet": "diffusion_models",
+ "diffusion_model": "diffusion_models",
+}
+
+
+def is_allowed_security_level(level):
+ if level == 'block':
+ return False
+ elif level == 'high':
+ if is_local_mode:
+ return core.get_config()['security_level'] in ['weak', 'normal-']
+ else:
+ return core.get_config()['security_level'] == 'weak'
+ elif level == 'middle':
+ return core.get_config()['security_level'] in ['weak', 'normal', 'normal-']
+ else:
+ return True
+
+
+async def get_risky_level(files, pip_packages):
+ json_data1 = await core.get_data_by_mode('local', 'custom-node-list.json')
+ json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url='https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main')
+
+ all_urls = set()
+ for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
+ all_urls.update(x.get('files', []))
+
+ for x in files:
+ if x not in all_urls:
+ return "high"
+
+ all_pip_packages = set()
+ for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
+ all_pip_packages.update(x.get('pip', []))
+
+ for p in pip_packages:
+ if p not in all_pip_packages:
+ return "block"
+
+ return "middle"
+
+
+class ManagerFuncsInComfyUI(core.ManagerFuncs):
+ def get_current_preview_method(self):
+ if args.preview_method == latent_preview.LatentPreviewMethod.Auto:
+ return "auto"
+ elif args.preview_method == latent_preview.LatentPreviewMethod.Latent2RGB:
+ return "latent2rgb"
+ elif args.preview_method == latent_preview.LatentPreviewMethod.TAESD:
+ return "taesd"
+ else:
+ return "none"
+
+ def run_script(self, cmd, cwd='.'):
+ if len(cmd) > 0 and cmd[0].startswith("#"):
+ logging.error(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
+ return 0
+
+ process = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, env=core.get_script_env())
+
+ stdout_thread = threading.Thread(target=handle_stream, args=(process.stdout, ""))
+ stderr_thread = threading.Thread(target=handle_stream, args=(process.stderr, "[!]"))
+
+ stdout_thread.start()
+ stderr_thread.start()
+
+ stdout_thread.join()
+ stderr_thread.join()
+
+ return process.wait()
+
+
+core.manager_funcs = ManagerFuncsInComfyUI()
+
+from comfyui_manager.common.manager_downloader import download_url, download_url_with_agent
+
+context.comfy_path = os.path.dirname(folder_paths.__file__)
+core.js_path = os.path.join(context.comfy_path, "web", "extensions")
+
+local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
+local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
+local_db_custom_node_list = os.path.join(manager_util.comfyui_manager_path, "custom-node-list.json")
+local_db_extension_node_mappings = os.path.join(manager_util.comfyui_manager_path, "extension-node-map.json")
+
+
+def set_preview_method(method):
+ if method == 'auto':
+ args.preview_method = latent_preview.LatentPreviewMethod.Auto
+ elif method == 'latent2rgb':
+ args.preview_method = latent_preview.LatentPreviewMethod.Latent2RGB
+ elif method == 'taesd':
+ args.preview_method = latent_preview.LatentPreviewMethod.TAESD
+ else:
+ args.preview_method = latent_preview.LatentPreviewMethod.NoPreviews
+
+ core.get_config()['preview_method'] = method
+
+
+set_preview_method(core.get_config()['preview_method'])
+
+
+def set_component_policy(mode):
+ core.get_config()['component_policy'] = mode
+
+def set_update_policy(mode):
+ core.get_config()['update_policy'] = mode
+
+def set_db_mode(mode):
+ core.get_config()['db_mode'] = mode
+
+def print_comfyui_version():
+ global comfy_ui_hash
+ global comfyui_tag
+
+ is_detached = False
+ try:
+ repo = git.Repo(os.path.dirname(folder_paths.__file__))
+ core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
+
+ comfy_ui_hash = repo.head.commit.hexsha
+ cm_global.variables['comfyui.revision'] = core.comfy_ui_revision
+
+ core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
+ cm_global.variables['comfyui.commit_datetime'] = core.comfy_ui_commit_datetime
+
+ is_detached = repo.head.is_detached
+ current_branch = repo.active_branch.name
+
+ comfyui_tag = context.get_comfyui_tag()
+
+ try:
+ if not os.environ.get('__COMFYUI_DESKTOP_VERSION__') and core.comfy_ui_commit_datetime.date() < core.comfy_ui_required_commit_datetime.date():
+ logging.warning(f"\n\n## [WARN] ComfyUI-Manager: Your ComfyUI version ({core.comfy_ui_revision})[{core.comfy_ui_commit_datetime.date()}] is too old. Please update to the latest version. ##\n\n")
+ except:
+ pass
+
+ # process on_revision_detected -->
+ if 'cm.on_revision_detected_handler' in cm_global.variables:
+ for k, f in cm_global.variables['cm.on_revision_detected_handler']:
+ try:
+ f(core.comfy_ui_revision)
+ except Exception:
+ logging.error(f"[ERROR] '{k}' on_revision_detected_handler")
+ traceback.print_exc()
+
+ del cm_global.variables['cm.on_revision_detected_handler']
+ else:
+ logging.warning("[ComfyUI-Manager] Some features are restricted due to your ComfyUI being outdated.")
+ # <--
+
+ if current_branch == "master":
+ if comfyui_tag:
+ logging.info(f"### ComfyUI Version: {comfyui_tag} | Released on '{core.comfy_ui_commit_datetime.date()}'")
+ else:
+ logging.info(f"### ComfyUI Revision: {core.comfy_ui_revision} [{comfy_ui_hash[:8]}] | Released on '{core.comfy_ui_commit_datetime.date()}'")
+ else:
+ if comfyui_tag:
+ logging.info(f"### ComfyUI Version: {comfyui_tag} on '{current_branch}' | Released on '{core.comfy_ui_commit_datetime.date()}'")
+ else:
+ logging.info(f"### ComfyUI Revision: {core.comfy_ui_revision} on '{current_branch}' [{comfy_ui_hash[:8]}] | Released on '{core.comfy_ui_commit_datetime.date()}'")
+ except:
+ if is_detached:
+ logging.info(f"### ComfyUI Revision: {core.comfy_ui_revision} [{comfy_ui_hash[:8]}] *DETACHED | Released on '{core.comfy_ui_commit_datetime.date()}'")
+ else:
+ logging.info("### ComfyUI Revision: UNKNOWN (The currently installed ComfyUI is not a Git repository)")
+
+
+print_comfyui_version()
+core.check_invalid_nodes()
+
+
+
+def setup_environment():
+ git_exe = core.get_config()['git_exe']
+
+ if git_exe != '':
+ git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
+
+
+setup_environment()
+
+# Expand Server api
+
+from aiohttp import web
+import aiohttp
+import json
+import zipfile
+import urllib.request
+
+
+def get_model_dir(data, show_log=False):
+ if 'download_model_base' in folder_paths.folder_names_and_paths:
+ models_base = folder_paths.folder_names_and_paths['download_model_base'][0][0]
+ else:
+ models_base = folder_paths.models_dir
+
+ # NOTE: Validate to prevent path traversal.
+ if any(char in data['filename'] for char in {'/', '\\', ':'}):
+ return None
+
+ def resolve_custom_node(save_path):
+ save_path = save_path[13:] # remove 'custom_nodes/'
+
+ # NOTE: Validate to prevent path traversal.
+ if save_path.startswith(os.path.sep) or ':' in save_path:
+ return None
+
+ repo_name = save_path.replace('\\','/').split('/')[0] # get custom node repo name
+
+ # NOTE: The creation of files within the custom node path should be removed in the future.
+ repo_path = core.lookup_installed_custom_nodes_legacy(repo_name)
+ if repo_path is not None and repo_path[0]:
+ # Returns the retargeted path based on the actually installed repository
+ return os.path.join(os.path.dirname(repo_path[1]), save_path)
+ else:
+ return None
+
+ if data['save_path'] != 'default':
+ if '..' in data['save_path'] or data['save_path'].startswith('/'):
+ if show_log:
+ logging.info(f"[WARN] '{data['save_path']}' is not allowed path. So it will be saved into 'models/etc'.")
+ base_model = os.path.join(models_base, "etc")
+ else:
+ if data['save_path'].startswith("custom_nodes"):
+ base_model = resolve_custom_node(data['save_path'])
+ if base_model is None:
+ if show_log:
+ logging.info(f"[ComfyUI-Manager] The target custom node for model download is not installed: {data['save_path']}")
+ return None
+ else:
+ base_model = os.path.join(models_base, data['save_path'])
+ else:
+ model_dir_name = model_dir_name_map.get(data['type'].lower())
+ if model_dir_name is not None:
+ base_model = folder_paths.folder_names_and_paths[model_dir_name][0][0]
+ else:
+ base_model = os.path.join(models_base, "etc")
+
+ return base_model
+
+
+def get_model_path(data, show_log=False):
+ base_model = get_model_dir(data, show_log)
+ if base_model is None:
+ return None
+ else:
+ if data['filename'] == '':
+ return os.path.join(base_model, os.path.basename(data['url']))
+ else:
+ return os.path.join(base_model, data['filename'])
+
+
+def check_state_of_git_node_pack(node_packs, do_fetch=False, do_update_check=True, do_update=False):
+ if do_fetch:
+ print("Start fetching...", end="")
+ elif do_update:
+ print("Start updating...", end="")
+ elif do_update_check:
+ print("Start update check...", end="")
+
+ def process_custom_node(item):
+ core.check_state_of_git_node_pack_single(item, do_fetch, do_update_check, do_update)
+
+ with concurrent.futures.ThreadPoolExecutor(4) as executor:
+ for k, v in node_packs.items():
+ if v.get('active_version') in ['unknown', 'nightly']:
+ executor.submit(process_custom_node, v)
+
+ if do_fetch:
+ print("\x1b[2K\rFetching done.")
+ elif do_update:
+ update_exists = any(item.get('updatable', False) for item in node_packs.values())
+ if update_exists:
+ print("\x1b[2K\rUpdate done.")
+ else:
+ print("\x1b[2K\rAll extensions are already up-to-date.")
+ elif do_update_check:
+ print("\x1b[2K\rUpdate check done.")
+
+
+def nickname_filter(json_obj):
+ preemptions_map = {}
+
+ for k, x in json_obj.items():
+ if 'preemptions' in x[1]:
+ for y in x[1]['preemptions']:
+ preemptions_map[y] = k
+ elif k.endswith("/ComfyUI"):
+ for y in x[0]:
+ preemptions_map[y] = k
+
+ updates = {}
+ for k, x in json_obj.items():
+ removes = set()
+ for y in x[0]:
+ k2 = preemptions_map.get(y)
+ if k2 is not None and k != k2:
+ removes.add(y)
+
+ if len(removes) > 0:
+ updates[k] = [y for y in x[0] if y not in removes]
+
+ for k, v in updates.items():
+ json_obj[k][0] = v
+
+ return json_obj
+
+
+class TaskBatch:
+ def __init__(self, batch_json, tasks, failed):
+ self.nodepack_result = {}
+ self.model_result = {}
+ self.batch_id = batch_json.get('batch_id') if batch_json is not None else None
+ self.batch_json = batch_json
+ self.tasks = tasks
+ self.current_index = 0
+ self.stats = {}
+ self.failed = failed if failed is not None else set()
+ self.is_aborted = False
+
+ def is_done(self):
+ return len(self.tasks) <= self.current_index
+
+ def get_next(self):
+ if self.is_done():
+ return None
+
+ item = self.tasks[self.current_index]
+ self.current_index += 1
+ return item
+
+ def done_count(self):
+ return len(self.nodepack_result) + len(self.model_result)
+
+ def total_count(self):
+ return len(self.tasks)
+
+ def abort(self):
+ self.is_aborted = True
+
+ def finalize(self):
+ if self.batch_id is not None:
+ batch_path = os.path.join(context.manager_batch_history_path, self.batch_id+".json")
+ json_obj = {
+ "batch": self.batch_json,
+ "nodepack_result": self.nodepack_result,
+ "model_result": self.model_result,
+ "failed": list(self.failed)
+ }
+ with open(batch_path, "w") as json_file:
+ json.dump(json_obj, json_file, indent=4)
+
+
+temp_queue_batch = []
+task_batch_queue = deque()
+tasks_in_progress = set()
+task_worker_lock = threading.Lock()
+aborted_batch = None
+
+
+def finalize_temp_queue_batch(batch_json=None, failed=None):
+ """
+ make temp_queue_batch as a batch snapshot and add to batch_queue
+ """
+
+ global temp_queue_batch
+
+ if len(temp_queue_batch):
+ batch = TaskBatch(batch_json, temp_queue_batch, failed)
+ task_batch_queue.append(batch)
+ temp_queue_batch = []
+
+
+async def task_worker():
+ global task_queue
+ global tasks_in_progress
+
+ async def do_install(item) -> str:
+ ui_id, node_spec_str, channel, mode, skip_post_install = item
+
+ try:
+ node_spec = core.unified_manager.resolve_node_spec(node_spec_str)
+ if node_spec is None:
+ logging.error(f"Cannot resolve install target: '{node_spec_str}'")
+ return f"Cannot resolve install target: '{node_spec_str}'"
+
+ node_name, version_spec, is_specified = node_spec
+ res = await core.unified_manager.install_by_id(node_name, version_spec, channel, mode, return_postinstall=skip_post_install) # discard post install if skip_post_install mode
+
+ if res.action not in ['skip', 'enable', 'install-git', 'install-cnr', 'switch-cnr']:
+ logging.error(f"[ComfyUI-Manager] Installation failed:\n{res.msg}")
+ return res.msg
+
+ elif not res.result:
+ logging.error(f"[ComfyUI-Manager] Installation failed:\n{res.msg}")
+ return res.msg
+
+ return 'success'
+ except Exception:
+ traceback.print_exc()
+ return f"Installation failed:\n{node_spec_str}"
+
+ async def do_enable(item) -> str:
+ ui_id, cnr_id = item
+ core.unified_manager.unified_enable(cnr_id)
+ return 'success'
+
+ async def do_update(item):
+ ui_id, node_name, node_ver = item
+
+ try:
+ res = core.unified_manager.unified_update(node_name, node_ver)
+
+ if res.ver == 'unknown':
+ url = core.unified_manager.unknown_active_nodes[node_name][0]
+ title = os.path.basename(url)
+ else:
+ url = core.unified_manager.cnr_map[node_name].get('repository')
+ title = core.unified_manager.cnr_map[node_name]['name']
+
+ manager_util.clear_pip_cache()
+
+ if url is not None:
+ base_res = {'url': url, 'title': title}
+ else:
+ base_res = {'title': title}
+
+ if res.result:
+ if res.action == 'skip':
+ base_res['msg'] = 'skip'
+ return base_res
+ else:
+ base_res['msg'] = 'success'
+ return base_res
+
+ base_res['msg'] = f"An error occurred while updating '{node_name}'."
+ logging.error(f"\nERROR: An error occurred while updating '{node_name}'. (res.result={res.result}, res.action={res.action})")
+ return base_res
+ except Exception:
+ traceback.print_exc()
+
+ return {'msg':f"An error occurred while updating '{node_name}'."}
+
+ async def do_update_comfyui(is_stable) -> str:
+ try:
+ repo_path = os.path.dirname(folder_paths.__file__)
+ latest_tag = None
+ if is_stable:
+ res, latest_tag = core.update_to_stable_comfyui(repo_path)
+ else:
+ res = core.update_path(repo_path)
+
+ if res == "fail":
+ logging.error("ComfyUI update failed")
+ return "fail"
+ elif res == "updated":
+ if is_stable:
+ logging.info("ComfyUI is updated to latest stable version.")
+ return "success-stable-"+latest_tag
+ else:
+ logging.info("ComfyUI is updated to latest nightly version.")
+ return "success-nightly"
+ else: # skipped
+ logging.info("ComfyUI is up-to-date.")
+ return "skip"
+
+ except Exception:
+ traceback.print_exc()
+
+ return "An error occurred while updating 'comfyui'."
+
+ async def do_fix(item) -> str:
+ ui_id, node_name, node_ver = item
+
+ try:
+ res = core.unified_manager.unified_fix(node_name, node_ver)
+
+ if res.result:
+ return 'success'
+ else:
+ logging.error(res.msg)
+
+ logging.error(f"\nERROR: An error occurred while fixing '{node_name}@{node_ver}'.")
+ except Exception:
+ traceback.print_exc()
+
+ return f"An error occurred while fixing '{node_name}@{node_ver}'."
+
+ async def do_uninstall(item) -> str:
+ ui_id, node_name, is_unknown = item
+
+ try:
+ res = core.unified_manager.unified_uninstall(node_name, is_unknown)
+
+ if res.result:
+ return 'success'
+
+ logging.error(f"\nERROR: An error occurred while uninstalling '{node_name}'.")
+ except Exception:
+ traceback.print_exc()
+
+ return f"An error occurred while uninstalling '{node_name}'."
+
+ async def do_disable(item) -> str:
+ ui_id, node_name, is_unknown = item
+
+ try:
+ res = core.unified_manager.unified_disable(node_name, is_unknown)
+
+ if res:
+ return 'success'
+
+ except Exception:
+ traceback.print_exc()
+
+ return f"Failed to disable: '{node_name}'"
+
+ async def do_install_model(item) -> str:
+ ui_id, json_data = item
+
+ model_path = get_model_path(json_data)
+ model_url = json_data['url']
+
+ res = False
+
+ try:
+ if model_path is not None:
+ logging.info(f"Install model '{json_data['name']}' from '{model_url}' into '{model_path}'")
+
+ if json_data['filename'] == '':
+ if os.path.exists(os.path.join(model_path, os.path.dirname(json_data['url']))):
+ logging.error(f"[ComfyUI-Manager] the model path already exists: {model_path}")
+ return f"The model path already exists: {model_path}"
+
+ logging.info(f"[ComfyUI-Manager] Downloading '{model_url}' into '{model_path}'")
+ manager_downloader.download_repo_in_bytes(repo_id=model_url, local_dir=model_path)
+
+ return 'success'
+
+ elif not core.get_config()['model_download_by_agent'] and (
+ model_url.startswith('https://github.com') or model_url.startswith('https://huggingface.co') or model_url.startswith('https://heibox.uni-heidelberg.de')):
+ model_dir = get_model_dir(json_data, True)
+ download_url(model_url, model_dir, filename=json_data['filename'])
+ if model_path.endswith('.zip'):
+ res = core.unzip(model_path)
+ else:
+ res = True
+
+ if res:
+ return 'success'
+ else:
+ res = download_url_with_agent(model_url, model_path)
+ if res and model_path.endswith('.zip'):
+ res = core.unzip(model_path)
+ else:
+ logging.error(f"[ComfyUI-Manager] Model installation error: invalid model type - {json_data['type']}")
+
+ if res:
+ return 'success'
+
+ except Exception as e:
+ logging.error(f"[ComfyUI-Manager] ERROR: {e}", file=sys.stderr)
+
+ return f"Model installation error: {model_url}"
+
+ while True:
+ with task_worker_lock:
+ if len(task_batch_queue) > 0:
+ cur_batch = task_batch_queue[0]
+ else:
+ logging.info("\n[ComfyUI-Manager] All tasks are completed.")
+ logging.info("\nAfter restarting ComfyUI, please refresh the browser.")
+
+ res = {'status': 'all-done'}
+
+ PromptServer.instance.send_sync("cm-queue-status", res)
+
+ return
+
+ if cur_batch.is_done():
+ logging.info(f"\n[ComfyUI-Manager] A tasks batch(batch_id={cur_batch.batch_id}) is completed.\nstat={cur_batch.stats}")
+
+ res = {'status': 'batch-done',
+ 'nodepack_result': cur_batch.nodepack_result,
+ 'model_result': cur_batch.model_result,
+ 'total_count': cur_batch.total_count(),
+ 'done_count': cur_batch.done_count(),
+ 'batch_id': cur_batch.batch_id,
+ 'remaining_batch_count': len(task_batch_queue) }
+
+ PromptServer.instance.send_sync("cm-queue-status", res)
+ cur_batch.finalize()
+ task_batch_queue.popleft()
+ continue
+
+ with task_worker_lock:
+ kind, item = cur_batch.get_next()
+ tasks_in_progress.add((kind, item[0]))
+
+ try:
+ if kind == 'install':
+ msg = await do_install(item)
+ elif kind == 'enable':
+ msg = await do_enable(item)
+ elif kind == 'install-model':
+ msg = await do_install_model(item)
+ elif kind == 'update':
+ msg = await do_update(item)
+ elif kind == 'update-main':
+ msg = await do_update(item)
+ elif kind == 'update-comfyui':
+ msg = await do_update_comfyui(item[1])
+ elif kind == 'fix':
+ msg = await do_fix(item)
+ elif kind == 'uninstall':
+ msg = await do_uninstall(item)
+ elif kind == 'disable':
+ msg = await do_disable(item)
+ else:
+ msg = "Unexpected kind: " + kind
+ except Exception:
+ traceback.print_exc()
+ msg = f"Exception: {(kind, item)}"
+
+ with task_worker_lock:
+ tasks_in_progress.remove((kind, item[0]))
+
+ ui_id = item[0]
+ if kind == 'install-model':
+ cur_batch.model_result[ui_id] = msg
+ ui_target = "model_manager"
+ elif kind == 'update-main':
+ cur_batch.nodepack_result[ui_id] = msg
+ ui_target = "main"
+ elif kind == 'update-comfyui':
+ cur_batch.nodepack_result['comfyui'] = msg
+ ui_target = "main"
+ elif kind == 'update':
+ cur_batch.nodepack_result[ui_id] = msg['msg']
+ ui_target = "nodepack_manager"
+ else:
+ cur_batch.nodepack_result[ui_id] = msg
+ ui_target = "nodepack_manager"
+
+ cur_batch.stats[kind] = cur_batch.stats.get(kind, 0) + 1
+
+ PromptServer.instance.send_sync("cm-queue-status",
+ {'status': 'in_progress',
+ 'target': item[0],
+ 'batch_id': cur_batch.batch_id,
+ 'ui_target': ui_target,
+ 'total_count': cur_batch.total_count(),
+ 'done_count': cur_batch.done_count()})
+
+
+@routes.post("/v2/manager/queue/batch")
+async def queue_batch(request):
+ json_data = await request.json()
+
+ failed = set()
+
+ for k, v in json_data.items():
+ if k == 'update_all':
+ await _update_all({'mode': v})
+
+ elif k == 'reinstall':
+ for x in v:
+ res = await _uninstall_custom_node(x)
+ if res.status != 200:
+ failed.add(x[0])
+ else:
+ res = await _install_custom_node(x)
+ if res.status != 200:
+ failed.add(x[0])
+
+ elif k == 'install':
+ for x in v:
+ res = await _install_custom_node(x)
+ if res.status != 200:
+ failed.add(x[0])
+
+ elif k == 'uninstall':
+ for x in v:
+ res = await _uninstall_custom_node(x)
+ if res.status != 200:
+ failed.add(x[0])
+
+ elif k == 'update':
+ for x in v:
+ res = await _update_custom_node(x)
+ if res.status != 200:
+ failed.add(x[0])
+
+ elif k == 'update_comfyui':
+ await update_comfyui(None)
+
+ elif k == 'disable':
+ for x in v:
+ await _disable_node(x)
+
+ elif k == 'install_model':
+ for x in v:
+ res = await _install_model(x)
+ if res.status != 200:
+ failed.add(x[0])
+
+ elif k == 'fix':
+ for x in v:
+ res = await _fix_custom_node(x)
+ if res.status != 200:
+ failed.add(x[0])
+
+ with task_worker_lock:
+ finalize_temp_queue_batch(json_data, failed)
+ _queue_start()
+
+ return web.json_response({"failed": list(failed)}, content_type='application/json')
+
+
+@routes.get("/v2/manager/queue/history_list")
+async def get_history_list(request):
+ history_path = context.manager_batch_history_path
+
+ try:
+ files = [os.path.join(history_path, f) for f in os.listdir(history_path) if os.path.isfile(os.path.join(history_path, f))]
+ files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
+ history_ids = [os.path.basename(f)[:-5] for f in files]
+
+ return web.json_response({"ids": list(history_ids)}, content_type='application/json')
+ except Exception as e:
+ logging.error(f"[ComfyUI-Manager] /v2/manager/queue/history_list - {e}")
+ return web.Response(status=400)
+
+
+@routes.get("/v2/manager/queue/history")
+async def get_history(request):
+ try:
+ json_name = request.rel_url.query["id"]+'.json'
+ batch_path = os.path.join(context.manager_batch_history_path, json_name)
+
+ with open(batch_path, 'r', encoding='utf-8') as file:
+ json_str = file.read()
+ json_obj = json.loads(json_str)
+ return web.json_response(json_obj, content_type='application/json')
+
+ except Exception as e:
+ logging.error(f"[ComfyUI-Manager] /v2/manager/queue/history - {e}")
+
+ return web.Response(status=400)
+
+
+@routes.get("/v2/customnode/getmappings")
+async def fetch_customnode_mappings(request):
+ """
+ provide unified (node -> node pack) mapping list
+ """
+ mode = request.rel_url.query["mode"]
+
+ nickname_mode = False
+ if mode == "nickname":
+ mode = "local"
+ nickname_mode = True
+
+ json_obj = await core.get_data_by_mode(mode, 'extension-node-map.json')
+ json_obj = core.map_to_unified_keys(json_obj)
+
+ if nickname_mode:
+ json_obj = nickname_filter(json_obj)
+
+ all_nodes = set()
+ patterns = []
+ for k, x in json_obj.items():
+ all_nodes.update(set(x[0]))
+
+ if 'nodename_pattern' in x[1]:
+ patterns.append((x[1]['nodename_pattern'], x[0]))
+
+ missing_nodes = set(nodes.NODE_CLASS_MAPPINGS.keys()) - all_nodes
+
+ for x in missing_nodes:
+ for pat, item in patterns:
+ if re.match(pat, x):
+ item.append(x)
+
+ return web.json_response(json_obj, content_type='application/json')
+
+
+@routes.get("/v2/customnode/fetch_updates")
+async def fetch_updates(request):
+ try:
+ if request.rel_url.query["mode"] == "local":
+ channel = 'local'
+ else:
+ channel = core.get_config()['channel_url']
+
+ await core.unified_manager.reload(request.rel_url.query["mode"])
+ await core.unified_manager.get_custom_nodes(channel, request.rel_url.query["mode"])
+
+ res = core.unified_manager.fetch_or_pull_git_repo(is_pull=False)
+
+ for x in res['failed']:
+ logging.error(f"FETCH FAILED: {x}")
+
+ logging.info("\nDone.")
+
+ if len(res['updated']) > 0:
+ return web.Response(status=201)
+
+ return web.Response(status=200)
+ except:
+ traceback.print_exc()
+ return web.Response(status=400)
+
+
+@routes.get("/v2/manager/queue/update_all")
+async def update_all(request):
+ json_data = dict(request.rel_url.query)
+ return await _update_all(json_data)
+
+
+async def _update_all(json_data):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403)
+
+ with task_worker_lock:
+ is_processing = task_worker_thread is not None and task_worker_thread.is_alive()
+ if is_processing:
+ return web.Response(status=401)
+
+ await core.save_snapshot_with_postfix('autosave')
+
+ if json_data["mode"] == "local":
+ channel = 'local'
+ else:
+ channel = core.get_config()['channel_url']
+
+ await core.unified_manager.reload(json_data["mode"])
+ await core.unified_manager.get_custom_nodes(channel, json_data["mode"])
+
+ for k, v in core.unified_manager.active_nodes.items():
+ if k == 'comfyui-manager':
+ # skip updating comfyui-manager if desktop version
+ if os.environ.get('__COMFYUI_DESKTOP_VERSION__'):
+ continue
+
+ update_item = k, k, v[0]
+ temp_queue_batch.append(("update-main", update_item))
+
+ for k, v in core.unified_manager.unknown_active_nodes.items():
+ if k == 'comfyui-manager':
+ # skip updating comfyui-manager if desktop version
+ if os.environ.get('__COMFYUI_DESKTOP_VERSION__'):
+ continue
+
+ update_item = k, k, 'unknown'
+ temp_queue_batch.append(("update-main", update_item))
+
+ return web.Response(status=200)
+
+
+def convert_markdown_to_html(input_text):
+ pattern_a = re.compile(r'\[a/([^]]+)]\(([^)]+)\)')
+ pattern_w = re.compile(r'\[w/([^]]+)]')
+ pattern_i = re.compile(r'\[i/([^]]+)]')
+ pattern_bold = re.compile(r'\*\*([^*]+)\*\*')
+ pattern_white = re.compile(r'%%([^*]+)%%')
+
+ def replace_a(match):
+ return f"{match.group(1)}"
+
+ def replace_w(match):
+ return f"{match.group(1)}
"
+
+ def replace_i(match):
+ return f"{match.group(1)}
"
+
+ def replace_bold(match):
+ return f"{match.group(1)}"
+
+ def replace_white(match):
+ return f"{match.group(1)}"
+
+ input_text = input_text.replace('\\[', '[').replace('\\]', ']').replace('<', '<').replace('>', '>')
+
+ result_text = re.sub(pattern_a, replace_a, input_text)
+ result_text = re.sub(pattern_w, replace_w, result_text)
+ result_text = re.sub(pattern_i, replace_i, result_text)
+ result_text = re.sub(pattern_bold, replace_bold, result_text)
+ result_text = re.sub(pattern_white, replace_white, result_text)
+
+ return result_text.replace("\n", "
")
+
+
+def populate_markdown(x):
+ if 'description' in x:
+ x['description'] = convert_markdown_to_html(manager_util.sanitize_tag(x['description']))
+
+ if 'name' in x:
+ x['name'] = manager_util.sanitize_tag(x['name'])
+
+ if 'title' in x:
+ x['title'] = manager_util.sanitize_tag(x['title'])
+
+
+# freeze imported version
+startup_time_installed_node_packs = core.get_installed_node_packs()
+@routes.get("/v2/customnode/installed")
+async def installed_list(request):
+ mode = request.query.get('mode', 'default')
+
+ if mode == 'imported':
+ res = startup_time_installed_node_packs
+ else:
+ res = core.get_installed_node_packs()
+
+ return web.json_response(res, content_type='application/json')
+
+
+@routes.get("/v2/customnode/getlist")
+async def fetch_customnode_list(request):
+ """
+ provide unified custom node list
+ """
+ if request.rel_url.query.get("skip_update", '').lower() == "true":
+ skip_update = True
+ else:
+ skip_update = False
+
+ if request.rel_url.query["mode"] == "local":
+ channel = 'local'
+ else:
+ channel = core.get_config()['channel_url']
+
+ node_packs = await core.get_unified_total_nodes(channel, request.rel_url.query["mode"], 'cache')
+ json_obj_github = core.get_data_by_mode(request.rel_url.query["mode"], 'github-stats.json', 'default')
+ json_obj_extras = core.get_data_by_mode(request.rel_url.query["mode"], 'extras.json', 'default')
+
+ core.populate_github_stats(node_packs, await json_obj_github)
+ core.populate_favorites(node_packs, await json_obj_extras)
+
+ check_state_of_git_node_pack(node_packs, not skip_update, do_update_check=not skip_update)
+
+ for v in node_packs.values():
+ populate_markdown(v)
+
+ if channel != 'local':
+ found = 'custom'
+
+ for name, url in core.get_channel_dict().items():
+ if url == channel:
+ found = name
+ break
+
+ channel = found
+
+ result = dict(channel=channel, node_packs=node_packs)
+
+ return web.json_response(result, content_type='application/json')
+
+
+@routes.get("/customnode/alternatives")
+async def fetch_customnode_alternatives(request):
+ alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
+
+ res = {}
+
+ for item in alter_json['items']:
+ populate_markdown(item)
+ res[item['id']] = item
+
+ res = core.map_to_unified_keys(res)
+
+ return web.json_response(res, content_type='application/json')
+
+
+def check_model_installed(json_obj):
+ def is_exists(model_dir_name, filename, url):
+ if filename == '':
+ filename = os.path.basename(url)
+
+ dirs = folder_paths.get_folder_paths(model_dir_name)
+
+ for x in dirs:
+ if os.path.exists(os.path.join(x, filename)):
+ return True
+
+ return False
+
+ model_dir_names = ['checkpoints', 'loras', 'vae', 'text_encoders', 'diffusion_models', 'clip_vision', 'embeddings',
+ 'diffusers', 'vae_approx', 'controlnet', 'gligen', 'upscale_models', 'hypernetworks',
+ 'photomaker', 'classifiers']
+
+ total_models_files = set()
+ for x in model_dir_names:
+ for y in folder_paths.get_filename_list(x):
+ total_models_files.add(y)
+
+ def process_model_phase(item):
+ if 'diffusion' not in item['filename'] and 'pytorch' not in item['filename'] and 'model' not in item['filename']:
+ # non-general name case
+ if item['filename'] in total_models_files:
+ item['installed'] = 'True'
+ return
+
+ if item['save_path'] == 'default':
+ model_dir_name = model_dir_name_map.get(item['type'].lower())
+ if model_dir_name is not None:
+ item['installed'] = str(is_exists(model_dir_name, item['filename'], item['url']))
+ else:
+ item['installed'] = 'False'
+ else:
+ model_dir_name = item['save_path'].split('/')[0]
+ if model_dir_name in folder_paths.folder_names_and_paths:
+ if is_exists(model_dir_name, item['filename'], item['url']):
+ item['installed'] = 'True'
+
+ if 'installed' not in item:
+ if item['filename'] == '':
+ filename = os.path.basename(item['url'])
+ else:
+ filename = item['filename']
+
+ fullpath = os.path.join(folder_paths.models_dir, item['save_path'], filename)
+
+ item['installed'] = 'True' if os.path.exists(fullpath) else 'False'
+
+ with concurrent.futures.ThreadPoolExecutor(8) as executor:
+ for item in json_obj['models']:
+ executor.submit(process_model_phase, item)
+
+
+@routes.get("/v2/externalmodel/getlist")
+async def fetch_externalmodel_list(request):
+ # The model list is only allowed in the default channel, yet.
+ json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'model-list.json')
+
+ check_model_installed(json_obj)
+
+ for x in json_obj['models']:
+ populate_markdown(x)
+
+ return web.json_response(json_obj, content_type='application/json')
+
+
+@PromptServer.instance.routes.get("/v2/snapshot/getlist")
+async def get_snapshot_list(request):
+ items = [f[:-5] for f in os.listdir(context.manager_snapshot_path) if f.endswith('.json')]
+ items.sort(reverse=True)
+ return web.json_response({'items': items}, content_type='application/json')
+
+
+@routes.get("/v2/snapshot/remove")
+async def remove_snapshot(request):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403)
+
+ try:
+ target = request.rel_url.query["target"]
+
+ path = os.path.join(context.manager_snapshot_path, f"{target}.json")
+ if os.path.exists(path):
+ os.remove(path)
+
+ return web.Response(status=200)
+ except:
+ return web.Response(status=400)
+
+
+@routes.get("/v2/snapshot/restore")
+async def restore_snapshot(request):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403)
+
+ try:
+ target = request.rel_url.query["target"]
+
+ path = os.path.join(context.manager_snapshot_path, f"{target}.json")
+ if os.path.exists(path):
+ if not os.path.exists(context.manager_startup_script_path):
+ os.makedirs(context.manager_startup_script_path)
+
+ target_path = os.path.join(context.manager_startup_script_path, "restore-snapshot.json")
+ shutil.copy(path, target_path)
+
+ logging.info(f"Snapshot restore scheduled: `{target}`")
+ return web.Response(status=200)
+
+ logging.error(f"Snapshot file not found: `{path}`")
+ return web.Response(status=400)
+ except:
+ return web.Response(status=400)
+
+
+@routes.get("/v2/snapshot/get_current")
+async def get_current_snapshot_api(request):
+ try:
+ return web.json_response(await core.get_current_snapshot(), content_type='application/json')
+ except:
+ return web.Response(status=400)
+
+
+@routes.get("/v2/snapshot/save")
+async def save_snapshot(request):
+ try:
+ await core.save_snapshot_with_postfix('snapshot')
+ return web.Response(status=200)
+ except:
+ return web.Response(status=400)
+
+
+def unzip_install(files):
+ temp_filename = 'manager-temp.zip'
+ for url in files:
+ if url.endswith("/"):
+ url = url[:-1]
+ try:
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
+
+ req = urllib.request.Request(url, headers=headers)
+ response = urllib.request.urlopen(req)
+ data = response.read()
+
+ with open(temp_filename, 'wb') as f:
+ f.write(data)
+
+ with zipfile.ZipFile(temp_filename, 'r') as zip_ref:
+ zip_ref.extractall(core.get_default_custom_nodes_path())
+
+ os.remove(temp_filename)
+ except Exception as e:
+ logging.error(f"Install(unzip) error: {url} / {e}", file=sys.stderr)
+ return False
+
+ logging.info("Installation was successful.")
+ return True
+
+
+@routes.get("/v2/customnode/versions/{node_name}")
+async def get_cnr_versions(request):
+ node_name = request.match_info.get("node_name", None)
+ versions = core.cnr_utils.all_versions_of_node(node_name)
+
+ if versions is not None:
+ return web.json_response(versions, content_type='application/json')
+
+ return web.Response(status=400)
+
+
+@routes.get("/v2/customnode/disabled_versions/{node_name}")
+async def get_disabled_versions(request):
+ node_name = request.match_info.get("node_name", None)
+ versions = []
+ if node_name in core.unified_manager.nightly_inactive_nodes:
+ versions.append(dict(version='nightly'))
+
+ for v in core.unified_manager.cnr_inactive_nodes.get(node_name, {}).keys():
+ versions.append(dict(version=v))
+
+ if versions:
+ return web.json_response(versions, content_type='application/json')
+
+ return web.Response(status=400)
+
+
+@routes.post("/v2/customnode/import_fail_info")
+async def import_fail_info(request):
+ json_data = await request.json()
+
+ if 'cnr_id' in json_data:
+ module_name = core.unified_manager.get_module_name(json_data['cnr_id'])
+ else:
+ module_name = core.unified_manager.get_module_name(json_data['url'])
+
+ if module_name is not None:
+ info = cm_global.error_dict.get(module_name)
+ if info is not None:
+ return web.json_response(info)
+
+ return web.Response(status=400)
+
+
+@routes.post("/v2/manager/queue/reinstall")
+async def reinstall_custom_node(request):
+ await uninstall_custom_node(request)
+ await install_custom_node(request)
+
+
+@routes.get("/v2/manager/queue/reset")
+async def reset_queue(request):
+ global task_batch_queue
+ global temp_queue_batch
+
+ with task_worker_lock:
+ temp_queue_batch = []
+ task_batch_queue = deque()
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/queue/abort_current")
+async def abort_queue(request):
+ global task_batch_queue
+ global temp_queue_batch
+
+ with task_worker_lock:
+ temp_queue_batch = []
+ if len(task_batch_queue) > 0:
+ task_batch_queue[0].abort()
+ task_batch_queue.popleft()
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/queue/status")
+async def queue_count(request):
+ global task_queue
+
+ with task_worker_lock:
+ if len(task_batch_queue) > 0:
+ cur_batch = task_batch_queue[0]
+ done_count = cur_batch.done_count()
+ total_count = cur_batch.total_count()
+ in_progress_count = len(tasks_in_progress)
+ is_processing = task_worker_thread is not None and task_worker_thread.is_alive()
+ else:
+ done_count = 0
+ total_count = 0
+ in_progress_count = 0
+ is_processing = False
+
+ return web.json_response({
+ 'total_count': total_count,
+ 'done_count': done_count,
+ 'in_progress_count': in_progress_count,
+ 'is_processing': is_processing})
+
+
+@routes.post("/v2/manager/queue/install")
+async def install_custom_node(request):
+ json_data = await request.json()
+ print(f"install={json_data}")
+ return await _install_custom_node(json_data)
+
+
+async def _install_custom_node(json_data):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
+
+ # non-nightly cnr is safe
+ risky_level = None
+ cnr_id = json_data.get('id')
+ skip_post_install = json_data.get('skip_post_install')
+
+ git_url = None
+
+ selected_version = json_data.get('selected_version')
+ if json_data['version'] != 'unknown' and selected_version != 'unknown':
+ if skip_post_install:
+ if cnr_id in core.unified_manager.nightly_inactive_nodes or cnr_id in core.unified_manager.cnr_inactive_nodes:
+ enable_item = json_data.get('ui_id'), cnr_id
+ temp_queue_batch.append(("enable", enable_item))
+ return web.Response(status=200)
+
+ elif selected_version is None:
+ selected_version = 'latest'
+
+ if selected_version != 'nightly':
+ risky_level = 'low'
+ node_spec_str = f"{cnr_id}@{selected_version}"
+ else:
+ node_spec_str = f"{cnr_id}@nightly"
+ git_url = [json_data.get('repository')]
+ if git_url is None:
+ logging.error(f"[ComfyUI-Manager] Following node pack doesn't provide `nightly` version: ${git_url}")
+ return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
+
+ elif json_data['version'] != 'unknown' and selected_version == 'unknown':
+ logging.error(f"[ComfyUI-Manager] Invalid installation request: {json_data}")
+ return web.Response(status=400, text="Invalid installation request")
+
+ else:
+ # unknown
+ unknown_name = os.path.basename(json_data['files'][0])
+ node_spec_str = f"{unknown_name}@unknown"
+ git_url = json_data.get('files')
+
+ # apply security policy if not cnr node (nightly isn't regarded as cnr node)
+ if risky_level is None:
+ if git_url is not None:
+ risky_level = await get_risky_level(git_url, json_data.get('pip', []))
+ else:
+ return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
+
+ if not is_allowed_security_level(risky_level):
+ logging.error(SECURITY_MESSAGE_GENERAL)
+ return web.Response(status=404, text="A security error has occurred. Please check the terminal logs")
+
+ install_item = json_data.get('ui_id'), node_spec_str, json_data['channel'], json_data['mode'], skip_post_install
+ temp_queue_batch.append(("install", install_item))
+
+ return web.Response(status=200)
+
+
+task_worker_thread:threading.Thread = None
+
+@routes.get("/v2/manager/queue/start")
+async def queue_start(request):
+ with task_worker_lock:
+ finalize_temp_queue_batch()
+ return _queue_start()
+
+def _queue_start():
+ global task_worker_thread
+
+ if task_worker_thread is not None and task_worker_thread.is_alive():
+ return web.Response(status=201) # already in-progress
+
+ task_worker_thread = threading.Thread(target=lambda: asyncio.run(task_worker()))
+ task_worker_thread.start()
+
+ return web.Response(status=200)
+
+
+@routes.post("/v2/manager/queue/fix")
+async def fix_custom_node(request):
+ json_data = await request.json()
+ return await _fix_custom_node(json_data)
+
+
+async def _fix_custom_node(json_data):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_GENERAL)
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
+
+ node_id = json_data.get('id')
+ node_ver = json_data['version']
+ if node_ver != 'unknown':
+ node_name = node_id
+ else:
+ # unknown
+ node_name = os.path.basename(json_data['files'][0])
+
+ update_item = json_data.get('ui_id'), node_name, json_data['version']
+ temp_queue_batch.append(("fix", update_item))
+
+ return web.Response(status=200)
+
+
+@routes.post("/v2/customnode/install/git_url")
+async def install_custom_node_git_url(request):
+ if not is_allowed_security_level('high'):
+ logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
+ return web.Response(status=403)
+
+ url = await request.text()
+ res = await core.gitclone_install(url)
+
+ if res.action == 'skip':
+ logging.info(f"\nAlready installed: '{res.target}'")
+ return web.Response(status=200)
+ elif res.result:
+ logging.info("\nAfter restarting ComfyUI, please refresh the browser.")
+ return web.Response(status=200)
+
+ logging.error(res.msg)
+ return web.Response(status=400)
+
+
+@routes.post("/v2/customnode/install/pip")
+async def install_custom_node_pip(request):
+ if not is_allowed_security_level('high'):
+ logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
+ return web.Response(status=403)
+
+ packages = await request.text()
+ core.pip_install(packages.split(' '))
+
+ return web.Response(status=200)
+
+
+@routes.post("/v2/manager/queue/uninstall")
+async def uninstall_custom_node(request):
+ json_data = await request.json()
+ return await _uninstall_custom_node(json_data)
+
+
+async def _uninstall_custom_node(json_data):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
+
+ node_id = json_data.get('id')
+ if json_data['version'] != 'unknown':
+ is_unknown = False
+ node_name = node_id
+ else:
+ # unknown
+ is_unknown = True
+ node_name = os.path.basename(json_data['files'][0])
+
+ uninstall_item = json_data.get('ui_id'), node_name, is_unknown
+ temp_queue_batch.append(("uninstall", uninstall_item))
+
+ return web.Response(status=200)
+
+
+@routes.post("/v2/manager/queue/update")
+async def update_custom_node(request):
+ json_data = await request.json()
+ return await _update_custom_node(json_data)
+
+
+async def _update_custom_node(json_data):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
+
+ node_id = json_data.get('id')
+ if json_data['version'] != 'unknown':
+ node_name = node_id
+ else:
+ # unknown
+ node_name = os.path.basename(json_data['files'][0])
+
+ update_item = json_data.get('ui_id'), node_name, json_data['version']
+ temp_queue_batch.append(("update", update_item))
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/queue/update_comfyui")
+async def update_comfyui(request):
+ is_stable = core.get_config()['update_policy'] != 'nightly-comfyui'
+ temp_queue_batch.append(("update-comfyui", ('comfyui', is_stable)))
+ return web.Response(status=200)
+
+
+@routes.get("/v2/comfyui_manager/comfyui_versions")
+async def comfyui_versions(request):
+ try:
+ res, current, latest = core.get_comfyui_versions()
+ return web.json_response({'versions': res, 'current': current}, status=200, content_type='application/json')
+ except Exception as e:
+ logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
+
+ return web.Response(status=400)
+
+
+@routes.get("/v2/comfyui_manager/comfyui_switch_version")
+async def comfyui_switch_version(request):
+ try:
+ if "ver" in request.rel_url.query:
+ core.switch_comfyui(request.rel_url.query['ver'])
+
+ return web.Response(status=200)
+ except Exception as e:
+ logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
+
+ return web.Response(status=400)
+
+
+@routes.post("/v2/manager/queue/disable")
+async def disable_node(request):
+ json_data = await request.json()
+ await _disable_node(json_data)
+ return web.Response(status=200)
+
+
+async def _disable_node(json_data):
+ node_id = json_data.get('id')
+ if json_data['version'] != 'unknown':
+ is_unknown = False
+ node_name = node_id
+ else:
+ # unknown
+ is_unknown = True
+ node_name = os.path.basename(json_data['files'][0])
+
+ update_item = json_data.get('ui_id'), node_name, is_unknown
+ temp_queue_batch.append(("disable", update_item))
+
+
+async def check_whitelist_for_model(item):
+ json_obj = await core.get_data_by_mode('cache', 'model-list.json')
+
+ for x in json_obj.get('models', []):
+ if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename']:
+ return True
+
+ json_obj = await core.get_data_by_mode('local', 'model-list.json')
+
+ for x in json_obj.get('models', []):
+ if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename']:
+ return True
+
+ return False
+
+
+@routes.post("/v2/manager/queue/install_model")
+async def install_model(request):
+ json_data = await request.json()
+ return await _install_model(json_data)
+
+
+async def _install_model(json_data):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
+
+ # validate request
+ if not await check_whitelist_for_model(json_data):
+ logging.error(f"[ComfyUI-Manager] Invalid model install request is detected: {json_data}")
+ return web.Response(status=400, text="Invalid model install request is detected")
+
+ if not json_data['filename'].endswith('.safetensors') and not is_allowed_security_level('high'):
+ models_json = await core.get_data_by_mode('cache', 'model-list.json', 'default')
+
+ is_belongs_to_whitelist = False
+ for x in models_json['models']:
+ if x.get('url') == json_data['url']:
+ is_belongs_to_whitelist = True
+ break
+
+ if not is_belongs_to_whitelist:
+ logging.error(SECURITY_MESSAGE_NORMAL_MINUS_MODEL)
+ return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
+
+ install_item = json_data.get('ui_id'), json_data
+ temp_queue_batch.append(("install-model", install_item))
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/preview_method")
+async def preview_method(request):
+ if "value" in request.rel_url.query:
+ set_preview_method(request.rel_url.query['value'])
+ core.write_config()
+ else:
+ return web.Response(text=core.manager_funcs.get_current_preview_method(), status=200)
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/db_mode")
+async def db_mode(request):
+ if "value" in request.rel_url.query:
+ set_db_mode(request.rel_url.query['value'])
+ core.write_config()
+ else:
+ return web.Response(text=core.get_config()['db_mode'], status=200)
+
+ return web.Response(status=200)
+
+
+
+@routes.get("/v2/manager/policy/component")
+async def component_policy(request):
+ if "value" in request.rel_url.query:
+ set_component_policy(request.rel_url.query['value'])
+ core.write_config()
+ else:
+ return web.Response(text=core.get_config()['component_policy'], status=200)
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/policy/update")
+async def update_policy(request):
+ if "value" in request.rel_url.query:
+ set_update_policy(request.rel_url.query['value'])
+ core.write_config()
+ else:
+ return web.Response(text=core.get_config()['update_policy'], status=200)
+
+ return web.Response(status=200)
+
+
+@routes.get("/v2/manager/channel_url_list")
+async def channel_url_list(request):
+ channels = core.get_channel_dict()
+ if "value" in request.rel_url.query:
+ channel_url = channels.get(request.rel_url.query['value'])
+ if channel_url is not None:
+ core.get_config()['channel_url'] = channel_url
+ core.write_config()
+ else:
+ selected = 'custom'
+ selected_url = core.get_config()['channel_url']
+
+ for name, url in channels.items():
+ if url == selected_url:
+ selected = name
+ break
+
+ res = {'selected': selected,
+ 'list': core.get_channel_list()}
+ return web.json_response(res, status=200)
+
+ return web.Response(status=200)
+
+
+def add_target_blank(html_text):
+ pattern = r'(]*)(>)'
+
+ def add_target(match):
+ if 'target=' not in match.group(1):
+ return match.group(1) + ' target="_blank"' + match.group(2)
+ return match.group(0)
+
+ modified_html = re.sub(pattern, add_target, html_text)
+
+ return modified_html
+
+
+@routes.get("/v2/manager/notice")
+async def get_notice(request):
+ url = "github.com"
+ path = "/ltdrdata/ltdrdata.github.io/wiki/News"
+
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
+ async with session.get(f"https://{url}{path}") as response:
+ if response.status == 200:
+ # html_content = response.read().decode('utf-8')
+ html_content = await response.text()
+
+ pattern = re.compile(r'([\s\S]*?)
')
+ match = pattern.search(html_content)
+
+ if match:
+ markdown_content = match.group(1)
+ version_tag = os.environ.get('__COMFYUI_DESKTOP_VERSION__')
+ if version_tag is not None:
+ markdown_content += f"
ComfyUI: {version_tag} [Desktop]"
+ else:
+ version_tag = context.get_comfyui_tag()
+ if version_tag is None:
+ markdown_content += f"
ComfyUI: {core.comfy_ui_revision}[{comfy_ui_hash[:6]}]({core.comfy_ui_commit_datetime.date()})"
+ else:
+ markdown_content += (f"
ComfyUI: {version_tag}
"
+ f" ({core.comfy_ui_commit_datetime.date()})")
+ # markdown_content += f"
()"
+ markdown_content += f"
Manager: {core.version_str}"
+
+ markdown_content = add_target_blank(markdown_content)
+
+ try:
+ if '__COMFYUI_DESKTOP_VERSION__' not in os.environ:
+ if core.comfy_ui_commit_datetime == datetime(1900, 1, 1, 0, 0, 0):
+ markdown_content = 'Your ComfyUI isn\'t git repo.
' + markdown_content
+ elif core.comfy_ui_required_commit_datetime.date() > core.comfy_ui_commit_datetime.date():
+ markdown_content = 'Your ComfyUI is too OUTDATED!!!
' + markdown_content
+ except:
+ pass
+
+ return web.Response(text=markdown_content, status=200)
+ else:
+ return web.Response(text="Unable to retrieve Notice", status=200)
+ else:
+ return web.Response(text="Unable to retrieve Notice", status=200)
+
+
+# legacy /manager/notice
+@routes.get("/manager/notice")
+async def get_notice_legacy(request):
+ return web.Response(text="""Starting from ComfyUI-Manager V4.0+, it should be installed via pip.
Please remove the ComfyUI-Manager installed in the 'custom_nodes' directory.""", status=200)
+
+
+@routes.get("/v2/manager/reboot")
+def restart(self):
+ if not is_allowed_security_level('middle'):
+ logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
+ return web.Response(status=403)
+
+ try:
+ sys.stdout.close_log()
+ except Exception:
+ pass
+
+ if '__COMFY_CLI_SESSION__' in os.environ:
+ with open(os.path.join(os.environ['__COMFY_CLI_SESSION__'] + '.reboot'), 'w'):
+ pass
+
+ print("\nRestarting...\n\n") # This printing should not be logging - that will be ugly
+ exit(0)
+
+ print("\nRestarting... [Legacy Mode]\n\n") # This printing should not be logging - that will be ugly
+
+ sys_argv = sys.argv.copy()
+ if '--windows-standalone-build' in sys_argv:
+ sys_argv.remove('--windows-standalone-build')
+
+ if sys_argv[0].endswith("__main__.py"): # this is a python module
+ module_name = os.path.basename(os.path.dirname(sys_argv[0]))
+ cmds = [sys.executable, '-m', module_name] + sys_argv[1:]
+ elif sys.platform.startswith('win32'):
+ cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
+ else:
+ cmds = [sys.executable] + sys_argv
+
+ print(f"Command: {cmds}", flush=True)
+
+ return os.execv(sys.executable, cmds)
+
+
+@routes.post("/v2/manager/component/save")
+async def save_component(request):
+ try:
+ data = await request.json()
+ name = data['name']
+ workflow = data['workflow']
+
+ if not os.path.exists(context.manager_components_path):
+ os.mkdir(context.manager_components_path)
+
+ if 'packname' in workflow and workflow['packname'] != '':
+ sanitized_name = manager_util.sanitize_filename(workflow['packname']) + '.pack'
+ else:
+ sanitized_name = manager_util.sanitize_filename(name) + '.json'
+
+ filepath = os.path.join(context.manager_components_path, sanitized_name)
+ components = {}
+ if os.path.exists(filepath):
+ with open(filepath) as f:
+ components = json.load(f)
+
+ components[name] = workflow
+
+ with open(filepath, 'w') as f:
+ json.dump(components, f, indent=4, sort_keys=True)
+ return web.Response(text=filepath, status=200)
+ except:
+ return web.Response(status=400)
+
+
+@routes.post("/v2/manager/component/loads")
+async def load_components(request):
+ if os.path.exists(context.manager_components_path):
+ try:
+ json_files = [f for f in os.listdir(context.manager_components_path) if f.endswith('.json')]
+ pack_files = [f for f in os.listdir(context.manager_components_path) if f.endswith('.pack')]
+
+ components = {}
+ for json_file in json_files + pack_files:
+ file_path = os.path.join(context.manager_components_path, json_file)
+ with open(file_path, 'r') as file:
+ try:
+ # When there is a conflict between the .pack and the .json, the pack takes precedence and overrides.
+ components.update(json.load(file))
+ except json.JSONDecodeError as e:
+ logging.error(f"[ComfyUI-Manager] Error decoding component file in file {json_file}: {e}")
+
+ return web.json_response(components)
+ except Exception as e:
+ logging.error(f"[ComfyUI-Manager] failed to load components\n{e}")
+ return web.Response(status=400)
+ else:
+ return web.json_response({})
+
+
+@routes.get("/v2/manager/version")
+async def get_version(request):
+ return web.Response(text=core.version_str, status=200)
+
+
+async def _confirm_try_install(sender, custom_node_url, msg):
+ json_obj = await core.get_data_by_mode('default', 'custom-node-list.json')
+
+ sender = manager_util.sanitize_tag(sender)
+ msg = manager_util.sanitize_tag(msg)
+ target = core.lookup_customnode_by_url(json_obj, custom_node_url)
+
+ if target is not None:
+ PromptServer.instance.send_sync("cm-api-try-install-customnode",
+ {"sender": sender, "target": target, "msg": msg})
+ else:
+ logging.error(f"[ComfyUI Manager API] Failed to try install - Unknown custom node url '{custom_node_url}'")
+
+
+def confirm_try_install(sender, custom_node_url, msg):
+ asyncio.run(_confirm_try_install(sender, custom_node_url, msg))
+
+
+cm_global.register_api('cm.try-install-custom-node', confirm_try_install)
+
+
+async def default_cache_update():
+ core.refresh_channel_dict()
+ channel_url = core.get_config()['channel_url']
+ async def get_cache(filename):
+ try:
+ if core.get_config()['default_cache_as_channel_url']:
+ uri = f"{channel_url}/{filename}"
+ else:
+ uri = f"{core.DEFAULT_CHANNEL}/{filename}"
+
+ cache_uri = str(manager_util.simple_hash(uri)) + '_' + filename
+ cache_uri = os.path.join(manager_util.cache_dir, cache_uri)
+
+ json_obj = await manager_util.get_data(uri, True)
+
+ with manager_util.cache_lock:
+ with open(cache_uri, "w", encoding='utf-8') as file:
+ json.dump(json_obj, file, indent=4, sort_keys=True)
+ logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
+ except Exception as e:
+ logging.error(f"[ComfyUI-Manager] Failed to perform initial fetching '{filename}': {e}")
+ traceback.print_exc()
+
+ if core.get_config()['network_mode'] != 'offline' and not manager_util.is_manager_pip_package():
+ a = get_cache("custom-node-list.json")
+ b = get_cache("extension-node-map.json")
+ c = get_cache("model-list.json")
+ d = get_cache("alter-list.json")
+ e = get_cache("github-stats.json")
+
+ await asyncio.gather(a, b, c, d, e)
+
+ if core.get_config()['network_mode'] == 'private':
+ logging.info("[ComfyUI-Manager] The private comfyregistry is not yet supported in `network_mode=private`.")
+ else:
+ # load at least once
+ await core.unified_manager.reload('remote', dont_wait=False)
+ await core.unified_manager.get_custom_nodes(channel_url, 'remote')
+ else:
+ await core.unified_manager.reload('remote', dont_wait=False, update_cnr_map=False)
+
+ logging.info("[ComfyUI-Manager] All startup tasks have been completed.")
+
+
+threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
+
+if not os.path.exists(context.manager_config_path):
+ core.get_config()
+ core.write_config()
+
+
+cm_global.register_extension('ComfyUI-Manager',
+ {'version': core.version,
+ 'name': 'ComfyUI Manager',
+ 'nodes': {},
+ 'description': 'This extension provides the ability to manage custom nodes in ComfyUI.', })
+
diff --git a/comfyui_manager/legacy/share_3rdparty.py b/comfyui_manager/legacy/share_3rdparty.py
new file mode 100644
index 00000000..64f68623
--- /dev/null
+++ b/comfyui_manager/legacy/share_3rdparty.py
@@ -0,0 +1,386 @@
+import mimetypes
+from ..common import context
+from . import manager_core as core
+
+import os
+from aiohttp import web
+import aiohttp
+import json
+import hashlib
+
+import folder_paths
+from server import PromptServer
+
+
+def extract_model_file_names(json_data):
+ """Extract unique file names from the input JSON data."""
+ file_names = set()
+ model_filename_extensions = {'.safetensors', '.ckpt', '.pt', '.pth', '.bin'}
+
+ # Recursively search for file names in the JSON data
+ def recursive_search(data):
+ if isinstance(data, dict):
+ for value in data.values():
+ recursive_search(value)
+ elif isinstance(data, list):
+ for item in data:
+ recursive_search(item)
+ elif isinstance(data, str) and '.' in data:
+ file_names.add(os.path.basename(data)) # file_names.add(data)
+
+ recursive_search(json_data)
+ return [f for f in list(file_names) if os.path.splitext(f)[1] in model_filename_extensions]
+
+
+def find_file_paths(base_dir, file_names):
+ """Find the paths of the files in the base directory."""
+ file_paths = {}
+
+ for root, dirs, files in os.walk(base_dir):
+ # Exclude certain directories
+ dirs[:] = [d for d in dirs if d not in ['.git']]
+
+ for file in files:
+ if file in file_names:
+ file_paths[file] = os.path.join(root, file)
+ return file_paths
+
+
+def compute_sha256_checksum(filepath):
+ """Compute the SHA256 checksum of a file, in chunks"""
+ sha256 = hashlib.sha256()
+ with open(filepath, 'rb') as f:
+ for chunk in iter(lambda: f.read(4096), b''):
+ sha256.update(chunk)
+ return sha256.hexdigest()
+
+
+@PromptServer.instance.routes.get("/v2/manager/share_option")
+async def share_option(request):
+ if "value" in request.rel_url.query:
+ core.get_config()['share_option'] = request.rel_url.query['value']
+ core.write_config()
+ else:
+ return web.Response(text=core.get_config()['share_option'], status=200)
+
+ return web.Response(status=200)
+
+
+def get_openart_auth():
+ if not os.path.exists(os.path.join(context.manager_files_path, ".openart_key")):
+ return None
+ try:
+ with open(os.path.join(context.manager_files_path, ".openart_key"), "r") as f:
+ openart_key = f.read().strip()
+ return openart_key if openart_key else None
+ except:
+ return None
+
+
+def get_matrix_auth():
+ if not os.path.exists(os.path.join(context.manager_files_path, "matrix_auth")):
+ return None
+ try:
+ with open(os.path.join(context.manager_files_path, "matrix_auth"), "r") as f:
+ matrix_auth = f.read()
+ homeserver, username, password = matrix_auth.strip().split("\n")
+ if not homeserver or not username or not password:
+ return None
+ return {
+ "homeserver": homeserver,
+ "username": username,
+ "password": password,
+ }
+ except:
+ return None
+
+
+def get_comfyworkflows_auth():
+ if not os.path.exists(os.path.join(context.manager_files_path, "comfyworkflows_sharekey")):
+ return None
+ try:
+ with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
+ share_key = f.read()
+ if not share_key.strip():
+ return None
+ return share_key
+ except:
+ return None
+
+
+def get_youml_settings():
+ if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
+ return None
+ try:
+ with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
+ youml_settings = f.read().strip()
+ return youml_settings if youml_settings else None
+ except:
+ return None
+
+
+def set_youml_settings(settings):
+ with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
+ f.write(settings)
+
+
+@PromptServer.instance.routes.get("/v2/manager/get_openart_auth")
+async def api_get_openart_auth(request):
+ # print("Getting stored Matrix credentials...")
+ openart_key = get_openart_auth()
+ if not openart_key:
+ return web.Response(status=404)
+ return web.json_response({"openart_key": openart_key})
+
+
+@PromptServer.instance.routes.post("/v2/manager/set_openart_auth")
+async def api_set_openart_auth(request):
+ json_data = await request.json()
+ openart_key = json_data['openart_key']
+ with open(os.path.join(context.manager_files_path, ".openart_key"), "w") as f:
+ f.write(openart_key)
+ return web.Response(status=200)
+
+
+@PromptServer.instance.routes.get("/v2/manager/get_matrix_auth")
+async def api_get_matrix_auth(request):
+ # print("Getting stored Matrix credentials...")
+ matrix_auth = get_matrix_auth()
+ if not matrix_auth:
+ return web.Response(status=404)
+ return web.json_response(matrix_auth)
+
+
+@PromptServer.instance.routes.get("/v2/manager/youml/settings")
+async def api_get_youml_settings(request):
+ youml_settings = get_youml_settings()
+ if not youml_settings:
+ return web.Response(status=404)
+ return web.json_response(json.loads(youml_settings))
+
+
+@PromptServer.instance.routes.post("/v2/manager/youml/settings")
+async def api_set_youml_settings(request):
+ json_data = await request.json()
+ set_youml_settings(json.dumps(json_data))
+ return web.Response(status=200)
+
+
+@PromptServer.instance.routes.get("/v2/manager/get_comfyworkflows_auth")
+async def api_get_comfyworkflows_auth(request):
+ # Check if the user has provided Matrix credentials in a file called 'matrix_accesstoken'
+ # in the same directory as the ComfyUI base folder
+ # print("Getting stored Comfyworkflows.com auth...")
+ comfyworkflows_auth = get_comfyworkflows_auth()
+ if not comfyworkflows_auth:
+ return web.Response(status=404)
+ return web.json_response({"comfyworkflows_sharekey": comfyworkflows_auth})
+
+
+@PromptServer.instance.routes.post("/v2/manager/set_esheep_workflow_and_images")
+async def set_esheep_workflow_and_images(request):
+ json_data = await request.json()
+ with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
+ json.dump(json_data, file, indent=4)
+ return web.Response(status=200)
+
+
+@PromptServer.instance.routes.get("/v2/manager/get_esheep_workflow_and_images")
+async def get_esheep_workflow_and_images(request):
+ with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
+ data = json.load(file)
+ return web.Response(status=200, text=json.dumps(data))
+
+
+def set_matrix_auth(json_data):
+ homeserver = json_data['homeserver']
+ username = json_data['username']
+ password = json_data['password']
+ with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
+ f.write("\n".join([homeserver, username, password]))
+
+
+def set_comfyworkflows_auth(comfyworkflows_sharekey):
+ with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
+ f.write(comfyworkflows_sharekey)
+
+
+def has_provided_matrix_auth(matrix_auth):
+ return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
+
+
+def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
+ return comfyworkflows_sharekey.strip()
+
+
+@PromptServer.instance.routes.post("/v2/manager/share")
+async def share_art(request):
+ # get json data
+ json_data = await request.json()
+
+ matrix_auth = json_data['matrix_auth']
+ comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
+
+ set_matrix_auth(matrix_auth)
+ set_comfyworkflows_auth(comfyworkflows_sharekey)
+
+ share_destinations = json_data['share_destinations']
+ credits = json_data['credits']
+ title = json_data['title']
+ description = json_data['description']
+ is_nsfw = json_data['is_nsfw']
+ prompt = json_data['prompt']
+ potential_outputs = json_data['potential_outputs']
+ selected_output_index = json_data['selected_output_index']
+
+ try:
+ output_to_share = potential_outputs[int(selected_output_index)]
+ except:
+ # for now, pick the first output
+ output_to_share = potential_outputs[0]
+
+ assert output_to_share['type'] in ('image', 'output')
+ output_dir = folder_paths.get_output_directory()
+
+ if output_to_share['type'] == 'image':
+ asset_filename = output_to_share['image']['filename']
+ asset_subfolder = output_to_share['image']['subfolder']
+
+ if output_to_share['image']['type'] == 'temp':
+ output_dir = folder_paths.get_temp_directory()
+ else:
+ asset_filename = output_to_share['output']['filename']
+ asset_subfolder = output_to_share['output']['subfolder']
+
+ if asset_subfolder:
+ asset_filepath = os.path.join(output_dir, asset_subfolder, asset_filename)
+ else:
+ asset_filepath = os.path.join(output_dir, asset_filename)
+
+ # get the mime type of the asset
+ assetFileType = mimetypes.guess_type(asset_filepath)[0]
+
+ share_website_host = "UNKNOWN"
+ if "comfyworkflows" in share_destinations:
+ share_website_host = "https://comfyworkflows.com"
+ share_endpoint = f"{share_website_host}/api"
+
+ # get presigned urls
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
+ async with session.post(
+ f"{share_endpoint}/get_presigned_urls",
+ json={
+ "assetFileName": asset_filename,
+ "assetFileType": assetFileType,
+ "workflowJsonFileName": 'workflow.json',
+ "workflowJsonFileType": 'application/json',
+ },
+ ) as resp:
+ assert resp.status == 200
+ presigned_urls_json = await resp.json()
+ assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
+ assetFileKey = presigned_urls_json["assetFileKey"]
+ workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
+ workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
+
+ # upload asset
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
+ async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
+ assert resp.status == 200
+
+ # upload workflow json
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
+ async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
+ assert resp.status == 200
+
+ model_filenames = extract_model_file_names(prompt['workflow'])
+ model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
+
+ models_info = {}
+ for filename, filepath in model_file_paths.items():
+ models_info[filename] = {
+ "filename": filename,
+ "sha256_checksum": compute_sha256_checksum(filepath),
+ "relative_path": os.path.relpath(filepath, folder_paths.base_path),
+ }
+
+ # make a POST request to /api/upload_workflow with form data key values
+ async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
+ form = aiohttp.FormData()
+ if comfyworkflows_sharekey:
+ form.add_field("shareKey", comfyworkflows_sharekey)
+ form.add_field("source", "comfyui_manager")
+ form.add_field("assetFileKey", assetFileKey)
+ form.add_field("assetFileType", assetFileType)
+ form.add_field("workflowJsonFileKey", workflowJsonFileKey)
+ form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
+ form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
+ form.add_field("shareWorkflowCredits", credits)
+ form.add_field("shareWorkflowTitle", title)
+ form.add_field("shareWorkflowDescription", description)
+ form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
+ form.add_field("currentSnapshot", json.dumps(await core.get_current_snapshot()))
+ form.add_field("modelsInfo", json.dumps(models_info))
+
+ async with session.post(
+ f"{share_endpoint}/upload_workflow",
+ data=form,
+ ) as resp:
+ assert resp.status == 200
+ upload_workflow_json = await resp.json()
+ workflowId = upload_workflow_json["workflowId"]
+
+ # check if the user has provided Matrix credentials
+ if "matrix" in share_destinations:
+ comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
+ filename = os.path.basename(asset_filepath)
+ content_type = assetFileType
+
+ try:
+ from matrix_client.api import MatrixHttpApi
+ from matrix_client.client import MatrixClient
+
+ homeserver = 'matrix.org'
+ if matrix_auth:
+ homeserver = matrix_auth.get('homeserver', 'matrix.org')
+ homeserver = homeserver.replace("http://", "https://")
+ if not homeserver.startswith("https://"):
+ homeserver = "https://" + homeserver
+
+ client = MatrixClient(homeserver)
+ try:
+ token = client.login(username=matrix_auth['username'], password=matrix_auth['password'])
+ if not token:
+ return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
+ except:
+ return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
+
+ matrix = MatrixHttpApi(homeserver, token=token)
+ with open(asset_filepath, 'rb') as f:
+ mxc_url = matrix.media_upload(f.read(), content_type, filename=filename)['content_uri']
+
+ workflow_json_mxc_url = matrix.media_upload(prompt['workflow'], 'application/json', filename='workflow.json')['content_uri']
+
+ text_content = ""
+ if title:
+ text_content += f"{title}\n"
+ if description:
+ text_content += f"{description}\n"
+ if credits:
+ text_content += f"\ncredits: {credits}\n"
+ matrix.send_message(comfyui_share_room_id, text_content)
+ matrix.send_content(comfyui_share_room_id, mxc_url, filename, 'm.image')
+ matrix.send_content(comfyui_share_room_id, workflow_json_mxc_url, 'workflow.json', 'm.file')
+ except:
+ import traceback
+ traceback.print_exc()
+ return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
+
+ return web.json_response({
+ "comfyworkflows": {
+ "url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
+ },
+ "matrix": {
+ "success": None if "matrix" not in share_destinations else True
+ }
+ }, content_type='application/json', status=200)
diff --git a/comfyui_manager/prestartup_script.py b/comfyui_manager/prestartup_script.py
index be2ae1a4..f0820f79 100644
--- a/comfyui_manager/prestartup_script.py
+++ b/comfyui_manager/prestartup_script.py
@@ -12,10 +12,10 @@ import ast
import logging
import traceback
-from .glob import security_check
-from .glob import manager_util
-from .glob import cm_global
-from .glob import manager_downloader
+from .common import security_check
+from .common import manager_util
+from .common import cm_global
+from .common import manager_downloader
import folder_paths
manager_util.add_python_path_to_env()