Skip to content

Commit

Permalink
新增链路选择节点,并修复小bug
Browse files Browse the repository at this point in the history
  • Loading branch information
zhulu111 committed Sep 11, 2024
1 parent 74caae9 commit 78853b4
Show file tree
Hide file tree
Showing 8 changed files with 214 additions and 72 deletions.
122 changes: 121 additions & 1 deletion __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
import folder_paths
from aiohttp import web
from collections import deque
import inspect
import os
import uuid
import hashlib
import platform
import stat
import nodes
import urllib.request
import numpy as np
import shutil
Expand All @@ -37,6 +39,7 @@
os.makedirs(input_directory, exist_ok=True)
save_input_directory = input_directory + '/temp'
os.makedirs(save_input_directory, exist_ok=True)
load_class = 'bxbSwitch'
def get_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def get_mac_address():
Expand Down Expand Up @@ -80,7 +83,6 @@ def __init__(self, local_port, subdomain):
self.monitoring_thread = None
self.stop_monitoring = False
def create_sdc_ini(self, file_path, subdomain):
# 生成 sdc.toml 文件
config_content = f"""
[common]
server_addr = "{self.server_addr}"
Expand Down Expand Up @@ -1066,6 +1068,122 @@ def compute_vars(input):
input = input.replace(f"%date:{original_format}%", formatted_date)
return input
return compute_vars(filename_prefix)
def is_execution_model_version_supported():
try:
import comfy_execution
return True
except:
return False
class AnyType(str):
def __ne__(self, __value: object) -> bool:
return False
any_typ = AnyType("*")
class AlwaysEqual(str):
def __eq__(self, other):
return True
def onprompt(json_data):
if is_execution_model_version_supported():
pass
else:
nodes_a = json_data['extra_data']['extra_pnginfo']['workflow']['nodes']
delete_arr = []
for index, item in enumerate(nodes_a):
if item['type'] == load_class:
first_value = item['widgets_values'][0]
index = next(
(i for i, value in enumerate(item['widgets_values'][1:], start=1)
if value == first_value),
None
)
if index is not None:
delete_arr.append({
'id': item['id'],
'index': index,
'first_value': first_value
})
for kk, vv in enumerate(delete_arr):
if str(vv['id']) in json_data['prompt']:
keys_to_delete = []
for key, value in json_data['prompt'][str(vv['id'])]['inputs'].items():
if not key.startswith(f"input{vv['index']}") and key != 'select':
keys_to_delete.append(key)
for key in keys_to_delete:
del json_data['prompt'][str(vv['id'])]['inputs'][key]
return json_data
server.PromptServer.instance.add_on_prompt_handler(onprompt)
always_equal = AlwaysEqual("any_value")
class bxbSwitch:
@classmethod
def INPUT_TYPES(s):
dyn_inputs = {
}
select_value = []
new_required = {
"select": ([always_equal for i in range(1, 200)],),
}
if is_execution_model_version_supported():
stack = inspect.stack()
if stack[2].function == 'get_input_info' and stack[3].function == 'add_node':
for x in range(0, 200):
dyn_inputs[f"input{x}"] = (any_typ, {"lazy": True})
inputs = {
"required": new_required,
"optional": dyn_inputs,
"hidden": {"unique_id": "UNIQUE_ID", "extra_pnginfo": "EXTRA_PNGINFO", 'nodes': [],
"select_index": ("INT", {"default": 1, "min": 1, "max": 999999, "step": 1,
"tooltip": "The input number you want to output among the inputs"}),
}
}
return inputs
RETURN_TYPES = (any_typ, "STRING", "INT")
RETURN_NAMES = ("selected_value", "selected_label", "selected_index")
FUNCTION = "do"
CATEGORY = "sdBxb"
def check_lazy_status(self, *args, **kwargs):
unique_id = kwargs['unique_id']
nodes_a = kwargs['extra_pnginfo']['workflow']['nodes']
if isinstance(unique_id, str):
try:
unique_id = int(unique_id)
except ValueError:
print(f"无法将 unique_id '{unique_id}' 转换为整数")
matching_node = next((node for node in nodes_a if int(node['id']) == unique_id), None)
if matching_node is None:
print(f"无效节点 ID: {unique_id}")
return []
first_value = matching_node['widgets_values'][0]
index = next(
(i for i, value in enumerate(matching_node['widgets_values'][1:], start=1)
if value == first_value),
None
)
if index is None:
return []
input_name = 'input' + str(index)
return [input_name]
@staticmethod
def do(*args, **kwargs):
unique_id = kwargs['unique_id']
nodes_a = kwargs['extra_pnginfo']['workflow']['nodes']
if isinstance(unique_id, str):
try:
unique_id = int(unique_id)
except ValueError:
return None, "", -1
matching_node = next((node for node in nodes_a if int(node['id']) == unique_id), None)
if matching_node is None:
print(f" ID: {unique_id}")
return None, "", -1
first_value = matching_node['widgets_values'][0]
index = next(
(i for i, value in enumerate(matching_node['widgets_values'][1:], start=1)
if value == first_value),
None
)
if index is None:
print(f" ID: {unique_id}")
return None, "", -1
return kwargs['input' + str(index)], first_value, index
class sdBxb_saveImage:
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
Expand Down Expand Up @@ -1113,9 +1231,11 @@ def save_images(self, images, filename_prefix="ComfyUI"):
"sdBxb": sdBxb,
"sdBxb_textInput": sdBxb_textInput,
"sdBxb_saveImage": sdBxb_saveImage,
"bxbSwitch": bxbSwitch,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"sdBxb": "sdBxb",
"sdBxb_textInput": "textInput",
"sdBxb_saveImage": "saveImage",
"bxbSwitch": "bxbSwitch",
}
52 changes: 26 additions & 26 deletions huise_admin/assets/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion huise_admin/input.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 17 additions & 14 deletions public.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import aiohttp
import folder_paths
from PIL import Image, ImageDraw
from PIL import Image
import traceback
import json
import sys
Expand All @@ -15,16 +15,14 @@
import urllib.request
import urllib.parse
import filetype
import subprocess
args = parser.parse_args()
if args and args.listen:
pass
else:
args = parser.parse_args([])
import time
import random
import asyncio
from urllib.parse import urlparse, urlunparse
from urllib.parse import urlparse
try:
resample_filter = Image.Resampling.LANCZOS
except AttributeError:
Expand Down Expand Up @@ -545,13 +543,18 @@ def send_binary_data_async(upload_url, file_path, is_binary=False, mime_type='im
headers = {
'Content-Type': mime_type,
}
if is_binary:
binary_data = file_path
else:
with open(file_path, 'rb') as file:
binary_data = file.read()
response = requests.put(upload_url, data=binary_data, headers=headers)
if response.status_code == 200:
return True
else:
return False
try:
if is_binary:
binary_data = file_path
else:
with open(file_path, 'rb') as file:
binary_data = file.read()
response = requests.put(upload_url, data=binary_data, headers=headers)
if response.status_code == 200:
return True, ''
else:
error_message = f"Error uploading file. Status code: {response.status_code}, Reason: {response.reason}, Response text: {response.text}"
return False, error_message
except Exception as e:
error_message = f"An error occurred while uploading the file: {str(e)}"
return False, error_message
41 changes: 26 additions & 15 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,24 +196,35 @@ def is_valid_exe(exe):
return result.returncode == 0
except Exception:
return False
from io import BytesIO
def get_image_dimensions(input_file, custom_data=None):
with Image.open(input_file) as img:
width, height = img.size
# if custom_data:
# if img.format == 'PNG':
# meta = PngImagePlugin.PngInfo()
# for key, value in custom_data.items():
# if isinstance(value, bytes):
# value = base64.b64encode(value).decode('utf-8')
# meta.add_text(key, value)
# img.save(input_file, "PNG", pnginfo=meta)
# elif img.format == 'JPEG':
# exif_dict = {}
# for key, value in custom_data.items():
# exif_dict[key] = value
# img.save(input_file, "JPEG", exif=exif_dict)
file_size_bytes = os.path.getsize(input_file)
file_size_mb = file_size_bytes / (1024 * 1024)
img_format = img.format
if not custom_data or (img_format != 'PNG' and img_format != 'JPEG'):
file_size_bytes = os.path.getsize(input_file)
file_size_mb = file_size_bytes / (1024 * 1024)
return width, height, file_size_mb
img_byte_arr = BytesIO()
if img_format == 'PNG':
meta = PngImagePlugin.PngInfo()
for key, value in custom_data.items():
if isinstance(value, bytes):
value = base64.b64encode(value).decode('utf-8')
meta.add_text(key, value)
img.save(img_byte_arr, format="PNG", pnginfo=meta)
elif img_format == 'JPEG':
img = img.convert("RGB")
exif_dict = {}
for key, value in custom_data.items():
exif_dict[key] = value
img.save(img_byte_arr, format="JPEG", exif=exif_dict)
img_byte_arr.seek(0)
image_bytes = img_byte_arr.getvalue()
with open(input_file, "wb") as f:
f.write(image_bytes)
file_size_bytes = len(image_bytes)
file_size_mb = file_size_bytes / (1024 * 1024)
return width, height, file_size_mb
def get_video_dimensions(input_file):
command = [
Expand Down
1 change: 1 addition & 0 deletions web/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 78853b4

Please sign in to comment.