-
Notifications
You must be signed in to change notification settings - Fork 11
/
components.py
220 lines (191 loc) · 8.1 KB
/
components.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
import os
import shutil
import folder_paths
import json
import copy
import comfy_execution.graph_utils
from .tools import VariantSupport
comfy_path = os.path.dirname(folder_paths.__file__)
js_path = os.path.join(comfy_path, "web", "extensions")
inversion_demo_path = os.path.dirname(__file__)
def setup_js():
# setup js
js_dest_path = os.path.join(js_path, "inversion-demo-components")
if not os.path.exists(js_dest_path):
os.makedirs(js_dest_path)
js_src_path = os.path.join(inversion_demo_path, "js", "inversion-demo-components.js")
shutil.copy(js_src_path, js_dest_path)
@VariantSupport()
class ComponentInput:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"name": ("STRING", {"multiline": False}),
"data_type": ("STRING", {"multiline": False, "default": "IMAGE"}),
"extra_args": ("STRING", {"multiline": False}),
"explicit_input_order": ("INT", {"default": 0, "min": 0, "max": 1000, "step": 1}),
"optional": ([False, True],),
},
"optional": {
"default_value": ("*",),
},
}
RETURN_TYPES = ("*",)
FUNCTION = "component_input"
CATEGORY = "InversionDemo Nodes/Component Creation"
def component_input(self, name, data_type, extra_args, explicit_input_order, optional, default_value = None):
return (default_value,)
@VariantSupport()
class ComponentOutput:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"index": ("INT", {"default": 0, "min": 0, "max": 1000, "step": 1}),
"data_type": ("STRING", {"multiline": False, "default": "IMAGE"}),
"name": ("STRING", {"multiline": False}),
"value": ("*",),
},
}
RETURN_TYPES = ("*",)
FUNCTION = "component_output"
CATEGORY = "InversionDemo Nodes/Component Creation"
def component_output(self, index, data_type, name, value):
return (value,)
@VariantSupport()
class ComponentMetadata:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"name": ("STRING", {"multiline": False}),
"always_output": ([False, True],),
},
}
RETURN_TYPES = ()
FUNCTION = "nop"
CATEGORY = "InversionDemo Nodes/Component Creation"
def nop(self, name):
return {}
COMPONENT_NODE_CLASS_MAPPINGS = {
"ComponentInput": ComponentInput,
"ComponentOutput": ComponentOutput,
"ComponentMetadata": ComponentMetadata,
}
COMPONENT_NODE_DISPLAY_NAME_MAPPINGS = {
"ComponentInput": "Component Input",
"ComponentOutput": "Component Output",
"ComponentMetadata": "Component Metadata",
}
DEFAULT_EXTRA_DATA = {
"STRING": {"multiline": False},
"INT": {"default": 0, "min": 0, "max": 1000, "step": 1},
"FLOAT": {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.1},
}
def default_extra_data(data_type, extra_args):
if data_type == "STRING":
args = {"multiline": False}
elif data_type == "INT":
args = {"default": 0, "min": -1000000, "max": 1000000, "step": 1}
elif data_type == "FLOAT":
args = {"default": 0.0, "min": -1000000.0, "max": 1000000.0, "step": 0.1}
else:
args = {}
args.update(extra_args)
return args
def LoadComponent(component_file):
try:
with open(component_file, "r", encoding="utf-8") as f:
component_data = f.read()
graph = json.loads(component_data)["output"]
component_raw_name = os.path.basename(component_file).split(".")[0]
component_display_name = component_raw_name
component_inputs = []
component_outputs = []
is_output_component = False
for node_id, data in graph.items():
if data["class_type"] == "ComponentMetadata":
component_display_name = data["inputs"].get("name", component_raw_name)
is_output_component = data["inputs"].get("always_output", False)
elif data["class_type"] == "ComponentInput":
data_type = data["inputs"]["data_type"]
if len(data_type) > 0 and data_type[0] == "[":
try:
data_type = json.loads(data_type)
except:
pass
try:
extra_args = json.loads(data["inputs"]["extra_args"])
except:
extra_args = {}
component_inputs.append({
"node_id": node_id,
"name": data["inputs"]["name"],
"data_type": data_type,
"extra_args": extra_args,
"explicit_input_order": data["inputs"]["explicit_input_order"],
"optional": data["inputs"]["optional"],
})
elif data["class_type"] == "ComponentOutput":
component_outputs.append({
"node_id": node_id,
"name": data["inputs"]["name"] or data["inputs"]["data_type"],
"index": data["inputs"]["index"],
"data_type": data["inputs"]["data_type"],
})
component_inputs.sort(key=lambda x: (x["explicit_input_order"], x["name"]))
component_outputs.sort(key=lambda x: x["index"])
for i in range(1, len(component_inputs)):
if component_inputs[i]["name"] == component_inputs[i-1]["name"]:
raise Exception("Component input name is not unique: {}".format(component_inputs[i]["name"]))
for i in range(1, len(component_outputs)):
if component_outputs[i]["index"] == component_outputs[i-1]["index"]:
raise Exception("Component output index is not unique: {}".format(component_outputs[i]["index"]))
except Exception as e:
print("Error loading component file: {}: {}".format(component_file, e))
return None
class ComponentNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {node["name"]: (node["data_type"], default_extra_data(node["data_type"], node["extra_args"])) for node in component_inputs if not node["optional"]},
"optional": {node["name"]: (node["data_type"], default_extra_data(node["data_type"], node["extra_args"])) for node in component_inputs if node["optional"]},
}
RETURN_TYPES = tuple([node["data_type"] for node in component_outputs])
RETURN_NAMES = tuple([node["name"] for node in component_outputs])
FUNCTION = "expand_component"
CATEGORY = "Custom Components"
OUTPUT_NODE = is_output_component
def expand_component(self, **kwargs):
new_graph = copy.deepcopy(graph)
for input_node in component_inputs:
if input_node["name"] in kwargs:
new_graph[input_node["node_id"]]["inputs"]["default_value"] = kwargs[input_node["name"]]
outputs = tuple([[node["node_id"], 0] for node in component_outputs])
new_graph, outputs = comfy_execution.graph_utils.add_graph_prefix(new_graph, outputs, comfy_execution.graph_utils.GraphBuilder.alloc_prefix())
return {
"result": outputs,
"expand": new_graph,
}
ComponentNode.__name__ = component_raw_name
COMPONENT_NODE_CLASS_MAPPINGS[component_raw_name] = ComponentNode
COMPONENT_NODE_DISPLAY_NAME_MAPPINGS[component_raw_name] = component_display_name
print("Loaded component: {}".format(component_display_name))
def load_components():
component_dir = os.path.join(comfy_path, "components")
if not os.path.exists(component_dir):
return
files = [f for f in os.listdir(component_dir) if os.path.isfile(os.path.join(component_dir, f)) and f.endswith(".json")]
for f in files:
print("Loading component file %s" % f)
LoadComponent(os.path.join(component_dir, f))
load_components()