Compare commits

...
11 Commits
11 changed files with 251 additions and 29 deletions
-11
View File
@@ -34,14 +34,3 @@ body:
![DESCRIPTION](LINK.png)
validations:
required: false
- type: dropdown
id: version
attributes:
label: "Version"
description: What version are you running?
multiple: false
options:
- 1.0.0
default: 0
validations:
required: false
+9
View File
@@ -1,4 +1,13 @@
# Change Log
## v1.2.0
- Add `Parameter Extractor` node #24
- Add a model matching feature to the `Prompt Reader` node #24
- Add `save_metadata_file` option to the `Prompt Saver` node #30
- Add `FILE_PATH` output to the `Prompt Saver` node #26
- Fix the issue where the `Prompt Merger` node threw an error when merging empty strings #29
- Enhance the `Batch Loader` node to support processing either a single file or a list of files #26
- Update core to 1.3.4.post1
## v1.1.0
- Add `Batch Loader` node #13
- Add `MODEL_NAME` output to the `Prompt Reader` node #23
+28 -4
View File
@@ -23,7 +23,7 @@ additional metadata to ensure compatibility with metadata detection on websites
<a href="./CHANGELOG.md">Change Log</a> •
<a href="#credits">Credits</a>
</p>
<img src="./images/screenshot_v110.png">
<img src="./images/screenshot_v120.png">
</div>
@@ -80,6 +80,15 @@ you will need to modify the `parameter_index` to select the parameters you need
- For images generated by SDXL and containing multiple sets of prompts,
the `text_g` will be combined with `text_l` into a single prompt
- For batch processing, please use the `Batch Loader` node.
- To read parameters other than the existing output, please connect the `settings` to the `Parameter Extractor` node.
- `MODEL_NAME` is a special output that matches the model name in the metadata with the existing models on the server
according to the following priority:
1. Identical path, filename, and extension.
2. Identical filename, and extension.
e.g. `sd_xl_base.safetensors` will be matched with `SDXL\sd_xl_base.safetensors`, and vice versa.
3. Identical filename.
e.g. `sd_xl_base` will be matched with `SDXL\sd_xl_base.safetensors`, and vice versa.
4. If a matching model cannot be found, the original name will be outputted.
<div align="center">
<img src="./images/reader.png" width="25%" height="25%" alt="reader node">
@@ -117,6 +126,8 @@ in the built-in Saver node, it will count all image files in the `path`.
e.g. `file.png, file_1.png, file_2.png`.
- For the `date_format` and `time_format`, please refer to
[strftime.org](https://strftime.org/) or [www.strfti.me](https://www.strfti.me/).
- When the `save_metadata_file` is turned on, the metadata will be saved as a TXT file with the same name
alongside the image.
<div align="center">
<img src="./images/saver.png" width="25%" height="25%" alt="saver node">
@@ -140,17 +151,30 @@ required by the refiner `KSampler` under the selected step ratio.
</div>
### Batch Loader Node
- The `Batch Loader` node is specifically designed for the `Prompt Reader` node to batch-read image files in a directory
- The `Batch Loader` Node is specifically designed for the `Prompt Reader` Node to batch-read image files in a directory
and cannot be used with other custom nodes.
- For batch processing, please connect the `IMAGE` output of the `Batch Loader` node to the `image` input of
the `Prompt Reader` node.
- For batch processing, please connect the `IMAGE` output of the `Batch Loader` Node to the `image` input of
the `Prompt Reader` Node.
- The `path` supports relative paths such as `./input/` or absolute paths like `C:/Users/receyuki/Pictures`.
- Both `\ ` and `/` are acceptable.
- You can also input a single file or a list of files into the `path`,
in which case the `image_load_limit` and `start_index` will not function.
<div align="center">
<img src="./images/loader.png" width="25%" height="25%" alt="loader node">
</div>
### Parameter Extractor Node
- The `Parameter Extractor` Node is an extension of the `Prompt Reader` Node, designed to retrieve the values
of all parameters in the settings (including those parameters that the `Prompt Reader` Node cannot output).
e.g. `Hires upscaler`
- Connect the `SETTINGS` of the `Prompt Reader` Node to the `settings` of the `Parameter Extractor` Node.
After the first run, the parameter list will be loaded.
<div align="center">
<img src="./images/extractor.png" width="25%" height="25%" alt="extractor node">
</div>
### Prompt Merger Node & Type Converter Node
- Since the A1111 format cannot store `text_g` and `text_l` separately, SDXL users need to use
the `Prompt Merger` Node to combine `text_g` and `text_l` into a single prompt.
+1
View File
@@ -17,6 +17,7 @@ files_to_copy = [
"parameterDisplay.js",
"seedGen.js",
"loaderDisplay.js",
"extractorDisplay.js",
]
for file in files_to_copy:
+1 -1
View File
@@ -1 +1 @@
VERSION = "1.1.0"
VERSION = "1.2.0"
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 507 KiB

After

Width:  |  Height:  |  Size: 512 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+38
View File
@@ -0,0 +1,38 @@
import {app} from "../../scripts/app.js";
import {ComfyWidgets} from "../../scripts/widgets.js";
// Create a read-only string widget
function createWidget(app, node, widgetName, type) {
const widget = ComfyWidgets[type](node, widgetName, ["STRING", {multiline: true}], app).widget;
widget.inputEl.readOnly = true;
widget.inputEl.style.textAlign = "center";
widget.inputEl.style.fontSize = "0.75rem";
return widget;
}
app.registerExtension({
name: "sd_prompt_reader.extractorDisplay",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "SDParameterExtractor") {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
// Create widgets
const value_display = createWidget(app, this, "value_display", "STRING");
};
// Update widgets
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
onExecuted?.apply(this, arguments);
this.widgets.find(obj => obj.name === "value_display").value = message.text[1]
this.widgets.find(obj => obj.name === "parameter").options.values = message.text[0]
if (this.widgets.find(obj => obj.name === "parameter").value === "parameters not loaded") {
this.widgets.find(obj => obj.name === "parameter").value = message.text[0][0]
}
};
}
},
});
+173 -12
View File
@@ -12,6 +12,7 @@ from itertools import chain
import torch
import json
import re
import numpy as np
from pathlib import Path
from PIL import Image, ImageOps
@@ -65,9 +66,17 @@ any_type = AnyType("*")
class SDPromptReader:
files = []
ckpt_paths = []
ckpt_names = []
ckpt_stems = []
@classmethod
def INPUT_TYPES(s):
for path in folder_paths.get_filename_list("checkpoints"):
SDPromptReader.ckpt_paths.append(path)
SDPromptReader.ckpt_names.append(Path(path).name)
SDPromptReader.ckpt_stems.append(Path(path).stem)
input_dir = folder_paths.get_input_directory()
SDPromptReader.files = sorted(
[
@@ -170,6 +179,9 @@ class SDPromptReader:
output_to_terminal("Positive: \n" + image_data.positive)
output_to_terminal("Negative: \n" + image_data.negative)
output_to_terminal("Setting: \n" + image_data.setting)
model = self.search_model(model)
return {
"ui": {
"text": (image_data.positive, image_data.negative, image_data.setting)
@@ -195,6 +207,27 @@ class SDPromptReader:
data_list = data.strip("()").split(",")
return data_list[0] if len(data_list) == 1 else data_list[index]
@staticmethod
def search_model(model: str):
if not model or model in SDPromptReader.ckpt_paths:
return model
model_path = Path(model)
model_name = model_path.name
model_stem = model_path.stem
if model_name in SDPromptReader.ckpt_names:
return SDPromptReader.ckpt_paths[
SDPromptReader.ckpt_names.index(model_name)
]
if model_stem in SDPromptReader.ckpt_stems:
return SDPromptReader.ckpt_paths[
SDPromptReader.ckpt_stems.index(model_stem)
]
return model
@classmethod
def IS_CHANGED(s, image, parameter_index):
image_path = folder_paths.get_annotated_filepath(image)
@@ -277,13 +310,14 @@ class SDPromptSaver:
"STRING",
{"default": "%H%M%S", "multiline": False},
),
"save_metadata_file": ("BOOLEAN", {"default": False}),
"extra_info": ("STRING", {"default": "", "multiline": True}),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("FILENAME", "METADATA")
RETURN_TYPES = ("STRING", "STRING", "STRING")
RETURN_NAMES = ("FILENAME", "FILE_PATH", "METADATA")
FUNCTION = "save_images"
OUTPUT_NODE = True
@@ -314,6 +348,7 @@ class SDPromptSaver:
jpg_webp_quality: int = 100,
date_format: str = "%Y-%m-%d",
time_format: str = "%H%M%S",
save_metadata_file: bool = False,
extra_info: str = "",
prompt=None,
extra_pnginfo=None,
@@ -334,6 +369,7 @@ class SDPromptSaver:
results = []
files = []
comments = []
file_paths = []
for image in images:
# model_name_str, sampler_name_str, scheduler_str = None, None, None
@@ -386,6 +422,7 @@ class SDPromptSaver:
stem = self.get_path(filename, variable_map)
file = self.get_unique_filename(stem, extension, output_folder)
file_path = output_folder / file
if extension == "png":
if not args.disable_metadata:
@@ -397,13 +434,13 @@ class SDPromptSaver:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
img.save(
output_folder / file,
file_path,
pnginfo=metadata,
compress_level=4,
)
else:
img.save(
output_folder / file,
file_path,
quality=jpg_webp_quality,
lossless=lossless_webp,
)
@@ -417,15 +454,21 @@ class SDPromptSaver:
},
}
)
piexif.insert(metadata, str(output_folder / file))
piexif.insert(metadata, str(file_path))
if save_metadata_file:
with open(file_path.with_suffix(".txt"), "w", encoding="utf-8") as f:
f.write(comment)
results.append(
{"filename": file.name, "subfolder": str(subfolder), "type": self.type}
)
files.append(str(file))
file_paths.append(str(file_path))
output_to_terminal("Saved file: " + str(file))
comments.append(comment)
return {"ui": {"images": results}, "result": (files, comments)}
return {"ui": {"images": results}, "result": (files, file_paths, comments)}
@staticmethod
def calculate_model_hash(model_name):
@@ -745,7 +788,8 @@ class SDPromptMerger:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"required": {},
"optional": {
"text_g": (
"STRING",
{"default": "", "multiline": True, "forceInput": True},
@@ -761,10 +805,8 @@ class SDPromptMerger:
FUNCTION = "merge_prompt"
CATEGORY = "SD Prompt Reader"
def merge_prompt(self, text_g, text_l):
if text_l == "":
return text_g
return (text_g + "\n" + text_l,)
def merge_prompt(self, text_g="", text_l=""):
return (text_g + ("\n" + text_l if text_g and text_l else text_l),)
class SDTypeConverter:
@@ -836,7 +878,22 @@ class SDBatchLoader:
image_load_limit: int = 0,
start_index: int = 0,
):
if not Path(path).is_dir():
if isinstance(path, list):
files_str = [str(Path(p)) for p in path if Path(p).exists()]
return {
"ui": {
"text": ("\n".join(files_str),),
},
"result": (files_str,),
}
elif Path(path).is_file():
return {
"ui": {
"text": (str(Path(path)),),
},
"result": ([str(Path(path))],),
}
elif not Path(path).is_dir():
raise FileNotFoundError(f"Invalid directory: {path}")
files = list(
@@ -873,11 +930,113 @@ class SDBatchLoader:
image_load_limit,
start_index,
):
if Path(path).is_file():
return True
if not Path(path).is_dir():
return f"Invalid directory: {path}"
return True
class SDParameterExtractor:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"settings": (
"STRING",
{"default": "", "multiline": True, "forceInput": True},
)
},
"optional": {
"parameter": (
["parameters not loaded"],
{"default": "parameters not loaded"},
),
"value_type": (["STRING", "INT", "FLOAT"], {"default": "STRING"}),
"parameter_index": (
"INT",
{"default": 0, "min": 0, "max": 255, "step": 1},
),
},
}
RETURN_TYPES = (any_type,)
RETURN_NAMES = ("VALUE",)
OUTPUT_NODE = True
FUNCTION = "extract_param"
CATEGORY = "SD Prompt Reader"
def extract_param(
self,
settings: str = "",
parameter: str = "",
value_type: str = "STRING",
parameter_index: int = 0,
):
setting_dict = self.parse_setting(settings)
if not settings or not parameter or parameter == "parameters not loaded":
return {
"ui": {
"text": (list(setting_dict.keys()), ""),
},
"result": ("",),
}
result = setting_dict.get(parameter)
try:
if isinstance(result, tuple):
result = result[parameter_index]
if value_type == "INT":
result = int(result)
elif value_type == "FLOAT":
result = float(result)
except IndexError:
return {
"ui": {
"text": (list(setting_dict.keys()), "Parameter index out of range"),
},
"result": ("",),
}
except (ValueError, TypeError):
return {
"ui": {
"text": (
list(setting_dict.keys()),
f"{parameter}: {result}\n"
f"{result} is not a valid number; it will be output as STRING",
),
},
"result": (result,),
}
return {
"ui": {
"text": (list(setting_dict.keys()), f"{parameter}: {result}"),
},
"result": (result,),
}
@staticmethod
def parse_setting(settings):
pattern = re.compile(r"([^:,]+):\s*\(([^)]+)\)|([^:,]+):\s*([^,]+)")
matches = pattern.findall(settings)
result = {}
for match in matches:
key, value_paren, key_nonparen, value_nonparen = match
if key:
key = key.strip()
value = value_paren.strip()
value = tuple(v.strip() for v in value.split(","))
else:
key = key_nonparen.strip()
value = value_nonparen.strip()
result[key] = value
return result
NODE_CLASS_MAPPINGS = {
"SDPromptReader": SDPromptReader,
"SDPromptSaver": SDPromptSaver,
@@ -885,6 +1044,7 @@ NODE_CLASS_MAPPINGS = {
"SDPromptMerger": SDPromptMerger,
"SDTypeConverter": SDTypeConverter,
"SDBatchLoader": SDBatchLoader,
"SDParameterExtractor": SDParameterExtractor,
}
NODE_DISPLAY_NAME_MAPPINGS = {
@@ -894,4 +1054,5 @@ NODE_DISPLAY_NAME_MAPPINGS = {
"SDPromptMerger": "SD Prompt Merger",
"SDTypeConverter": "SD Type Converter",
"SDBatchLoader": "SD Batch Loader",
"SDParameterExtractor": "SD Parameter Extractor",
}