diff --git a/.gitignore b/.gitignore index 654640b..e39b4dd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ - +.tox* *.pyc +automated_outputs/* userfiles/antilist.csv -userfiles/config.csv \ No newline at end of file +userfiles/config.csv +userfiles/*replace.csv +userfiles/*addon.csv \ No newline at end of file diff --git a/OneButtonPromptNodes.py b/OneButtonPromptNodes.py index 95f50e6..4d3dafa 100644 --- a/OneButtonPromptNodes.py +++ b/OneButtonPromptNodes.py @@ -1,47 +1,139 @@ -import sys import os -import folder_paths -from datetime import datetime -import uuid import platform - +import sys +import uuid +from datetime import datetime + +import folder_paths + +from build_dynamic_prompt import build_dynamic_prompt, createpromptvariant +from csv_reader import load_config_csv, re + custom_nodes_path = os.path.join(folder_paths.base_path, "custom_nodes") onebuttonprompt_path = os.path.join(custom_nodes_path, "OneButtonPrompt") sys.path.append(onebuttonprompt_path) -from build_dynamic_prompt import * -from csv_reader import * - -artists = ["all", "none", "popular", "greg mode", "3D", "abstract", "angular", "anime" ,"architecture", "art nouveau", "art deco", "baroque", "bauhaus", "cartoon", "character", "children's illustration", "cityscape", "clean", "cloudscape", "collage", "colorful", "comics", "cubism", "dark", "detailed", "digital", "expressionism", "fantasy", "fashion", "fauvism", "figurativism", "gore", "graffiti", "graphic design", "high contrast", "horror", "impressionism", "installation", "landscape", "light", "line drawing", "low contrast", "luminism", "magical realism", "manga", "melanin", "messy", "monochromatic", "nature", "nudity", "photography", "pop art", "portrait", "primitivism", "psychedelic", "realism", "renaissance", "romanticism", "scene", "sci-fi", "sculpture", "seascape", "space", "stained glass", "still life", "storybook realism", "street art", "streetscape", "surrealism", "symbolism", "textile", "ukiyo-e", "vibrant", "watercolor", "whimsical"] -imagetypes = ["all", "all - force multiple", "photograph", "octane render","digital art","concept art", "painting", "portrait", "anime key visual", "only other types", "only templates mode", "art blaster mode", "quality vomit mode", "color cannon mode", "unique art mode", "massive madness mode", "photo fantasy mode", "subject only mode", "fixed styles mode"] -subjects =["all", "object", "animal", "humanoid", "landscape", "concept"] +artists = [ + "all", + "none", + "popular", + "greg mode", + "3D", + "abstract", + "angular", + "anime", + "architecture", + "art nouveau", + "art deco", + "baroque", + "bauhaus", + "cartoon", + "character", + "children's illustration", + "cityscape", + "clean", + "cloudscape", + "collage", + "colorful", + "comics", + "cubism", + "dark", + "detailed", + "digital", + "expressionism", + "fantasy", + "fashion", + "fauvism", + "figurativism", + "gore", + "graffiti", + "graphic design", + "high contrast", + "horror", + "impressionism", + "installation", + "landscape", + "light", + "line drawing", + "low contrast", + "luminism", + "magical realism", + "manga", + "melanin", + "messy", + "monochromatic", + "nature", + "nudity", + "photography", + "pop art", + "portrait", + "primitivism", + "psychedelic", + "realism", + "renaissance", + "romanticism", + "scene", + "sci-fi", + "sculpture", + "seascape", + "space", + "stained glass", + "still life", + "storybook realism", + "street art", + "streetscape", + "surrealism", + "symbolism", + "textile", + "ukiyo-e", + "vibrant", + "watercolor", + "whimsical" +] +imagetypes = [ + "all", + "all - force multiple", + "photograph", + "octane render", + "digital art", + "concept art", + "painting", + "portrait", + "anime key visual", + "only other types", + "only templates mode", + "art blaster mode", + "quality vomit mode", + "color cannon mode", + "unique art mode", + "massive madness mode", + "photo fantasy mode", + "subject only mode", + "fixed styles mode" +] +subjects = ["all", "object", "animal", "humanoid", "landscape", "concept"] genders = ["all", "male", "female"] emojis = [False, True] - -subjects =["all"] +subjects = ["all"] subjectsubtypesobject = ["all"] subjectsubtypeshumanoid = ["all"] subjectsubtypesconcept = ["all"] -#subjectsubtypesobject = ["all", "generic objects", "vehicles", "food", "buildings", "space", "flora"] -#subjectsubtypeshumanoid = ["all", "generic humans", "generic human relations", "celebrities e.a.", "fictional characters", "humanoids", "based on job or title", "based on first name"] -#subjectsubtypesconcept = ["all", "event", "the X of Y concepts", "lines from poems", "lines from songs"] - # Load up stuff for personal artists list, if any # find all artist files starting with personal_artits in userfiles script_dir = os.path.dirname(os.path.abspath(__file__)) # Script directory -userfilesfolder = os.path.join(script_dir, "./userfiles/" ) +userfilesfolder = os.path.join(script_dir, "./userfiles/") for filename in os.listdir(userfilesfolder): - if(filename.endswith(".csv") and filename.startswith("personal_artists") and filename != "personal_artists_sample.csv"): + if filename.endswith(".csv") and filename.startswith("personal_artists") and \ + filename != "personal_artists_sample.csv": name = os.path.splitext(filename)[0] - name = name.replace("_"," ",-1).lower() + name = name.replace("_", " ", -1).lower() # directly insert into the artists list artists.insert(2, name) # on startup, check if we have a config file, or else create it -config = load_config_csv() - +config = load_config_csv() # load subjects stuff from config generatevehicle = True @@ -64,176 +156,194 @@ generatepoemline = True generatesongline = True - for item in config: - # objects - if item[0] == 'subject_vehicle' and item[1] != 'on': - generatevehicle = False - if item[0] == 'subject_object' and item[1] != 'on': - generateobject = False - if item[0] == 'subject_food' and item[1] != 'on': - generatefood = False - if item[0] == 'subject_building' and item[1] != 'on': - generatebuilding = False - if item[0] == 'subject_space' and item[1] != 'on': - generatespace = False - if item[0] == 'subject_flora' and item[1] != 'on': - generateflora = False - # animals - if item[0] == 'subject_animal' and item[1] != 'on': - generateanimal = False - # humanoids - if item[0] == 'subject_manwoman' and item[1] != 'on': - generatemanwoman = False - if item[0] == 'subject_manwomanrelation' and item[1] != 'on': - generatemanwomanrelation = False - if item[0] == 'subject_fictional' and item[1] != 'on': - generatefictionalcharacter = False - if item[0] == 'subject_nonfictional' and item[1] != 'on': - generatenonfictionalcharacter = False - if item[0] == 'subject_humanoid' and item[1] != 'on': - generatehumanoids = False - if item[0] == 'subject_job' and item[1] != 'on': - generatejob = False - if item[0] == 'subject_firstnames' and item[1] != 'on': - generatefirstnames = False - # landscape - if item[0] == 'subject_landscape' and item[1] != 'on': - generatelandscape = False - # concept - if item[0] == 'subject_event' and item[1] != 'on': - generateevent = False - if item[0] == 'subject_concept' and item[1] != 'on': - generateconcepts = False - if item[0] == 'poemline' and item[1] != 'on': - generatepoemline = False - if item[0] == 'songline' and item[1] != 'on': - generatesongline = False + # objects + if item[0] == 'subject_vehicle' and item[1] != 'on': + generatevehicle = False + if item[0] == 'subject_object' and item[1] != 'on': + generateobject = False + if item[0] == 'subject_food' and item[1] != 'on': + generatefood = False + if item[0] == 'subject_building' and item[1] != 'on': + generatebuilding = False + if item[0] == 'subject_space' and item[1] != 'on': + generatespace = False + if item[0] == 'subject_flora' and item[1] != 'on': + generateflora = False + # animals + if item[0] == 'subject_animal' and item[1] != 'on': + generateanimal = False + # humanoids + if item[0] == 'subject_manwoman' and item[1] != 'on': + generatemanwoman = False + if item[0] == 'subject_manwomanrelation' and item[1] != 'on': + generatemanwomanrelation = False + if item[0] == 'subject_fictional' and item[1] != 'on': + generatefictionalcharacter = False + if item[0] == 'subject_nonfictional' and item[1] != 'on': + generatenonfictionalcharacter = False + if item[0] == 'subject_humanoid' and item[1] != 'on': + generatehumanoids = False + if item[0] == 'subject_job' and item[1] != 'on': + generatejob = False + if item[0] == 'subject_firstnames' and item[1] != 'on': + generatefirstnames = False + # landscape + if item[0] == 'subject_landscape' and item[1] != 'on': + generatelandscape = False + # concept + if item[0] == 'subject_event' and item[1] != 'on': + generateevent = False + if item[0] == 'subject_concept' and item[1] != 'on': + generateconcepts = False + if item[0] == 'poemline' and item[1] != 'on': + generatepoemline = False + if item[0] == 'songline' and item[1] != 'on': + generatesongline = False # build up all subjects we can choose based on the loaded config file -if(generatevehicle or generateobject or generatefood or generatebuilding or generatespace): - subjects.append("object") -if(generateanimal): - subjects.append("animal") -if(generatemanwoman or generatemanwomanrelation or generatefictionalcharacter or generatenonfictionalcharacter or generatehumanoids or generatejob): - subjects.append("humanoid") -if(generatelandscape): - subjects.append("landscape") -if(generateevent or generateconcepts or generatepoemline or generatesongline): - subjects.append("concept") - - -# do the same for the subtype subjects -# subjectsubtypesobject = ["all"] -# subjectsubtypeshumanoid = ["all"] -# subjectsubtypesconcept = ["all"] +if generatevehicle or generateobject or generatefood or generatebuilding or generatespace: + subjects.append("object") +if generateanimal: + subjects.append("animal") +if generatemanwoman or generatemanwomanrelation or generatefictionalcharacter or generatenonfictionalcharacter \ + or generatehumanoids or generatejob: + subjects.append("humanoid") +if generatelandscape: + subjects.append("landscape") +if generateevent or generateconcepts or generatepoemline or generatesongline: + subjects.append("concept") # objects first -if(generateobject): - subjectsubtypesobject.append("generic objects") -if(generatevehicle): - subjectsubtypesobject.append("vehicles") -if(generatefood): - subjectsubtypesobject.append("food") -if(generatebuilding): - subjectsubtypesobject.append("buildings") -if(generatespace): - subjectsubtypesobject.append("space") -if(generateflora): - subjectsubtypesobject.append("flora") +if generateobject: + subjectsubtypesobject.append("generic objects") +if generatevehicle: + subjectsubtypesobject.append("vehicles") +if generatefood: + subjectsubtypesobject.append("food") +if generatebuilding: + subjectsubtypesobject.append("buildings") +if generatespace: + subjectsubtypesobject.append("space") +if generateflora: + subjectsubtypesobject.append("flora") # humanoids (should I review descriptions??) -if(generatemanwoman): - subjectsubtypeshumanoid.append("generic humans") -if(generatemanwomanrelation): - subjectsubtypeshumanoid.append("generic human relations") -if(generatenonfictionalcharacter): - subjectsubtypeshumanoid.append("celebrities e.a.") -if(generatefictionalcharacter): - subjectsubtypeshumanoid.append("fictional characters") -if(generatehumanoids): - subjectsubtypeshumanoid.append("humanoids") -if(generatejob): - subjectsubtypeshumanoid.append("based on job or title") -if(generatefirstnames): - subjectsubtypeshumanoid.append("based on first name") +if generatemanwoman: + subjectsubtypeshumanoid.append("generic humans") +if generatemanwomanrelation: + subjectsubtypeshumanoid.append("generic human relations") +if generatenonfictionalcharacter: + subjectsubtypeshumanoid.append("celebrities e.a.") +if generatefictionalcharacter: + subjectsubtypeshumanoid.append("fictional characters") +if generatehumanoids: + subjectsubtypeshumanoid.append("humanoids") +if generatejob: + subjectsubtypeshumanoid.append("based on job or title") +if generatefirstnames: + subjectsubtypeshumanoid.append("based on first name") # concepts -if(generateevent): - subjectsubtypesconcept.append("event") -if(generateconcepts): - subjectsubtypesconcept.append("the X of Y concepts") -if(generatepoemline): - subjectsubtypesconcept.append("lines from poems") -if(generatesongline): - subjectsubtypesconcept.append("lines from songs") - -class OneButtonPrompt: +if generateevent: + subjectsubtypesconcept.append("event") +if generateconcepts: + subjectsubtypesconcept.append("the X of Y concepts") +if generatepoemline: + subjectsubtypesconcept.append("lines from poems") +if generatesongline: + subjectsubtypesconcept.append("lines from songs") +class OneButtonPrompt: def __init__(self): pass - + @classmethod def INPUT_TYPES(s): - return { "required": { "insanitylevel": ("INT", { "default": 5, - "min": 1, #Minimum value - "max": 10, #Maximum value - "step": 1 #Slider's step + "min": 1, + "max": 10, + "step": 1 }), - }, + }, "optional": { "artist": (artists, {"default": "all"}), "imagetype": (imagetypes, {"default": "all"}), "imagemodechance": ("INT", { "default": 20, - "min": 1, #Minimum value - "max": 100, #Maximum value - "step": 1 #Slider's step + "min": 1, + "max": 100, + "step": 1 }), "subject": (subjects, {"default": "all"}), "custom_subject": ("STRING", { - "multiline": False, #True if you want the field to look like the one on the ClipTextEncode node + "multiline": False, # True if you want the field to look like the one on the ClipTextEncode node "default": "" }), "subject_subtype_objects": (subjectsubtypesobject, {"default": "all"}), "subject_subtypes_humanoids": (subjectsubtypeshumanoid, {"default": "all"}), "humanoids_gender": (genders, {"default": "all"}), "subject_subtypes_concepts": (subjectsubtypesconcept, {"default": "all"}), - "emojis":(emojis, {"default": False}), - + "emojis": (emojis, {"default": False}), "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), }, } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("prompt",) - FUNCTION = "Comfy_OBP" - - #OUTPUT_NODE = False - CATEGORY = "OneButtonPrompt" - - def Comfy_OBP(self, insanitylevel, custom_subject,seed, artist,imagetype, subject, imagemodechance, humanoids_gender, subject_subtype_objects, subject_subtypes_humanoids, subject_subtypes_concepts, emojis): - generatedprompt = build_dynamic_prompt(insanitylevel,subject,artist,imagetype,False,"","","",1,"",custom_subject,True,"",imagemodechance, humanoids_gender, subject_subtype_objects, subject_subtypes_humanoids, subject_subtypes_concepts, False, emojis) - #print(generatedprompt) + + def Comfy_OBP( + self, + insanitylevel, + custom_subject, + seed, + artist, + imagetype, + subject, + imagemodechance, + humanoids_gender, + subject_subtype_objects, + subject_subtypes_humanoids, + subject_subtypes_concepts, + emojis + ): + generatedprompt = build_dynamic_prompt( + insanitylevel, + subject, + artist, + imagetype, + False, + "", + "", + "", + 1, + "", + custom_subject, + True, + "", + imagemodechance, + humanoids_gender, + subject_subtype_objects, + subject_subtypes_humanoids, + subject_subtypes_concepts, + False, + emojis + ) return (generatedprompt,) class CreatePromptVariant: - - def __init__(self): pass - + @classmethod def INPUT_TYPES(s): - return { "required": { "prompt_input": ("STRING", {"default": '', "multiline": True}), @@ -241,9 +351,9 @@ def INPUT_TYPES(s): "optional": { "insanitylevel": ("INT", { "default": 5, - "min": 1, #Minimum value - "max": 10, #Maximum value - "step": 1 #Slider's step + "min": 1, + "max": 10, + "step": 1 }), "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}), }, @@ -251,20 +361,17 @@ def INPUT_TYPES(s): RETURN_TYPES = ("STRING",) RETURN_NAMES = ("prompt",) - FUNCTION = "Comfy_OBP_PromptVariant" - #OUTPUT_NODE = False - CATEGORY = "OneButtonPrompt" - + def Comfy_OBP_PromptVariant(self, prompt_input, insanitylevel, seed): generatedprompt = createpromptvariant(prompt_input, insanitylevel) - + print(generatedprompt) - return (generatedprompt,) + # Let us create our own prompt saver. Not everyone has WAS installed class SavePromptToFile: def __init__(self): @@ -277,15 +384,14 @@ def INPUT_TYPES(s): return { "required": { "filename_prefix": ("STRING", {"default": "Prompt"}), - "positive_prompt": ("STRING",{"multiline": True}), - "negative_prompt": ("STRING",{"multiline": True}), + "positive_prompt": ("STRING", {"multiline": True}), + "negative_prompt": ("STRING", {"multiline": True}), }, } OUTPUT_NODE = True RETURN_TYPES = () FUNCTION = "saveprompttofile" - CATEGORY = "OneButtonPrompt" def saveprompttofile(self, positive_prompt, negative_prompt, filename_prefix): @@ -309,12 +415,10 @@ def saveprompttofile(self, positive_prompt, negative_prompt, filename_prefix): # first lol, I got to make sure it doesn't overlap things date_format = date_format.replace('M', 'X') date_format = date_format.replace('m', 'Z') - - # This is so bad + # This is so bad # lets make it even worse, it work differently on windows than in Linux - if(platform.system() == 'Windows'): - + if platform.system() == 'Windows': date_format = date_format.replace('yyyy', '%Y') date_format = date_format.replace('yy', '%#y') date_format = date_format.replace('X', '%#m') @@ -331,29 +435,26 @@ def saveprompttofile(self, positive_prompt, negative_prompt, filename_prefix): date_format = date_format.replace('Z', '%-M') date_format = date_format.replace('s', '%-S') - # Format the date using the extracted format formatted_date = current_date.strftime(date_format) # Replace the matched pattern with the formatted date filename_prefix = re.sub(pattern, formatted_date, filename_prefix) - - - - full_output_folder, filename_short, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir) + full_output_folder, filename_short, counter, subfolder, filename_prefix = \ + folder_paths.get_save_image_path(filename_prefix, self.output_dir) # make the filename, from from a to the first comma # find the index of the first comma after "of a" or end of the prompt - if(positive_prompt.find("of a ") != -1): - start_index = positive_prompt.find("of a ") + len("of a ") + if positive_prompt.find("of a ") != -1: + start_index = f'{positive_prompt.find("of a ")}{len("of a ")}' end_index = positive_prompt.find(",", start_index) - if(end_index == -1): - end_index=len(positive_prompt) + if end_index == -1: + end_index = len(positive_prompt) else: start_index = 0 end_index = 128 - + # extract the desired substring using slicing filename = positive_prompt[start_index:end_index] @@ -372,35 +473,30 @@ def saveprompttofile(self, positive_prompt, negative_prompt, filename_prefix): # Use regular expression to filter out any characters not in the whitelist filename = re.sub(r"[^{}]+".format(re.escape(''.join(safe_characters))), '', filename) - - if(filename==""): + if filename == "": filename = str(uuid.uuid4()) - - if(filename_prefix == ""): - # create a datetime object for the current date and time - # if there is no prefix + + if filename_prefix == "": + # create a datetime object for the current date and time + # if there is no prefix now = datetime.now() - filenamecomplete = now.strftime("%Y%m%d%H%M%S") + "_" + filename.replace(" ", "_").strip() + ".txt" - + filenamecomplete = f'{now.strftime("%Y%m%d%H%M%S")}_{filename.replace(" ", "_").strip()}.txt' else: # lol since we insert a file, the counter of the image goes up by 1. # So we add 1 here, so the prompt file matches the image file formatted_counter = str(counter + 1).zfill(5) - filenamecomplete = filename_short + "_" + formatted_counter + "_" + filename.replace(" ", "_").strip() + ".txt" - - + filenamecomplete = f'{filename_short}_{formatted_counter}_{filename.replace(" ", "_").strip()}.txt' + directoryandfilename = os.path.abspath(os.path.join(full_output_folder, filenamecomplete)) - with open(directoryandfilename, 'w', encoding="utf-8") as file: - file.write("prompt: " + positive_prompt + "\n") - file.write("negative prompt: " + negative_prompt + "\n") - - + file.write(f'prompt: {positive_prompt}\n') + file.write(f'negative prompt: {negative_prompt}\n') return ("done") + # A dictionary that contains all nodes you want to export with their names # NOTE: names should be globally unique NODE_CLASS_MAPPINGS = { diff --git a/__init__.py b/__init__.py index a42abda..28bb4f8 100644 --- a/__init__.py +++ b/__init__.py @@ -1,11 +1,13 @@ import os import sys + import folder_paths +from OneButtonPromptNodes import (NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS) + custom_nodes_path = os.path.join(folder_paths.base_path, "custom_nodes") onebuttonprompt_path = os.path.join(custom_nodes_path, "OneButtonPrompt") sys.path.append(onebuttonprompt_path) -from OneButtonPromptNodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS - -__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] \ No newline at end of file +__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] diff --git a/build_dynamic_prompt.py b/build_dynamic_prompt.py index aa1896f..b7e65c6 100644 --- a/build_dynamic_prompt.py +++ b/build_dynamic_prompt.py @@ -1,78 +1,104 @@ import random import re -from csv_reader import * -from random_functions import * +from csv_reader import (artist_category_csv_to_list, csv_to_list, + load_config_csv) +from random_functions import (chance_roll, common_dist, legendary_dist, + normal_dist, novel_dist, rare_dist, + uncommon_dist, unique_dist) - -#builds a prompt dynamically +# builds a prompt dynamically # insanity level controls randomness of propmt 0-10 # forcesubject van be used to force a certain type of subject -# Set artistmode to none, to exclude artists -def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all", imagetype = "all", onlyartists = False, antivalues = "", prefixprompt = "", suffixprompt ="",promptcompounderlevel ="1", seperator = "comma", givensubject="",smartsubject = True,giventypeofimage="", imagemodechance = 20, gender = "all", subtypeobject="all", subtypehumanoid="all", subtypeconcept="all", advancedprompting=True, hardturnoffemojis=False): - - +# Set artistmode to none, to exclude artists +def build_dynamic_prompt( + insanitylevel=5, + forcesubject="all", + artists="all", + imagetype="all", + onlyartists=False, + antivalues="", + prefixprompt="", + suffixprompt="", + promptcompounderlevel="1", + seperator="comma", + givensubject="", + smartsubject=True, + giventypeofimage="", + imagemodechance=20, + gender="all", + subtypeobject="all", + subtypehumanoid="all", + subtypeconcept="all", + advancedprompting=True, + hardturnoffemojis=False +): # load the config file config = load_config_csv() - - # first build up a complete anti list. Those values are removing during list building # this uses the antivalues string AND the antilist.csv emptylist = [] - antilist = csv_to_list("antilist",emptylist , "./userfiles/",1) + antilist = csv_to_list("antilist", emptylist, "./userfiles/", 1) antivaluelist = antivalues.split(",") - antilist += antivaluelist # build all lists here - - colorlist = csv_to_list("colors",antilist) - animallist = csv_to_list("animals",antilist) - materiallist = csv_to_list("materials",antilist) - objectlist = csv_to_list("objects",antilist) - fictionallist = csv_to_list(csvfilename="fictional characters",antilist=antilist,skipheader=True,gender=gender) - nonfictionallist = csv_to_list(csvfilename="nonfictional characters",antilist=antilist,skipheader=True,gender=gender) - conceptsuffixlist = csv_to_list("concept_suffix",antilist) - buildinglist = csv_to_list("buildings",antilist) - vehiclelist = csv_to_list("vehicles",antilist) - outfitlist = csv_to_list("outfits",antilist) - locationlist = csv_to_list("locations",antilist) - - accessorielist = csv_to_list("accessories",antilist) - artmovementlist = csv_to_list("artmovements",antilist) - bodytypelist = csv_to_list("body_types",antilist) - cameralist = csv_to_list("cameras",antilist) - colorschemelist = csv_to_list("colorscheme",antilist) - conceptprefixlist = csv_to_list("concept_prefix",antilist) - culturelist = csv_to_list("cultures",antilist) - descriptorlist = csv_to_list("descriptors",antilist) - devmessagelist = csv_to_list("devmessages",antilist) - directionlist = csv_to_list("directions",antilist) - emojilist = csv_to_list("emojis",antilist) - eventlist = csv_to_list("events",antilist) - focuslist = csv_to_list("focus",antilist) - greatworklist = csv_to_list("greatworks",antilist) - haircolorlist = csv_to_list("haircolors",antilist) - hairstylelist = csv_to_list("hairstyles",antilist) - humanactivitylist = csv_to_list("human_activities",antilist) - humanoidlist = csv_to_list("humanoids",antilist) - imagetypelist = csv_to_list("imagetypes",antilist) - joblist = csv_to_list("jobs",antilist) - lenslist = csv_to_list("lenses",antilist) - lightinglist = csv_to_list("lighting",antilist) - malefemalelist = csv_to_list(csvfilename="malefemale",antilist=antilist,skipheader=True,gender=gender) - manwomanlist = csv_to_list(csvfilename="manwoman",antilist=antilist,skipheader=True,gender=gender) - moodlist = csv_to_list("moods",antilist) - othertypelist = csv_to_list("othertypes",antilist) - poselist = csv_to_list("poses",antilist) - qualitylist = csv_to_list("quality",antilist) - shotsizelist = csv_to_list("shotsizes",antilist) - timeperiodlist = csv_to_list("timeperiods",antilist) - vomitlist = csv_to_list("vomit",antilist) + colorlist = csv_to_list("colors", antilist) + animallist = csv_to_list("animals", antilist) + materiallist = csv_to_list("materials", antilist) + objectlist = csv_to_list("objects", antilist) + fictionallist = csv_to_list(csvfilename="fictional characters", antilist=antilist, skipheader=True, gender=gender) + nonfictionallist = csv_to_list( + csvfilename="nonfictional characters", + antilist=antilist, + skipheader=True, + gender=gender + ) + conceptsuffixlist = csv_to_list("concept_suffix", antilist) + buildinglist = csv_to_list("buildings", antilist) + vehiclelist = csv_to_list("vehicles", antilist) + outfitlist = csv_to_list("outfits", antilist) + locationlist = csv_to_list("locations", antilist) + accessorielist = csv_to_list("accessories", antilist) + artmovementlist = csv_to_list("artmovements", antilist) + bodytypelist = csv_to_list("body_types", antilist) + cameralist = csv_to_list("cameras", antilist) + colorschemelist = csv_to_list("colorscheme", antilist) + conceptprefixlist = csv_to_list("concept_prefix", antilist) + culturelist = csv_to_list("cultures", antilist) + descriptorlist = csv_to_list("descriptors", antilist) + devmessagelist = csv_to_list("devmessages", antilist) + directionlist = csv_to_list("directions", antilist) + emojilist = csv_to_list("emojis", antilist) + eventlist = csv_to_list("events", antilist) + focuslist = csv_to_list("focus", antilist) + greatworklist = csv_to_list("greatworks", antilist) + haircolorlist = csv_to_list("haircolors", antilist) + hairstylelist = csv_to_list("hairstyles", antilist) + humanactivitylist = csv_to_list("human_activities", antilist) + humanoidlist = csv_to_list("humanoids", antilist) + imagetypelist = csv_to_list("imagetypes", antilist) + joblist = csv_to_list("jobs", antilist) + lenslist = csv_to_list("lenses", antilist) + lightinglist = csv_to_list("lighting", antilist) + malefemalelist = csv_to_list(csvfilename="malefemale", antilist=antilist, skipheader=True, gender=gender) + manwomanlist = csv_to_list(csvfilename="manwoman", antilist=antilist, skipheader=True, gender=gender) + moodlist = csv_to_list("moods", antilist) + othertypelist = csv_to_list("othertypes", antilist) + poselist = csv_to_list("poses", antilist) + qualitylist = csv_to_list("quality", antilist) + shotsizelist = csv_to_list("shotsizes", antilist) + timeperiodlist = csv_to_list("timeperiods", antilist) + vomitlist = csv_to_list("vomit", antilist) foodlist = csv_to_list("foods", antilist) - genderdescriptionlist = csv_to_list(csvfilename="genderdescription",antilist=antilist,skipheader=True,gender=gender) + genderdescriptionlist = csv_to_list( + csvfilename="genderdescription", + antilist=antilist, + skipheader=True, + gender=gender + ) minilocationlist = csv_to_list("minilocations", antilist) minioutfitlist = csv_to_list("minioutfits", antilist) seasonlist = csv_to_list("seasons", antilist) @@ -85,72 +111,71 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all poemlinelist = csv_to_list("poemlines", antilist) songlinelist = csv_to_list("songlines", antilist) musicgenrelist = csv_to_list("musicgenres", antilist) - manwomanrelationlist = csv_to_list(csvfilename="manwomanrelations",antilist=antilist,skipheader=True,gender=gender) + manwomanrelationlist = csv_to_list( + csvfilename="manwomanrelations", + antilist=antilist, + skipheader=True, + gender=gender + ) waterlocationlist = csv_to_list("waterlocations", antilist) containerlist = csv_to_list("containers", antilist) - firstnamelist = csv_to_list(csvfilename="firstnames",antilist=antilist,skipheader=True,gender=gender) + firstnamelist = csv_to_list(csvfilename="firstnames", antilist=antilist, skipheader=True, gender=gender) floralist = csv_to_list("flora", antilist) printlist = csv_to_list("prints", antilist) patternlist = csv_to_list("patterns", antilist) chairlist = csv_to_list("chairs", antilist) - humanlist = fictionallist + nonfictionallist + humanoidlist objecttotallist = objectlist + buildinglist + vehiclelist + foodlist + spacelist + floralist + containerlist - outfitprinttotallist = objecttotallist + locationlist + colorlist + musicgenrelist + seasonlist + animallist + patternlist + outfitprinttotallist = \ + objecttotallist + locationlist + colorlist + musicgenrelist + seasonlist + animallist + patternlist # build artists list artistlist = [] # create artist list to use in the code, maybe based on category or personal lists - if(artists != "all" and artists != "none" and artists.startswith("personal_artists") == False and artists.startswith("personal artists") == False): - artistlist = artist_category_csv_to_list("artists_and_category",artists) - elif(artists.startswith("personal_artists") == True or artists.startswith("personal artists") == True): - artists = artists.replace(" ","_",-1) # add underscores back in - artistlist = csv_to_list(artists,antilist,"./userfiles/") - elif(artists != "none"): - artistlist = csv_to_list("artists",antilist) + if artists != "all" and artists != "none" and artists.startswith("personal_artists") is False \ + and artists.startswith("personal artists") is False: + artistlist = artist_category_csv_to_list("artists_and_category", artists) + elif artists.startswith("personal_artists") is True or artists.startswith("personal artists") is True: + artists = artists.replace(" ", "_", -1) # add underscores back in + artistlist = csv_to_list(artists, antilist, "./userfiles/") + elif artists != "none": + artistlist = csv_to_list("artists", antilist) # create special artists lists, used in templates - fantasyartistlist = artist_category_csv_to_list("artists_and_category","fantasy") - popularartistlist = artist_category_csv_to_list("artists_and_category","popular") - romanticismartistlist = artist_category_csv_to_list("artists_and_category","romanticism") - photographyartistlist = artist_category_csv_to_list("artists_and_category","photography") - + fantasyartistlist = artist_category_csv_to_list("artists_and_category", "fantasy") + popularartistlist = artist_category_csv_to_list("artists_and_category", "popular") + romanticismartistlist = artist_category_csv_to_list("artists_and_category", "romanticism") + photographyartistlist = artist_category_csv_to_list("artists_and_category", "photography") # add any other custom lists - stylestiloralist = csv_to_list("styles_ti_lora",antilist,"./userfiles/") - generatestyle = bool(stylestiloralist) # True of not empty - - custominputprefixlist = csv_to_list("custom_input_prefix",antilist,"./userfiles/") - generatecustominputprefix = bool(custominputprefixlist) # True of not empty - - custominputmidlist = csv_to_list("custom_input_mid",antilist,"./userfiles/") - generatecustominputmid = bool(custominputmidlist) # True of not empty - - custominputsuffixlist = csv_to_list("custom_input_suffix",antilist,"./userfiles/") - generatecustominputsuffix = bool(custominputsuffixlist) # True of not empty - - customsubjectslist = csv_to_list("custom_subjects",antilist,"./userfiles/") + stylestiloralist = csv_to_list("styles_ti_lora", antilist, "./userfiles/") + generatestyle = bool(stylestiloralist) # True of not empty + custominputprefixlist = csv_to_list("custom_input_prefix", antilist, "./userfiles/") + generatecustominputprefix = bool(custominputprefixlist) # True of not empty + custominputmidlist = csv_to_list("custom_input_mid", antilist, "./userfiles/") + generatecustominputmid = bool(custominputmidlist) # True of not empty + custominputsuffixlist = csv_to_list("custom_input_suffix", antilist, "./userfiles/") + generatecustominputsuffix = bool(custominputsuffixlist) # True of not empty + customsubjectslist = csv_to_list("custom_subjects", antilist, "./userfiles/") # special lists - backgroundtypelist = csv_to_list("backgroundtypes", antilist,"./csvfiles/special_lists/") - insideshotlist = csv_to_list("insideshots", antilist,"./csvfiles/special_lists/") - photoadditionlist = csv_to_list("photoadditions", antilist,"./csvfiles/special_lists/") - buildhairlist = csv_to_list("buildhair", antilist,"./csvfiles/special_lists/") - buildoutfitlist = csv_to_list("buildoutfit", antilist,"./csvfiles/special_lists/") - objectadditionslist = csv_to_list("objectadditions", antilist,"./csvfiles/special_lists/") - humanadditionlist = csv_to_list("humanadditions", antilist,"./csvfiles/special_lists/") - animaladditionlist = csv_to_list("animaladditions", antilist,"./csvfiles/special_lists/") - buildaccessorielist = csv_to_list("buildaccessorie", antilist,"./csvfiles/special_lists/") - minilocationadditionslist = csv_to_list("minilocationadditions", antilist,"./csvfiles/special_lists/") - overalladditionlist = csv_to_list("overalladditions", antilist,"./csvfiles/special_lists/") - imagetypemodelist = csv_to_list("imagetypemodes", antilist,"./csvfiles/special_lists/") - miniactivitylist = csv_to_list("miniactivity", antilist,"./csvfiles/special_lists/") - animalsuffixadditionlist = csv_to_list("animalsuffixadditions", antilist,"./csvfiles/special_lists/") - - styleslist = csv_to_list("styles", antilist,"./csvfiles/templates/") - - - + backgroundtypelist = csv_to_list("backgroundtypes", antilist, "./csvfiles/special_lists/") + insideshotlist = csv_to_list("insideshots", antilist, "./csvfiles/special_lists/") + photoadditionlist = csv_to_list("photoadditions", antilist, "./csvfiles/special_lists/") + buildhairlist = csv_to_list("buildhair", antilist, "./csvfiles/special_lists/") + buildoutfitlist = csv_to_list("buildoutfit", antilist, "./csvfiles/special_lists/") + objectadditionslist = csv_to_list("objectadditions", antilist, "./csvfiles/special_lists/") + humanadditionlist = csv_to_list("humanadditions", antilist, "./csvfiles/special_lists/") + animaladditionlist = csv_to_list("animaladditions", antilist, "./csvfiles/special_lists/") + buildaccessorielist = csv_to_list("buildaccessorie", antilist, "./csvfiles/special_lists/") + minilocationadditionslist = csv_to_list("minilocationadditions", antilist, "./csvfiles/special_lists/") + overalladditionlist = csv_to_list("overalladditions", antilist, "./csvfiles/special_lists/") + imagetypemodelist = csv_to_list("imagetypemodes", antilist, "./csvfiles/special_lists/") + miniactivitylist = csv_to_list("miniactivity", antilist, "./csvfiles/special_lists/") + animalsuffixadditionlist = csv_to_list("animalsuffixadditions", antilist, "./csvfiles/special_lists/") + + styleslist = csv_to_list("styles", antilist, "./csvfiles/templates/") + # subjects mainchooserlist = [] objectwildcardlist = [] @@ -202,7 +227,6 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all subjectculturechance = 'normal' subjectconceptsuffixchance = 'unique' - subjectlandscapeinsideshotchance = 'unique' subjectlandscapeaddonlocationchance = 'normal' subjectlandscapeaddonlocationdescriptorchance = 'rare' subjectlandscapeaddonlocationculturechance = 'rare' @@ -240,7 +264,7 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all lenschance = 'normal' colorschemechance = 'normal' vomit1chance = 'uncommon' - vomit2chance= 'uncommon' + vomit2chance = 'uncommon' greatworkchance = 'novel' poemlinechance = 'novel' songlinechance = 'novel' @@ -299,21 +323,20 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all generatepoemline = False if item[0] == 'songline' and item[1] != 'on': generatesongline = False - # main list stuff if item[0] == 'custominputprefixrepeats': custominputprefixrepeats = int(item[1]) if item[0] == 'custominputprefixchance': custominputprefixchance = item[1] - if(custominputprefixchance == 'never'): + if custominputprefixchance == 'never': generatecustominputprefix = False if item[0] == 'imagetypechance': imagetypechance = item[1] - if(imagetypechance == 'never'): + if imagetypechance == 'never': generateimagetype = False if item[0] == 'imagetypequalitychance': imagetypequalitychance = item[1] - if(imagetypequalitychance == 'never'): + if imagetypequalitychance == 'never': generateimagetypequality = False if item[0] == 'minilocationadditionchance': minilocationadditionchance = item[1] @@ -323,10 +346,8 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all minivomitprefix1chance = item[1] if item[0] == 'minivomitprefix2chance': minivomitprefix2chance = item[1] - if item[0] == 'shotsizechance': shotsizechance = item[1] - if item[0] == 'subjectdescriptor1chance': subjectdescriptor1chance = item[1] if item[0] == 'subjectdescriptor2chance': @@ -337,16 +358,12 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all subjectculturechance = item[1] if item[0] == 'subjectconceptsuffixchance': subjectconceptsuffixchance = item[1] - - if item[0] == 'subjectlandscapeinsideshotchance': - subjectlandscapeinsideshotchance = item[1] if item[0] == 'subjectlandscapeaddonlocationchance': subjectlandscapeaddonlocationchance = item[1] if item[0] == 'subjectlandscapeaddonlocationdescriptorchance': subjectlandscapeaddonlocationdescriptorchance = item[1] if item[0] == 'subjectlandscapeaddonlocationculturechance': subjectlandscapeaddonlocationculturechance = item[1] - if item[0] == 'objectadditionsrepeats': objectadditionsrepeats = int(item[1]) if item[0] == 'objectadditionschance': @@ -355,21 +372,18 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all humanadditionchance = item[1] if item[0] == 'overalladditionchance': overalladditionchance = item[1] - if item[0] == 'emojichance': emojichance = item[1] - if(hardturnoffemojis==True): - emojichance='never' + if hardturnoffemojis is True: + emojichance = 'never' if item[0] == 'joboractivitychance': joboractivitychance = item[1] - if item[0] == 'custominputmidrepeats': custominputmidrepeats = int(item[1]) if item[0] == 'custominputmidchance': custominputmidchance = item[1] if item[0] == 'minivomitmidchance': minivomitmidchance = item[1] - if item[0] == 'outfitchance': outfitchance = item[1] if item[0] == 'posechance': @@ -382,12 +396,10 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all humanoidinsideshotchance = item[1] if item[0] == 'humanoidbackgroundchance': humanoidbackgroundchance = item[1] - if item[0] == 'landscapeminilocationchance': landscapeminilocationchance = item[1] if item[0] == 'generalminilocationchance': generalminilocationchance = item[1] - if item[0] == 'timperiodchance': timperiodchance = item[1] if item[0] == 'focuschance': @@ -422,12 +434,10 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all quality1chance = item[1] if item[0] == 'quality2chance': quality2chance = item[1] - if item[0] == 'customstyle1chance': customstyle1chance = item[1] if item[0] == 'customstyle2chance': customstyle2chance = item[1] - if item[0] == 'custominputsuffixrepeats': custominputsuffixrepeats = int(item[1]) if item[0] == 'custominputsuffixchance': @@ -436,46 +446,45 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all if item[0] == 'artistsatbackchance': artistsatbackchance = item[1] - generatevehicle = bool(vehiclelist) and generatevehicle generateobject = bool(objectlist) and generateobject generatefood = bool(foodlist) and generatefood generatebuilding = bool(buildinglist) and generatebuilding generatespace = bool(spacelist) and generatespace generateflora = bool(floralist) and generateflora - generateobject = generatevehicle or generateobject or generatefood or generatebuilding or generatespace or generateflora - + generateobject = \ + generatevehicle or generateobject or generatefood or generatebuilding or generatespace or generateflora - if(generatevehicle): + if generatevehicle: objectwildcardlist.append("-vehicle-") hybridlist.append("-vehicle-") addontolocationlist.append("-vehicle-") - - if(generateobject): + + if generateobject: objectwildcardlist.append("-object-") hybridlist.append("-object-") - if(generatefood): + if generatefood: objectwildcardlist.append("-food-") hybridlist.append("-food-") - - if(generatespace): + + if generatespace: objectwildcardlist.append("-space-") hybridlist.append("-space-") addontolocationlist.append("-space-") - if(generatebuilding): + if generatebuilding: objectwildcardlist.append("-building-") hybridlist.append("-building-") addontolocationlist.append("-building-") addontolocationinsidelist.append("-building-") - - if(generateflora): + + if generateflora: objectwildcardlist.append("-flora-") hybridlist.append("-flora-") addontolocationlist.append("-flora-") - - if(generateobject): + + if generateobject: mainchooserlist.append("object") generatefictionalcharacter = bool(fictionallist) and generatefictionalcharacter @@ -485,82 +494,78 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all generatemanwomanrelation = bool(manwomanrelationlist) and generatemanwomanrelation generatejob = bool(joblist) and generatejob generatefirstnames = bool(firstnamelist) and generatefirstnames - generatehumanoid = generatefictionalcharacter or generatenonfictionalcharacter or generatehumanoids or generatemanwoman or generatejob or generatemanwomanrelation or generatefirstnames - + generatehumanoid = generatefictionalcharacter or generatenonfictionalcharacter or generatehumanoids or \ + generatemanwoman or generatejob or generatemanwomanrelation or generatefirstnames - if(generatefictionalcharacter): + if generatefictionalcharacter: humanoidsubjectchooserlist.append("fictional") hybridlist.append("-fictional-") hybridhumanlist.append("-fictional-") - if(generatefictionalcharacter): + if generatefictionalcharacter: humanoidsubjectchooserlist.append("non fictional") hybridlist.append("-nonfictional-") hybridhumanlist.append("-nonfictional-") - - if(generatehumanoids): + + if generatehumanoids: humanoidsubjectchooserlist.append("humanoid") hybridlist.append("-humanoid-") hybridhumanlist.append("-humanoid-") - - if(generatemanwoman): + + if generatemanwoman: humanoidsubjectchooserlist.append("human") - if(generatemanwomanrelation): + if generatemanwomanrelation: humanoidsubjectchooserlist.append("manwomanrelation") - if(generatejob): + if generatejob: humanoidsubjectchooserlist.append("job") - - if(generatehumanoid): + + if generatehumanoid: mainchooserlist.append("humanoid") - if(generatefirstnames): + if generatefirstnames: humanoidsubjectchooserlist.append("firstname") - - + generateanimal = bool(animallist) and generateanimal - if(generateanimal): + if generateanimal: mainchooserlist.append("animal") hybridlist.append("-animal-") generatelandscape = bool(locationlist) and generatelandscape - if(generatelandscape): + if generatelandscape: mainchooserlist.append("landscape") addontolocationlist.append("-location-") addontolocationinsidelist.append("-location-") - + generateevent = bool(eventlist) and generateevent generateconcepts = bool(conceptprefixlist) and bool(conceptsuffixlist) and generateconcepts - generatepoemline = bool(poemlinelist) and generatepoemline + generatepoemline = bool(poemlinelist) and generatepoemline generatesongline = bool(songlinelist) and generatesongline - - generateconcept = generateevent or generateconcepts or generatepoemline or generatesongline - if(generateevent): + if generateevent: eventsubjectchooserlist.append("event") - - if(generateconcepts): + + if generateconcepts: eventsubjectchooserlist.append("concept") - if(generatepoemline): + if generatepoemline: eventsubjectchooserlist.append("poemline") - - if(generatesongline): + + if generatesongline: eventsubjectchooserlist.append("songline") - if(generateconcept): + if generateconcept: mainchooserlist.append("concept") # determine wether we have a special mode or not - if(random.randint(1,int(imagemodechance)) == 1 and imagetype == "all" and giventypeofimage == ""): + if random.randint(1, int(imagemodechance)) == 1 and imagetype == "all" and giventypeofimage == "": imagetype = random.choice(imagetypemodelist) # override imagetype with a random "mode" value - specialmode = False templatemode = False artblastermode = False @@ -569,57 +574,54 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all colorcannonmode = False photofantasymode = False massivemadnessmode = False - onlysubjectmode = False stylesmode = False # determine wether we should go for a template or not. Not hooked up to insanitylevel - if(imagetype == "only templates mode"): + if imagetype == "only templates mode": specialmode = True templatemode = True print("Running with a randomized template instead of a randomized prompt") - if(imagetype == "art blaster mode"): + if imagetype == "art blaster mode": specialmode = True artblastermode = True print("Running in art blaster mode") - if(imagetype == "unique art mode"): + if imagetype == "unique art mode": specialmode = True uniqueartmode = True print("Running in unique art mode") - if(imagetype == "quality vomit mode"): + if imagetype == "quality vomit mode": specialmode = True qualityvomitmode = True print("Running in quality vomit mode") - if(imagetype == "color cannon mode"): + if imagetype == "color cannon mode": specialmode = True colorcannonmode = True print("Running in color cannon mode") - if(imagetype == "photo fantasy mode"): + if imagetype == "photo fantasy mode": specialmode = True photofantasymode = True print("Running in photo fantasy mode") - if(imagetype == "massive madness mode"): + if imagetype == "massive madness mode": specialmode = True massivemadnessmode = True print("Running in massive madness mode") print("Are you ready for this?") - if(imagetype == "subject only mode"): + if imagetype == "subject only mode": specialmode = True - onlysubjectmode = True print("Running in only subject mode") - if(imagetype == "fixed styles mode"): + if imagetype == "fixed styles mode": specialmode = True stylesmode = True print("Running with a randomized style instead of a randomized prompt") - # main stuff generatetype = not specialmode generatesubject = not templatemode @@ -659,23 +661,18 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all generategreatwork = bool(greatworklist) and not specialmode generatepoemline = bool(poemlinelist) and not specialmode generatesongline = bool(songlinelist) and not specialmode - generateminilocationaddition = bool(minilocationadditionslist) and not specialmode generateminivomit = bool(minivomitlist) and not specialmode generateimagetypequality = bool(imagetypequalitylist) and not specialmode and generateimagetypequality generateoveralladdition = bool(overalladditionlist) and not specialmode generateimagetype = bool(imagetypelist) and not specialmode and generateimagetype - # Smart subject logic - if(givensubject != "" and smartsubject == True): - + if givensubject != "" and smartsubject is True: # Remove any list that has a matching word in the list # Remove any list/logic with keywords, such as: # wearing, bodytype, pose, location, hair, background - # first get all the words - # Split the string by commas and spaces words = re.split(r'[,\s]+', givensubject) # Remove leading/trailing whitespaces from each word @@ -697,137 +694,126 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all # Filter out empty words and duplicates givensubjectlistwords = list(set(filter(None, words))) - givensubjectlist = givensubjectlistsinglewords + givensubjectlistwords - # Check only for the lists that make sense? - # outfit foundinlist = any(word.lower() in [item.lower() for item in outfitlist] for word in givensubjectlist) - keywordslist = ["wearing","outfit", "dressed"] + keywordslist = ["wearing", "outfit", "dressed"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generateoutfit = False - + # bodytype foundinlist = any(word.lower() in [item.lower() for item in bodytypelist] for word in givensubjectlist) - keywordslist = ["bodytype","body type"] + keywordslist = ["bodytype", "body type"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generatebodytype = False # hair foundinlist = any(word.lower() in [item.lower() for item in hairstylelist] for word in givensubjectlist) keywordslist = ["hair"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generatehairstyle = False - + # descriptorlist foundinlist = any(word.lower() in [item.lower() for item in descriptorlist] for word in givensubjectlist) foundinlist2 = any(word.lower() in [item.lower() for item in culturelist] for word in givensubjectlist) - if(foundinlist == True or foundinlist2 == True): + if foundinlist is True or foundinlist2 is True: generatedescriptors = False # background foundinlist = any(word.lower() in [item.lower() for item in locationlist] for word in givensubjectlist) foundinlist2 = any(word.lower() in [item.lower() for item in buildinglist] for word in givensubjectlist) - keywordslist = ["location","background", "inside"] + keywordslist = ["location", "background", "inside"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or foundinlist2 == True or keywordsinstring == True): + if foundinlist is True or foundinlist2 is True or keywordsinstring is True: generatebackground = False generateinsideshot = False # accessorielist foundinlist = any(word.lower() in [item.lower() for item in accessorielist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generateaccessorie = False # lenslist foundinlist = any(word.lower() in [item.lower() for item in lenslist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatelens = False # lightinglist foundinlist = any(word.lower() in [item.lower() for item in lightinglist] for word in givensubjectlist) keywordslist = ["lighting"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generatelighting = False # mood foundinlist = any(word.lower() in [item.lower() for item in moodlist] for word in givensubjectlist) keywordslist = ["mood"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generatemood = False - # poselist foundinlist = any(word.lower() in [item.lower() for item in poselist] for word in givensubjectlist) keywordslist = ["pose", "posing"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generatepose = False # qualitylist foundinlist = any(word.lower() in [item.lower() for item in qualitylist] for word in givensubjectlist) keywordslist = ["quality"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generatequality = False # shotsize foundinlist = any(word.lower() in [item.lower() for item in shotsizelist] for word in givensubjectlist) keywordslist = ["shot"] keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - if(foundinlist == True or keywordsinstring == True): + if foundinlist is True or keywordsinstring is True: generateshot = False # timeperiodlist foundinlist = any(word.lower() in [item.lower() for item in timeperiodlist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatetimeperiod = False # vomit foundinlist = any(word.lower() in [item.lower() for item in vomitlist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatevomit = False # directionlist foundinlist = any(word.lower() in [item.lower() for item in directionlist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatedirection = False # focus foundinlist = any(word.lower() in [item.lower() for item in focuslist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatefocus = False # artmovementlist foundinlist = any(word.lower() in [item.lower() for item in artmovementlist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generateartmovement = False - + # camera foundinlist = any(word.lower() in [item.lower() for item in cameralist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatecamera = False # colorschemelist foundinlist = any(word.lower() in [item.lower() for item in colorschemelist] for word in givensubjectlist) - if(foundinlist == True): + if foundinlist is True: generatecolorscheme = False - - - completeprompt = "" - - - - promptstocompound = int(promptcompounderlevel) compoundcounter = 0 @@ -841,18 +827,12 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all hybridorswap = "" artistmode = "normal" insideshot = 0 - - completeprompt += prefixprompt + completeprompt += prefixprompt completeprompt += ", " - if(templatemode==True): - templatelist = csv_to_list("templates", antilist,"./csvfiles/templates/",1,";",True) - - - # templateenvironments = [templateenvironment[1] for templateenvironment in templatelist] - # templateenvironmentsources = [templateenvironmentsource[2] for templateenvironmentsource in templatelist] - # templatesubjecttypes = [templatesubjecttype[3] for templatesubjecttype in templatelist] + if templatemode is True: + templatelist = csv_to_list("templates", antilist, "./csvfiles/templates/", 1, ";", True) targettemplateenvironment = "all" templateenvironmentsources = "all" @@ -860,10 +840,25 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all # takes the prompt based on filters: # targettemplateenvironment: either civitai model or website # templateenvironmentsources: either - templateprompts = [templateprompt[0] for templateprompt in templatelist if( (templateprompt[1] == targettemplateenvironment or targettemplateenvironment =="all") and (templateprompt[2] == templateenvironmentsources or templateenvironmentsources == "all") and (templateprompt[3] == forcesubject or forcesubject == "all") ) ] - templatepromptcreator = [templateprompt[1] for templateprompt in templatelist if( (templateprompt[1] == targettemplateenvironment or targettemplateenvironment =="all") and (templateprompt[2] == templateenvironmentsources or templateenvironmentsources == "all") and (templateprompt[3] == forcesubject or forcesubject == "all") ) ] - templatesubjects= [templateprompt[4] for templateprompt in templatelist if( (templateprompt[1] == targettemplateenvironment or targettemplateenvironment =="all") and (templateprompt[2] == templateenvironmentsources or templateenvironmentsources == "all") and (templateprompt[3] == forcesubject or forcesubject == "all") )] - + templateprompts = [ + templateprompt[0] for templateprompt in templatelist if + (templateprompt[1] == targettemplateenvironment or targettemplateenvironment == "all") and + (templateprompt[2] == templateenvironmentsources or templateenvironmentsources == "all") and + (templateprompt[3] == forcesubject or forcesubject == "all") + ] + templatepromptcreator = [ + templateprompt[1] for templateprompt in templatelist if + (templateprompt[1] == targettemplateenvironment or targettemplateenvironment == "all") and + (templateprompt[2] == templateenvironmentsources or templateenvironmentsources == "all") and + (templateprompt[3] == forcesubject or forcesubject == "all") + ] + templatesubjects = [ + templateprompt[4] for templateprompt in templatelist if + (templateprompt[1] == targettemplateenvironment or targettemplateenvironment == "all") and + (templateprompt[2] == templateenvironmentsources or templateenvironmentsources == "all") and + (templateprompt[3] == forcesubject or forcesubject == "all") + ] + # choose the template chosentemplate = random.choice(templateprompts) templateindex = templateprompts.index(chosentemplate) @@ -871,231 +866,214 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all print("Processing a prompt that was inspired from: " + templatepromptcreator[templateindex]) # if there is a subject override, then replace the subject with that - if(givensubject==""): - completeprompt += chosentemplate.replace("-subject-",templatesubjects[templateindex] ) + if givensubject == "": + completeprompt += chosentemplate.replace("-subject-", templatesubjects[templateindex]) else: - completeprompt += chosentemplate.replace("-subject-",givensubject ) - + completeprompt += chosentemplate.replace("-subject-", givensubject) # custom prefix list for i in range(custominputprefixrepeats): - if(chance_roll(insanitylevel, custominputprefixchance) and generatecustominputprefix == True): - completeprompt += random.choice(custominputprefixlist) + ", " - - + if chance_roll(insanitylevel, custominputprefixchance) and generatecustominputprefix is True: + completeprompt += f'{random.choice(custominputprefixlist)}, ' - if(insanitylevel==0): - insanitylevel = random.randint(1, 10) # 10 = add everything, 1 is add almost nothing - insanitylevel3 = int((insanitylevel/3) + 1.20) - - # print("Setting insanity level to " + str(insanitylevel)) + if insanitylevel == 0: + insanitylevel = random.randint(1, 10) # 10 = add everything, 1 is add almost nothing + insanitylevel3 = int((insanitylevel / 3) + 1.20) # main chooser: 0 object, 1 animal, 2 humanoid, 3 landscape, 4 event/concept - #mainchooserlist = ["object","animal","humanoid", "landscape", "concept"] mainchooser = random.choice(mainchooserlist) - - if(forcesubject != "" and forcesubject != "all"): - mainchooser = forcesubject - # 0 object, 1 animal, 2 animal as human, 3 ManWoman, 4 Job, 5 fictional, 6 non fictional, 7 humanoid, 8 landscape, 9 event - if(mainchooser == "object"): + + if forcesubject != "" and forcesubject != "all": + mainchooser = forcesubject + # 0 object, 1 animal, 2 animal as human, 3 ManWoman, 4 Job + # 5 fictional, 6 non fictional, 7 humanoid, 8 landscape, 9 event + if mainchooser == "object": subjectchooser = "object" - if(mainchooser == "animal"): + if mainchooser == "animal": # sometimes interpret the animal as a human - if(random.randint(0,5) < 5): + if random.randint(0, 5) < 5: subjectchooser = "animal" else: subjectchooser = "animal as human" - if(mainchooser == "humanoid"): - #humanoidsubjectchooserlist = ["human", "job", "fictional", "non fictional", "humanoid", "manwomanrelation", "firstname"] + if mainchooser == "humanoid": subjectchooser = random.choice(humanoidsubjectchooserlist) - if(subtypehumanoid != "all"): - if(subtypehumanoid == "generic humans"): + if subtypehumanoid != "all": + if subtypehumanoid == "generic humans": subjectchooser = "human" - if(subtypehumanoid == "generic human relations"): + if subtypehumanoid == "generic human relations": subjectchooser = "manwomanrelation" - if(subtypehumanoid == "celebrities e.a."): + if subtypehumanoid == "celebrities e.a.": subjectchooser = "non fictional" - if(subtypehumanoid == "fictional characters"): + if subtypehumanoid == "fictional characters": subjectchooser = "fictional" - if(subtypehumanoid == "humanoids"): + if subtypehumanoid == "humanoids": subjectchooser = "humanoid" - if(subtypehumanoid == "based on job or title"): + if subtypehumanoid == "based on job or title": subjectchooser = "job" - if(subtypehumanoid == "based on first name"): + if subtypehumanoid == "based on first name": subjectchooser = "firstname" - if(mainchooser == "landscape"): + if mainchooser == "landscape": subjectchooser = "landscape" - if(mainchooser == "concept"): - #eventsubjectchooserlist = ["event", "concept", "poemline", "songline"] + if mainchooser == "concept": subjectchooser = random.choice(eventsubjectchooserlist) - if(subtypeconcept != "all"): - if(subtypeconcept == "event"): + if subtypeconcept != "all": + if subtypeconcept == "event": subjectchooser = "event" - if(subtypeconcept == "the X of Y concepts"): + if subtypeconcept == "the X of Y concepts": subjectchooser = "concept" - if(subtypeconcept == "lines from poems"): + if subtypeconcept == "lines from poems": subjectchooser = "poemline" - if(subtypeconcept == "lines from songs"): + if subtypeconcept == "lines from songs": subjectchooser = "songline" - - - # special modes - + # special modes # start art blaster here - if(artblastermode==True): + if artblastermode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(artistlist)): + if uncommon_dist(insanitylevel) and bool(artistlist): completeprompt += "-artist-, " - if(uncommon_dist(insanitylevel) and bool(artmovementlist)): + if uncommon_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(unique_dist(insanitylevel) and bool(vomitlist)): + if unique_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(unique_dist(insanitylevel) and bool(imagetypelist)): + if unique_dist(insanitylevel) and bool(imagetypelist): completeprompt += "-imagetype-, " - if(unique_dist(insanitylevel) and bool(colorschemelist)): + if unique_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - step = step + 1 + step = step + 1 # start unique art here - if(uniqueartmode==True): + if uniqueartmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(othertypelist)): + if uncommon_dist(insanitylevel) and bool(othertypelist): completeprompt += "-othertype-, " - if(uncommon_dist(insanitylevel) and bool(artmovementlist)): + if uncommon_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(uncommon_dist(insanitylevel) and bool(colorschemelist)): + if uncommon_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - if(rare_dist(insanitylevel) and bool(vomitlist)): + if rare_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(rare_dist(insanitylevel) and bool(lightinglist)): + if rare_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - if(unique_dist(insanitylevel) and bool(imagetypelist)): + if unique_dist(insanitylevel) and bool(imagetypelist): completeprompt += "-imagetype-, " - if(unique_dist(insanitylevel) and bool(qualitylist)): + if unique_dist(insanitylevel) and bool(qualitylist): completeprompt += "-quality-, " - - step = step + 1 + step = step + 1 # start quality vomit here - if(qualityvomitmode==True): + if qualityvomitmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(vomitlist)): + if uncommon_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(uncommon_dist(insanitylevel) and bool(qualitylist)): + if uncommon_dist(insanitylevel) and bool(qualitylist): completeprompt += "-quality-, " - if(unique_dist(insanitylevel) and bool(minivomitlist)): + if unique_dist(insanitylevel) and bool(minivomitlist): completeprompt += "-minivomit-, " - if(unique_dist(insanitylevel) and bool(artmovementlist)): + if unique_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(unique_dist(insanitylevel) and bool(colorschemelist)): + if unique_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " step = step + 1 # start mood color here - if(colorcannonmode == True): + if colorcannonmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(moodlist)): + if uncommon_dist(insanitylevel) and bool(moodlist): completeprompt += "-mood-, " - if(uncommon_dist(insanitylevel) and bool(colorschemelist)): + if uncommon_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - if(rare_dist(insanitylevel) and bool(vomitlist)): + if rare_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(unique_dist(insanitylevel) and bool(artmovementlist)): + if unique_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(unique_dist(insanitylevel) and bool(lightinglist)): + if unique_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - step = step + 1 + step = step + 1 # start photo fantasy here - if(photofantasymode == True): + if photofantasymode is True: step = 0 end = random.randint(1, insanitylevel) + 1 - if(common_dist(insanitylevel)): - if(uncommon_dist(insanitylevel)): + if common_dist(insanitylevel): + if uncommon_dist(insanitylevel): completeprompt += "-imagetypequality- " completeprompt += " photograph, " + while step < end: - if(uncommon_dist(insanitylevel) and bool(lightinglist)): + if uncommon_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - if(uncommon_dist(insanitylevel) and bool(cameralist)): + if uncommon_dist(insanitylevel) and bool(cameralist): completeprompt += "-camera-, " - if(rare_dist(insanitylevel) and bool(lenslist)): + if rare_dist(insanitylevel) and bool(lenslist): completeprompt += "-lens-, " - if(unique_dist(insanitylevel) and bool(moodlist)): + if unique_dist(insanitylevel) and bool(moodlist): completeprompt += "-mood-, " - if(unique_dist(insanitylevel) and bool(colorschemelist)): + if unique_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - step = step + 1 + step = step + 1 # start massive madness here - if(massivemadnessmode == True): + if massivemadnessmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(rare_dist(insanitylevel) and bool(artistlist)): + if rare_dist(insanitylevel) and bool(artistlist): completeprompt += "-artist-, " - if(rare_dist(insanitylevel) and bool(descriptorlist)): + if rare_dist(insanitylevel) and bool(descriptorlist): completeprompt += "-descriptor-, " - if(rare_dist(insanitylevel) and bool(moodlist)): + if rare_dist(insanitylevel) and bool(moodlist): completeprompt += "-mood-, " - if(rare_dist(insanitylevel) and bool(colorschemelist)): + if rare_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - if(rare_dist(insanitylevel) and bool(vomitlist)): + if rare_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(rare_dist(insanitylevel) and bool(artmovementlist)): + if rare_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(rare_dist(insanitylevel) and bool(lightinglist)): + if rare_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - if(rare_dist(insanitylevel) and bool(minilocationadditionslist)): + if rare_dist(insanitylevel) and bool(minilocationadditionslist): completeprompt += "-minilocationaddition-, " - if(rare_dist(insanitylevel) and bool(materiallist)): + if rare_dist(insanitylevel) and bool(materiallist): completeprompt += "-material-, " - if(rare_dist(insanitylevel) and bool(conceptsuffixlist)): + if rare_dist(insanitylevel) and bool(conceptsuffixlist): completeprompt += "-conceptsuffix-, " - if(rare_dist(insanitylevel) and bool(qualitylist)): + if rare_dist(insanitylevel) and bool(qualitylist): completeprompt += "-quality-, " - if(rare_dist(insanitylevel) and bool(cameralist)): + if rare_dist(insanitylevel) and bool(cameralist): completeprompt += "-camera-, " - if(rare_dist(insanitylevel) and bool(lenslist)): + if rare_dist(insanitylevel) and bool(lenslist): completeprompt += "-lens-, " - if(rare_dist(insanitylevel) and bool(imagetypelist)): + if rare_dist(insanitylevel) and bool(imagetypelist): completeprompt += "-imagetype-, " - step = step + 1 + step = step + 1 completeprompt += " (" - - # start styles mode here - if(stylesmode == True): + # start styles mode here + if stylesmode is True: chosenstyle = random.choice(styleslist) chosenstyleprefix = chosenstyle.split("-subject-")[0] - chosenstylesuffix= chosenstyle.split("-subject-")[1] + chosenstylesuffix = chosenstyle.split("-subject-")[1] completeprompt += chosenstyleprefix - - # start artist part - artistsplacement = "front" - if(chance_roll(insanitylevel, artistsatbackchance) and onlyartists == False): + if chance_roll(insanitylevel, artistsatbackchance) and onlyartists is False: artistsplacement = "back" - if(artists != "none" and artistsplacement == "front" and generateartist == True): + if artists != "none" and artistsplacement == "front" and generateartist is True: # take 1-3 artists, weighted to 1-2 step = random.randint(0, 1) end = random.randint(1, insanitylevel3) - - - # determine artist mode: # normal # hybrid | @@ -1103,937 +1081,1095 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all # adding at step x a:X # stopping at step x ::X # enhancing from step x - - - - - modeselector = random.randint(0,10) + modeselector = random.randint(0, 10) if modeselector < 5 and end - step >= 2: artistmodeslist = ["hybrid", "stopping", "adding", "switching", "enhancing"] artistmode = artistmodeslist[modeselector] - if(advancedprompting == False): + if advancedprompting is False: artistmode = "normal" - if (artistmode in ["hybrid","switching"] and end - step == 1): + if (artistmode in ["hybrid", "switching"] and end - step == 1): artistmode = "normal" - - if(onlyartists == True and artistmode == "enhancing"): + + if onlyartists is True and artistmode == "enhancing": artistmode = "normal" # if there are not enough artists in the list, then just go normal - if(len(artistlist) < 3): + if len(artistlist) < 3: artistmode = "normal" - if(onlyartists == True and step == end): + if onlyartists is True and step == end: step = step - 1 - - if artistmode in ["hybrid", "stopping", "adding","switching"]: + if artistmode in ["hybrid", "stopping", "adding", "switching"]: completeprompt += " [" - - while step < end: - if(normal_dist(insanitylevel)): + + while step < end: + if normal_dist(insanitylevel): isweighted = 1 - if isweighted == 1: completeprompt += " (" - #completeprompt = add_from_csv(completeprompt, "artists", 0, "art by ","") completeprompt += "-artist-" - if isweighted == 1: - completeprompt += ":" + str(1 + (random.randint(-3,3)/10)) + ")" - + completeprompt += f':{1 + (random.randint(-3, 3) / 10)})' if artistmode in ["hybrid"] and not end - step == 1: completeprompt += "|" if artistmode in ["switching"] and not end - step == 1: completeprompt += ":" - - if artistmode not in ["hybrid", "switching"]and not end - step == 1: + if artistmode not in ["hybrid", "switching"] and not end - step == 1: completeprompt += "," - + isweighted = 0 - step = step + 1 if artistmode in ["stopping"]: - completeprompt += "::" - completeprompt += str(random.randint(1,19)) - - if artistmode in ["switching","adding"]: - completeprompt += ":" + str(random.randint(1,18)) - if artistmode in ["hybrid", "stopping","adding", "switching"]: - completeprompt += "] " + completeprompt += f'::{random.randint(1, 19)}' + if artistmode in ["switching", "adding"]: + completeprompt += f':{random.randint(1, 18)}' + if artistmode in ["hybrid", "stopping", "adding", "switching"]: + completeprompt += "] " - if(onlyartists == True): - + if onlyartists is True: # replace artist wildcards completeprompt = replacewildcard(completeprompt, insanitylevel, "-artist-", artistlist, False, False) - + # clean it up completeprompt = cleanup(completeprompt, advancedprompting) - print("only generated these artists:" + completeprompt) + print(f'only generated these artists:{completeprompt}') return completeprompt - completeprompt += ", " - - if artistmode in ["enhancing"]: completeprompt += " [" - - # start image type - if(giventypeofimage=="" and generatetype == True): - if(imagetype != "all" and imagetype != "all - force multiple" and imagetype != "only other types"): - - completeprompt += " " + imagetype + ", " - elif(imagetype == "all - force multiple" or unique_dist(insanitylevel)): - amountofimagetypes = random.randint(2,3) - elif(imagetype == "only other types"): + # start image type + if giventypeofimage == "" and generatetype is True: + if imagetype != "all" and imagetype != "all - force multiple" and imagetype != "only other types": + completeprompt += f' {imagetype}, ' + elif imagetype == "all - force multiple" or unique_dist(insanitylevel): + amountofimagetypes = random.randint(2, 3) + elif imagetype == "only other types": othertype = 1 completeprompt += random.choice(othertypelist) - - if(imagetype == "all" and chance_roll(insanitylevel, imagetypechance) and amountofimagetypes <= 1): + + if imagetype == "all" and chance_roll(insanitylevel, imagetypechance) and amountofimagetypes <= 1: amountofimagetypes = 1 - - for i in range(amountofimagetypes): - # one in 6 images is a complex/other type - if(chance_roll(insanitylevel, imagetypequalitychance) and generateimagetypequality): + # one in 6 images is a complex/other type + if chance_roll(insanitylevel, imagetypequalitychance) and generateimagetypequality: completeprompt += "-imagetypequality- " - if(random.randint(0,5) < 5): + if random.randint(0, 5) < 5: completeprompt += " -imagetype-, " else: othertype = 1 completeprompt += " -othertype-, " - - if(othertype==1): + + if othertype == 1: completeprompt += " of a " else: completeprompt += ", " - elif(generatetype == True): + elif generatetype is True: othertype = 1 - completeprompt += giventypeofimage + " of a " + completeprompt += f'{giventypeofimage} of a ' - - - ### here we can do some other stuff to spice things up - if(chance_roll(insanitylevel, minilocationadditionchance) and generateminilocationaddition == True): + # here we can do some other stuff to spice things up + if chance_roll(insanitylevel, minilocationadditionchance) and generateminilocationaddition is True: completeprompt += " -minilocationaddition-, " - - if(chance_roll(insanitylevel, artmovementprefixchance) and generateartmovement == True): + + if chance_roll(insanitylevel, artmovementprefixchance) and generateartmovement is True: generateartmovement = False completeprompt += " -artmovement-, " - - if(chance_roll(insanitylevel, minivomitprefix1chance) and generateminivomit == True): + + if chance_roll(insanitylevel, minivomitprefix1chance) and generateminivomit is True: completeprompt += " -minivomit-, " - - if(chance_roll(insanitylevel, minivomitprefix2chance) and generateminivomit == True): + + if chance_roll(insanitylevel, minivomitprefix2chance) and generateminivomit is True: completeprompt += " -minivomit-, " # start shot size - - if(mainchooser in ["object", "animal", "humanoid", "concept"] and othertype == 0 and "portrait" not in completeprompt and generateshot == True and chance_roll(insanitylevel,shotsizechance)): + if mainchooser in ["object", "animal", "humanoid", "concept"] and othertype == 0 and "portrait" \ + not in completeprompt and generateshot is True and chance_roll(insanitylevel, shotsizechance): completeprompt += "-shotsize- of a " - elif("portrait" in completeprompt and generateshot == True): + elif "portrait" in completeprompt and generateshot is True: completeprompt += " ,close up of a " - elif(mainchooser in ["landscape"] and generateshot == True): + elif mainchooser in ["landscape"] and generateshot is True: completeprompt += " landscape of a " - elif(generateshot == True): + elif generateshot is True: completeprompt += ", " - # start subject building - if(generatesubject == True): - # start with descriptive qualities - + if generatesubject is True: + # start with descriptive qualities # Common to have 1 description, uncommon to have 2 - if(chance_roll(insanitylevel, subjectdescriptor1chance) and generatedescriptors == True): + if chance_roll(insanitylevel, subjectdescriptor1chance) and generatedescriptors is True: completeprompt += "-descriptor- " - if(chance_roll(insanitylevel, subjectdescriptor2chance) and generatedescriptors == True): + if chance_roll(insanitylevel, subjectdescriptor2chance) and generatedescriptors is True: completeprompt += "-descriptor- " - if(subjectchooser in ["animal as human,","human", "job", "fictional", "non fictional", "humanoid", "manwomanrelation","firstname"] and chance_roll(insanitylevel, subjectbodytypechance) and generatebodytype == True): + if subjectchooser in [ + "animal as human,", + "human", + "job", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, subjectbodytypechance) and generatebodytype is True: completeprompt += "-bodytype- " - if(subjectchooser in ["object","animal as human,","human", "job", "fictional", "non fictional", "humanoid", "manwomanrelation","firstname"] and chance_roll(insanitylevel, subjectculturechance) and generatedescriptors == True): + if subjectchooser in [ + "object", + "animal as human,", + "human", + "job", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, subjectculturechance) and generatedescriptors is True: completeprompt += "-culture- " - if(mainchooser == "object"): + if mainchooser == "object": # first add a wildcard that can be used to create prompt strenght completeprompt += " -objectstrengthstart-" # if we have an overwrite, then make sure we only take the override - if(subtypeobject != "all"): - if(subtypeobject == "generic objects"): + if subtypeobject != "all": + if subtypeobject == "generic objects": objectwildcardlist = ["-object-"] - if(subtypeobject == "vehicles"): + if subtypeobject == "vehicles": objectwildcardlist = ["-vehicle-"] - if(subtypeobject == "food"): + if subtypeobject == "food": objectwildcardlist = ["-food-"] - if(subtypeobject == "buildings"): + if subtypeobject == "buildings": objectwildcardlist = ["-building-"] - if(subtypeobject == "space"): + if subtypeobject == "space": objectwildcardlist = ["-space-"] - if(subtypeobject == "flora"): + if subtypeobject == "flora": objectwildcardlist = ["-flora-"] - - # if we have a given subject, we should skip making an actual subject - if(givensubject == ""): - if(rare_dist(insanitylevel) and advancedprompting == True): + # if we have a given subject, we should skip making an actual subject + if givensubject == "": + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" chosenobjectwildcard = random.choice(objectwildcardlist) - completeprompt += chosenobjectwildcard + " " + completeprompt += f'{chosenobjectwildcard} ' - if(hybridorswap == "hybrid"): - if(uncommon_dist(insanitylevel)): - completeprompt += "|" + random.choice(objectwildcardlist) + "] " + if hybridorswap == "hybrid": + if uncommon_dist(insanitylevel): + completeprompt += f'|{random.choice(objectwildcardlist)}] ' else: - completeprompt += "|" - completeprompt += chosenobjectwildcard + " " - completeprompt += "] " - if(hybridorswap == "swap"): - if(uncommon_dist(insanitylevel)): - completeprompt += ":" + random.choice(objectwildcardlist) + ":" + str(random.randint(1,5)) + "] " + completeprompt += f'|{chosenobjectwildcard} ] ' + if hybridorswap == "swap": + if uncommon_dist(insanitylevel): + completeprompt += f':{random.choice(objectwildcardlist)}:{random.randint(1, 5)}] ' else: - completeprompt += ":" - completeprompt += chosenobjectwildcard + " " - completeprompt += ":" + str(random.randint(1,5)) + "] " + completeprompt += f':{chosenobjectwildcard} :{random.randint(1, 5)}] ' else: - completeprompt += " " + givensubject + " " - + completeprompt += f' {givensubject} ' + hybridorswap = "" # completion of strenght end completeprompt += "-objectstrengthend-" - if(mainchooser == "animal"): + if mainchooser == "animal": # first add a wildcard that can be used to create prompt strenght completeprompt += " -objectstrengthstart-" - - # if we have a given subject, we should skip making an actual subject - if(givensubject == ""): - if(rare_dist(insanitylevel) and advancedprompting == True): + # if we have a given subject, we should skip making an actual subject + if givensubject == "": + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" - - if(unique_dist(insanitylevel) and generateanimaladdition == True): + + if unique_dist(insanitylevel) and generateanimaladdition is True: animaladdedsomething = 1 completeprompt += "-animaladdition- -animal- " - if(animaladdedsomething != 1): + if animaladdedsomething != 1: completeprompt += "-animal- " - - - if(hybridorswap == "hybrid"): - if(uncommon_dist(insanitylevel)): - completeprompt += "|" + random.choice(hybridlist) + "] " + if hybridorswap == "hybrid": + if uncommon_dist(insanitylevel): + completeprompt += f'|{random.choice(hybridlist)}] ' else: completeprompt += "| -animal- ] " - if(hybridorswap == "swap"): - if(uncommon_dist(insanitylevel)): - completeprompt += ":" + random.choice(hybridlist) + ":" + str(random.randint(1,5)) + "] " + if hybridorswap == "swap": + if uncommon_dist(insanitylevel): + completeprompt += f':{random.choice(hybridlist)}:{random.randint(1, 5)}] ' else: - completeprompt += ":-animal-:" + str(random.randint(1,5)) + "] " + completeprompt += f':-animal-:{random.randint(1, 5)}] ' else: - completeprompt += " " + givensubject + " " - + completeprompt += f' {givensubject} ' + hybridorswap = "" # completion of strenght end completeprompt += "-objectstrengthend-" - if(legendary_dist(insanitylevel)): + if legendary_dist(insanitylevel): animaladdedsomething = 1 completeprompt += "-animalsuffixaddition- " - + # if we have a given subject, we should skip making an actual subject - if(mainchooser == "humanoid"): + if mainchooser == "humanoid": # first add a wildcard that can be used to create prompt strenght completeprompt += " -objectstrengthstart-" - if(givensubject==""): + if givensubject == "": - if(subjectchooser == "human"): + if subjectchooser == "human": completeprompt += "-manwoman- " - - if(subjectchooser == "manwomanrelation"): + + if subjectchooser == "manwomanrelation": completeprompt += "-manwomanrelation- " - if(subjectchooser == "job"): + if subjectchooser == "job": completeprompt += "-malefemale- " completeprompt += "-job- " - if(subjectchooser == "fictional"): - if(rare_dist(insanitylevel) and advancedprompting == True): + if subjectchooser == "fictional": + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" - + completeprompt += "-fictional- " - if(hybridorswap == "hybrid"): - completeprompt += "|" + random.choice(hybridhumanlist) + " ] " - if(hybridorswap == "swap"): - completeprompt += ":" + random.choice(hybridhumanlist) + ":" + str(random.randint(1,5)) + "] " + if hybridorswap == "hybrid": + completeprompt += f'|{random.choice(hybridhumanlist)} ] ' + if hybridorswap == "swap": + completeprompt += f':{random.choice(hybridhumanlist)}:{random.randint(1, 5)}] ' hybridorswap = "" - if(subjectchooser == "non fictional"): - if(rare_dist(insanitylevel) and advancedprompting == True): + if subjectchooser == "non fictional": + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" completeprompt += "-nonfictional- " - if(hybridorswap == "hybrid"): - completeprompt += "|" + random.choice(hybridhumanlist) + "] " - if(hybridorswap == "swap"): - completeprompt += ":" + random.choice(hybridhumanlist) + ":" + str(random.randint(1,5)) + "] " + if hybridorswap == "hybrid": + completeprompt += f'|{random.choice(hybridhumanlist)}] ' + if hybridorswap == "swap": + completeprompt += f':{random.choice(hybridhumanlist)}:{random.randint(1, 5)}] ' hybridorswap = "" - if(subjectchooser == "humanoid"): - if(gender != "all"): + if subjectchooser == "humanoid": + if gender != "all": completeprompt += "-malefemale- " - if(rare_dist(insanitylevel) and advancedprompting == True): + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" - + completeprompt += "-humanoid- " - if(hybridorswap == "hybrid"): - completeprompt += "|" + random.choice(hybridhumanlist) + "] " - if(hybridorswap == "swap"): - completeprompt += ":" + random.choice(hybridhumanlist) + ":" + str(random.randint(1,5)) + "] " + if hybridorswap == "hybrid": + completeprompt += f'|{random.choice(hybridhumanlist)}] ' + if hybridorswap == "swap": + completeprompt += f':{random.choice(hybridhumanlist)}:{random.randint(1, 5)}] ' hybridorswap = "" - if(subjectchooser == "firstname"): - if(rare_dist(insanitylevel) and advancedprompting == True): + if subjectchooser == "firstname": + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" - + completeprompt += "-firstname- " - if(hybridorswap == "hybrid"): - completeprompt += "|" + "-firstname-" + "] " - if(hybridorswap == "swap"): - completeprompt += ":" + "-firstname-" + ":" + str(random.randint(1,5)) + "] " + if hybridorswap == "hybrid": + completeprompt += '|-firstname-] ' + if hybridorswap == "swap": + completeprompt += f':-firstname-:{random.randint(1, 5)}] ' hybridorswap = "" - - else: - completeprompt += " " + givensubject + " " + completeprompt += " " + givensubject + " " # completion of strenght end - completeprompt += "-objectstrengthend-" - - # sometimes add a suffix for more fun! - if( (mainchooser == "humanoid" or mainchooser == "animal" or mainchooser == "object") and chance_roll(insanitylevel, subjectconceptsuffixchance)): + completeprompt += "-objectstrengthend-" + + # sometimes add a suffix for more fun! + if (mainchooser == "humanoid" or mainchooser == "animal" or mainchooser == "object") \ + and chance_roll(insanitylevel, subjectconceptsuffixchance): completeprompt += " of -conceptsuffix- " - - if(subjectchooser == "landscape"): + + if subjectchooser == "landscape": # first add a wildcard that can be used to create prompt strenght completeprompt += " -objectstrengthstart-" - + # if we have a given subject, we should skip making an actual subject - if(givensubject == ""): - if(rare_dist(insanitylevel) and advancedprompting == True): + if givensubject == "": + if rare_dist(insanitylevel) and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) completeprompt += "[" - + completeprompt += "-location- " - if(hybridorswap == "hybrid"): - completeprompt += "|" + "-location-" + "] " - if(hybridorswap == "swap"): - completeprompt += ":" + "-location-" + ":" + str(random.randint(1,5)) + "] " + if hybridorswap == "hybrid": + completeprompt += '|-location-] ' + if hybridorswap == "swap": + completeprompt += f':-location-:{random.randint(1, 5)}] ' else: - completeprompt += " " + givensubject + " " - + completeprompt += f' {givensubject} ' + hybridorswap = "" # completion of strenght end completeprompt += "-objectstrengthend-" # shots from inside can create cool effects in landscapes - if(chance_roll(insanitylevel, subjectlandscapeaddonlocationchance)): + if chance_roll(insanitylevel, subjectlandscapeaddonlocationchance): insideshot = 1 completeprompt += " from inside of a -addontolocationinside- " - if(chance_roll(insanitylevel, subjectlandscapeaddonlocationchance) and insideshot == 0): + if chance_roll(insanitylevel, subjectlandscapeaddonlocationchance) and insideshot == 0: completeprompt += " and " - if(chance_roll(insanitylevel, subjectlandscapeaddonlocationdescriptorchance)): - completeprompt += "-descriptor- " - if(chance_roll(insanitylevel, subjectlandscapeaddonlocationculturechance)): + if chance_roll(insanitylevel, subjectlandscapeaddonlocationdescriptorchance): + completeprompt += "-descriptor- " + if chance_roll(insanitylevel, subjectlandscapeaddonlocationculturechance): completeprompt += "-culture- " - #addontolocation = [locationlist,buildinglist, vehiclelist] completeprompt += "-addontolocation- " - - if(mainchooser == "concept"): + if mainchooser == "concept": # first add a wildcard that can be used to create prompt strenght completeprompt += " -objectstrengthstart-" - if(givensubject == ""): - if(subjectchooser == "event"): - completeprompt += " \"" + random.choice(eventlist) + "\" " - - if(subjectchooser == "concept"): + if givensubject == "": + if subjectchooser == "event": + completeprompt += f' "{random.choice(eventlist)}" ' + + if subjectchooser == "concept": completeprompt += " \" The -conceptprefix- of -conceptsuffix- \" " - if(subjectchooser == "poemline"): + if subjectchooser == "poemline": completeprompt += " \" -poemline- \" " - if(subjectchooser == "songline"): + if subjectchooser == "songline": completeprompt += " \" -songline- \" " else: - completeprompt += " " + givensubject + " " + completeprompt += f' {givensubject} ' # completion of strenght end completeprompt += "-objectstrengthend-" - - # object additions for i in range(objectadditionsrepeats): - if(mainchooser == "object" and chance_roll(insanitylevel, objectadditionschance) and generateobjectaddition == True): + if mainchooser == "object" and chance_roll(insanitylevel, objectadditionschance) \ + and generateobjectaddition is True: completeprompt += ", -objectaddition- , " - - + # riding an animal, holding an object or driving a vehicle, rare - if(subjectchooser in ["animal as human,","human","fictional", "non fictional", "humanoid", "manwomanrelation","firstname"] and chance_roll(insanitylevel, humanadditionchance) and generatehumanaddition == True): + if subjectchooser in [ + "animal as human,", + "human", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, humanadditionchance) and generatehumanaddition is True: humanspecial = 1 completeprompt += "-humanaddition- " - + completeprompt += ", " # unique additions for all types: - if(chance_roll(insanitylevel, overalladditionchance) and generateoveralladdition == True): + if chance_roll(insanitylevel, overalladditionchance) and generateoveralladdition is True: completeprompt += "-overalladdition- " - - - - # SD understands emoji's. Can be used to manipulate facial expressions. # emoji, legendary - if(subjectchooser in ["animal as human,","human","fictional", "non fictional", "humanoid", "manwomanrelation","firstname"] and chance_roll(insanitylevel, emojichance) and generateemoji== True): + if subjectchooser in [ + "animal as human,", + "human", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, emojichance) and generateemoji is True: completeprompt += "-emoji-, " - - # cosplaying - #if(subjectchooser in ["animal as human", "non fictional", "humanoid"] and rare_dist(insanitylevel) and humanspecial != 1): - # completeprompt += "cosplaying as " + random.choice(fictionallist) + ", " - - # Job + # Job # either go job or activity, not both - - if(subjectchooser in ["animal as human","human","fictional", "non fictional", "humanoid", "manwomanrelation","firstname"] and chance_roll(insanitylevel, joboractivitychance) and humanspecial != 1 and generatesubject == True): - joboractivitylist = [joblist,humanactivitylist] - completeprompt += random.choice(random.choice(joboractivitylist)) + ", " - - - # if(subjectchooser in ["animal as human","human","job", "fictional", "non fictional", "humanoid"] and legendary_dist(insanitylevel)): - # skintypelist = ["-color-", "-material-"] - # completeprompt += ", with " + random.choice(skintypelist) + " skin, " + if subjectchooser in [ + "animal as human", + "human", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, joboractivitychance) and humanspecial != 1 and generatesubject is True: + joboractivitylist = [joblist, humanactivitylist] + completeprompt += f'{random.choice(random.choice(joboractivitylist))}, ' # custom mid list for i in range(custominputmidrepeats): - if(chance_roll(insanitylevel, custominputmidchance) and generatecustominputmid == True): - completeprompt += random.choice(custominputmidlist) + ", " - + if chance_roll(insanitylevel, custominputmidchance) and generatecustominputmid is True: + completeprompt += f'{random.choice(custominputmidlist)}, ' + # add in some more mini vomits - if(chance_roll(insanitylevel, minivomitmidchance) and generateminivomit == True): + if chance_roll(insanitylevel, minivomitmidchance) and generateminivomit is True: completeprompt += " -minivomit-, " - + # outfit builder - if(subjectchooser in ["animal as human","human","fictional", "non fictional", "humanoid", "manwomanrelation", "firstname"] and chance_roll(insanitylevel, outfitchance) and generateoutfit == True and humanspecial != 1): - completeprompt += ", wearing " + random.choice(buildoutfitlist) + ", " - - if(subjectchooser in ["animal as human","human","fictional", "non fictional", "humanoid", "manwomanrelation", "firstname"] and chance_roll(insanitylevel, posechance) and humanspecial != 1 and generatepose == True): - completeprompt += random.choice(poselist) + ", " - - if(subjectchooser in ["human","job","fictional", "non fictional", "humanoid", "manwomanrelation", "firstname"] and chance_roll(insanitylevel, hairchance) and generatehairstyle == True): - completeprompt += random.choice(buildhairlist) + ", " - - if(subjectchooser in ["animal as human,","human","fictional", "non fictional", "humanoid", "manwomanrelation", "firstname"] and chance_roll(insanitylevel, accessorychance) and generateaccessorie == True and generateaccessories == True): - completeprompt += random.choice(buildaccessorielist) + ", " - - if(chance_roll(insanitylevel, humanoidinsideshotchance) and subjectchooser not in ["landscape", "concept"] and generateinsideshot == True): + if subjectchooser in [ + "animal as human", + "human", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, outfitchance) and generateoutfit is True and humanspecial != 1: + completeprompt += f', wearing {random.choice(buildoutfitlist)}, ' + + if subjectchooser in [ + "animal as human", + "human", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, posechance) and humanspecial != 1 and generatepose is True: + completeprompt += f'{random.choice(poselist)}, ' + + if subjectchooser in [ + "human", + "job", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, hairchance) and generatehairstyle is True: + completeprompt += f'{random.choice(buildhairlist)}, ' + + if subjectchooser in [ + "animal as human,", + "human", + "fictional", + "non fictional", + "humanoid", + "manwomanrelation", + "firstname" + ] and chance_roll(insanitylevel, accessorychance) and generateaccessorie is True \ + and generateaccessories is True: + completeprompt += f'{random.choice(buildaccessorielist)}, ' + + if chance_roll(insanitylevel, humanoidinsideshotchance) and subjectchooser not in ["landscape", "concept"] \ + and generateinsideshot is True: insideshot = 1 - completeprompt += random.choice(insideshotlist) + ", " - - if(subjectchooser not in ["landscape", "concept"] and humanspecial != 1 and insideshot == 0 and chance_roll(insanitylevel, humanoidbackgroundchance) and generatebackground == True): - completeprompt += random.choice(backgroundtypelist) + ", " + completeprompt += f'{random.choice(insideshotlist)}, ' + + if subjectchooser not in ["landscape", "concept"] and humanspecial != 1 and insideshot == 0 \ + and chance_roll(insanitylevel, humanoidbackgroundchance) and generatebackground is True: + completeprompt += f'{random.choice(backgroundtypelist)}, ' # minilocation bit - if(subjectchooser in ["landscape"] and chance_roll(insanitylevel, landscapeminilocationchance) and generateminilocationaddition == True): + if subjectchooser in ["landscape"] and chance_roll(insanitylevel, landscapeminilocationchance) \ + and generateminilocationaddition is True: completeprompt += " -minilocationaddition-, " - - if(chance_roll(insanitylevel, generalminilocationchance) and generateminilocationaddition == True): - completeprompt += " -minilocationaddition-, " - + if chance_roll(insanitylevel, generalminilocationchance) and generateminilocationaddition is True: + completeprompt += " -minilocationaddition-, " # landscapes it is nice to always have a time period - if(chance_roll(insanitylevel, timperiodchance) or subjectchooser=="landscape"): - if(generatetimeperiod == True): + if chance_roll(insanitylevel, timperiodchance) or subjectchooser == "landscape": + if generatetimeperiod is True: completeprompt += "-timeperiod-, " - if(mainchooser not in ["landscape"] and chance_roll(insanitylevel, focuschance) and generatefocus == True): + if mainchooser not in ["landscape"] and chance_roll(insanitylevel, focuschance) and generatefocus is True: completeprompt += "-focus-, " - - # others - if(chance_roll(insanitylevel, directionchance) and generatedirection == True): + if chance_roll(insanitylevel, directionchance) and generatedirection is True: completeprompt += "-direction-, " - if(chance_roll(insanitylevel, moodchance) and generatemood == True): - completeprompt += "-mood-, " + if chance_roll(insanitylevel, moodchance) and generatemood is True: + completeprompt += "-mood-, " # add in some more mini vomits - if(chance_roll(insanitylevel, minivomitsuffixchance) and generateminivomit == True): + if chance_roll(insanitylevel, minivomitsuffixchance) and generateminivomit is True: completeprompt += " -minivomit-, " - - if(chance_roll(insanitylevel, artmovementchance) and generateartmovement == True): - completeprompt += "-artmovement-, " - - if(chance_roll(insanitylevel, lightingchance) and generatelighting == True): - completeprompt += "-lighting-, " + + if chance_roll(insanitylevel, artmovementchance) and generateartmovement is True: + completeprompt += "-artmovement-, " + + if chance_roll(insanitylevel, lightingchance) and generatelighting is True: + completeprompt += "-lighting-, " # determine wether we have a photo or not - if("photo" in completeprompt.lower()): + if "photo" in completeprompt.lower(): isphoto = 1 - - if(chance_roll(insanitylevel, photoadditionchance) and isphoto == 1 and generatephotoaddition == True): - completeprompt += random.choice(photoadditionlist) + ", " - - if(isphoto == 1 and generatecamera == True): - completeprompt += "-camera-, " - - if(chance_roll(insanitylevel, lenschance) or isphoto == 1): - if(generatelens == True): + + if chance_roll(insanitylevel, photoadditionchance) and isphoto == 1 and generatephotoaddition is True: + completeprompt += f'{random.choice(photoadditionlist)}, ' + + if isphoto == 1 and generatecamera is True: + completeprompt += "-camera-, " + + if chance_roll(insanitylevel, lenschance) or isphoto == 1: + if generatelens is True: completeprompt += "-lens-, " - if(chance_roll(insanitylevel, colorschemechance) and generatecolorscheme == True): + if chance_roll(insanitylevel, colorschemechance) and generatecolorscheme is True: completeprompt += "-colorscheme-, " # vomit some cool/wierd things into the prompt - if(chance_roll(insanitylevel, vomit1chance) and generatevomit == True): + if chance_roll(insanitylevel, vomit1chance) and generatevomit is True: completeprompt += "-vomit-, " - if(chance_roll(insanitylevel, vomit2chance)): + if chance_roll(insanitylevel, vomit2chance): completeprompt += "-vomit-, " - #adding a great work of art, like starry night has cool effects. But this should happen only very rarely. - if(chance_roll(insanitylevel, greatworkchance) and generategreatwork == True): + # adding a great work of art, like starry night has cool effects. But this should happen only very rarely. + if chance_roll(insanitylevel, greatworkchance) and generategreatwork is True: completeprompt += " in the style of -greatwork-, " - #adding a poemline. But this should happen only very rarely. - if(chance_roll(insanitylevel, poemlinechance) and generatepoemline == True): + # adding a poemline. But this should happen only very rarely. + if chance_roll(insanitylevel, poemlinechance) and generatepoemline is True: completeprompt += " \"-poemline-\", " - #adding a songline. But this should happen only very rarely. - if(chance_roll(insanitylevel, songlinechance) and generatesongline == True): + # adding a songline. But this should happen only very rarely. + if chance_roll(insanitylevel, songlinechance) and generatesongline is True: completeprompt += " \"-songline-\", " # everyone loves the adding quality. The better models don't need this, but lets add it anyway - if(chance_roll(insanitylevel, quality1chance) and generatequality == True): + if chance_roll(insanitylevel, quality1chance) and generatequality is True: completeprompt += "-quality-, " - if(chance_roll(insanitylevel, quality2chance)): + if chance_roll(insanitylevel, quality2chance): completeprompt += "-quality-, " - - # start second part of art blaster here - if(artblastermode==True): + if artblastermode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(artistlist)): + if uncommon_dist(insanitylevel) and bool(artistlist): completeprompt += "-artist-, " - if(uncommon_dist(insanitylevel) and bool(artmovementlist)): + if uncommon_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(unique_dist(insanitylevel) and bool(vomitlist)): + if unique_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(unique_dist(insanitylevel) and bool(imagetypelist)): + if unique_dist(insanitylevel) and bool(imagetypelist): completeprompt += "-imagetype-, " - if(unique_dist(insanitylevel) and bool(colorschemelist)): + if unique_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - step = step + 1 - - # start second part of unique art here - if(uniqueartmode==True): + step = step + 1 + + # start second part of unique art here + if uniqueartmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(artmovementlist)): + if uncommon_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(uncommon_dist(insanitylevel) and bool(colorschemelist)): + if uncommon_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - if(rare_dist(insanitylevel) and bool(vomitlist)): + if rare_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(rare_dist(insanitylevel) and bool(lightinglist)): + if rare_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - if(unique_dist(insanitylevel) and bool(qualitylist)): + if unique_dist(insanitylevel) and bool(qualitylist): completeprompt += "-quality-, " - if(unique_dist(insanitylevel) and bool(artistlist)): + if unique_dist(insanitylevel) and bool(artistlist): completeprompt += "-artist-, " - if(novel_dist(insanitylevel) and bool(greatworklist)): + if novel_dist(insanitylevel) and bool(greatworklist): completeprompt += "in style of -greatwork-, " - if(novel_dist(insanitylevel) and bool(poemlinelist)): + if novel_dist(insanitylevel) and bool(poemlinelist): completeprompt += "\"-poemline-\", " - if(novel_dist(insanitylevel) and bool(songlinelist)): + if novel_dist(insanitylevel) and bool(songlinelist): completeprompt += "\"-songline-\", " - - step = step + 1 - - + + step = step + 1 + # start second part of quality vomit here - if(qualityvomitmode==True): + if qualityvomitmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(vomitlist)): + if uncommon_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(uncommon_dist(insanitylevel) and bool(qualitylist)): + if uncommon_dist(insanitylevel) and bool(qualitylist): completeprompt += "-quality-, " - if(unique_dist(insanitylevel) and bool(minivomitlist)): + if unique_dist(insanitylevel) and bool(minivomitlist): completeprompt += "-minivomit-, " - if(unique_dist(insanitylevel) and bool(artmovementlist)) : + if unique_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(unique_dist(insanitylevel) and bool(colorschemelist)): + if unique_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - step = step + 1 - + step = step + 1 + # start second part of mood color here - if(colorcannonmode == True): + if colorcannonmode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(moodlist)): + if uncommon_dist(insanitylevel) and bool(moodlist): completeprompt += "-mood-, " - if(uncommon_dist(insanitylevel) and bool(colorschemelist)): + if uncommon_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - if(rare_dist(insanitylevel) and bool(vomitlist)): + if rare_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(unique_dist(insanitylevel) and bool(artmovementlist)): + if unique_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(unique_dist(insanitylevel) and bool(lightinglist)): + if unique_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - step = step + 1 + step = step + 1 - # start second part of photo fantasy here - if(photofantasymode == True): + if photofantasymode is True: step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(uncommon_dist(insanitylevel) and bool(lightinglist)): + if uncommon_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - if(uncommon_dist(insanitylevel) and bool(cameralist)): + if uncommon_dist(insanitylevel) and bool(cameralist): completeprompt += "-camera-, " - if(rare_dist(insanitylevel) and bool(lenslist)): + if rare_dist(insanitylevel) and bool(lenslist): completeprompt += "-lens-, " - if(unique_dist(insanitylevel) and bool(moodlist)): + if unique_dist(insanitylevel) and bool(moodlist): completeprompt += "-mood-, " - if(unique_dist(insanitylevel) and bool(colorschemelist)): + if unique_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - step = step + 1 - + step = step + 1 + # start second part of massive madness here - if(massivemadnessmode == True): + if massivemadnessmode is True: completeprompt += ":1.3), " step = 0 end = random.randint(1, insanitylevel) + 1 while step < end: - if(rare_dist(insanitylevel) and bool(artistlist)): + if rare_dist(insanitylevel) and bool(artistlist): completeprompt += "-artist-, " - if(rare_dist(insanitylevel) and bool(descriptorlist)): + if rare_dist(insanitylevel) and bool(descriptorlist): completeprompt += "-descriptor-, " - if(rare_dist(insanitylevel) and bool(moodlist)): + if rare_dist(insanitylevel) and bool(moodlist): completeprompt += "-mood-, " - if(rare_dist(insanitylevel) and bool(colorschemelist)): + if rare_dist(insanitylevel) and bool(colorschemelist): completeprompt += "-colorscheme-, " - if(rare_dist(insanitylevel) and bool(vomitlist)): + if rare_dist(insanitylevel) and bool(vomitlist): completeprompt += "-vomit-, " - if(rare_dist(insanitylevel) and bool(artmovementlist)): + if rare_dist(insanitylevel) and bool(artmovementlist): completeprompt += "-artmovement-, " - if(rare_dist(insanitylevel) and bool(lightinglist)): + if rare_dist(insanitylevel) and bool(lightinglist): completeprompt += "-lighting-, " - if(rare_dist(insanitylevel) and bool(minilocationadditionslist)): + if rare_dist(insanitylevel) and bool(minilocationadditionslist): completeprompt += "-minilocationaddition-, " - if(rare_dist(insanitylevel) and bool(materiallist)): + if rare_dist(insanitylevel) and bool(materiallist): completeprompt += "-material-, " - if(rare_dist(insanitylevel) and bool(conceptsuffixlist)): + if rare_dist(insanitylevel) and bool(conceptsuffixlist): completeprompt += "-conceptsuffix-, " - if(rare_dist(insanitylevel) and bool(qualitylist)): + if rare_dist(insanitylevel) and bool(qualitylist): completeprompt += "-quality-, " - if(rare_dist(insanitylevel) and bool(cameralist)): + if rare_dist(insanitylevel) and bool(cameralist): completeprompt += "-camera-, " - step = step + 1 + step = step + 1 # start styles mode here - if(stylesmode == True): + if stylesmode is True: completeprompt += chosenstylesuffix - # custom style list - if(chance_roll(insanitylevel, customstyle1chance) and generatestyle == True): + if chance_roll(insanitylevel, customstyle1chance) and generatestyle is True: completeprompt += "-styletilora-, " - if(chance_roll(insanitylevel, customstyle2chance)): + if chance_roll(insanitylevel, customstyle2chance): completeprompt += "-styletilora-, " - # custom suffix list for i in range(custominputsuffixrepeats): - if(chance_roll(insanitylevel, custominputsuffixchance) and generatecustominputsuffix == True): - completeprompt += random.choice(custominputsuffixlist) + ", " - - + if chance_roll(insanitylevel, custominputsuffixchance) and generatecustominputsuffix is True: + completeprompt += f'{random.choice(custominputsuffixlist)}, ' if artistmode in ["enhancing"]: - completeprompt += "::" + str(random.randint(1,17)) + "] " - + completeprompt += f'::{random.randint(1, 17)}] ' - - if(artists != "none" and artistsplacement == "back" and generateartist == True): + if artists != "none" and artistsplacement == "back" and generateartist is True: completeprompt += ", " # take 1-3 artists, weighted to 1-2 step = random.randint(0, 1) end = random.randint(1, insanitylevel3) - - - - # determine artist mode: - # normal - # hybrid | - # switching A:B:X - # adding at step x a:X - # stopping at step x ::X - - - modeselector = random.randint(0,10) + modeselector = random.randint(0, 10) if modeselector < 4 and end - step >= 2: artistmodeslist = ["hybrid", "stopping", "adding", "switching"] artistmode = artistmodeslist[modeselector] - if(advancedprompting == False): + if advancedprompting is False: artistmode = "normal" - if artistmode in ["hybrid","switching"] and end - step == 1: + if artistmode in ["hybrid", "switching"] and end - step == 1: artistmode = "normal" # if there are not enough artists in the list, then just go normal - if(len(artistlist) < 3): + if len(artistlist) < 3: artistmode = "normal" - - if artistmode in ["hybrid", "stopping", "adding","switching"]: + + if artistmode in ["hybrid", "stopping", "adding", "switching"]: completeprompt += " [" - - while step < end: - if(normal_dist(insanitylevel)): + + while step < end: + if normal_dist(insanitylevel): isweighted = 1 - + if isweighted == 1: completeprompt += " (" - #completeprompt = add_from_csv(completeprompt, "artists", 0, "art by ","") completeprompt += "-artist-" - + if isweighted == 1: - completeprompt += ":" + str(1 + (random.randint(-3,3)/10)) + ")" - + completeprompt += ":" + str(1 + (random.randint(-3, 3) / 10)) + ")" + if artistmode in ["hybrid"] and not end - step == 1: completeprompt += "|" if artistmode in ["switching"] and not end - step == 1: completeprompt += ":" - - if artistmode not in ["hybrid", "switching"]and not end - step == 1: + + if artistmode not in ["hybrid", "switching"] and not end - step == 1: completeprompt += "," - + isweighted = 0 - step = step + 1 if artistmode in ["stopping"]: - completeprompt += "::" - completeprompt += str(random.randint(1,19)) - - if artistmode in ["switching","adding"]: - completeprompt += ":" + str(random.randint(1,18)) - if artistmode in ["hybrid", "stopping","adding", "switching"]: + completeprompt += f'::{random.randint(1, 19)}' + + if artistmode in ["switching", "adding"]: + completeprompt += f':{random.randint(1, 18)}' + if artistmode in ["hybrid", "stopping", "adding", "switching"]: completeprompt += "] " # end of the artist stuff - - - completeprompt += ", " completeprompt += suffixprompt # and then up the compounding stuff compoundcounter += 1 - + # Here comes all the seperator stuff for prompt compounding - if(compoundcounter < promptstocompound): - if(seperator == "comma"): + if compoundcounter < promptstocompound: + if seperator == "comma": completeprompt += " \n , " else: - completeprompt += " \n " + seperator + " " - - - - - - #end of the while loop, now clean up the prompt + completeprompt += f' \n {seperator} ' + # end of the while loop, now clean up the prompt # first some manual stuff for outfit + # sometimes, its just nice to have descriptor and a normal "outfit". We use mini outfits for this! + if unique_dist(insanitylevel): + completeprompt = completeprompt.replace("-outfit-", "-minioutfit-", 1) - if(unique_dist(insanitylevel)): # sometimes, its just nice to have descriptor and a normal "outfit". We use mini outfits for this! - completeprompt = completeprompt.replace("-outfit-", "-minioutfit-",1) - - - - # lol, this needs a rewrite :D while ( - "-color-" in completeprompt or - "-material-" in completeprompt or - "-animal-" in completeprompt or - "-object-" in completeprompt or - "-fictional-" in completeprompt or - "-nonfictional-" in completeprompt or - "-conceptsuffix-" in completeprompt or - "-building-" in completeprompt or - "-vehicle-" in completeprompt or - "-outfit-" in completeprompt or - "-location-" in completeprompt or - "-conceptprefix-" in completeprompt or - "-descriptor-" in completeprompt or - "-food-" in completeprompt or - "-haircolor-" in completeprompt or - "-hairstyle-" in completeprompt or - "-job-" in completeprompt or - "-culture-" in completeprompt or - "-accessory-" in completeprompt or - "-humanoid-" in completeprompt or - "-manwoman-" in completeprompt or - "-human-" in completeprompt or - "-colorscheme-" in completeprompt or - "-mood-" in completeprompt or - "-genderdescription-" in completeprompt or - "-artmovement-" in completeprompt or - "-malefemale-" in completeprompt or - "-objecttotal-" in completeprompt or - "-outfitprinttotal-" in completeprompt or - "-bodytype-" in completeprompt or - "-minilocation-" in completeprompt or - "-minilocationaddition-" in completeprompt or - "-pose-" in completeprompt or - "-season-" in completeprompt or - "-minioutfit-" in completeprompt or - "-elaborateoutfit-" in completeprompt or - "-minivomit-" in completeprompt or - "-vomit-" in completeprompt or - "-rpgclass-" in completeprompt or - "-subjectfromfile-" in completeprompt or - "-brand-" in completeprompt or - "-space-" in completeprompt or - "-artist-" in completeprompt or - "-imagetype-" in completeprompt or - "-othertype-" in completeprompt or - "-quality-" in completeprompt or - "-lighting-" in completeprompt or - "-camera-" in completeprompt or - "-lens-" in completeprompt or - "-imagetypequality-" in completeprompt or - "-poemline-" in completeprompt or - "-songline-" in completeprompt or - "-greatwork-" in completeprompt or - "-artistfantasy-" in completeprompt or - "-artistpopular-" in completeprompt or - "-artistromanticism-" in completeprompt or - "-artistphotography-" in completeprompt or - "-emoji-" in completeprompt or - "-timeperiod-" in completeprompt or - "-shotsize-" in completeprompt or - "-musicgenre-" in completeprompt or - "-animaladdition-" in completeprompt or - "-addontolocationinside-" in completeprompt or - "-addontolocation-" in completeprompt or - "-objectaddition-" in completeprompt or - "-humanaddition-" in completeprompt or - "-overalladdition-" in completeprompt or - "-focus-" in completeprompt or - "-direction-" in completeprompt or - "-styletilora-" in completeprompt or - "-manwomanrelation-" in completeprompt or - "-waterlocation-" in completeprompt or - "-container-" in completeprompt or - "-firstname-" in completeprompt or - "-flora-" in completeprompt or - "-print-" in completeprompt or - "-miniactivity-" in completeprompt or - "-pattern-" in completeprompt or - "-animalsuffixaddition-" in completeprompt or - "-chair-" in completeprompt): - allwildcardslistnohybrid = [ "-color-","-object-", "-animal-", "-fictional-","-nonfictional-","-building-","-vehicle-","-location-","-conceptprefix-","-food-","-haircolor-","-hairstyle-","-job-", "-accessory-", "-humanoid-", "-manwoman-", "-human-", "-colorscheme-", "-mood-", "-genderdescription-", "-artmovement-", "-malefemale-", "-bodytype-", "-minilocation-", "-minilocationaddition-", "-pose-", "-season-", "-minioutfit-", "-elaborateoutfit-", "-minivomit-", "-vomit-", "-rpgclass-", "-subjectfromfile-", "-brand-", "-space-", "-artist-", "-imagetype-", "-othertype-", "-quality-", "-lighting-", "-camera-", "-lens-","-imagetypequality-", "-poemline-", "-songline-", "-greatwork-", "-artistfantasy-", "-artistpopular-", "-artistromanticism-", "-artistphotography-", "-emoji-", "-timeperiod-", "-shotsize-", "-musicgenre-", "-animaladdition-", "-addontolocationinside-", "-addontolocation-", "-objectaddition-", "-humanaddition-", "-overalladdition-", "-focus-", "-direction-", "-styletilora-", "-manwomanrelation-", "-waterlocation-", "-container-", "-firstname-", "-flora-", "-print-", "-miniactivity-", "-pattern-", "-animalsuffixaddition-", "-chair-"] - allwildcardslistnohybridlists = [colorlist, objectlist, animallist, fictionallist, nonfictionallist, buildinglist, vehiclelist, locationlist,conceptprefixlist,foodlist,haircolorlist, hairstylelist,joblist, accessorielist, humanoidlist, manwomanlist, humanlist, colorschemelist, moodlist, genderdescriptionlist, artmovementlist, malefemalelist, bodytypelist, minilocationlist, minilocationadditionslist, poselist, seasonlist, minioutfitlist, elaborateoutfitlist, minivomitlist, vomitlist, rpgclasslist, customsubjectslist, brandlist, spacelist, artistlist, imagetypelist, othertypelist, qualitylist, lightinglist, cameralist, lenslist, imagetypequalitylist, poemlinelist, songlinelist, greatworklist, fantasyartistlist, popularartistlist, romanticismartistlist, photographyartistlist, emojilist, timeperiodlist, shotsizelist, musicgenrelist, animaladditionlist, addontolocationinsidelist, addontolocationlist, objectadditionslist, humanadditionlist, overalladditionlist, focuslist, directionlist, stylestiloralist, manwomanrelationlist, waterlocationlist, containerlist, firstnamelist, floralist, printlist, miniactivitylist, patternlist, animalsuffixadditionlist, chairlist] - - allwildcardslistwithhybrid = ["-material-", "-descriptor-", "-outfit-", "-conceptsuffix-","-culture-", "-objecttotal-", "-outfitprinttotal-"] - allwildcardslistwithhybridlists = [materiallist, descriptorlist,outfitlist,conceptsuffixlist,culturelist, objecttotallist, outfitprinttotallist] - - + "-color-" in completeprompt or + "-material-" in completeprompt or + "-animal-" in completeprompt or + "-object-" in completeprompt or + "-fictional-" in completeprompt or + "-nonfictional-" in completeprompt or + "-conceptsuffix-" in completeprompt or + "-building-" in completeprompt or + "-vehicle-" in completeprompt or + "-outfit-" in completeprompt or + "-location-" in completeprompt or + "-conceptprefix-" in completeprompt or + "-descriptor-" in completeprompt or + "-food-" in completeprompt or + "-haircolor-" in completeprompt or + "-hairstyle-" in completeprompt or + "-job-" in completeprompt or + "-culture-" in completeprompt or + "-accessory-" in completeprompt or + "-humanoid-" in completeprompt or + "-manwoman-" in completeprompt or + "-human-" in completeprompt or + "-colorscheme-" in completeprompt or + "-mood-" in completeprompt or + "-genderdescription-" in completeprompt or + "-artmovement-" in completeprompt or + "-malefemale-" in completeprompt or + "-objecttotal-" in completeprompt or + "-outfitprinttotal-" in completeprompt or + "-bodytype-" in completeprompt or + "-minilocation-" in completeprompt or + "-minilocationaddition-" in completeprompt or + "-pose-" in completeprompt or + "-season-" in completeprompt or + "-minioutfit-" in completeprompt or + "-elaborateoutfit-" in completeprompt or + "-minivomit-" in completeprompt or + "-vomit-" in completeprompt or + "-rpgclass-" in completeprompt or + "-subjectfromfile-" in completeprompt or + "-brand-" in completeprompt or + "-space-" in completeprompt or + "-artist-" in completeprompt or + "-imagetype-" in completeprompt or + "-othertype-" in completeprompt or + "-quality-" in completeprompt or + "-lighting-" in completeprompt or + "-camera-" in completeprompt or + "-lens-" in completeprompt or + "-imagetypequality-" in completeprompt or + "-poemline-" in completeprompt or + "-songline-" in completeprompt or + "-greatwork-" in completeprompt or + "-artistfantasy-" in completeprompt or + "-artistpopular-" in completeprompt or + "-artistromanticism-" in completeprompt or + "-artistphotography-" in completeprompt or + "-emoji-" in completeprompt or + "-timeperiod-" in completeprompt or + "-shotsize-" in completeprompt or + "-musicgenre-" in completeprompt or + "-animaladdition-" in completeprompt or + "-addontolocationinside-" in completeprompt or + "-addontolocation-" in completeprompt or + "-objectaddition-" in completeprompt or + "-humanaddition-" in completeprompt or + "-overalladdition-" in completeprompt or + "-focus-" in completeprompt or + "-direction-" in completeprompt or + "-styletilora-" in completeprompt or + "-manwomanrelation-" in completeprompt or + "-waterlocation-" in completeprompt or + "-container-" in completeprompt or + "-firstname-" in completeprompt or + "-flora-" in completeprompt or + "-print-" in completeprompt or + "-miniactivity-" in completeprompt or + "-pattern-" in completeprompt or + "-animalsuffixaddition-" in completeprompt or + "-chair-" in completeprompt + ): + allwildcardslistnohybrid = [ + "-color-", + "-object-", + "-animal-", + "-fictional-", + "-nonfictional-", + "-building-", + "-vehicle-", + "-location-", + "-conceptprefix-", + "-food-", + "-haircolor-", + "-hairstyle-", + "-job-", + "-accessory-", + "-humanoid-", + "-manwoman-", + "-human-", + "-colorscheme-", + "-mood-", + "-genderdescription-", + "-artmovement-", + "-malefemale-", + "-bodytype-", + "-minilocation-", + "-minilocationaddition-", + "-pose-", + "-season-", + "-minioutfit-", + "-elaborateoutfit-", + "-minivomit-", + "-vomit-", + "-rpgclass-", + "-subjectfromfile-", + "-brand-", + "-space-", + "-artist-", + "-imagetype-", + "-othertype-", + "-quality-", + "-lighting-", + "-camera-", + "-lens-", + "-imagetypequality-", + "-poemline-", + "-songline-", + "-greatwork-", + "-artistfantasy-", + "-artistpopular-", + "-artistromanticism-", + "-artistphotography-", + "-emoji-", + "-timeperiod-", + "-shotsize-", + "-musicgenre-", + "-animaladdition-", + "-addontolocationinside-", + "-addontolocation-", + "-objectaddition-", + "-humanaddition-", + "-overalladdition-", + "-focus-", + "-direction-", + "-styletilora-", + "-manwomanrelation-", + "-waterlocation-", + "-container-", + "-firstname-", + "-flora-", + "-print-", + "-miniactivity-", + "-pattern-", + "-animalsuffixaddition-", + "-chair-" + ] + allwildcardslistnohybridlists = [ + colorlist, + objectlist, + animallist, + fictionallist, + nonfictionallist, + buildinglist, + vehiclelist, + locationlist, + conceptprefixlist, + foodlist, + haircolorlist, + hairstylelist, + joblist, + accessorielist, + humanoidlist, + manwomanlist, + humanlist, + colorschemelist, + moodlist, + genderdescriptionlist, + artmovementlist, + malefemalelist, + bodytypelist, + minilocationlist, + minilocationadditionslist, + poselist, + seasonlist, + minioutfitlist, + elaborateoutfitlist, + minivomitlist, + vomitlist, + rpgclasslist, + customsubjectslist, + brandlist, + spacelist, + artistlist, + imagetypelist, + othertypelist, + qualitylist, + lightinglist, + cameralist, + lenslist, + imagetypequalitylist, + poemlinelist, + songlinelist, + greatworklist, + fantasyartistlist, + popularartistlist, + romanticismartistlist, + photographyartistlist, + emojilist, + timeperiodlist, + shotsizelist, + musicgenrelist, + animaladditionlist, + addontolocationinsidelist, + addontolocationlist, + objectadditionslist, + humanadditionlist, + overalladditionlist, + focuslist, + directionlist, + stylestiloralist, + manwomanrelationlist, + waterlocationlist, + containerlist, + firstnamelist, + floralist, + printlist, + miniactivitylist, + patternlist, + animalsuffixadditionlist, + chairlist + ] + + allwildcardslistwithhybrid = [ + "-material-", + "-descriptor-", + "-outfit-", + "-conceptsuffix-", + "-culture-", + "-objecttotal-", + "-outfitprinttotal-" + ] + allwildcardslistwithhybridlists = [ + materiallist, + descriptorlist, + outfitlist, + conceptsuffixlist, + culturelist, + objecttotallist, + outfitprinttotallist + ] + # keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) for wildcard in allwildcardslistnohybrid: attachedlist = allwildcardslistnohybridlists[allwildcardslistnohybrid.index(wildcard)] - completeprompt = replacewildcard(completeprompt, insanitylevel, wildcard, attachedlist,False, advancedprompting) + completeprompt = replacewildcard( + completeprompt, + insanitylevel, + wildcard, + attachedlist, + False, + advancedprompting + ) - - for wildcard in allwildcardslistwithhybrid: attachedlist = allwildcardslistwithhybridlists[allwildcardslistwithhybrid.index(wildcard)] - completeprompt = replacewildcard(completeprompt, insanitylevel, wildcard, attachedlist,True, advancedprompting) - + completeprompt = replacewildcard( + completeprompt, + insanitylevel, + wildcard, + attachedlist, + True, + advancedprompting + ) - # prompt strenght stuff - # if the given subject already is formed like this ( :1.x) # then just ignore this - matches = [] - if(givensubject != ""): + if givensubject != "": pattern = r'\(\w+:\d+\.\d+\)' matches = re.findall(pattern, givensubject) - - if(len(completeprompt) > 325 and matches == []): - if(len(completeprompt) < 375): - strenght = "1.1" - elif(len(completeprompt) < 450): - strenght = "1.2" + if len(completeprompt) > 325 and matches == []: + if len(completeprompt) < 375: + strenght = "1.1" + elif len(completeprompt) < 450: + strenght = "1.2" else: - strenght = "1.3" - completeprompt = completeprompt.replace("-objectstrengthstart-","(") - completeprompt = completeprompt.replace("-objectstrengthend-",":" + strenght + ")") + strenght = "1.3" + completeprompt = completeprompt.replace("-objectstrengthstart-", "(") + completeprompt = completeprompt.replace("-objectstrengthend-", f':{strenght})') else: - completeprompt = completeprompt.replace("-objectstrengthstart-","") - completeprompt = completeprompt.replace("-objectstrengthend-","") + completeprompt = completeprompt.replace("-objectstrengthstart-", "") + completeprompt = completeprompt.replace("-objectstrengthend-", "") # clean it up completeprompt = cleanup(completeprompt, advancedprompting) - #just for me, some fun with posting fake dev messages (ala old sim games) - if(random.randint(1, 50)==1): + # just for me, some fun with posting fake dev messages (ala old sim games) + if random.randint(1, 50) == 1: print("") print(random.choice(devmessagelist)) print("") @@ -2043,65 +2179,78 @@ def build_dynamic_prompt(insanitylevel = 5, forcesubject = "all", artists = "all # function that takes an existing prompt and tries to create a variant out of it -def createpromptvariant(prompt = "", insanitylevel = 5, antivalues = "" , gender = "all", artists = "all", advancedprompting = True): +def createpromptvariant( + prompt="", + insanitylevel=5, + antivalues="", + gender="all", + artists="all", + advancedprompting=True +): # first load the lists, all copied from above (can that be done better?) # do we want to use the same settings or keep it open?? # first build up a complete anti list. Those values are removing during list building # this uses the antivalues string AND the antilist.csv emptylist = [] - antilist = csv_to_list("antilist",emptylist , "./userfiles/",1) + antilist = csv_to_list("antilist", emptylist, "./userfiles/", 1) antivaluelist = antivalues.split(",") antilist += antivaluelist # build all lists here - - colorlist = csv_to_list("colors",antilist) - animallist = csv_to_list("animals",antilist) - materiallist = csv_to_list("materials",antilist) - objectlist = csv_to_list("objects",antilist) - fictionallist = csv_to_list(csvfilename="fictional characters",antilist=antilist,skipheader=True,gender=gender) - nonfictionallist = csv_to_list(csvfilename="nonfictional characters",antilist=antilist,skipheader=True,gender=gender) - conceptsuffixlist = csv_to_list("concept_suffix",antilist) - buildinglist = csv_to_list("buildings",antilist) - vehiclelist = csv_to_list("vehicles",antilist) - outfitlist = csv_to_list("outfits",antilist) - locationlist = csv_to_list("locations",antilist) - - accessorielist = csv_to_list("accessories",antilist) - artmovementlist = csv_to_list("artmovements",antilist) - bodytypelist = csv_to_list("body_types",antilist) - cameralist = csv_to_list("cameras",antilist) - colorschemelist = csv_to_list("colorscheme",antilist) - conceptprefixlist = csv_to_list("concept_prefix",antilist) - culturelist = csv_to_list("cultures",antilist) - descriptorlist = csv_to_list("descriptors",antilist) - devmessagelist = csv_to_list("devmessages",antilist) - directionlist = csv_to_list("directions",antilist) - emojilist = csv_to_list("emojis",antilist) - eventlist = csv_to_list("events",antilist) - focuslist = csv_to_list("focus",antilist) - greatworklist = csv_to_list("greatworks",antilist) - haircolorlist = csv_to_list("haircolors",antilist) - hairstylelist = csv_to_list("hairstyles",antilist) - humanactivitylist = csv_to_list("human_activities",antilist) - humanoidlist = csv_to_list("humanoids",antilist) - imagetypelist = csv_to_list("imagetypes",antilist) - joblist = csv_to_list("jobs",antilist) - lenslist = csv_to_list("lenses",antilist) - lightinglist = csv_to_list("lighting",antilist) - malefemalelist = csv_to_list(csvfilename="malefemale",antilist=antilist,skipheader=True,gender=gender) - manwomanlist = csv_to_list(csvfilename="manwoman",antilist=antilist,skipheader=True,gender=gender) - moodlist = csv_to_list("moods",antilist) - othertypelist = csv_to_list("othertypes",antilist) - poselist = csv_to_list("poses",antilist) - qualitylist = csv_to_list("quality",antilist) - shotsizelist = csv_to_list("shotsizes",antilist) - timeperiodlist = csv_to_list("timeperiods",antilist) - vomitlist = csv_to_list("vomit",antilist) + colorlist = csv_to_list("colors", antilist) + animallist = csv_to_list("animals", antilist) + materiallist = csv_to_list("materials", antilist) + objectlist = csv_to_list("objects", antilist) + fictionallist = csv_to_list(csvfilename="fictional characters", antilist=antilist, skipheader=True, gender=gender) + nonfictionallist = csv_to_list( + csvfilename="nonfictional characters", + antilist=antilist, + skipheader=True, + gender=gender + ) + conceptsuffixlist = csv_to_list("concept_suffix", antilist) + buildinglist = csv_to_list("buildings", antilist) + vehiclelist = csv_to_list("vehicles", antilist) + outfitlist = csv_to_list("outfits", antilist) + locationlist = csv_to_list("locations", antilist) + accessorielist = csv_to_list("accessories", antilist) + artmovementlist = csv_to_list("artmovements", antilist) + bodytypelist = csv_to_list("body_types", antilist) + cameralist = csv_to_list("cameras", antilist) + colorschemelist = csv_to_list("colorscheme", antilist) + conceptprefixlist = csv_to_list("concept_prefix", antilist) + culturelist = csv_to_list("cultures", antilist) + descriptorlist = csv_to_list("descriptors", antilist) + directionlist = csv_to_list("directions", antilist) + emojilist = csv_to_list("emojis", antilist) + eventlist = csv_to_list("events", antilist) + focuslist = csv_to_list("focus", antilist) + greatworklist = csv_to_list("greatworks", antilist) + haircolorlist = csv_to_list("haircolors", antilist) + hairstylelist = csv_to_list("hairstyles", antilist) + humanoidlist = csv_to_list("humanoids", antilist) + imagetypelist = csv_to_list("imagetypes", antilist) + joblist = csv_to_list("jobs", antilist) + lenslist = csv_to_list("lenses", antilist) + lightinglist = csv_to_list("lighting", antilist) + malefemalelist = csv_to_list(csvfilename="malefemale", antilist=antilist, skipheader=True, gender=gender) + manwomanlist = csv_to_list(csvfilename="manwoman", antilist=antilist, skipheader=True, gender=gender) + moodlist = csv_to_list("moods", antilist) + othertypelist = csv_to_list("othertypes", antilist) + poselist = csv_to_list("poses", antilist) + qualitylist = csv_to_list("quality", antilist) + shotsizelist = csv_to_list("shotsizes", antilist) + timeperiodlist = csv_to_list("timeperiods", antilist) + vomitlist = csv_to_list("vomit", antilist) foodlist = csv_to_list("foods", antilist) - genderdescriptionlist = csv_to_list(csvfilename="genderdescription",antilist=antilist,skipheader=True,gender=gender) + genderdescriptionlist = csv_to_list( + csvfilename="genderdescription", + antilist=antilist, + skipheader=True, + gender=gender + ) minilocationlist = csv_to_list("minilocations", antilist) minioutfitlist = csv_to_list("minioutfits", antilist) seasonlist = csv_to_list("seasons", antilist) @@ -2114,10 +2263,15 @@ def createpromptvariant(prompt = "", insanitylevel = 5, antivalues = "" , gender poemlinelist = csv_to_list("poemlines", antilist) songlinelist = csv_to_list("songlines", antilist) musicgenrelist = csv_to_list("musicgenres", antilist) - manwomanrelationlist = csv_to_list(csvfilename="manwomanrelations",antilist=antilist,skipheader=True,gender=gender) + manwomanrelationlist = csv_to_list( + csvfilename="manwomanrelations", + antilist=antilist, + skipheader=True, + gender=gender + ) waterlocationlist = csv_to_list("waterlocations", antilist) containerlist = csv_to_list("containers", antilist) - firstnamelist = csv_to_list(csvfilename="firstnames",antilist=antilist,skipheader=True,gender=gender) + firstnamelist = csv_to_list(csvfilename="firstnames", antilist=antilist, skipheader=True, gender=gender) floralist = csv_to_list("flora", antilist) printlist = csv_to_list("prints", antilist) patternlist = csv_to_list("patterns", antilist) @@ -2125,56 +2279,48 @@ def createpromptvariant(prompt = "", insanitylevel = 5, antivalues = "" , gender humanlist = fictionallist + nonfictionallist + humanoidlist + malefemalelist + manwomanlist + manwomanrelationlist objecttotallist = objectlist + buildinglist + vehiclelist + foodlist + spacelist + floralist + containerlist - outfitprinttotallist = objecttotallist + locationlist + colorlist + musicgenrelist + seasonlist + animallist + patternlist + outfitprinttotallist = objecttotallist + locationlist + colorlist + musicgenrelist + seasonlist + animallist \ + + patternlist # build artists list artistlist = [] # create artist list to use in the code, maybe based on category or personal lists - if(artists != "all" and artists != "none" and artists.startswith("personal_artists") == False and artists.startswith("personal artists") == False): - artistlist = artist_category_csv_to_list("artists_and_category",artists) - elif(artists.startswith("personal_artists") == True or artists.startswith("personal artists") == True): - artists = artists.replace(" ","_",-1) # add underscores back in - artistlist = csv_to_list(artists,antilist,"./userfiles/") - elif(artists != "none"): - artistlist = csv_to_list("artists",antilist) + if artists != "all" and artists != "none" and artists.startswith("personal_artists") is False \ + and artists.startswith("personal artists") is False: + artistlist = artist_category_csv_to_list("artists_and_category", artists) + elif artists.startswith("personal_artists") is True or artists.startswith("personal artists") is True: + artists = artists.replace(" ", "_", -1) # add underscores back in + artistlist = csv_to_list(artists, antilist, "./userfiles/") + elif artists != "none": + artistlist = csv_to_list("artists", antilist) # create special artists lists, used in templates - fantasyartistlist = artist_category_csv_to_list("artists_and_category","fantasy") - popularartistlist = artist_category_csv_to_list("artists_and_category","popular") - romanticismartistlist = artist_category_csv_to_list("artists_and_category","romanticism") - photographyartistlist = artist_category_csv_to_list("artists_and_category","photography") - + fantasyartistlist = artist_category_csv_to_list("artists_and_category", "fantasy") + popularartistlist = artist_category_csv_to_list("artists_and_category", "popular") + romanticismartistlist = artist_category_csv_to_list("artists_and_category", "romanticism") + photographyartistlist = artist_category_csv_to_list("artists_and_category", "photography") # add any other custom lists - stylestiloralist = csv_to_list("styles_ti_lora",antilist,"./userfiles/") - generatestyle = bool(stylestiloralist) # True of not empty - - custominputprefixlist = csv_to_list("custom_input_prefix",antilist,"./userfiles/") - generatecustominputprefix = bool(custominputprefixlist) # True of not empty - - custominputmidlist = csv_to_list("custom_input_mid",antilist,"./userfiles/") - generatecustominputmid = bool(custominputmidlist) # True of not empty - - custominputsuffixlist = csv_to_list("custom_input_suffix",antilist,"./userfiles/") - generatecustominputsuffix = bool(custominputsuffixlist) # True of not empty - - customsubjectslist = csv_to_list("custom_subjects",antilist,"./userfiles/") + stylestiloralist = csv_to_list("styles_ti_lora", antilist, "./userfiles/") + custominputprefixlist = csv_to_list("custom_input_prefix", antilist, "./userfiles/") + custominputmidlist = csv_to_list("custom_input_mid", antilist, "./userfiles/") + custominputsuffixlist = csv_to_list("custom_input_suffix", antilist, "./userfiles/") + customsubjectslist = csv_to_list("custom_subjects", antilist, "./userfiles/") # special lists - backgroundtypelist = csv_to_list("backgroundtypes", antilist,"./csvfiles/special_lists/") - insideshotlist = csv_to_list("insideshots", antilist,"./csvfiles/special_lists/") - photoadditionlist = csv_to_list("photoadditions", antilist,"./csvfiles/special_lists/") - buildhairlist = csv_to_list("buildhair", antilist,"./csvfiles/special_lists/") - buildoutfitlist = csv_to_list("buildoutfit", antilist,"./csvfiles/special_lists/") - objectadditionslist = csv_to_list("objectadditions", antilist,"./csvfiles/special_lists/") - humanadditionlist = csv_to_list("humanadditions", antilist,"./csvfiles/special_lists/") - animaladditionlist = csv_to_list("animaladditions", antilist,"./csvfiles/special_lists/") - buildaccessorielist = csv_to_list("buildaccessorie", antilist,"./csvfiles/special_lists/") - minilocationadditionslist = csv_to_list("minilocationadditions", antilist,"./csvfiles/special_lists/") - overalladditionlist = csv_to_list("overalladditions", antilist,"./csvfiles/special_lists/") - imagetypemodelist = csv_to_list("imagetypemodes", antilist,"./csvfiles/special_lists/") - miniactivitylist = csv_to_list("miniactivity", antilist,"./csvfiles/special_lists/") - + backgroundtypelist = csv_to_list("backgroundtypes", antilist, "./csvfiles/special_lists/") + insideshotlist = csv_to_list("insideshots", antilist, "./csvfiles/special_lists/") + photoadditionlist = csv_to_list("photoadditions", antilist, "./csvfiles/special_lists/") + buildhairlist = csv_to_list("buildhair", antilist, "./csvfiles/special_lists/") + buildoutfitlist = csv_to_list("buildoutfit", antilist, "./csvfiles/special_lists/") + objectadditionslist = csv_to_list("objectadditions", antilist, "./csvfiles/special_lists/") + humanadditionlist = csv_to_list("humanadditions", antilist, "./csvfiles/special_lists/") + animaladditionlist = csv_to_list("animaladditions", antilist, "./csvfiles/special_lists/") + buildaccessorielist = csv_to_list("buildaccessorie", antilist, "./csvfiles/special_lists/") + minilocationadditionslist = csv_to_list("minilocationadditions", antilist, "./csvfiles/special_lists/") + overalladditionlist = csv_to_list("overalladditions", antilist, "./csvfiles/special_lists/") + imagetypemodelist = csv_to_list("imagetypemodes", antilist, "./csvfiles/special_lists/") + miniactivitylist = csv_to_list("miniactivity", antilist, "./csvfiles/special_lists/") prompt = prompt.replace(",", " , ") prompt = prompt.replace("(", " ( ") @@ -2184,237 +2330,201 @@ def createpromptvariant(prompt = "", insanitylevel = 5, antivalues = "" , gender prompt = prompt.replace("|", " | ") prompt = prompt.replace(":", " : ") - prompt = " " + prompt + prompt = f' {prompt}' # store the (sort of) original prompt originalprompt = prompt - ### Get all combinations of 1 to 4 consecutive words - + # Get all combinations of 1 to 4 consecutive words words = prompt.split() num_words = len(words) - + combinations_list = [] - + for length in range(1, 5): # Generate combinations of length 1 to 4 for start_idx in range(num_words - length + 1): end_idx = start_idx + length combination = ' '.join(words[start_idx:end_idx]) combinations_list.append(combination) - + maxamountofruns = 4 runs = 0 - if(insanitylevel != 0): + if insanitylevel != 0: print("") print("Creating a prompt variation") print("") - while(originalprompt == prompt and runs != maxamountofruns): + while originalprompt == prompt and runs != maxamountofruns: for combination in combinations_list: - lowercase_combination = combination.lower() - combination = " " + combination + " " - - # some rare changes if needed - if lowercase_combination in [x.lower() for x in humanlist] and chance_roll(insanitylevel, "rare"): - prompt = prompt.replace(combination," -human- ") - - if lowercase_combination in [x.lower() for x in objecttotallist] and chance_roll(insanitylevel, "rare"): - prompt = prompt.replace(combination," -objecttotal- ") - - if lowercase_combination in [x.lower() for x in artistlist] and chance_roll(insanitylevel, "rare"): - prompt = prompt.replace(combination," -artist- ") - - - if lowercase_combination in [x.lower() for x in colorlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -color- ") - - if lowercase_combination in [x.lower() for x in animallist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -animal- ") - - if lowercase_combination in [x.lower() for x in objectlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -object- ") - - if lowercase_combination in [x.lower() for x in fictionallist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -fictional- ") - - - if lowercase_combination in [x.lower() for x in nonfictionallist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -nonfictional- ") - - - #if lowercase_combination in [x.lower() for x in conceptsuffixlist] and chance_roll(insanitylevel, "uncommon"): - # prompt = prompt.replace(combination," -conceptsuffix- ") - - - if lowercase_combination in [x.lower() for x in buildinglist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -building- ") - - - if lowercase_combination in [x.lower() for x in vehiclelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -vehicle- ") - - - if lowercase_combination in [x.lower() for x in outfitlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -outfit- ") - - - if lowercase_combination in [x.lower() for x in locationlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -location- ") - - - if lowercase_combination in [x.lower() for x in accessorielist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -accessory- ") - - - if lowercase_combination in [x.lower() for x in artmovementlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -artmovement- ") - - - if lowercase_combination in [x.lower() for x in bodytypelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -bodytype- ") - - - if lowercase_combination in [x.lower() for x in cameralist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -camera- ") - - - if lowercase_combination in [x.lower() for x in colorschemelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -colorscheme- ") - - - #if lowercase_combination in [x.lower() for x in conceptprefixlist] and chance_roll(insanitylevel, "uncommon"): - # prompt = prompt.replace(combination," -conceptprefix- ") - - - if lowercase_combination in [x.lower() for x in culturelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -culture- ") - - - if lowercase_combination in [x.lower() for x in descriptorlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -descriptor- ") - - if lowercase_combination in [x.lower() for x in directionlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -direction- ") - - if lowercase_combination in [x.lower() for x in emojilist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -emoji- ") - - if lowercase_combination in [x.lower() for x in eventlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -event- ") - - if lowercase_combination in [x.lower() for x in focuslist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -focus- ") - - if lowercase_combination in [x.lower() for x in greatworklist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -greatwork- ") - - if lowercase_combination in [x.lower() for x in haircolorlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -haircolor- ") - - if lowercase_combination in [x.lower() for x in hairstylelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -hairstyle- ") - - if lowercase_combination in [x.lower() for x in directionlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -direction- ") - - if lowercase_combination in [x.lower() for x in humanoidlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -humanoid- ") - - if lowercase_combination in [x.lower() for x in joblist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -job- ") - - if lowercase_combination in [x.lower() for x in lenslist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -lens- ") - if lowercase_combination in [x.lower() for x in lightinglist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -lighting- ") - if lowercase_combination in [x.lower() for x in malefemalelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -malefemale- ") - if lowercase_combination in [x.lower() for x in manwomanlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -manwoman- ") - if lowercase_combination in [x.lower() for x in moodlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -mood- ") - if lowercase_combination in [x.lower() for x in othertypelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -othertype- ") - if lowercase_combination in [x.lower() for x in poselist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -pose- ") - if lowercase_combination in [x.lower() for x in qualitylist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -quality- ") - if lowercase_combination in [x.lower() for x in shotsizelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -shotsize- ") - if lowercase_combination in [x.lower() for x in timeperiodlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -timeperiod- ") - if lowercase_combination in [x.lower() for x in vomitlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -vomit- ") - if lowercase_combination in [x.lower() for x in foodlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -food- ") - if lowercase_combination in [x.lower() for x in genderdescriptionlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -genderdescription- ") - if lowercase_combination in [x.lower() for x in minilocationlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -minilocation- ") - if lowercase_combination in [x.lower() for x in minioutfitlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -minioutfit- ") - if lowercase_combination in [x.lower() for x in lenslist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -lens- ") - if lowercase_combination in [x.lower() for x in seasonlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -season- ") - if lowercase_combination in [x.lower() for x in imagetypequalitylist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -imagetypequality- ") - if lowercase_combination in [x.lower() for x in rpgclasslist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -rpgclass- ") - if lowercase_combination in [x.lower() for x in brandlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -brand- ") - if lowercase_combination in [x.lower() for x in spacelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -space- ") - if lowercase_combination in [x.lower() for x in poemlinelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -poemline- ") - if lowercase_combination in [x.lower() for x in songlinelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -songline- ") - if lowercase_combination in [x.lower() for x in musicgenrelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -musicgenre- ") - if lowercase_combination in [x.lower() for x in manwomanrelationlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -manwomanrelation- ") - if lowercase_combination in [x.lower() for x in waterlocationlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -waterlocation- ") - if lowercase_combination in [x.lower() for x in containerlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -container- ") - if lowercase_combination in [x.lower() for x in firstnamelist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -firstname- ") - if lowercase_combination in [x.lower() for x in floralist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -flora- ") - if lowercase_combination in [x.lower() for x in printlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -print- ") - if lowercase_combination in [x.lower() for x in miniactivitylist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -miniactivity- ") - if lowercase_combination in [x.lower() for x in patternlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -pattern- ") - if lowercase_combination in [x.lower() for x in chairlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -chair- ") - - - if lowercase_combination in [x.lower() for x in fantasyartistlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -artistfantasy- ") - if lowercase_combination in [x.lower() for x in popularartistlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -artistpopular- ") - if lowercase_combination in [x.lower() for x in romanticismartistlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -artistromanticism- ") - if lowercase_combination in [x.lower() for x in photographyartistlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -artistphotography- ") - - if lowercase_combination in [x.lower() for x in stylestiloralist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -styletilora- ") - if lowercase_combination in [x.lower() for x in waterlocationlist] and chance_roll(insanitylevel, "uncommon"): - prompt = prompt.replace(combination," -waterlocation- ") + comb = combination.lower() + combination = f' {combination} ' + + # some rare changes if needed + if comb in [x.lower() for x in humanlist] and chance_roll(insanitylevel, "rare"): + prompt = prompt.replace(combination, " -human- ") + if comb in [x.lower() for x in objecttotallist] and chance_roll(insanitylevel, "rare"): + prompt = prompt.replace(combination, " -objecttotal- ") + if comb in [x.lower() for x in artistlist] and chance_roll(insanitylevel, "rare"): + prompt = prompt.replace(combination, " -artist- ") + if comb in [x.lower() for x in colorlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -color- ") + if comb in [x.lower() for x in animallist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -animal- ") + if comb in [x.lower() for x in objectlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -object- ") + if comb in [x.lower() for x in fictionallist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -fictional- ") + if comb in [x.lower() for x in nonfictionallist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -nonfictional- ") + if comb in [x.lower() for x in buildinglist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -building- ") + if comb in [x.lower() for x in vehiclelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -vehicle- ") + if comb in [x.lower() for x in outfitlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -outfit- ") + if comb in [x.lower() for x in locationlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -location- ") + if comb in [x.lower() for x in accessorielist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -accessory- ") + if comb in [x.lower() for x in artmovementlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -artmovement- ") + if comb in [x.lower() for x in bodytypelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -bodytype- ") + if comb in [x.lower() for x in cameralist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -camera- ") + if comb in [x.lower() for x in colorschemelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -colorscheme- ") + if comb in [x.lower() for x in culturelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -culture- ") + if comb in [x.lower() for x in descriptorlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -descriptor- ") + if comb in [x.lower() for x in directionlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -direction- ") + if comb in [x.lower() for x in emojilist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -emoji- ") + if comb in [x.lower() for x in eventlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -event- ") + if comb in [x.lower() for x in focuslist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -focus- ") + if comb in [x.lower() for x in greatworklist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -greatwork- ") + if comb in [x.lower() for x in haircolorlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -haircolor- ") + if comb in [x.lower() for x in hairstylelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -hairstyle- ") + if comb in [x.lower() for x in directionlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -direction- ") + if comb in [x.lower() for x in humanoidlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -humanoid- ") + if comb in [x.lower() for x in joblist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -job- ") + if comb in [x.lower() for x in lenslist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -lens- ") + if comb in [x.lower() for x in lightinglist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -lighting- ") + if comb in [x.lower() for x in malefemalelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -malefemale- ") + if comb in [x.lower() for x in manwomanlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -manwoman- ") + if comb in [x.lower() for x in moodlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -mood- ") + if comb in [x.lower() for x in othertypelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -othertype- ") + if comb in [x.lower() for x in poselist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -pose- ") + if comb in [x.lower() for x in qualitylist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -quality- ") + if comb in [x.lower() for x in shotsizelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -shotsize- ") + if comb in [x.lower() for x in timeperiodlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -timeperiod- ") + if comb in [x.lower() for x in vomitlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -vomit- ") + if comb in [x.lower() for x in foodlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -food- ") + if comb in [x.lower() for x in genderdescriptionlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -genderdescription- ") + if comb in [x.lower() for x in minilocationlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -minilocation- ") + if comb in [x.lower() for x in minioutfitlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -minioutfit- ") + if comb in [x.lower() for x in lenslist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -lens- ") + if comb in [x.lower() for x in seasonlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -season- ") + if comb in [x.lower() for x in imagetypequalitylist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -imagetypequality- ") + if comb in [x.lower() for x in rpgclasslist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -rpgclass- ") + if comb in [x.lower() for x in brandlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -brand- ") + if comb in [x.lower() for x in spacelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -space- ") + if comb in [x.lower() for x in poemlinelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -poemline- ") + if comb in [x.lower() for x in songlinelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -songline- ") + if comb in [x.lower() for x in musicgenrelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -musicgenre- ") + if comb in [x.lower() for x in manwomanrelationlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -manwomanrelation- ") + if comb in [x.lower() for x in waterlocationlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -waterlocation- ") + if comb in [x.lower() for x in containerlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -container- ") + if comb in [x.lower() for x in firstnamelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -firstname- ") + if comb in [x.lower() for x in floralist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -flora- ") + if comb in [x.lower() for x in printlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -print- ") + if comb in [x.lower() for x in miniactivitylist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -miniactivity- ") + if comb in [x.lower() for x in patternlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -pattern- ") + if comb in [x.lower() for x in chairlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -chair- ") + if comb in [x.lower() for x in fantasyartistlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -artistfantasy- ") + if comb in [x.lower() for x in popularartistlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -artistpopular- ") + if comb in [x.lower() for x in romanticismartistlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -artistromanticism- ") + if comb in [x.lower() for x in photographyartistlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -artistphotography- ") + if comb in [x.lower() for x in stylestiloralist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -styletilora- ") + if comb in [x.lower() for x in waterlocationlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -waterlocation- ") + if comb in [x.lower() for x in imagetypemodelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -imagetypemodes- ") + if comb in [x.lower() for x in buildaccessorielist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -buildaccessorie- ") + if comb in [x.lower() for x in buildoutfitlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -buildoutfit- ") + if comb in [x.lower() for x in buildhairlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -buildhair- ") + if comb in [x.lower() for x in insideshotlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -insideshots- ") + if comb in [x.lower() for x in photoadditionlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -photoadditions- ") + if comb in [x.lower() for x in backgroundtypelist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -backgroundtypes- ") + if comb in [x.lower() for x in customsubjectslist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -custom_subjects- ") + if comb in [x.lower() for x in custominputsuffixlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -custom_input_suffix- ") + if comb in [x.lower() for x in custominputmidlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -custom_input_mid- ") + if comb in [x.lower() for x in custominputprefixlist] and chance_roll(insanitylevel, "uncommon"): + prompt = prompt.replace(combination, " -custom_input_prefix- ") runs += 1 - - prompt = prompt.replace(" :", ":") prompt = prompt.replace(": ", ":") completeprompt = prompt - - while ( "-color-" in completeprompt or "-material-" in completeprompt or @@ -2469,9 +2579,9 @@ def createpromptvariant(prompt = "", insanitylevel = 5, antivalues = "" , gender "-poemline-" in completeprompt or "-songline-" in completeprompt or "-greatwork-" in completeprompt or - "-artistfantasy-" in completeprompt or - "-artistpopular-" in completeprompt or - "-artistromanticism-" in completeprompt or + "-artistfantasy-" in completeprompt or + "-artistpopular-" in completeprompt or + "-artistromanticism-" in completeprompt or "-artistphotography-" in completeprompt or "-emoji-" in completeprompt or "-timeperiod-" in completeprompt or @@ -2491,97 +2601,309 @@ def createpromptvariant(prompt = "", insanitylevel = 5, antivalues = "" , gender "-flora-" in completeprompt or "-print-" in completeprompt or "-miniactivity-" in completeprompt or - "-pattern-" in completeprompt): - allwildcardslistnohybrid = [ "-color-","-object-", "-animal-", "-fictional-","-nonfictional-","-building-","-vehicle-","-location-","-conceptprefix-","-food-","-haircolor-","-hairstyle-","-job-", "-accessory-", "-humanoid-", "-manwoman-", "-human-", "-colorscheme-", "-mood-", "-genderdescription-", "-artmovement-", "-malefemale-", "-bodytype-", "-minilocation-", "-minilocationaddition-", "-pose-", "-season-", "-minioutfit-", "-elaborateoutfit-", "-minivomit-", "-vomit-", "-rpgclass-", "-subjectfromfile-", "-brand-", "-space-", "-artist-", "-imagetype-", "-othertype-", "-quality-", "-lighting-", "-camera-", "-lens-","-imagetypequality-", "-poemline-", "-songline-", "-greatwork-", "-artistfantasy-", "-artistpopular-", "-artistromanticism-", "-artistphotography-", "-emoji-", "-timeperiod-", "-shotsize-", "-musicgenre-", "-animaladdition-", "-objectaddition-", "-humanaddition-", "-overalladdition-", "-focus-", "-direction-", "-styletilora-", "-manwomanrelation-", "-waterlocation-", "-container-", "-firstname-", "-flora-", "-print-", "-miniactivity-", "-pattern-"] - allwildcardslistnohybridlists = [colorlist, objectlist, animallist, fictionallist, nonfictionallist, buildinglist, vehiclelist, locationlist,conceptprefixlist,foodlist,haircolorlist, hairstylelist,joblist, accessorielist, humanoidlist, manwomanlist, humanlist, colorschemelist, moodlist, genderdescriptionlist, artmovementlist, malefemalelist, bodytypelist, minilocationlist, minilocationadditionslist, poselist, seasonlist, minioutfitlist, elaborateoutfitlist, minivomitlist, vomitlist, rpgclasslist, customsubjectslist, brandlist, spacelist, artistlist, imagetypelist, othertypelist, qualitylist, lightinglist, cameralist, lenslist, imagetypequalitylist, poemlinelist, songlinelist, greatworklist, fantasyartistlist, popularartistlist, romanticismartistlist, photographyartistlist, emojilist, timeperiodlist, shotsizelist, musicgenrelist, animaladditionlist, objectadditionslist, humanadditionlist, overalladditionlist, focuslist, directionlist, stylestiloralist, manwomanrelationlist, waterlocationlist, containerlist, firstnamelist, floralist, printlist, miniactivitylist, patternlist] - - allwildcardslistwithhybrid = ["-material-", "-descriptor-", "-outfit-", "-conceptsuffix-","-culture-", "-objecttotal-", "-outfitprinttotal-"] - allwildcardslistwithhybridlists = [materiallist, descriptorlist,outfitlist,conceptsuffixlist,culturelist, objecttotallist, outfitprinttotallist] - - - # keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) - for wildcard in allwildcardslistnohybrid: - attachedlist = allwildcardslistnohybridlists[allwildcardslistnohybrid.index(wildcard)] - completeprompt = replacewildcard(completeprompt, insanitylevel, wildcard, attachedlist,False, advancedprompting) - - - - for wildcard in allwildcardslistwithhybrid: - attachedlist = allwildcardslistwithhybridlists[allwildcardslistwithhybrid.index(wildcard)] - completeprompt = replacewildcard(completeprompt, insanitylevel, wildcard, attachedlist,True, advancedprompting) - - - - - # clean it up - completeprompt = cleanup(completeprompt, advancedprompting) - - + "-chair-" in completeprompt or + "-pattern-" in completeprompt or + "-artistfantasy-" in completeprompt or + "-artistpopular-" in completeprompt or + "-artistromanticism-" in completeprompt or + "-artistphotography-" in completeprompt or + "-styletilora-" in completeprompt or + "-waterlocation-" in completeprompt or + "-imagetypemodes-" in completeprompt or + "-buildaccessorie-" in completeprompt or + "-buildoutfit-" in completeprompt or + "-buildhair-" in completeprompt or + "-insideshots-" in completeprompt or + "-photoadditions-" in completeprompt or + "-backgroundtypes-" in completeprompt or + "-custom_subjects-" in completeprompt or + "-custom_input_suffix-" in completeprompt or + "-custom_input_mid-" in completeprompt or + "-custom_input_prefix-" in completeprompt + ): + allwildcardslistnohybrid = [ + "-color-", + "-object-", + "-animal-", + "-fictional-", + "-nonfictional-", + "-building-", + "-vehicle-", + "-location-", + "-conceptprefix-", + "-food-", + "-haircolor-", + "-hairstyle-", + "-job-", + "-accessory-", + "-humanoid-", + "-manwoman-", + "-human-", + "-colorscheme-", + "-mood-", + "-genderdescription-", + "-artmovement-", + "-malefemale-", + "-bodytype-", + "-minilocation-", + "-minilocationaddition-", + "-pose-", + "-season-", + "-minioutfit-", + "-elaborateoutfit-", + "-minivomit-", + "-vomit-", + "-rpgclass-", + "-subjectfromfile-", + "-brand-", + "-space-", + "-artist-", + "-imagetype-", + "-othertype-", + "-quality-", + "-lighting-", + "-camera-", + "-lens-", + "-imagetypequality-", + "-poemline-", + "-songline-", + "-greatwork-", + "-artistfantasy-", + "-artistpopular-", + "-artistromanticism-", + "-artistphotography-", + "-emoji-", + "-timeperiod-", + "-shotsize-", + "-musicgenre-", + "-animaladdition-", + "-objectaddition-", + "-humanaddition-", + "-overalladdition-", + "-focus-", + "-direction-", + "-styletilora-", + "-manwomanrelation-", + "-waterlocation-", + "-container-", + "-firstname-", + "-flora-", + "-print-", + "-miniactivity-", + "-pattern-", + "-chair-", + "-pattern-", + "-artistfantasy-", + "-artistpopular-", + "-artistromanticism-", + "-artistphotography-", + "-styletilora-", + "-waterlocation-", + "-imagetypemodes-", + "-buildaccessorie-", + "-buildoutfit-", + "-buildhair-", + "-insideshots-", + "-photoadditions-", + "-backgroundtypes-", + "-custom_subjects-", + "-custom_input_suffix-", + "-custom_input_mid-", + "-custom_input_prefix-" + ] + + allwildcardslistnohybridlists = [ + colorlist, + objectlist, + animallist, + fictionallist, + nonfictionallist, + buildinglist, + vehiclelist, + locationlist, + conceptprefixlist, + foodlist, + haircolorlist, + hairstylelist, + joblist, + accessorielist, + humanoidlist, + manwomanlist, + humanlist, + colorschemelist, + moodlist, + genderdescriptionlist, + artmovementlist, + malefemalelist, + bodytypelist, + minilocationlist, + minilocationadditionslist, + poselist, + seasonlist, + minioutfitlist, + elaborateoutfitlist, + minivomitlist, + vomitlist, + rpgclasslist, + customsubjectslist, + brandlist, + spacelist, + artistlist, + imagetypelist, + othertypelist, + qualitylist, + lightinglist, + cameralist, + lenslist, + imagetypequalitylist, + poemlinelist, + songlinelist, + greatworklist, + fantasyartistlist, + popularartistlist, + romanticismartistlist, + photographyartistlist, + emojilist, + timeperiodlist, + shotsizelist, + musicgenrelist, + animaladditionlist, + objectadditionslist, + humanadditionlist, + overalladditionlist, + focuslist, + directionlist, + stylestiloralist, + manwomanrelationlist, + waterlocationlist, + containerlist, + firstnamelist, + floralist, + printlist, + miniactivitylist, + patternlist, + chairlist, + fantasyartistlist, + popularartistlist, + romanticismartistlist, + photographyartistlist, + stylestiloralist, + waterlocationlist, + imagetypemodelist, + buildaccessorielist, + buildoutfitlist, + buildhairlist, + insideshotlist, + photoadditionlist, + backgroundtypelist, + customsubjectslist, + custominputsuffixlist, + custominputmidlist, + custominputprefixlist + ] + + allwildcardslistwithhybrid = [ + "-material-", + "-descriptor-", + "-outfit-", + "-conceptsuffix-", + "-culture-", + "-objecttotal-", + "-outfitprinttotal-" + ] + + allwildcardslistwithhybridlists = [ + materiallist, + descriptorlist, + outfitlist, + conceptsuffixlist, + culturelist, + objecttotallist, + outfitprinttotallist + ] + # keywordsinstring = any(word.lower() in givensubject.lower() for word in keywordslist) + for wildcard in allwildcardslistnohybrid: + attachedlist = allwildcardslistnohybridlists[allwildcardslistnohybrid.index(wildcard)] + completeprompt = replacewildcard( + completeprompt, + insanitylevel, + wildcard, + attachedlist, + False, + advancedprompting + ) + for wildcard in allwildcardslistwithhybrid: + attachedlist = allwildcardslistwithhybridlists[allwildcardslistwithhybrid.index(wildcard)] + completeprompt = replacewildcard( + completeprompt, + insanitylevel, + wildcard, + attachedlist, + True, + advancedprompting + ) + # clean it up + completeprompt = cleanup(completeprompt, advancedprompting) return completeprompt - # function -def replacewildcard(completeprompt, insanitylevel, wildcard,listname, activatehybridorswap, advancedprompting): - if(len(listname) == 0): +def replacewildcard(completeprompt, insanitylevel, wildcard, listname, activatehybridorswap, advancedprompting): + if len(listname) == 0: # handling empty lists - completeprompt = completeprompt.replace(wildcard, "",1) + completeprompt = completeprompt.replace(wildcard, "", 1) else: - while wildcard in completeprompt: - if(unique_dist(insanitylevel) and activatehybridorswap == True and len(listname)>2 and advancedprompting==True): + if unique_dist(insanitylevel) and activatehybridorswap is True and len(listname) > 2 \ + and advancedprompting is True: hybridorswaplist = ["hybrid", "swap"] hybridorswap = random.choice(hybridorswaplist) replacementvalue = random.choice(listname) listname.remove(replacementvalue) - hybridorswapreplacementvalue = "[" + replacementvalue - - if(hybridorswap == "hybrid"): - replacementvalue = random.choice(listname) - listname.remove(replacementvalue) - hybridorswapreplacementvalue += "|" + replacementvalue + "] " - if(hybridorswap == "swap"): - replacementvalue = random.choice(listname) - listname.remove(replacementvalue) - hybridorswapreplacementvalue += ":" + replacementvalue + ":" + str(random.randint(1,20)) + "] " - - completeprompt = completeprompt.replace(wildcard, hybridorswapreplacementvalue,1) - - #if list is not empty - if(bool(listname)): + hybridorswapreplacementvalue = f'[{replacementvalue}' + + if hybridorswap == "hybrid": + replacementvalue = random.choice(listname) + listname.remove(replacementvalue) + hybridorswapreplacementvalue += f'|{replacementvalue}] ' + if hybridorswap == "swap": + replacementvalue = random.choice(listname) + listname.remove(replacementvalue) + hybridorswapreplacementvalue += f':{replacementvalue}:{random.randint(1, 20)}]' + + completeprompt = completeprompt.replace(wildcard, hybridorswapreplacementvalue, 1) + + # if list is not empty + if bool(listname): replacementvalue = random.choice(listname) listname.remove(replacementvalue) - if(wildcard == "-artist-"): - replacementvalue = "art by " + replacementvalue - + if wildcard == "-artist-": + replacementvalue = f'art by {replacementvalue}' else: replacementvalue = "" - - completeprompt = completeprompt.replace(wildcard, replacementvalue,1) - + completeprompt = completeprompt.replace(wildcard, replacementvalue, 1) return completeprompt + def replace_match(match): # Extract the first word from the match words = match.group(0)[1:-1].split('|') return words[0] -def cleanup(completeprompt, advancedprompting): +def cleanup(completeprompt, advancedprompting): # first, move LoRA's to the back dynamically - # Find all occurrences of text between < and > using regex allLoRA = re.findall(r"<[^>]+>", completeprompt) # Remove the extracted matches from completeprompt completeprompt = re.sub(r"<[^>]+>", "", completeprompt) - # if we are not using advanced prompting, remove any hybrid stuff: - if(advancedprompting==False): + if advancedprompting is False: hybridpattern = r'\[\w+\|\w+\]' # Replace the matched pattern with the first word in the group completeprompt = re.sub(hybridpattern, replace_match, completeprompt) @@ -2592,11 +2914,11 @@ def cleanup(completeprompt, advancedprompting): completeprompt = completeprompt.replace("|", " ") # sometimes if there are not enough artist, we get left we things formed as (:1.2) - completeprompt = re.sub('\(\:\d+\.\d+\)', '', completeprompt) + completeprompt = re.sub('\(\:\d+\.\d+\)', '', completeprompt) # all cleanup steps moved here completeprompt = re.sub('\[ ', '[', completeprompt) - completeprompt = re.sub('\[,', '[', completeprompt) + completeprompt = re.sub('\[,', '[', completeprompt) completeprompt = re.sub(' \]', ']', completeprompt) completeprompt = re.sub(' \|', '|', completeprompt) completeprompt = re.sub(' \"', '\"', completeprompt) @@ -2627,13 +2949,12 @@ def cleanup(completeprompt, advancedprompting): completeprompt = re.sub('of a,', 'of a', completeprompt) completeprompt = re.sub('of a of a', 'of a', completeprompt) - completeprompt = re.sub('(?= isGoodNumber or debugmode == 1): + print(f'This image has scored: {score} out of {isGoodNumber}') + if score >= isGoodNumber or debugmode == 1: foundgood = True print("Yay its good! Keeping this result.") else: runstodo = MaxRuns - Runs - 1 - print("Not a good result. Retrying for another " + str(runstodo) + " times or until the image is good enough.") + print('Not a good result.') + print(f'Retrying for another {runstodo} times or until the image is good enough.') - except ImportError: - foundgood = True # just continue :) + foundgood = True # just continue :) # handle the case where the module doesn't exist print("Could not find the stable-diffusion-webui-aesthetic-image-scorer extension.") print("Install this extension via the WebUI to use Quality Gate") pass else: - foundgood = True # If there is no quality gate, then everything is good. So we escape this loop - + foundgood = True # If there is no quality gate, then everything is good. So we escape this loop + Runs += 1 - if(foundgood == True): - break #Break the loop if we found something good. Or if we set it to good :) + if foundgood is True: + break # Break the loop if we found something good. Or if we set it to good :) - if(len(imagelist) > 0): + if len(imagelist) > 0: - if(foundgood == True): - if(qualitykeep == "keep used"): + if foundgood is True: + if qualitykeep == "keep used": print("Removing any other images generated this run (if any).") else: - if(qualitymode == "highest"): + if qualitymode == "highest": print("") print("Stopped trying, keeping the best image we had so far.") print("") @@ -255,35 +266,32 @@ def call_txt2img(passingprompt,size,upscale,debugmode,filename="",model = "curre print("Eh, its all pretty bad. Not going forward with any image.") print("") - # Get the index of the first occurrence of the maximum value in the list - #if(qualitymode == "highest" or (qualitymode != "highest" and foundgood == True)): indexofimagetokeep = scoredeclist.index(max(scoredeclist)) - outputTXT2IMGFull = imagelist[indexofimagetokeep] #store the image to keep in here, so we can pass it along + outputTXT2IMGFull = imagelist[indexofimagetokeep] # store the image to keep in here, so we can pass it along pnginfo = pnginfolist[indexofimagetokeep] usedseed = seedlist[indexofimagetokeep] - usedwidht = widthlist[indexofimagetokeep] + usedwidht = widthlist[indexofimagetokeep] usedheight = heightlist[indexofimagetokeep] imagethatiskept = imagelist[indexofimagetokeep] imagelist.pop(indexofimagetokeep) - - - #remove all other images - if(qualitykeep == "keep used"): + + # remove all other images + if qualitykeep == "keep used": for imagelocation in imagelist: os.remove(imagelocation) - if(foundgood == False and qualitymode != "highest"): + if foundgood is False and qualitymode != "highest": continuewithnextpart = False - if(imagethatiskept != "" and qualitykeep == "keep used"): + if imagethatiskept != "" and qualitykeep == "keep used": os.remove(imagethatiskept) - - # We have done everything, but if we want to run Hires fix from the quality gate, we are going to have to do it again. But this time a little easier. + # We have done everything, but if we want to run Hires fix from the quality gate, + # we are going to have to do it again. But this time a little easier. # We do have the check wether we want to run hiresfix first - if(qualityhiresfix == True and upscale == False and continuewithnextpart == True): + if qualityhiresfix is True and upscale is False and continuewithnextpart is True: print("Quality Gate hires fix was enabled, but no hires fix settings were given.") - if(qualityhiresfix == True and upscale == True and continuewithnextpart == True): + if qualityhiresfix is True and upscale is True and continuewithnextpart is True: print("Going to run the chosen image with hiresfix") payload["seed"] = usedseed @@ -294,79 +302,76 @@ def call_txt2img(passingprompt,size,upscale,debugmode,filename="",model = "curre # make the filename unique for hiresfix addrun = "_hiresfix" filenamefull = filename + addrun - outputTXT2IMGFull = '{}{}{}'.format(outputTXT2IMGfolder,filenamefull,outputTXT2IMGpng) + outputTXT2IMGFull = f'{outputTXT2IMGfolder}{filenamefull}{outputTXT2IMGpng}' # If we don't get an image back, we want to retry a few times. Max 3 times for i in range(4): response = requests.post(url=f'{url}/sdapi/v1/txt2img', json=payload) r = response.json() - if('images' in r): - break # this means if we have the images object, then we "break" out of the for loop. + if 'images' in r: + break # this means if we have the images object, then we "break" out of the for loop. else: - if(i == 3): + if i == 3: print("If this keeps happening: Is WebUI started with --api enabled?") print("") raise ValueError("API has not been responding after several retries. Stopped processing.") print("") - print("We haven't received an image from the API. Maybe something went wrong. Will retry after waiting a bit.") - - - time.sleep(10 * (i+1) ) # incremental waiting time - - + print("We haven't received an image from the API. Maybe something went wrong.") + print("Will retry after waiting a bit.") + time.sleep(10 * (i + 1)) # incremental waiting time for i in r['images']: - image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0]))) + image = Image.open(io.BytesIO(base64.b64decode(i.split(",", 1)[0]))) + + png_payload = {"image": f'data:image/png;base64,{i}'} - png_payload = { - "image": "data:image/png;base64," + i - } response2 = requests.post(url=f'{url}/sdapi/v1/png-info', json=png_payload) pnginfo = PngImagePlugin.PngInfo() pnginfo.add_text("parameters", response2.json().get("info")) image.save(outputTXT2IMGFull, pnginfo=pnginfo) - - - with open(outputTXT2IMGtxtFull,'w',encoding="utf8") as txt: - json_object = json.dumps(payload, indent = 4) + with open(outputTXT2IMGtxtFull, 'w', encoding="utf8") as txt: + json_object = json.dumps(payload, indent=4) txt.write(json_object) - return [outputTXT2IMGFull,pnginfo,continuewithnextpart] + return [outputTXT2IMGFull, pnginfo, continuewithnextpart] -def setsize(ratio,basesize, originalsize): - # prompt + size - if(originalsize == "all"): +def setsize(ratio, basesize, originalsize): + # prompt + size + if originalsize == "all": sizelist = ["portrait", "wide", "square"] ratio = random.choice(sizelist) - # from base ratio - if(ratio=='wide' and basesize != "1024"): - width = str(int(basesize) + 256) - height = basesize - elif(ratio=='wide' and basesize == "1024"): - width = "1152" - height = "896" - elif(ratio=='portrait' and basesize != "1024"): - width = basesize - height = str(int(basesize) + 256) - elif(ratio=='portrait' and basesize == "1024"): - width = "896" - height = "1152" - elif(ratio=='ultrawide'): - width = "1280" - height = "360" - elif(ratio=='ultraheight'): - width = "360" - height = "1280" - elif(ratio=='wild'): - width = str(round((random.randint(0,4) * 128) + (int(basesize) /2) ) ) # random value of 0 to 512 in steps of 128 + half of base size - height = str(round( (random.randint(0,4) * 128) + (int(basesize) /2) ) ) # random value of 0 to 512 in steps of 128 + half of base size - else: - width = basesize - height = basesize - return [width, height] \ No newline at end of file + # from base ratio + match ratio: + case "wide": + if basesize == "1024": + width = "1152" + height = "896" + else: + width = str(int(basesize) + 256) + height = basesize + case "portrait": + if basesize == "1024": + width = "896" + height = "1152" + else: + width = basesize + height = str(int(basesize) + 256) + case "ultrawide": + width = "1280" + height = "360" + case "ultraheight": + width = "360" + height = "1280" + case "wild": + width = height = str(round((random.randint(0, 4) * 128) + (int(basesize) / 2))) + case _: + width = basesize + height = basesize + + return [width, height] diff --git a/csv_reader.py b/csv_reader.py index 4066fbf..7ea436b 100644 --- a/csv_reader.py +++ b/csv_reader.py @@ -1,127 +1,131 @@ import csv -import random import os +import random import shutil + def random_read_from_csv(filename): script_dir = os.path.dirname(os.path.abspath(__file__)) # Script directory - full_path = os.path.join(script_dir, "./csvfiles/" ) - with open(full_path + filename + ".csv", "r",encoding="utf8") as csv_file: - csv_reader = csv.reader(csv_file) - output = (random.choice([line[0] for line in csv_reader])) - return output + full_path = os.path.join(script_dir, "./csvfiles/") + + with open(f'{full_path}{filename}.csv', "r", encoding="utf8") as csv_file: + csv_reader = csv.reader(csv_file) + return random.choice([line[0] for line in csv_reader]) + def add_from_csv(completeprompt, csvfilename, addcomma, prefix, suffix): - randomreadfromcsv = random_read_from_csv(csvfilename) - #print(csvfilename+ ": " + randomreadfromcsv) - addtoprompt = prefix + " " + randomreadfromcsv + " " + suffix - if(addcomma == 1): - return ", ".join([completeprompt,addtoprompt]) - return " ".join([completeprompt,addtoprompt]) - -def csv_to_list(csvfilename, antilist=[], directory="./csvfiles/", lowerandstrip=0, delimiter=";", listoflistmode = False, skipheader = False, gender = "all"): - userfilesdirectory = "./userfiles/" - userfileaddonname = csvfilename + "_addon.csv" - userfilereplacename = csvfilename + "_replace.csv" - csvlist = [] - script_dir = os.path.dirname(os.path.abspath(__file__)) - full_path = os.path.join(script_dir, directory ) - userfilesfolder = os.path.join(script_dir, userfilesdirectory ) - # check if there is a replace file - if(directory=="./csvfiles/" or directory=="./csvfiles/special_lists/" or directory=="./csvfiles/templates/"): - for filename in os.listdir(userfilesfolder): - if(filename == userfilereplacename): - # Just override the parameters, and let it run normally - full_path = os.path.join(script_dir, userfilesdirectory ) - csvfilename = csvfilename + "_replace" - - - # return empty list if we can't find the file. Build for antilist.csv - if(os.path.isfile(full_path + csvfilename + ".csv")): - with open(full_path + csvfilename + ".csv", "r", newline="",encoding="utf8") as file: - reader = csv.reader(file, delimiter=delimiter) - if(skipheader==True): - next(reader) - if(listoflistmode==True): - csvlist = list(reader) - else: - for row in reader: - value = row[0] - if( - (gender != "all" and row[1] == gender) - or gender == "all" - ): - if(value.lower().strip() not in antilist): - if(lowerandstrip == 1): - csvlist.append(row[0].lower().strip()) - else: - csvlist.append(row[0]) - - # do the add ons! - if(directory=="./csvfiles/" or directory=="./csvfiles/special_lists/"): - if(os.path.isfile(userfilesfolder + csvfilename + "_addon" + ".csv")): - with open(userfilesfolder + csvfilename + "_addon" + ".csv", "r", newline="",encoding="utf8") as file: - reader = csv.reader(file, delimiter=",") - if(skipheader==True): - next(reader) - if(listoflistmode==True): - csvlist.append(list(reader)) - else: - for row in reader: - value = row[0] - if( - (gender != "all" and row[1] == gender) - or gender == "all" - ): - if(value.lower().strip() not in antilist): - if(lowerandstrip == 1): - csvlist.append(row[0].lower().strip()) - else: - csvlist.append(row[0]) - - - # remove duplicates, but check only for lowercase stuff - deduplicated_list = [] - lowercase_elements = set() - if(listoflistmode==False): - for element in csvlist: - lowercase_element = element.lower() - if lowercase_element not in lowercase_elements: - lowercase_elements.add(lowercase_element) - deduplicated_list.append(element) - else: - deduplicated_list = csvlist - - return deduplicated_list - -def artist_category_csv_to_list(csvfilename,category): - csvlist = [] - script_dir = os.path.dirname(os.path.abspath(__file__)) - full_path = os.path.join(script_dir, "./csvfiles/" ) - with open(full_path + csvfilename + ".csv", "r", newline="",encoding="utf8") as file: - reader = csv.DictReader(file, delimiter=",") + randomreadfromcsv = random_read_from_csv(csvfilename) + addtoprompt = f'{prefix} {randomreadfromcsv} {suffix}' + + if addcomma == 1: + return ", ".join([completeprompt, addtoprompt]) + return " ".join([completeprompt, addtoprompt]) + + +def csv_to_list( + csvfilename, + antilist=[], + directory="./csvfiles/", + lowerandstrip=0, + delimiter=";", + listoflistmode=False, + skipheader=False, + gender="all" +): + userfilesdirectory = "./userfiles/" + userfileaddonname = f"{csvfilename}_addon.csv" + userfilereplacename = f"{csvfilename}_replace.csv" + csvlist = [] + script_dir = os.path.dirname(os.path.abspath(__file__)) + full_path = os.path.join(script_dir, directory) + userfilesfolder = os.path.join(script_dir, userfilesdirectory) + + # check if there is a replace file + if directory == "./csvfiles/" or directory == "./csvfiles/special_lists/" or directory == "./csvfiles/templates/": + for filename in os.listdir(userfilesfolder): + if filename == userfilereplacename: + # Just override the parameters, and let it run normally + full_path = os.path.join(script_dir, userfilesdirectory) + csvfilename = f'{csvfilename}_replace' + + # return empty list if we can't find the file. Build for antilist.csv + filename = f'{full_path}{csvfilename}.csv' + if os.path.isfile(filename): + with open(filename, "r", newline="", encoding="utf8") as file: + reader = csv.reader(file, delimiter=delimiter) + if skipheader is True: + next(reader) + if listoflistmode is True: + csvlist = list(reader) + else: for row in reader: - if(row[category] == "1"): - csvlist.append(row["Artist"]) - return csvlist + value = row[0] + if (gender != "all" and row[1] == gender) or gender == "all": + if value.lower().strip() not in antilist: + if lowerandstrip == 1: + csvlist.append(row[0].lower().strip()) + else: + csvlist.append(row[0]) + + # do the add ons! + if directory == "./csvfiles/" or directory == "./csvfiles/special_lists/": + filename = f'{userfilesfolder}{userfileaddonname}' + if os.path.isfile(filename): + with open(filename, "r", newline="", encoding="utf8") as file: + reader = csv.reader(file, delimiter=",") + if skipheader is True: + next(reader) + if listoflistmode is True: + csvlist.append(list(reader)) + else: + for row in reader: + value = row[0] + if (gender != "all" and row[1] == gender) or gender == "all": + if value.lower().strip() not in antilist: + if lowerandstrip == 1: + csvlist.append(row[0].lower().strip()) + else: + csvlist.append(row[0]) + + # remove duplicates, but check only for lowercase stuff + deduplicated_list = [] + lowercase_elements = set() + if listoflistmode is False: + for element in csvlist: + lowercase_element = element.lower() + if lowercase_element not in lowercase_elements: + lowercase_elements.add(lowercase_element) + deduplicated_list.append(element) + else: + deduplicated_list = csvlist + + return deduplicated_list +def artist_category_csv_to_list(csvfilename, category): + csvlist = [] + script_dir = os.path.dirname(os.path.abspath(__file__)) + full_path = os.path.join(script_dir, "./csvfiles/") + + with open(f'{full_path}{csvfilename}.csv', "r", newline="", encoding="utf8") as file: + reader = csv.DictReader(file, delimiter=",") + for row in reader: + if row[category] == "1": + csvlist.append(row["Artist"]) + return csvlist + def load_config_csv(): - csvlist = [] - script_dir = os.path.dirname(os.path.abspath(__file__)) - full_path_config_file = os.path.join(script_dir, "./userfiles/" ) - full_path_default_config_file = os.path.join(script_dir, "./csvfiles/config/" ) - config_file = full_path_config_file + 'config.csv' - default_config_file = full_path_default_config_file + 'default_config.csv' - - if not os.path.exists(config_file): - shutil.copy2(default_config_file, config_file) - print("Config file created.") - - - with open(config_file, "r", newline="",encoding="utf8") as file: - reader = csv.DictReader(file, delimiter=";") - csvlist = [list(row.values()) for row in reader if not any(value.startswith('#') for value in row.values())] - return csvlist - \ No newline at end of file + script_dir = os.path.dirname(os.path.abspath(__file__)) + full_path_config_file = os.path.join(script_dir, "./userfiles/") + full_path_default_config_file = os.path.join(script_dir, "./csvfiles/config/") + config_file = f'{full_path_config_file}config.csv' + default_config_file = f'{full_path_default_config_file}default_config.csv' + + if not os.path.exists(config_file): + shutil.copy2(default_config_file, config_file) + print("Config file created.") + + with open(config_file, "r", newline="", encoding="utf8") as file: + reader = csv.DictReader(file, delimiter=";") + return [list(row.values()) for row in reader if not any(value.startswith('#') for value in row.values())] diff --git a/main.py b/main.py index 799284a..23a657e 100644 --- a/main.py +++ b/main.py @@ -1,26 +1,106 @@ -import sys, os +import os import random -import uuid import re -from datetime import datetime +import sys import time -sys.path.append(os.path.abspath("..")) +import uuid +from datetime import datetime -from call_txt2img import * -from call_img2img import * -from build_dynamic_prompt import * -from call_extras import * -from model_lists import * +import requests +from build_dynamic_prompt import build_dynamic_prompt, createpromptvariant +from call_extras import call_extras +from call_img2img import call_img2img +from call_txt2img import call_txt2img +from model_lists import (get_models, get_samplers, get_samplers_for_img2img, + get_upscalers, get_upscalers_for_img2img) -def generateimages(amount = 1, size = "all",model = "currently selected model",samplingsteps = "40",cfg= "7",hiresfix = True,hiressteps ="0",denoisestrength="0.6",samplingmethod="DPM++ SDE Karras", upscaler="R-ESRGAN 4x+", hiresscale="2",apiurl="http://127.0.0.1:7860",qualitygate=False,quality="7.6",runs="5",insanitylevel="5",subject="all", artist="all", imagetype="all",silentmode=False, workprompt="", antistring="",prefixprompt="", suffixprompt="", negativeprompt="",promptcompounderlevel = "1", seperator="comma", img2imgbatch = "1", img2imgsamplingsteps = "20", img2imgcfg = "7", img2imgsamplingmethod = "DPM++ SDE Karras", img2imgupscaler = "R-ESRGAN 4x+", img2imgmodel = "currently selected model", img2imgactivate = False, img2imgscale = "2", img2imgpadding = "64",img2imgdenoisestrength="0.3",ultimatesdupscale=False,usdutilewidth = "512", usdutileheight = "0", usdumaskblur = "8", usduredraw ="Linear", usduSeamsfix = "None", usdusdenoise = "0.35", usduswidth = "64", usduspadding ="32", usdusmaskblur = "8",controlnetenabled=False, controlnetmodel="",img2imgdenoisestrengthmod="-0.05",enableextraupscale = False,controlnetblockymode = False,extrasupscaler1 = "all",extrasupscaler2 ="all",extrasupscaler2visiblity="0.5",extrasupscaler2gfpgan="0",extrasupscaler2codeformer="0.15",extrasupscaler2codeformerweight="0.1",extrasresize="2",onlyupscale="false",givensubject="",smartsubject=True,giventypeofimage="",imagemodechance=20, gender="all", chosensubjectsubtypeobject="all", chosensubjectsubtypehumanoid="all", chosensubjectsubtypeconcept="all", increasestability = False, qualityhiresfix = False, qualitymode = "highest", qualitykeep="keep used", basesize = "512", promptvariantinsanitylevel = 0): +sys.path.append(os.path.abspath("..")) + + +def generateimages( + amount=1, + size="all", + model="currently selected model", + samplingsteps="40", + cfg="7", + hiresfix=True, + hiressteps="0", + denoisestrength="0.6", + samplingmethod="DPM++ SDE Karras", + upscaler="R-ESRGAN 4x+", + hiresscale="2", + apiurl="http://127.0.0.1:7860", + qualitygate=False, + quality="7.6", + runs="5", + insanitylevel="5", + subject="all", + artist="all", + imagetype="all", + silentmode=False, + workprompt="", + antistring="", + prefixprompt="", + suffixprompt="", + negativeprompt="", + promptcompounderlevel="1", + seperator="comma", + img2imgbatch="1", + img2imgsamplingsteps="20", + img2imgcfg="7", + img2imgsamplingmethod="DPM++ SDE Karras", + img2imgupscaler="R-ESRGAN 4x+", + img2imgmodel="currently selected model", + img2imgactivate=False, + img2imgscale="2", + img2imgpadding="64", + img2imgdenoisestrength="0.3", + ultimatesdupscale=False, + usdutilewidth="512", + usdutileheight="0", + usdumaskblur="8", + usduredraw="Linear", + usduSeamsfix="None", + usdusdenoise="0.35", + usduswidth="64", + usduspadding="32", + usdusmaskblur="8", + controlnetenabled=False, + controlnetmodel="", + img2imgdenoisestrengthmod="-0.05", + enableextraupscale=False, + controlnetblockymode=False, + extrasupscaler1="all", + extrasupscaler2="all", + extrasupscaler2visiblity="0.5", + extrasupscaler2gfpgan="0", + extrasupscaler2codeformer="0.15", + extrasupscaler2codeformerweight="0.1", + extrasresize="2", + onlyupscale="false", + givensubject="", + smartsubject=True, + giventypeofimage="", + imagemodechance=20, + gender="all", + chosensubjectsubtypeobject="all", + chosensubjectsubtypehumanoid="all", + chosensubjectsubtypeconcept="all", + increasestability=False, + qualityhiresfix=False, + qualitymode="highest", + qualitykeep="keep used", + basesize="512", + promptvariantinsanitylevel=0 +): loops = int(amount) # amount of images to generate steps = 0 - upscalefilelist=[] + upscalefilelist = [] originalimage = "" - originalpnginfo ="" + originalpnginfo = "" randomprompt = "" - filename="" + filename = "" continuewithnextpart = True originalmodel = model @@ -37,14 +117,13 @@ def generateimages(amount = 1, size = "all",model = "currently selected model",s originalimg2imgdenoisestrength = img2imgdenoisestrength originalimg2imgpadding = img2imgpadding - currentlyselectedmodel = "" - modellist=get_models() - samplerlist=get_samplers() - upscalerlist=get_upscalers() - img2imgupscalerlist=get_upscalers_for_img2img() - img2imgsamplerlist=get_samplers_for_img2img() + modellist = get_models() + samplerlist = get_samplers() + upscalerlist = get_upscalers() + img2imgupscalerlist = get_upscalers_for_img2img() + img2imgsamplerlist = get_samplers_for_img2img() tempmodel = "v1-5-pruned-emaonly.safetensors [6ce0161689]" @@ -57,7 +136,7 @@ def generateimages(amount = 1, size = "all",model = "currently selected model",s sdmodelsresponsejson = sdmodelsrespone.json() for item in sdmodelsresponsejson: - if(item['sha256'] == currentlyselectedmodelhash): + if item['sha256'] == currentlyselectedmodelhash: currentlyselectedmodel = item['title'] break @@ -69,84 +148,90 @@ def generateimages(amount = 1, size = "all",model = "currently selected model",s print("Cannot find current model.") currentlyselectedmodel = tempmodel - - while(currentlyselectedmodel == tempmodel or tempmodel not in modellist): + while currentlyselectedmodel == tempmodel or tempmodel not in modellist: tempmodel = random.choice(modellist) - - if(onlyupscale==True): + if onlyupscale is True: script_dir = os.path.dirname(os.path.abspath(__file__)) # Script directory - inputupscalemefolder = os.path.join(script_dir, "./automated_outputs/upscale_me/" ) - + inputupscalemefolder = os.path.join(script_dir, "./automated_outputs/upscale_me/") + for upscalefilename in os.listdir(inputupscalemefolder): f = os.path.join(inputupscalemefolder, upscalefilename) # checking if it is a file if os.path.isfile(f): - if(f[-3:]!="txt"): + if f[-3:] != "txt": upscalefilelist.append(f) - + loops = len(upscalefilelist) - if(loops==0): + if loops == 0: print('No files to upscale found! Please place images in //upscale_me// folder') else: print("") print("Found and upscaling files") print("") - - - - if(ultimatesdupscale==False): - upscalescript="SD upscale" + if ultimatesdupscale is False: + upscalescript = "SD upscale" else: - upscalescript="Ultimate SD upscale" + upscalescript = "Ultimate SD upscale" - while steps < loops: # load the base model as a workaround - if(steps > 0 and increasestability == True): + if steps > 0 and increasestability is True: print("") print("Increase Stability has been turned on.") print("To prevent a memory issue, we are going to unload and then load the checkpoint back in.") print("This helps with a memory leak issue. However A1111 is bad with memory management.") print("") - response = requests.post(url=f'{apiurl}/sdapi/v1/unload-checkpoint') - + requests.post(url=f'{apiurl}/sdapi/v1/unload-checkpoint') print("model unloaded") - response = requests.post(url=f'{apiurl}/sdapi/v1/reload-checkpoint') - + requests.post(url=f'{apiurl}/sdapi/v1/reload-checkpoint') print("model reloaded") # build prompt - if(silentmode==True and workprompt == ""): + if silentmode is True and workprompt == "": print("Trying to use provided workflow prompt, but is empty. Generating a random prompt instead.") - - if(onlyupscale==False): # only do txt2img when onlyupscale is False - if(silentmode==True and workprompt != ""): + + if onlyupscale is False: # only do txt2img when onlyupscale is False + if silentmode is True and workprompt != "": randomprompt = createpromptvariant(workprompt, promptvariantinsanitylevel) print("Using provided workflow prompt") print(randomprompt) - - - - else: - randomprompt = build_dynamic_prompt(insanitylevel,subject,artist,imagetype, False,antistring,prefixprompt,suffixprompt,promptcompounderlevel, seperator,givensubject,smartsubject,giventypeofimage,imagemodechance, gender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept) + else: + randomprompt = build_dynamic_prompt( + insanitylevel, + subject, + artist, + imagetype, + False, + antistring, + prefixprompt, + suffixprompt, + promptcompounderlevel, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + gender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept + ) # make the filename, from from a to the first comma # find the index of the first comma after "of a" or end of the prompt - if(randomprompt.find("of a ") != -1): + if randomprompt.find("of a ") != -1: start_index = randomprompt.find("of a ") + len("of a ") end_index = randomprompt.find(",", start_index) - if(end_index == -1): - end_index=len(randomprompt) + if end_index == -1: + end_index = len(randomprompt) else: start_index = 0 end_index = 128 - - # extract the desired substring using slicing filename = randomprompt[start_index:end_index] @@ -167,151 +252,199 @@ def generateimages(amount = 1, size = "all",model = "currently selected model",s # Use regular expression to filter out any characters not in the whitelist filename = re.sub(r"[^{}]+".format(re.escape(''.join(safe_characters))), '', filename) - if(filename==""): + if filename == "": filename = str(uuid.uuid4()) - + # create a datetime object for the current date and time now = datetime.now() - filenamecomplete = now.strftime("%Y%m%d%H%M%S") + "_" + filename.replace(" ", "_").strip() - - + filenamecomplete = f'{now.strftime("%Y%m%d%H%M%S")}_{filename.replace(" ", "_").strip()}' - #Check if there is any random value we have to choose or not - if(originalmodel=="all"): + # Check if there is any random value we have to choose or not + if originalmodel == "all": model = random.choice(modellist) - #lets not do inpainting models + # lets not do inpainting models while "inpaint" in model: model = random.choice(modellist) - print("Going to run with model " + model) - if(originalmodel=="currently selected model"): + print(f"Going to run with model {model}") + if originalmodel == "currently selected model": model = currentlyselectedmodel - # set the model here - #if(originalmodel!="currently selected model"): - option_payload = { - "sd_model_checkpoint": model - } - response = requests.post(url=f'{apiurl}/sdapi/v1/options', json=option_payload) - - if(originalsamplingmethod=="all"): + option_payload = {"sd_model_checkpoint": model} + requests.post(url=f'{apiurl}/sdapi/v1/options', json=option_payload) + + if originalsamplingmethod == "all": samplingmethod = random.choice(samplerlist) - print ("Going to run with sampling method " + samplingmethod) + print(f"Going to run with sampling method {samplingmethod}") - if(originalupscaler=="all" and hiresfix == True): + if originalupscaler == "all" and hiresfix is True: upscaler = random.choice(upscalerlist) - print ("Going to run with upscaler " + upscaler) + print(f"Going to run with upscaler {upscaler}") # WebUI fix for PLMS and UniPC and hiresfix - if(samplingmethod in ['PLMS', 'UniPC']): # PLMS/UniPC do not support hirefix so we just silently switch to DDIM + # PLMS/UniPC do not support hirefix so we just silently switch to DDIM + if samplingmethod in ['PLMS', 'UniPC']: samplingmethod = 'DDIM' - - - - txt2img = call_txt2img(randomprompt, size ,hiresfix, 0, filenamecomplete,model ,samplingsteps,cfg, hiressteps, denoisestrength,samplingmethod, upscaler,hiresscale,apiurl,qualitygate,quality,runs,negativeprompt, qualityhiresfix, qualitymode, qualitykeep, basesize) - originalimage = txt2img[0] #Set this for later use - originalpnginfo = txt2img[1] #Sort of hacky way of bringing this forward. But if it works, it works + txt2img = call_txt2img( + randomprompt, + size, + hiresfix, + 0, + filenamecomplete, + model, + samplingsteps, + cfg, + hiressteps, + denoisestrength, + samplingmethod, + upscaler, + hiresscale, + apiurl, + qualitygate, + quality, + runs, + negativeprompt, + qualityhiresfix, + qualitymode, + qualitykeep, + basesize + ) + originalimage = txt2img[0] # Set this for later use + originalpnginfo = txt2img[1] # Sort of hacky way of bringing this forward. But if it works, it works continuewithnextpart = txt2img[2] image = txt2img[0] else: - if(filename==""): + if filename == "": filename = str(uuid.uuid4()) - + # create a datetime object for the current date and time now = datetime.now() - filenamecomplete = now.strftime("%Y%m%d%H%M%S") + "_" + filename.replace(" ", "_").strip() + filenamecomplete = f'{now.strftime("%Y%m%d%H%M%S")}_{filename.replace(" ", "_").strip()}' image = upscalefilelist[steps] # else we get the image from the upscale file list - originalimage = image # this is also the original image file + originalimage = image # this is also the original image file - # upscale via img2img - img2imgloops = int(img2imgbatch) - if(img2imgactivate == False or continuewithnextpart == False): # If we dont want to run, turn it off + if img2imgactivate is False or continuewithnextpart is False: # If we dont want to run, turn it off img2imgloops = 0 else: - #Check if there is any random value we have to choose or not - if(originalimg2imgmodel=="all"): + # Check if there is any random value we have to choose or not + if originalimg2imgmodel == "all": img2imgmodel = random.choice(modellist) - #lets not do inpainting models + # lets not do inpainting models while "inpaint" in model: img2imgmodel = random.choice(modellist) print("Going to upscale with model " + img2imgmodel) - if(originalimg2imgmodel=="currently selected model"): + if originalimg2imgmodel == "currently selected model": img2imgmodel = currentlyselectedmodel - + # set the model here - #if(originalimg2imgmodel!="currently selected model"): - option_payload = { - "sd_model_checkpoint": img2imgmodel - } - response = requests.post(url=f'{apiurl}/sdapi/v1/options', json=option_payload) + option_payload = {"sd_model_checkpoint": img2imgmodel} + requests.post(url=f'{apiurl}/sdapi/v1/options', json=option_payload) - if(originalimg2imgsamplingmethod=="all"): + if originalimg2imgsamplingmethod == "all": img2imgsamplingmethod = random.choice(img2imgsamplerlist) - print ("Going to upscale with sampling method " + img2imgsamplingmethod) + print(f"Going to upscale with sampling method {img2imgsamplingmethod}") - if(originalimg2imgupscaler=="all"): + if originalimg2imgupscaler == "all": img2imgupscaler = random.choice(img2imgupscalerlist) - print ("Going to run with upscaler " + img2imgupscaler) - + print(f"Going to run with upscaler {img2imgupscaler}") + # WebUI fix for PLMS and UniPC and img2img - if(img2imgsamplingmethod in ['PLMS', 'UniPC']): # PLMS/UniPC do not support img2img so we just silently switch to DDIM + # PLMS/UniPC do not support img2img so we just silently switch to DDIM + if img2imgsamplingmethod in ['PLMS', 'UniPC']: img2imgsamplingmethod = 'DDIM' img2imgsteps = 0 - + # start the batching! img2imgdenoisestrength = originalimg2imgdenoisestrength img2imgpadding = originalimg2imgpadding - + while img2imgsteps < img2imgloops: + img2img = call_img2img( + image, + originalimage, + originalpnginfo, + apiurl, + filenamecomplete, + randomprompt, + negativeprompt, + img2imgsamplingsteps, + img2imgcfg, + img2imgsamplingmethod, + img2imgupscaler, + img2imgmodel, + img2imgdenoisestrength, + img2imgscale, + img2imgpadding, + upscalescript, + usdutilewidth, + usdutileheight, + usdumaskblur, + usduredraw, + usduSeamsfix, + usdusdenoise, + usduswidth, + usduspadding, + usdusmaskblur, + controlnetenabled, + controlnetmodel, + controlnetblockymode + ) - - #filenamecomplete = originalfilenamecomplete + "_" + str(img2imgsteps) - #print(filenamecomplete) - - img2img = call_img2img(image, originalimage, originalpnginfo, apiurl, filenamecomplete, randomprompt,negativeprompt,img2imgsamplingsteps, img2imgcfg, img2imgsamplingmethod, img2imgupscaler, img2imgmodel, img2imgdenoisestrength, img2imgscale, img2imgpadding,upscalescript,usdutilewidth, usdutileheight, usdumaskblur, usduredraw, usduSeamsfix, usdusdenoise, usduswidth, usduspadding, usdusmaskblur,controlnetenabled, controlnetmodel,controlnetblockymode) - image = img2img[0] - if(originalpnginfo==""): + if originalpnginfo == "": originalpnginfo = img2img[1] - img2imgdenoisestrength = str(round(float(img2imgdenoisestrength) + float(img2imgdenoisestrengthmod),2)) # lower or increase the denoise strength for each batch - img2imgpadding = str(int(int(img2imgpadding) * float(img2imgscale))) # also increase padding by scale + # lower or increase the denoise strength for each batch + img2imgdenoisestrength = str(round(float(img2imgdenoisestrength) + float(img2imgdenoisestrengthmod), 2)) + img2imgpadding = str(int(int(img2imgpadding) * float(img2imgscale))) # also increase padding by scale - if(int(img2imgpadding)>256): # but not overdo it :D - img2imgpadding="256" - - # Sometimes, we are too quick to do another call, causing memory issues. So we wait a bit to let the system settle done a bit. + if int(img2imgpadding) > 256: # but not overdo it :D + img2imgpadding = "256" + + # Sometimes, we are too quick to do another call, causing memory issues. + # So we wait a bit to let the system settle done a bit. # Its stupid but it works. Sometimes.... time.sleep(5) - + img2imgsteps += 1 # upscale via extras upscaler next - - if(enableextraupscale==True and continuewithnextpart == True): - if(extrasupscaler1=="all"): + if enableextraupscale is True and continuewithnextpart is True: + if extrasupscaler1 == "all": extrasupscaler1 = random.choice(img2imgupscalerlist) - print ("Going to upscale with upscaler 1 " + extrasupscaler1) - - if(extrasupscaler2=="all"): - extrasupscaler2 = random.choice(img2imgupscalerlist) - print ("Going to upscale with upscaler 2 " + extrasupscaler2) - - image = call_extras(image, originalimage, originalpnginfo, apiurl, filenamecomplete,extrasupscaler1,extrasupscaler2 ,extrasupscaler2visiblity,extrasupscaler2gfpgan,extrasupscaler2codeformer,extrasupscaler2codeformerweight,extrasresize) + print("Going to upscale with upscaler 1 " + extrasupscaler1) - if(continuewithnextpart == True): + if extrasupscaler2 == "all": + extrasupscaler2 = random.choice(img2imgupscalerlist) + print("Going to upscale with upscaler 2 " + extrasupscaler2) + + image = call_extras( + image, + originalimage, + originalpnginfo, + apiurl, + filenamecomplete, + extrasupscaler1, + extrasupscaler2, + extrasupscaler2visiblity, + extrasupscaler2gfpgan, + extrasupscaler2codeformer, + extrasupscaler2codeformerweight, + extrasresize + ) + + if continuewithnextpart is True: # only count images we actually fully processed steps += 1 - print("") print("All done!") + def tryinterrupt(apiurl="http://127.0.0.1:7860"): - response = requests.post(url=f'{apiurl}/sdapi/v1/interrupt') - \ No newline at end of file + requests.post(url=f'{apiurl}/sdapi/v1/interrupt') diff --git a/model_lists.py b/model_lists.py index a640c85..0cead43 100644 --- a/model_lists.py +++ b/model_lists.py @@ -1,29 +1,34 @@ -import modules.scripts as scripts -import os -from modules import modelloader, paths, shared, sd_models, sd_samplers -from modules.paths import models_path, script_path -import importlib +from modules import modelloader, sd_models, sd_samplers, shared + def get_models(): modellist = sd_models.checkpoint_tiles() return modellist + def get_upscalers(): # Upscalers are sort of hardcoded as well for Latent, but not for the 2 others. So build it up! - latentlist=["Latent","Latent (antialiased)","Latent (bicubic)","Latent (bicubic antialiased)","Latent (nearest)","Latent (nearest-exact)","Lanczos","Nearest"] + latentlist = [ + "Latent", + "Latent (antialiased)", + "Latent (bicubic)", + "Latent (bicubic antialiased)", + "Latent (nearest)", + "Latent (nearest-exact)", + "Lanczos", + "Nearest" + ] - # From 1.4 onwards, the shared.sd_upscalers isn't available on startup. Run load_upscalers first # It doesn't work perfectly, I have to call this each time to make sure it stays working. upscalerlistfromwWebUI = upscalers_on_startup() - + # deduplicate the list upscalerlistfromwWebUI = list(dict.fromkeys(upscalerlistfromwWebUI)) - if("None" in upscalerlistfromwWebUI): + if "None" in upscalerlistfromwWebUI: upscalerlistfromwWebUI.remove("None") - upscalerlist = latentlist + upscalerlistfromwWebUI # Just to be sure, deduplicate again @@ -31,11 +36,12 @@ def get_upscalers(): return upscalerlist + def get_samplers(): samplerlist = list(sd_samplers.all_samplers_map.keys()) # fallback method - if(samplerlist==[]): + if samplerlist == []: samplerlist = [ "DDIM", "DPM adaptive", @@ -61,16 +67,16 @@ def get_samplers(): return samplerlist + def get_upscalers_for_img2img(): - # From 1.4 onwards, the shared.sd_upscalers isn't available on startup. Run load_upscalers first # It doesn't work perfectly, I have to call this each time to make sure it stays working. upscalerlistfromwWebUI = upscalers_on_startup() - + # deduplicate the list upscalerlistfromwWebUI = list(dict.fromkeys(upscalerlistfromwWebUI)) - if("None" in upscalerlistfromwWebUI): + if "None" in upscalerlistfromwWebUI: upscalerlistfromwWebUI.remove("None") return upscalerlistfromwWebUI @@ -78,13 +84,14 @@ def get_upscalers_for_img2img(): def get_samplers_for_img2img(): samplerlist = get_samplers().copy() - #UniPC and PLMS dont support upscaling apparently + # UniPC and PLMS dont support upscaling apparently for s in ["UniPC", "PLMS"]: if samplerlist and s in samplerlist: samplerlist.remove(s) return samplerlist + def upscalers_on_startup(): modelloader.cleanup_models() modelloader.load_upscalers() @@ -92,13 +99,13 @@ def upscalers_on_startup(): # In vlad this seems to work, but in WebUI some of these aren't loaded yet # lets just hardcode it, and get it over with - if('LDSR' not in upscalerlistfromwWebUI): + if 'LDSR' not in upscalerlistfromwWebUI: upscalerlistfromwWebUI.append('LDSR') - if('ScuNET GAN' not in upscalerlistfromwWebUI): + if 'ScuNET GAN' not in upscalerlistfromwWebUI: upscalerlistfromwWebUI.append('ScuNET GAN') - if('ScuNET PSNR' not in upscalerlistfromwWebUI): + if 'ScuNET PSNR' not in upscalerlistfromwWebUI: upscalerlistfromwWebUI.append('ScuNET PSNR') - if('SwinIR_4x' not in upscalerlistfromwWebUI and 'SwinIR 4x' not in upscalerlistfromwWebUI): + if 'SwinIR_4x' not in upscalerlistfromwWebUI and 'SwinIR 4x' not in upscalerlistfromwWebUI: upscalerlistfromwWebUI.append('SwinIR_4x') - + return upscalerlistfromwWebUI diff --git a/prompttester.py b/prompttester.py index 740e767..3188a19 100644 --- a/prompttester.py +++ b/prompttester.py @@ -1,49 +1,113 @@ -import sys, os -import random -import uuid -import re -from datetime import datetime -sys.path.append(os.path.abspath("..")) - +import os +import sys -from build_dynamic_prompt import * +from build_dynamic_prompt import build_dynamic_prompt +sys.path.append(os.path.abspath("..")) -def generateprompts(amount = 1,insanitylevel="5",subject="all", artist="all", imagetype="all",onlyartists=False, workprompt="", antistring="",prefixprompt="", suffixprompt="", negativeprompt="",promptcompounderlevel = "1", seperator="comma",givensubject="",smartsubject=True,giventypeofimage="",imagemodechance=20, gender = "all", subtypeobject = "all", subtypehumanoid = "all", subtypeconcept = "all", advancedprompting = True, hardturnoffemojis=False): +def generateprompts( + amount=1, + insanitylevel="5", + subject="all", + artist="all", + imagetype="all", + onlyartists=False, + workprompt="", + antistring="", + prefixprompt="", + suffixprompt="", + negativeprompt="", + promptcompounderlevel="1", + seperator="comma", + givensubject="", + smartsubject=True, + giventypeofimage="", + imagemodechance=20, + gender="all", + subtypeobject="all", + subtypehumanoid="all", + subtypeconcept="all", + advancedprompting=True, + hardturnoffemojis=False +): loops = int(amount) # amount of images to generate steps = 0 - + insanitylevel = int(insanitylevel) while steps < loops: # build prompt - - result = build_dynamic_prompt(insanitylevel,subject,artist,imagetype, onlyartists,antistring,prefixprompt,suffixprompt,promptcompounderlevel, seperator,givensubject,smartsubject,giventypeofimage,imagemodechance, gender, subtypeobject, subtypehumanoid, subtypeconcept, advancedprompting, hardturnoffemojis) + result = build_dynamic_prompt( + insanitylevel, + subject, + artist, + imagetype, + onlyartists, + antistring, + prefixprompt, + suffixprompt, + promptcompounderlevel, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + gender, + subtypeobject, + subtypehumanoid, + subtypeconcept, + advancedprompting, + hardturnoffemojis + ) print("") - print("loop " + str(steps)) + print(f'loop {steps}') print("") - if(onlyartists == True): + + if onlyartists is True: print(result) print("") - - if(result.count("-")>1 and imagetype == "only templates"): + + if result.count("-") > 1 and imagetype == "only templates": print("Is there a mistake in wildcards?") print("") print(result) break - - if(givensubject != "" and givensubject not in result and imagetype == "only templates"): + + if givensubject != "" and givensubject not in result and imagetype == "only templates": print("No givensubject, there must be an issue:") print("") print(result) break - steps += 1 - print("") print("All done!") -generateprompts(10,8,"all","all","all",False,"","","PREFIXPROMPT" ,"SUFFIXPROMPT","",1,"","",True,"",100, "all", "all", "all", "all", False, True) \ No newline at end of file + +generateprompts( + 10, + 8, + "all", + "all", + "all", + False, + "", + "", + "PREFIXPROMPT", + "SUFFIXPROMPT", + "", + 1, + "", + "", + True, + "", + 100, + "all", + "all", + "all", + "all", + False, + True +) diff --git a/promptvarianttester.py b/promptvarianttester.py index b67e7d3..49beedd 100644 --- a/promptvarianttester.py +++ b/promptvarianttester.py @@ -1,23 +1,19 @@ -import sys, os -import random -import uuid -import re -from datetime import datetime -sys.path.append(os.path.abspath("..")) - +import os +import sys -from build_dynamic_prompt import * +from build_dynamic_prompt import build_dynamic_prompt, createpromptvariant +sys.path.append(os.path.abspath("..")) -def generatepromptvariants(amount = 1,prompt="",insanitylevel="5"): +def generatepromptvariants(amount=1, prompt="", insanitylevel="5"): loops = int(amount) # amount of images to generate steps = 0 - + insanitylevel = int(insanitylevel) while steps < loops: # build prompt - if(prompt == ""): + if prompt == "": prompt = build_dynamic_prompt(insanitylevel) result = createpromptvariant(prompt, insanitylevel) @@ -25,14 +21,18 @@ def generatepromptvariants(amount = 1,prompt="",insanitylevel="5"): print(result) print("") - print("loop " + str(steps)) + print(f'loop {steps}') print("") - steps += 1 - print("") print("All done!") -generatepromptvariants(1,"purple (galaxy) in a (bottle:1.2), , background is a lush jungle and a woman wearing a summer dress, -artmovement-", 5) \ No newline at end of file + +generatepromptvariants( + 1, + "purple (galaxy) in a (bottle:1.2), , background is a lush jungle and a woman wearing a summer dress," + + " -artmovement-", + 5 +) diff --git a/random_functions.py b/random_functions.py index 579b42f..50d12c2 100644 --- a/random_functions.py +++ b/random_functions.py @@ -1,49 +1,61 @@ import random + + def common_dist(insanitylevel): - return (random.randint(1, 5)= 10) + return random.randint(1, 5) < insanitylevel or insanitylevel >= 10 + def normal_dist(insanitylevel): - return (random.randint(1, 10)= 10) + return random.randint(1, 10) < insanitylevel or insanitylevel >= 10 + def uncommon_dist(insanitylevel): - return (random.randint(1, 18)= 10) + return random.randint(1, 18) < insanitylevel or insanitylevel >= 10 + def rare_dist(insanitylevel): - roll = (random.randint(1, 30)= 10) - if(roll): + roll = random.randint(1, 30) < insanitylevel or insanitylevel >= 10 + if roll: print("adding something rare to the prompt") return roll + def legendary_dist(insanitylevel): - roll = (random.randint(1, 50)= 10): - if(message != ""): + if set_number <= 35 and insanitylevel >= 10: + if message != "": print(message) - return True + return True roll = random.randint(1, set_number) < insanitylevel - if(message != "" and roll == True): - print(message) + if message != "" and roll is True: + print(message) return roll else: raise ValueError(f"Invalid chance value: {chance}") diff --git a/scripts/api.py b/scripts/api.py index 9289ffc..2e35507 100644 --- a/scripts/api.py +++ b/scripts/api.py @@ -1,7 +1,9 @@ -from fastapi import FastAPI, Body import gradio as gr -from build_dynamic_prompt import * -from scripts.onebuttonprompt import subjects, artists, imagetypes +from fastapi import Body, FastAPI + +from build_dynamic_prompt import build_dynamic_prompt +from scripts.onebuttonprompt import artists, imagetypes, subjects + def one_button_prompt_api(_: gr.Blocks, app: FastAPI): @app.get("/one_button_prompt/version") @@ -10,54 +12,70 @@ async def version(): @app.get("/one_button_prompt/config") async def get_config(): - - config ={ - "subjects": subjects, - "artists": artists, - "imagetypes": imagetypes, - + config = { + "subjects": subjects, + "artists": artists, + "imagetypes": imagetypes, } - return config + return config @app.post("/one_button_prompt/prompt/random") - async def random_prompts(numberofprompts:int = Body(1,title="number of prompts"), - insanitylevel: int= Body(5,title="insanity level"), - forcesubject: str =Body('all',title="force subject"), - artists : str =Body('all',title="artists"), - imagetype : str =Body('all',title="image type"), - onlyartists: bool =Body(False,title="only artists"), - antivalues : str =Body('',title="anti values"), - prefixprompt: str =Body('',title="prefix prompt"), - suffixprompt: str =Body('',title="suffix prompt"), - promptcompounderlevel: str =Body('1',title="prompt compounder level"), - seperator: str =Body('comma',title="seperator"), - givensubject: str =Body('',title="givensubject"), - smartsubject:bool = Body(True,title='smart subject'), - giventypeofimage: str = Body('',title='given type of image'), - imagemodechance: int = Body(20,title='image mode chance'), - gender: str = Body('all',title='gender'), - subtypeobject: str = Body('all',title='subtypeobject'), - subtypehumanoid: str = Body('all', title='subtypehumanoid'), + async def random_prompts( + numberofprompts: int = Body(1, title="number of prompts"), + insanitylevel: int = Body(5, title="insanity level"), + forcesubject: str = Body('all', title="force subject"), + artists: str = Body('all', title="artists"), + imagetype: str = Body('all', title="image type"), + onlyartists: bool = Body(False, title="only artists"), + antivalues: str = Body('', title="anti values"), + prefixprompt: str = Body('', title="prefix prompt"), + suffixprompt: str = Body('', title="suffix prompt"), + promptcompounderlevel: str = Body('1', title="prompt compounder level"), + seperator: str = Body('comma', title="seperator"), + givensubject: str = Body('', title="givensubject"), + smartsubject: bool = Body(True, title='smart subject'), + giventypeofimage: str = Body('', title='given type of image'), + imagemodechance: int = Body(20, title='image mode chance'), + gender: str = Body('all', title='gender'), + subtypeobject: str = Body('all', title='subtypeobject'), + subtypehumanoid: str = Body('all', title='subtypehumanoid'), subtypeconcept: str = Body('all', title='subtypeconcept'), - advancedprompting:bool = Body(True,title='advancedprompting'), - hardturnoffemojis:bool = Body(False,title='hardturnoffemojis') - ): - - - keys = ['insanitylevel', 'forcesubject', 'artists', 'imagetype', 'onlyartists', 'antivalues', 'prefixprompt', - 'suffixprompt', 'promptcompounderlevel', 'seperator', 'givensubject', 'smartsubject', 'giventypeofimage', - 'imagemodechance', 'gender', 'subtypeobject','subtypehumanoid','subtypeconcept','advancedprompting','hardturnoffemojis'] - payload = {} - for key in keys: - payload[key] = locals()[key] - - prompts = [build_dynamic_prompt(**payload) for _ in range(numberofprompts)] - return {"prompts": prompts} + advancedprompting: bool = Body(True, title='advancedprompting'), + hardturnoffemojis: bool = Body(False, title='hardturnoffemojis') + ): + keys = [ + 'insanitylevel', + 'forcesubject', + 'artists', + 'imagetype', + 'onlyartists', + 'antivalues', + 'prefixprompt', + 'suffixprompt', + 'promptcompounderlevel', + 'seperator', + 'givensubject', + 'smartsubject', + 'giventypeofimage', + 'imagemodechance', + 'gender', + 'subtypeobject', + 'subtypehumanoid', + 'subtypeconcept', + 'advancedprompting', + 'hardturnoffemojis' + ] + payload = {} + for key in keys: + payload[key] = locals()[key] + + prompts = [build_dynamic_prompt(**payload) for _ in range(numberofprompts)] + return {"prompts": prompts} try: import modules.script_callbacks as script_callbacks script_callbacks.on_app_started(one_button_prompt_api) -except: - pass +except ImportError as error: + print(error) diff --git a/scripts/onebuttonprompt.py b/scripts/onebuttonprompt.py index d2663f3..961a1c3 100644 --- a/scripts/onebuttonprompt.py +++ b/scripts/onebuttonprompt.py @@ -1,28 +1,128 @@ -import modules.scripts as scripts -import gradio as gr import os import platform +import random import subprocess as sp +import sys -from modules import images -from modules.processing import process_images, Processed -from modules.processing import Processed -from modules.shared import opts, cmd_opts, state +import gradio as gr +import modules.scripts as scripts +from modules.processing import Processed, process_images +from modules.shared import state +from csv_reader import load_config_csv +from main import (build_dynamic_prompt, createpromptvariant, generateimages, + tryinterrupt) +from model_lists import (get_models, get_samplers, get_samplers_for_img2img, + get_upscalers, get_upscalers_for_img2img) -from build_dynamic_prompt import * -from main import * -from model_lists import * -from csv_reader import * +# from build_dynamic_prompt import * +# from csv_reader import * +# from main import * +# from model_lists import * -#subjects = ["all","object","animal","humanoid", "landscape", "concept"] -subjects =["all"] +subjects = ["all"] subjectsubtypesobject = ["all"] subjectsubtypeshumanoid = ["all"] subjectsubtypesconcept = ["all"] -artists = ["all", "none", "popular", "greg mode", "3D", "abstract", "angular", "anime" ,"architecture", "art nouveau", "art deco", "baroque", "bauhaus", "cartoon", "character", "children's illustration", "cityscape", "clean", "cloudscape", "collage", "colorful", "comics", "cubism", "dark", "detailed", "digital", "expressionism", "fantasy", "fashion", "fauvism", "figurativism", "gore", "graffiti", "graphic design", "high contrast", "horror", "impressionism", "installation", "landscape", "light", "line drawing", "low contrast", "luminism", "magical realism", "manga", "melanin", "messy", "monochromatic", "nature", "nudity", "photography", "pop art", "portrait", "primitivism", "psychedelic", "realism", "renaissance", "romanticism", "scene", "sci-fi", "sculpture", "seascape", "space", "stained glass", "still life", "storybook realism", "street art", "streetscape", "surrealism", "symbolism", "textile", "ukiyo-e", "vibrant", "watercolor", "whimsical"] -imagetypes = ["all", "all - force multiple", "photograph", "octane render","digital art","concept art", "painting", "portrait", "anime key visual", "only other types", "only templates mode", "art blaster mode", "quality vomit mode", "color cannon mode", "unique art mode", "massive madness mode", "photo fantasy mode", "subject only mode", "fixed styles mode"] +artists = [ + "all", + "none", + "popular", + "greg mode", + "3D", + "abstract", + "angular", + "anime", + "architecture", + "art nouveau", + "art deco", + "baroque", + "bauhaus", + "cartoon", + "character", + "children's illustration", + "cityscape", + "clean", + "cloudscape", + "collage", + "colorful", + "comics", + "cubism", + "dark", + "detailed", + "digital", + "expressionism", + "fantasy", + "fashion", + "fauvism", + "figurativism", + "gore", + "graffiti", + "graphic design", + "high contrast", + "horror", + "impressionism", + "installation", + "landscape", + "light", + "line drawing", + "low contrast", + "luminism", + "magical realism", + "manga", + "melanin", + "messy", + "monochromatic", + "nature", + "nudity", + "photography", + "pop art", + "portrait", + "primitivism", + "psychedelic", + "realism", + "renaissance", + "romanticism", + "scene", + "sci-fi", + "sculpture", + "seascape", + "space", + "stained glass", + "still life", + "storybook realism", + "street art", + "streetscape", + "surrealism", + "symbolism", + "textile", + "ukiyo-e", + "vibrant", + "watercolor", + "whimsical" +] +imagetypes = [ + "all", + "all - force multiple", + "photograph", + "octane render", + "digital art", + "concept art", + "painting", + "portrait", + "anime key visual", + "only other types", + "only templates mode", + "art blaster mode", + "quality vomit mode", + "color cannon mode", + "unique art mode", + "massive madness mode", + "photo fantasy mode", + "subject only mode", + "fixed styles mode" +] promptmode = ["at the back", "in the front"] promptcompounder = ["1", "2", "3", "4", "5"] ANDtogglemode = ["none", "automatic", "prefix AND prompt + suffix", "prefix + prefix + prompt + suffix"] @@ -30,48 +130,49 @@ genders = ["all", "male", "female"] qualitymodelist = ["highest", "gated"] -qualitykeeplist = ["keep used","keep all"] +qualitykeeplist = ["keep used", "keep all"] -#for autorun and upscale +# for autorun and upscale sizelist = ["all", "portrait", "wide", "square", "ultrawide", "ultraheight", "wild"] basesizelist = ["512", "768", "1024"] modellist = get_models() -modellist.insert(0,"all") -modellist.insert(0,"currently selected model") # First value us the currently selected model +modellist.insert(0, "all") +modellist.insert(0, "currently selected model") # First value us the currently selected model upscalerlist = get_upscalers() -upscalerlist.insert(0,"automatic") -upscalerlist.insert(0,"all") +upscalerlist.insert(0, "automatic") +upscalerlist.insert(0, "all") samplerlist = get_samplers() -samplerlist.insert(0,"all") +samplerlist.insert(0, "all") -#for img2img +# for img2img img2imgupscalerlist = get_upscalers_for_img2img() -img2imgupscalerlist.insert(0,"automatic") -img2imgupscalerlist.insert(0,"all") +img2imgupscalerlist.insert(0, "automatic") +img2imgupscalerlist.insert(0, "all") img2imgsamplerlist = get_samplers_for_img2img() -img2imgsamplerlist.insert(0,"all") +img2imgsamplerlist.insert(0, "all") -#for ultimate SD upscale +# for ultimate SD upscale -seams_fix_types = ["None","Band pass","Half tile offset pass","Half tile offset pass + intersections"] -redraw_modes = ["Linear","Chess","None"] +seams_fix_types = ["None", "Band pass", "Half tile offset pass", "Half tile offset pass + intersections"] +redraw_modes = ["Linear", "Chess", "None"] -#folder stuff +# folder stuff folder_symbol = '\U0001f4c2' # 📂 sys.path.append(os.path.abspath("..")) # Load up stuff for personal artists list, if any # find all artist files starting with personal_artits in userfiles script_dir = os.path.dirname(os.path.abspath(__file__)) # Script directory -userfilesfolder = os.path.join(script_dir, "../userfiles/" ) +userfilesfolder = os.path.join(script_dir, "../userfiles/") for filename in os.listdir(userfilesfolder): - if(filename.endswith(".csv") and filename.startswith("personal_artists") and filename != "personal_artists_sample.csv"): + if filename.endswith(".csv") and filename.startswith("personal_artists") and \ + filename != "personal_artists_sample.csv": name = os.path.splitext(filename)[0] - name = name.replace("_"," ",-1).lower() + name = name.replace("_", " ", -1).lower() # directly insert into the artists list artists.insert(2, name) @@ -99,138 +200,172 @@ generatepoemline = True generatesongline = True - for item in config: + if item[1] == 'on': + continue + + match item[0]: # objects - if item[0] == 'subject_vehicle' and item[1] != 'on': + case 'subject_vehicle': generatevehicle = False - if item[0] == 'subject_object' and item[1] != 'on': + case 'subject_object': generateobject = False - if item[0] == 'subject_food' and item[1] != 'on': + case 'subject_food': generatefood = False - if item[0] == 'subject_building' and item[1] != 'on': + case 'subject_building': generatebuilding = False - if item[0] == 'subject_space' and item[1] != 'on': + case 'subject_space': generatespace = False - if item[0] == 'subject_flora' and item[1] != 'on': + case 'subject_flora': generateflora = False + # animals - if item[0] == 'subject_animal' and item[1] != 'on': + case 'subject_animal': generateanimal = False + # humanoids - if item[0] == 'subject_manwoman' and item[1] != 'on': + case 'subject_manwoman': generatemanwoman = False - if item[0] == 'subject_manwomanrelation' and item[1] != 'on': + case 'subject_manwomanrelation': generatemanwomanrelation = False - if item[0] == 'subject_fictional' and item[1] != 'on': + case 'subject_fictional': generatefictionalcharacter = False - if item[0] == 'subject_nonfictional' and item[1] != 'on': + case 'subject_nonfictional': generatenonfictionalcharacter = False - if item[0] == 'subject_humanoid' and item[1] != 'on': + case 'subject_humanoid': generatehumanoids = False - if item[0] == 'subject_job' and item[1] != 'on': + case 'subject_job': generatejob = False - if item[0] == 'subject_firstnames' and item[1] != 'on': + case 'subject_firstnames': generatefirstnames = False + # landscape - if item[0] == 'subject_landscape' and item[1] != 'on': + case 'subject_landscape': generatelandscape = False + # concept - if item[0] == 'subject_event' and item[1] != 'on': + case 'subject_event': generateevent = False - if item[0] == 'subject_concept' and item[1] != 'on': + case 'subject_concept': generateconcepts = False - if item[0] == 'poemline' and item[1] != 'on': + case 'poemline': generatepoemline = False - if item[0] == 'songline' and item[1] != 'on': + case 'songline': generatesongline = False # build up all subjects we can choose based on the loaded config file -if(generatevehicle or generateobject or generatefood or generatebuilding or generatespace): - subjects.append("object") -if(generateanimal): - subjects.append("animal") -if(generatemanwoman or generatemanwomanrelation or generatefictionalcharacter or generatenonfictionalcharacter or generatehumanoids or generatejob): - subjects.append("humanoid") -if(generatelandscape): - subjects.append("landscape") -if(generateevent or generateconcepts or generatepoemline or generatesongline): - subjects.append("concept") - - -# do the same for the subtype subjects -# subjectsubtypesobject = ["all"] -# subjectsubtypeshumanoid = ["all"] -# subjectsubtypesconcept = ["all"] +if generatevehicle or generateobject or generatefood or generatebuilding or generatespace: + subjects.append("object") +if generateanimal: + subjects.append("animal") +if generatemanwoman or generatemanwomanrelation or generatefictionalcharacter or generatenonfictionalcharacter or \ + generatehumanoids or generatejob: + subjects.append("humanoid") +if generatelandscape: + subjects.append("landscape") +if generateevent or generateconcepts or generatepoemline or generatesongline: + subjects.append("concept") # objects first -if(generateobject): - subjectsubtypesobject.append("generic objects") -if(generatevehicle): - subjectsubtypesobject.append("vehicles") -if(generatefood): - subjectsubtypesobject.append("food") -if(generatebuilding): - subjectsubtypesobject.append("buildings") -if(generatespace): - subjectsubtypesobject.append("space") -if(generateflora): - subjectsubtypesobject.append("flora") +if generateobject: + subjectsubtypesobject.append("generic objects") +if generatevehicle: + subjectsubtypesobject.append("vehicles") +if generatefood: + subjectsubtypesobject.append("food") +if generatebuilding: + subjectsubtypesobject.append("buildings") +if generatespace: + subjectsubtypesobject.append("space") +if generateflora: + subjectsubtypesobject.append("flora") # humanoids (should I review descriptions??) -if(generatemanwoman): - subjectsubtypeshumanoid.append("generic humans") -if(generatemanwomanrelation): - subjectsubtypeshumanoid.append("generic human relations") -if(generatenonfictionalcharacter): - subjectsubtypeshumanoid.append("celebrities e.a.") -if(generatefictionalcharacter): - subjectsubtypeshumanoid.append("fictional characters") -if(generatehumanoids): - subjectsubtypeshumanoid.append("humanoids") -if(generatejob): - subjectsubtypeshumanoid.append("based on job or title") -if(generatefirstnames): - subjectsubtypeshumanoid.append("based on first name") +if generatemanwoman: + subjectsubtypeshumanoid.append("generic humans") +if generatemanwomanrelation: + subjectsubtypeshumanoid.append("generic human relations") +if generatenonfictionalcharacter: + subjectsubtypeshumanoid.append("celebrities e.a.") +if generatefictionalcharacter: + subjectsubtypeshumanoid.append("fictional characters") +if generatehumanoids: + subjectsubtypeshumanoid.append("humanoids") +if generatejob: + subjectsubtypeshumanoid.append("based on job or title") +if generatefirstnames: + subjectsubtypeshumanoid.append("based on first name") # concepts -if(generateevent): - subjectsubtypesconcept.append("event") -if(generateconcepts): - subjectsubtypesconcept.append("the X of Y concepts") -if(generatepoemline): - subjectsubtypesconcept.append("lines from poems") -if(generatesongline): - subjectsubtypesconcept.append("lines from songs") - +if generateevent: + subjectsubtypesconcept.append("event") +if generateconcepts: + subjectsubtypesconcept.append("the X of Y concepts") +if generatepoemline: + subjectsubtypesconcept.append("lines from poems") +if generatesongline: + subjectsubtypesconcept.append("lines from songs") class Script(scripts.Script): - def title(self): return "One Button Prompt" def show(self, is_img2img): return True - def ui(self, is_img2img): - def gen_prompt(insanitylevel, subject, artist, imagetype, antistring, prefixprompt, suffixprompt, promptcompounderlevel, seperator,givensubject,smartsubject,giventypeofimage, imagemodechance,chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept): - + def gen_prompt( + insanitylevel, + subject, + artist, + imagetype, + antistring, + prefixprompt, + suffixprompt, + promptcompounderlevel, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept + ): promptlist = [] for i in range(5): - promptlist.append(build_dynamic_prompt(insanitylevel,subject,artist, imagetype, False, antistring,prefixprompt,suffixprompt,promptcompounderlevel,seperator,givensubject,smartsubject, giventypeofimage, imagemodechance,chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept)) - + promptlist.append(build_dynamic_prompt( + insanitylevel, + subject, + artist, + imagetype, + False, + antistring, + prefixprompt, + suffixprompt, + promptcompounderlevel, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept + )) return promptlist - + def prompttoworkflowprompt(text): return text - + # Copied code from WebUI def openfolder(): script_dir = os.path.dirname(os.path.abspath(__file__)) # Script directory - automatedoutputsfolder = os.path.join(script_dir, "../automated_outputs/" ) + automatedoutputsfolder = os.path.join(script_dir, "../automated_outputs/") path = os.path.normpath(automatedoutputsfolder) @@ -242,554 +377,641 @@ def openfolder(): sp.Popen(["wsl-open", path]) else: sp.Popen(["xdg-open", path]) - with gr.Tab("Main"): with gr.Row(): - gr.Markdown(""" - - One Button Prompt is now active. Just press the normal Generate button to start generating images. + gr.Markdown( + """ + + One Button Prompt is now active. Just press the normal Generate button to start generating images. - The settings below give you more control over what you wish to generate. - - """) + The settings below give you more control over what you wish to generate. + + """ + ) with gr.Row(): - insanitylevel = gr.Slider(1, 10, value=5, step=1, label="Higher levels increases complexity and randomness of generated prompt") + insanitylevel = gr.Slider( + 1, + 10, + value=5, + step=1, + label="Higher levels increases complexity and randomness of generated prompt" + ) with gr.Row(): with gr.Column(scale=1, variant="compact"): - subject = gr.Dropdown( - subjects, label="Subject Types", value="all") + subject = gr.Dropdown(subjects, label="Subject Types", value="all") with gr.Column(scale=1, variant="compact"): - artist = gr.Dropdown( - artists, label="Artists", value="all") + artist = gr.Dropdown(artists, label="Artists", value="all") with gr.Row(): - chosensubjectsubtypeobject = gr.Dropdown( - subjectsubtypesobject, label="Type of object", value="all", visible=False) - chosensubjectsubtypehumanoid = gr.Dropdown( - subjectsubtypeshumanoid, label="Type of humanoids", value="all", visible=False) - chosensubjectsubtypeconcept = gr.Dropdown( - subjectsubtypesconcept, label="Type of concept", value="all", visible=False) - chosengender = gr.Dropdown( - genders, label="gender", value="all", visible=False) + chosensubjectsubtypeobject = gr.Dropdown( + subjectsubtypesobject, + label="Type of object", + value="all", + visible=False + ) + chosensubjectsubtypehumanoid = gr.Dropdown( + subjectsubtypeshumanoid, + label="Type of humanoids", + value="all", + visible=False + ) + chosensubjectsubtypeconcept = gr.Dropdown( + subjectsubtypesconcept, + label="Type of concept", + value="all", + visible=False + ) + chosengender = gr.Dropdown(genders, label="gender", value="all", visible=False) with gr.Row(): with gr.Column(scale=2, variant="compact"): - imagetype = gr.Dropdown( - imagetypes, label="type of image", value="all") + imagetype = gr.Dropdown(imagetypes, label="type of image", value="all") with gr.Column(scale=2, variant="compact"): imagemodechance = gr.Slider( - 1, 100, value="20", step=1, label="One in X chance to use special image type mode") + 1, + 100, + value="20", + step=1, + label="One in X chance to use special image type mode" + ) with gr.Row(): - gr.Markdown(""" - - Override options (choose the related subject type first for better results) - - """ - ) + gr.Markdown( + """ + + Override options (choose the related subject type first for better results) + + """ + ) with gr.Row(): - givensubject = gr.Textbox(label="Overwrite subject: ", value="") - smartsubject = gr.Checkbox(label="Smart subject", value = True) + givensubject = gr.Textbox(label="Overwrite subject: ", value="") + smartsubject = gr.Checkbox(label="Smart subject", value=True) with gr.Row(): - gr.Markdown(""" - - Prompt fields - - """ + gr.Markdown( + """ + + Prompt fields + + """ ) with gr.Row(): with gr.Column(): - prefixprompt = gr.Textbox(label="Place this in front of generated prompt (prefix)",value="") - suffixprompt = gr.Textbox(label="Place this at back of generated prompt (suffix)",value="") - negativeprompt = gr.Textbox(label="Use this negative prompt",value="") + prefixprompt = gr.Textbox(label="Place this in front of generated prompt (prefix)", value="") + suffixprompt = gr.Textbox(label="Place this at back of generated prompt (suffix)", value="") + negativeprompt = gr.Textbox(label="Use this negative prompt", value="") with gr.Row(): - gr.Markdown(""" - - Additional options - - """ + gr.Markdown( + """ + + Additional options + + """ ) with gr.Row(): - giventypeofimage = gr.Textbox(label="Overwrite type of image: ", value="") + giventypeofimage = gr.Textbox(label="Overwrite type of image: ", value="") with gr.Row(): with gr.Column(): - antistring = gr.Textbox(label="Filter out following properties (comma seperated). Example ""film grain, purple, cat"" ") + antistring = gr.Textbox( + label="Filter out following properties (comma seperated). Example ""film grain, purple, cat""" + ) with gr.Row(): - gr.Markdown( - """ - ### Description - - - Just press the normal Generate button. - - This generator will generate a complete full prompt for you and generate the image, based on randomness. You can increase the slider, to include more things to put into the prompt. - Recommended is keeping it around 3-7. Use 10 at your own risk. - - There are a lot of special things build in, based on various research papers. Just try it, and let it surprise you. - - Add additional prompting to the prefix, suffix and negative prompt in this screen. The actual prompt fields are ignored. - - - ### Subject Types - - - You can choose a certain subject type, if you want to generate something more specific. It has the following types: - - 1. object - Can be a random object, a building or a vehicle. - - 2. animal - A random (fictional) animal. Has a chance to have human characteristics, such as clothing added. - - 3. humanoid - A random humanoid, males, females, fantasy types, fictional and non-fictional characters. Can add clothing, features and a bunch of other things. - - 4. landscape - A landscape or a landscape with a building. - - 5. concept - Can be a concept, such as "a X of Y", or an historical event such as "The Trojan War". It can also generate a line from a poem or a song. - - After choosing object, humanoid or concept a subselection menu will show. You can pick further details here. When choosing humanoid, you can also select the gender you wish to generate. - - Type of Object: - - 1. all - selects randomly (default) - - 2. generic objects - Hodgepodge of objects, can be household items, weapons or any other general object. - - 3. vehicles - Cars, but also planes, trains and boats. - - 4. food - Meals, fruits and others. - - 5. buildings - From churches to libraries to castles. - - 6. space - Some bigger objects, nebula's, black holes and constellations - - 7. flora - Flowers and trees. - - Type of humanoid: - - 1. all - selects randomly (default) - - 2. generic humans - Generic human descriptions. Example values would be Man, Woman, Male, etc - - 3. generic human relations - Human relations, example values would be Grandpa, Sister, Father, etc - - 4. celebrities e.a. - Known people, usually celebrities. - - 5. fictional characters - Movie and videogame characters, such as Mario and Peach. - - 6. humanoids - Humanoid type races, think Elves, Orcs, Dwarves, etc - - 7. based on job or title - Examples are Queen, Carpenter, Vampire hunter - - 8. based on first name - Examples are Anna, James, Emma etc. - - gender: - - 1. all - selects randomly - - 2. male - - 3. female - - Type of concept: - - 1. all - selects randomly (default) - - 2. event - an historical event, or even mythological event. Example The fall of Rome - - 3. the X of Y concepts - Randomly creates a small sentence, example The Ocean of Thought or The Fortress of Flame, etc - - 4. lines from poems - Picks a line from a poem - - 5. lines from songs - Picks a line from a song - - - - ### Artists - - - Artists have a major impact on the result. Automatically, it will select between 0-3 artists out of 3483 artists for your prompt. - - You can turn it off and maybe add your own in the prefix or suffix prompt fields - - - ### type of image - - - There are an immense number of image types, not only paintings and photo's, but also isometric renders and funko pops. - You can however, overwrite it with the most popular ones. - + gr.Markdown(""" +### Description + + +Just press the normal Generate button. + +This generator will generate a complete full prompt for you and generate the image, +based on randomness. You can increase the slider, to include more things to put into the prompt. +Recommended is keeping it around 3-7. Use 10 at your own risk. + +There are a lot of special things build in, based on various research papers. +Just try it, and let it surprise you. + +Add additional prompting to the prefix, suffix and negative prompt in this screen. +The actual prompt fields are ignored. + + +### Subject Types + + +You can choose a certain subject type, if you want to generate something more specific. +It has the following types: + +1. object - Can be a random object, a building or a vehicle. +2. animal - A random (fictional) animal. Has a chance to have human characteristics, such as clothing added. +3. humanoid - A random humanoid, males, females, fantasy types, fictional and non-fictional characters. \ +Can add clothing, features and a bunch of other things. +4. landscape - A landscape or a landscape with a building. +5. concept - Can be a concept, such as "a X of Y", or an historical event such as "The Trojan War". \ +It can also generate a line from a poem or a song. + +After choosing object, humanoid or concept a subselection menu will show. +You can pick further details here. When choosing humanoid, you can also select the gender you wish to generate. + +#### Type of Object: + +1. all - selects randomly (default) +2. generic objects - Hodgepodge of objects, can be household items, weapons or any other general object. +3. vehicles - Cars, but also planes, trains and boats. +4. food - Meals, fruits and others. +5. buildings - From churches to libraries to castles. +6. space - Some bigger objects, nebula's, black holes and constellations +7. flora - Flowers and trees. - 1. all --> normally picks a image type as random. Can choose a 'other' more unique type. +#### Type of humanoid: - 2. all - force multiple --> idea by redditor WestWordHoeDown, it forces to choose between 2 and 3 image types - - 3. photograph +1. all - selects randomly (default) +2. generic humans - Generic human descriptions. Example values would be Man, Woman, Male, etc +3. generic human relations - Human relations, example values would be Grandpa, Sister, Father, etc +4. celebrities e.a. - Known people, usually celebrities. +5. fictional characters - Movie and videogame characters, such as Mario and Peach. +6. humanoids - Humanoid type races, think Elves, Orcs, Dwarves, etc +7. based on job or title - Examples are Queen, Carpenter, Vampire hunter +8. based on first name - Examples are Anna, James, Emma etc. - 4. octane render +#### gender: - 5. digital art +1. all - selects randomly +2. male +3. female - 6. concept art +#### Type of concept: - 7. painting +1. all - selects randomly (default) +2. event - an historical event, or even mythological event. Example The fall of Rome +3. the X of Y concepts - Randomly creates a small sentence, example The Ocean of Thought or The Fortress of Flame, etc +4. lines from poems - Picks a line from a poem +5. lines from songs - Picks a line from a song + - 6. portrait +### Artists - 7. anime key visual - - 8. only other types --> Will pick only from the more unique types, such as stained glass window or a funko pop + +Artists have a major impact on the result. +Automatically, it will select between 0-3 artists out of 3483 artists for your prompt. - All modes below are considered a special image type mode. +You can turn it off and maybe add your own in the prefix or suffix prompt fields + - 9. only templates mode --> Will only choose from a set of wildcarded prompt templates. Templates have been gathered from various sources, such as CivitAI, prompthero, promptbook, etc. +### type of image - only templates mode is perfect for beginners, who want to see some good results fast. + +There are an immense number of image types, not only paintings and photo's, but also isometric renders and funko pops. +You can however, overwrite it with the most popular ones. - 10. art blaster mode --> Special generation mode that focusses on art movements, stylings and artists. +1. Normal + 1. all --> normally picks a image type as random. Can choose a 'other' more unique type. + 2. all - force multiple --> idea by redditor WestWordHoeDown, it forces to choose between 2 and 3 image types + 3. photograph + 4. octane render + 5. digital art + 6. concept art + 7. painting + 8. portrait + 9. anime key visual + 10. only other types --> Will pick only from the more unique types, such as stained glass window or a funko pop - 11. quality vomit mode --> Special generation mode that focusses on qualifiers and stylings. +2. All modes below are considered a special image type mode. + 11. only templates mode --> Will only choose from a set of wildcarded prompt templates. \ + Templates have been gathered from various sources, such as CivitAI, prompthero, promptbook, etc. \ + only templates mode is perfect for beginners, who want to see some good results fast. + 12. art blaster mode --> art movements, stylings and artists. + 13. quality vomit mode --> qualifiers and stylings. + 14. color cannon mode --> color scheme's and moods. + 15. unique art mode --> other image types, art movements, stylings and lighting. + 16. massive madness mode --> Special generation mode, creates prompt soup. Almost pure randomness. + 17. photo fantasy mode --> photographs, cameras, lenses and lighting. + 18. subject only mode --> Will only generate a subject, with no additional frills. + 19. fixed styles mode --> Generate a subject on top of a fixed style. - 12. color cannon mode --> Special generation mode that focusses on color scheme's and moods. +### One in X chance to use special image type mode - 13. unique art mode --> Special generation mode that focusses on other image types, art movements, stylings and lighting. + +This controls how often it will pick a special generation mode. It is a 1 in X chance. +So lower means more often. This will only be applied of "type of image" is set to "all" and +there is no Overwrite type of image set. - 14. massive madness mode --> Special generation mode, creates prompt soup. Almost pure randomness. +When set to 1, it will always pick a random special generation mode. +When set to 20, it is a 1 in 20 chance this will happen. + - 15. photo fantasy mode --> Special generation mode that focusses on photographs, cameras, lenses and lighting. +### Overwrite subject - 16. subject only mode --> Will only generate a subject, with no additional frills. +When you fill in the Overwrite subject field, that subject will be used to build the dynamic prompt around. +It is best, if you set the subject type to match the subject. +For example, set it to humanoid if you place a person in the override subject field. - 17. fixed styles mode --> Generate a subject on top of a fixed style. +This way, you can create unlimited variants of a subject. - ### One in X chance to use special image type mode +Smart subject tries to determine what to and not to generate based on your subject. +Example, if your Overwrite subject is formed like this: Obese man wearing a kimono - - This controls how often it will pick a special generation mode. It is a 1 in X chance. So lower means more often. This will only be applied of "type of image" is set to "all" and there is no Overwrite type of image set. +It will then recognize the body type and not generate it. +It also recognizes the keyword wearing, and will not generate an outfit. - When set to 1, it will always pick a random special generation mode. When set to 20, it is a 1 in 20 chance this will happen. - - - ### Overwrite subject +### Other prompt fields - When you fill in the Overwrite subject field, that subject will be used to build the dynamic prompt around. It is best, if you set the subject type to match the subject. For example, set it to humanoid if you place a person in the override subject field. - - This way, you can create unlimited variants of a subject. +The existing prompt and negative prompt fields are ignored. - Smart subject tries to determine what to and not to generate based on your subject. Example, if your Overwrite subject is formed like this: Obese man wearing a kimono - - It will then recognize the body type and not generate it. It also recognizes the keyword wearing, and will not generate an outfit. +Add a prompt prefix, suffix and the negative prompt in the respective fields. +They will be automatically added during processing. - ### Other prompt fields +These can be used to add textual inversion and LoRA's to always apply. +They can also be used to add your models trigger words. - The existing prompt and negative prompt fields are ignored. - - Add a prompt prefix, suffix and the negative prompt in the respective fields. They will be automatically added during processing. +Please read the custom_files documentation on how to apply random textual inversion and LoRA's. - These can be used to add textual inversion and LoRA's to always apply. They can also be used to add your models trigger words. + - Please read the custom_files documentation on how to apply random textual inversion and LoRA's. +### Filter values + +You can put comma seperated values here, those will be ignored from any list processing. +For example, adding ""film grain, sepia"", will make these values not appear during generation. - +For advanced users, you can create a permanent file in \\OneButtonPrompt\\userfiles\\ called antilist.csv - ### Filter values - - You can put comma seperated values here, those will be ignored from any list processing. For example, adding ""film grain, sepia"", will make these values not appear during generation. +This way, you don't ever have to add it manually again. This file won't be overwritten during upgrades. - For advanced users, you can create a permanent file in \\OneButtonPrompt\\userfiles\\ called antilist.csv - - This way, you don't ever have to add it manually again. This file won't be overwritten during upgrades. +Idea by redditor jonesaid. - Idea by redditor jonesaid. + + """) - - """ - ) with gr.Tab("Workflow assist"): with gr.Row(): - silentmode = gr.Checkbox( - label="Workflow mode, turns off prompt generation and uses below Workflow prompt instead.") + silentmode = gr.Checkbox( + label="Workflow mode, turns off prompt generation and uses below Workflow prompt instead." + ) with gr.Row(): workprompt = gr.Textbox(label="Workflow prompt") with gr.Row(): - promptvariantinsanitylevel = gr.Slider(0, 10, value=0, step=1, label="Prompt variant. Strength of variation of workflow prompt. 0 = no variance.") + promptvariantinsanitylevel = gr.Slider( + 0, + 10, + value=0, + step=1, + label="Prompt variant. Strength of variation of workflow prompt. 0 = no variance." + ) with gr.Row(): gr.Markdown( - """ - - Workflow assist, suggestions by redditor Woisek. + """ + + Workflow assist, suggestions by redditor Woisek. - With Workflow mode, you turn off the automatic generation of new prompts on 'generate', and it will use the Workflow prompt field instead. So you can work and finetune any fun prompts without turning of the script. + With Workflow mode, you turn off the automatic generation of new prompts on 'generate' + and it will use the Workflow prompt field instead. + So you can work and finetune any fun prompts without turning of the script. - You can use One Button Prompt wildcards in the workflow prompt. For example -outfit- . + You can use One Button Prompt wildcards in the workflow prompt. For example -outfit- . - With the Prompt Variant, you can let One Button Prompt dynamically create small variance in the workflow prompt. 0 means no effect. + With the Prompt Variant, you can let One Button Prompt dynamically create small variance + in the workflow prompt. 0 means no effect. - Below here, you can generate a set of random prompts, and send them to the Workflow prompt field. The generation of the prompt uses the settings in the Main tab. - - """) + Below here, you can generate a set of random prompts, and send them to the Workflow prompt field. + The generation of the prompt uses the settings in the Main tab. + + """ + ) with gr.Row(): genprom = gr.Button("Generate me some prompts!") with gr.Row(): - with gr.Column(scale=4): - prompt1 = gr.Textbox(label="prompt 1") - with gr.Column(scale=1, variant="compact"): - prompt1toworkflow = gr.Button("Send prompt up") + with gr.Column(scale=4): + prompt1 = gr.Textbox(label="prompt 1") + with gr.Column(scale=1, variant="compact"): + prompt1toworkflow = gr.Button("Send prompt up") with gr.Row(): - with gr.Column(scale=4): - prompt2 = gr.Textbox(label="prompt 2") - with gr.Column(scale=1, variant="compact"): - prompt2toworkflow = gr.Button("Send prompt up") + with gr.Column(scale=4): + prompt2 = gr.Textbox(label="prompt 2") + with gr.Column(scale=1, variant="compact"): + prompt2toworkflow = gr.Button("Send prompt up") with gr.Row(): - with gr.Column(scale=4): - prompt3 = gr.Textbox(label="prompt 3") - with gr.Column(scale=1, variant="compact"): - prompt3toworkflow = gr.Button("Send prompt up") + with gr.Column(scale=4): + prompt3 = gr.Textbox(label="prompt 3") + with gr.Column(scale=1, variant="compact"): + prompt3toworkflow = gr.Button("Send prompt up") with gr.Row(): - with gr.Column(scale=4): - prompt4 = gr.Textbox(label="prompt 4") - with gr.Column(scale=1, variant="compact"): - prompt4toworkflow = gr.Button("Send prompt up") + with gr.Column(scale=4): + prompt4 = gr.Textbox(label="prompt 4") + with gr.Column(scale=1, variant="compact"): + prompt4toworkflow = gr.Button("Send prompt up") with gr.Row(): - with gr.Column(scale=4): - prompt5 = gr.Textbox(label="prompt 5") - with gr.Column(scale=1, variant="compact"): - prompt5toworkflow = gr.Button("Send prompt up") + with gr.Column(scale=4): + prompt5 = gr.Textbox(label="prompt 5") + with gr.Column(scale=1, variant="compact"): + prompt5toworkflow = gr.Button("Send prompt up") + with gr.Tab("Advanced"): with gr.Row(): with gr.Column(scale=1): - promptcompounderlevel = gr.Dropdown( - promptcompounder, label="Prompt compounder", value="1") + promptcompounderlevel = gr.Dropdown(promptcompounder, label="Prompt compounder", value="1") with gr.Row(): with gr.Column(scale=1): - seperator = gr.Dropdown( - seperatorlist, label="Prompt seperator", value="comma") + seperator = gr.Dropdown(seperatorlist, label="Prompt seperator", value="comma") with gr.Column(scale=2): - ANDtoggle = gr.Dropdown( - ANDtogglemode, label="Prompt seperator mode", value="none") + ANDtoggle = gr.Dropdown(ANDtogglemode, label="Prompt seperator mode", value="none") with gr.Row(): gr.Markdown( """ ### Prompt compounder - + - Normally, it creates a single random prompt. With prompt compounder, it will generate multiple prompts and compound them together. - + Normally, it creates a single random prompt. With prompt compounder, + it will generate multiple prompts and compound them together. + Keep at 1 for normal behavior. Set to different values to compound that many prompts together. My suggestion is to try 2 first. - - This was originally a bug in the first release when using multiple batches, now brought back as a feature. - Raised by redditor drone2222, to bring this back as a toggle, since it did create interesting results. So here it is. - + + This was originally a bug in the first release when using multiple batches, + now brought back as a feature. + Raised by redditor drone2222, to bring this back as a toggle, + since it did create interesting results. So here it is. + You can toggle the separator mode. Standardly this is a comma, but you can choose an AND or a BREAK. - + You can also choose the prompt seperator mode for use with Latent Couple extension - + Example flow: Set the Latent Couple extension to 2 area's (standard setting) - + In the main tab, set the subject to humanoids - + In the prefix prompt field then add for example: Art by artistname, 2 people - + Set the prompt compounder to: 2 - + Set the Prompt seperator to: AND Set the Prompt Seperator mode to: prefix AND prompt + suffix - "automatic" is entirely build around Latent Couple. It will pass artists and the amount of people/animals/objects to generate in the prompt automatically. Set the prompt compounder equal to the amount of areas defined in Laten Couple. - + "automatic" is entirely build around Latent Couple. + It will pass artists and the amount of people/animals/objects to generate + in the prompt automatically. + Set the prompt compounder equal to the amount of areas defined in Laten Couple. + Example flow: Set the Latent Couple extension to 2 area's (standard setting) - + In the main tab, set the subject to humanoids - + Leave the prompt field empty - + Set the prompt compounder to: 2 Set the Prompt seperator to: AND Set the Prompt Seperator mode to: automatic - - + """ - ) + ) + with gr.Tab("One Button Run and Upscale"): with gr.Row(): - gr.Markdown( - """ - ### TXT2IMG - - Start WebUi with option --api for this to work. This is not needed for Vlad SD Next. + gr.Markdown( + """ + ### TXT2IMG + + Start WebUi with option --api for this to work. This is not needed for Vlad SD Next. - Note: This part is entirely optional and you can use the normal generate button. + Note: This part is entirely optional and you can use the normal generate button. - This part is only intended for running an upscaling at the same time. - - """ - ) + This part is only intended for running an upscaling at the same time. + + """ + ) with gr.Row(): - with gr.Column(scale=1): - startmain = gr.Button("Start generating and upscaling!") - interrupt = gr.Button("Interrupt current") - automatedoutputsfolderbutton = gr.Button(folder_symbol) - apiurl = gr.Textbox(label="URL", value="http://127.0.0.1:7860") - with gr.Column(scale=1): - onlyupscale = gr.Checkbox(label="Don't generate, only upscale", value=False) - gr.Markdown( - """ - - Only upscale will not use txt2img to generate an image. - - Instead it will pick up all files in the \\upscale_me\\ folder and upscale them with below settings. - - """ - ) - increasestability = gr.Checkbox(label="Increase stability", value=False) - gr.Markdown( - """ - - If you get NaN's or memory issues, turn this on. - - """ - ) + with gr.Column(scale=1): + startmain = gr.Button("Start generating and upscaling!") + interrupt = gr.Button("Interrupt current") + automatedoutputsfolderbutton = gr.Button(folder_symbol) + apiurl = gr.Textbox(label="URL", value="http://127.0.0.1:7860") + with gr.Column(scale=1): + onlyupscale = gr.Checkbox(label="Don't generate, only upscale", value=False) + gr.Markdown( + """ + + Only upscale will not use txt2img to generate an image. + + Instead it will pick up all files in the \\upscale_me\\ folder and + upscale them with below settings. + + """ + ) + increasestability = gr.Checkbox(label="Increase stability", value=False) + gr.Markdown( + """ + + If you get NaN's or memory issues, turn this on. + + """ + ) with gr.Row(): with gr.Column(scale=1): - amountofimages = gr.Slider(1, 50, value="20", step=1, label="Amount of images to generate") - size = gr.Dropdown( - sizelist, label="Size to generate", value="all") - basesize = gr.Dropdown( - basesizelist, label="base size", value="512") + size = gr.Dropdown(sizelist, label="Size to generate", value="all") + basesize = gr.Dropdown(basesizelist, label="base size", value="512") with gr.Row(scale=1): samplingsteps = gr.Slider(1, 100, value="20", step=1, label="Sampling steps") - cfg = gr.Slider(1,20, value="6.0", step=0.1, label="CFG") - with gr.Row(scale=1): + cfg = gr.Slider(1, 20, value="6.0", step=0.1, label="CFG") + with gr.Row(scale=1): hiresfix = gr.Checkbox(label="hires. fix", value=True) - hiressteps = gr.Slider(0, 100, value = "0", step=1, label="Hires steps") - hiresscale = gr.Slider(1, 4, value = "2", step=0.05, label="Scale") + hiressteps = gr.Slider(0, 100, value="0", step=1, label="Hires steps") + hiresscale = gr.Slider(1, 4, value="2", step=0.05, label="Scale") denoisestrength = gr.Slider(0, 1, value="0.60", step=0.01, label="Denoise strength") with gr.Column(scale=1): - - model = gr.Dropdown( - modellist, label="model to use", value="currently selected model") + model = gr.Dropdown(modellist, label="model to use", value="currently selected model") with gr.Column(scale=1): - samplingmethod = gr.Dropdown( - samplerlist, label= "Sampler", value="all") - upscaler = gr.Dropdown( - upscalerlist, label="hires upscaler", value="all") + samplingmethod = gr.Dropdown(samplerlist, label="Sampler", value="all") + upscaler = gr.Dropdown(upscalerlist, label="hires upscaler", value="all") with gr.Row(): gr.Markdown( - """ - ### Quality Gate - - Uses aesthetic image scorer extension to check the quality of the image. - - Once turned on, it will retry for n amount of times to get an image with the quality score. If not, it will take the best image so far and continue or set it to gated to only take matching or higher quality images. - - You can move Hiresfix to be applied afterwards. You can opt to keep all generated images. - - Idea and inspiration by xKean. Additional improvements suggested by pto2k. - - """ - ) + """ + ### Quality Gate + + Uses aesthetic image scorer extension to check the quality of the image. + + Once turned on, it will retry for n amount of times to get an image with the quality score. + If not, it will take the best image so far and continue or set it to gated to only take + matching or higher quality images. + + You can move Hiresfix to be applied afterwards. You can opt to keep all generated images. + + Idea and inspiration by xKean. Additional improvements suggested by pto2k. + + """ + ) with gr.Row(): - qualitygate = gr.Checkbox(label="Quality Gate", value=False) - quality = gr.Slider(1, 10, value = "7.2", step=0.1, label="Quality", visible = False) - runs = gr.Slider(1, 50, value = "5", step=1, label="Amount of tries", visible = False) + qualitygate = gr.Checkbox(label="Quality Gate", value=False) + quality = gr.Slider(1, 10, value="7.2", step=0.1, label="Quality", visible=False) + runs = gr.Slider(1, 50, value="5", step=1, label="Amount of tries", visible=False) with gr.Row(): - qualityhiresfix = gr.Checkbox(label="Move Hires fix afterwards", value=False, visible = False) - qualitymode = gr.Dropdown( - qualitymodelist, label= "Mode of operation", value="highest", visible = False) - qualitykeep = gr.Dropdown( - qualitykeeplist, label= "Images", value="keep used", visible = False) + qualityhiresfix = gr.Checkbox(label="Move Hires fix afterwards", value=False, visible=False) + qualitymode = gr.Dropdown(qualitymodelist, label="Mode of operation", value="highest", visible=False) + qualitykeep = gr.Dropdown(qualitykeeplist, label="Images", value="keep used", visible=False) with gr.Row(): - gr.Markdown( - """ - ### IMG2IMG upscale - """ - ) + gr.Markdown( + """ + ### IMG2IMG upscale + """ + ) with gr.Row(): - img2imgactivate = gr.Checkbox(label="Upscale image with IMG2IMG", value=True) + img2imgactivate = gr.Checkbox(label="Upscale image with IMG2IMG", value=True) with gr.Row(): - with gr.Column(scale=1): - img2imgbatch = gr.Slider(1, 5, value="1", step=1, label="Amount times to repeat upscaling with IMG2IMG (loopback)") - img2imgsamplingsteps = gr.Slider(1, 100, value="20", step=1, label="img2img Sampling steps") - img2imgcfg = gr.Slider(1,20, value="6", step=0.1, label="img2img CFG") - img2imgdenoisestrength = gr.Slider(0, 1, value="0.30", step=0.01, label="img2img denoise strength") - img2imgdenoisestrengthmod = gr.Slider(-1,1, value = "-0.05", step=0.01, label="adjust denoise each img2img batch") - with gr.Column(scale=1): - img2imgmodel = gr.Dropdown( - modellist, label="img2img model to use", value="currently selected model") - img2imgsamplingmethod = gr.Dropdown( - img2imgsamplerlist, label= "img2img sampler", value="all") - img2imgupscaler = gr.Dropdown( - img2imgupscalerlist, label="img2img upscaler", value="all") - with gr.Row(): - img2imgscale = gr.Slider(1, 4, value="2", step=0.05, label="img2img scale") - img2imgpadding = gr.Slider(32, 256, value="64", step=12, label="img2img padding") + with gr.Column(scale=1): + img2imgbatch = gr.Slider( + 1, + 5, + value="1", + step=1, + label="Amount times to repeat upscaling with IMG2IMG (loopback)" + ) + img2imgsamplingsteps = gr.Slider(1, 100, value="20", step=1, label="img2img Sampling steps") + img2imgcfg = gr.Slider(1, 20, value="6", step=0.1, label="img2img CFG") + img2imgdenoisestrength = gr.Slider(0, 1, value="0.30", step=0.01, label="img2img denoise strength") + img2imgdenoisestrengthmod = gr.Slider( + -1, + 1, + value="-0.05", + step=0.01, + label="adjust denoise each img2img batch" + ) + with gr.Column(scale=1): + img2imgmodel = gr.Dropdown( + modellist, + label="img2img model to use", + value="currently selected model" + ) + img2imgsamplingmethod = gr.Dropdown(img2imgsamplerlist, label="img2img sampler", value="all") + img2imgupscaler = gr.Dropdown(img2imgupscalerlist, label="img2img upscaler", value="all") + with gr.Row(): + img2imgscale = gr.Slider(1, 4, value="2", step=0.05, label="img2img scale") + img2imgpadding = gr.Slider(32, 256, value="64", step=12, label="img2img padding") with gr.Row(): - ultimatesdupscale = gr.Checkbox(label="Use Ultimate SD Upscale script instead", value=False) - gr.Markdown( - """ - - This requires the Ultimate SD Upscale extension, install this if you haven't - - """ - ) + ultimatesdupscale = gr.Checkbox(label="Use Ultimate SD Upscale script instead", value=False) + gr.Markdown( + """ + + This requires the Ultimate SD Upscale extension, install this if you haven't + + """ + ) with gr.Row(): - with gr.Column(scale = 1): - #usdutilewidth, usdutileheight, usdumaskblur, usduredraw, usduSeamsfix, usdusdenoise, usduswidth, usduspadding, usdusmaskblur - #usdutilewidth = "512", usdutileheight = "0", usdumaskblur = "8", usduredraw ="Linear", usduSeamsfix = "None", usdusdenoise = "0.35", usduswidth = "64", usduspadding ="32", usdusmaskblur = "8" - usdutilewidth = gr.Slider(0, 2048, value="512", step=12, label="tile width", visible = False) - usdutileheight = gr.Slider(0, 2048, value="0", step=12, label="tile height", visible = False) - usdumaskblur = gr.Slider(0, 64, value="8", step=1, label="Mask blur", visible = False) - usduredraw = gr.Dropdown( - redraw_modes, label="Type", value="Linear", visible = False) - with gr.Column(scale = 1): - usduSeamsfix = gr.Dropdown( - seams_fix_types, label="Seams fix", value="None", visible = False) - usdusdenoise = gr.Slider(0, 1, value="0.35", step=0.01, label="Seams denoise strenght", visible = False) - usduswidth = gr.Slider(0, 128, value="64", step=12, label="Seams Width", visible = False) - usduspadding = gr.Slider(0, 128, value="32", step=12, label="Seams padding", visible = False) - usdusmaskblur = gr.Slider(0, 64, value="8", step=1, label="Seams Mask blur (offset pass only)", visible = False) + with gr.Column(scale=1): + usdutilewidth = gr.Slider(0, 2048, value="512", step=12, label="tile width", visible=False) + usdutileheight = gr.Slider(0, 2048, value="0", step=12, label="tile height", visible=False) + usdumaskblur = gr.Slider(0, 64, value="8", step=1, label="Mask blur", visible=False) + usduredraw = gr.Dropdown(redraw_modes, label="Type", value="Linear", visible=False) + with gr.Column(scale=1): + usduSeamsfix = gr.Dropdown(seams_fix_types, label="Seams fix", value="None", visible=False) + usdusdenoise = gr.Slider( + 0, + 1, + value="0.35", + step=0.01, + label="Seams denoise strenght", + visible=False + ) + usduswidth = gr.Slider(0, 128, value="64", step=12, label="Seams Width", visible=False) + usduspadding = gr.Slider(0, 128, value="32", step=12, label="Seams padding", visible=False) + usdusmaskblur = gr.Slider( + 0, + 64, + value="8", + step=1, + label="Seams Mask blur (offset pass only)", + visible=False + ) with gr.Row(): - with gr.Column(scale = 1): - controlnetenabled = gr.Checkbox(label="Enable controlnet tile resample", value=False) - controlnetblockymode = gr.Checkbox(label="also enable wierd blocky upscale mode", value=False) - with gr.Column(scale = 1): - controlnetmodel = gr.Textbox(label="Controlnet tile model name", value = "control_v11f1e_sd15_tile [a371b31b]") + with gr.Column(scale=1): + controlnetenabled = gr.Checkbox(label="Enable controlnet tile resample", value=False) + controlnetblockymode = gr.Checkbox(label="also enable wierd blocky upscale mode", value=False) + with gr.Column(scale=1): + controlnetmodel = gr.Textbox( + label="Controlnet tile model name", + value="control_v11f1e_sd15_tile [a371b31b]" + ) with gr.Row(): - gr.Markdown( - """ - - This requires Controlnet 1.1 extension and the tile resample model, install this if you haven't - In settings for Controlnet, enable "Allow other script to control this extension" - - Don't use wierd blocky upscale mode. Or maybe do? - - """ - ) + gr.Markdown( + """ + + This requires Controlnet 1.1 extension and the tile resample model, install this if you haven't + In settings for Controlnet, enable "Allow other script to control this extension" + + Don't use wierd blocky upscale mode. Or maybe do? + + """ + ) with gr.Row(): - with gr.Column(scale = 1): - enableextraupscale = gr.Checkbox(label="Enable upscale with extras", value=False) + with gr.Column(scale=1): + enableextraupscale = gr.Checkbox(label="Enable upscale with extras", value=False) with gr.Row(): - with gr.Column(scale = 1): - extrasresize = gr.Slider(0, 8, value="2", step=0.05, label="Upscale resize", visible = False) - extrasupscaler1 = gr.Dropdown( - img2imgupscalerlist, label="upscaler 1", value="all", visible = False) - extrasupscaler2 = gr.Dropdown( - img2imgupscalerlist, label="upscaler 2", value="all", visible = False) - extrasupscaler2visiblity = gr.Slider(0, 1, value="0.5", step=0.05, label="Upscaler 2 vis.", visible = False) - with gr.Column(scale = 1): - extrasupscaler2gfpgan = gr.Slider(0, 1, value="0", step=0.05, label="GFPGAN vis.", visible = False) - extrasupscaler2codeformer = gr.Slider(0, 1, value="0.15", step=0.05, label="CodeFormer vis.", visible = False) - extrasupscaler2codeformerweight = gr.Slider(0, 1, value="0.1", step=0.05, label="CodeFormer weight", visible = False) - - - genprom.click(gen_prompt, inputs=[insanitylevel,subject, artist, imagetype, antistring,prefixprompt, suffixprompt,promptcompounderlevel, seperator, givensubject,smartsubject,giventypeofimage,imagemodechance, chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept], outputs=[prompt1, prompt2, prompt3,prompt4,prompt5]) + with gr.Column(scale=1): + extrasresize = gr.Slider(0, 8, value="2", step=0.05, label="Upscale resize", visible=False) + extrasupscaler1 = gr.Dropdown( + img2imgupscalerlist, + label="upscaler 1", + value="all", + visible=False + ) + extrasupscaler2 = gr.Dropdown( + img2imgupscalerlist, + label="upscaler 2", + value="all", + visible=False + ) + extrasupscaler2visiblity = gr.Slider( + 0, + 1, + value="0.5", + step=0.05, + label="Upscaler 2 vis.", + visible=False + ) + + with gr.Column(scale=1): + extrasupscaler2gfpgan = gr.Slider(0, 1, value="0", step=0.05, label="GFPGAN vis.", visible=False) + extrasupscaler2codeformer = gr.Slider( + 0, + 1, + value="0.15", + step=0.05, + label="CodeFormer vis.", + visible=False + ) + extrasupscaler2codeformerweight = gr.Slider( + 0, + 1, + value="0.1", + step=0.05, + label="CodeFormer weight", + visible=False + ) + + genprom.click( + gen_prompt, + inputs=[ + insanitylevel, + subject, + artist, + imagetype, + antistring, + prefixprompt, + suffixprompt, + promptcompounderlevel, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept + ], + outputs=[prompt1, prompt2, prompt3, prompt4, prompt5] + ) prompt1toworkflow.click(prompttoworkflowprompt, inputs=prompt1, outputs=workprompt) prompt2toworkflow.click(prompttoworkflowprompt, inputs=prompt2, outputs=workprompt) @@ -797,263 +1019,410 @@ def openfolder(): prompt4toworkflow.click(prompttoworkflowprompt, inputs=prompt4, outputs=workprompt) prompt5toworkflow.click(prompttoworkflowprompt, inputs=prompt5, outputs=workprompt) - startmain.click(generateimages, inputs=[amountofimages,size,model,samplingsteps,cfg,hiresfix,hiressteps,denoisestrength,samplingmethod, upscaler,hiresscale, apiurl, qualitygate, quality, runs,insanitylevel,subject, artist, imagetype, silentmode, workprompt, antistring, prefixprompt, suffixprompt,negativeprompt,promptcompounderlevel, seperator, img2imgbatch, img2imgsamplingsteps, img2imgcfg, img2imgsamplingmethod, img2imgupscaler, img2imgmodel,img2imgactivate, img2imgscale, img2imgpadding,img2imgdenoisestrength,ultimatesdupscale,usdutilewidth, usdutileheight, usdumaskblur, usduredraw, usduSeamsfix, usdusdenoise, usduswidth, usduspadding, usdusmaskblur, controlnetenabled, controlnetmodel,img2imgdenoisestrengthmod,enableextraupscale,controlnetblockymode,extrasupscaler1,extrasupscaler2,extrasupscaler2visiblity,extrasupscaler2gfpgan,extrasupscaler2codeformer,extrasupscaler2codeformerweight,extrasresize,onlyupscale,givensubject,smartsubject,giventypeofimage,imagemodechance, chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept, increasestability, qualityhiresfix, qualitymode, qualitykeep, basesize, promptvariantinsanitylevel]) + startmain.click( + generateimages, + inputs=[ + amountofimages, + size, + model, + samplingsteps, + cfg, + hiresfix, + hiressteps, + denoisestrength, + samplingmethod, + upscaler, + hiresscale, + apiurl, + qualitygate, + quality, + runs, + insanitylevel, + subject, + artist, + imagetype, + silentmode, + workprompt, + antistring, + prefixprompt, + suffixprompt, + negativeprompt, + promptcompounderlevel, + seperator, + img2imgbatch, + img2imgsamplingsteps, + img2imgcfg, + img2imgsamplingmethod, + img2imgupscaler, + img2imgmodel, + img2imgactivate, + img2imgscale, + img2imgpadding, + img2imgdenoisestrength, + ultimatesdupscale, + usdutilewidth, + usdutileheight, + usdumaskblur, + usduredraw, + usduSeamsfix, + usdusdenoise, + usduswidth, + usduspadding, + usdusmaskblur, + controlnetenabled, + controlnetmodel, + img2imgdenoisestrengthmod, + enableextraupscale, + controlnetblockymode, + extrasupscaler1, + extrasupscaler2, + extrasupscaler2visiblity, + extrasupscaler2gfpgan, + extrasupscaler2codeformer, + extrasupscaler2codeformerweight, + extrasresize, + onlyupscale, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept, + increasestability, + qualityhiresfix, + qualitymode, + qualitykeep, + basesize, + promptvariantinsanitylevel + ] + ) interrupt.click(tryinterrupt, inputs=[apiurl]) - + automatedoutputsfolderbutton.click(openfolder) # turn things on and off for gender def subjectsvalue(subject): - enable=(subject=="humanoid") - return { - chosengender: gr.update(visible=enable), - } - subject.change( - subjectsvalue, - [subject], - [chosengender] - ) + enable = (subject == "humanoid") + return {chosengender: gr.update(visible=enable), } + + subject.change(subjectsvalue, [subject], [chosengender]) # turn things on and off for subject subtype object def subjectsvalueforsubtypeobject(subject): - enable=(subject=="object") - return { - chosensubjectsubtypeobject: gr.update(visible=enable), - } - subject.change( - subjectsvalueforsubtypeobject, - [subject], - [chosensubjectsubtypeobject] - ) - + enable = (subject == "object") + return {chosensubjectsubtypeobject: gr.update(visible=enable), } + + subject.change(subjectsvalueforsubtypeobject, [subject], [chosensubjectsubtypeobject]) + # turn things on and off for subject subtype humanoid - def subjectsvalueforsubtypeobject(subject): - enable=(subject=="humanoid") - return { - chosensubjectsubtypehumanoid: gr.update(visible=enable), - } - subject.change( - subjectsvalueforsubtypeobject, - [subject], - [chosensubjectsubtypehumanoid] - ) + def subjectsvalueforsubtypehumanoid(subject): + enable = (subject == "humanoid") + return {chosensubjectsubtypehumanoid: gr.update(visible=enable), } + + subject.change(subjectsvalueforsubtypehumanoid, [subject], [chosensubjectsubtypehumanoid]) # turn things on and off for subject subtype concept def subjectsvalueforsubtypeconcept(subject): - enable=(subject=="concept") - return { - chosensubjectsubtypeconcept: gr.update(visible=enable), - } - subject.change( - subjectsvalueforsubtypeconcept, - [subject], - [chosensubjectsubtypeconcept] - ) + enable = (subject == "concept") + return {chosensubjectsubtypeconcept: gr.update(visible=enable), } + subject.change(subjectsvalueforsubtypeconcept, [subject], [chosensubjectsubtypeconcept]) # Turn things off and on for onlyupscale and txt2img def onlyupscalevalues(onlyupscale): - onlyupscale = not onlyupscale - return { - amountofimages: gr.update(visible=onlyupscale), - size: gr.update(visible=onlyupscale), - samplingsteps: gr.update(visible=onlyupscale), - cfg: gr.update(visible=onlyupscale), - - hiresfix: gr.update(visible=onlyupscale), - hiressteps: gr.update(visible=onlyupscale), - hiresscale: gr.update(visible=onlyupscale), - denoisestrength: gr.update(visible=onlyupscale), - upscaler: gr.update(visible=onlyupscale), - - model: gr.update(visible=onlyupscale), - samplingmethod: gr.update(visible=onlyupscale), - upscaler: gr.update(visible=onlyupscale), - - qualitygate: gr.update(visible=onlyupscale), - quality: gr.update(visible=onlyupscale), - runs: gr.update(visible=onlyupscale), - qualityhiresfix: gr.update(visible=onlyupscale), - qualitymode: gr.update(visible=onlyupscale), - qualitykeep: gr.update(visible=onlyupscale) - - - } - + onlyupscale = not onlyupscale + return { + amountofimages: gr.update(visible=onlyupscale), + size: gr.update(visible=onlyupscale), + samplingsteps: gr.update(visible=onlyupscale), + cfg: gr.update(visible=onlyupscale), + hiresfix: gr.update(visible=onlyupscale), + hiressteps: gr.update(visible=onlyupscale), + hiresscale: gr.update(visible=onlyupscale), + denoisestrength: gr.update(visible=onlyupscale), + upscaler: gr.update(visible=onlyupscale), + model: gr.update(visible=onlyupscale), + samplingmethod: gr.update(visible=onlyupscale), + qualitygate: gr.update(visible=onlyupscale), + quality: gr.update(visible=onlyupscale), + runs: gr.update(visible=onlyupscale), + qualityhiresfix: gr.update(visible=onlyupscale), + qualitymode: gr.update(visible=onlyupscale), + qualitykeep: gr.update(visible=onlyupscale) + } + onlyupscale.change( onlyupscalevalues, [onlyupscale], - [amountofimages,size,samplingsteps,cfg,hiresfix,hiressteps,hiresscale,denoisestrength,upscaler,model,samplingmethod,upscaler,qualitygate,quality,runs,qualityhiresfix,qualitymode,qualitykeep] + [ + amountofimages, + size, + samplingsteps, + cfg, + hiresfix, + hiressteps, + hiresscale, + denoisestrength, + upscaler, + model, + samplingmethod, + upscaler, + qualitygate, + quality, + runs, + qualityhiresfix, + qualitymode, + qualitykeep + ] ) - - + # Turn things off and on for hiresfix def hireschangevalues(hiresfix): - return { - hiressteps: gr.update(visible=hiresfix), - hiresscale: gr.update(visible=hiresfix), - denoisestrength: gr.update(visible=hiresfix), - upscaler: gr.update(visible=hiresfix) - } - + return { + hiressteps: gr.update(visible=hiresfix), + hiresscale: gr.update(visible=hiresfix), + denoisestrength: gr.update(visible=hiresfix), + upscaler: gr.update(visible=hiresfix) + } + hiresfix.change( hireschangevalues, [hiresfix], - [hiressteps,hiresscale,denoisestrength,upscaler] + [hiressteps, hiresscale, denoisestrength, upscaler] ) # Turn things off and on for quality gate def qgatechangevalues(qualitygate): - return { - quality: gr.update(visible=qualitygate), - runs: gr.update(visible=qualitygate), - qualityhiresfix: gr.update(visible=qualitygate), - qualitymode: gr.update(visible=qualitygate), - qualitykeep: gr.update(visible=qualitygate) - } - + return { + quality: gr.update(visible=qualitygate), + runs: gr.update(visible=qualitygate), + qualityhiresfix: gr.update(visible=qualitygate), + qualitymode: gr.update(visible=qualitygate), + qualitykeep: gr.update(visible=qualitygate) + } + qualitygate.change( qgatechangevalues, [qualitygate], - [quality,runs,qualityhiresfix,qualitymode,qualitykeep] + [quality, runs, qualityhiresfix, qualitymode, qualitykeep] ) - + # Turn things off and on for USDU def ultimatesdupscalechangevalues(ultimatesdupscale): - return { - usdutilewidth: gr.update(visible=ultimatesdupscale), - usdutileheight: gr.update(visible=ultimatesdupscale), - usdumaskblur: gr.update(visible=ultimatesdupscale), - usduredraw: gr.update(visible=ultimatesdupscale), - - usduSeamsfix: gr.update(visible=ultimatesdupscale), - usdusdenoise: gr.update(visible=ultimatesdupscale), - usduswidth: gr.update(visible=ultimatesdupscale), - usduspadding: gr.update(visible=ultimatesdupscale), - usdusmaskblur: gr.update(visible=ultimatesdupscale) - } - + return { + usdutilewidth: gr.update(visible=ultimatesdupscale), + usdutileheight: gr.update(visible=ultimatesdupscale), + usdumaskblur: gr.update(visible=ultimatesdupscale), + usduredraw: gr.update(visible=ultimatesdupscale), + usduSeamsfix: gr.update(visible=ultimatesdupscale), + usdusdenoise: gr.update(visible=ultimatesdupscale), + usduswidth: gr.update(visible=ultimatesdupscale), + usduspadding: gr.update(visible=ultimatesdupscale), + usdusmaskblur: gr.update(visible=ultimatesdupscale) + } + ultimatesdupscale.change( ultimatesdupscalechangevalues, [ultimatesdupscale], - [usdutilewidth,usdutileheight,usdumaskblur,usduredraw,usduSeamsfix,usdusdenoise,usduswidth,usduspadding,usdusmaskblur] + [ + usdutilewidth, + usdutileheight, + usdumaskblur, + usduredraw, + usduSeamsfix, + usdusdenoise, + usduswidth, + usduspadding, + usdusmaskblur + ] ) # Turn things off and on for EXTRAS def enableextraupscalechangevalues(enableextraupscale): - return { - extrasupscaler1: gr.update(visible=enableextraupscale), - extrasupscaler2: gr.update(visible=enableextraupscale), - extrasupscaler2visiblity: gr.update(visible=enableextraupscale), - extrasresize: gr.update(visible=enableextraupscale), - - extrasupscaler2gfpgan: gr.update(visible=enableextraupscale), - extrasupscaler2codeformer: gr.update(visible=enableextraupscale), - extrasupscaler2codeformerweight: gr.update(visible=enableextraupscale) - } - + return { + extrasupscaler1: gr.update(visible=enableextraupscale), + extrasupscaler2: gr.update(visible=enableextraupscale), + extrasupscaler2visiblity: gr.update(visible=enableextraupscale), + extrasresize: gr.update(visible=enableextraupscale), + extrasupscaler2gfpgan: gr.update(visible=enableextraupscale), + extrasupscaler2codeformer: gr.update(visible=enableextraupscale), + extrasupscaler2codeformerweight: gr.update(visible=enableextraupscale) + } + enableextraupscale.change( enableextraupscalechangevalues, [enableextraupscale], - [extrasupscaler1,extrasupscaler2,extrasupscaler2visiblity,extrasresize, extrasupscaler2gfpgan,extrasupscaler2codeformer,extrasupscaler2codeformerweight] + [ + extrasupscaler1, + extrasupscaler2, + extrasupscaler2visiblity, + extrasresize, + extrasupscaler2gfpgan, + extrasupscaler2codeformer, + extrasupscaler2codeformerweight + ] ) - - - return [insanitylevel,subject, artist, imagetype, prefixprompt,suffixprompt,negativeprompt, promptcompounderlevel, ANDtoggle, silentmode, workprompt, antistring, seperator, givensubject, smartsubject, giventypeofimage, imagemodechance, chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept, promptvariantinsanitylevel] - - - - - def run(self, p, insanitylevel, subject, artist, imagetype, prefixprompt,suffixprompt,negativeprompt, promptcompounderlevel, ANDtoggle, silentmode, workprompt, antistring,seperator, givensubject, smartsubject, giventypeofimage, imagemodechance, chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept, promptvariantinsanitylevel): - - images = [] + return [ + insanitylevel, + subject, + artist, + imagetype, + prefixprompt, + suffixprompt, + negativeprompt, + promptcompounderlevel, + ANDtoggle, + silentmode, + workprompt, + antistring, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept, + promptvariantinsanitylevel + ] + + def run( + self, + p, + insanitylevel, + subject, + artist, + imagetype, + prefixprompt, + suffixprompt, + negativeprompt, + promptcompounderlevel, + ANDtoggle, + silentmode, + workprompt, + antistring, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept, + promptvariantinsanitylevel + ): + + imgs = [] infotexts = [] all_seeds = [] all_prompts = [] batches = p.n_iter - initialbatchsize = p.batch_size batchsize = p.batch_size p.n_iter = 1 p.batch_size = 1 - + initialseed = p.seed if p.seed == -1: p.seed = int(random.randrange(4294967294)) - if(silentmode and workprompt != ""): + if silentmode and workprompt != "": print("Workflow mode turned on, not generating a prompt. Using workflow prompt.") - elif(silentmode): + elif silentmode: print("Warning, workflow mode is turned on, but no workprompt has been given.") elif p.prompt != "" or p.negative_prompt != "": print("Please note that existing prompt and negative prompt fields are (no longer) used") - - if(ANDtoggle == "automatic" and artist == "none"): + + if ANDtoggle == "automatic" and artist == "none": print("Automatic and artist mode set to none, don't work together well. Ignoring this setting!") artist = "all" - #if(ANDtoggle == "automatic" and (prefixprompt != "")): - # print("Automatic doesnt work well if there is an prefix prompt filled in. Ignoring this prompt fields!") - # prefixprompt = "" - - state.job_count = batches - + for i in range(batches): - - if(silentmode == False): + if silentmode is False: # prompt compounding print("Starting generating the prompt") preppedprompt = "" - + artistcopy = artist prefixpromptcopy = prefixprompt - - if(ANDtoggle == "automatic"): - if(artist != "none"): - preppedprompt += build_dynamic_prompt(insanitylevel,subject,artist, imagetype, True, antistring) - if(subject == "humanoid"): - preppedprompt += ", " + promptcompounderlevel + " people" - if(subject == "landscape"): - preppedprompt += ", landscape" - if(subject == "animal"): - preppedprompt += ", " + promptcompounderlevel + " animals" - if(subject == "object"): - preppedprompt += ", " + promptcompounderlevel + " objects" - #sneaky! If we are running on automatic, we don't want "artists" to show up during the rest of the prompt, so set it to none, but only temporary! + if ANDtoggle == "automatic": + if artist != "none": + preppedprompt += build_dynamic_prompt( + insanitylevel, + subject, + artist, + imagetype, + True, + antistring + ) + + match subject: + case "humanoid": + preppedprompt += f', {promptcompounderlevel} people' + case "landscape": + preppedprompt += ", landscape" + case "animal": + preppedprompt += f', {promptcompounderlevel} animals' + case "object": + preppedprompt += f', {promptcompounderlevel} objects' + + # sneaky! If we are running on automatic, + # we don't want "artists" to show up during the rest of the prompt, + # so set it to none, but only temporary! artist = "none" - - if(ANDtoggle != "none" and ANDtoggle != "automatic"): + if ANDtoggle != "none" and ANDtoggle != "automatic": preppedprompt += prefixprompt - - if(ANDtoggle != "none"): - if(ANDtoggle!="prefix + prefix + prompt + suffix"): + + if ANDtoggle != "none": + if ANDtoggle != "prefix + prefix + prompt + suffix": prefixprompt = "" - if(seperator == "comma"): + if seperator == "comma": preppedprompt += " \n , " else: - preppedprompt += " \n " + seperator + " " - - - #Here is where we build a "normal" prompt - preppedprompt += build_dynamic_prompt(insanitylevel,subject,artist, imagetype, False, antistring, prefixprompt, suffixprompt,promptcompounderlevel, seperator,givensubject,smartsubject,giventypeofimage,imagemodechance,chosengender, chosensubjectsubtypeobject, chosensubjectsubtypehumanoid, chosensubjectsubtypeconcept) + preppedprompt += f' \n {seperator} ' + + # Here is where we build a "normal" prompt + preppedprompt += build_dynamic_prompt( + insanitylevel, + subject, + artist, + imagetype, + False, + antistring, + prefixprompt, + suffixprompt, + promptcompounderlevel, + seperator, + givensubject, + smartsubject, + giventypeofimage, + imagemodechance, + chosengender, + chosensubjectsubtypeobject, + chosensubjectsubtypehumanoid, + chosensubjectsubtypeconcept + ) # set the artist mode back when done (for automatic mode) artist = artistcopy prefixprompt = prefixpromptcopy - + # set everything ready - p.prompt = preppedprompt + p.prompt = preppedprompt p.negative_prompt = negativeprompt - if(silentmode == True): - p.prompt = createpromptvariant(workprompt,promptvariantinsanitylevel) + if silentmode is True: + p.prompt = createpromptvariant(workprompt, promptvariantinsanitylevel) - #for j in range(batchsize): - print(" ") print("Full prompt to be processed:") print(" ") @@ -1068,24 +1437,31 @@ def run(self, p, insanitylevel, subject, artist, imagetype, prefixprompt,suffixp p.batch_size = batchsize p.hr_prompt = promptlist processed = process_images(p) - images += processed.images + imgs += processed.images infotexts += processed.infotexts - + # prompt and seed info for batch grid all_seeds.append(processed.seed) all_prompts.append(processed.prompt) - + # prompt and seed info for individual images all_seeds += processed.all_seeds all_prompts += processed.all_prompts - - state.job = f"{state.job_no} out of {state.job_count}" - + + state.job = f"{state.job_no} out of {state.job_count}" + # Increase seed by batchsize for unique seeds for every picture if -1 was chosen if initialseed == -1: p.seed += batchsize - + # just return all the things p.n_iter = 0 p.batch_size = 0 - return Processed(p=p, images_list=images, info=infotexts[0], infotexts=infotexts, all_seeds=all_seeds, all_prompts=all_prompts) \ No newline at end of file + return Processed( + p=p, + images_list=imgs, + info=infotexts[0], + infotexts=infotexts, + all_seeds=all_seeds, + all_prompts=all_prompts + ) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..986009c --- /dev/null +++ b/tox.ini @@ -0,0 +1,32 @@ +[tox] +envlist = isort, pep8 + +[testenv] +basepython = python3 + +[isort] +skip_glob=.tox +sections = STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER + + +[testenv:isort] +commands = isort -c {toxinidir} +deps = + isort + +[testenv:isort-run] +commands = isort --ac {toxinidir}y +deps = + isort + +[flake8] +exclude = .env*,.venv*,.git,.tox, +max-line-length = 120 +format = %(path)s#-%(row)d :%(col)d::%(code)s::%(text)s +enable-extensions = H203, H904 +ignore = F405, W504, W605 + +[testenv:pep8] +commands = flake8 +deps = + flake8 \ No newline at end of file diff --git a/upscaler.py b/upscaler.py index b6fbff1..ba8b766 100644 --- a/upscaler.py +++ b/upscaler.py @@ -1,7 +1,8 @@ -from call_img2img import * -from call_extras import * import os +from call_extras import call_extras +from call_img2img import call_img2img + # C:\automated_output\extras\ # C:\automated_output\img2img\ # C:\automated_output\upscale me\ @@ -14,7 +15,7 @@ f = os.path.join(directory, filename) # checking if it is a file if os.path.isfile(f): - - img2img1 = call_img2img(f,0.25,1.5,256) - + + img2img1 = call_img2img(f, 0.25, 1.5, 256) + finalfile = call_extras(img2img1)