Skip to content

Commit

Permalink
Merge pull request #140 from AIGODLIKE/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
KarryCharon authored Dec 12, 2024
2 parents 208915a + 7c9e3d9 commit d065baf
Show file tree
Hide file tree
Showing 113 changed files with 15,718 additions and 467 deletions.
3 changes: 2 additions & 1 deletion SDNode/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from .tree import rtnode_reg, rtnode_unreg
from .nodegroup import nodegroup_reg, nodegroup_unreg
from .operators import ops_register, ops_unregister
from .manager import TaskManager, Task, FakeServer
from .custom_support import crystools_monitor
try:
from . import aiprompt
from . import node_process
except Exception as e:
import traceback
traceback.print_exc()
traceback.print_exc()
125 changes: 93 additions & 32 deletions SDNode/blueprints.py

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions SDNode/custom_nodes/Cup-ClipBoard/cup_clipboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -2101,7 +2101,7 @@ const ext = {
var data = window.app.graph.serialize();
navigator.clipboard.writeText(JSON.stringify(data));
},
tooltip: "PasteTree",
tooltip: "CopyTree",
content: "",
classList: "clipbord-copy-button comfyui-button"
});
Expand All @@ -2110,7 +2110,7 @@ const ext = {
action: () => {
navigator.clipboard.readText().then(ext.paste);
},
tooltip: "CopyTree",
tooltip: "PasteTree",
content: "",
classList: "clipbord-paste-button comfyui-button"
});
Expand Down
10 changes: 6 additions & 4 deletions SDNode/custom_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def f(data, mtype):
Timer.put((f, data, mtype))
return True

def draw(self, layout: bpy.types.UILayout, ctxt=""):
def draw(self, layout: bpy.types.UILayout, ctxt="", use_region_width=True):
from . import TaskManager
if self.enable:
cp = bpy.context.screen.sdn_custom
Expand All @@ -187,9 +187,11 @@ def draw(self, layout: bpy.types.UILayout, ctxt=""):
import blf
per = prog["value"] / prog["max"]
content = f"{per*100:3.0f}% "
lnum = int(bpy.context.region.width / bpy.context.preferences.view.ui_scale / 7 - 21)
lnum = int(lnum * 0.3)
lnum = int((bpy.context.region.width - blf.dimensions(0, content)[0]) / blf.dimensions(0, "█")[0]) - 10
lnum = 20
if use_region_width:
lnum = int(bpy.context.region.width / bpy.context.preferences.view.ui_scale / 7 - 21)
lnum = int(lnum * 0.3)
lnum = int((bpy.context.region.width - blf.dimensions(0, content)[0]) / blf.dimensions(0, "█")[0]) - 10
v = int(per * lnum)
content = content + "█" * v + "░" * (lnum - v)
row = layout.row()
Expand Down
5 changes: 5 additions & 0 deletions SDNode/history/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from pathlib import Path
from ...utils import read_json


class History:
path = Path(__file__).parent.joinpath("history.json")
num = 20
Expand Down Expand Up @@ -59,3 +60,7 @@ def update_timer():
@staticmethod
def register_timer():
bpy.app.timers.register(History.update_timer, persistent=True)

@staticmethod
def unregister_timer():
bpy.app.timers.unregister(History.update_timer)
55 changes: 49 additions & 6 deletions SDNode/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import aud
from platform import system
import struct
from ast import literal_eval
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from shutil import rmtree
Expand All @@ -19,6 +20,7 @@
from subprocess import Popen, PIPE, STDOUT
from pathlib import Path
from queue import Queue
from .utils import WindowLogger
from ..utils import rmtree as rt, logger, _T, PkgInstaller, update_screen
from ..timer import Timer
from ..preference import get_pref
Expand Down Expand Up @@ -150,9 +152,18 @@ class ErrType:

def get_print(self, info):
etype = info["type"]
if isinstance(etype, str) and etype.endswith("cup.CupException"):
info = literal_eval(info["message"])
etype = info["type"]
func = getattr(self, etype, self.unknown)
return func(info)

def sdn_no_image_provided(self, info):
return self.__print__(info)

def sdn_image_not_found(self, info):
return self.__print__(info)

