Spaces:
Runtime error
Runtime error
File size: 32,782 Bytes
2de3774 |
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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 |
import os
import re
import random
import json
from modules.sdxl_styles import apply_style, allstyles
from random_prompt.build_dynamic_prompt import (
build_dynamic_prompt,
build_dynamic_negative,
)
def process_metadata(gen_data):
try:
if isinstance(gen_data["prompt"], dict):
meta = gen_data["prompt"]
else:
meta = json.loads(gen_data["prompt"])
meta = dict((k.lower(), v) for k, v in meta.items())
gen_data.update(meta)
if "prompt" in meta:
gen_data["style_selection"] = []
if "steps" in meta:
gen_data["custom_steps"] = int(meta["steps"])
except:
pass
return gen_data
def get_promptlist(gen_data):
return gen_data["prompt"].split("---")
def process_wildcards(wildcard_text, directory="wildcards"):
# removed regex method
placeholders = []
splitup = wildcard_text.split("__")
for i in range(len(splitup)):
if i % 2 != 0: # check if index is odd
placeholders.append(splitup[i])
placeholder_choices = {} # Store random choices for each placeholder
official_directory = "wildcards_official"
directories = []
directories.append(directory)
directories.append(official_directory)
for placeholder in placeholders:
# Skip onebuttonprompt wildcards for now; handled below
if placeholder.startswith("onebutton"):
continue
elif placeholder not in placeholder_choices:
found = False
for dir in directories:
for root, dirs, files in os.walk(dir):
if f"{placeholder}.txt" in files:
file_path = os.path.join(root, f"{placeholder}.txt")
with open(file_path, encoding="utf-8") as f:
words = [
word.strip()
for word in f.read().splitlines()
if not word.startswith("#")
]
placeholder_choices[placeholder] = words
found = True
break
if found == True:
break
if not found:
print(
f"Error: Could not find file {placeholder}.txt in {directory} or its subdirectories."
)
placeholder_choices[placeholder] = [f"{placeholder}"]
for placeholder in placeholders:
random_choice = ""
# Some one button prompt specials
if placeholder.startswith("onebutton"):
subjectoverride = ""
placeholdersplit = placeholder.split(":", 1)
if len(placeholdersplit) > 1:
subjectoverride = placeholdersplit[1]
if placeholder.startswith("onebuttonprompt"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
givensubject=subjectoverride,
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonsubject"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonhumanoid"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="human - all",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonmale"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="human - all",
gender="male",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonfemale"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="human - all",
gender="female",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonanimal"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="animal - all",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonobject"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="object",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonlandscape"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="landscape - all",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonconcept"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="concept - all",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebuttonartist"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
onlyartists=True,
artists=subjectoverride or "all",
advancedprompting=False,
base_model="SDXL",
)
elif placeholder.startswith("onebutton1girl"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="human - all",
gender="female",
advancedprompting=False,
base_model="Anime Model",
)
elif placeholder.startswith("onebutton1boy"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="human - all",
gender="male",
advancedprompting=False,
base_model="Anime Model",
)
elif placeholder.startswith("onebuttonfurry"):
random_choice = build_dynamic_prompt(
insanitylevel=5,
imagetype="subject only mode",
givensubject=subjectoverride,
forcesubject="animal - all",
advancedprompting=False,
base_model="Anime Model",
)
# failover
else:
random_choice = build_dynamic_prompt(
insanitylevel=3,
imagetype="subject only mode",
givensubject=subjectoverride,
advancedprompting=False,
base_model="SDXL",
)
# Regular wildcards
else:
random_choice = random.choice(placeholder_choices[placeholder])
wildcard_text = re.sub(
rf"__{placeholder}__", random_choice, wildcard_text, count=1
)
return wildcard_text
def process_prompt(style, prompt, negative, gen_data=[]):
if "obp_assume_direct_control" in gen_data and gen_data["obp_assume_direct_control"]:
prompt = build_dynamic_prompt(
insanitylevel=gen_data["obp_insanitylevel"],
forcesubject=gen_data["obp_subject"],
artists=gen_data["obp_artist"],
subtypeobject=gen_data["obp_chosensubjectsubtypeobject"],
subtypehumanoid=gen_data["obp_chosensubjectsubtypehumanoid"],
subtypeconcept=gen_data["obp_chosensubjectsubtypeconcept"],
gender=gen_data["obp_chosengender"],
imagetype=gen_data["obp_imagetype"],
imagemodechance=gen_data["obp_imagemodechance"],
givensubject=gen_data["obp_givensubject"],
smartsubject=gen_data["obp_smartsubject"],
overrideoutfit=gen_data["obp_givenoutfit"],
prefixprompt=gen_data["obp_prefixprompt"],
suffixprompt=gen_data["obp_suffixprompt"],
giventypeofimage=gen_data["obp_giventypeofimage"],
antivalues=gen_data["obp_antistring"],
OBP_preset=gen_data["OBP_preset"],
advancedprompting=False,
base_model=gen_data["OBP_modeltype"],
prompt_enhancer=gen_data["OBP_promptenhance"],
)
# styles
pattern = re.compile(r"<style:([^>]+)>")
styles = [] if style is None else style.copy()
for match in re.finditer(pattern, prompt):
styles += [f"Style: {match.group(1)}"]
prompt = re.sub(pattern, "", prompt)
if "lora_keywords" in gen_data:
keywords = gen_data["lora_keywords"]
else:
keywords = ""
p_txt, n_txt = apply_style(styles, prompt, negative, keywords)
# wildcards
wildcard_pattern = r"__([\w\-:]+)__"
wildcard_pattern_onebutton = r"__([\w]+:[^\s_]+(?:[^\s_]+|\s(?=[\w:]+))*)__"
while (
(match := re.search(wildcard_pattern, p_txt))
or (match := re.search(wildcard_pattern_onebutton, p_txt))
) is not None:
p_txt = process_wildcards(p_txt)
# apply auto negative prompt if enabled
if "auto_negative" in gen_data and gen_data["auto_negative"] == True:
n_txt = build_dynamic_negative(
positive_prompt=p_txt, existing_negative_prompt=n_txt, base_model="SDXL"
)
return p_txt, n_txt
def parse_loras(prompt, negative):
pattern = re.compile(r"<lora:([^>]+):(\d*\.*\d+)>")
loras = []
for match in re.finditer(pattern, prompt):
loras.append((f"{match.group(1)}.safetensors", float(match.group(2))))
for match in re.finditer(pattern, negative):
loras.append((f"{match.group(1)}.safetensors", float(match.group(2))))
return loras, re.sub(pattern, "", prompt), re.sub(pattern, "", negative)
def prompt_switch_per_step(prompt, steps):
# Find all occurrences of [option1|option2|...] in the input string
# basic prompt editing:
# [bla|bla2|bla3] -> repeat each prompt
# A1111 style prompt editing:
# [bla:bla2:16] --> after step 16, move on from bla1 to bla2
# [bla:bla2:0.5] --> after 50% of steps move on from bla1 to bla2
# [bla1::16] --> remove bla1 after step 16
# [bla1::0.5] --> remove bla1 after 50% of steps
# Lets explore this space more, RF!
# [bla|bla2:bla3|bla4:16] --> after5 step 16, move on from [bla1|bla2] to [bla3|bla4]
# [bla:bla2:16] --> after step 16, move on from bla1 to bla2
# [bla1:0.5::0.75] --> Start and remove bla1 from the prompt at 50% and 75%
# [bla1~bla2] --> Same as | but in steps of 10% of steps
# [bla^bla2] --> slowly switch bla to bla2 with a peak
# [bla?bla2] --> random switch
# [bla1/bla2] --> slowly switch bla to bla2, but keeps bla2 after half
# [bla1\bla2] --> start with bla1, but after half, slowly transform into bla2
prompt_per_step = []
# step through all steps
for i in range(0, steps):
try:
prompt_per_step.append(prompt)
while "[" in prompt_per_step[i]:
startoflastpattern = prompt_per_step[i].rfind("[")
startoflastpatterncomplete = prompt_per_step[i][startoflastpattern:]
switchpattern = r"\[(.*?)\]"
allswitchpatterns = re.findall(
switchpattern, startoflastpatterncomplete
)
for switchpattern in allswitchpatterns:
switchpattern = "[" + switchpattern + "]"
matchfound = False
# start with basic matching [bla:bla2:16]
basic_match_pattern = r"\[((?!.*::).*?):([^\]]*?):([^\]]*?)\]"
matches = re.finditer(basic_match_pattern, switchpattern)
for match in matches:
replacement = ""
exact_match = match.group(0)
number = match.group(3)
parts = number.split(".")
intnumber = int(parts[0])
decnumber = float(number) if len(parts) > 1 else 0
if (intnumber != 0 and intnumber > i) or (
intnumber == 0 and int(steps * decnumber) > i
):
replacement = match.group(1)
if (intnumber != 0 and intnumber <= i) or (
intnumber == 0 and int(steps * decnumber) <= i
):
replacement = match.group(2)
# a trick for downstream! nice ;)
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_per_step[i].replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
matchfound = True
# Now do basic closing with [text::16]
basic_match_pattern = r"\[(.*?)::(.*?)\]"
matches = re.finditer(basic_match_pattern, switchpattern)
if matchfound == False:
for match in matches:
replacement = ""
exact_match = match.group(0)
# logic for ( : ::)
startintnumber = 0
startdecnumber = 0
print("match group 1 thingy")
print(match.group(1))
if ":" in match.group(1):
number = match.group(1).split(":")
parts = number[1].split(".")
startintnumber = int(parts[0])
startdecnumber = (
float(number[1]) if len(parts) > 1 else 0
)
tempreplacement = number[0]
else:
tempreplacement = match.group(1)
number = match.group(2)
parts = number.split(".")
intnumber = int(parts[0])
decnumber = float(number) if len(parts) > 1 else 0
if (intnumber != 0 and intnumber > i) or (
intnumber == 0 and int(steps * decnumber) > i
):
if (
(startintnumber != 0 and startintnumber <= i)
or (
startdecnumber != 0
and int(steps * startdecnumber) <= i
)
or (startintnumber == 0 and startdecnumber == 0)
):
replacement = tempreplacement
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_per_step[i].replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
matchfound = True
# Now do basic starting with [text:16]
basic_match_pattern = r"\[(.*?):(.*?)\]"
matches = re.finditer(basic_match_pattern, switchpattern)
if matchfound == False:
for match in matches:
replacement = ""
exact_match = match.group(0)
number = match.group(2)
parts = number.split(".")
intnumber = int(parts[0])
decnumber = float(number) if len(parts) > 1 else 0
if (intnumber != 0 and intnumber <= i) or (
intnumber == 0 and int(steps * decnumber) <= i
):
replacement = match.group(1)
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_per_step[i].replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
matchfound = True
# do long swapping
if "~" in switchpattern:
options_pattern = r"\[([^~\]]+(?:~[^~\]]+)*)\]"
matches = re.finditer(options_pattern, switchpattern)
options_list = []
exact_matches = []
for match in matches:
options = (
match.group(1).split("~")
if "~" in match.group(1)
else [match.group(1)]
)
options_list.append(options)
exact_matches.append(match.group(0))
prompt_to_append = prompt_per_step[i]
factor = max(
round(steps / 10), 2
) # minimum of 2, else just use |
for options, exact_match in zip(
options_list, exact_matches
):
replacement = options[
int((i) / factor) % len(options)
] # Use modulo to cycle through options
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_to_append.replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
# do lerp flip swapping
if "^" in switchpattern:
options_pattern = r"\[([^^\]]+(?:\^[^^\]]+)*)\]"
matches = re.finditer(options_pattern, switchpattern)
options_list = []
exact_matches = []
factor = i / steps
for match in matches:
options = (
match.group(1).split("^")
if "^" in match.group(1)
else [match.group(1)]
)
options_list.append(options)
exact_matches.append(match.group(0))
prompt_to_append = prompt_per_step[i]
if i > steps / 2:
options.reverse()
for options, exact_match in zip(
options_list, exact_matches
):
replacement = options[
round(i + (steps - i) * factor) % len(options)
] # Use lerp type to swap
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_to_append.replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
# do starting half lerp flip swapping
if "/" in switchpattern:
options_pattern = r"\[([^\/]+(?:\/[^\/]+)*)\]"
matches = re.finditer(options_pattern, switchpattern)
options_list = []
exact_matches = []
factor = i / steps
for match in matches:
options = (
match.group(1).split("/")
if "/" in match.group(1)
else [match.group(1)]
)
options_list.append(options)
exact_matches.append(match.group(0))
prompt_to_append = prompt_per_step[i]
for options, exact_match in zip(
options_list, exact_matches
):
if i > steps / 2:
replacement = options[len(options) - 1]
else:
replacement = options[
round(i + (steps - i) * factor) % len(options)
] # Use lerp type to swap
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_to_append.replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
# do closing half lerp flip swapping
if "\\" in switchpattern:
options_pattern = r"\[([^\/]+(?:\/\[^\/]+)*)\]"
matches = re.finditer(options_pattern, switchpattern)
options_list = []
exact_matches = []
factor = i / steps
for match in matches:
options = (
match.group(1).split("\\")
if "\\" in match.group(1)
else [match.group(1)]
)
options_list.append(options)
exact_matches.append(match.group(0))
prompt_to_append = prompt_per_step[i]
if i > steps / 2:
options.reverse()
for options, exact_match in zip(
options_list, exact_matches
):
if i < steps / 2:
replacement = options[0]
else:
replacement = options[
round(i + (steps - i) * factor) % len(options)
] # Use lerp type to swap
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_to_append.replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
# do random prompt swapping
if "?" in switchpattern:
options_pattern = r"\[([^?]+(?:\?[^?]+)*)\]"
matches = re.finditer(options_pattern, switchpattern)
options_list = []
exact_matches = []
for match in matches:
options = (
match.group(1).split("?")
if "?" in match.group(1)
else [match.group(1)]
)
options_list.append(options)
exact_matches.append(match.group(0))
prompt_to_append = prompt_per_step[i]
for options, exact_match in zip(
options_list, exact_matches
):
replacement = options[
random.randint(0, len(options) - 1)
] # take a random value
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_to_append.replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
# do prompt swapping
if "|" in switchpattern:
options_pattern = r"\[([^|\]]+(?:\|[^|\]]+)*)\]"
matches = re.finditer(options_pattern, switchpattern)
options_list = []
exact_matches = []
for match in matches:
options = (
match.group(1).split("|")
if "|" in match.group(1)
else [match.group(1)]
)
options_list.append(options)
exact_matches.append(match.group(0))
prompt_to_append = prompt_per_step[i]
for options, exact_match in zip(
options_list, exact_matches
):
replacement = options[
i % len(options)
] # Use modulo to cycle through options
if (
"|" in replacement
or "~" in replacement
or "^" in replacement
or "?" in replacement
or "/" in replacement
or "\\" in replacement
):
replacement = "[" + replacement + "]"
prompt_to_append = prompt_to_append.replace(
exact_match, replacement, 1
)
prompt_per_step[i] = prompt_to_append
# if there is no pattern, then just replace the value?
if (
"|" not in switchpattern
and "~" not in switchpattern
and "^" not in switchpattern
and "?" not in switchpattern
and "/" not in switchpattern
and "\\" not in switchpattern
and ":" not in switchpattern
):
replacement = switchpattern
replacement = replacement.replace("[", "")
replacement = replacement.replace("]", "")
prompt_to_append = prompt_per_step[i]
prompt_to_append = prompt_to_append.replace(
switchpattern, replacement, 1
)
prompt_per_step[i] = prompt_to_append
except ValueError:
print("There seems to be a mistake in the prompt.")
break
# print("All prompts generated after applying logic:")
# for i in range(0, steps):
# print("Step:" + str(i + 1))
# print(prompt_per_step[i])
# print("")
return prompt_per_step
|