-
Notifications
You must be signed in to change notification settings - Fork 1
/
ppp.py
1654 lines (1549 loc) · 77.4 KB
/
ppp.py
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from functools import reduce
import logging
import math
import os
import re
import textwrap
import time
from collections import namedtuple
from enum import Enum
from typing import Any, Callable, Optional
import lark
import lark.parsers
import numpy as np
from ppp_logging import DEBUG_LEVEL
from ppp_wildcards import PPPWildcard, PPPWildcards
class PromptPostProcessor: # pylint: disable=too-few-public-methods,too-many-instance-attributes
"""
The PromptPostProcessor class is responsible for processing and manipulating prompt strings.
"""
@staticmethod
def get_version_from_pyproject() -> str:
"""
Reads the version from the pyproject.toml file.
Returns:
str: The version string.
"""
version_str = "0.0.0"
try:
pyproject_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "pyproject.toml")
with open(pyproject_path, "r", encoding="utf-8") as file:
for line in file:
if line.startswith("version = "):
version_str = line.split("=")[1].strip().strip('"')
break
except Exception as e: # pylint: disable=broad-exception-caught
logging.getLogger().exception(e)
return version_str
NAME = "Prompt Post-Processor"
VERSION = get_version_from_pyproject()
class IFWILDCARDS_CHOICES(Enum):
ignore = "ignore"
remove = "remove"
warn = "warn"
stop = "stop"
DEFAULT_STN_SEPARATOR = ", "
DEFAULT_PONY_SUBSTRINGS = ",".join(["pony", "pny", "pdxl"])
DEFAULT_CHOICE_SEPARATOR = ", "
WILDCARD_WARNING = '(WARNING TEXT "INVALID WILDCARD" IN BRIGHT RED:1.5)\nBREAK '
WILDCARD_STOP = "INVALID WILDCARD! {0}\nBREAK "
UNPROCESSED_STOP = "UNPROCESSED CONSTRUCTS!\nBREAK "
def __init__(
self,
logger: logging.Logger,
interrupt: Optional[Callable],
env_info: dict[str, Any],
options: Optional[dict[str, Any]] = None,
grammar_content: Optional[str] = None,
wildcards_obj: PPPWildcards = None,
):
"""
Initializes the PPP object.
Args:
logger: The logger object.
interrupt: The interrupt function.
env_info: A dictionary with information for the environment and loaded model.
options: Optional. The options dictionary for configuring PPP behavior.
grammar_content: Optional. The grammar content to be used for parsing.
wildcards_obj: Optional. The wildcards object to be used for processing wildcards.
"""
self.logger = logger
self.rng = np.random.default_rng() # gets seeded on each process prompt call
self.interrupt_callback = interrupt
self.options = options
self.env_info = env_info
self.wildcard_obj = wildcards_obj
# General options
self.debug_level = DEBUG_LEVEL(options.get("debug_level", DEBUG_LEVEL.none.value))
self.pony_substrings = list(
x.strip() for x in (str(options.get("pony_substrings", self.DEFAULT_PONY_SUBSTRINGS))).split(",")
)
# Wildcards options
self.wil_process_wildcards = options.get("process_wildcards", True)
self.wil_keep_choices_order = options.get("keep_choices_order", False)
self.wil_choice_separator = options.get("choice_separator", self.DEFAULT_CHOICE_SEPARATOR)
self.wil_ifwildcards = self.IFWILDCARDS_CHOICES(
options.get("if_wildcards", self.IFWILDCARDS_CHOICES.ignore.value)
)
# Send to negative options
self.stn_ignore_repeats = options.get("stn_ignore_repeats", True)
self.stn_separator = options.get("stn_separator", self.DEFAULT_STN_SEPARATOR)
# Cleanup options
self.cup_extraspaces = options.get("cleanup_extra_spaces", True)
self.cup_emptyconstructs = options.get("cleanup_empty_constructs", True)
self.cup_extraseparators = options.get("cleanup_extra_separators", True)
self.cup_extraseparators2 = options.get("cleanup_extra_separators2", True)
self.cup_breaks = options.get("cleanup_breaks", True)
self.cup_breaks_eol = options.get("cleanup_breaks_eol", False)
self.cup_ands = options.get("cleanup_ands", True)
self.cup_ands_eol = options.get("cleanup_ands_eol", False)
self.cup_extranetworktags = options.get("cleanup_extranetwork_tags", False)
self.cup_mergeattention = options.get("cleanup_merge_attention", True)
# Remove options
self.rem_removeextranetworktags = options.get("remove_extranetwork_tags", False)
# if self.debug_level != DEBUG_LEVEL.none:
# self.logger.info(f"Detected environment info: {env_info}")
# Process with lark (debug with https://www.lark-parser.org/ide/)
if grammar_content is None:
grammar_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "grammar.lark")
with open(grammar_filename, "r", encoding="utf-8") as file:
grammar_content = file.read()
self.parser_complete = lark.Lark(
grammar_content,
propagate_positions=True,
)
self.parser_choice = lark.Lark(
grammar_content,
propagate_positions=True,
start="choice",
)
self.parser_choicesoptions = lark.Lark(
grammar_content,
propagate_positions=True,
start="choicesoptions",
)
self.parser_condition = lark.Lark(
grammar_content,
propagate_positions=True,
start="condition",
)
self.parser_choicevalue = lark.Lark(
grammar_content,
propagate_positions=True,
start="choicevalue",
)
self.__init_sysvars()
self.user_variables = {}
def interrupt(self):
if self.interrupt_callback is not None:
self.interrupt_callback()
def format_output(self, text: str) -> str:
"""
Formats the output text by encoding it using unicode_escape and decoding it using utf-8.
Args:
text (str): The input text to be formatted.
Returns:
str: The formatted output text.
"""
return text.encode("unicode_escape").decode("utf-8")
def is_comfy_ui(self) -> bool:
"""
Checks if the current environment is ComfyUI.
Returns:
bool: True if the environment is ComfyUI, False otherwise.
"""
return self.env_info.get("app", "") == "comfyui"
def __init_sysvars(self):
"""
Initializes the system variables.
"""
self.system_variables = {}
sdchecks = {
"sd1": self.env_info.get("is_sd1", False),
"sd2": self.env_info.get("is_sd2", False),
"sdxl": self.env_info.get("is_sdxl", False),
"sd3": self.env_info.get("is_sd3", False),
"flux": self.env_info.get("is_flux", False),
"auraflow": self.env_info.get("is_auraflow", False),
"": True,
}
self.system_variables["_model"] = [k for k, v in sdchecks.items() if v][0]
self.system_variables["_sd"] = self.system_variables["_model"] # deprecated
model_filename = self.env_info.get("model_filename", "")
is_pony = any(s in model_filename.lower() for s in self.pony_substrings)
is_ssd = self.env_info.get("is_ssd", False)
self.system_variables["_sdfullname"] = model_filename # deprecated
self.system_variables["_modelfullname"] = model_filename
self.system_variables["_sdname"] = os.path.basename(model_filename) # deprecated
self.system_variables["_modelname"] = os.path.basename(model_filename)
self.system_variables["_modelclass"] = self.env_info.get("model_class", "")
self.system_variables["_is_sd1"] = sdchecks["sd1"]
self.system_variables["_is_sd2"] = sdchecks["sd2"]
self.system_variables["_is_sdxl"] = sdchecks["sdxl"]
self.system_variables["_is_ssd"] = is_ssd
self.system_variables["_is_sdxl_no_ssd"] = sdchecks["sdxl"] and not is_ssd
self.system_variables["_is_pony"] = sdchecks["sdxl"] and is_pony
self.system_variables["_is_sdxl_no_pony"] = sdchecks["sdxl"] and not is_pony
self.system_variables["_is_sd3"] = sdchecks["sd3"]
self.system_variables["_is_sd"] = sdchecks["sd1"] or sdchecks["sd2"] or sdchecks["sdxl"] or sdchecks["sd3"]
self.system_variables["_is_flux"] = sdchecks["flux"]
self.system_variables["_is_auraflow"] = sdchecks["auraflow"]
def __add_to_insertion_points(
self, negative_prompt: str, add_at_insertion_point: list[str], insertion_at: list[tuple[int, int]]
) -> str:
"""
Adds the negative prompt to the insertion points.
Args:
negative_prompt (str): The negative prompt to be added.
add_at_insertion_point (list): A list of insertion points.
insertion_at (list): A list of insertion blocks.
Returns:
str: The modified negative prompt.
"""
ordered_range = sorted(
range(10), key=lambda x: insertion_at[x][0] if insertion_at[x] is not None else float("-inf"), reverse=True
)
for n in ordered_range:
if insertion_at[n] is not None:
ipp = insertion_at[n][0]
ipl = insertion_at[n][1] - insertion_at[n][0]
if negative_prompt[ipp - len(self.stn_separator) : ipp] == self.stn_separator:
ipp -= len(self.stn_separator) # adjust for existing start separator
ipl += len(self.stn_separator)
add_at_insertion_point[n].insert(0, negative_prompt[:ipp])
if negative_prompt[ipp + ipl : ipp + ipl + len(self.stn_separator)] == self.stn_separator:
ipl += len(self.stn_separator) # adjust for existing end separator
endPart = negative_prompt[ipp + ipl :]
if len(endPart) > 0:
add_at_insertion_point[n].append(endPart)
negative_prompt = self.stn_separator.join(add_at_insertion_point[n])
else:
ipp = 0
if negative_prompt.startswith(self.stn_separator):
ipp = len(self.stn_separator)
add_at_insertion_point[n].append(negative_prompt[ipp:])
negative_prompt = self.stn_separator.join(add_at_insertion_point[n])
return negative_prompt
def __add_to_start(self, negative_prompt: str, add_at_start: list[str]) -> str:
"""
Adds the elements in `add_at_start` list to the start of the `negative_prompt` string.
Args:
negative_prompt (str): The original negative prompt string.
add_at_start (list): The list of elements to be added at the start of the negative prompt.
Returns:
str: The updated negative prompt string with the elements added at the start.
"""
if len(negative_prompt) > 0:
ipp = 0
if negative_prompt.startswith(self.stn_separator):
ipp = len(self.stn_separator) # adjust for existing end separator
add_at_start.append(negative_prompt[ipp:])
negative_prompt = self.stn_separator.join(add_at_start)
return negative_prompt
def __add_to_end(self, negative_prompt: str, add_at_end: list[str]) -> str:
"""
Adds the elements in `add_at_end` list to the end of `negative_prompt` string.
Args:
negative_prompt (str): The original negative prompt string.
add_at_end (list): The list of elements to be added at the end of `negative_prompt`.
Returns:
str: The updated negative prompt string with elements added at the end.
"""
if len(negative_prompt) > 0:
ipl = len(negative_prompt)
if negative_prompt.endswith(self.stn_separator):
ipl -= len(self.stn_separator) # adjust for existing start separator
add_at_end.insert(0, negative_prompt[:ipl])
negative_prompt = self.stn_separator.join(add_at_end)
return negative_prompt
def __cleanup(self, text: str) -> str:
"""
Trims the given text based on the specified cleanup options.
Args:
text (str): The text to be cleaned up.
Returns:
str: The resulting text.
"""
escapedSeparator = re.escape(self.stn_separator)
if self.cup_extraseparators:
#
# sendtonegative separator
#
# collapse separators
text = re.sub(r"(?:\s*" + escapedSeparator + r"\s*){2,}", self.stn_separator, text)
# remove separator after starting parenthesis or bracket
text = re.sub(r"(\s*" + escapedSeparator + r"\s*[([])(?:\s*" + escapedSeparator + r"\s*)+", r"\1", text)
# remove before colon or ending parenthesis or bracket
text = re.sub(r"(?:\s*" + escapedSeparator + r"\s*)+([:)\]]\s*" + escapedSeparator + r"\s*)", r"\1", text)
if self.cup_extraseparators2:
# remove at start of prompt or line
text = re.sub(r"^(?:\s*" + escapedSeparator + r"\s*)+", "", text, flags=re.MULTILINE)
# remove at end of prompt or line
text = re.sub(r"(?:\s*" + escapedSeparator + r"\s*)+$", "", text, flags=re.MULTILINE)
if self.cup_extraseparators:
#
# regular comma separator
#
# collapse separators
text = re.sub(r"(?:\s*,\s*){2,}", ", ", text)
# remove separators after starting parenthesis or bracket
text = re.sub(r"(\s*,\s*[([])(?:\s*,\s*)+", r"\1", text)
# remove separators before colon or ending parenthesis or bracket
text = re.sub(r"(?:\s*,\s*)+([:)\]]\s*,\s*)", r"\1", text)
if self.cup_extraseparators2:
# remove at start of prompt or line
text = re.sub(r"^(?:\s*,\s*)+", "", text, flags=re.MULTILINE)
# remove at end of prompt or line
text = re.sub(r"(?:\s*,\s*)+$", "", text, flags=re.MULTILINE)
if self.cup_breaks_eol:
# replace spaces before break with EOL
text = re.sub(r"[, ]+BREAK\b", "\nBREAK", text)
if self.cup_breaks:
# collapse separators and commas before BREAK
text = re.sub(r"[, ]+BREAK\b", " BREAK", text)
# collapse separators and commas after BREAK
text = re.sub(r"\bBREAK[, ]+", "BREAK ", text)
# collapse separators and commas around BREAK
text = re.sub(r"[, ]+BREAK[, ]+", " BREAK ", text)
# collapse BREAKs
text = re.sub(r"\bBREAK(?:\s+BREAK)+\b", " BREAK ", text)
# remove spaces between start of line and BREAK
text = re.sub(r"^[ ]+BREAK\b", "BREAK", text, flags=re.MULTILINE)
# remove spaces between BREAK and end of line
text = re.sub(r"\bBREAK[ ]+$", "BREAK", text, flags=re.MULTILINE)
# remove at start of prompt
text = re.sub(r"\A(?:\s*BREAK\b\s*)+", "", text)
# remove at end of prompt
text = re.sub(r"(?:\s*\bBREAK\s*)+\Z", "", text)
if self.cup_ands:
# collapse ANDs with space after
text = re.sub(r"\bAND(?:\s+AND)+\s+", "AND ", text)
# collapse ANDs without space after
text = re.sub(r"\bAND(?:\s+AND)+\b", "AND", text)
# collapse separators and spaces before ANDs
text = re.sub(r"[, ]+AND\b", " AND", text)
# collapse separators and spaces after ANDs
text = re.sub(r"\bAND[, ]+", "AND ", text)
# remove at start of prompt
text = re.sub(r"\A(?:AND\b\s*)+", "", text)
# remove at end of prompt
text = re.sub(r"(\s*\bAND)+\Z", "", text)
if self.cup_extranetworktags:
# remove spaces before <
text = re.sub(r"\B\s+<(?!!)", "<", text)
# remove spaces after >
text = re.sub(r">\s+\B", ">", text)
if self.cup_extraspaces:
# remove spaces before comma
text = re.sub(r"[ ]+,", ",", text)
# remove spaces at end of line
text = re.sub(r"[ ]+$", "", text, flags=re.MULTILINE)
# remove spaces at start of line
text = re.sub(r"^[ ]+", "", text, flags=re.MULTILINE)
# remove extra whitespace after starting parenthesis or bracket
text = re.sub(r"([,\.;\s]+[([])\s+", r"\1", text)
# remove extra whitespace before ending parenthesis or bracket
text = re.sub(r"\s+([)\]][,\.;\s]+)", r"\1", text)
# remove empty lines
text = re.sub(r"(?:^|\n)[ ]*\n", "\n", text)
text = re.sub(r"\n[ ]*\n$", "\n", text)
# collapse spaces
text = re.sub(r"[ ]{2,}", " ", text)
# remove spaces at start and end
text = text.strip()
return text
def __processprompts(self, prompt, negative_prompt):
"""
Process the prompt and negative prompt.
Args:
prompt (str): The prompt.
negative_prompt (str): The negative prompt.
Returns:
tuple: A tuple containing the processed prompt and negative prompt.
"""
self.user_variables = {}
# Process prompt
p_processor = self.TreeProcessor(self)
p_parsed = self.parse_prompt("prompt", prompt, self.parser_complete)
prompt = p_processor.start_visit("prompt", p_parsed, False)
# Process negative prompt
n_processor = self.TreeProcessor(self)
n_parsed = self.parse_prompt("negative prompt", negative_prompt, self.parser_complete)
negative_prompt = n_processor.start_visit("negative prompt", n_parsed, True)
# Insertions in the negative prompt
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(self.format_output(f"New negative additions: {p_processor.add_at}"))
self.logger.debug(self.format_output(f"New negative indexes: {n_processor.insertion_at}"))
negative_prompt = self.__add_to_insertion_points(
negative_prompt, p_processor.add_at["insertion_point"], n_processor.insertion_at
)
if len(p_processor.add_at["start"]) > 0:
negative_prompt = self.__add_to_start(negative_prompt, p_processor.add_at["start"])
if len(p_processor.add_at["end"]) > 0:
negative_prompt = self.__add_to_end(negative_prompt, p_processor.add_at["end"])
# Clean up
prompt = self.__cleanup(prompt)
negative_prompt = self.__cleanup(negative_prompt)
# Check for wildcards not processed
foundP = len(p_processor.detectedWildcards) > 0
foundNP = len(n_processor.detectedWildcards) > 0
if foundP or foundNP:
if self.wil_ifwildcards == self.IFWILDCARDS_CHOICES.stop:
self.logger.error("Found unprocessed wildcards!")
else:
self.logger.info("Found unprocessed wildcards.")
ppwl = ", ".join(p_processor.detectedWildcards)
npwl = ", ".join(n_processor.detectedWildcards)
if foundP:
self.logger.error(self.format_output(f"In the positive prompt: {ppwl}"))
if foundNP:
self.logger.error(self.format_output(f"In the negative prompt: {npwl}"))
if self.wil_ifwildcards == self.IFWILDCARDS_CHOICES.warn:
prompt = self.WILDCARD_WARNING + prompt
elif self.wil_ifwildcards == self.IFWILDCARDS_CHOICES.stop:
self.logger.error("Stopping the generation.")
if foundP:
prompt = self.WILDCARD_STOP.format(ppwl) + prompt
if foundNP:
negative_prompt = self.WILDCARD_STOP.format(npwl) + negative_prompt
self.interrupt()
# Check for special character sequences that should not be in the result
compound_prompt = prompt + "\n" + negative_prompt
found_sequences = re.findall(r"::|\$\$|\$\{|[{|}]", compound_prompt)
if len(found_sequences) > 0:
self.logger.warning(
f"""Found probably invalid character sequences on the result ({', '.join(map(lambda x: '"' + x + '"', set(found_sequences)))}). Something might be wrong!"""
)
return prompt, negative_prompt
def process_prompt(
self,
original_prompt: str,
original_negative_prompt: str,
seed: int = 0,
):
"""
Initializes the random number generator and processes the prompt and negative prompt.
Args:
original_prompt (str): The original prompt.
original_negative_prompt (str): The original negative prompt.
seed (int): The seed.
Returns:
tuple: A tuple containing the processed prompt and negative prompt.
"""
try:
if seed == -1:
seed = np.random.randint(0, 2**32, dtype=np.int64)
self.rng = np.random.default_rng(seed & 0xFFFFFFFF)
prompt = original_prompt
negative_prompt = original_negative_prompt
self.debug_level = DEBUG_LEVEL(self.options.get("debug_level", DEBUG_LEVEL.none.value))
if self.debug_level != DEBUG_LEVEL.none:
self.logger.info(f"System variables: {self.system_variables}")
self.logger.info(f"Input seed: {seed}")
self.logger.info(self.format_output(f"Input prompt: {prompt}"))
self.logger.info(self.format_output(f"Input negative_prompt: {negative_prompt}"))
t1 = time.time()
prompt, negative_prompt = self.__processprompts(prompt, negative_prompt)
t2 = time.time()
if self.debug_level != DEBUG_LEVEL.none:
self.logger.info(self.format_output(f"Result prompt: {prompt}"))
self.logger.info(self.format_output(f"Result negative_prompt: {negative_prompt}"))
self.logger.info(f"Process prompt pair time: {t2 - t1:.3f} seconds")
# Check for constructs not processed due to parsing problems
fullcontent: str = prompt + negative_prompt
if fullcontent.find("<ppp:") >= 0:
self.logger.error("Found unprocessed constructs in prompt or negative prompt! Stopping the generation.")
prompt = self.UNPROCESSED_STOP + prompt
self.interrupt()
return prompt, negative_prompt
except Exception as e: # pylint: disable=broad-exception-caught
self.logger.exception(e)
return original_prompt, original_negative_prompt
def parse_prompt(self, prompt_description: str, prompt: str, parser: lark.Lark, raise_parsing_error: bool = False):
"""
Parses a prompt using the specified parser.
Args:
prompt_description (str): The description of the prompt.
prompt (str): The prompt to be parsed.
parser (lark.Lark): The parser to be used.
raise_parsing_error (bool): Whether to raise a parsing error.
Returns:
Tree: The parsed prompt.
"""
t1 = time.time()
try:
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(self.format_output(f"Parsing {prompt_description}: '{prompt}'"))
parsed_prompt = parser.parse(prompt)
# we store the contents so we can use them later even if the meta position is not valid anymore
for n in parsed_prompt.iter_subtrees():
if isinstance(n, lark.Tree):
if n.meta.empty:
n.meta.content = ""
else:
n.meta.content = prompt[n.meta.start_pos : n.meta.end_pos]
except lark.exceptions.UnexpectedInput:
if raise_parsing_error:
raise
self.logger.exception(self.format_output(f"Parsing failed on prompt!: {prompt}"))
t2 = time.time()
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug("Tree:\n" + textwrap.indent(re.sub(r"\n$", "", parsed_prompt.pretty()), " "))
self.logger.debug(f"Parse {prompt_description} time: {t2 - t1:.3f} seconds")
return parsed_prompt
class TreeProcessor(lark.visitors.Interpreter):
"""
A class for interpreting and processing a tree generated by the prompt parser.
Args:
ppp (PromptPostProcessor): The PromptPostProcessor object.
Attributes:
add_at (dict): The dictionary to store the content to be added at different positions of the negative prompt.
insertion_at (list): The list of insertion points in the negative prompt.
detectedWildcards (list): The list of detected invalid wildcards or choices.
result (str): The final processed prompt.
"""
def __init__(self, ppp: "PromptPostProcessor"):
super().__init__()
self.__ppp = ppp
self.AccumulatedShell = namedtuple("AccumulatedShell", ["type", "data"])
self.NegTag = namedtuple("NegTag", ["start", "end", "content", "parameters", "shell"])
self.__shell: list[self.AccumulatedShell] = [] # type: ignore
self.__negtags: list[self.NegTag] = [] # type: ignore
self.__already_processed: list[str] = []
self.__is_negative = False
self.__wildcard_filters = {}
self.add_at: dict = {"start": [], "insertion_point": [[] for x in range(10)], "end": []}
self.insertion_at: list[tuple[int, int]] = [None for x in range(10)]
self.detectedWildcards: list[str] = []
self.result = ""
def start_visit(self, prompt_description: str, parsed_prompt: lark.Tree, is_negative: bool = False) -> str:
"""
Start the visit process.
Args:
prompt_description (str): The description of the prompt.
parsed_prompt (Tree): The parsed prompt.
is_negative (bool): Whether the prompt is negative or not.
Returns:
str: The processed prompt.
"""
t1 = time.time()
self.__is_negative = is_negative
if self.__ppp.debug_level != DEBUG_LEVEL.none:
self.__ppp.logger.info(f"Processing {prompt_description}...")
self.visit(parsed_prompt)
t2 = time.time()
if self.__ppp.debug_level != DEBUG_LEVEL.none:
self.__ppp.logger.info(f"Process {prompt_description} time: {t2 - t1:.3f} seconds")
return self.result
def __visit(
self,
node: lark.Tree | lark.Token | list[lark.Tree | lark.Token] | None,
restore_state: bool = False,
discard_content: bool = False,
) -> str:
"""
Visit a node in the tree and process it or accumulate its value if it is a Token.
Args:
node (Tree|Token|list): The node or list of nodes to visit.
restore_state (bool): Whether to restore the state after visiting the node.
discard_content (bool): Whether to discard the content of the node.
Returns:
str: The result of the visit.
"""
backup_result = self.result
if restore_state:
backup_shell = self.__shell.copy()
backup_negtags = self.__negtags.copy()
backup_already_processed = self.__already_processed.copy()
backup_add_at = self.add_at.copy()
backup_insertion_at = self.insertion_at.copy()
backup_detectedwildcards = self.detectedWildcards.copy()
if node is not None:
if isinstance(node, list):
for child in node:
self.__visit(child)
elif isinstance(node, lark.Tree):
self.visit(node)
elif isinstance(node, lark.Token):
self.result += node
added_result = self.result[len(backup_result) :]
if discard_content or restore_state:
self.result = backup_result
if restore_state:
self.__shell = backup_shell
self.__negtags = backup_negtags
self.__already_processed = backup_already_processed
self.add_at = backup_add_at
self.insertion_at = backup_insertion_at
self.detectedWildcards = backup_detectedwildcards
return added_result
def __get_original_node_content(self, node: lark.Tree | lark.Token, default=None) -> str:
"""
Get the original content of a node.
Args:
node (Tree|Token): The node to get the content from.
default: The default value to return if the content is not found.
Returns:
str: The original content of the node.
"""
return (
node.meta.content
if hasattr(node, "meta") and node.meta is not None and not node.meta.empty
else default
)
def __get_user_variable_value(self, name: str, evaluate=True, visit=False) -> str:
"""
Get the value of a user variable.
Args:
name (str): The name of the user variable.
evaluate (bool): Whether to evaluate the variable.
visit (bool): Whether to also visit the variable (add to result).
Returns:
str: The value of the user variable.
"""
v = self.__ppp.user_variables.get(name, None)
if v is not None:
visited = False
if isinstance(v, lark.Tree):
if evaluate:
v = self.__visit(v, not visit)
visited = visit
else:
v = self.__get_original_node_content(v, "not evaluated yet")
if visit and not visited:
self.result += v
return v
def __set_user_variable_value(self, name: str, value: str):
"""
Set the value of a user variable.
Args:
name (str): The name of the user variable.
value (str): The value to be set.
"""
self.__ppp.user_variables[name] = value
def __remove_user_variable(self, name: str):
"""
Remove a user variable.
Args:
name (str): The name of the user variable.
"""
if name in self.__ppp.user_variables:
del self.__ppp.user_variables[name]
def __debug_end(self, construct: str, start_result: str, duration: float, info=None):
"""
Log the end of a construct processing.
Args:
construct (str): The name of the construct.
start_result (str): The initial result.
duration (float): The duration of the processing.
info: Additional information to log.
"""
if self.__ppp.debug_level == DEBUG_LEVEL.full:
info = f"({info}) " if info is not None and info != "" else ""
output = self.result[len(start_result) :]
if output != "":
output = f" >> '{output}'"
self.__ppp.logger.debug(
self.__ppp.format_output(f"TreeProcessor.{construct} {info}({duration:.3f} seconds){output}")
)
def __eval_condition(self, cond_var: str, cond_comp: str, cond_value: str | list[str]) -> bool:
"""
Evaluate a condition based on the given variable, comparison, and value.
Args:
cond_var (str): The variable to be compared.
cond_comp (str): The comparison operator.
cond_value (str or list[str]): The value to be compared with.
Returns:
bool: The result of the condition evaluation.
"""
var_value = self.__ppp.system_variables.get(cond_var, self.__get_user_variable_value(cond_var))
if var_value is None:
var_value = ""
self.__ppp.logger.warning(f"Unknown variable {cond_var}")
if isinstance(var_value, str):
var_value = var_value.lower()
if isinstance(cond_value, list):
comp_ops = {
"contains": lambda x, y: y in x,
"in": lambda x, y: x == y,
}
else:
cond_value = [cond_value]
comp_ops = {
"eq": lambda x, y: x == y,
"ne": lambda x, y: x != y,
"gt": lambda x, y: x > y,
"lt": lambda x, y: x < y,
"ge": lambda x, y: x >= y,
"le": lambda x, y: x <= y,
"contains": lambda x, y: y in x,
"truthy": lambda x, y: bool(x),
}
if cond_comp not in comp_ops:
return False
cond_value_adjusted = list(
(
c[1:-1].lower()
if c.startswith('"') or c.startswith("'")
else True if c.lower() == "true" else False if c.lower() == "false" else int(c)
)
for c in cond_value
)
result = False
for c in cond_value_adjusted:
var_value_adjusted = (
var_value
if isinstance(c, str)
else (
True
if isinstance(c, bool) and var_value != "false" and var_value is not False
else (
False
if isinstance(c, bool) and (var_value != "true" or var_value is False)
else int(var_value)
)
)
)
result = comp_ops[cond_comp](var_value_adjusted, c)
if result:
break
return result
def __evaluate_if(self, condition: lark.Tree) -> bool:
"""
Evaluate an if condition based on the given condition tree.
Args:
condition (Node): The condition tree to be evaluated.
Returns:
bool: The result of the if condition evaluation.
"""
individualcondition: lark.Tree = condition.children[0]
# we get the name of the variable and check for a preceding not
invert = False
first = individualcondition.children[0].value # it should be a Token
if first == "not":
invert = True
cond_var = individualcondition.children[1].value # it should be a Token
poscomp = 2
else:
cond_var = first
poscomp = 1
if poscomp >= len(individualcondition.children):
# no condition, just a variable
cond_comp = "truthy"
cond_value = "true"
else:
# we get the comparison (with possible not) and the value
cond_comp = individualcondition.children[poscomp].value # it should be a Token
if cond_comp == "not":
invert = not invert
poscomp += 1
cond_comp = individualcondition.children[poscomp].value # it should be a Token
poscomp += 1
cond_value_node = individualcondition.children[poscomp]
cond_value = (
list(v.value for v in cond_value_node.children)
if isinstance(cond_value_node, (lark.Tree, list))
else cond_value_node.value if isinstance(cond_value_node, lark.Token) else cond_value_node
)
cond_result = self.__eval_condition(cond_var, cond_comp, cond_value)
if invert:
cond_result = not cond_result
return cond_result
def promptcomp(self, tree: lark.Tree):
"""
Process a prompt composition construct in the tree.
"""
# if self.__ppp.is_comfy_ui():
# self.__ppp.logger.warning("Prompt composition is not supported in ComfyUI.")
start_result = self.result
t1 = time.time()
self.__visit(tree.children[0])
if len(tree.children) > 1:
if tree.children[1] is not None:
self.result += f":{tree.children[1]}"
for i in range(2, len(tree.children), 3):
if self.__ppp.cup_ands:
self.result = re.sub(r"[, ]+$", "\n" if self.__ppp.cup_ands_eol else " ", self.result)
if self.result[-1:].isalnum(): # add space if needed
self.result += " "
self.result += "AND"
added_result = self.__visit(tree.children[i + 1], False, True)
if self.__ppp.cup_ands:
added_result = re.sub(r"^[, ]+", " ", added_result)
if added_result[0:1].isalnum(): # add space if needed
added_result = " " + added_result
self.result += added_result
if tree.children[i + 2] is not None:
self.result += f":{tree.children[i+2]}"
t2 = time.time()
self.__debug_end("promptcomp", start_result, t2 - t1)
def scheduled(self, tree: lark.Tree):
"""
Process a scheduling construct in the tree and add it to the accumulated shell.
"""
# if self.__ppp.is_comfy_ui():
# self.__ppp.logger.warning("Prompt scheduling is not supported in ComfyUI.")
start_result = self.result
t1 = time.time()
before = tree.children[0]
after = tree.children[-2]
pos_str = tree.children[-1]
pos = float(pos_str)
if pos >= 1:
pos = int(pos)
# self.__shell.append(self.AccumulatedShell("sc", pos))
self.result += "["
if before is not None:
if self.__ppp.debug_level == DEBUG_LEVEL.full:
self.__ppp.logger.debug(f"Shell scheduled before with position {pos}")
self.__shell.append(self.AccumulatedShell("scb", pos))
self.__visit(before)
self.__shell.pop()
if self.__ppp.debug_level == DEBUG_LEVEL.full:
self.__ppp.logger.debug(f"Shell scheduled after with position {pos}")
self.__shell.append(self.AccumulatedShell("sca", pos))
self.result += ":"
self.__visit(after)
self.__shell.pop()
if self.__ppp.cup_emptyconstructs and self.result == start_result + "[:":
self.result = start_result
else:
self.result += f":{pos_str}]"
# self.__shell.pop()
t2 = time.time()
self.__debug_end("scheduled", start_result, t2 - t1, pos_str)
def alternate(self, tree: lark.Tree):
"""
Process an alternation construct in the tree and add it to the accumulated shell.
"""
# if self.__ppp.is_comfy_ui():
# self.__ppp.logger.warning("Prompt alternation is not supported in ComfyUI.")
start_result = self.result
t1 = time.time()
# self.__shell.append(self.AccumulatedShell("al", len(tree.children)))
self.result += "["
for i, opt in enumerate(tree.children):
if self.__ppp.debug_level == DEBUG_LEVEL.full:
self.__ppp.logger.debug(f"Shell alternate option {i+1}")
self.__shell.append(self.AccumulatedShell("alo", {"pos": i + 1, "len": len(tree.children)}))
if i > 0:
self.result += "|"
self.__visit(opt)
self.__shell.pop()
self.result += "]"
if self.__ppp.cup_emptyconstructs and self.result == start_result + "[]":
self.result = start_result
# self.__shell.pop()
t2 = time.time()
self.__debug_end("alternate", start_result, t2 - t1)
def attention(self, tree: lark.Tree):
"""
Process a attention change construct in the tree and add it to the accumulated shell.
"""
start_result = self.result
t1 = time.time()
if len(tree.children) == 2:
weight_str = tree.children[-1]
if weight_str is not None:
weight = float(weight_str)
else:
weight = 1.1
weight_str = "1.1"
else:
weight = 0.9
weight_str = "0.9"
if self.__ppp.debug_level == DEBUG_LEVEL.full:
self.__ppp.logger.debug(f"Shell attention with weight {weight}")
current_tree = tree.children[0]
if self.__ppp.cup_mergeattention:
while isinstance(current_tree, lark.Tree) and current_tree.data == "attention":
# we merge the weights
if len(current_tree.children) == 2:
inner_weight = current_tree.children[-1]
if inner_weight is not None:
inner_weight = float(inner_weight)
else:
inner_weight = 1.1
else:
inner_weight = 0.9
weight *= inner_weight
current_tree = current_tree.children[0]
weight = math.floor(weight * 100) / 100 # we round to 2 decimals
weight_str = f"{weight:.2f}".rstrip("0").rstrip(".")
self.__shell.append(self.AccumulatedShell("at", weight))
if weight == 0.9 and not self.__ppp.is_comfy_ui():
starttag = "["
self.result += starttag
self.__visit(current_tree)
endtag = "]"
elif weight == 1.1:
starttag = "("
self.result += starttag
self.__visit(current_tree)
endtag = ")"
else:
starttag = "("
self.result += starttag
self.__visit(current_tree)
endtag = f":{weight_str})"
if self.__ppp.cup_emptyconstructs and self.result == start_result + starttag:
self.result = start_result
else:
self.result += endtag
self.__shell.pop()
t2 = time.time()
self.__debug_end("attention", start_result, t2 - t1, weight_str)
def commandstn(self, tree: lark.Tree):
"""
Process a send to negative command in the tree and add it to the list of negative tags.
"""
start_result = self.result
info = None
t1 = time.time()
if not self.__is_negative:
negtagparameters = tree.children[0]
if negtagparameters is not None:
parameters = negtagparameters.value # should be a token
else:
parameters = ""
content = self.__visit(tree.children[1::], False, True)
self.__negtags.append(
self.NegTag(len(self.result), len(self.result), content, parameters, self.__shell.copy())
)
info = f"with {parameters or 'no parameters'} : {content}"
else:
self.__ppp.logger.warning("Ignored negative command in negative prompt")
self.__visit(tree.children[1::])
t2 = time.time()
self.__debug_end("commandstn", start_result, t2 - t1, info)