-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathppp.py
More file actions
2323 lines (2193 loc) · 110 KB
/
ppp.py
File metadata and controls
2323 lines (2193 loc) · 110 KB
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
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 numpy as np
from ppp_hosts import SUPPORTED_APPS # pylint: disable=import-error
from ppp_logging import DEBUG_LEVEL # pylint: disable=import-error
from ppp_wildcards import PPPWildcard, PPPWildcards # pylint: disable=import-error
from ppp_enmappings import PPPENMappingVariant, PPPExtraNetworkMappings # pylint: disable=import-error
class PPPInterrupt(Exception):
"""
Custom exception to handle interruptions in the PromptPostProcessor.
This exception can be raised to stop the processing of prompts.
"""
def __init__(self, message: str = "Processing interrupted.", pos_prefix: str = "", neg_prefix: str = ""):
super().__init__(message)
self.message = message
self.pos_prefix = pos_prefix
self.neg_prefix = neg_prefix
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"
class ONWARNING_CHOICES(Enum):
warn = "warn"
stop = "stop"
DEFAULT_STN_SEPARATOR = ", "
DEFAULT_VARIANTS_DEFINITIONS = "pony(sdxl)=pony,pny,pdxl\nillustrious(sdxl)=illustrious,illust,ilxl"
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 "
INVALID_CONTENT_STOP = "INVALID CONTENT! {0}\nBREAK "
SUPPORTED_MODELS = [
"sd1",
"sd2",
"sdxl",
"sd3",
"flux",
"auraflow",
]
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,
extranetwork_mappings_obj: PPPExtraNetworkMappings = 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.
extranetwork_mappings_obj: Optional. The extranetwork mappings object to be used for processing.
"""
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
self.extranetwork_mappings_obj = extranetwork_mappings_obj
# General options
self.debug_level = DEBUG_LEVEL(options.get("debug_level", DEBUG_LEVEL.none.value))
self.gen_onwarning = self.ONWARNING_CHOICES(options.get("on_warning", self.ONWARNING_CHOICES.warn.value))
variants_definitions_option = str(options.get("variants_definitions", self.DEFAULT_VARIANTS_DEFINITIONS))
self.variants_definitions = {}
if variants_definitions_option:
lines = variants_definitions_option.splitlines()
for line in lines:
if "=" in line:
model_tag, elements = line.split("=", 1)
model_name, model_type = re.match(r"(\w+)(?:\((\w+)\))?", model_tag).groups()
if model_type is not None and model_type not in self.SUPPORTED_MODELS:
self.logger.warning(
f"Unsupported model type '{model_type}' in definition for variant '{model_name}'."
)
elif model_name in self.SUPPORTED_MODELS:
self.logger.warning(f"Invalid model name in definition for variant '{model_name}'.")
else:
self.variants_definitions[model_name.strip()] = (
model_type or "",
[element.strip() for element in elements.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.stop.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_extraseparators_include_eol = options.get("cleanup_extra_separators_include_eol", False)
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()
# Preprocess grammar content for conditional compilation
self.parser_full_only_old = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": False,
"ALLOW_WILDCARDS": False,
"ALLOW_CHOICES": False,
"ALLOW_COMMVARS": False,
},
),
propagate_positions=True,
)
grammar_content_full = self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": True,
"ALLOW_CHOICES": True,
"ALLOW_COMMVARS": True,
},
)
self.parser_complete_full = lark.Lark(
grammar_content_full,
propagate_positions=True,
)
self.parser_complete_wc_ch = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": True,
"ALLOW_CHOICES": True,
"ALLOW_COMMVARS": False,
},
),
propagate_positions=True,
)
self.parser_complete_wc_cv = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": True,
"ALLOW_CHOICES": False,
"ALLOW_COMMVARS": True,
},
),
propagate_positions=True,
)
self.parser_complete_ch_cv = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": False,
"ALLOW_CHOICES": True,
"ALLOW_COMMVARS": True,
},
),
propagate_positions=True,
)
self.parser_complete_wc = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": True,
"ALLOW_CHOICES": False,
"ALLOW_COMMVARS": False,
},
),
propagate_positions=True,
)
self.parser_complete_ch = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": False,
"ALLOW_CHOICES": True,
"ALLOW_COMMVARS": False,
},
),
propagate_positions=True,
)
self.parser_complete_cv = lark.Lark(
self.__preprocess_grammar(
grammar_content,
{
"ALLOW_NEW_CONTENT": True,
"ALLOW_WILDCARDS": False,
"ALLOW_CHOICES": False,
"ALLOW_COMMVARS": True,
},
),
propagate_positions=True,
)
# Partial parsers
self.parser_content = lark.Lark(
grammar_content_full,
propagate_positions=True,
start="content",
)
self.parser_choice = lark.Lark(
grammar_content_full,
propagate_positions=True,
start="choice",
)
self.parser_choicesoptions = lark.Lark(
grammar_content_full,
propagate_positions=True,
start="choicesoptions",
)
self.parser_condition = lark.Lark(
grammar_content_full,
propagate_positions=True,
start="condition",
)
self.parser_choicevalue = lark.Lark(
grammar_content_full,
propagate_positions=True,
start="choicevalue",
)
self.__init_sysvars()
self.user_variables = {}
self.echoed_variables = {}
def __preprocess_grammar(self, grammar_content: str, options: dict[str, bool]) -> str:
"""
Preprocesses the grammar content to handle conditional compilation directives.
Args:
grammar_content (str): The raw grammar content.
options (dict[str,bool]): Options for preprocessing.
Returns:
str: The preprocessed grammar content.
"""
lines = grammar_content.split("\n")
result_lines = []
skip_current_block = []
all_blocks_skipped = []
def evaluate_conditions(conditions: list[str]) -> bool:
"""
Evaluates the conditions based on the provided options. Allows for negation with '!' prefix.
Args:
conditions (list[str]): List of conditions to evaluate.
Returns:
bool: True if all conditions are met, False otherwise.
"""
r = True
for condition in conditions:
if condition.startswith("!"):
r = r and not options.get(condition[1:], False)
else:
r = r and options.get(condition, True)
return r
for line in lines:
stripped_line = line.strip()
if stripped_line.startswith("//#if"):
# Extract condition from the #if directive
conditions = stripped_line[5:].strip().split(" ")
# Evaluate the conditions
skip_current_block.append(not evaluate_conditions(conditions))
all_blocks_skipped.append(skip_current_block[-1])
continue
if stripped_line.startswith("//#elif"):
if not skip_current_block:
self.logger.warning("Unmatched //#elif directive found in grammar content.")
elif all_blocks_skipped[-1]:
# Extract condition from the #elif directive
conditions = stripped_line[7:].strip().split(" ")
# Evaluate the conditions
skip_current_block[-1] = not evaluate_conditions(conditions)
if not skip_current_block[-1]:
all_blocks_skipped[-1] = False
else:
skip_current_block[-1] = True
continue
if stripped_line.startswith("//#else"):
if not skip_current_block:
self.logger.warning("Unmatched //#else directive found in grammar content.")
elif all_blocks_skipped[-1]:
skip_current_block[-1] = False
else:
skip_current_block[-1] = True
continue
if stripped_line.startswith("//#endif"):
if not skip_current_block:
self.logger.warning("Unmatched //#endif directive found in grammar content.")
else:
skip_current_block.pop()
all_blocks_skipped.pop()
continue
# Include the line if we're not skipping any current block
if not any(skip_current_block):
result_lines.append(stripped_line)
# Check for unclosed blocks at the end
if skip_current_block:
self.logger.warning(
f"Found {len(skip_current_block)} unclosed conditional directive(s) at the end of the file"
)
return "\n".join(result_lines)
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", "") == SUPPORTED_APPS.comfyui.value
def __init_sysvars(self):
"""
Initializes the system variables.
"""
self.system_variables = {}
sdchecks = {x: self.env_info.get("is_" + x, False) for x in self.SUPPORTED_MODELS}
sdchecks.update({"": 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", "")
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", "")
is_models = {
model_name: (model_type_and_substrings[0] == "" or sdchecks.get(model_type_and_substrings[0], False))
and any(s in model_filename.lower() for s in model_type_and_substrings[1])
for model_name, model_type_and_substrings in self.variants_definitions.items()
if model_name not in self.SUPPORTED_MODELS
}
is_models_true = [k for k, v in is_models.items() if v]
if len(is_models_true) > 1:
self.logger.warning(
f"Multiple model variants detected at the same time in the filename!: {', '.join(is_models_true)}"
)
self.system_variables.update({"_is_" + x: y for x, y in is_models.items()})
for x in sdchecks.keys():
if x != "":
self.system_variables["_is_" + x] = sdchecks[x]
self.system_variables["_is_pure_" + x] = sdchecks[x] and not any(is_models.values())
self.system_variables["_is_variant_" + x] = sdchecks[x] and any(is_models.values())
# special cases
self.system_variables["_is_sd"] = sdchecks["sd1"] or sdchecks["sd2"] or sdchecks["sdxl"] or sdchecks["sd3"]
is_ssd = self.env_info.get("is_ssd", False)
self.system_variables["_is_ssd"] = is_ssd
self.system_variables["_is_sdxl_no_ssd"] = sdchecks["sdxl"] and not is_ssd
# backcompatibility (but the modern one to use would be _is_pure_sdxl)
self.system_variables["_is_sdxl_no_pony"] = sdchecks["sdxl"] and not self.system_variables.get(
"_is_pony", False
)
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)
optwhitespace = r"\s*" if self.cup_extraseparators_include_eol else r"[ \t\v\f]*"
optwhitespace_separator = optwhitespace + escapedSeparator + optwhitespace
optwhitespace_comma = optwhitespace + "," + optwhitespace
sep_options = [(optwhitespace_separator, self.stn_separator)] # sendtonegative separator
if optwhitespace_comma != optwhitespace_separator:
sep_options.append((optwhitespace_comma, ", ")) # regular comma separator
for sep, replacement in sep_options:
if self.cup_extraseparators:
# collapse separators
text = re.sub(r"(?:" + sep + r"){2,}", replacement, text)
# remove separator after starting parenthesis or bracket
text = re.sub(
r"(" + sep + r"[([])(?:" + sep + r")+",
r"\1",
text,
)
# remove before colon or ending parenthesis or bracket
text = re.sub(
r"(?:" + sep + r")+([:)\]]" + sep + r")",
r"\1",
text,
)
if self.cup_extraseparators2:
# remove at start of prompt or line
text = re.sub(r"^(?:" + sep + r")+", "", text, flags=re.MULTILINE)
# remove at end of prompt or line
text = re.sub(r"(?:" + sep + r")+$", "", 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 __get_best_parser(self, prompt: str) -> tuple[lark.Lark, str]:
"""
Checks the prompt and returns the best parser to use based on its content.
Args:
prompt (str): The prompt to check.
Returns:
tuple[lark.Lark, str]: The best parser and its description.
"""
tests = {
"ALLOW_WILDCARDS": re.search(r"(?<!\\)__", prompt) is not None,
"ALLOW_CHOICES": re.search(r"(?<!\$\\)\{|\}", prompt) is not None,
"ALLOW_COMMVARS": re.search(r"(?<!\\)(?:<ppp:|\$\{)", prompt) is not None,
}
if tests["ALLOW_WILDCARDS"] and tests["ALLOW_CHOICES"] and tests["ALLOW_COMMVARS"]:
return (
self.parser_complete_full,
"full parser with wildcards, choices, commands and variables",
)
if tests["ALLOW_WILDCARDS"] and tests["ALLOW_CHOICES"]:
return (
self.parser_complete_wc_ch,
"parser with wildcards and choices",
)
if tests["ALLOW_WILDCARDS"] and tests["ALLOW_COMMVARS"]:
return (
self.parser_complete_wc_cv,
"parser with wildcards, commands and variables",
)
if tests["ALLOW_CHOICES"] and tests["ALLOW_COMMVARS"]:
return (
self.parser_complete_ch_cv,
"parser with choices, commands and variables",
)
if tests["ALLOW_WILDCARDS"]:
return (
self.parser_complete_wc,
"parser with wildcards",
)
if tests["ALLOW_CHOICES"]:
return (
self.parser_complete_ch,
"parser with choices",
)
if tests["ALLOW_COMMVARS"]:
return (
self.parser_complete_cv,
"parser with commands and variables",
)
return (
self.parser_full_only_old,
"simple parser without new constructs",
)
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 = {}
self.echoed_variables = {}
all_variables = {**self.system_variables}
# Process prompt
p_processor = self.TreeProcessor(self)
(prompt_parser, parser_description) = self.__get_best_parser(prompt)
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(f"Using {parser_description} for prompt")
p_parsed = self.parse_prompt(
"prompt",
prompt,
prompt_parser,
)
prompt = p_processor.start_visit("prompt", p_parsed, False)
# Process negative prompt
n_processor = self.TreeProcessor(self)
(n_prompt_parser, n_parser_description) = self.__get_best_parser(negative_prompt)
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(f"Using {n_parser_description} for negative prompt")
n_parsed = self.parse_prompt(
"negative prompt",
negative_prompt,
n_prompt_parser,
)
negative_prompt = n_processor.start_visit("negative prompt", n_parsed, True)
var_keys = set(self.user_variables.keys()).union(set(self.echoed_variables.keys()))
for k in var_keys:
ev = self.echoed_variables.get(k)
if ev is None:
ev = self.user_variables.get(k)
if ev is None or not isinstance(ev, str):
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(self.format_output(f"Completing variable: {k}"))
ev = p_processor.get_final_user_variable(k)
all_variables[k] = ev
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(self.format_output(f"All variables: {all_variables}"))
# 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 p_processor.add_at["start"]:
negative_prompt = self.__add_to_start(negative_prompt, p_processor.add_at["start"])
if p_processor.add_at["end"]:
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 = bool(p_processor.detectedWildcards)
foundNP = bool(n_processor.detectedWildcards)
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:
raise PPPInterrupt(
"Found unprocessed wildcards!",
self.WILDCARD_STOP.format(ppwl) if foundP else "",
self.WILDCARD_STOP.format(npwl) if foundNP else "",
)
# 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 found_sequences:
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, all_variables
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, negative prompt and all the prompt variables.
"""
all_variables = {}
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.monotonic_ns()
prompt, negative_prompt, all_variables = self.__processprompts(prompt, negative_prompt)
t2 = time.monotonic_ns()
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) / 1_000_000_000:.3f} seconds")
# if self.debug_level != DEBUG_LEVEL.none:
# self.logger.debug(f"Wildcards memory usage: {self.wildcard_obj.__sizeof__()}")
# Check for constructs not processed due to parsing problems
fullcontent: str = prompt + negative_prompt
if fullcontent.find("<ppp:") >= 0:
raise PPPInterrupt(
"Found unprocessed constructs!",
self.UNPROCESSED_STOP if prompt.find("<ppp:") >= 0 else "",
self.UNPROCESSED_STOP if negative_prompt.find("<ppp:") >= 0 else "",
)
return prompt, negative_prompt, all_variables
except PPPInterrupt as e:
self.logger.error(e.message)
if e.pos_prefix:
prompt = e.pos_prefix + prompt
if e.neg_prefix:
negative_prompt = e.neg_prefix + negative_prompt
self.logger.error("Interrupting!")
self.interrupt()
return prompt, negative_prompt, all_variables
except Exception as e: # pylint: disable=broad-exception-caught
self.logger.exception(e)
return original_prompt, original_negative_prompt, all_variables
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.monotonic_ns()
parsed_prompt = None
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
if isinstance(parsed_prompt, lark.Tree):
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.monotonic_ns()
if self.debug_level == DEBUG_LEVEL.full:
self.logger.debug(f"Parse {prompt_description} time: {(t2 - t1) / 1_000_000_000:.3f} seconds")
if parsed_prompt:
self.logger.debug(
"Tree:\n"
+ textwrap.indent(
re.sub(
r"\n$",
"",
parsed_prompt.pretty() if isinstance(parsed_prompt, lark.Tree) else parsed_prompt,
),
" ",
)
)
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.__seen_wildcards: list[str] = []
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 warn_or_stop(self, message: str, e: Exception = None):
if self.__ppp.gen_onwarning == self.__ppp.ONWARNING_CHOICES.stop:
raise PPPInterrupt(
message,
self.__ppp.INVALID_CONTENT_STOP.format(message) if not self.__is_negative else "",
self.__ppp.INVALID_CONTENT_STOP.format(message) if self.__is_negative else "",
) from e
self.__ppp.logger.warning(message)
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.monotonic_ns()
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.monotonic_ns()
if self.__ppp.debug_level != DEBUG_LEVEL.none:
self.__ppp.logger.info(f"Process {prompt_description} time: {(t2 - t1) / 1_000_000_000:.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
len_backup = len(backup_result)
# if self.result[:len_backup] == backup_result: # this is only necessary if we call parse_prompt with a parser from "start", because it resets the result
added_result = self.result[len_backup:]
# else:
# added_result = self.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:
"""