I'm trying to create an app that 1 ask customers questions that are stored to file with some other information that is stored but preset, the customers only answers questions the first run unless they decide to change answers later. With the saved answers in a json file so a script can randomly select a couple answers from each question (but some are always used I think questions 1-3). The point of this is to get a unique prompt a out their business each image generation with it after first initial setup to be completely automated with a unique prompt every time I sent 3 scripts for. vtou to look at.... And tell me what was wrong. import json
import os
from datetime import datetime

# Constants
STYLES = {
    1: "Minimalist",
    2: "Bold",
    3: "Vintage",
    4: "Modern",
    5: "Colorful",
    6: "Elegant",
    7: "Whimsical",
    8: "Industrial",
    9: "Rustic",
    10: "Futuristic"
}

COLORS = {
    1: "Red",
    2: "Blue",
    3: "Green",
    4: "Yellow",
    5: "Black",
    6: "White",
    7: "Purple",
    8: "Orange",
    9: "Pink",
    10: "Brown"
}

def get_multi_choice_input(prompt, options):
    print(f"\n{prompt}")
    for num, option in options.items():
        print(f"{num}: {option}")

    while True:
        choices = input("\nEnter the numbers of your choices (comma-separated): ")
        try:
            selected_numbers = [int(x.strip()) for x in choices.split(',')]
            if all(num in options for num in selected_numbers):
                return [options[num] for num in selected_numbers]
            else:
                print("Please enter valid option numbers.")
        except ValueError:
            print("Please enter numbers separated by commas.")

def get_contact_info():
    print("\nBest Contact Method:")
    contact_method = input("Choose your contact method (1: Phone calls, 2: Text messages, 3: Both, 4: Facebook Messenger): ")
    
    contact_info = {}
    
    if contact_method == '1' or contact_method == '3':
        phone_number = input("Please provide your phone number: ")
        contact_info['phone'] = phone_number
    
    if contact_method == '2' or contact_method == '3':
        text_number = input("Please provide your text contact number (if different): ")
        contact_info['text'] = text_number
    
    if contact_method == '4':
        fb_page = input("Please provide your Facebook page address: ")
        contact_info['facebook'] = fb_page
    
    return contact_info

def setup_business():
    business_data = {
        'setup_date': datetime.now().isoformat(),
        'last_modified': datetime.now().isoformat()
    }
    
    print("Welcome to the Business Ad Setup!")

    # Basic Information
    business_data['company_name'] = input("What is your company's name? ")
    business_data['slogan'] = input("What is your company slogan? ")
    business_data['description'] = input("Please tell me about your company: ")

    # Preferred Styles
    business_data['preferred_styles'] = get_multi_choice_input("What styles do you like?", STYLES)

    # Preferred Color Palette
    business_data['preferred_colors'] = get_multi_choice_input("What colors do you prefer for your branding?", COLORS)

    # Contact Information
    business_data['contact_info'] = get_contact_info()

    # Additional Information
    business_data['additional_info'] = input("Is there any other information you would like to include in your advertisements? ")

    # Save data
    os.makedirs('data', exist_ok=True)
    with open('data/business_data.json', 'w') as f:
        json.dump(business_data, f, indent=2)
    
    print("\nSetup completed successfully!")
    return business_data

if __name__ == "__main__":
    # Check if setup has already been completed
    if os.path.exists('data/business_data.json'):
        print("Existing business data found!")
        choice = input("Would you like to redo the setup? (y/n): ")
        if not choice.lower().startswith('y'):
            print("Skipping setup. Moving to ad creation...")
            exit()
    
    business_data = setup_business()


import json
import random

def load_business_data():
    with open('data/business_data.json', 'r') as f:
        return json.load(f)

def ensure_keys_exist(data):
    # Add default styles if 'styles' key is missing or empty
    if 'styles' not in data or not data['styles']:
        data['styles'] = ["Minimalist", "Bold & Vibrant", "Vintage", "Flat Design", "Photographic"]
        print(f"'styles' key was missing. Added default styles: {data['styles']}")

    # Add default colors if 'colors' key is missing or empty
    if 'colors' not in data or not data['colors']:
        data['colors'] = ["Blue", "Red", "Black", "White", "Green"]
        print(f"'colors' key was missing. Added default colors: {data['colors']}")

    return data

def save_business_data(data):
    with open('data/business_data.json', 'w') as f:
        json.dump(data, f, indent=2)

def generate_prompt():
    data = load_business_data()

    # Ensure required keys exist and save updated data
    data = ensure_keys_exist(data)
    save_business_data(data)

    # Always include core business info
    core_elements = [
        data['company_name'],
        data['slogan'],
        data['description'].replace('\n', ' ').strip()
    ]

    # Randomly select a style and color
    selected_style = random.choice(data['styles'])
    selected_color = random.choice(data['colors'])

    # Construct the base prompt
    prompt_parts = [
        "Create a professional advertisement with the following elements:",
        f"Company: {core_elements[0]}",
        f"Slogan: {core_elements[1]}",
        f"Style: {selected_style}",
        f"Color: {selected_color}",
        "The image should be elegant and professionally designed,",
        "suitable for social media marketing and brand promotion.",
        "The design should be clean, visually appealing, and instantly recognizable.",
        f"Incorporate the essence of: {core_elements[2]}"
    ]

    # Create the structured prompt
    structured_prompt = {
        "prompt": " ".join(prompt_parts),
        "negative_prompt": "text, watermark, low quality, blurry, amateurish",
        "seed": random.randint(1, 2147483647),
        "width": 1024,
        "height": 1024,
        "num_inference_steps": 30,
        "guidance_scale": 7.5
    }

    # Save the prompt
    with open('data/new_prompt.json', 'w') as f:
        json.dump(structured_prompt, f, indent=2)

    return structured_prompt

