This repository has been archived by the owner on Feb 21, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path__init__.py
368 lines (304 loc) · 11.3 KB
/
__init__.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
from typing import List
from unittest.mock import MagicMock, patch
import random
import time
import os
import json
import pathlib
from aiohttp import web
import hashlib
import traceback
from rich.console import Console
from execution import validate_prompt
from comfy_execution.graph_utils import GraphBuilder, is_link
import execution
import folder_paths
from server import PromptServer
import nodes
console = Console(color_system="truecolor", force_terminal=True)
idempt = 0
current_node_id = 0
orignal_exe = execution.execute
def new_exe(*args):
global idempt
global current_node_id
try:
node_id = args[3]
current_node_id = node_id
node = args[1].get_node(node_id)
class_type = node["class_type"];
node_title = f"{class_type} #{node_id}"
PromptServer.instance.send_sync("/viv/subgraph/executing", {"title": node_title, "idempt": idempt})
idempt += 1
except Exception as e:
console.print(f"[red]{e}[/red]")
pass
return orignal_exe(*args)
execution.execute = new_exe
SUBNODE_FOLDER = pathlib.Path(folder_paths.base_path) / "subnodes"
if not SUBNODE_FOLDER.exists():
os.mkdir(SUBNODE_FOLDER)
def get_workflow_names() -> list[str]:
files = list(SUBNODE_FOLDER.glob("*.json"))
return [file.name for file in files]
def load_workflow(workflow, raw=False):
with open(SUBNODE_FOLDER / workflow, encoding='utf-8') as f:
data = json.load(f)
if not raw:
if "api_prompt" in data:
data = data["api_prompt"]
if "nodes" in data:
raise ValueError((
f"Invalid subgraph file: {workflow}\n"
"reason: full workflow export without injected `api_prompt` key\n"
"hint: Try loading and re exporting the workflow."
))
return data
def get_outputs(workflow):
data = load_workflow(workflow, raw=True)
if "api_prompt" in data:
prompt = data["api_prompt"]
extra_data = True
else:
prompt = data
extra_data = False
results = []
for (node_id, node) in prompt.items():
if node["class_type"] == "VIV_Subgraph_Outputs":
for index, name in enumerate(node["inputs"].keys()):
type_ = name.split(".")[0]
if extra_data:
for graph_node in data["nodes"]:
if str(graph_node["id"]) == node_id:
graph_input = graph_node["inputs"][index]
if "label" in graph_input:
name = graph_input["label"]
results.append({"name": name, "type": type_})
return results
def get_inputs(workflow):
data = load_workflow(workflow, raw=True)
if "api_prompt" in data:
prompt = data["api_prompt"]
extra_data = True
else:
prompt = data
extra_data = False
for (node_id, node) in prompt.items():
if node["class_type"] == "VIV_Subgraph_Inputs":
break;
else:
return []
inputs = {}
for (id, node) in prompt.items():
for (name, input) in node["inputs"].items():
if isinstance(input, list):
if input[0] == node_id:
type_ = "*"
prompt_name = name
node_name = node["class_type"]
cls = nodes.NODE_CLASS_MAPPINGS[node_name]
cls_input_config = cls.INPUT_TYPES()
input_data = cls_input_config.get("required", {}).get(name) or cls_input_config.get("optional", {}).get(name)
widget_data = {}
if input_data is not None:
if len(input_data) >= 2:
if isinstance(input_data[1], dict):
widget_data = input_data[1]
if widget_data.get("multiline", False):
widget_data["multiline"] = False
if isinstance(input_data[0], tuple | list):
widget_data["values"] = input_data[0]
if extra_data:
for graph_node in data["nodes"]:
if str(graph_node["id"]) == id:
if "title" in graph_node:
node_name = graph_node["title"]
for graph_input in graph_node.get("inputs", []):
if graph_input["name"] == name:
type_ = graph_input["type"]
if "label" in graph_input:
prompt_name = graph_input["label"]
display_name = f"{prompt_name}.{node_name}.{id}"
inputs[input[1]] = {
"name": display_name,
"type": type_,
"widget": widget_data
}
if extra_data:
for graph_node in data["nodes"]:
if str(graph_node["id"]) == node_id:
for index, graph_input in enumerate(graph_node.get("outputs", [])):
if "label" in graph_input:
input_name = graph_input["label"]
inputs[index]["name"] = input_name
if graph_input["name"] in graph_node["properties"]:
inputs[index]["widget"]["default"] = graph_node["properties"][graph_input["name"]]
return [name for (_, name) in sorted(inputs.items(), key=lambda x: x[0])]
class Any(str):
def __ne__(self, value: object, /) -> bool:
return False
class AcceptAnyWidgetInput(dict):
def __contains__(self, key: object, /) -> bool:
return True
def __getitem__(self, key):
return self.get(key, Any("*"))
class ReturnAnyAmount(tuple):
def __getitem__(self, index):
return Any("*")
in_subgraph = False
class VIV_Subgraph:
@classmethod
def INPUT_TYPES(cls):
return {
"required": AcceptAnyWidgetInput({
"workflow": (tuple(get_workflow_names()), {"forceInput": True})
}),
}
RETURN_TYPES = ReturnAnyAmount()
RETURN_NAMES = ReturnAnyAmount()
FUNCTION = "run"
CATEGORY = "sub_graph"
@classmethod
def IS_CHANGED(cls, workflow, **kwargs):
workflows = {workflow}
stack = [workflow]
while stack:
workflow = stack.pop()
data = load_workflow(workflow)
for node in data.values():
if node["class_type"] == "VIV_Subgraph":
file = node["inputs"]["workflow"]
if file not in workflows:
workflows.add(file)
stack.append(file)
m = hashlib.sha256()
for workflow in sorted(workflows):
with open(SUBNODE_FOLDER / workflow, "rb") as f:
m.update(f.read())
return m.digest().hex()
def run(self, workflow: str, **kwargs):
prompt = load_workflow(workflow)
_, error, outputs, _ = validate_prompt(prompt)
if error is not None:
console.print(f"[red]INVALID SUBGRAPH: {workflow}[/red]")
console.print(error)
raise ValueError(f"Invalid subgraph: {error['message']}")
inputs = get_inputs(workflow)
input_order = [inp["name"] for inp in inputs]
kwargs = {key: value for (key, value) in kwargs.items() if key in input_order}
for inp in inputs:
if inp["name"] not in kwargs:
kwargs[inp["name"]] = None
kwargs = sorted(kwargs.items(), key=lambda x: input_order.index(x[0]))
kwargs = (value for (_, value) in kwargs)
graph = GraphBuilder()
output_node = None
for (node_id, orig_node) in prompt.items():
node = graph.node(orig_node["class_type"], node_id)
if orig_node["class_type"] == "VIV_Subgraph_Outputs":
output_node = node
for (node_id, orig_node) in prompt.items():
node = graph.lookup_node(node_id)
for k, v in orig_node["inputs"].items():
if is_link(v):
parent = graph.lookup_node(v[0])
node.set_input(k, parent.out(v[1]))
else:
node.set_input(k, v)
for (node_id, orig_node) in prompt.items():
if orig_node["class_type"] == "VIV_Subgraph_Inputs":
for index, value in enumerate(kwargs):
graph.replace_node_output(node_id, index, value)
if output_node:
result = tuple(output_node.inputs.values())
else:
result = ()
return {
"result": result,
"expand": graph.finalize(),
}
OUTPUT_RESULTS = []
class VIV_Subgraph_outputs:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
}
RETURN_TYPES = ()
RETURN_NAMES = ()
FUNCTION = "run"
CATEGORY = "sub_graph"
OUTPUT_NODE = True
def run(self, **kwargs):
return ()
# @classmethod
# def IS_CHANGED(cls, **kwargs):
# return time.time()
# INPUTS = []
class VIV_Subgraph_inputs:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {},
}
RETURN_TYPES = ReturnAnyAmount()
RETURN_NAMES = ReturnAnyAmount()
FUNCTION = "run"
CATEGORY = "sub_graph"
OUTPUT_NODE = True
def run(self, **kwargs):
# return tuple(INPUTS.pop())
return ()
# @classmethod
# def IS_CHANGED(cls, **args):
# return time.time()
class VIV_Default:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"default": Any("*"),
},
"optional": {
"inp": Any("*"),
}
}
DEPRECATED = True
RETURN_TYPES = (Any("*"),)
RETURN_NAMES = ("result",)
FUNCTION = "run"
CATEGORY = "sub_graph"
def run(self, default, inp=None):
if inp is None:
return (default,)
return (inp,)
@PromptServer.instance.routes.get("/viv/subgraph")
async def get_workflow(request):
workflow = request.rel_url.query["workflow"] + ".json"
data = load_workflow(workflow, raw=True)
return web.json_response(data)
@PromptServer.instance.routes.get("/viv/input_outputs")
async def get_input_outputs(request):
workflow = request.rel_url.query["workflow"] + ".json"
try:
load_workflow(workflow) # in order to catch errors
response = {
"outputs": get_outputs(workflow),
"inputs": get_inputs(workflow)
}
return web.json_response({"data": response})
except Exception as err:
traceback.print_exception(err)
return web.json_response({"error": str(err)})
console.print("[green]Sub nodes, yay![/green]")
console.print("[red]WARNING: This is a very experimental setup :P![/red]")
NODE_CLASS_MAPPINGS = {
"VIV_Subgraph": VIV_Subgraph,
"VIV_Subgraph_Outputs": VIV_Subgraph_outputs,
"VIV_Subgraph_Inputs": VIV_Subgraph_inputs,
"VIV_Default": VIV_Default,
}
MANIFEST = {
"name": "VIVAX",
}
WEB_DIRECTORY = "web"