-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi.py
More file actions
406 lines (348 loc) · 12.5 KB
/
api.py
File metadata and controls
406 lines (348 loc) · 12.5 KB
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
import json
import re
import subprocess
import sys
import copy
import io
import numpy as np
import torch
import base64
import random
from PIL import Image
# Eww. I'm sure there's a better way to do this, but it's probably not worth the effort
def store_at_position(obj, result, path):
path = re.split('[\.\[]', path)
current = obj
for i in range(len(path) - 1):
next_is_list = path[i + 1][-1] == "]"
if path[i] == "]":
assert isinstance(current, list)
if next_is_list:
current.append([])
else:
current.append({})
current = current[-1]
elif path[i][-1] == "]":
assert isinstance(current, list)
key = int(path[i][:-1])
if key == -1 and len(current) == 0:
key = 0
if key >= len(current):
current += [None] * (key - len(current) + 1)
if current[key] is None:
if next_is_list:
current[key] = []
else:
current[key] = {}
current = current[key]
elif path[i] not in current:
key = path[i]
if next_is_list:
current[key] = []
else:
current[key] = {}
current = current[key]
else:
current = current[path[i]]
last = path[-1]
if last == "]":
current.append(result)
elif last[-1] == "]":
key = int(last[:-1])
if key >= len(current):
current += [None] * (key - len(current) + 1)
current[key] = result
else:
current[last] = result
def serialize_image(images):
B, H, W, C = images.shape
results = []
for b in range(B):
image = images[b] * 255
array = image.cpu().numpy()
im = Image.fromarray(np.uint8(array))
im.convert('RGBA')
f = io.BytesIO()
im.save(f, format='PNG')
results.append(base64.b64encode(f.getvalue()).decode("utf-8"))
return results
def default_serialize(value):
return value
def GenericSerializeNodeFactory(name, arg_type, serialize_function=default_serialize, default_value=None):
class GenericSerializeNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
if default_value is None:
value = (arg_type,)
else:
value = (arg_type, {"default": default_value})
return {
"required": {
"value": value,
"path": ("STRING", {"multiline": False}),
},
"optional": {
"json_object_optional": ("JSON_OBJECT",)
},
}
FUNCTION = "output"
RETURN_TYPES = ("JSON_OBJECT",)
CATEGORY = "API Output"
def output(self, value, path, json_object_optional=None):
output = serialize_function(value)
if json_object_optional is None:
return ([(path, output)],)
else:
# return (copy.deepcopy(json_object_optional) + [(path, output)],)
return (json_object_optional + [(path, output)],)
GenericSerializeNode.__name__ = name
return GenericSerializeNode
class APISerializeNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"path": ("STRING", {"multiline": False}),
"value": ("*",),
},
"optional": {
"json_object_optional": ("JSON_OBJECT",),
},
}
FUNCTION = "output"
RETURN_TYPES = ("JSON_OBJECT",)
CATEGORY = "API Output"
def output(self, path, value, json_object_optional=None):
if isinstance(value, torch.Tensor):
value = serialize_image(value)
if json_object_optional is None:
return ([(path, value)],)
else:
# return (copy.deepcopy(json_object_optional) + [(path, output)],)
return (json_object_optional + [(path, value)],)
def deserialize_image(image_input):
if not isinstance(image_input, list):
image_input = [image_input]
result = None
for image_string in image_input:
decoded = base64.b64decode(image_string)
image = Image.open(io.BytesIO(decoded)).convert('RGB')
# image.save("/home/guill/Desktop/test_result.png", format="PNG")
image_array = np.array(image).astype(np.float32)
tensor = torch.from_numpy(image_array / 255.0)
tensor = tensor.unsqueeze(0)
if result is None:
result = tensor
else:
result = torch.cat([result, tensor], dim=0)
return result
def default_deserialize(value):
return value
def GenericInputNodeFactory(name, arg_type, deserialize_function=default_deserialize, default_value=None):
class GenericInputNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
if default_value is None:
value = (arg_type,)
else:
value = (arg_type, {"default": default_value})
return {
"required": {
"path": ("STRING", {"multiline": False}),
},
"optional": {
"default_value": value,
},
"hidden": {
"api_value": value,
},
}
FUNCTION = "input"
RETURN_TYPES = (arg_type,)
CATEGORY = "API Input"
def input(self, path, default_value = None, api_value = None):
if api_value is not None:
return (deserialize_function(api_value),)
elif default_value is not None:
return (default_value,)
else:
return (None,)
GenericInputNode.__name__ = name
return GenericInputNode
class SerializeImageNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"path": ("STRING", {"multiline": False}),
},
"optional": {
"json_object_optional": ("JSON_OBJECT",)
},
}
FUNCTION = "output"
RETURN_TYPES = ("JSON_OBJECT",)
CATEGORY = "API Output"
def output(self, image, path, json_object_optional=None):
output = "The image goes here"
if json_object_optional is None:
return ([(path, output)],)
else:
# return (copy.deepcopy(json_object_optional) + [(path, output)],)
return (json_object_optional + [(path, output)],)
class APIOutputNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"json_object": ("JSON_OBJECT",),
},
"optional": {
"extra_object2": ("JSON_OBJECT",),
"extra_object3": ("JSON_OBJECT",),
"extra_object4": ("JSON_OBJECT",),
"extra_object5": ("JSON_OBJECT",),
},
}
FUNCTION = "output"
RETURN_TYPES = ()
OUTPUT_NODE = True
CATEGORY = "API Output"
def output(self, json_object, extra_object2=None, extra_object3=None, extra_object4=None, extra_object5=None):
obj = json_object
if extra_object2 is not None:
obj = obj + extra_object2
if extra_object3 is not None:
obj = obj + extra_object3
if extra_object4 is not None:
obj = obj + extra_object4
if extra_object5 is not None:
obj = obj + extra_object5
output = {}
for i in range(len(obj)):
path, value = obj[i]
store_at_position(output, copy.deepcopy(value), path)
return { "ui": { "api_output": [output] } }
class APIInputNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"path": ("STRING", {"multiline": False}),
"kind": (["string", "integer", "float", "boolean", "image"],),
},
"optional": {
"default_string": ("STRING", {"multiline": False}),
"default_input": ("*",),
},
"hidden": {
"api_value": ("*",),
},
}
FUNCTION = "input"
RETURN_TYPES = ("*",)
CATEGORY = "API Input"
def input(self, path, kind, default_string = None, default_input = None, api_value = None):
value = api_value
if value is None:
value = default_input
if value is None:
if default_string != "" or kind == "string" :
value = default_string
if kind == "string":
value = str(value)
elif kind == "integer":
value = int(value)
elif kind == "float":
value = float(value)
elif kind == "boolean":
if value.lower() == "true":
value = True
elif value.lower() == "false":
value = False
else:
try:
value = bool(int(value))
except:
value = False
elif kind == "image":
if not isinstance(value, torch.Tensor):
value = deserialize_image(value)
return (value,)
class APIRandomSeedInput:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"seed": ("INT", {"default": -1, "min": -1, "max": 0xffffffffffffffff}),
"path": ("STRING", {"multiline": False}),
}
}
FUNCTION = "random_seed"
RETURN_TYPES = ("INT",)
CATEGORY = "API Input"
def random_seed(self, seed, path):
if seed is None or seed == -1:
seed = random.randint(0, 0xffffffffffffffff)
return (seed,)
class MergeJSONObjectsNode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"json_object1": ("JSON_OBJECT",),
},
"optional": {
"extra_object2": ("JSON_OBJECT",),
"extra_object3": ("JSON_OBJECT",),
"extra_object4": ("JSON_OBJECT",),
"extra_object5": ("JSON_OBJECT",),
},
}
FUNCTION = "merge"
RETURN_TYPES = ("JSON_OBJECT",)
CATEGORY = "API Output"
def merge(self, json_object, extra_object2=None, extra_object3=None, extra_object4=None, extra_object5=None):
obj = json_object
if extra_object2 is not None:
obj = obj + extra_object2
if extra_object3 is not None:
obj = obj + extra_object3
if extra_object4 is not None:
obj = obj + extra_object4
if extra_object5 is not None:
obj = obj + extra_object5
return (obj,)
NODE_CLASS_MAPPINGS = {
"API Output": APIOutputNode,
# "Serialize Image (API)": SerializeImageNode,
# "Image Output (API)": GenericSerializeNodeFactory("Image Output (API)", "IMAGE", serialize_function=serialize_image),
# "Integer Output (API)": GenericSerializeNodeFactory("Integer Output (API)", "INT", default_value=0),
# "Float Output (API)": GenericSerializeNodeFactory("Float Output (API)", "FLOAT", default_value=0.0),
# "Text Output (API)": GenericSerializeNodeFactory("String Output (API)", "STRING", default_value=""),
"Serialize (API)": APISerializeNode,
"Merge JSON Objects": MergeJSONObjectsNode,
"Input (API)": APIInputNode,
# "Image Input (API)": GenericInputNodeFactory("Image Input (API)", "IMAGE", deserialize_function=deserialize_image),
# "Integer Input (API)": GenericInputNodeFactory("Integer Input (API)", "INT", default_value=0),
# "Float Input (API)": GenericInputNodeFactory("Float Input (API)", "FLOAT", default_value=0.0),
# "Text Input (API)": GenericInputNodeFactory("String Input (API)", "STRING", default_value=""),
"Random Seed Input (API)": APIRandomSeedInput,
}