if __name__ == "__main__":
    prompt = generate_prompt()
    print("Prompt generated successfully. Running image creation script...")
    import subprocess
    subprocess.run(['python3', '/root/mm/final/scripts/3_create.py'])


# prompt_generator.py
import json

def generate_prompt(company_info_path):
    with open(company_info_path, 'r') as f:
        company_info = json.load(f)

    company_name = company_info.get('company_name', '')
    slogan = company_info.get('slogan', '')
    description = company_info.get('description', '')
    preferred_styles = company_info.get('preferred_styles', [])
    preferred_colors = company_info.get('preferred_colors', [])

    # Build the prompt
    styles = ', '.join(preferred_styles)
    colors = ', '.join(preferred_colors)
    prompt = (f"Create a high-quality advertisement image for '{company_name}', "
              f"which is {description}. The design should be in {styles} style "
              f"with the following colors: {colors}. "
              f"Include the slogan: '{slogan}'.")

    return prompt

import json
import os
import requests
from datetime import datetime
import subprocess
from dotenv import load_dotenv
import sys
import traceback

# Import the prompt generator
from prompt_generator import generate_prompt

def main():
    # Get the directory of the current script
    script_dir = os.path.dirname(os.path.abspath(__file__))

    # Load environment variables from the .env file in the script's directory
    dotenv_path = os.path.join(script_dir, '.env')
    if not os.path.isfile(dotenv_path):
        print(f"Error: '.env' file not found in {script_dir}.")
        sys.exit(1)
    load_dotenv(dotenv_path)

    # Generate the image
    image_path = generate_image(script_dir)
    if image_path:
        print("Running logo overlay script...")
        if overlay_logo(image_path, script_dir):
            print("Image generation and logo overlay process completed successfully.")
        else:
            print("Image generated successfully, but logo overlay failed.")
    else:
        print("Image generation failed. Logo overlay not attempted.")

def generate_image(script_dir):
    # Path to company_info.json
    company_info_path = os.path.join(script_dir, 'data', 'company_info.json')
    if not os.path.isfile(company_info_path):
        print(f"Error: '{company_info_path}' file not found.")
        return None

    # Generate the prompt
    try:
        prompt = generate_prompt(company_info_path)
    except Exception as e:
        print(f"Error generating prompt: {e}")
        traceback.print_exc()
        return None

    # Prepare the payload
    payload = {
        "inputs": prompt,
        # Include any other options required by the API
    }

    # Hugging Face API setup
    API_URL = os.getenv('API_URL')
    API_KEY = os.getenv('HF_API_KEY')

    if not API_URL:
        print("Error: 'API_URL' not set in .env file.")
        return None
    if not API_KEY:
        print("Error: 'HF_API_KEY' not set in .env file.")
        return None

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

    try:
        print(f"Sending request to API with payload: {payload}")
        response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
        response.raise_for_status()

        # Verify response content is an image
        content_type = response.headers.get('Content-Type', '')
        if 'image' not in content_type:
            print(f"Error: Unexpected content type in response: {content_type}")
            print(f"Response content: {response.text}")
            return None

        # Save the image
        output_dir = os.path.join(script_dir, 'output', 'ads')
        os.makedirs(output_dir, exist_ok=True)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        image_path = os.path.join(output_dir, f'ad_base_{timestamp}.png')

        with open(image_path, 'wb') as f:
            f.write(response.content)

        print(f"Image generated successfully: {image_path}")
        return image_path

    except requests.exceptions.RequestException as e:
        print(f"Error making request to Hugging Face API: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error generating image: {e}")
        traceback.print_exc()
        return None

def overlay_logo(image_path, script_dir):
    try:
        logo_script_path = os.path.join(script_dir, 'scripts', '4_logo.py')
        if not os.path.isfile(logo_script_path):
            print(f"Error: '{logo_script_path}' script not found.")
            return False

        # Run the logo overlay script with the image path as an argument
        result = subprocess.run(['python', logo_script_path, image_path],
                                check=True, capture_output=True, text=True)
        print("Logo overlay completed successfully.")
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error running logo overlay script:\n{e.stderr}")
        return False
    except Exception as e:
        print(f"Unexpected error during logo overlay: {e}")
        traceback.print_exc()
        return False

if __name__ == "__main__":
    main()
business_data.json
{
  "setup_date": "2024-10-05T13:09:33.085027",
  "last_modified": "2024-10-05T13:09:33.085041",
  "company_name": "Game Changer Gaming",
  "slogan": "WIN,WIN WIN!",
  "description": "It is an online social gaming provider, we offer video slots to customers to play fromvthe comfort of home",
  "preferred_styles": [
    "Bold",
    "Vintage",
    "Modern",
    "Colorful",
    "Whimsical",
    "Futuristic"
  ],
  "preferred_colors": [
    "Red",
    "Blue",
    "Green",
    "Black",
    "White",
    "Purple",
    "Orange",
    "Pink"
  ],
  "contact_info": {
    "phone": "(903) 576-2529",
    "text": ""
  },
  "additional_info": "exciting,funfun,thrilling,joy,happy"
}