root# python3 image.py                   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']          Image saved successfully at /root/mm/aig/images/generated_image.png               VisionEncoderDecoderModel has generative capabilities, as `prepare_inputs_for_generation` is explicitly overwritten. However, it doesn't directly inherit from `GenerationMixin`. From 👉v4.50👈 onwards, `PreTrainedModel` will NOT inherit from `GenerationMixin`, and this model will lose the ability to call `generate` and other related functions.                          - If you're using `trust_remote_code=True`, you can get rid of this warning by loading the model with an auto class. See https://huggingface.co/docs/transformers/en/model_doc/auto#auto-classes             - If you are the owner of the model architecture code, please modify your model class such that it inherits from `GenerationMixin` (after `PreTrainedModel`, otherwise you'll get an exception).             - If you are not the owner of the model architecture class, please contact the model code owner to update it.import os
import requests
import io
from pathlib import Path
import yaml
from dotenv import load_dotenv
from PIL import Image
import subprocess

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 (current working directory)
        self.root_dir = Path.cwd()

        # 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'
        if not config_path.exists():
            print(f"Configuration file not found at {config_path}")
            return None
        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."""
        if self.config_data:
            return self.config_data.get('styles_list', [])
        else:
            return []

def query(payload, api_key):
    """Send a request to the Hugging Face API and return the image bytes."""
    # Use a publicly available model
    API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
    headers = {"Authorization": f"Bearer {api_key}"}

    response = requests.post(API_URL, headers=headers, json=payload)
    if response.status_code != 200:
        print(f"Error {response.status_code}: {response.reason}")
        print(f"Response details: {response.text}")
        response.raise_for_status()  # This will raise an HTTPError
    return response.content

def generate_image(prompt, config):
    """Generate an image using the provided prompt."""
    payload = {
        "inputs": prompt,
        "options": {
            "wait_for_model": True  # Ensure the request waits if the model needs to be loaded
        }
    }
    try:
        image_bytes = query(payload, config.get_api_key())

        # Save the image to the specified path
        image_dir = config.root_dir / 'images'
        image_dir.mkdir(exist_ok=True)
        image_path = image_dir / '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
    except Exception as e:
        print(f"An error occurred while generating the image: {e}")
        return None

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

    # Confirm that the API key has been loaded (without printing it)
    if not config.get_api_key():
        print("Error: API key not found. Please ensure it is set in your .env file.")
        return

    # 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 (Adjust the path if necessary)
            try:
                subprocess.run(["python3", "av.py"], check=True)
            except subprocess.CalledProcessError as e:
                print(f"An error occurred while running av.py: {e}")
    else:
        print("Failed to load configuration.")

if __name__ == "__main__":
    main()