def unknown(self, info):
if self.WITH_PRINT:
print(info)
Expand All @@ -179,8 +190,10 @@ def __print__(self, info):
info_list = []
if msg:
info_list.append(msg)
WindowLogger.push_log(msg)
if dt:
info_list.append(dt)
WindowLogger.push_log(dt)
return info_list

def required_input_missing(self, info):
Expand Down Expand Up @@ -412,7 +425,8 @@ def node_error_parse(self):
node_errors = self.error_info["node_errors"]
import bpy
from .utils import get_tree
logger.error("Node Error Parse")
logger.error(_T("Node Error Parse"))
WindowLogger.push_log(_T("Node Error Parse"))
for sc in bpy.data.screens:
try:
tree = get_tree(screen=sc)
Expand Down Expand Up @@ -623,20 +637,23 @@ def run(self) -> bool:
pidpath = Path(__file__).parent / "pid"
if pidpath.exists():
self.force_kill(pidpath.read_text())
pidpath.unlink()
pidpath.unlink(missing_ok=True)

pref = get_pref()
model_path = pref.model_path
if not model_path or not Path(model_path).exists():
logger.error(_T("ComfyUI Path Not Found"))
TaskManager.put_error_msg(_T("ComfyUI Path Not Found"))
WindowLogger.push_log(_T("ComfyUI Path Not Found"))
return
logger.debug("%s: %s", _T("Model Path"), model_path)
WindowLogger.push_log("%s: %s", _T("Model Path"), model_path)
python = pref.get_python()
if pref.install_deps:
self.run_pre()

logger.warning(_T("Server Launching"))
WindowLogger.push_log(_T("Server Launching"))
if sys.platform == "win32" and not python.exists():
logger.error("%s:", _T("python interpreter not found"))
logger.error(" ↳%s:", _T("Ensure that the python_embeded located in the same level as ComfyUI dir"))
Expand All @@ -646,6 +663,14 @@ def run(self) -> bool:
logger.error(" │ ├─ python.exe")
logger.error(" │ └─ ...")
logger.error(" └─ ...")
WindowLogger.push_log("%s:", _T("python interpreter not found"))
WindowLogger.push_log(" ↳%s:", _T("Ensure that the python_embeded located in the same level as ComfyUI dir"))
WindowLogger.push_log(" SomeDirectory")
WindowLogger.push_log(" ├─ ComfyUI")
WindowLogger.push_log(" ├─ python_embeded")
WindowLogger.push_log(" │ ├─ python.exe")
WindowLogger.push_log(" │ └─ ...")
WindowLogger.push_log(" └─ ...")
return

# custom_nodes
Expand All @@ -669,7 +694,7 @@ def run(self) -> bool:
t = t.replace("FORCE_LOG = False", f"FORCE_LOG = {get_pref().force_log}")
Path(model_path).joinpath("custom_nodes", file.name, cup_py.name).write_text(t, encoding="utf-8")
if old_cup_py.exists():
Path(model_path).joinpath("custom_nodes", cup_py.name).unlink()
Path(model_path).joinpath("custom_nodes", cup_py.name).unlink(missing_ok=True)
except Exception as e:
# 可能会拷贝失败(权限问题)
...
Expand Down Expand Up @@ -703,7 +728,7 @@ def close(self):
pidpath = Path(__file__).parent / "pid"
if pidpath.exists():
self.force_kill(pidpath.read_text())
pidpath.unlink()
pidpath.unlink(missing_ok=True)

if self.child:
self.child.kill()
Expand All @@ -720,7 +745,7 @@ def wait_connect(self) -> bool:
update_screen()
import requests
try:
if requests.get(f"{self.get_url()}/object_info", proxies={"http": None, "https": None}, timeout=1).status_code == 200:
if requests.get(f"{self.get_url()}/object_info", proxies={"http": None, "https": None}, timeout=5).status_code == 200:
get_pref().preview_method = get_pref().preview_method
return True
except requests.exceptions.ConnectionError:
Expand Down Expand Up @@ -961,10 +986,12 @@ def init_server(fake=False, callback=lambda: ...):
running = TaskManager.server.run()
if not TaskManager.server.exited() and running:
logger.warning(_T("Server Launched"))
WindowLogger.push_log(_T("Server Launched"))
TaskManager.start_polling()
callback()
else:
logger.error(_T("Server Launch Failed"))
WindowLogger.push_log(_T("Server Launch Failed"))
TaskManager.server.close()
return running

