mirror of
https://git.datalinker.icu/comfyanonymous/ComfyUI
synced 2026-11-22 12:57:02 +08:00
- Fixed documentation for dynamic_prompt.py
- Commented out VALIDATE_INPUTS for nodes using dynamic prompts, since I can't get it to run without crashing the run.
This commit is contained in:
parent
cbd27a8848
commit
a6c8e43af0
@ -1,46 +1,62 @@
|
|||||||
|
"""Contains functions for processing dynamic prompts."""
|
||||||
import re
|
import re
|
||||||
import random
|
import random
|
||||||
|
from typing import List, Literal, Union
|
||||||
|
|
||||||
# This function is used to strip comments from a string.
|
|
||||||
# It supports both single-line and multi-line comments of the following formats:
|
def strip_comments(text: str) -> str:
|
||||||
# // Single-line comment
|
"""
|
||||||
# /* Multi-line comment */
|
Strips comments from a string.
|
||||||
#
|
Supports both single-line and multi-line comments of the following formats:
|
||||||
# @param text The string to strip comments from.
|
// Single-line comment
|
||||||
# @return The string with comments stripped.
|
/* Multi-line comment */
|
||||||
def strip_comments(text):
|
|
||||||
|
Args:
|
||||||
|
text (str): The string to strip comments from.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The string with comments stripped.
|
||||||
|
"""
|
||||||
return re.sub(r'/\*.*?\*/|//.*?$', '', text, flags=re.MULTILINE | re.DOTALL)
|
return re.sub(r'/\*.*?\*/|//.*?$', '', text, flags=re.MULTILINE | re.DOTALL)
|
||||||
|
|
||||||
# This function is used to generate a dynamic prompt from a string.
|
|
||||||
# It allows you to include random text in your prompt, contained within option blocks of the following format:
|
def process_dynamic_prompt(text: str) -> str:
|
||||||
# {option1|option2|option3}
|
"""
|
||||||
#
|
Generates a dynamic prompt from a string.
|
||||||
# For example, the following prompt:
|
Allows you to include random text in your prompt, contained within option
|
||||||
# > "This is a {good|great|spectacular} prompt."
|
blocks of the following format:
|
||||||
#
|
{option1|option2|option3}
|
||||||
# Could generate any of the following prompts:
|
|
||||||
# > "This is a good prompt."
|
For example, the following prompt:
|
||||||
# > "This is a great prompt."
|
> "This is a {good|great|spectacular} prompt."
|
||||||
# > "This is a spectacular prompt."
|
|
||||||
#
|
Could generate any of the following prompts:
|
||||||
# If you need to include a '{' or '}' character in your prompt, you can escape it by doubling it, like so:
|
> "This is a good prompt."
|
||||||
# > "This is a {{ and }} character."
|
> "This is a great prompt."
|
||||||
#
|
> "This is a spectacular prompt."
|
||||||
# Which would generate the following prompt:
|
|
||||||
# > "This is a { and } character."
|
If you need to include a '{' or '}' character in your prompt, you can escape
|
||||||
#
|
it by doubling it, like so:
|
||||||
# It also strips comments from the prompt, so you can include comments in your prompt like so:
|
> "This is a {{ and }} character."
|
||||||
#
|
|
||||||
# @param text The string to generate a dynamic prompt from.
|
Which would generate the following prompt:
|
||||||
# @return The generated dynamic prompt.
|
> "This is a { and } character."
|
||||||
def process_dynamic_prompt(text):
|
|
||||||
|
It also strips comments from the prompt, so you can include comments in your prompt like so:
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text (str): The string to generate a dynamic prompt from.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The generated dynamic prompt.
|
||||||
|
"""
|
||||||
prompt = strip_comments(text)
|
prompt = strip_comments(text)
|
||||||
|
|
||||||
new_prompt = ""
|
new_prompt = ""
|
||||||
options = []
|
options: List[str] = []
|
||||||
inside_option = False
|
inside_option = False
|
||||||
|
|
||||||
i = 0
|
i: int = 0
|
||||||
while i < len(prompt):
|
while i < len(prompt):
|
||||||
char = prompt[i]
|
char = prompt[i]
|
||||||
if char == "{":
|
if char == "{":
|
||||||
@ -49,7 +65,6 @@ def process_dynamic_prompt(text):
|
|||||||
options[-1] += char
|
options[-1] += char
|
||||||
i += 2
|
i += 2
|
||||||
continue
|
continue
|
||||||
else:
|
|
||||||
raise ValueError(f"Option block opened at position {i} inside another option block. "
|
raise ValueError(f"Option block opened at position {i} inside another option block. "
|
||||||
"Each option block should be closed before starting a new one. "
|
"Each option block should be closed before starting a new one. "
|
||||||
"If you want to include a '{' inside an option block, use '{{'.")
|
"If you want to include a '{' inside an option block, use '{{'.")
|
||||||
@ -71,9 +86,11 @@ def process_dynamic_prompt(text):
|
|||||||
i += 2
|
i += 2
|
||||||
continue
|
continue
|
||||||
if not inside_option:
|
if not inside_option:
|
||||||
raise ValueError(f"Option block closed at position {i} without being opened. "
|
raise ValueError(
|
||||||
|
f"Option block closed at position {i} without being opened. "
|
||||||
"Make sure each '{' has a matching '}'. "
|
"Make sure each '{' has a matching '}'. "
|
||||||
"If you want to include a '}' without closing an option block, use '}}'.")
|
"If you want to include a '}' without closing an option block, use '}}'."
|
||||||
|
)
|
||||||
inside_option = False
|
inside_option = False
|
||||||
random_option = random.choice(options[-1].split("|"))
|
random_option = random.choice(options[-1].split("|"))
|
||||||
new_prompt += random_option
|
new_prompt += random_option
|
||||||
@ -85,40 +102,62 @@ def process_dynamic_prompt(text):
|
|||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
if inside_option:
|
if inside_option:
|
||||||
raise ValueError("Option block opened but not closed. "
|
raise ValueError(
|
||||||
|
"Option block opened but not closed. "
|
||||||
"Make sure each '{' has a matching '}'. "
|
"Make sure each '{' has a matching '}'. "
|
||||||
"If you want to include a '}' without closing an option block, use '}}'.")
|
"If you want to include a '}' without closing an option block, use '}}'."
|
||||||
|
)
|
||||||
|
|
||||||
return new_prompt
|
return new_prompt
|
||||||
|
|
||||||
# Checks if the given string is a valid dynamic prompt.
|
|
||||||
# @param text The string to check.
|
def validate_dynamic_prompt(text: str) -> Union[Literal[True], str]:
|
||||||
# @return An error message if the string is not a valid dynamic prompt, True otherwise.
|
"""
|
||||||
def validate_dynamic_prompt(text):
|
Checks if the given string is a valid dynamic prompt.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text (str): The string to check.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: An error message if the string is not a valid dynamic prompt, True otherwise.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
process_dynamic_prompt(text)
|
process_dynamic_prompt(text)
|
||||||
except ValueError as e:
|
except ValueError as err:
|
||||||
print("validate_dynamic_prompt: %s" % str(e))
|
print(f"validate_dynamic_prompt: {err}")
|
||||||
return str(e)
|
return str(err)
|
||||||
|
|
||||||
print("validate_dynamic_prompt: True")
|
print("validate_dynamic_prompt: True")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Checks if the given string contains any dynamic prompts.
|
|
||||||
# @param text The string to check.
|
def contains_dynamic_prompt(text: str) -> bool:
|
||||||
# @return True if the string contains any dynamic prompts, False otherwise.
|
"""
|
||||||
def contains_dynamic_prompt(text):
|
Checks if the given string contains any dynamic prompts.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text (str): The string to check.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the string contains any dynamic prompts, False otherwise.
|
||||||
|
"""
|
||||||
# This should check if there are any { or } characters that aren't escaped
|
# This should check if there are any { or } characters that aren't escaped
|
||||||
return re.search(r'(?<!\{)\{(?!\{)|(?<!\})\}(?!\})', text) is not None
|
return re.search(r'(?<!\{)\{(?!\{)|(?<!\})\}(?!\})', text) is not None
|
||||||
|
|
||||||
|
|
||||||
# Checks a prompt and returns a hash of it if there are no dynamic elements, or NaN if there are, thus forcing it to always change.
|
def is_dynamic_prompt_changed(prompt: str) -> Union[float, str]:
|
||||||
# @param prompt The prompt to check.
|
"""
|
||||||
# @return A hash of the prompt if there are no dynamic elements, or NaN if there are.
|
Checks a prompt and returns it if there are no dynamic elements,
|
||||||
def is_dynamic_prompt_changed(prompt):
|
or NaN if there are, thus forcing it to always change.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prompt (str): The prompt to check.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Union[float, str]: A hash of the prompt if there are no dynamic elements,
|
||||||
|
or NaN if there are.
|
||||||
|
"""
|
||||||
if contains_dynamic_prompt(prompt):
|
if contains_dynamic_prompt(prompt):
|
||||||
print("is_dynamic_prompt_changed: NaN")
|
|
||||||
return float("nan")
|
return float("nan")
|
||||||
else:
|
|
||||||
print("is_dynamic_prompt_changed: %s" % hash(prompt))
|
|
||||||
return prompt
|
return prompt
|
||||||
|
|||||||
@ -1,10 +1,11 @@
|
|||||||
import math
|
import math
|
||||||
from nodes import MAX_RESOLUTION
|
from nodes import MAX_RESOLUTION
|
||||||
from comfy.dynamic_prompt import process_dynamic_prompt, is_dynamic_prompt_changed, validate_dynamic_prompt
|
from comfy.dynamic_prompt import process_dynamic_prompt, is_dynamic_prompt_changed #, validate_dynamic_prompt
|
||||||
|
|
||||||
|
|
||||||
class CLIPTextEncodeSDXLRefiner:
|
class CLIPTextEncodeSDXLRefiner:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(cls):
|
||||||
return {"required": {
|
return {"required": {
|
||||||
"clip": ("CLIP", ),
|
"clip": ("CLIP", ),
|
||||||
"ascore": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
|
"ascore": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
|
||||||
@ -21,19 +22,26 @@ class CLIPTextEncodeSDXLRefiner:
|
|||||||
text = process_dynamic_prompt(text)
|
text = process_dynamic_prompt(text)
|
||||||
tokens = clip.tokenize(text)
|
tokens = clip.tokenize(text)
|
||||||
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
||||||
return ([[cond, {"pooled_output": pooled, "aesthetic_score": ascore, "width": width,"height": height}]], )
|
return ([[
|
||||||
|
cond,
|
||||||
|
{
|
||||||
|
"pooled_output": pooled, "aesthetic_score": ascore,
|
||||||
|
"width": width, "height": height
|
||||||
|
}
|
||||||
|
]],)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def IS_CHANGED(s, clip, ascore, width, height, text):
|
def IS_CHANGED(s, clip, ascore, width, height, text):
|
||||||
return is_dynamic_prompt_changed(text)
|
return is_dynamic_prompt_changed(text)
|
||||||
|
|
||||||
@classmethod
|
# @classmethod
|
||||||
def VALIDATE_INPUTS(s, clip, ascore, width, height, text):
|
# def VALIDATE_INPUTS(cls, text):
|
||||||
return validate_dynamic_prompt(text)
|
# return validate_dynamic_prompt(text)
|
||||||
|
|
||||||
|
|
||||||
class CLIPTextEncodeSDXL:
|
class CLIPTextEncodeSDXL:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(cls):
|
||||||
return {"required": {
|
return {"required": {
|
||||||
"clip": ("CLIP", ),
|
"clip": ("CLIP", ),
|
||||||
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
@ -78,24 +86,22 @@ class CLIPTextEncodeSDXL:
|
|||||||
text_l_changed = is_dynamic_prompt_changed(text_l)
|
text_l_changed = is_dynamic_prompt_changed(text_l)
|
||||||
# If either is NaN, return NaN, otherwise return the sum
|
# If either is NaN, return NaN, otherwise return the sum
|
||||||
if math.isnan(text_g_changed) or math.isnan(text_l_changed):
|
if math.isnan(text_g_changed) or math.isnan(text_l_changed):
|
||||||
# Log to console
|
|
||||||
print("CLIPTextEncodeSDXL.IS_CHANGED: NaN")
|
|
||||||
return float("nan")
|
return float("nan")
|
||||||
else:
|
else:
|
||||||
# Log to console
|
# Log to console
|
||||||
print("CLIPTextEncodeSDXL.IS_CHANGED: %s" % (text_g_changed + text_l_changed))
|
|
||||||
return text_g_changed + text_l_changed
|
return text_g_changed + text_l_changed
|
||||||
|
|
||||||
@classmethod
|
# @classmethod
|
||||||
def VALIDATE_INPUTS(cls, clip, width, height, crop_w, crop_h, target_width, target_height, text_g, text_l):
|
# def VALIDATE_INPUTS(cls, clip, width, height, crop_w, crop_h, target_width, target_height, text_g, text_l):
|
||||||
# These return `True`, or an error message if the input is invalid
|
# # These return `True`, or an error message if the input is invalid
|
||||||
text_g_valid = validate_dynamic_prompt(text_g)
|
# text_g_valid = validate_dynamic_prompt(text_g)
|
||||||
text_l_valid = validate_dynamic_prompt(text_l)
|
# text_l_valid = validate_dynamic_prompt(text_l)
|
||||||
# If either is not `True`, return the error message, otherwise return `True`
|
# # If either is not `True`, return the error message, otherwise return `True`
|
||||||
if text_g_valid is not True:
|
# if text_g_valid is not True:
|
||||||
return text_g_valid
|
# return text_g_valid
|
||||||
elif text_l_valid is not True:
|
# elif text_l_valid is not True:
|
||||||
return text_l_valid
|
# return text_l_valid
|
||||||
|
|
||||||
|
|
||||||
NODE_CLASS_MAPPINGS = {
|
NODE_CLASS_MAPPINGS = {
|
||||||
"CLIPTextEncodeSDXLRefiner": CLIPTextEncodeSDXLRefiner,
|
"CLIPTextEncodeSDXLRefiner": CLIPTextEncodeSDXLRefiner,
|
||||||
|
|||||||
12
nodes.py
12
nodes.py
@ -66,9 +66,9 @@ class CLIPTextEncode:
|
|||||||
# Assume that if the text contains a dynamic prompt, it is always changed.
|
# Assume that if the text contains a dynamic prompt, it is always changed.
|
||||||
return is_dynamic_prompt_changed(text)
|
return is_dynamic_prompt_changed(text)
|
||||||
|
|
||||||
@classmethod
|
# @classmethod
|
||||||
def VALIDATE_INPUTS(s, clip, text):
|
# def VALIDATE_INPUTS(s, clip, text):
|
||||||
return validate_dynamic_prompt(text)
|
# return validate_dynamic_prompt(text)
|
||||||
|
|
||||||
|
|
||||||
class ConditioningCombine:
|
class ConditioningCombine:
|
||||||
@ -866,9 +866,9 @@ class GLIGENTextBoxApply:
|
|||||||
def IS_CHANGED(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
def IS_CHANGED(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
||||||
return is_dynamic_prompt_changed(text)
|
return is_dynamic_prompt_changed(text)
|
||||||
|
|
||||||
@classmethod
|
# @classmethod
|
||||||
def VALIDATE_INPUTS(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
# def VALIDATE_INPUTS(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
||||||
return validate_dynamic_prompt(text)
|
# return validate_dynamic_prompt(text)
|
||||||
|
|
||||||
class EmptyLatentImage:
|
class EmptyLatentImage:
|
||||||
def __init__(self, device="cpu"):
|
def __init__(self, device="cpu"):
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user