-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathutils.py
2580 lines (2437 loc) · 97 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import struct
import queue
import platform
import time
import re
import json
import bpy
from pathlib import Path
from threading import Thread
from functools import lru_cache
from urllib.parse import urlparse
from ast import literal_eval
from .kclogger import logger
from .translations import LANG_TEXT
from .timer import Timer
from .datas import IMG_SUFFIX, get_bl_version
translation = {}
addon_bl_info = {}
def get_bl_info():
return addon_bl_info
def popup_folder(path: Path):
import os
if platform.system() == "Windows":
if path.is_file():
path = path.parent
path = path.as_posix()
os.startfile(path)
else:
os.system(f"open {path}")
def get_ai_mat_tree(obj: bpy.types.Object):
if not obj or obj.type != "MESH":
return None
if hasattr(obj, "ai_mat_tree"):
return getattr(obj, "ai_mat_tree")
tree_name = obj.get("AI_Mat_Gen", "")
if not tree_name:
return None
sdn_time_code = obj.get("AI_Mat_Gen_Id", "-1")
tree = bpy.data.node_groups.get(tree_name, None)
if not tree or tree.get("sdn_time_code", "0") != sdn_time_code:
for ng in bpy.data.node_groups:
if ng.get("sdn_time_code", "0") == sdn_time_code:
return ng
return None
return tree
def set_ai_mat_tree(obj: bpy.types.Object, tree: bpy.types.NodeTree):
obj["AI_Mat_Gen"] = tree.name
tree.set_sdn_time_code()
obj["AI_Mat_Gen_Id"] = tree.sdn_time_code
def read_json(path: Path | str) -> dict:
import json
encodings = ["utf8", "gbk"]
for encoding in encodings:
try:
return json.loads(Path(path).read_text(encoding=encoding))
except UnicodeDecodeError:
continue
except json.JSONDecodeError:
continue
return {}
def rmtree(path: Path):
if path.is_file():
path.unlink()
elif path.is_dir():
for child in path.iterdir():
rmtree(child)
try:
path.rmdir() # nas 的共享盘可能会有残留
except BaseException:
...
def get_addon_name():
return "AI Node" + get_bl_version()
def _T(word):
if not isinstance(word, str):
return word
import bpy
from bpy.app.translations import pgettext
locale = bpy.context.preferences.view.language
culture = translation.setdefault(locale, {})
if t := culture.get(word):
return t
def f(word):
culture[word] = pgettext(word)
Timer.put((f, word))
return LANG_TEXT.get(locale, {}).get(word, word)
logger.set_translate(_T)
def _T2(word):
import bpy
from .translations.translation import REPLACE_DICT
locale = bpy.context.preferences.view.language
return REPLACE_DICT.get(locale, {}).get(word, word)
def update_screen():
try:
import bpy
for area in bpy.context.screen.areas:
area.tag_redraw()
bpy.context.workspace.status_text_set_internal(None)
except BaseException:
...
def update_node_editor():
try:
import bpy
for area in bpy.context.screen.areas:
for space in area.spaces:
if space.type != "NODE_EDITOR":
continue
space.node_tree = space.node_tree
if area.type == "NODE_EDITOR":
area.tag_redraw()
except Exception:
...
def clear_cache(d=None):
from shutil import rmtree as shutil_rmtree
if not d:
clear_cache(Path(__file__).parent)
else:
for file in Path(d).iterdir():
if not file.is_dir():
continue
clear_cache(file)
if file.name == "__pycache__":
shutil_rmtree(file)
def rgb2hex(r, g, b, *args):
hex_val = f"#{int(r*256):02x}{int(g*256):02x}{int(b*256):02x}"
return hex_val
def hex2rgb(hex_val):
hex_val = hex_val.lstrip('#')
if len(hex_val) == 3:
return [int(h, 16) / 16 for h in hex_val]
return [int(hex_val[i:i + 2], 16) / 256 for i in (0, 2, 4)]
class PrevMgr:
__PREV__ = {}
@staticmethod
def new():
import bpy.utils.previews
import random
prev = bpy.utils.previews.new()
while (i := random.randint(0, 999999999)) in PrevMgr.__PREV__:
continue
PrevMgr.__PREV__[i] = prev
return prev
@staticmethod
def remove(prev):
import bpy.utils.previews
bpy.utils.previews.remove(prev)
@staticmethod
def clear():
for prev in PrevMgr.__PREV__.values():
prev.clear()
prev.close()
PrevMgr.__PREV__.clear()
def __del__():
PrevMgr.clear()
class MetaIn(type):
def __contains__(cls, name):
return cls.__contains__(cls, name)
class Icon(metaclass=MetaIn):
PREV_DICT = PrevMgr.new()
NONE_IMAGE = ""
IMG_STATUS = {}
PIX_STATUS = {}
PATH2BPY = {}
ENABLE_HQ_PREVIEW = False
INSTANCE = None
def __init__(self) -> None:
if Icon.NONE_IMAGE and Icon.NONE_IMAGE not in Icon:
Icon.NONE_IMAGE = FSWatcher.to_str(Icon.NONE_IMAGE)
self.reg_icon(Icon.NONE_IMAGE)
def __new__(cls, *args, **kwargs):
if cls.INSTANCE is None:
cls.INSTANCE = object.__new__(cls, *args, **kwargs)
return cls.INSTANCE
@staticmethod
def update_path2bpy():
import bpy
Icon.PATH2BPY.clear()
for i in bpy.data.images:
Icon.PATH2BPY[FSWatcher.to_str(i.filepath)] = i
@staticmethod
def apply_alpha(img):
if img.file_format != "PNG" or img.channels < 4:
return
# 预乘alpha 到rgb
import numpy as np
pixels = np.zeros(img.size[0] * img.size[1] * 4, dtype=np.float32)
img.pixels.foreach_get(pixels)
sized_pixels = pixels.reshape(-1, 4)
sized_pixels[:, :3] *= sized_pixels[:, 3].reshape(-1, 1)
img.pixels.foreach_set(pixels)
@staticmethod
def clear():
Icon.PREV_DICT.clear()
Icon.IMG_STATUS.clear()
Icon.PIX_STATUS.clear()
Icon.PATH2BPY.clear()
Icon.reg_icon(Icon.NONE_IMAGE)
@staticmethod
def set_hq_preview():
from .preference import get_pref
Icon.ENABLE_HQ_PREVIEW = get_pref().enable_hq_preview
@staticmethod
def try_mark_image(path) -> bool:
p = FSWatcher.to_path(path)
path = FSWatcher.to_str(path)
if not p.exists():
return False
if Icon.IMG_STATUS.get(path, -1) == p.stat().st_mtime_ns:
return False
return True
@staticmethod
def can_mark_image(path) -> bool:
p = FSWatcher.to_path(path)
path = FSWatcher.to_str(path)
if not Icon.try_mark_image(p):
return False
Icon.IMG_STATUS[path] = p.stat().st_mtime_ns
return True
@staticmethod
def can_mark_pixel(prev, name) -> bool:
name = FSWatcher.to_str(name)
if Icon.PIX_STATUS.get(name) == hash(prev.pixels):
return False
Icon.PIX_STATUS[name] = hash(prev.pixels)
return True
@staticmethod
def remove_mark(name) -> bool:
name = FSWatcher.to_str(name)
Icon.IMG_STATUS.pop(name)
Icon.PIX_STATUS.pop(name)
Icon.PREV_DICT.pop(name)
return True
@staticmethod
def reg_none(none: Path):
none = FSWatcher.to_str(none)
if none in Icon:
return
Icon.NONE_IMAGE = none
Icon.reg_icon(Icon.NONE_IMAGE)
@staticmethod
def reg_icon(path, reload=False, hq=False):
path = FSWatcher.to_str(path)
if not Icon.can_mark_image(path):
return Icon[path]
if Icon.ENABLE_HQ_PREVIEW and hq:
try:
Icon.reg_icon_hq(path)
except BaseException:
Timer.put((Icon.reg_icon_hq, path))
return Icon[path]
else:
if path not in Icon:
Icon.PREV_DICT.load(path, path, 'IMAGE')
if reload:
Timer.put(Icon.PREV_DICT[path].reload)
return Icon[path]
@staticmethod
def reg_icon_hq(path):
import bpy
p = FSWatcher.to_path(path)
path = FSWatcher.to_str(path)
if path in Icon:
return
if p.exists() and p.suffix.lower() in IMG_SUFFIX:
img = bpy.data.images.load(path)
Icon.apply_alpha(img)
Icon.reg_icon_by_pixel(img, path)
Timer.put((bpy.data.images.remove, img)) # 直接使用 bpy.data.images.remove 会导致卡死
@staticmethod
def find_image(path):
img = Icon.PATH2BPY.get(FSWatcher.to_str(path), None)
if not img:
return None
try:
_ = img.name # hack ref detect
return img
except ReferenceError:
Icon.update_path2bpy()
return None
@staticmethod
def load_icon(path):
import bpy
p = FSWatcher.to_path(path)
path = FSWatcher.to_str(path)
# ctrl + z 导致bpy.data中的图像被删除
if path not in Icon.PATH2BPY:
Icon.IMG_STATUS.pop(path, None)
if not Icon.can_mark_image(path):
return
# if p.name[:63] in bpy.data.images:
# img = bpy.data.images[p.name[:63]]
# Icon.update_icon_pixel(img.name, img)
if img := Icon.find_image(path):
Icon.update_icon_pixel(path, img)
return img
elif p.suffix.lower() in IMG_SUFFIX:
img = bpy.data.images.load(path)
img.filepath = path
Icon.apply_alpha(img)
Icon.update_path2bpy()
# img.name = path
return img
@staticmethod
def reg_icon_by_pixel(prev, name):
name = FSWatcher.to_str(name)
if not Icon.can_mark_pixel(prev, name):
return
if name in Icon:
return
p = Icon.PREV_DICT.new(name)
p.icon_size = (32, 32)
p.image_size = (prev.size[0], prev.size[1])
p.image_pixels_float[:] = prev.pixels[:]
@staticmethod
def get_icon_id(name: Path):
p = Icon.PREV_DICT.get(FSWatcher.to_str(name), None)
if not p:
p = Icon.PREV_DICT.get(FSWatcher.to_str(Icon.NONE_IMAGE), None)
return p.icon_id if p else 0
@staticmethod
def update_icon_pixel(name, prev):
"""
更新bpy.data.image 时一并更新(因为pixel 的hash 不变)
"""
prev.reload()
p = Icon.PREV_DICT.get(name, None)
if not p:
# logger.error("No")
return
p.icon_size = (32, 32)
p.image_size = (prev.size[0], prev.size[1])
p.image_pixels_float[:] = prev.pixels[:]
def __getitem__(self, name):
return Icon.get_icon_id(name)
def __contains__(self, name):
return FSWatcher.to_str(name) in Icon.PREV_DICT
def __class_getitem__(cls, name):
return cls.__getitem__(cls, name)
class PngParse:
@staticmethod
def read_head(pngpath):
with open(pngpath, 'rb') as f:
png_header = f.read(25)
file_sig, ihdr_sig, width, height, bit_depth, color_type, \
compression_method, filter_method, interlace_method = \
struct.unpack('>8s4sIIBBBBB', png_header)
# 输出 PNG 文件头
_ = {
"PNG file signature": file_sig,
"IHDR_signature": ihdr_sig,
"Image_size": [width, height],
"Bit_depth": bit_depth,
"Color_type": color_type,
"Compression_method": compression_method,
"Filter_method": filter_method,
"Interlace_method": interlace_method
}
@staticmethod
def read_text_chunk(pngpath) -> dict[str, str]:
data = {}
with open(pngpath, 'rb') as file:
signature = file.read(8)
if signature != b'\x89PNG\r\n\x1a\n':
print('Error: Not a PNG file')
return data
# IDHR, PLTE, sRGB, tEXt
while True:
length_bytes = file.read(4)
length = struct.unpack('>I', length_bytes)[0] # Read chunk length (4 bytes)
chunk_type = file.read(4) # Read chunk type (4 bytes)
chunk_data = file.read(length) # Read chunk data (length bytes)
_ = file.read(4) # Read CRC (4 bytes)
if chunk_type in {b'IHDR', b'PLTE'}: # header and Palette
continue
elif chunk_type == b'tEXt':
keyword, text = chunk_data.decode().split('\0', 1)
data[keyword] = text
elif chunk_type == b'IEND':
break
return data
class PkgInstaller:
source = [
"https://mirrors.aliyun.com/pypi/simple/",
"https://pypi.tuna.tsinghua.edu.cn/simple/",
"https://pypi.mirrors.ustc.edu.cn/simple/",
"https://pypi.python.org/simple/",
"https://pypi.org/simple",
]
fast_url = ""
@staticmethod
def select_pip_source():
if not PkgInstaller.fast_url:
import requests
t, PkgInstaller.fast_url = 999, PkgInstaller.source[0]
for url in PkgInstaller.source:
try:
tping = requests.get(url, timeout=1).elapsed.total_seconds()
except Exception as e:
logger.warning(e)
continue
if tping < 0.1:
PkgInstaller.fast_url = url
break
if tping < t:
t, PkgInstaller.fast_url = tping, url
return PkgInstaller.fast_url
@staticmethod
def is_installed(package):
import importlib
try:
return importlib.import_module(package)
except ModuleNotFoundError:
return False
@staticmethod
def prepare_pip():
import ensurepip
if PkgInstaller.is_installed("pip"):
return True
try:
ensurepip.bootstrap()
return True
except BaseException:
...
return False
@staticmethod
def try_install(*packages):
if not PkgInstaller.prepare_pip():
return False
need = [pkg for pkg in packages if not PkgInstaller.is_installed(pkg)]
from pip._internal import main
if need:
url = PkgInstaller.select_pip_source()
for pkg in need:
try:
site = urlparse(url)
# 避免build
command = ['install', pkg, "-i", url, "--prefer-binary"]
command.append("--trusted-host")
command.append(site.netloc)
main(command)
if not PkgInstaller.is_installed(pkg):
return False
except Exception:
return False
return True
class FSWatcher:
"""
监听文件/文件夹变化的工具类
register: 注册监听, 传入路径和回调函数(可空)
unregister: 注销监听
run: 监听循环, 使用单例,只在第一次初始化时调用
stop: 停止监听, 释放资源
consume_change: 消费变化, 当监听对象发生变化时记录为changed, 主动消费后置False, 用于自定义回调函数
"""
_watcher_path: dict[Path, bool] = {}
_watcher_stat = {}
_watcher_callback = {}
_watcher_queue = queue.Queue()
_running = False
@staticmethod
def init() -> None:
FSWatcher._run()
@staticmethod
def register(path, callback=None):
path = FSWatcher.to_path(path)
if path in FSWatcher._watcher_path:
return
FSWatcher._watcher_path[path] = False
FSWatcher._watcher_callback[path] = callback
@staticmethod
def unregister(path):
path = FSWatcher.to_path(path)
FSWatcher._watcher_path.pop(path)
FSWatcher._watcher_callback.pop(path)
@staticmethod
def _run():
if FSWatcher._running:
return
FSWatcher._running = True
Thread(target=FSWatcher._loop, daemon=True).start()
Thread(target=FSWatcher._run_ex, daemon=True).start()
@staticmethod
def _run_ex():
while FSWatcher._running:
try:
path = FSWatcher._watcher_queue.get(timeout=0.1)
if path not in FSWatcher._watcher_path:
continue
if callback := FSWatcher._watcher_callback[path]:
callback(path)
except queue.Empty:
pass
@staticmethod
def _loop():
"""
监听所有注册的路径, 有变化时记录为changed
"""
while FSWatcher._running:
# list() avoid changed while iterating
for path, changed in list(FSWatcher._watcher_path.items()):
if changed:
continue
if not path.exists():
continue
mtime = path.stat().st_mtime_ns
if FSWatcher._watcher_stat.get(path, None) == mtime:
continue
FSWatcher._watcher_stat[path] = mtime
FSWatcher._watcher_path[path] = True
FSWatcher._watcher_queue.put(path)
time.sleep(0.5)
@staticmethod
def stop():
FSWatcher._watcher_queue.put(None)
FSWatcher._running = False
@staticmethod
def consume_change(path) -> bool:
path = FSWatcher.to_path(path)
if path in FSWatcher._watcher_path and FSWatcher._watcher_path[path]:
FSWatcher._watcher_path[path] = False
return True
return False
@lru_cache
@staticmethod
def get_nas_mapping():
if platform.system() != "Windows":
return {}
import subprocess
try:
result = subprocess.run("net use", capture_output=True, text=True, encoding="gbk", check=True)
except subprocess.CalledProcessError as e:
logger.warning(e)
return {}
if result.returncode != 0 or result.stdout is None:
return {}
nas_mapping = {}
try:
lines = result.stdout.strip().split("\n")[4:]
for line in lines:
columns = line.split()
if len(columns) < 3:
continue
local_drive = columns[1] + "/"
nas_path = Path(columns[2]).resolve().as_posix()
nas_mapping[local_drive] = nas_path
except Exception:
...
return nas_mapping
@lru_cache(maxsize=1024)
@staticmethod
def to_str(path: Path):
p = Path(path)
try:
res_str = p.resolve().as_posix()
except FileNotFoundError as e:
res_str = p.as_posix()
logger.warning(e)
# 处理nas路径
for local_drive, nas_path in FSWatcher.get_nas_mapping().items():
if not res_str.startswith(nas_path):
continue
return res_str.replace(nas_path, local_drive)
return res_str
@lru_cache(maxsize=1024)
@staticmethod
def to_path(path: Path):
return Path(path)
class ScopeTimer:
def __init__(self, name: str = "", prt=print):
self.name = name
self.time_start = time.time()
self.echo = prt
def __del__(self):
self.echo(f"{self.name} cost {time.time() - self.time_start:.4f}s")
class CtxTimer:
def __init__(self, name: str = "", prt=print):
self.name = name
self.time_start = time.time()
self.echo = prt
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.echo(f"{self.name} cost {time.time() - self.time_start:.4f}s")
class WebUIToComfyUI:
SAMPLERNAME_W2C = {
"Euler": "euler",
"Euler a": "euler_ancestral",
"Heun": "heun",
"DPM fast": "dpm_fast",
"DPM adaptive": "dpm_adaptive",
"DPM2": "dpm_2",
"DPM2 a": "dpm_2_ancestral",
"DPM++ 2M": "dpmpp_2m",
"DPM++ SDE": "dpmpp_sde_gpu",
"DPM++ 2M SDE": "dpmpp_2m_sde_gpu",
"DPM++ 3M SDE": "dpmpp_3m_sde",
"DDIM": "ddim",
"LMS": "lms",
"LCM": "LCM",
"UniPC": "uni_pc",
}
SCHEDULERNAME_W2C = {
"Automatic": "normal",
"Karras": "karras",
"Exponential": "exponential",
"SGM Uniform": "sgm_uniform",
}
PREPROCESSOR_W2C = {
"animal_openpose": "AnimalPosePreprocessor",
"blur_gaussian": "*TilePreprocessor",
"canny": "CannyEdgePreprocessor",
"densepose (pruple bg & purple torso)": "DensePosePreprocessor",
"densepose_parula (black bg & blue torso)": "DensePosePreprocessor",
"depth_anything": "DepthAnythingPreprocessor",
"depth_anything_v2": "DepthAnythingV2Preprocessor",
"depth_hand_refiner": "MeshGraphormer+ImpactDetector-DepthMapPreprocessor",
"depth_leres": "LeReS-DepthMapPreprocessor",
"depth_leres++": "*LeReS-DepthMapPreprocessor",
"depth_midas": "MiDaS-DepthMapPreprocessor",
"depth_zoe": "Zoe-DepthMapPreprocessor",
"dw_openpose_full": "DWPreprocessor",
"facexlib": "",
"inpaint_global_harmonious": "",
"inpaint_only": "InpaintPreprocessor",
"inpaint_only+lama": "",
"instant_id_face_embedding": "",
"instant_id_face_keypoints": "",
"invert (from white bg & black line)": "ImageInvert",
"ip-adapter-auto": "IPAdapter+IPAdapterUnifiedLoader",
"ip-adapter_clip_g": "IPAdapter+IPAdapterUnifiedLoader",
"ip-adapter_clip_h": "IPAdapter+IPAdapterUnifiedLoader",
"ip-adapter_clip_sdxl_plus_vith": "IPAdapter+IPAdapterUnifiedLoader",
"ip-adapter_face_id": "IPAdapterFaceID+IPAdapterUnifiedLoaderFaceID",
"ip-adapter_face_id_plus": "IPAdapterFaceID+IPAdapterUnifiedLoaderFaceID",
"ip-adapter_pulid": "",
"lineart_anime": "AnimeLineArtPreprocessor",
"lineart_anime_denoise": "",
"lineart_coarse": "LineArtPreprocessor",
"lineart_realistic": "LineArtPreprocessor",
"lineart_standard (from white bg & black line)": "LineartStandardPreprocessor",
"mediapipe_face": "MediaPipe-FaceMeshPreprocessor",
"mlsd": "M-LSDPreprocessor",
"none": "",
"normal_bae": "BAE-NormalMapPreprocessor",
"normal_dsine": "DSINE-NormalMapPreprocessor",
"normal_midas": "MiDaS-NormalMapPreprocessor",
"openpose": "OpenposePreprocessor",
"openpose_face": "OpenposePreprocessor",
"openpose_faceonly": "OpenposePreprocessor",
"openpose_full": "OpenposePreprocessor",
"openpose_hand": "OpenposePreprocessor",
"recolor_intensity": "ImageIntensityDetector",
"recolor_luminance": "ImageLuminanceDetector",
"reference_adain": "",
"reference_adain+attn": "",
"reference_only": "",
"revision_clipvision": "",
"revision_ignore_prompt": "",
"scribble_hed": "FakeScribblePreprocessor",
"scribble_pidinet": "Scribble_PiDiNet_Preprocessor",
"scribble_xdog": "Scribble_XDoG_Preprocessor",
"seg_anime_face": "AnimeFace_SemSegPreprocessor",
"seg_ofade20k": "OneFormer-ADE20K-SemSegPreprocessor",
"seg_ofcoco": "OneFormer-COCO-SemSegPreprocessor",
"seg_ufade20k": "UniFormer-SemSegPreprocessor",
"shuffle": "ShufflePreprocessor",
"softedge_anyline": "",
"softedge_hed": "HEDPreprocessor",
"softedge_hedsafe": "HEDPreprocessor",
"softedge_pidinet": "PiDiNetPreprocessor",
"softedge_pidisafe": "PiDiNetPreprocessor",
"softedge_teed": "TEED_Preprocessor",
"t2ia_color_grid": "ColorPreprocessor",
"t2ia_sketch_pidi": "",
"t2ia_style_clipvision": "",
"threshold": "BinaryPreprocessor",
"tile_colorfix": "",
"tile_colorfix+sharp": "",
"tile_resample": "TilePreprocessor",
}
def __init__(self, text: str = "", ):
self.text: str = text
self.params: dict = {}
self.parse_cn = False
def is_webui_format(self):
return "Negative prompt: " in self.text and "Steps: " in self.text
def get_registered_node_types(self):
from .SDNode.nodes import NodeBase
registered_node_types = {n.class_type: n.__metadata__ for n in NodeBase.__subclasses__()}
return registered_node_types
def with_efficient(self):
registered_node_types = self.get_registered_node_types()
return "Efficient Loader" in registered_node_types and "KSampler (Efficient)" in registered_node_types
def apply_nodes_offset(this, nodes, offset=None):
if offset is None:
return
for node in nodes:
node["pos"][0] += offset[0]
node["pos"][1] += offset[1]
def find_following_nodes(self, wk, node, _nodes=None):
if _nodes is None:
_nodes = []
for out in node.get("outputs", []):
for link_id in out.get("links", []) or []:
_l = next((l for l in wk["links"] if l[0] == link_id), None)
if not _l:
continue
_in = next((n for n in wk["nodes"] if n["id"] == _l[3]), None)
if not _in:
continue
if _in not in _nodes:
_nodes.append(_in)
self.find_following_nodes(wk, _in, _nodes)
return _nodes
def make_link(self, workflow, out_node, out_index, in_node, in_index):
last_link_id = workflow["last_link_id"] + 1
workflow["last_link_id"] = last_link_id
ltype = out_node["outputs"][out_index]["type"] or None
link = [last_link_id, out_node["id"], out_index, in_node["id"], in_index, ltype]
out_node["outputs"][out_index]["links"].append(last_link_id)
old_in_link = in_node["inputs"][in_index]["link"]
if old_in_link and old_in_link != last_link_id:
self.remove_link(workflow, old_in_link)
in_node["inputs"][in_index]["link"] = last_link_id
workflow["links"].append(link)
def remove_link(self, workflow, link_id):
if link_id is None:
return
if link_id == workflow["last_link_id"]:
workflow["last_link_id"] = workflow["last_link_id"] - 1
for i in range(len(workflow["links"])):
link = workflow["links"][i]
if link[0] != link_id:
continue
workflow["links"].pop(i)
return
def remove_node_by_id(self, workflow, node_id):
if not node_id:
return
find_node = None
find_node_index = -1
for i in range(len(workflow["nodes"])):
if (workflow["nodes"][i]["id"] == node_id):
find_node = workflow["nodes"][i]
find_node_index = i
break
if not find_node:
return
# 移除关联的link
for inp in find_node.get("inputs", []):
link_id = inp["link"]
if not link_id:
continue
for node in workflow["nodes"]:
for output in node["outputs"]:
try:
output["links"].remove(link_id)
break
except ValueError:
...
self.remove_link(workflow, link_id)
for out in find_node.get("outputs", []):
for link_id in out.get("links", []):
if link_id is None:
continue
for node in workflow["nodes"]:
for inp in node.get("inputs", []):
inp["link"] = None if inp["link"] == link_id else inp["link"]
self.remove_link(workflow, link_id)
# 移除节点
workflow["nodes"].pop(find_node_index)
def to_comfyui_format(self):
if self.with_efficient():
return self.to_comfyui_format_efficient()
return self.to_comfyui_format_base()
def to_comfyui_format_base(self):
params = self.params.copy()
wk = self.base_workflow()
self.apply_nodes_offset(wk["nodes"], (-200, 63))
np = wk["nodes"][0]
pp = wk["nodes"][1]
empty_image = wk["nodes"][2]
ksampler = wk["nodes"][3]
checkpoint_loader = wk["nodes"][6]
clip_last_layer = wk["nodes"][7]
if "Negative prompt" in params:
np["widgets_values"][0] = params["Negative prompt"]
if "Positive prompt" in params:
pp["widgets_values"][0] = params["Positive prompt"]
if "Size" in params:
width = 512
height = 512
if "x" in params["Size"]:
size_list = params["Size"].split("x")
width = size_list[0]
height = size_list[1]
empty_image["widgets_values"][0] = width
empty_image["widgets_values"][1] = height
if "Seed" in params:
ksampler["widgets_values"][0] = params["Seed"]
if "Steps" in params:
ksampler["widgets_values"][2] = params["Steps"]
if "CFG scale" in params:
ksampler["widgets_values"][3] = params["CFG scale"]
if "Sampler" in params:
sampler_name: str = params["Sampler"]
scheduler_name: str = "normal"
if "Schedule type" in params:
sampler_name = params["Sampler"]
scheduler_name = params["Schedule type"]
else:
# samper存储 sampler_name + " " + scheduler_name
for one_sch_name in self.SCHEDULERNAME_W2C:
if one_sch_name in sampler_name:
scheduler_name = one_sch_name
sampler_name = sampler_name.replace(one_sch_name, "").strip()
break
if sampler_name in self.SAMPLERNAME_W2C:
ksampler["widgets_values"][4] = self.SAMPLERNAME_W2C[sampler_name]
if scheduler_name in self.SCHEDULERNAME_W2C:
ksampler["widgets_values"][5] = self.SCHEDULERNAME_W2C[scheduler_name]
self._gen_control_net(wk, ksampler, pp, np)
if "Denoising strength" in params:
ksampler["widgets_values"][6] = params["Denoising strength"]
if float(params["Denoising strength"]) < 1:
# 图生图, 需要添加图片输入
last_node_id = wk["last_node_id"]
load_image = {
"id": last_node_id + 1,
"type": "LoadImage",
"pos": [250, -110],
"size": [320, 310],
"mode": 0,
"outputs": [
{
"name": "IMAGE",
"type": "IMAGE",
"links": [],
"shape": 3,
"label": "图像",
"slot_index": 0,
},
{
"name": "MASK",
"type": "MASK",
"links": None,
"shape": 3,
"label": "遮罩",
},
],
"properties": {"Node name for S&R": "LoadImage"},
"widgets_values": ["xxx.png", "image"],
}
vae_encode = {
"id": last_node_id + 2,
"type": "VAEEncode",
"pos": [640, 10],
"size": {0: 210, 1: 50},
"mode": 0,
"inputs": [
{
"name": "pixels",
"type": "IMAGE",
"link": 0,
"label": "图像",
},
{
"name": "vae",
"type": "VAE",
"link": None,
"label": "VAE",
},
],
"outputs": [
{
"name": "LATENT",
"type": "LATENT",
"links": [],
"shape": 3,
"label": "Latent",
"slot_index": 0,
},
],
"properties": {"Node name for S&R": "VAEEncode"},
}
wk["nodes"].append(load_image)
wk["nodes"].append(vae_encode)
wk["last_node_id"] = last_node_id + 2