Split Loader.py 2
This commit is contained in:
+9
-5
@@ -1,13 +1,17 @@
|
||||
from .boot.Logger import Logger
|
||||
from .boot.Backends import Backends
|
||||
from .boot.Config import Config
|
||||
from .boot.Update import Update
|
||||
from .boot.Paths import Paths
|
||||
from .boot.Override import Override
|
||||
from .boot.Modules import Modules
|
||||
|
||||
config = Config().initiate()
|
||||
logger = Logger()
|
||||
config = Config(logger).initiate()
|
||||
backends = Backends(logger).initiate()
|
||||
|
||||
Update(config).initiate()
|
||||
Paths(config).initiate()
|
||||
Override(config).initiate()
|
||||
Update(logger, config, backends).initiate()
|
||||
Paths(logger, config).initiate()
|
||||
Override(logger, config).initiate()
|
||||
|
||||
NODE_CLASS_MAPPINGS = Modules(config).initiate()
|
||||
NODE_CLASS_MAPPINGS = Modules(logger, config, backends).initiate()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import importlib
|
||||
|
||||
|
||||
class Backends:
|
||||
TORCH = "torch"
|
||||
NUMPY = "numpy"
|
||||
CV2 = "cv2"
|
||||
PIL = "PIL"
|
||||
REMBG = "rembg"
|
||||
GIT = "git"
|
||||
|
||||
def __init__(self, logger):
|
||||
self.__logger = logger
|
||||
self.__backends = [Backends.TORCH, Backends.NUMPY, Backends.CV2, Backends.PIL, Backends.REMBG, Backends.GIT]
|
||||
|
||||
def initiate(self):
|
||||
dependencies = {}
|
||||
|
||||
for backend in self.__backends:
|
||||
try:
|
||||
importlib.import_module(backend)
|
||||
dependencies[backend] = True
|
||||
except ImportError:
|
||||
self.__logger.error(f"Loading {backend} library ended with an error.")
|
||||
dependencies[backend] = False
|
||||
|
||||
return dependencies
|
||||
+8
-9
@@ -1,15 +1,14 @@
|
||||
import json
|
||||
|
||||
from .Constants import Constants
|
||||
from .Logger import Logger
|
||||
from .Paths import Paths
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self):
|
||||
self.__logger = Logger()
|
||||
def __init__(self, logger):
|
||||
self.__logger = logger
|
||||
self.__template = self.__get_template()
|
||||
|
||||
if not Constants.CONFIG_PATH.exists():
|
||||
if not Paths.CONFIG_PATH.exists():
|
||||
self.__logger.info("Creating configuration file.")
|
||||
self.__create_config()
|
||||
|
||||
@@ -23,11 +22,11 @@ class Config:
|
||||
return self.__get_config()
|
||||
|
||||
def __create_config(self):
|
||||
with open(Constants.CONFIG_PATH, "w", encoding="utf-8") as f:
|
||||
with open(Paths.CONFIG_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(self.__template, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def __get_template(self):
|
||||
with open(Constants.TEMPLATE_PATH, "r") as f:
|
||||
with open(Paths.TEMPLATE_PATH, "r") as f:
|
||||
template = json.load(f)
|
||||
|
||||
if "__comment" in template:
|
||||
@@ -36,7 +35,7 @@ class Config:
|
||||
return template
|
||||
|
||||
def __get_config(self):
|
||||
with open(Constants.CONFIG_PATH, "r") as f:
|
||||
with open(Paths.CONFIG_PATH, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
def __verify_keys(self, json1, json2):
|
||||
@@ -94,5 +93,5 @@ class Config:
|
||||
source = delete_keys(template, source)
|
||||
source = sync_order(template, source)
|
||||
|
||||
with open(Constants.CONFIG_PATH, "w", encoding="utf-8") as f:
|
||||
with open(Paths.CONFIG_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(source, f, ensure_ascii=False, indent=4)
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Constants:
|
||||
ROOT_PATH = Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
TEMPLATE_PATH = ROOT_PATH / "resources/template.json"
|
||||
TIMESTAMP_PATH = ROOT_PATH / "resources/timestamp.json"
|
||||
CONFIG_PATH = ROOT_PATH / "config.json"
|
||||
GIT_PATH = ROOT_PATH / ".git"
|
||||
LOG_PATH = ROOT_PATH / f"resources/logs/log_{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.txt"
|
||||
|
||||
DAY_SECONDS = 24 * 60 * 60
|
||||
WEEK_SECONDS = 7 * DAY_SECONDS
|
||||
MONTH_SECONDS = 30 * DAY_SECONDS
|
||||
+217
-54
@@ -1,30 +1,54 @@
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
from .Constants import Constants
|
||||
from .Paths import Paths
|
||||
|
||||
|
||||
class Logger:
|
||||
file = Constants.LOG_PATH
|
||||
levels = {
|
||||
"FATAL": 92,
|
||||
"ERROR": 91,
|
||||
"WARN": 93,
|
||||
"INFO": 94,
|
||||
"DEBUG": 95,
|
||||
"TRACE": 96,
|
||||
"LINE": 0
|
||||
}
|
||||
class SingletonLogger(type):
|
||||
_instances = {}
|
||||
|
||||
def __call__(cls, *args, **kwargs):
|
||||
if cls not in cls._instances:
|
||||
cls._instances[cls] = super(SingletonLogger, cls).__call__(*args, **kwargs)
|
||||
return cls._instances[cls]
|
||||
|
||||
|
||||
class Logger(metaclass=SingletonLogger):
|
||||
file = Paths.LOG_PATH
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
self.formatting = _Formatting()
|
||||
self.levels = {
|
||||
"FATAL": _Formatting.COLOR["RED"],
|
||||
"ERROR": _Formatting.COLOR["RED"],
|
||||
"WARN": _Formatting.COLOR["YELLOW"],
|
||||
"INFO": _Formatting.COLOR["BLUE"],
|
||||
"EMIT": _Formatting.COLOR["GREEN"],
|
||||
"DEBUG": _Formatting.COLOR["MAGENTA"],
|
||||
"TRACE": _Formatting.COLOR["CYAN"],
|
||||
"LINE": _Formatting.COLOR["DEFAULT"],
|
||||
}
|
||||
|
||||
def __log(self, text, level):
|
||||
if level == "LINE":
|
||||
print()
|
||||
else:
|
||||
print(f"\033[{self.levels.get(level, '')}m[Allor]\033[0m: " + text)
|
||||
info = self.__get_info()
|
||||
|
||||
if info["branch"] == "main":
|
||||
info["branch"] = "v.2"
|
||||
|
||||
self.debug(f"{info['branch']} : {info['hex']}")
|
||||
|
||||
def __log(self, text, level, display):
|
||||
if display:
|
||||
if level == "LINE":
|
||||
print()
|
||||
else:
|
||||
indent = " " * 9
|
||||
indented_text = "\n".join(line if i == 0 or not line else indent + line for i, line in enumerate(text.split("\n")))
|
||||
|
||||
print(f"{self.formatting.foreground('[Allor]: ', self.levels.get(level), _Formatting.INTENSITY['BRIGHT'])}" + indented_text)
|
||||
|
||||
if Logger.file:
|
||||
directory = Logger.file.parent
|
||||
@@ -33,7 +57,7 @@ class Logger:
|
||||
directory.mkdir(parents=True)
|
||||
|
||||
if not Logger.file.exists():
|
||||
log_files = list(glob.glob(str(directory / 'log_*.txt')))
|
||||
log_files = list(glob.glob(str(directory / "log_*.log")))
|
||||
|
||||
if len(log_files) > 5:
|
||||
log_files.sort(key=os.path.getmtime)
|
||||
@@ -46,53 +70,192 @@ class Logger:
|
||||
if level == "LINE":
|
||||
f.write("\n")
|
||||
else:
|
||||
text = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub("", text)
|
||||
indent = " " * 30
|
||||
indented_text = "\n".join(line if i == 0 or not line else indent + line for i, line in enumerate(text.split("\n")))
|
||||
indented_text = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub("", indented_text)
|
||||
|
||||
f.write(f"[{level}]: {text}\n")
|
||||
f.write(f"[{datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}][{level:<5}]: {indented_text}\n")
|
||||
|
||||
def fatal(self, text):
|
||||
self.__log(text, "FATAL")
|
||||
def fatal(self, text, display=True):
|
||||
self.__log(text, "FATAL", display)
|
||||
|
||||
def error(self, text):
|
||||
self.__log(text, "ERROR")
|
||||
def error(self, text, display=True):
|
||||
self.__log(text, "ERROR", display)
|
||||
|
||||
def warn(self, text):
|
||||
self.__log(text, "WARN")
|
||||
def warn(self, text, display=True):
|
||||
self.__log(text, "WARN", display)
|
||||
|
||||
def info(self, text):
|
||||
self.__log(text, "INFO")
|
||||
def info(self, text, display=True):
|
||||
self.__log(text, "INFO", display)
|
||||
|
||||
def debug(self, text):
|
||||
self.__log(text, "DEBUG")
|
||||
def emit(self, text, display=True):
|
||||
self.__log(text, "EMIT", display)
|
||||
|
||||
def trace(self, text):
|
||||
self.__log(text, "TRACE")
|
||||
def debug(self, text, display=True):
|
||||
self.__log(text, "DEBUG", display)
|
||||
|
||||
def line(self, count=1):
|
||||
self.__log("\n" * count, "LINE")
|
||||
def trace(self, text, display=True):
|
||||
self.__log(text, "TRACE", display)
|
||||
|
||||
def line(self, count=1, display=True):
|
||||
self.__log("\n" * count, "LINE", display)
|
||||
|
||||
def warning_unstable_branch(self, branch_name="main"):
|
||||
warn_messages = [
|
||||
f"Attention! You are currently using an unstable \033[1m{branch_name}\033[0m update branch.",
|
||||
f"This branch is intended for the development of \033[1mAllor v.2\033[0m.",
|
||||
f"Please be aware that changes made in \033[1mAllor v.2\033[0m may disrupt your current workflow.",
|
||||
"Nodes may be renamed, parameters within them may be altered or even removed.",
|
||||
"If backward compatibility of your workflow is important to you, consider this.",
|
||||
f"You can change the \033[1m\"branch_name\"\033[0m parameter to \033[1m\"v.1\"\033[0m in your \033[1mconfig.json.\033[0m",
|
||||
"If you are prepared for potential changes, you can modify your current workflow.",
|
||||
f"To accept, switch the \033[1m\"confirm_unstable\"\033[0m parameter in your \033[1mconfig.json.\033[0m to \033[1m\"true\".\033[0m",
|
||||
def bold(text):
|
||||
return self.formatting.format(text, _Formatting.FORMAT["BOLD"])
|
||||
|
||||
branch_name = bold(branch_name)
|
||||
allor_v2 = bold("Allor v.2")
|
||||
branch_name_param = bold("\"branch_name\"")
|
||||
v1 = bold("\"v.1\"")
|
||||
config_json = bold("config.json")
|
||||
confirm_unstable_param = bold("\"confirm_unstable\"")
|
||||
true = bold("\"true\"")
|
||||
|
||||
warn_messages = (
|
||||
f"Attention! You are currently using an unstable {branch_name} update branch. \n"
|
||||
f"This branch is intended for the development of {allor_v2}. \n"
|
||||
f"Please be aware that changes made in {allor_v2} may disrupt your current workflow. \n"
|
||||
"Nodes may be renamed, parameters within them may be altered or even removed. \n"
|
||||
"If backward compatibility of your workflow is important to you, consider this. \n"
|
||||
f"You can change the {branch_name_param} parameter to {v1} in your {config_json}. \n"
|
||||
"If you are prepared for potential changes, you can modify your current workflow. \n"
|
||||
f"To accept, switch the {confirm_unstable_param} parameter in your {config_json} to {true}. \n"
|
||||
"This will result in this warning no longer appearing."
|
||||
]
|
||||
)
|
||||
|
||||
info_messages = [
|
||||
"We appreciate your support and understanding during this transition period.",
|
||||
f"Thank you and welcome to \033[1mAllor v.2\033[0m.\n"
|
||||
]
|
||||
|
||||
for message in warn_messages:
|
||||
self.warn(message)
|
||||
emit_messages = (
|
||||
"We appreciate your support and understanding during this transition period. \n"
|
||||
f"Thank you and welcome to {allor_v2}."
|
||||
)
|
||||
|
||||
self.warn(warn_messages)
|
||||
self.line()
|
||||
self.emit(emit_messages)
|
||||
self.line()
|
||||
|
||||
for message in info_messages:
|
||||
self.info(message)
|
||||
def __get_info(self):
|
||||
with open(Paths.INFO_PATH, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
class _Formatting:
|
||||
COLOR = {
|
||||
"BLACK": 0,
|
||||
"RED": 1,
|
||||
"GREEN": 2,
|
||||
"YELLOW": 3,
|
||||
"BLUE": 4,
|
||||
"MAGENTA": 5,
|
||||
"CYAN": 6,
|
||||
"WHITE": 7,
|
||||
"DEFAULT": 8,
|
||||
"GRAY_1": 232,
|
||||
"GRAY_2": 233,
|
||||
"GRAY_3": 234,
|
||||
"GRAY_4": 235,
|
||||
"GRAY_5": 236,
|
||||
"GRAY_6": 237,
|
||||
"GRAY_7": 238,
|
||||
"GRAY_8": 239,
|
||||
"GRAY_9": 240,
|
||||
"GRAY_10": 241,
|
||||
"GRAY_11": 242,
|
||||
"GRAY_12": 243,
|
||||
"GRAY_13": 244,
|
||||
"GRAY_14": 245,
|
||||
"GRAY_15": 246,
|
||||
"GRAY_16": 247,
|
||||
"GRAY_17": 248,
|
||||
"GRAY_18": 249,
|
||||
"GRAY_19": 250,
|
||||
"GRAY_20": 251,
|
||||
"GRAY_21": 252,
|
||||
"GRAY_22": 253,
|
||||
"GRAY_32": 254,
|
||||
"GRAY_24": 255
|
||||
}
|
||||
|
||||
INTENSITY = {
|
||||
"NORMAL": 30,
|
||||
"BRIGHT": 90
|
||||
}
|
||||
|
||||
FORMAT = {
|
||||
"BOLD": 1,
|
||||
"FAINT": 2,
|
||||
"ITALIC": 3,
|
||||
"UNDERLINE": 4,
|
||||
"BLINKING": 5,
|
||||
"FAST_BLINKING": 6,
|
||||
"REVERSE": 7,
|
||||
"HIDE": 8,
|
||||
"STRIKETHROUGH": 9,
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.__ansi = self.__formatting_support()
|
||||
|
||||
# noinspection PyPep8Naming
|
||||
def __formatting_support(self):
|
||||
platform = sys.platform
|
||||
|
||||
if platform == "win32":
|
||||
import ctypes
|
||||
|
||||
STD_OUTPUT_HANDLE = -11
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
|
||||
|
||||
kernel32 = ctypes.WinDLL("kernel32")
|
||||
hStdOut = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
|
||||
mode = ctypes.c_ulong()
|
||||
|
||||
if not kernel32.GetConsoleMode(hStdOut, ctypes.byref(mode)):
|
||||
return False
|
||||
|
||||
if not mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING:
|
||||
return False
|
||||
|
||||
if platform in ("linux", "darwin"):
|
||||
term = os.getenv("TERM")
|
||||
|
||||
if term not in ("xterm", "xterm-256color", "vt100", "ansi", "linux"):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def format(self, text, format_code):
|
||||
if self.__ansi:
|
||||
if re.search(r"\033\[\d+m", text):
|
||||
return re.sub(r"(\033\[\d+m)", r"\1;\033[" + str(format_code) + "m", text)
|
||||
else:
|
||||
return "\033[" + str(format_code) + "m" + text + "\033[0m"
|
||||
else:
|
||||
return text
|
||||
|
||||
def foreground(self, text, color_code, intensity):
|
||||
if 232 <= color_code <= 255:
|
||||
intensity = 0
|
||||
|
||||
if self.__ansi:
|
||||
if re.search(r"\033\[\d+m", text):
|
||||
return re.sub(r"(\033\[\d+m)", r"\1;\033[" + str(color_code + intensity) + "m", text)
|
||||
else:
|
||||
return "\033[" + str(color_code + intensity) + "m" + text + "\033[0m"
|
||||
else:
|
||||
return text
|
||||
|
||||
def background(self, text, color_code, intensity):
|
||||
if 232 <= color_code <= 255:
|
||||
intensity = 0
|
||||
|
||||
if self.__ansi:
|
||||
if re.search(r"\033\[\d+m", text):
|
||||
return re.sub(r"(\033\[\d+m)", r"\1;\033[" + str(color_code + 10 + intensity) + "m", text)
|
||||
else:
|
||||
return "\033[" + str(color_code + 10 + intensity) + "m" + text + "\033[0m"
|
||||
else:
|
||||
return text
|
||||
|
||||
def reset(self, text):
|
||||
return re.compile(r'\033\[[0-?]*[ -/]*[@-~]').sub('', text)
|
||||
|
||||
+42
-60
@@ -1,72 +1,54 @@
|
||||
from .Logger import Logger
|
||||
import functools
|
||||
from importlib import import_module
|
||||
|
||||
from .Backends import Backends
|
||||
|
||||
|
||||
class Modules:
|
||||
def __init__(self, config):
|
||||
self.__logger = Logger()
|
||||
def __init__(self, logger, config, backends):
|
||||
self.__logger = logger
|
||||
self.__config = config
|
||||
self.__backends = backends
|
||||
|
||||
def initiate(self):
|
||||
modules = dict()
|
||||
modules_loaded = dict()
|
||||
modules_not_loaded = dict()
|
||||
|
||||
if self.__config["modules"]["AlphaChanel"]:
|
||||
from ..modules import AlphaChanel
|
||||
modules.update(AlphaChanel.NODE_CLASS_MAPPINGS)
|
||||
modules_info = {
|
||||
"AlphaChanel": [Backends.TORCH],
|
||||
"Clamp": [],
|
||||
"ImageBatch": [Backends.TORCH],
|
||||
"ImageComposite": [Backends.TORCH, Backends.PIL],
|
||||
"ImageContainer": [Backends.TORCH],
|
||||
"ImageDraw": [Backends.PIL],
|
||||
"ImageEffects": [Backends.TORCH, Backends.NUMPY, Backends.CV2],
|
||||
"ImageFilter": [Backends.TORCH, Backends.PIL, Backends.CV2],
|
||||
"ImageNoise": [Backends.TORCH, Backends.NUMPY],
|
||||
"ImageSegmentation": [Backends.TORCH, Backends.PIL, Backends.REMBG],
|
||||
"ImageText": [Backends.PIL],
|
||||
"ImageTransform": [Backends.TORCH, Backends.PIL]
|
||||
}
|
||||
|
||||
if self.__config["modules"]["Clamp"]:
|
||||
from ..modules import Clamp
|
||||
modules.update(Clamp.NODE_CLASS_MAPPINGS)
|
||||
for module_name, backends in modules_info.items():
|
||||
if self.__config["modules"][module_name]:
|
||||
if self.__required(module_name, *backends):
|
||||
if module := import_module(f"..modules.{module_name}", package=__package__):
|
||||
modules_loaded.update(module.NODE_CLASS_MAPPINGS)
|
||||
else:
|
||||
modules_not_loaded[module_name] = backends
|
||||
|
||||
if self.__config["modules"]["ImageBatch"]:
|
||||
from ..modules import ImageBatch
|
||||
modules.update(ImageBatch.NODE_CLASS_MAPPINGS)
|
||||
modules_len = len({k: v for k, v in self.__config["modules"].items() if v})
|
||||
nodes_len = len(modules_loaded)
|
||||
|
||||
if self.__config["modules"]["ImageComposite"]:
|
||||
from ..modules import ImageComposite
|
||||
modules.update(ImageComposite.NODE_CLASS_MAPPINGS)
|
||||
self.__logger.info(f"{modules_len} modules were enabled.", self.__config["logger"]["modules_enabled"])
|
||||
self.__logger.info(f"{nodes_len} nodes were loaded.", self.__config["logger"]["nodes_loaded"])
|
||||
|
||||
if self.__config["modules"]["ImageContainer"]:
|
||||
from ..modules import ImageContainer
|
||||
modules.update(ImageContainer.NODE_CLASS_MAPPINGS)
|
||||
return modules_loaded
|
||||
|
||||
if self.__config["modules"]["ImageDraw"]:
|
||||
from ..modules import ImageDraw
|
||||
modules.update(ImageDraw.NODE_CLASS_MAPPINGS)
|
||||
|
||||
if self.__config["modules"]["ImageEffects"]:
|
||||
from ..modules import ImageEffects
|
||||
modules.update(ImageEffects.NODE_CLASS_MAPPINGS)
|
||||
|
||||
if self.__config["modules"]["ImageFilter"]:
|
||||
from ..modules import ImageFilter
|
||||
modules.update(ImageFilter.NODE_CLASS_MAPPINGS)
|
||||
|
||||
if self.__config["modules"]["ImageNoise"]:
|
||||
from ..modules import ImageNoise
|
||||
modules.update(ImageNoise.NODE_CLASS_MAPPINGS)
|
||||
|
||||
if self.__config["modules"]["ImageSegmentation"]:
|
||||
from ..modules import ImageSegmentation
|
||||
modules.update(ImageSegmentation.NODE_CLASS_MAPPINGS)
|
||||
|
||||
if self.__config["modules"]["ImageText"]:
|
||||
from ..modules import ImageText
|
||||
modules.update(ImageText.NODE_CLASS_MAPPINGS)
|
||||
|
||||
if self.__config["modules"]["ImageTransform"]:
|
||||
from ..modules import ImageTransform
|
||||
modules.update(ImageTransform.NODE_CLASS_MAPPINGS)
|
||||
|
||||
modules_len = dict(
|
||||
filter(
|
||||
lambda item: item[1],
|
||||
self.__config["modules"].items()
|
||||
)
|
||||
).__len__()
|
||||
|
||||
nodes_len = modules.__len__()
|
||||
|
||||
self.__logger.info(str(modules_len) + " modules were enabled.")
|
||||
self.__logger.info(str(nodes_len) + " nodes were loaded.")
|
||||
|
||||
return modules
|
||||
@functools.lru_cache
|
||||
def __required(self, module, *backends):
|
||||
for backend in backends:
|
||||
if not self.__backends[backend]:
|
||||
self.__logger.error(f"Module {module} did not find all necessary backends. Loading skipped.")
|
||||
return False
|
||||
return True
|
||||
|
||||
+3
-3
@@ -3,8 +3,8 @@ from .Logger import Logger
|
||||
|
||||
|
||||
class Override:
|
||||
def __init__(self, config):
|
||||
self.__logger = Logger()
|
||||
def __init__(self, logger, config):
|
||||
self.__logger = logger
|
||||
self.__config = config
|
||||
|
||||
def initiate(self):
|
||||
@@ -31,4 +31,4 @@ class Override:
|
||||
|
||||
override_nodes_len += override(lambda item: not item[1].CATEGORY.startswith("_for_testing"))
|
||||
|
||||
self.__logger.info(str(override_nodes_len) + " nodes were overridden.")
|
||||
self.__logger.info(str(override_nodes_len) + " nodes were overridden.", self.__config["logger"]["nodes_overridden"])
|
||||
|
||||
+12
-4
@@ -1,14 +1,22 @@
|
||||
import os
|
||||
import platform
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import folder_paths
|
||||
|
||||
from .Logger import Logger
|
||||
|
||||
|
||||
class Paths:
|
||||
def __init__(self, config):
|
||||
self.__logger = Logger()
|
||||
ROOT_PATH = Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
TEMPLATE_PATH = ROOT_PATH / "resources/template.json"
|
||||
TIMESTAMP_PATH = ROOT_PATH / "resources/timestamp.json"
|
||||
INFO_PATH = ROOT_PATH / "resources/info.json"
|
||||
CONFIG_PATH = ROOT_PATH / "config.json"
|
||||
GIT_PATH = ROOT_PATH / ".git"
|
||||
LOG_PATH = ROOT_PATH / f"resources/logs/log_{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.log"
|
||||
|
||||
def __init__(self, logger, config):
|
||||
self.__logger = logger
|
||||
self.__config = config
|
||||
|
||||
def initiate(self):
|
||||
|
||||
+33
-31
@@ -1,47 +1,52 @@
|
||||
import json
|
||||
import time
|
||||
|
||||
from .Constants import Constants
|
||||
from .Logger import Logger
|
||||
from .Backends import Backends
|
||||
from .Paths import Paths
|
||||
|
||||
|
||||
class Update:
|
||||
def __init__(self, config):
|
||||
self.__logger = Logger()
|
||||
self.__config = config
|
||||
DAY_SECONDS = 24 * 60 * 60
|
||||
WEEK_SECONDS = 7 * DAY_SECONDS
|
||||
MONTH_SECONDS = 30 * DAY_SECONDS
|
||||
|
||||
if not Constants.CONFIG_PATH.exists():
|
||||
def __init__(self, logger, config, backends):
|
||||
self.__logger = logger
|
||||
self.__config = config
|
||||
self.__backends = backends
|
||||
|
||||
if not Paths.CONFIG_PATH.exists():
|
||||
self.__logger.info("Creating timestamp file.")
|
||||
self.__create_timestamp()
|
||||
|
||||
self.__timestamp = self.__get_timestamp()
|
||||
|
||||
def initiate(self):
|
||||
confirm_unstable_agreement = self.__config["updates"]["confirm_unstable"]
|
||||
confirm_unstable_agreement = self.__config["logger"]["confirm_unstable"]
|
||||
branch_name = self.__config["updates"]["branch_name"]
|
||||
update_frequency = self.__config["updates"]["update_frequency"].lower()
|
||||
search_frequency = self.__config["updates"]["search_frequency"].lower()
|
||||
time_difference = time.time() - self.__timestamp["timestamp"]
|
||||
|
||||
valid_frequencies = {
|
||||
"always": True,
|
||||
"day": time_difference >= Constants.DAY_SECONDS,
|
||||
"week": time_difference >= Constants.WEEK_SECONDS,
|
||||
"month": time_difference >= Constants.MONTH_SECONDS,
|
||||
"day": time_difference >= self.DAY_SECONDS,
|
||||
"week": time_difference >= self.WEEK_SECONDS,
|
||||
"month": time_difference >= self.MONTH_SECONDS,
|
||||
"never": False
|
||||
}
|
||||
|
||||
try:
|
||||
it_is_time_for_update = valid_frequencies[update_frequency]
|
||||
it_is_time_for_update = valid_frequencies[search_frequency]
|
||||
except KeyError:
|
||||
self.__logger.error(f"Unknown update frequency - {update_frequency}, available: {list(valid_frequencies.keys())}")
|
||||
self.__logger.error(f"Unknown update frequency - {search_frequency}, available: {list(valid_frequencies.keys())}")
|
||||
|
||||
return
|
||||
|
||||
if not confirm_unstable_agreement and branch_name == "main" and update_frequency != "never":
|
||||
if not confirm_unstable_agreement and branch_name == "main" and search_frequency != "never":
|
||||
self.__logger.warning_unstable_branch(branch_name)
|
||||
|
||||
if it_is_time_for_update:
|
||||
if not (Constants.GIT_PATH.exists() and Constants.GIT_PATH.is_dir()):
|
||||
if not (Paths.GIT_PATH.exists() and Paths.GIT_PATH.is_dir()):
|
||||
self.__logger.error("Root directory of Allor is not a git repository. Update canceled.")
|
||||
|
||||
return
|
||||
@@ -49,26 +54,26 @@ class Update:
|
||||
self.__update_allor(branch_name)
|
||||
|
||||
def __get_timestamp(self):
|
||||
with open(Constants.TIMESTAMP_PATH, "r") as f:
|
||||
with open(Paths.TIMESTAMP_PATH, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
def __create_timestamp(self):
|
||||
with open(Constants.TIMESTAMP_PATH, "w", encoding="utf-8") as f:
|
||||
with open(Paths.TIMESTAMP_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump({"timestamp": 0}, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def __update_timestamp(self):
|
||||
with open(Constants.TIMESTAMP_PATH, "w", encoding="utf-8") as f:
|
||||
with open(Paths.TIMESTAMP_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump({"timestamp": time.time()}, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def __update_allor(self, branch_name):
|
||||
try:
|
||||
if self.__backends[Backends.GIT]:
|
||||
import git
|
||||
|
||||
from git import Repo
|
||||
from git import GitCommandError
|
||||
|
||||
# noinspection PyTypeChecker, PyUnboundLocalVariable
|
||||
repo = Repo(Constants.ROOT_PATH, odbt=git.db.GitDB)
|
||||
repo = Repo(Paths.ROOT_PATH, odbt=git.db.GitDB)
|
||||
current_commit = repo.head.commit.hexsha
|
||||
|
||||
repo.remotes.origin.fetch()
|
||||
@@ -76,13 +81,11 @@ class Update:
|
||||
latest_commit = getattr(repo.remotes.origin.refs, branch_name).commit.hexsha
|
||||
|
||||
if current_commit == latest_commit:
|
||||
if self.__config["updates"]["notify_if_no_new_updates"]:
|
||||
self.__logger.info("No new updates.")
|
||||
self.__logger.info("New updates not found.", self.__config["logger"]["updates_search"])
|
||||
else:
|
||||
if self.__config["updates"]["notify_if_has_new_updates"]:
|
||||
self.__logger.info("New updates are available.")
|
||||
self.__logger.info("New updates are available.", self.__config["logger"]["updates_search"])
|
||||
|
||||
if self.__config["updates"]["auto_update"]:
|
||||
if self.__config["updates"]["install_update"]:
|
||||
update_mode = self.__config["updates"]["update_mode"].lower()
|
||||
valid_modes = ["soft", "hard"]
|
||||
|
||||
@@ -98,8 +101,8 @@ class Update:
|
||||
try:
|
||||
repo.git.pull()
|
||||
except GitCommandError:
|
||||
self.__logger.error("An error occurred during the update. "
|
||||
"It is recommended to use \"hard\" update mode. "
|
||||
self.__logger.error("An error occurred during the update. \n"
|
||||
"It is recommended to use \"hard\" update mode. \n"
|
||||
"But be careful, it erases all personal changes from Allor repository.")
|
||||
|
||||
elif update_mode == "hard":
|
||||
@@ -109,9 +112,8 @@ class Update:
|
||||
|
||||
return
|
||||
|
||||
self.__logger.info("Update complete.")
|
||||
self.__logger.info("Updates installed successfully.", self.__config["logger"]["install_complete"])
|
||||
|
||||
self.__update_timestamp()
|
||||
|
||||
except ImportError:
|
||||
self.__logger.error("GitPython is not installed.")
|
||||
else:
|
||||
self.__logger.error("Update canceled because GitPython is not installed.")
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
|
||||
for /f %%i in ('git rev-parse --abbrev-ref HEAD') do set branch=%%i
|
||||
for /f "delims=" %%i in ('git log -1 --pretty=%%B') do set commit=%%i
|
||||
for /f %%i in ('git rev-parse --short HEAD') do set hex=%%i
|
||||
|
||||
echo {\"branch\": \"%branch%\", \"commit\": \"%commit%\", \"hex\": \"%hex%\"} > info.json
|
||||
@@ -0,0 +1 @@
|
||||
{"branch": "main", "commit": "Split Loader.py", "hex": "14bff6a"}
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
branch=$(git rev-parse --abbrev-ref HEAD)
|
||||
commit=$(git log -1 --pretty=%B)
|
||||
hex=$(git rev-parse --short HEAD)
|
||||
|
||||
echo "{\"branch\": \"$branch\", \"commit\": \"$commit\", \"hex\": \"$hex\"}" > info.json
|
||||
+11
-6
@@ -20,17 +20,22 @@
|
||||
"debug": false
|
||||
},
|
||||
"updates": {
|
||||
"update_frequency": "day",
|
||||
"notify_if_has_new_updates": true,
|
||||
"notify_if_no_new_updates": true,
|
||||
"auto_update": true,
|
||||
"search_frequency": "day",
|
||||
"install_update": true,
|
||||
"branch_name": "main",
|
||||
"update_mode": "soft",
|
||||
"confirm_unstable": false
|
||||
"update_mode": "soft"
|
||||
},
|
||||
"fonts": {
|
||||
"folder_path": "comfy_extras/fonts",
|
||||
"system_fonts": false,
|
||||
"user_fonts": false
|
||||
},
|
||||
"logger": {
|
||||
"confirm_unstable": false,
|
||||
"updates_search": true,
|
||||
"install_complete": true,
|
||||
"modules_enabled": true,
|
||||
"nodes_loaded": true,
|
||||
"nodes_overridden": true
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user