I import os
import requests
import io
from pathlib import Path
import yaml
from dotenv import load_dotenv
from PIL import Image

class Config:
    def __init__(self):
        # Load environment variables from the .env file
        load_dotenv()

        # Retrieve the API key from the .env file
        self.api_key = os.getenv("API_KEY")

        # Set root directory for the project
        self.root_dir = Path('/root/mm/aig')

        # Load configuration data from config.yaml
        self.config_data = self.load_config()

        # Set up logging directory
        self.setup_logging()

    def load_config(self):
        """Load the YAML config file."""
        config_path = self.root_dir / 'config.yaml'
        with open(config_path, 'r') as file:
            try:
                return yaml.safe_load(file)
            except yaml.YAMLError as exc:
                print(f"Error loading YAML config: {exc}")
                return None

    def setup_logging(self):
        """Set up logging in the logs directory."""
        log_dir = self.root_dir / 'logs'
        log_dir.mkdir(exist_ok=True)

    def get_api_key(self):
        """Return the API key."""
        return self.api_key

    def get_styles(self):
        """Return the list of styles from config."""
        return self.config_data.get('styles_list', [])

def query(payload, api_key):
    """Send a request to the Hugging Face API and return the image bytes."""
    API_URL = "https://api-inference.huggingface.co/models/kothariyashhh/GenAi-Texttoimage"
    headers = {"Authorization": f"Bearer {api_key}"}
    
    response = requests.post(API_URL, headers=headers, json=payload)
    response.raise_for_status()  # Raise an error for bad responses
    return response.content

def generate_image(prompt, config):
    """Generate an image using the provided prompt."""
    payload = {"inputs": prompt}
    image_bytes = query(payload, config.get_api_key())
    
    # Save the image to the specified path
    image_path = '/root/mm/aig/images/generated_image.png'
    image = Image.open(io.BytesIO(image_bytes))
    image.save(image_path)

    print(f"Image saved successfully at {image_path}")
    return image_path

def main():
    # Initialize the configuration
    config = Config()

    # Print API key to confirm it has been loaded correctly
    print(f"Loaded API Key: {config.get_api_key()}")

    # Access configuration data from config.yaml
    if config.config_data:
        print("Configuration loaded successfully.")
        print(f"Styles: {config.get_styles()}")

        # Define prompt (for demonstration purposes)
        prompt = "Astronaut riding a horse"

        # Generate the image
        generated_image_path = generate_image(prompt, config)
        
        if generated_image_path:
            # Call the next script av.py
            subprocess.run(["python3", "av.py"])  # Adjust the path if necessary

if __name__ == "__main__":
    main()
(aig) {24-10-04 15:24}localhost:~/mm/aig root# python3 image.py
Loaded API Key: yhf_cwxQYZIlAOUofhYRSzobYAGqxFvRwVcAfA
Configuration loaded successfully.
Styles: ['Minimalist Style', 'Flat Design', 'Vintage/Retro Style', 'Bold & Vibrant', 'Photographic Style', 'Illustrative Style', 'Typography-Focused', 'Monochrome', 'Surreal/Abstract', 'Collage', 'Grunge', '3D Design', 'Futuristic/Techno', 'Pop Art', 'Geometric Patterns', 'Cinematic/Film Noir', 'Hand-Drawn Doodles', 'Pastel Aesthetic', 'Urban/Street Style']
Traceback (most recent call last):
  File "/root/mm/aig/image.py", line 94, in <module>
    main()
  File "/root/mm/aig/image.py", line 87, in main
    generated_image_path = generate_image(prompt, config)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/root/mm/aig/image.py", line 61, in generate_image
    image_bytes = query(payload, config.get_api_key())
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/root/mm/aig/image.py", line 55, in query
    response.raise_for_status()  # Raise an error for bad responses
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/root/mm/aig/aig/lib/python3.12/site-packages/requests/models.py", line 1024, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api-inference.huggingface.co/models/kothariyashhh/GenAi-Texttoimage