-
Notifications
You must be signed in to change notification settings - Fork 12
/
nodes.py
3281 lines (2854 loc) · 101 KB
/
nodes.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
"""
@author: Trung0246
@title: ComfyUI-0246
@nickname: ComfyUI-0246
@description: Random nodes for ComfyUI I made to solve my struggle with ComfyUI (ex: pipe, process). Have varying quality.
"""
# Built-in
import sys
import ast
import random
import json
import copy
import functools
import itertools
import copy
import uuid
import unicodedata
import struct
import inspect
builtins = __import__("builtins")
re = __import__("re")
# Self Code
from . import utils as lib0246
# 3rd Party
import aiohttp.web
import natsort
import regex
import torch
# ComfyUI
import server
import execution
import nodes
import comfy.sd1_clip
import comfy.samplers
comfy_graph = None
comfy_graph_utils = None
wat = None
try:
wat = __import__("wat")
comfy_graph = __import__("comfy_execution.graph").graph
comfy_graph_utils = __import__("comfy_execution.graph_utils").graph_utils
print("\033[95m" + f"{lib0246.HEAD_LOG}Topological Execution is detected." + "\033[0m")
except ModuleNotFoundError:
pass
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
######################################################################################
######################################## IMPL ########################################
######################################################################################
def highway_impl(_prompt, _id, _workflow, _way_in, flag, kwargs):
if isinstance(_prompt, list):
_prompt = _prompt[0]
if isinstance(_id, list):
_id = _id[0]
if isinstance(_workflow, list):
_workflow = _workflow[0]
if isinstance(_way_in, list):
_way_in = _way_in[0]
if _way_in is None:
_way_in = lib0246.RevisionDict()
else:
_way_in = lib0246.RevisionDict(_way_in)
# _way_in._id = _id
# _way_in.purge(_way_in.find(lambda item: item.id == _id))
# Time to let the magic play out
curr_node = next(_ for _ in _workflow["workflow"]["nodes"] if str(_["id"]) == _id)
for i, curr_input in enumerate(curr_node["inputs"]):
if curr_input["name"] in kwargs:
name = _workflow["workflow"]["extra"]["0246.__NAME__"][_id]["inputs"][str(i)]["name"][1:]
if flag:
_way_in[("data", name)] = lib0246.RevisionBatch(*kwargs[curr_input["name"]])
else:
_way_in[("data", name)] = kwargs[curr_input["name"]]
_way_in[("type", name)] = curr_input.get("type", "*") # Sometimes this does not exist. Weird.
res = []
for i, curr_output in enumerate(curr_node["outputs"]):
if curr_output["name"] not in lib0246.BLACKLIST:
name = _workflow["workflow"]["extra"]["0246.__NAME__"][_id]["outputs"][str(i)]["name"][1:]
if ("data", name) in _way_in:
if curr_output.get("links") is None:
res.append([None])
elif curr_output["type"] == "*" or _way_in[("type", name)] == "*" or curr_output["type"] == _way_in[("type", name)]:
res.append(_way_in[("data", name)])
else:
raise Exception(f"Output \"{name}\" is not defined or is not of type \"{curr_output['type']}\". Expected \"{_way_in[('type', name)]}\".")
_way_in[("kind")] = "highway"
_way_in[("id")] = _id
return (_way_in, ) + tuple(res)
def gather_highway_impl(_dict_list, _id):
new_dict = lib0246.RevisionDict()
if _dict_list is None:
return new_dict
if isinstance(_id, list):
_id = _id[0]
for elem in _dict_list:
iter_inst = elem.path_iter(("data", ))
for key in iter_inst:
if ("type", key[1]) not in new_dict:
new_dict[("type", key[1])] = elem[("type", key[1])]
if ("data", key[1]) not in new_dict:
new_dict[("data", key[1])] = lib0246.RevisionBatch()
if isinstance(elem[("data", key[1])], lib0246.RevisionBatch):
new_dict[("data", key[1])].extend(elem[("data", key[1])])
else:
new_dict[("data", key[1])].append(elem[("data", key[1])])
new_dict[("kind")] = "highway"
new_dict[("id")] = _id
return new_dict
def junction_impl(self, _id, _prompt, _workflow, _junc_in, _offset = None, _in_mode = False, _out_mode = False, _offset_mode = False, **kwargs):
if isinstance(_prompt, list):
_prompt = _prompt[0]
if isinstance(_id, list):
_id = _id[0]
if isinstance(_offset, list):
_offset = _offset[0]
if isinstance(_workflow, list):
_workflow = _workflow[0]
if _junc_in is None:
_junc_in = lib0246.RevisionDict()
else:
_junc_in = lib0246.RevisionDict(_junc_in)
# _junc_in._id = _id
# _junc_in.purge(_junc_in.find(lambda item: item.id == _id))
# Pack all data from _junc_in and kwargs together with a specific format
curr_node = next(_ for _ in _workflow["workflow"]["nodes"] if str(_["id"]) == _id)
if _in_mode:
flat_iter = lib0246.FlatIter(kwargs)
for param, (key, value) in lib0246.flat_zip(list(filter(lambda _: _["name"] not in lib0246.BLACKLIST, curr_node["inputs"])), flat_iter):
junction_pack_loop(_junc_in, param["type"], value)
else:
for param, key in zip(list(filter(lambda _: _["name"] not in lib0246.BLACKLIST, curr_node["inputs"])), list(kwargs)):
junction_pack_loop(_junc_in, param["type"], kwargs[key])
# Parse the offset string
if hasattr(self, "_prev_offset") and hasattr(self, "_parsed_offset") and _offset is not None:
if type(_offset) is str:
_offset = ast.literal_eval(_offset)
if _offset["data"] != self._prev_offset:
parsed_offset, err = lib0246.parse_offset(_offset["data"])
if err:
raise Exception(err)
self._prev_offset = _offset["data"]
self._parsed_offset = parsed_offset
# Apply the offset to the junction input
if hasattr(self, "_parsed_offset"):
if self._parsed_offset is None:
raise Exception("Offset is not parsed.")
for elem in self._parsed_offset:
total = _junc_in.path_count(("data", elem[0]))
if total == 0:
raise Exception(f"Type \"{elem[0]}\" in offset string does not available in junction.")
# Check for ops char
if elem[1][0] == '+':
_junc_in[("index", elem[0])] += int(elem[1][1:])
elif elem[1][0] == '-':
_junc_in[("index", elem[0])] -= int(elem[1][1:])
else:
_junc_in[("index", elem[0])] = int(elem[1])
temp = _junc_in[("index", elem[0])]
if temp >= total:
raise Exception(f"Offset \"{elem[1]}\" (total: \"{temp}\") is too large (count: \"{total}\").")
elif temp < 0:
raise Exception(f"Offset \"{elem[1]}\" (total: \"{temp}\") is too small (count: \"{total}\").")
res = []
track = {}
db = {}
if _out_mode:
done_type = {}
for elem in curr_node["outputs"]:
if elem["name"] in lib0246.BLACKLIST:
continue
if elem["type"] in done_type:
# Rotate the list from [11, 22, 33] to [22, 33, 11]
if elem["type"] not in db:
db[elem["type"]] = done_type[elem["type"]]
db[elem["type"]] = (db[elem["type"]][1:] + db[elem["type"]][:1])
res.append(db[elem["type"]])
continue
total = _junc_in.path_count(("data", elem["type"]))
if total == 0:
raise Exception(f"Type \"{elem['type']}\" of output \"{elem['name']}\" does not available in junction.")
offset = _junc_in[("index", elem["type"])]
if offset >= total:
raise Exception(f"Too much type \"{elem['type']}\" being taken or offset \"{offset}\" is too large (count: \"{total}\").")
temp = []
res.append(temp)
for i in range(offset, total):
temp.append(_junc_in[("data", elem["type"], i)])
done_type[elem["type"]] = temp
# Check if every single array in done_type have same length
base_len = -1
base_type = None
for key in done_type:
curr_len = len(done_type[key])
if base_len == -1:
base_len = curr_len
base_type = key
elif curr_len != base_len:
print("\033[93m" + f"{lib0246.HEAD_LOG}WARNING: Type \"{key}\" has different amount (node {_id}, got {curr_len}, want {base_len} from first type \"{base_type}\")." + "\033[0m")
else:
for key in _junc_in.path_iter(("type", )):
track[key[1]] = 0
for elem in curr_node["outputs"]:
if elem["name"] in lib0246.BLACKLIST:
continue
total = _junc_in.path_count(("data", elem["type"]))
if total == 0:
raise Exception(f"Type \"{elem['type']}\" of output \"{elem['name']}\" does not available in junction.")
offset = _junc_in[("index", elem["type"])]
real_index = track[elem["type"]] + offset
if real_index >= total:
raise Exception(f"Too much type \"{elem['type']}\" being taken or offset \"{offset}\" is too large (count: \"{total}\").")
res.append(_junc_in[("data", elem["type"], real_index)])
track[elem["type"]] += 1
_junc_in[("kind")] = "junction"
_junc_in[("id")] = _id
return (_junc_in, ) + tuple(res)
def gather_junction_impl(_dict_list, _id):
new_dict = lib0246.RevisionDict()
if _dict_list is None:
return new_dict
if isinstance(_id, list):
_id = _id[0]
for _dict in _dict_list:
for tuple_key in _dict.path_iter(("data", )):
junction_pack_loop(new_dict, tuple_key[1], _dict[tuple_key])
new_dict[("kind")] = "junction"
new_dict[("id")] = _id
return new_dict
def junction_unpack_raw(
data_dict, param_dict, key_list, regex_inst,
base_dict = {}, type_dict = {}, key_special=("default", "data", "index"),
pack_func=lambda _: _, type_func=lambda _: _,
fill_func=lambda d, k, v: d.setdefault(k, v),
stub_flag=False,
block=1,
):
for key in data_dict:
if key[0] == key_special[2]:
type_dict[type_func(key[1])] = data_dict[key]
for param_key in lib0246.dict_iter(param_dict):
type_dict.setdefault(type_func(lib0246.dict_get(param_dict, param_key)[0]), 0)
block_count = 0
kill_flag = False
def block_evt():
nonlocal block_count
nonlocal kill_flag
kill_flag = True
block_count += 1
return block_count >= block
param_iter = lib0246.cycle_iter(
block_evt,
filter(
lambda _: _[0] in key_list,
lib0246.dict_iter(param_dict)
),
)
while block_count < block or block == sys.maxsize:
try:
param_key = next(param_iter)
param_tuple = lib0246.dict_get(param_dict, param_key)
defaults = {} if len(param_tuple) == 1 else param_tuple[1]
regex_res = regex_inst.match(param_key[-1])
if regex_res is not None and regex_res.lastgroup == "_":
continue
data_key = (key_special[1], type_func(param_tuple[0]), type_dict.get(type_func(param_tuple[0]), 0))
value = None
if data_key in data_dict:
value = data_dict[data_key]
kill_flag = False
elif key_special[0] in defaults and (block < sys.maxsize or stub_flag):
if param_key[-1] in base_dict:
break
value = defaults[key_special[0]]
kill_flag = False
else:
break
fill_func(base_dict, param_key[-1], pack_func(value))
type_dict[type_func(param_tuple[0])] += 1
except StopIteration:
break
if kill_flag:
break
return base_dict
def junction_pack_loop(_junc_in, name, value):
_junc_in[("type", name)] = type(value).__name__
count = _junc_in.path_count(("data", name))
_junc_in[("data", name, count)] = value
if count == 0:
_junc_in[("index", name)] = 0
def trace_node_func(id_stk, linked_node_id):
id_stk.append(str(linked_node_id))
def trace_node(_prompt, _id, _workflow, _input = False, _func = trace_node_func):
id_stk = []
if _input:
for key in _prompt[_id]["inputs"]:
if isinstance(_prompt[_id]["inputs"][key], list) and key != "_event":
id_stk.append(_prompt[_id]["inputs"][key][0])
else:
id_stk.append(_id)
id_res = set()
while len(id_stk) > 0:
curr_id = id_stk.pop(0)
if curr_id not in id_res:
id_res.add(curr_id)
for node in _workflow["workflow"]["nodes"]:
if node["id"] == int(curr_id):
if node.get("outputs"):
for output in node["outputs"]:
if output.get("links"):
for link in output["links"]:
linked_node_id = find_input_node(_workflow["workflow"]["nodes"], link)
if linked_node_id is not None:
_func(id_stk, linked_node_id)
return id_res
def trace_node_back(node_id, dynprompt, upstream):
stack = [node_id]
while len(stack) > 0:
node_id = stack.pop()
node_info = dynprompt.get_node(node_id)
if "inputs" not in node_info:
continue
for k, v in node_info["inputs"].items():
if comfy_graph_utils.is_link(v):
parent_id = v[0]
if parent_id not in upstream:
upstream[parent_id] = []
stack.append(parent_id)
upstream[parent_id].append(node_id)
def trace_node_front(node_id, upstream, contained):
stack = [node_id]
while len(stack) > 0:
node_id = stack.pop()
if node_id not in upstream:
continue
for child_id in upstream[node_id]:
if child_id not in contained:
contained[child_id] = True
stack.append(child_id)
def find_input_node(nodes, link):
for node in nodes:
if node.get("inputs"):
for input in node["inputs"]:
if input["link"] == link:
return node["id"]
return None
class ScriptData(dict):
def __init__(self, data):
super().__init__(data)
def script_node_exec(node_inst, node_name, node_class, node_input, node_args, node_args_base, node_args_hide, node_args_hide_full, **kwargs):
if "pin" in kwargs:
func = getattr(node_inst, getattr(node_class, "FUNCTION"))
real_pin = {k: v for k, v in kwargs["pin"].items() if k in node_args_base}
flag = hasattr(node_class, "INPUT_IS_LIST") and node_class.INPUT_IS_LIST
for key, kind in node_args_hide_full:
match kind:
case "PROMPT":
real_pin[key] = [kwargs["inst"]["prompt"]] if flag else kwargs["inst"]["prompt"]
case "UNIQUE_ID":
real_pin[key] = [kwargs["inst"]["id"][-1]] if flag else kwargs["inst"]["id"][-1]
case "EXTRA_PNGINFO":
real_pin[key] = [kwargs["inst"]["workflow"]] if flag else kwargs["inst"]["workflow"]
if flag:
return lib0246.transpose(func(**real_pin), tuple)
else:
return func(**real_pin)
else:
return (node_class, node_inst, node_name, node_input, node_args, node_args_base, node_args_hide)
def script_rule_slice(func, res, pin, **kwargs):
return res.extend(func(pin=curr_pin[0]) for curr_pin in lib0246.dict_slice(pin))
def script_rule_product(func, res, pin, **kwargs):
return res.extend(func(pin=curr_pin[0]) for curr_pin in lib0246.dict_product(pin))
def script_rule_direct(func, res, pin, **kwargs):
return res.extend(func(pin=pin))
def highway_unpack(pipe_in):
def temp_func(pin, res, **kwargs):
if res is None:
iter_inst = pipe_in.path_iter(("data", ))
for key in iter_inst:
if isinstance(pipe_in[key], lib0246.RevisionBatch):
if key[1] in pin:
pin[key[1]].extend(pipe_in[key])
else:
pin[key[1]] = pipe_in[key]
else:
if key[1] in pin:
pin[key[1]].append(pipe_in[key])
else:
pin[key[1]] = [pipe_in[key]]
return True
return False
return temp_func
def junction_unpack(pipe_in, input_type, regex_inst):
def temp_func(pin, res, **kwargs):
if res is None:
junction_unpack_raw(
pipe_in, input_type,
list(filter(lambda x: x != "hidden", input_type.keys())),
base_dict=pin,
pack_func=lambda _: [_],
type_func=lambda _: "STRING" if isinstance(_, list) else _,
fill_func=lambda d, k, v: d.setdefault(k, []).extend(v),
stub_flag=True,
regex_inst=regex_inst,
block=sys.maxsize,
)
return True
return False
return temp_func
class EventBoolStr(str):
def __ne__(self, other):
return other != "EVENT_TYPE" and other != "BOOL" and other != "BOOLEAN" and other != "toggle"
CLOUD_METHOD = {
"text": None, # Cannot be used as function if None
"pin": None,
"weight": {
"bind": False, # Can affect other clouds if itself is affected
# "many": False, # Can output multiple clouds
"sole": True, # Can only exist once for same kind within a group
},
"rand": {
"bind": True,
# "many": True,
"sole": True,
},
"cycle": {
"bind": True,
# "many": True,
"sole": True,
},
"merge": {
"bind": True,
# "many": False,
"sole": True,
},
}
STR_BRACKET = r"([()])"
STR_REPLACE = r"\\\1"
def group_query_inst(group_dict, group_id, group_list = None, inst_curr = None):
inst_curr = set() if inst_curr is None else inst_curr
group_list = list(group_dict.keys()) if group_list is None else group_list
stack = [group_id]
seen = set()
while len(stack) > 0:
track_group = stack.pop()
if track_group in seen:
continue
seen.add(track_group)
if "group" in group_dict[track_group]:
stack.extend(group_dict[track_group]["group"])
if "inst" in group_dict[track_group]:
for track_inst in group_dict[track_group]["inst"]:
inst_curr.add(track_inst)
return inst_curr
class CloudFunc:
def __init__(self, kind):
self.func = getattr(CloudFunc, f"func_{kind}")
@classmethod
def func_rand(cls, obj, hold, state):
res = []
inst_id = obj.inst[state["index"]]["id"]
if inst_id not in state["data"]:
state["data"][inst_id] = {
"rand": random.Random(),
"seed_mode": [],
"seed_data": [],
"seed_count": 0
}
curr_state = state["data"][inst_id]
curr_state["seed_count"] = len(obj.inst[state["index"]]["widgets_values"][0])
curr_seed_len = len(curr_state["seed_data"])
if curr_state["seed_count"] > curr_seed_len:
curr_state["seed_data"].extend([None] * (curr_state["seed_count"] - curr_seed_len))
curr_state["seed_mode"].extend([None] * (curr_state["seed_count"] - curr_seed_len))
elif curr_state["seed_count"] < curr_seed_len:
curr_state["seed_data"] = curr_state["seed_data"][:curr_state["seed_count"]]
curr_state["seed_mode"] = curr_state["seed_mode"][:curr_state["seed_count"]]
for i, curr_seed, curr_count, curr_order, curr_mode in zip(itertools.count(start=0, step=1), *obj.inst[state["index"]]["widgets_values"]):
if curr_state["seed_data"][i] is None or \
curr_state["seed_mode"][i] != curr_mode or \
state["change"]:
curr_state["seed_data"][i] = curr_seed
curr_state["seed_mode"][i] = curr_mode
curr_state["rand"].seed(curr_seed)
if curr_mode != "fix":
PROMPT_UPDATE.add(state["id"])
else:
match curr_mode:
case "fix":
curr_state["rand"].seed(curr_seed)
case "add":
curr_state["seed_data"][i] += 1
curr_state["rand"].seed(curr_state["seed_data"][i])
case "sub":
curr_state["seed_data"][i] -= 1
curr_state["rand"].seed(curr_state["seed_data"][i])
case _:
# Default to "rand" mode
pass
if curr_mode != "fix":
PROMPT_UPDATE.add(state["id"])
if curr_order:
lib0246.sort_dict_of_list(hold, "index")
res.extend(lib0246.random_order(hold["data"], min(len(hold["data"]), curr_count), curr_state["rand"]))
else:
choice_list: list = copy.copy(hold["data"])
for i in range(curr_count):
curr_choice_idx = curr_state["rand"].randint(0, len(choice_list) - 1)
res.append(choice_list[curr_choice_idx])
choice_list.pop(curr_choice_idx)
for i in range(len(hold["index"])):
hold["index"][i] = None
return res
@classmethod
def func_cycle(cls, obj, hold, state):
res = []
inst_id = obj.inst[state["index"]]["id"]
if inst_id not in state["data"]:
state["data"][inst_id] = {
"track_step": [],
"track_data": [],
"track_count": 0
}
curr_state = state["data"][inst_id]
curr_state["track_count"] = len(obj.inst[state["index"]]["widgets_values"][0])
curr_track_len = len(curr_state["track_data"])
if curr_state["track_count"] > curr_track_len:
curr_state["track_data"].extend([None] * (curr_state["track_count"] - curr_track_len))
curr_state["track_step"].extend([None] * (curr_state["track_count"] - curr_track_len))
elif curr_state["track_count"] < curr_track_len:
curr_state["track_data"] = curr_state["track_data"][:curr_state["track_count"]]
curr_state["track_step"] = curr_state["track_step"][:curr_state["track_count"]]
for i, curr_offset, curr_step, curr_space, curr_count in zip(itertools.count(start=0, step=1), *obj.inst[state["index"]]["widgets_values"]):
if curr_state["track_data"][i] is None or \
curr_state["track_step"][i] != curr_step or \
state["change"]:
curr_state["track_data"][i] = curr_offset
curr_state["track_step"][i] = curr_step
if curr_step != 0:
PROMPT_UPDATE.add(state["id"])
else:
curr_state["track_data"][i] += curr_step
if curr_step != 0:
PROMPT_UPDATE.add(state["id"])
lib0246.sort_dict_of_list(hold, "index")
for i, track in zip(itertools.count(start=curr_state["track_data"][i], step=curr_space), range(curr_count)):
res.append(hold["data"][i % len(hold["data"])])
for i in range(len(hold["index"])):
hold["index"][i] = None
return res
@classmethod
def func_text(cls, obj, hold, state):
return obj.inst[state["index"]]["widgets_values"][0]
@classmethod
def func_weight(cls, obj, hold, state):
hold["data"] = list(map(lambda _: f"({re.sub(STR_BRACKET, STR_REPLACE, _[0])}: {lib0246.snap_place(_[1], round, 2)})", itertools.product(hold["data"], obj.inst[state["index"]]["widgets_values"][0])))
state["index"] = None
return []
@classmethod
def func_merge(cls, obj, hold, state):
res = []
lib0246.sort_dict_of_list(hold, "index")
for i, curr_delim in zip(itertools.count(start=0, step=1), *obj.inst[state["index"]]["widgets_values"]):
res.append(curr_delim.join(hold["data"]))
for i in range(len(hold["index"])):
hold["index"][i] = None
return res
class CloudData:
def __init__(self):
self.inst = []
self.group = {}
self.db = {}
self.state = {}
self.func = {}
self.track = 0
self.order = None
self.id = None
@classmethod
def full_dict_to_data(cls, curr_id, inst_list, group_dict, db_dict = None, kwargs = None):
dict_dupe = dict(filter(lambda item: item[0].split(":")[0].isnumeric(), kwargs.items()))
if len(dict_dupe) == 0:
return [
CloudData().dict_to_data(curr_id, inst_list, group_dict, db_dict, dict_dupe)
]
return [
CloudData().dict_to_data(curr_id, inst_list, group_dict, db_dict, dupe[0]) for dupe in
lib0246.dict_product(dict_dupe)
]
def dict_to_data(self, curr_id, inst_list, group_dict, db_dict = None, kwargs = None):
if kwargs is not None:
self.track = PROMPT_COUNT
self.id = curr_id
if db_dict is not None:
self.db.update(db_dict)
self.db[curr_id] = self.db.get(curr_id, {})
for inst in inst_list:
old_id = inst["id"]
new_id = str(uuid.uuid4())
match inst["kind"]:
case "pin" if kwargs is not None:
curr_value = None
for key in kwargs:
curr_int = key.split(":")[0]
if curr_int.isnumeric() and int(curr_int) == inst["widgets_values"][0]:
curr_value = kwargs[key]
break
match curr_value:
case CloudData():
self.dict_to_data(curr_value.id, curr_value.inst, curr_value.group, curr_value.db, None)
for group_id in group_dict:
if "inst" in group_dict[group_id]:
try:
curr_index = group_dict[group_id]["inst"].index(old_id)
group_dict[group_id]["inst"][curr_index:curr_index + 1] = map(lambda _: _["id"], curr_value.inst)
except ValueError:
pass
continue
case str() | int() | float():
self.inst.append({
"id": new_id,
"kind": "text",
"widgets_values": [[*map(str, kwargs[key])]],
"widgets_names": [f"cloud:_:{new_id}:text:text_input"]
})
case _:
self.inst.append(inst)
if old_id.isnumeric():
inst["id"] = new_id
self.db[curr_id][new_id] = old_id
if kwargs is not None:
for param in kwargs:
if param.startswith("cloud:"):
for inst in self.inst:
for i in range(len(inst["widgets_values"])):
if inst["widgets_names"][i] == param:
inst["widgets_values"][i] = kwargs[param]
break
for old_id, group_data in group_dict.items():
if "inst" in group_data:
new_list = []
for i, inst_id in enumerate(group_data["inst"]):
if not inst_id.isnumeric():
new_list.append(inst_id)
else:
for curr_inst_id in self.db[curr_id].keys():
if self.db[curr_id][curr_inst_id] == inst_id:
new_list.append(curr_inst_id)
break
if len(new_list) > 0:
group_data["inst"] = new_list
else:
del group_data["inst"]
if "group" in group_data:
for i, inner_old_id in enumerate(group_data["group"]):
new_id = str(uuid.uuid4())
if not inner_old_id.split(":")[-1].isnumeric():
group_data["group"][i] = inner_old_id
else:
for curr_group_id in self.db[curr_id].keys():
if self.db[curr_id][curr_group_id] == inner_old_id:
group_data["group"][i] = curr_group_id
break
new_id = str(uuid.uuid4())
if not old_id.split(":")[-1].isnumeric():
self.group[old_id] = group_data
else:
for curr_group_id in self.db[curr_id].keys():
if self.db[curr_id][curr_group_id] == old_id:
self.group[curr_group_id] = group_data
break
else:
self.group[new_id] = group_data
for curr_group_id in self.db[curr_id].keys():
if self.db[curr_id][curr_group_id] == old_id:
break
else:
self.db[curr_id][new_id] = old_id
return self
@classmethod
def text_to_dict(cls, text):
old_func = comfy.sd1_clip.parse_parentheses
comfy.sd1_clip.parse_parentheses = lib0246.parse_parentheses
res = list(map(lambda _: (comfy.sd1_clip.unescape_important(_[0]), _[1]), comfy.sd1_clip.token_weights(comfy.sd1_clip.escape_important(text), 1.0)))
comfy.sd1_clip.parse_parentheses = old_func
return res
def text_to_data(self, text):
pass
def data_eval(self, node_id, prompt, workflow):
"""
{
eval # Evaluated data
data # Persistent data
order # Current instance order
index # Current instance result index
change # Whether whole cloud changed
}
"""
self.state["eval"] = {}
self.state["change"] = self.track == PROMPT_COUNT
self.state["id"] = node_id
self.state["prompt"] = prompt
self.state["workflow"] = workflow
if self.state["change"] or self.order is None:
self.order = self.sort()
self.func = {}
self.state["data"] = {}
self.track = PROMPT_COUNT
for inst in self.inst:
self.func[inst["id"]] = CloudFunc(inst["kind"]) if \
isinstance(inst["kind"], str) else \
inst["kind"]
for i, curr_id in enumerate(self.order["idx"]):
self.state["order"] = i
self.state["index"] = next(i for i, _ in enumerate(self.inst) if _["id"] == curr_id)
hold_curr = {
"data": [],
"index": []
}
for inst_id_dep in self.order["dep"][curr_id]:
hold_curr["data"].extend(self.state["eval"][inst_id_dep]["data"])
hold_curr["index"].extend([self.state["eval"][inst_id_dep]["index"]] * len(self.state["eval"][inst_id_dep]["data"]))
self.state["eval"][curr_id] = {
"data": self.func[curr_id].func(
obj=self,
hold=hold_curr,
state=self.state
),
"index": self.state["index"]
}
i = 0
for inst_id_dep in self.order["dep"][curr_id]:
self.state["eval"][inst_id_dep]["index"] = hold_curr["index"][i]
curr_len = len(self.state["eval"][inst_id_dep]["data"])
self.state["eval"][inst_id_dep]["data"] = hold_curr["data"][i:i + curr_len]
i += curr_len
temp_res = []
for curr_id in self.state["eval"]:
curr_eval = self.state["eval"][curr_id]
if curr_eval["index"] is not None:
curr_eval["id"] = curr_id
temp_res.append(curr_eval)
temp_res.sort(key=lambda _: _["index"])
return sum((curr_eval["data"] for curr_eval in temp_res), [])
def sort(self):
dep = {}
for group_id in self.group:
inst_list = group_query_inst(self.group, group_id)
inst_dep_list_prim = []
inst_dep_list_func = []
inst_dep_list_bind = []
inst_kind_set = set()
for inst_id in inst_list:
if inst_id not in dep:
dep[inst_id] = []
inst_curr_kind = next(filter(lambda _: _["id"] == inst_id, self.inst))["kind"]
if CLOUD_METHOD[inst_curr_kind] is None:
inst_dep_list_prim.append(inst_id)
else:
if inst_curr_kind in inst_kind_set and CLOUD_METHOD[inst_curr_kind]["sole"]:
raise Exception(f"Cannot have multiple {inst_curr_kind} cloud to same group {group_id}.")
(inst_dep_list_bind if CLOUD_METHOD[inst_curr_kind]["bind"] else inst_dep_list_func).append(inst_id)
if isinstance(inst_curr_kind, str):
inst_kind_set.add(inst_curr_kind)
for inst_id in inst_dep_list_func:
dep[inst_id].extend(inst_dep_list_prim)
dep[inst_id].extend(inst_dep_list_bind)
idx_db = {}
for inst_id in inst_dep_list_bind:
dep[inst_id].extend(inst_dep_list_prim)
# dep[inst_id].extend(inst_dep_list_func)
idx_db[inst_id] = self.inst.index(next(filter(lambda _: _["id"] == inst_id, self.inst)))
for a_inst_id in inst_dep_list_bind:
for b_inst_id in inst_dep_list_bind:
if idx_db[a_inst_id] > idx_db[b_inst_id] and idx_db[a_inst_id] != idx_db[b_inst_id]:
dep[a_inst_id].append(b_inst_id)
for inst_id in self.inst:
if inst_id["id"] not in dep:
dep[inst_id["id"]] = []
return {
"idx": list(map(lambda _: _[0], lib0246.flat_iter(lib0246.toposort(dep, key_func=lambda _: next(i for i, c in enumerate(self.inst) if c["id"] == _)), layer=1))),
"dep": dep
}
def __str__(self):
return f"CloudData({self.inst}, {self.group}, {self.db})"
def __repr__(self):
return f"CloudData({json.dumps(self.inst, indent=2)}, {json.dumps(self.group, indent=2)}, {json.dumps(self.db, indent=2)})"
########################################################################################
######################################## HIJACK ########################################
########################################################################################
BASE_EXECUTOR = None
def init_executor_param_handle(*args, **kwargs):
return None, tuple(), {}
def init_executor_res_handle(result, *args, **kwargs):
global BASE_EXECUTOR
if BASE_EXECUTOR is None:
BASE_EXECUTOR = args[0]
return result
lib0246.hijack(execution.PromptExecutor, "__init__", init_executor_param_handle, init_executor_res_handle)
PROMPT_COUNT = 0
PROMPT_DATA = None
PROMPT_ID = None
PROMPT_EXTRA = None
PROMPT_UPDATE = set()
PROMPT_IGNORE = set()
PROMPT_IGNORE_FLAG = False
PROMPT_NODE_ID = None
PROMPT_HIJACK = set()
def is_changed_res_handle(result, *args, **kwargs):
global PROMPT_NODE_ID
if PROMPT_NODE_ID in PROMPT_IGNORE:
PROMPT_NODE_ID = None
return False
if PROMPT_NODE_ID in PROMPT_UPDATE:
PROMPT_UPDATE.remove(PROMPT_NODE_ID)
PROMPT_NODE_ID = None
return float("NaN")
return result
def execute_param_handle(*args, **kwargs):
global PROMPT_ID
global PROMPT_COUNT
global PROMPT_DATA
global PROMPT_EXTRA
if PROMPT_ID is None or PROMPT_ID != args[2]:
PROMPT_COUNT += 1
PROMPT_DATA = args[1]
PROMPT_ID = args[2]
PROMPT_EXTRA = args[3]
return None, tuple(), {}
def executor_res_handle(result, *args, **kwargs):
global PROMPT_UPDATE
global PROMPT_IGNORE
global PROMPT_IGNORE_FLAG
global PROMPT_HIJACK
for node_id in PROMPT_UPDATE:
if hasattr(BASE_EXECUTOR, "outputs") and node_id in BASE_EXECUTOR.outputs:
del BASE_EXECUTOR.outputs[node_id]
else:
curr_class_type = args[1][node_id]["class_type"]
if curr_class_type not in PROMPT_HIJACK:
PROMPT_HIJACK.add(curr_class_type)
curr_class = nodes.NODE_CLASS_MAPPINGS[curr_class_type]
if hasattr(curr_class, "IS_CHANGED"):
lib0246.hijack(curr_class, "IS_CHANGED", res_func=is_changed_res_handle)
else:
curr_class.IS_CHANGED = functools.partial(is_changed_res_handle, None)
if hasattr(BASE_EXECUTOR, "outputs"):