Expand Down Expand Up @@ -992,10 +1019,14 @@ def close_server():
@staticmethod
def push_task(task, pre=None, post=None, tree=None):
logger.debug(_T('Add Task'))
WindowLogger.push_log(_T('Add Task'))
if not TaskManager.is_launched():
TaskManager.put_error_msg(_T("Server Not Launched, Add Task Failed"))
WindowLogger.push_log(_T("Server Not Launched, Add Task Failed"))
TaskManager.put_error_msg(_T("Please Check ComfyUI Directory"))
WindowLogger.push_log(_T("Please Check ComfyUI Directory"))
logger.error(_T("Server Not Launched"))
WindowLogger.push_log(_T("Server Not Launched"))
return
TaskManager.task_queue.put(Task(task, pre=pre, post=post, tree=tree))

Expand Down Expand Up @@ -1055,6 +1086,7 @@ def poll_task():
task = TaskManager.task_queue.get()
TaskManager.progress = {'value': 0, 'max': 1}
logger.debug(_T("Submit Task"))
WindowLogger.push_log(_T("Submit Task"))
TaskManager.cur_task = task
try:
TaskManager.submit(task)
Expand Down Expand Up @@ -1088,6 +1120,7 @@ def submit(task: Task):
def queue_task(task: dict):
res = TaskManager.query_server_task()
logger.debug("P/R: %s/%s", len(res["queue_pending"]), len(res["queue_running"]))
WindowLogger.push_log("P/R: %s/%s", len(res["queue_pending"]), len(res["queue_running"]))

api = task.get("api")
if api == "prompt":
Expand Down Expand Up @@ -1220,16 +1253,23 @@ def on_message(ws, message):
n = data.get("node", "")
if n:
logger.debug("%s: %s", _T("Executing Node"), n)
WindowLogger.push_log("%s: %s", _T("Executing Node"), n)
elif mtype == "execution_start":
...
elif mtype == "execution_cached":
logger.debug("%s: %s", _T("Execution Cached"), data.get("nodes", ""))
elif mtype == "status":
WindowLogger.push_log("%s: %s", _T("Execution Cached"), data.get("nodes", ""))
elif mtype == "executed":
...
elif mtype == "execution_success":
...
elif mtype == "execution_error":
...
elif mtype == "status":
...
elif mtype != "progress":
logger.debug("%s: %s", _T("Message Type"), mtype)
WindowLogger.push_log("%s: %s", _T("Message Type"), mtype)

Timer.put(update_screen)

Expand Down Expand Up @@ -1273,6 +1313,7 @@ def on_message(ws, message):
TaskManager.progress_bar = 0
tm.push_res(data)
logger.warning("%s: %s", _T("Ran Node"), data["node"])
WindowLogger.push_log("%s: %s", _T("Ran Node"), data["node"])
elif mtype == "execution_error":
_msg = data.get("message", None)
if not _msg:
Expand All @@ -1298,6 +1339,7 @@ def on_message(ws, message):
...
elif mtype == "execution_success":
logger.warning("%s: %s", _T("Execute Node Success"), data["node"])
WindowLogger.push_log("%s: %s", _T("Execute Node Success"), data["node"])
elif mtype == "execution_interrupted":
{"type": "execution_interrupted",
"data": {"prompt_id": "e1f3cbf9-4b83-47cf-95c3-9f9a76ab5508",
Expand Down Expand Up @@ -1331,6 +1373,7 @@ def on_message(ws, message):
except ConnectionClosedError:
...
logger.debug(_T("Poll Result Thread Exit"))
# WindowLogger.push_log(_T("Poll Result Thread Exit")) # 可能是blender退出, 会导致crash
TaskManager.ws = None
if TaskManager.server.is_launched():
Timer.put((TaskManager.restart_server, True))
Expand Down
Loading

0 comments on commit d065baf

Please sign in to comment.