# script3.py

import json
import os
import subprocess
import requests
from PIL import Image
import io
from dotenv import load_dotenv

def load_prompts(filename='prompts.json'):
    """Load prompts from a JSON file."""
    with open(filename, 'r') as file:
        return json.load(file)['prompts']

def query_huggingface_api(prompt_text, api_url, headers):
    """Send a request to the Hugging Face Inference API and return the image."""
    payload = {
        "inputs": prompt_text,
    }
    response = requests.post(api_url, headers=headers, json=payload)
    if response.status_code != 200:
        raise Exception(f"API request failed with status code {response.status_code}: {response.content}")
    return response.content

def generate_image(prompt, idx, output_dir, api_url, headers):
    """Generate an image using the Hugging Face Inference API and save it."""
    print(f"\nGenerating image {idx}...")
    print(f"Prompt: {prompt['prompt_text']}")

    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # Set image parameters
    parameters = {
        'width': prompt['image_settings']['width'],
        'height': prompt['image_settings']['height'],
        'format': prompt['image_settings']['format']
    }

    # Query the Hugging Face Inference API
    try:
        image_bytes = query_huggingface_api(prompt['prompt_text'], api_url, headers)
    except Exception as e:
        print(f"Error generating image: {e}")
        return

    # Load the image
    image = Image.open(io.BytesIO(image_bytes)).convert("RGB")

    # Resize the image if necessary
    if image.size != (parameters['width'], parameters['height']):
        image = image.resize((parameters['width'], parameters['height']), Image.ANTIALIAS)

    # Save the image
    image_filename = f"image_{idx}.{parameters['format']}"
    image_path = os.path.join(output_dir, image_filename)
    image.save(image_path)
    print(f"Image {idx} generated and saved as '{image_path}'.")

def start_script_4():
    """Start script4.py as a subprocess."""
    print("\nStarting Script 4...")
    subprocess.Popen(['python3', 'script4.py'], env=os.environ)

def main():
    # Load environment variables from .env file
    load_dotenv()

    prompts = load_prompts()
    output_dir = '/root/mm/android_final/automated_image_generator'  # The specified directory

    # Hugging Face API settings
    API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
    hf_api_token = os.getenv('HF_API_TOKEN')
    if not hf_api_token:
        print("Error: HF_API_TOKEN not found in environment variables.")
        return

    headers = {"Authorization": f"Bearer {hf_api_token}"}

    for idx, prompt in enumerate(prompts, start=1):
        generate_image(prompt, idx, output_dir, API_URL, headers)

    # After generating the image(s), start script4.py
    start_script_4()

if __name__ == "__main__":
    main()
generator root#
Generating image 1...
Prompt: Creative representation of play from anywhere slots for Game Changer Gaming in Futuristic style and Vibrant scheme.
Traceback (most recent call last):
  File "/root/mm/android_final/automated_image_generator/script3.py", line 89, in <module>
    main()
  File "/root/mm/android_final/automated_image_generator/script3.py", line 83, in main
    generate_image(prompt, idx, output_dir, API_URL, headers)
  File "/root/mm/android_final/automated_image_generator/script3.py", line 53, in generate_image
    image = image.resize((parameters['width'], parameters['height']), Image.ANTIALIAS) write script 3.py complete with updates