mirror of
https://git.datalinker.icu/comfyanonymous/ComfyUI
synced 2026-11-22 12:37:04 +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 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:
|
||||
# // Single-line comment
|
||||
# /* Multi-line comment */
|
||||
#
|
||||
# @param text The string to strip comments from.
|
||||
# @return The string with comments stripped.
|
||||
def strip_comments(text):
|
||||
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:
|
||||
# {option1|option2|option3}
|
||||
#
|
||||
# For example, the following prompt:
|
||||
# > "This is a {good|great|spectacular} prompt."
|
||||
#
|
||||
# Could generate any of the following prompts:
|
||||
# > "This is a good prompt."
|
||||
# > "This is a great prompt."
|
||||
# > "This is a spectacular prompt."
|
||||
#
|
||||
# If you need to include a '{' or '}' character in your prompt, you can escape it by doubling it, like so:
|
||||
# > "This is a {{ and }} character."
|
||||
#
|
||||
# Which would generate the following prompt:
|
||||
# > "This is a { and } character."
|
||||
#
|
||||
# It also strips comments from the prompt, so you can include comments in your prompt like so:
|
||||
#
|
||||
# @param text The string to generate a dynamic prompt from.
|
||||
# @return The generated dynamic prompt.
|
||||
def process_dynamic_prompt(text):
|
||||
def strip_comments(text: str) -> str:
|
||||
"""
|
||||
Strips comments from a string.
|
||||
Supports both single-line and multi-line comments of the following formats:
|
||||
// Single-line comment
|
||||
/* Multi-line comment */
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def process_dynamic_prompt(text: str) -> str:
|
||||
"""
|
||||
Generates a dynamic prompt from a string.
|
||||
Allows you to include random text in your prompt, contained within option
|
||||
blocks of the following format:
|
||||
{option1|option2|option3}
|
||||
|
||||
For example, the following prompt:
|
||||
> "This is a {good|great|spectacular} prompt."
|
||||
|
||||
Could generate any of the following prompts:
|
||||
> "This is a good prompt."
|
||||
> "This is a great prompt."
|
||||
> "This is a spectacular prompt."
|
||||
|
||||
If you need to include a '{' or '}' character in your prompt, you can escape
|
||||
it by doubling it, like so:
|
||||
> "This is a {{ and }} character."
|
||||
|
||||
Which would generate the following prompt:
|
||||
> "This is a { and } character."
|
||||
|
||||
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)
|
||||
|
||||
new_prompt = ""
|
||||
options = []
|
||||
options: List[str] = []
|
||||
inside_option = False
|
||||
|
||||
i = 0
|
||||
i: int = 0
|
||||
while i < len(prompt):
|
||||
char = prompt[i]
|
||||
if char == "{":
|
||||
@ -49,10 +65,9 @@ def process_dynamic_prompt(text):
|
||||
options[-1] += char
|
||||
i += 2
|
||||
continue
|
||||
else:
|
||||
raise ValueError(f"Option block opened at position {i} inside another option block. "
|
||||
"Each option block should be closed before starting a new one. "
|
||||
"If you want to include a '{' inside an option block, use '{{'.")
|
||||
raise ValueError(f"Option block opened at position {i} inside another option block. "
|
||||
"Each option block should be closed before starting a new one. "
|
||||
"If you want to include a '{' inside an option block, use '{{'.")
|
||||
else:
|
||||
if i < len(prompt) - 1 and prompt[i + 1] == "{":
|
||||
new_prompt += char
|
||||
@ -71,9 +86,11 @@ def process_dynamic_prompt(text):
|
||||
i += 2
|
||||
continue
|
||||
if not inside_option:
|
||||
raise ValueError(f"Option block closed at position {i} without being opened. "
|
||||
"Make sure each '{' has a matching '}'. "
|
||||
"If you want to include a '}' without closing an option block, use '}}'.")
|
||||
raise ValueError(
|
||||
f"Option block closed at position {i} without being opened. "
|
||||
"Make sure each '{' has a matching '}'. "
|
||||
"If you want to include a '}' without closing an option block, use '}}'."
|
||||
)
|
||||
inside_option = False
|
||||
random_option = random.choice(options[-1].split("|"))
|
||||
new_prompt += random_option
|
||||
@ -85,40 +102,62 @@ def process_dynamic_prompt(text):
|
||||
i += 1
|
||||
|
||||
if inside_option:
|
||||
raise ValueError("Option block opened but not closed. "
|
||||
"Make sure each '{' has a matching '}'. "
|
||||
"If you want to include a '}' without closing an option block, use '}}'.")
|
||||
raise ValueError(
|
||||
"Option block opened but not closed. "
|
||||
"Make sure each '{' has a matching '}'. "
|
||||
"If you want to include a '}' without closing an option block, use '}}'."
|
||||
)
|
||||
|
||||
return new_prompt
|
||||
|
||||
# Checks if the given string is a valid dynamic prompt.
|
||||
# @param text The string to check.
|
||||
# @return An error message if the string is not a valid dynamic prompt, True otherwise.
|
||||
def validate_dynamic_prompt(text):
|
||||
|
||||
def validate_dynamic_prompt(text: str) -> Union[Literal[True], str]:
|
||||
"""
|
||||
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:
|
||||
process_dynamic_prompt(text)
|
||||
except ValueError as e:
|
||||
print("validate_dynamic_prompt: %s" % str(e))
|
||||
return str(e)
|
||||
except ValueError as err:
|
||||
print(f"validate_dynamic_prompt: {err}")
|
||||
return str(err)
|
||||
|
||||
print("validate_dynamic_prompt: True")
|
||||
return True
|
||||
|
||||
# Checks if the given string contains any dynamic prompts.
|
||||
# @param text The string to check.
|
||||
# @return True if the string contains any dynamic prompts, False otherwise.
|
||||
def contains_dynamic_prompt(text):
|
||||
|
||||
def contains_dynamic_prompt(text: str) -> bool:
|
||||
"""
|
||||
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
|
||||
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.
|
||||
# @param prompt The prompt to check.
|
||||
# @return A hash of the prompt if there are no dynamic elements, or NaN if there are.
|
||||
def is_dynamic_prompt_changed(prompt):
|
||||
def is_dynamic_prompt_changed(prompt: str) -> Union[float, str]:
|
||||
"""
|
||||
Checks a prompt and returns it if there are no dynamic elements,
|
||||
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):
|
||||
print("is_dynamic_prompt_changed: NaN")
|
||||
return float("nan")
|
||||
else:
|
||||
print("is_dynamic_prompt_changed: %s" % hash(prompt))
|
||||
return prompt
|
||||
|
||||
return prompt
|
||||
|
||||
@ -1,17 +1,18 @@
|
||||
import math
|
||||
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:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"clip": ("CLIP", ),
|
||||
"ascore": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
|
||||
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||
"height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||
"text": ("STRING", {"multiline": True}),
|
||||
}}
|
||||
}}
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
FUNCTION = "encode"
|
||||
|
||||
@ -21,19 +22,26 @@ class CLIPTextEncodeSDXLRefiner:
|
||||
text = process_dynamic_prompt(text)
|
||||
tokens = clip.tokenize(text)
|
||||
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
|
||||
def IS_CHANGED(s, clip, ascore, width, height, text):
|
||||
return is_dynamic_prompt_changed(text)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, clip, ascore, width, height, text):
|
||||
return validate_dynamic_prompt(text)
|
||||
# @classmethod
|
||||
# def VALIDATE_INPUTS(cls, text):
|
||||
# return validate_dynamic_prompt(text)
|
||||
|
||||
|
||||
class CLIPTextEncodeSDXL:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {
|
||||
"clip": ("CLIP", ),
|
||||
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||
@ -44,7 +52,7 @@ class CLIPTextEncodeSDXL:
|
||||
"target_height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||
"text_g": ("STRING", {"multiline": True, "default": "CLIP_G"}),
|
||||
"text_l": ("STRING", {"multiline": True, "default": "CLIP_L"}),
|
||||
}}
|
||||
}}
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
FUNCTION = "encode"
|
||||
|
||||
@ -78,24 +86,22 @@ class CLIPTextEncodeSDXL:
|
||||
text_l_changed = is_dynamic_prompt_changed(text_l)
|
||||
# If either is NaN, return NaN, otherwise return the sum
|
||||
if math.isnan(text_g_changed) or math.isnan(text_l_changed):
|
||||
# Log to console
|
||||
print("CLIPTextEncodeSDXL.IS_CHANGED: NaN")
|
||||
return float("nan")
|
||||
else:
|
||||
# Log to console
|
||||
print("CLIPTextEncodeSDXL.IS_CHANGED: %s" % (text_g_changed + text_l_changed))
|
||||
return text_g_changed + text_l_changed
|
||||
|
||||
@classmethod
|
||||
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
|
||||
text_g_valid = validate_dynamic_prompt(text_g)
|
||||
text_l_valid = validate_dynamic_prompt(text_l)
|
||||
# If either is not `True`, return the error message, otherwise return `True`
|
||||
if text_g_valid is not True:
|
||||
return text_g_valid
|
||||
elif text_l_valid is not True:
|
||||
return text_l_valid
|
||||
# @classmethod
|
||||
# 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
|
||||
# text_g_valid = validate_dynamic_prompt(text_g)
|
||||
# text_l_valid = validate_dynamic_prompt(text_l)
|
||||
# # If either is not `True`, return the error message, otherwise return `True`
|
||||
# if text_g_valid is not True:
|
||||
# return text_g_valid
|
||||
# elif text_l_valid is not True:
|
||||
# return text_l_valid
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"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.
|
||||
return is_dynamic_prompt_changed(text)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, clip, text):
|
||||
return validate_dynamic_prompt(text)
|
||||
# @classmethod
|
||||
# def VALIDATE_INPUTS(s, clip, text):
|
||||
# return validate_dynamic_prompt(text)
|
||||
|
||||
|
||||
class ConditioningCombine:
|
||||
@ -866,9 +866,9 @@ class GLIGENTextBoxApply:
|
||||
def IS_CHANGED(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
||||
return is_dynamic_prompt_changed(text)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
||||
return validate_dynamic_prompt(text)
|
||||
# @classmethod
|
||||
# def VALIDATE_INPUTS(s, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
||||
# return validate_dynamic_prompt(text)
|
||||
|
||||
class EmptyLatentImage:
|
||||
def __init__(self, device="cpu"):
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user