-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathoutput_node.py
More file actions
449 lines (387 loc) · 13.9 KB
/
output_node.py
File metadata and controls
449 lines (387 loc) · 13.9 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
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
from io import BytesIO
import json
import os
import re
from pathlib import Path
from PIL import Image, ImageOps
from PIL.PngImagePlugin import PngInfo
import torch
from comfy import model_management
import requests
import numpy as np
import folder_paths
from nodes import LoadImage
from comfy.utils import ProgressBar
from server import PromptServer
from .rice_def import RiceRoundErrorDef, RiceTaskErrorDef
from .rice_url_config import RiceUrlConfig, user_upload_image, user_upload_imagefile
from .utils import get_machine_id, pil2tensor
from .auth_unit import AuthUnit
from .rice_prompt_info import RicePromptInfo
from .rice_websocket import (
TaskInfo,
TaskStatus,
TaskWebSocket,
start_and_wait_task_done,
)
class RiceRoundDecryptNode:
def __init__(self):
self.auth_unit = AuthUnit()
self.machine_id = get_machine_id()
self.url_config = RiceUrlConfig()
self.pbar = None
self.last_progress = 0
self.user_token = None
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"rice_template_id": ("STRING", {"default": ""}),
"seed": (
"INT",
{
"default": 0,
"min": 0,
"max": 0xFFFFFFFFFFFFFFFF,
"tooltip": "The random seed used for creating the noise.",
},
),
},
"optional": {"input_anything": ("*", {})},
"hidden": {
"unique_id": "UNIQUE_ID",
"prompt": "PROMPT",
"extra_pnginfo": "EXTRA_PNGINFO",
},
}
@classmethod
def VALIDATE_INPUTS(s, input_types):
for key, value in input_types.items():
if key.startswith("input_anything"):
if value not in ("STRING", "TEXT", "PROMPT"):
return f"{key} must be of string type"
return True
RETURN_TYPES = ("IMAGE",)
OUTPUT_NODE = True
FUNCTION = "execute"
CATEGORY = "RiceRound/Output"
def progress_callback(self, task_uuid, progress_text, progress, preview_refreshed):
if not self.pbar:
return
if preview_refreshed:
url = self.url_config.workflow_preview_url + "?task_uuid=" + task_uuid
try:
headers = {"Authorization": f"Bearer {self.user_token}"}
response = requests.get(url, stream=True, headers=headers)
response.raise_for_status()
preview_image = Image.open(BytesIO(response.content))
self.pbar.update_absolute(
self.last_progress, preview=("PNG", preview_image, None)
)
except Exception as e:
print(f"Failed to load preview image: {str(e)}")
self.pbar.update_absolute(self.last_progress)
else:
self.last_progress = progress
self.pbar.update_absolute(progress)
def execute(self, rice_template_id, **kwargs):
self.pbar = ProgressBar(100)
self.user_token, error_msg, error_code = self.auth_unit.get_user_token()
if not self.user_token:
if (
error_code == RiceRoundErrorDef.HTTP_UNAUTHORIZED
or error_code == RiceRoundErrorDef.NO_TOKEN_ERROR
):
AuthUnit().login_dialog("运行云节点需要先完成登录")
else:
PromptServer.instance.send_sync(
"riceround_toast",
{"content": "无法完成鉴权登录,请检查网络或完成登录步骤", "type": "error"},
)
raise ValueError(error_msg)
index_dict = {}
for k, v in kwargs.items():
if k.startswith("input_anything"):
suffix = k[len("input_anything") :]
suffix = re.sub("\\s*\\([^)]*\\)", "", suffix)
index = 0 if suffix == "" else int(suffix)
if index in index_dict:
raise ValueError(f"Duplicate input_anything index: {index}")
if isinstance(v, str):
index_dict[str(index)] = v
else:
raise ValueError(f"Invalid input type: {type(v)}")
if not index_dict:
return (torch.zeros(1, 1, 1, 3),)
task_info = self.create_task(index_dict, rice_template_id, self.user_token)
if not task_info or not task_info.task_uuid:
raise ValueError("Failed to create task")
start_and_wait_task_done(
self.url_config.task_ws_url,
self.user_token,
self.machine_id,
task_info,
self.progress_callback,
RicePromptInfo().get_wait_time(),
)
model_management.throw_exception_if_processing_interrupted()
result_data = task_info.result_data
if not result_data:
if task_info.progress_text and task_info.state > TaskStatus.FINISHED:
raise ValueError(task_info.progress_text)
else:
raise ValueError("websocket failed")
image_results = result_data.get("image_results", [])
if not image_results:
raise ValueError("Failed to get image results")
images = []
for image_url in image_results:
image = Image.open(requests.get(image_url, stream=True).raw)
image = ImageOps.exif_transpose(image)
images.append(pil2tensor(image))
image_tensor = torch.cat(images, dim=0)
self.pbar = None
return (image_tensor,)
def create_task(self, input_data, template_id, user_token):
task_url = self.url_config.prompt_task_url
headers = {
"Authorization": f"Bearer {user_token}",
"Content-Type": "application/json",
}
request_data = {
"taskData": json.dumps(input_data),
"workData": json.dumps({"template_id": template_id}),
}
response = requests.post(task_url, json=request_data, headers=headers)
if response.status_code == 200:
response_data = response.json()
if response_data.get("code") == 0 and "data" in response_data:
task_info = TaskInfo(response_data.get("data", {}))
if task_info.task_uuid:
return task_info
else:
raise ValueError("No task UUID in response")
else:
raise ValueError(
f"API error: {response_data.get('message','Unknown error')}"
)
elif response.status_code == RiceRoundErrorDef.HTTP_INTERNAL_ERROR:
response_data = response.json()
if (
response_data.get("code")
== RiceTaskErrorDef.ERROR_INSUFFICIENT_PERMISSION_INSUFFICIENT_BALANCE
):
PromptServer.instance.send_sync(
"riceround_show_workflow_payment_dialog",
{"template_id": template_id, "title": "余额不足,请充值"},
)
raise ValueError(f"余额不足,运行失败,请完成支付后重试!")
else:
raise ValueError(
f"API error: {response_data.get('message','Unknown error')}"
)
else:
raise ValueError(f"HTTP error {response.status_code}: {response.text}")
class RiceRoundBaseChoiceNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(cls):
node_name = getattr(cls, "__node_name__", None)
options = (
RicePromptInfo().get_choice_node_options(node_name) if node_name else []
)
return {
"required": {
"name": ("STRING", {"default": "Parameter"}),
"default": (options,),
},
"optional": {},
"hidden": {},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
FUNCTION = "placeholder"
CATEGORY = "__hidden__"
def placeholder(self, default, **kwargs):
return (default,)
def upload_imagefile(image_path):
user_token, error_msg, error_code = AuthUnit().get_user_token()
if not user_token:
if (
error_code == RiceRoundErrorDef.HTTP_UNAUTHORIZED
or error_code == RiceRoundErrorDef.NO_TOKEN_ERROR
):
AuthUnit().login_dialog("运行云节点需要先完成登录")
else:
PromptServer.instance.send_sync(
"riceround_toast", {"content": "无法完成鉴权登录,请检查网络或完成登录步骤", "type": "error"}
)
raise ValueError(error_msg)
return user_upload_imagefile(image_path, user_token)
def upload_image(image):
user_token, error_msg, error_code = AuthUnit().get_user_token()
if not user_token:
if (
error_code == RiceRoundErrorDef.HTTP_UNAUTHORIZED
or error_code == RiceRoundErrorDef.NO_TOKEN_ERROR
):
AuthUnit().login_dialog("运行云节点需要先完成登录")
else:
PromptServer.instance.send_sync(
"riceround_toast", {"content": "无法完成鉴权登录,请检查网络或完成登录步骤", "type": "error"}
)
raise ValueError(error_msg)
return user_upload_image(image, user_token)
class RiceRoundImageUrlNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {"required": {"image_url": ("STRING",)}}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "load_image"
CATEGORY = "RiceRound/Output"
def load_image(self, image_url, **kwargs):
return (image_url,)
class RiceRoundUploadImageNode(LoadImage):
def __init__(self):
super().__init__()
@classmethod
def INPUT_TYPES(s):
input_dir = folder_paths.get_input_directory()
files = [
f
for f in os.listdir(input_dir)
if os.path.isfile(os.path.join(input_dir, f))
]
return {"required": {"image": (sorted(files), {"image_upload": True})}}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "load_image"
CATEGORY = "RiceRound/Output"
def load_image(self, image, **kwargs):
image_path = folder_paths.get_annotated_filepath(image)
download_url = upload_imagefile(image_path)
return (download_url,)
class RiceRoundOutputImageBridgeNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {
"required": {"images": ("IMAGE", {"tooltip": "only image."})},
"optional": {},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "bridge"
CATEGORY = "RiceRound/Output"
def bridge(self, images, **kwargs):
return upload_image(images)
class RiceRoundOutputMaskBridgeNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {"required": {"mask": ("MASK",)}}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "bridge"
CATEGORY = "RiceRound/Output"
def bridge(self, mask, **kwargs):
mask_np = mask.cpu().numpy()
mask_np = (mask_np * 255).astype(np.uint8)
mask_image = Image.fromarray(mask_np)
image_url = upload_image(mask_image)
return (image_url,)
class RiceRoundMaskUrlNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {"required": {"mask_url": ("STRING",)}}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "load_image"
CATEGORY = "RiceRound/Output"
def load_image(self, mask_url, **kwargs):
return (mask_url,)
class RiceRoundOutputIntNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"name": ("STRING", {"default": "数值"}),
"number": ("INT",),
"min": ("INT", {"default": 0}),
"max": ("INT", {"default": 1000000}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "bridge"
CATEGORY = "RiceRound/Output"
def bridge(self, name, number, min, max, **kwargs):
return (str(number),)
class RiceRoundOutputFloatNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"name": ("STRING", {"default": "数值"}),
"number": ("FLOAT",),
"min": ("FLOAT", {"default": 0.0}),
"max": ("FLOAT", {"default": 1e6}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "bridge"
CATEGORY = "RiceRound/Output"
def bridge(self, name, number, min, max, **kwargs):
return (str(number),)
class RiceRoundOutputBooleanNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"name": ("STRING", {"default": "开关"}),
"value": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "bridge"
CATEGORY = "RiceRound/Output"
def bridge(self, name, value, **kwargs):
str_value = "true" if value else "false"
return (str_value,)
class RiceRoundOutputTextNode:
def __init__(self):
0
@classmethod
def INPUT_TYPES(s):
return {"required": {"name": ("STRING", {"default": "文本"}), "str": ("STRING",)}}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("value",)
OUTPUT_NODE = True
FUNCTION = "bridge"
CATEGORY = "RiceRound/Output"
def bridge(self, name, str, **kwargs):
return (str,)