import os
import requests
from dotenv import load_dotenv
from PIL import Image
import io
import base64
import json
import random

# Load environment variables
load_dotenv()
API_KEY = os.getenv("STABILITY_API_KEY")
ENGINE_ID = "stable-diffusion-v2-1"  # Set your engine ID here
TEXT_TO_IMAGE_URL = f"https://api.stability.ai/v1/generation/{ENGINE_ID}/text-to-image"

# Headers
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def generate_image(prompt, width=512, height=512):
    payload = {
        "prompt": prompt,
        "width": width,
        "height": height,
        "samples": 1,
        "num_inference_steps": 50
    }

    try:
        response = requests.post(TEXT_TO_IMAGE_URL, headers=HEADERS, json=payload, timeout=60)
        response.raise_for_status()  # Raise an error for HTTP errors
        data = response.json()
        return data.get("images", [])
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err} - Response: {response.text}")
    except requests.exceptions.ConnectionError:
        print("Error Connecting to the API")
    except requests.exceptions.Timeout:
        print("Timeout Error")
    except requests.exceptions.RequestException as err:
        print(f"An error occurred: {err}")
    return []

def save_images(images, prefix="image"):
    for idx, img_data in enumerate(images):
        try:
            # Assuming 'data' is Base64-encoded string
            image_bytes = base64.b64decode(img_data.get("data"))
            image = Image.open(io.BytesIO(image_bytes))
            filename = f"{prefix}_{idx+1}.png"
            image.save(filename)
            print(f"Image saved as {filename}")
        except Exception as e:
            print(f"Failed to save image {idx+1}: {e}")

def load_cheat_sheet():
    with open("cheat_sheet.json", "r") as f:
        return json.load(f)

def create_prompt(cheat_sheet):
    prompt = f"{random.choice(cheat_sheet['main_subjects'])} in a {random.choice(cheat_sheet['environments'])}, with a {random.choice(cheat_sheet['moods'])} mood."
    return prompt

def main():
    cheat_sheet = load_cheat_sheet()
    
    while True:
        print("Menu:")
        print("1. Answer Questions")
        print("2. Create Prompt")
        print("3. Generate Image")
        print("4. Exit")
        
        choice = input("Choose an option: ")
        
        if choice == '1':
            # Placeholder for answering questions logic
            print("Answering questions... (Functionality not implemented)")
        
        elif choice == '2':
            prompt = create_prompt(cheat_sheet)
            print(f"Generated Prompt: {prompt}")
            with open("generated_prompt.txt", "w") as f:
                f.write(prompt)
        
        elif choice == '3':
            try:
                with open("generated_prompt.txt", "r") as f:
                    prompt = f.read()
                print(f"Generating image for prompt: {prompt}")
                images = generate_image(prompt)
                
                if images:
                    save_images(images, prefix="generated_image")
                else:
                    print("No images were generated.")
            except FileNotFoundError:
                print("No generated prompt found. Please create a prompt first.")
        
        elif choice == '4':
            print("Exiting...")
            break
        
        else:
            print("Invalid option. Please choose again.")

if __name__ == "__main__":
    main()
Choose an option: 3
Generating image for prompt: An image of something in a an environment environment, with a excited,winning mood, in a style style.
HTTP error occurred: 400 Client Error: Bad Request for url: https://api.stability.ai/v1/generation/stable-diffusion-v2-1/text-to-image - Response: {"id":"37b68a21e8c60f5ca5614b9eb9482458","message":"text_prompts: cannot be blank.","name":"bad_request"}Generating image for prompt: An image of something in a an environment environment, with a excited,winning mood, in a style style.
HTTP error occurred: 400 Client Error: Bad Request for url: https://api.stability.ai/v1/generation/stable-diffusion-v2-1/text-to-image - Response: {"id":"37b68a21e8c60f5ca5614b9eb9482458","message":"text_prompts: cannot be blank.","name":"bad_request"}

