├── README.md ├── nprompts.txt ├── openaiapikey2.txt ├── prompts.txt ├── requirements.txt ├── sdapikey.txt ├── sdspeed.py └── sdspeed2.py /README.md: -------------------------------------------------------------------------------- 1 | # SD-Python-Automation 2 | Stable Diffusion + Python Automation 3 | 4 | Pip install: 5 | openai 6 | requests 7 | Pillow 8 | 9 | 1. Set Your OpenAI API key in openaiapikey.txt 10 | 2. Set Your SD API ket in sdapikey.txt 11 | 3. Adjust prompts for your needs 12 | 4. Run sdspeed.py (NO UI) 13 | 5. Run sdspeed.py (WITH UI) 14 | 15 | Check SDimages folder for your images. 16 | -------------------------------------------------------------------------------- /nprompts.txt: -------------------------------------------------------------------------------- 1 | Here are examples of AMAZING Negative Prompts: 2 | 3 | 1. negative_prompts = "illustration, 3d, sepia, painting, cartoons, sketch, (worst quality:2), 4 | (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, normal quality, ((monochrome)), 5 | ((grayscale:1.2)),newhalf, collapsed eyeshadow, multiple eyebrows, pink hair, analog, analogphoto" 6 | 7 | 2. negative_prompts = "jpeg artifacts, low quality, lowres, 3d, render, doll, plastic, blur, haze, 8 | monochrome, b&w, text, (ugly:1.2), unclear eyes, no arms, bad anatomy, cropped, censoring, asymmetric eyes, 9 | bad anatomy, bad proportions, cropped, cross-eyed, deformed, extra arms, extra fingers, extra limbs, fused fingers, 10 | malformed, mangled hands, misshapen body, missing arms, missing fingers, missing hands, missing legs, poorly drawn, 11 | tentacle finger, too many arms, too many fingers, watermark, logo, text, letters, signature, username, words, blurry, cropped" 12 | 13 | 3. negative_prompts = "[text, rash, freckles, tattoos, cgi, blurry, fuzzy, Two bodies, Two heads, doll, 14 | extra nipples, bad anatomy, long neck, extra arms, extra fingers, poorly drawn hands, disfigured, tiling, 15 | deformed, mutated, out of frame, cloned face]" 16 | 17 | Create new negative_prompts that we dont want in a photo of a hyperrealistic beautiful cyberpunk girl: 18 | -------------------------------------------------------------------------------- /openaiapikey2.txt: -------------------------------------------------------------------------------- 1 | YOUR KEY -------------------------------------------------------------------------------- /prompts.txt: -------------------------------------------------------------------------------- 1 | Here are examples of AMAZING Text Prompts: 2 | 3 | 1. text_prompt = "(masterpiece:1. 0), (best quality:1. 4), (ultra highres:1. 2), (photorealistic:1. 4), 4 | (8k, RAW photo:1. 2), (soft focus:1. 4), 1 woman, posh, (sharp focus:1. 4), (korean:1. 2), (american:1. 1), 5 | detailed beautiful face, black hair, (detailed open blazer:1. 4), tie, beautiful white shiny humid skin, smiling" 6 | 7 | 2. text_prompt = "full body, walking pose, slow motion, female paladin wearing full body (light silver armour:1. 2), 8 | (insanely detailed, bloom:1. 5), (highest quality, Alessandro Casagrande, Greg Rutkowski, Sally Mann, concept art, 4k), 9 | (analog:1. 2), (high sharpness), (detailed pupils:1. 1), (painting:1. 1), (digital painting:1. 1), detailed face and eyes, 10 | Masterpiece, best quality, (highly detailed photo:1. 1), 8k, photorealistic, (long blonde Hair, ponytail haircut, ecstatic:1. 1), 11 | (young woman:1. 1), By jeremy mann, by sandra chevrier, by maciej kuciara, sharp, (perfect body:1. 1), realistic, real shadow, 3d, 12 | (temple background:1. 2), (by Michelangelo)" 13 | 14 | 3. text_prompt = "redshift style, a real perfect female body of beautiful redhead, glasses, perfect face, intricate, elegant, 15 | highly detailed, trending on artstation, by Tom Bagshaw and Seb McKinnon, 150mm portrait, photography, epic cinematic, 16 | octane render , denoise, photograph with a Hasselblad H3DII, extremely detailed" 17 | 18 | Create a new text_prompt of a hyperrealistic beautiful cyberpunk girl: 19 | 20 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | openai 2 | requests 3 | Pillow 4 | -------------------------------------------------------------------------------- /sdapikey.txt: -------------------------------------------------------------------------------- 1 | YOUR KEY 2 | -------------------------------------------------------------------------------- /sdspeed.py: -------------------------------------------------------------------------------- 1 | # Import the necessary libraries 2 | import openai # for the OpenAI API 3 | import os # to interact with the operating system 4 | import requests # to send HTTP requests 5 | import datetime # to work with dates and times 6 | import base64 # to encode and decode binary data 7 | import json # to work with JSON data 8 | 9 | # This function opens a file and reads its contents 10 | def open_file(filepath): 11 | with open(filepath, 'r', encoding='utf-8') as infile: 12 | return infile.read() 13 | 14 | # This function writes content to a file 15 | def save_file(filepath, content): 16 | with open(filepath, 'a', encoding='utf-8') as outfile: 17 | outfile.write(content) 18 | 19 | # Here, we read API keys from text files 20 | api_key = open_file('openaiapikey2.txt') # OpenAI API key 21 | sd_api_key = open_file('sdapikey.txt') # Stability.AI API key 22 | 23 | # This function calls the OpenAI API's ChatCompletion endpoint to carry out a conversation 24 | def chatgpt(api_key, conversation, chatbot, user_input, temperature=0.8, frequency_penalty=0.2, presence_penalty=0): 25 | openai.api_key = api_key 26 | 27 | # Add user input to the conversation history 28 | conversation.append({"role": "user","content": user_input}) 29 | 30 | # Add a system message to the conversation 31 | messages_input = conversation.copy() 32 | prompt = [{"role": "system", "content": chatbot}] 33 | messages_input.insert(0, prompt[0]) 34 | 35 | # Make a call to the OpenAI API 36 | completion = openai.ChatCompletion.create( 37 | model="gpt-4", 38 | temperature=temperature, 39 | frequency_penalty=frequency_penalty, 40 | presence_penalty=presence_penalty, 41 | messages=messages_input) 42 | 43 | # Extract ChatGPTs response 44 | chat_response = completion['choices'][0]['message']['content'] 45 | 46 | # Add ChatGPTs response to the conversation 47 | conversation.append({"role": "assistant", "content": chat_response}) 48 | 49 | # Return ChatGPTs response 50 | return chat_response 51 | 52 | # This function calls the Stability.AI API to generate an image from text prompts 53 | def generate_image(api_key, text_prompt, negative_prompts, height=512, width=512, cfg_scale=9, clip_guidance_preset="FAST_BLUE", steps=70, samples=1): 54 | api_host = 'https://api.stability.ai' 55 | engine_id = "stable-diffusion-xl-beta-v2-2-2" 56 | 57 | # Here, we're making a POST request to the SD API with our parameters 58 | response = requests.post( 59 | f"{api_host}/v1/generation/{engine_id}/text-to-image", 60 | headers={ 61 | "Content-Type": "application/json", 62 | "Accept": "application/json", 63 | "Authorization": f"Bearer {api_key}" 64 | }, 65 | json={ 66 | "text_prompts": [ 67 | { 68 | "text": text_prompt # Our Text Prompt 69 | } 70 | ], 71 | "negative_prompts": [ 72 | { 73 | "text": negative_prompts # Our Negative Prompt 74 | } 75 | ], 76 | "cfg_scale": cfg_scale, 77 | "clip_guidance_preset": clip_guidance_preset, 78 | "height": height, 79 | "width": width, 80 | "samples": samples, 81 | "steps": steps, 82 | }, 83 | ) 84 | 85 | # Check for errors in the API response 86 | if response.status_code != 200: 87 | raise Exception("Non-200 response: " + str(response.text)) 88 | 89 | # Extract the base64 image data from the response 90 | data = response.json() 91 | image_data = data["artifacts"][0]["base64"] 92 | 93 | # Save the image data as a PNG file 94 | timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") 95 | image_filename = os.path.join("SDimages", f"generated_image_{timestamp}.png") # Where we save your image "SDimages" folder 96 | 97 | with open(image_filename, "wb") as f: 98 | f.write(base64.b64decode(image_data)) 99 | 100 | # Return the file path of the saved image 101 | return image_filename 102 | 103 | # Start with an empty conversation 104 | conversation = [] 105 | 106 | # Here we start the main loop, n is how many images we care gonna create 107 | n = 10 108 | for i in range(n): 109 | # Reset conversation for each loop 110 | conversation = [] 111 | 112 | # Define an system message for ChatGPT 113 | chatbot = "You are Photograph and Art Expert. You task to creating amazing prompts" 114 | 115 | # Read prompts from a text file and use the OpenAI assistant to refine them 116 | text_prompt1 = open_file("prompts.txt") 117 | text_prompt = chatgpt(api_key, conversation, chatbot, text_prompt1) 118 | print(text_prompt) 119 | negative_prompts1 = open_file("nprompts.txt") 120 | negative_prompts = chatgpt(api_key, conversation, chatbot, negative_prompts1) 121 | print(negative_prompts) 122 | 123 | # Call the Stability.AI API to generate an image using the refined prompts 124 | image_filename = generate_image(sd_api_key, text_prompt, negative_prompts) 125 | -------------------------------------------------------------------------------- /sdspeed2.py: -------------------------------------------------------------------------------- 1 | import openai 2 | import os 3 | import requests 4 | import glob 5 | import re 6 | from colorama import Fore, Style, init 7 | import datetime 8 | import base64 9 | import json 10 | import tkinter as tk 11 | from PIL import Image, ImageTk 12 | 13 | def open_file(filepath): 14 | with open(filepath, 'r', encoding='utf-8') as infile: 15 | return infile.read() 16 | 17 | def save_file(filepath, content): 18 | with open(filepath, 'a', encoding='utf-8') as outfile: 19 | outfile.write(content) 20 | 21 | api_key = open_file('openaiapikey2.txt') 22 | sd_api_key = open_file('sdapikey.txt') 23 | 24 | def chatgpt(api_key, conversation, chatbot, user_input, temperature=0.8, frequency_penalty=0.2, presence_penalty=0): 25 | openai.api_key = api_key 26 | conversation.append({"role": "user","content": user_input}) 27 | messages_input = conversation.copy() 28 | prompt = [{"role": "system", "content": chatbot}] 29 | messages_input.insert(0, prompt[0]) 30 | 31 | completion = openai.ChatCompletion.create( 32 | model="gpt-3.5-turbo", 33 | temperature=temperature, 34 | frequency_penalty=frequency_penalty, 35 | presence_penalty=presence_penalty, 36 | messages=messages_input) 37 | 38 | chat_response = completion['choices'][0]['message']['content'] 39 | conversation.append({"role": "assistant", "content": chat_response}) 40 | return chat_response 41 | 42 | def generate_image(api_key, text_prompt, negative_prompts, height=512, width=512, cfg_scale=7, clip_guidance_preset="FAST_BLUE", steps=50, samples=1): 43 | api_host = 'https://api.stability.ai' 44 | engine_id = "stable-diffusion-xl-beta-v2-2-2" 45 | 46 | response = requests.post( 47 | f"{api_host}/v1/generation/{engine_id}/text-to-image", 48 | headers={ 49 | "Content-Type": "application/json", 50 | "Accept": "application/json", 51 | "Authorization": f"Bearer {api_key}" 52 | }, 53 | json={ 54 | "text_prompts": [ 55 | { 56 | "text": text_prompt 57 | } 58 | ], 59 | "negative_prompts": [ 60 | { 61 | "text": negative_prompts 62 | } 63 | ], 64 | "cfg_scale": cfg_scale, 65 | "clip_guidance_preset": clip_guidance_preset, 66 | "height": height, 67 | "width": width, 68 | "samples": samples, 69 | "steps": steps, 70 | }, 71 | ) 72 | 73 | if response.status_code != 200: 74 | raise Exception("Non-200 response: " + str(response.text)) 75 | 76 | data = response.json() 77 | image_data = data["artifacts"][0]["base64"] 78 | 79 | timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") 80 | image_filename = os.path.join("SDimages", f"generated_image_{timestamp}.png") 81 | 82 | with open(image_filename, "wb") as f: 83 | f.write(base64.b64decode(image_data)) 84 | 85 | return image_filename 86 | 87 | def get_latest_image_filename(folder): 88 | list_of_files = glob.glob(f"{folder}/*.png") 89 | latest_file = max(list_of_files, key=os.path.getctime) 90 | return latest_file 91 | 92 | def update_ui_with_image(root, label): 93 | folder = "C:/Users/kris_/Python/sdspeed/SDimages" 94 | image_filename = get_latest_image_filename(folder) 95 | img = Image.open(image_filename) 96 | img = img.resize((1080, 1080), Image.ANTIALIAS) 97 | img = ImageTk.PhotoImage(img) 98 | label.config(image=img) 99 | label.image = img 100 | root.update() 101 | 102 | conversation = [] 103 | chatbot = "I am Photograph and Art Expert. I will assist you creating amazing prompts for all kinds of images." 104 | 105 | root = tk.Tk() 106 | root.title("Generated Images") 107 | root.geometry("1200x1200") 108 | label = tk.Label(root) 109 | label.pack() 110 | 111 | n = 25 112 | for i in range(n): 113 | conversation = [] 114 | chatbot = "I am Photograph and Art Expert. I will assist you creating amazing prompts for all kinds of images." 115 | text_prompt1 = open_file("prompts.txt") 116 | text_prompt = chatgpt(api_key, conversation, chatbot, text_prompt1) 117 | print(text_prompt) 118 | negative_prompts1 = open_file("nprompts.txt") 119 | negative_prompts = chatgpt(api_key, conversation, chatbot, negative_prompts1) 120 | print(negative_prompts) 121 | image_filename = generate_image(sd_api_key, text_prompt, negative_prompts) 122 | update_ui_with_image(root, label) 123 | 124 | root.mainloop() --------------------------------------------------------------------------------