Archived
158 lines
5.6 KiB
Python
158 lines
5.6 KiB
Python
from __future__ import annotations
|
|
import os
|
|
import sys
|
|
import json
|
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
|
|
|
|
import folder_paths
|
|
from PIL.PngImagePlugin import PngInfo
|
|
from PIL import Image
|
|
import numpy as np
|
|
|
|
class ImageLabSaveImage:
|
|
def __init__(self):
|
|
self.output_dir = folder_paths.get_output_directory()
|
|
self.type = "output"
|
|
self.prefix_append = ""
|
|
self.compress_level = 4
|
|
|
|
@classmethod
|
|
def INPUT_TYPES(s):
|
|
return {
|
|
"required": {
|
|
"images": ("IMAGE", {"tooltip": "The images to save."}),
|
|
"filename_prefix": ("STRING", {"default": "ImageLab", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."})
|
|
},
|
|
"hidden": {
|
|
"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"
|
|
},
|
|
}
|
|
|
|
RETURN_TYPES = ()
|
|
FUNCTION = "save_images"
|
|
|
|
OUTPUT_NODE = True
|
|
|
|
CATEGORY = "image"
|
|
DESCRIPTION = "Saves the input images to your ComfyUI output directory."
|
|
|
|
def save_images(self, images, filename_prefix="ImageLab", prompt=None, extra_pnginfo=None):
|
|
filename_prefix += self.prefix_append
|
|
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
|
|
results = list()
|
|
for (batch_number, image) in enumerate(images):
|
|
i = 255. * image.cpu().numpy()
|
|
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
|
|
metadata = PngInfo()
|
|
|
|
# add comfyui specific workflow metadata
|
|
if prompt is not None:
|
|
metadata.add_text("prompt", json.dumps(prompt))
|
|
|
|
# add imagelab parameters metadata
|
|
if extra_pnginfo is not None:
|
|
for x in extra_pnginfo:
|
|
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
|
|
|
|
filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
|
|
file = f"{filename_with_batch_num}_{counter:05}_.png"
|
|
img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level)
|
|
results.append({
|
|
"filename": file,
|
|
"subfolder": subfolder,
|
|
"type": self.type
|
|
})
|
|
counter += 1
|
|
|
|
return { "ui": { "images": results } }
|
|
|
|
import hashlib
|
|
import os
|
|
import torch
|
|
import numpy as np
|
|
from PIL import Image
|
|
from io import BytesIO
|
|
|
|
def is_changed_file(filepath):
|
|
"""Check if file has changed using MD5 hash."""
|
|
try:
|
|
with open(filepath, "rb") as f:
|
|
file_hash = hashlib.md5(f.read()).hexdigest()
|
|
if not hasattr(is_changed_file, "file_hashes"):
|
|
is_changed_file.file_hashes = {}
|
|
if filepath in is_changed_file.file_hashes:
|
|
if is_changed_file.file_hashes[filepath] == file_hash:
|
|
return False
|
|
is_changed_file.file_hashes[filepath] = file_hash
|
|
return float("NaN") # Signals ComfyUI that the node needs re-execution
|
|
except Exception as e:
|
|
print(f"Error checking file {filepath}: {e}")
|
|
return False
|
|
|
|
class WatchImageFile:
|
|
"""Watches a specific image file for changes and loads it when changed."""
|
|
|
|
_watched_path = None # Class variable to store path for IS_CHANGED
|
|
|
|
@classmethod
|
|
def INPUT_TYPES(cls):
|
|
return {
|
|
"required": {
|
|
"file_path": ("STRING", {
|
|
"default": "C:/path/to/your/image.png",
|
|
"multiline": False
|
|
}),
|
|
"wait_for_changes": ("BOOLEAN", {"default": True}),
|
|
}
|
|
}
|
|
|
|
RETURN_TYPES = ("IMAGE", "INT", "INT")
|
|
RETURN_NAMES = ("image", "width", "height")
|
|
FUNCTION = "load_image"
|
|
CATEGORY = "image"
|
|
|
|
def load_image(self, file_path, wait_for_changes):
|
|
# Store path for IS_CHANGED to access
|
|
WatchImageFile._watched_path = file_path
|
|
|
|
if not os.path.exists(file_path):
|
|
# Return a blank image if file doesn't exist
|
|
print(f"File not found: {file_path}")
|
|
blank = Image.new("RGB", (512, 512), (0, 0, 0))
|
|
img_array = np.array(blank).astype(np.float32) / 255.0
|
|
return (torch.from_numpy(img_array)[None,], 512, 512)
|
|
|
|
try:
|
|
with open(file_path, "rb") as f:
|
|
img_data = f.read()
|
|
|
|
img = Image.open(BytesIO(img_data))
|
|
img = img.convert("RGB")
|
|
width, height = img.size
|
|
|
|
img_array = np.array(img).astype(np.float32) / 255.0
|
|
img_tensor = torch.from_numpy(img_array)[None,]
|
|
|
|
return (img_tensor, width, height)
|
|
except Exception as e:
|
|
print(f"Error loading image: {e}")
|
|
blank = Image.new("RGB", (512, 512), (0, 0, 0))
|
|
img_array = np.array(blank).astype(np.float32) / 255.0
|
|
return (torch.from_numpy(img_array)[None,], 512, 512)
|
|
|
|
@classmethod
|
|
def IS_CHANGED(cls, file_path, wait_for_changes):
|
|
if not wait_for_changes:
|
|
return float("NaN") # Always re-execute if not waiting
|
|
return is_changed_file(file_path)
|
|
|
|
|
|
NODE_CLASS_MAPPINGS = {
|
|
"WatchImageFile": WatchImageFile,
|
|
"ImageLabSaveImage": ImageLabSaveImage,
|
|
}
|
|
|
|
NODE_DISPLAY_NAME_MAPPINGS = {
|
|
"WatchImageFile": "Watch Image File",
|
|
"ImageLabSaveImage": "ImageLab Save Image",
|
|
} |