No images were generated.
Menu:
1. Answer Questions
2. Create Prompt
3. Generate Image
4. Exitimport os
import requests
from dotenv import load_dotenv
from PIL import Image
import io
import base64
import json
import random

# Load environment variables
load_dotenv()
API_KEY = os.getenv("STABILITY_API_KEY")
ENGINE_ID = "stable-diffusion-v2-1"  # Set your engine ID here
TEXT_TO_IMAGE_URL = f"https://api.stability.ai/v1/generation/{ENGINE_ID}/text-to-image"

# Headers
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

def generate_image(prompt, width=512, height=512, samples=1, num_inference_steps=50):
    payload = {
        "text_prompts": [
            {
                "text": prompt,
                "weight": 1
            }
        ],
        "width": width,
        "height": height,
        "samples": samples,
        "num_inference_steps": num_inference_steps
    }

    try:
        response = requests.post(TEXT_TO_IMAGE_URL, headers=HEADERS, json=payload, timeout=60)
        response.raise_for_status()  # Raise an error for HTTP errors
        data = response.json()
        return data.get("artifacts", [])
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err} - Response: {response.text}")
    except requests.exceptions.ConnectionError:
        print("Error Connecting to the API")
    except requests.exceptions.Timeout:
        print("Timeout Error")
    except requests.exceptions.RequestException as err:
        print(f"An error occurred: {err}")
    return []

def save_images(images, prefix="image"):
    for idx, img_data in enumerate(images):
        try:
            # Assuming 'base64' is the encoding used; adjust if different
            image_bytes = base64.b64decode(img_data.get("base64"))
            image = Image.open(io.BytesIO(image_bytes))
            filename = f"{prefix}_{idx+1}.png"
            image.save(filename)
            print(f"Image saved as {filename}")
        except Exception as e:
            print(f"Failed to save image {idx+1}: {e}")

def load_cheat_sheet():
    with open("cheat_sheet.json", "r") as f:
        return json.load(f)

def create_prompt(cheat_sheet):
    # Option based on your cheat_sheet.json structure
    main_subject = random.choice([
        cheat_sheet.get("main_subject"),
        *cheat_sheet.get("characters", [])
    ])
    mood = random.choice(cheat_sheet.get("moods", []))
    style = random.choice(cheat_sheet.get("styles", []))
    feature = random.choice(cheat_sheet.get("features", []))
    
    prompt = f"{main_subject}, {feature}, in a {style} style, with a {mood} mood."
    return prompt

def main():
    cheat_sheet = load_cheat_sheet()
    
    while True:
        print("\nMenu:")
        print("1. Answer Questions")
        print("2. Create Prompt")
        print("3. Generate Image")
        print("4. Exit")
        
        choice = input("Choose an option: ")
        
        if choice == '1':
            # Placeholder for answering questions logic
            print("Answering questions... (Functionality not implemented)")
        
        elif choice == '2':
            prompt = create_prompt(cheat_sheet)
            print(f"\nGenerated Prompt: {prompt}")
            with open("generated_prompt.txt", "w") as f:
                f.write(prompt)
        
        elif choice == '3':
            try:
                with open("generated_prompt.txt", "r") as f:
                    prompt = f.read()
                if not prompt.strip():
                    print("The prompt is empty. Please create a prompt first.")
                    continue
                print(f"\nGenerating image for prompt: {prompt}")
                images = generate_image(prompt)
                
                if images:
                    save_images(images, prefix="generated_image")
                else:
                    print("No images were generated.")
            except FileNotFoundError:
                print("No generated prompt found. Please create a prompt first.")
        
        elif choice == '4':
            print("Exiting...")
            break
        
        else:
            print("Invalid option. Please choose again.")

if __name__ == "__main__":
    main()STABILITY_API_KEY
API Key: STABILITY_API_KEY
Use your Stability API key to authentication requests to this App.

Header parameter name: authorization