aidenli / ComfyUI_NYJY

ComfyUI自定义节点,提供提示词翻译功能,支持多语言。comfyui custom nodes,translate prompt
Apache License 2.0
82 stars 2 forks source link

`winreg` not available on linux #4

Closed tommitytom closed 2 months ago

tommitytom commented 2 months ago

The inclusion of winreg causes failure on linux

Amit30swgoh commented 2 months ago

Had same problem since im running via Collab so had to edit a code for ensures that the code can run on both Windows and non-Windows platforms without errors.

Updated config.py with Conditional winreg Import:

import os
import json
from inspect import currentframe, stack, getmodule
import time

# Import winreg only if running on Windows
if os.name == 'nt':  # 'nt' indicates Windows
    import winreg
else:
    # Define a mock for winreg to avoid errors on non-Windows platforms
    winreg = None

# 获取系统代理地址
def get_system_proxy():
    if winreg is None:
        print("winreg is not available on this platform. Skipping proxy detection.")
        return None

    try:
        internet_settings = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
        )
        proxy_server, _ = winreg.QueryValueEx(internet_settings, "ProxyServer")
        proxy_enable, _ = winreg.QueryValueEx(internet_settings, "ProxyEnable")
        if proxy_enable:
            return proxy_server
        else:
            return None
    except FileNotFoundError:
        return None

config_template = {
    "Baidu": {"AppId": "", "Secret": ""},
    "joytag": {
        "model_download": "https://hf-mirror.com/fancyfeast/joytag/tree/main",
        "hf_project": "fancyfeast/joytag",
    },
    "Google": {"proxy": "http://localhost:10809"},
}

current_path = os.path.abspath(os.path.dirname(__file__))
config_path = os.path.join(current_path, "../config.json")
config_data = None

def merge_config(src_conf, target_conf):
    result = src_conf.copy()
    for key, value in target_conf.items():
        if key not in result:
            result[key] = value
        else:
            if isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = merge_config(result[key], value)
    return result

def LoadConfig():
    global config_data
    global config_path
    global current_path

    config_data = config_template.copy()

    if os.path.exists(config_path):
        with open(config_path, "r") as f:
            content = f.read()
            config_data = json.loads(content)
            # 合并最新的配置项(当config_template有变动的时候)
            config_data = merge_config(config_data, config_template)

    # 获取系统代理地址,并修改配置文件
    proxy = get_system_proxy()
    if proxy:
        config_data["Google"]["proxy"] = proxy

    with open(config_path, "w") as f:
        f.write(json.dumps(config_data, indent=4))

    current_dir = os.path.dirname(__file__)
    config_data["base_path"] = os.path.dirname(
        current_dir
    )  # os.path.join(current_path, "../")
    return config_data

def print_log(str_msg):
    # f_current_line = str(currentframe().f_back.f_lineno)  # 哪一行调用的此函数
    # mod = getmodule(stack()[1][0])  # 调用函数的信息
    str_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(f"[NYJY][{str_time}][{stack()[1][1]}, line: {stack()[1][2]}]: {str_msg}")

If it still failed then also modify the Init.py and replace the code with :

import importlib.util
import subprocess
import sys
import os
import re

def install_package(full_name, package_name):
    """Installs a package if it's not already installed."""
    try:
        spec = importlib.util.find_spec(package_name)
        if spec is None:
            raise ImportError(f"{package_name} is not installed")
    except ImportError:
        print(f"{package_name} is not installed, installing...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", full_name])
        print(f"{package_name} installation complete.")

def check_and_install_packages():
    """Checks and installs packages listed in requirements.txt."""
    packages = ["pygtrans"]
    for package in packages:
        package_name = re.match(r"^([^\s=<>!]+)", package.strip())
        if package_name:
            install_package(package, package_name.group(1))

# Check and install required packages
check_and_install_packages()

# Import custom nodes
from .nodes.Translate import TranslateNode
from .nodes.JoyTag.JoyTag import JoyTagNode
from .nodes.JoyCaption.JoyCaption import JoyCaptionNode

# Define node mappings
NODE_CLASS_MAPPINGS = {
    "Translate": TranslateNode,
    "JoyTag": JoyTagNode,
    "JoyCaption": JoyCaptionNode,
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "Translate": "Translate (NYJY)",
    "JoyTag": "JoyTag (NYJY)",
    "JoyCaption": "JoyCaption (NYJY)",
}

__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]

Good luck!

aidenli commented 2 months ago

The inclusion of winreg causes failure on linux

Thanks for the feedback, I will look into this issue later. Because I mainly run comfyui on Windows platform, and have not deployed it on Linux platform yet.

aidenli commented 2 months ago

@tommitytom I have fixed the bug, thanks to @Amit30swgoh for providing the code。