File size: 8,509 Bytes
1e3b872 |
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 |
import hashlib
import os
import json
from server import PromptServer
from aiohttp import web
import base64
from io import BytesIO
import asyncio
from PIL import Image, ImageOps
import torch
import numpy as np
import folder_paths
# Directory node save settings
CHUNK_SIZE = 1024
dir_painter_node = os.path.dirname(__file__)
extension_path = os.path.join(os.path.abspath(dir_painter_node))
nodes_settings_path = os.path.join(extension_path, "settings_nodes")
# Create directory settings_nodes if not exists
if not os.path.exists(nodes_settings_path):
os.mkdir(nodes_settings_path)
tipsfile = os.path.join(nodes_settings_path, "Stores painter nodes settings.txt")
with open(tipsfile, "w+", encoding="utf-8") as tipsfile:
tipsfile.write("Painter node saved settings!")
# Function create file json file
PREFIX = "_setting.json"
def isFileName(filename):
if (
not filename
and filename is not None
and (type(filename) == str and filename.strip() == "")
):
print("Filename is incorrect")
return False
return True
def create_settings_json(filename):
try:
json_file = os.path.join(nodes_settings_path, filename)
if not os.path.isfile(json_file):
print(f"File settings for '{filename}' is not found! Create file!")
with open(json_file, "w") as f:
json.dump({}, f)
except Exception as e:
print(f"Error: ${e}")
def get_settings_json(filename, notExistCreate=True):
if not isFileName(filename):
return {}
json_file = os.path.join(nodes_settings_path, filename)
if os.path.isfile(json_file):
f = open(json_file, "rb")
try:
load_data = json.load(f)
return load_data
except Exception as e:
print("Error load json file: ", e)
if notExistCreate:
f.close()
os.remove(json_file)
create_settings_json(filename)
finally:
f.close()
else:
create_settings_json(filename)
return {}
# Load json file
@PromptServer.instance.routes.get("/alekpet/loading_node_settings/{nodeName}")
async def loadingSettings(request):
filename = request.match_info.get("nodeName", None)
if not isFileName(filename):
load_data = {}
else:
load_data = get_settings_json(filename + PREFIX)
return web.json_response({"settings_nodes": load_data})
# Save data to json file
@PromptServer.instance.routes.post("/alekpet/save_node_settings")
async def saveSettings(request):
try:
if not request.content_type.startswith("multipart/"):
return web.json_response(
{"error": "multipart/* content type expected"}, status=400
)
reader = await request.multipart()
filename_reader = await reader.next()
filename = await filename_reader.text()
data_reader = await reader.next()
if isFileName(filename):
filename = filename + PREFIX
json_file = os.path.join(nodes_settings_path, filename)
if os.path.isfile(json_file):
with open(json_file, "wb") as f:
while True:
chunk = await data_reader.read_chunk(size=CHUNK_SIZE)
if not chunk:
break
f.write(chunk)
return web.json_response(
{"message": "Painter data saved successfully"}, status=200
)
else:
create_settings_json(filename)
return web.json_response(
{"message": "Painter file settings created!"}, status=200
)
else:
raise Exception("Filename is not found or incorrect!")
except Exception as e:
print("Error save json file: ", e)
return web.json_response({"error": str(e)}, status=500)
# Remove file settings painter node data
@PromptServer.instance.routes.post("/alekpet/remove_node_settings")
async def saveSettings(request):
try:
json_data = await request.json()
filename = json_data.get("name")
if isFileName(filename):
filename = filename + PREFIX
json_file = os.path.join(nodes_settings_path, filename)
os.remove(json_file)
return web.json_response(
{"message": "Painter data removed successfully"}, status=200
)
except OSError as e:
return web.json_response(
{"error": "Error: %s - %s." % (e.filename, e.strerror)}, status=500
)
# Piping image
PAINTER_DICT = {} # Painter nodes dict instances
def toBase64ImgUrl(img):
bytesIO = BytesIO()
img.save(bytesIO, format="PNG")
img_types = bytesIO.getvalue()
img_base64 = base64.b64encode(img_types)
return f"data:image/png;base64,{img_base64.decode('utf-8')}"
@PromptServer.instance.routes.post("/alekpet/check_canvas_changed")
async def check_canvas_changed(request):
json_data = await request.json()
unique_id = json_data.get("unique_id", None)
is_ok = json_data.get("is_ok", False)
if unique_id is not None and unique_id in PAINTER_DICT and is_ok == True:
PAINTER_DICT[unique_id].canvas_set = True
return web.json_response({"status": "Ok"})
return web.json_response({"status": "Error"})
async def wait_canvas_change(unique_id, time_out=40):
for _ in range(time_out):
if (
hasattr(PAINTER_DICT[unique_id], "canvas_set")
and PAINTER_DICT[unique_id].canvas_set == True
):
PAINTER_DICT[unique_id].canvas_set = False
return True
await asyncio.sleep(0.1)
return False
# end - Piping image
class PainterNode(object):
@classmethod
def INPUT_TYPES(self):
self.canvas_set = False
work_dir = folder_paths.get_input_directory()
imgs = [
img
for img in os.listdir(work_dir)
if os.path.isfile(os.path.join(work_dir, img))
]
return {
"required": {"image": (sorted(imgs),)},
"hidden": {"unique_id": "UNIQUE_ID"},
"optional": {"images": ("IMAGE",), "update_node": (([True, False],))},
}
RETURN_TYPES = ("IMAGE", "MASK")
FUNCTION = "painter_execute"
CATEGORY = "AlekPet Nodes/image"
def painter_execute(self, image, unique_id, update_node=True, images=None):
# Piping image input
if unique_id not in PAINTER_DICT:
PAINTER_DICT[unique_id] = self
if update_node == True and images is not None:
input_images = []
for imgs in images:
i = 255.0 * imgs.cpu().numpy()
i = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
input_images.append(toBase64ImgUrl(i))
PAINTER_DICT[unique_id].canvas_set = False
PromptServer.instance.send_sync(
"alekpet_get_image", {"unique_id": unique_id, "images": input_images}
)
if not asyncio.run(wait_canvas_change(unique_id)):
print(f"Painter_{unique_id}: Failed to get image!")
else:
print(f"Painter_{unique_id}: Image received, canvas changed!")
# end - Piping image input
image_path = folder_paths.get_annotated_filepath(image)
i = Image.open(image_path)
i = ImageOps.exif_transpose(i)
image = i.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if "A" in i.getbands():
mask = np.array(i.getchannel("A")).astype(np.float32) / 255.0
mask = 1.0 - torch.from_numpy(mask)
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
return (image, mask.unsqueeze(0))
@classmethod
def IS_CHANGED(self, image, unique_id, update_node=True, images=None):
image_path = folder_paths.get_annotated_filepath(image)
m = hashlib.sha256()
with open(image_path, "rb") as f:
m.update(f.read())
return m.digest().hex()
@classmethod
def VALIDATE_INPUTS(self, image, unique_id, update_node=True, images=None):
if not folder_paths.exists_annotated_filepath(image):
return "Invalid image file: {}".format(image)
return True
|