Spaces:
Running
Running
File size: 10,186 Bytes
681fa96 |
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 os
import hashlib
from datetime import datetime
import json
import piexif
import piexif.helper
from PIL import Image, ExifTags
from PIL.PngImagePlugin import PngInfo
import numpy as np
import folder_paths
import comfy.sd
from nodes import MAX_RESOLUTION
def parse_name(ckpt_name):
path = ckpt_name
filename = path.split("/")[-1]
filename = filename.split(".")[:-1]
filename = ".".join(filename)
return filename
def calculate_sha256(file_path):
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
# Read the file in chunks to avoid loading the entire file into memory
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def handle_whitespace(string: str):
return string.strip().replace("\n", " ").replace("\r", " ").replace("\t", " ")
def get_timestamp(time_format):
now = datetime.now()
try:
timestamp = now.strftime(time_format)
except:
timestamp = now.strftime("%Y-%m-%d-%H%M%S")
return timestamp
def make_pathname(filename, seed, modelname, counter, time_format):
filename = filename.replace("%date", get_timestamp("%Y-%m-%d"))
filename = filename.replace("%time", get_timestamp(time_format))
filename = filename.replace("%model", modelname)
filename = filename.replace("%seed", str(seed))
filename = filename.replace("%counter", str(counter))
return filename
def make_filename(filename, seed, modelname, counter, time_format):
filename = make_pathname(filename, seed, modelname, counter, time_format)
return get_timestamp(time_format) if filename == "" else filename
class SeedGenerator:
RETURN_TYPES = ("INT",)
FUNCTION = "get_seed"
CATEGORY = "ImageSaverTools/utils"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff})}}
def get_seed(self, seed):
return (seed,)
class StringLiteral:
RETURN_TYPES = ("STRING",)
FUNCTION = "get_string"
CATEGORY = "ImageSaverTools/utils"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"string": ("STRING", {"default": "", "multiline": True})}}
def get_string(self, string):
return (string,)
class SizeLiteral:
RETURN_TYPES = ("INT",)
FUNCTION = "get_int"
CATEGORY = "ImageSaverTools/utils"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"int": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 8})}}
def get_int(self, int):
return (int,)
class IntLiteral:
RETURN_TYPES = ("INT",)
FUNCTION = "get_int"
CATEGORY = "ImageSaverTools/utils"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"int": ("INT", {"default": 0, "min": 0, "max": 1000000})}}
def get_int(self, int):
return (int,)
class CfgLiteral:
RETURN_TYPES = ("FLOAT",)
FUNCTION = "get_float"
CATEGORY = "ImageSaverTools/utils"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"float": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0})}}
def get_float(self, float):
return (float,)
class CheckpointSelector:
CATEGORY = 'ImageSaverTools/utils'
RETURN_TYPES = (folder_paths.get_filename_list("checkpoints"),)
RETURN_NAMES = ("ckpt_name",)
FUNCTION = "get_names"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),}}
def get_names(self, ckpt_name):
return (ckpt_name,)
class SamplerSelector:
CATEGORY = 'ImageSaverTools/utils'
RETURN_TYPES = (comfy.samplers.KSampler.SAMPLERS,)
RETURN_NAMES = ("sampler_name",)
FUNCTION = "get_names"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"sampler_name": (comfy.samplers.KSampler.SAMPLERS,)}}
def get_names(self, sampler_name):
return (sampler_name,)
class SchedulerSelector:
CATEGORY = 'ImageSaverTools/utils'
RETURN_TYPES = (comfy.samplers.KSampler.SCHEDULERS,)
RETURN_NAMES = ("scheduler",)
FUNCTION = "get_names"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"scheduler": (comfy.samplers.KSampler.SCHEDULERS,)}}
def get_names(self, scheduler):
return (scheduler,)
class ImageSaveWithMetadata:
def __init__(self):
self.output_dir = folder_paths.output_directory
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images": ("IMAGE", ),
"filename": ("STRING", {"default": f'%time_%seed', "multiline": False}),
"path": ("STRING", {"default": '', "multiline": False}),
"extension": (['png', 'jpeg', 'webp'],),
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
"modelname": (folder_paths.get_filename_list("checkpoints"),),
"sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
"scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
},
"optional": {
"positive": ("STRING", {"default": 'unknown', "multiline": True}),
"negative": ("STRING", {"default": 'unknown', "multiline": True}),
"seed_value": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 8}),
"height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 8}),
"lossless_webp": ("BOOLEAN", {"default": True}),
"quality_jpeg_or_webp": ("INT", {"default": 100, "min": 1, "max": 100}),
"counter": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff }),
"time_format": ("STRING", {"default": "%Y-%m-%d-%H%M%S", "multiline": False}),
},
"hidden": {
"prompt": "PROMPT",
"extra_pnginfo": "EXTRA_PNGINFO"
},
}
RETURN_TYPES = ()
FUNCTION = "save_files"
OUTPUT_NODE = True
CATEGORY = "ImageSaverTools"
def save_files(self, images, seed_value, steps, cfg, sampler_name, scheduler, positive, negative, modelname, quality_jpeg_or_webp,
lossless_webp, width, height, counter, filename, path, extension, time_format, prompt=None, extra_pnginfo=None):
filename = make_filename(filename, seed_value, modelname, counter, time_format)
path = make_pathname(path, seed_value, modelname, counter, time_format)
ckpt_path = folder_paths.get_full_path("checkpoints", modelname)
basemodelname = parse_name(modelname)
modelhash = calculate_sha256(ckpt_path)[:10]
comment = f"{handle_whitespace(positive)}\nNegative prompt: {handle_whitespace(negative)}\nSteps: {steps}, Sampler: {sampler_name}{f'_{scheduler}' if scheduler != 'normal' else ''}, CFG Scale: {cfg}, Seed: {seed_value}, Size: {width}x{height}, Model hash: {modelhash}, Model: {basemodelname}, Version: ComfyUI"
output_path = os.path.join(self.output_dir, path)
if output_path.strip() != '':
if not os.path.exists(output_path.strip()):
print(f'The path `{output_path.strip()}` specified doesn\'t exist! Creating directory.')
os.makedirs(output_path, exist_ok=True)
filenames = self.save_images(images, output_path, filename, comment, extension, quality_jpeg_or_webp, lossless_webp, prompt, extra_pnginfo)
subfolder = os.path.normpath(path)
return {"ui": {"images": map(lambda filename: {"filename": filename, "subfolder": subfolder if subfolder != '.' else '', "type": 'output'}, filenames)}}
def save_images(self, images, output_path, filename_prefix, comment, extension, quality_jpeg_or_webp, lossless_webp, prompt=None, extra_pnginfo=None) -> list[str]:
img_count = 1
paths = list()
for image in images:
i = 255. * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
if images.size()[0] > 1:
filename_prefix += "_{:02d}".format(img_count)
if extension == 'png':
metadata = PngInfo()
metadata.add_text("parameters", comment)
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
filename = f"{filename_prefix}.png"
img.save(os.path.join(output_path, filename), pnginfo=metadata, optimize=True)
else:
filename = f"{filename_prefix}.{extension}"
file = os.path.join(output_path, filename)
img.save(file, optimize=True, quality=quality_jpeg_or_webp, lossless=lossless_webp)
exif_bytes = piexif.dump({
"Exif": {
piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(comment, encoding="unicode")
},
})
piexif.insert(exif_bytes, file)
paths.append(filename)
img_count += 1
return paths
NODE_CLASS_MAPPINGS = {
"Checkpoint Selector": CheckpointSelector,
"Save Image w/Metadata": ImageSaveWithMetadata,
"Sampler Selector": SamplerSelector,
"Scheduler Selector": SchedulerSelector,
"Seed Generator": SeedGenerator,
"String Literal": StringLiteral,
"Width/Height Literal": SizeLiteral,
"Cfg Literal": CfgLiteral,
"Int Literal": IntLiteral,
}
|