Spaces:
Sleeping
Sleeping
Download image_engine.py from Mr-Vicky-01/AI_Artist: direct link, hf CLI and curl.
- Browser
- Download file 1.64 kB
-
https://huggingface.co/spaces/Mr-Vicky-01/AI_Artist/resolve/main/image_engine.py
- Command line
-
hf download hf://spaces/Mr-Vicky-01/AI_Artist/image_engine.py
-
curl -L -o image_engine.py https://huggingface.co/spaces/Mr-Vicky-01/AI_Artist/resolve/main/image_engine.py
1.64 kB
| from PIL import Image | |
| import requests | |
| import random | |
| import io | |
| import os | |
| # Define the ImageGenerator class for Hugging Face API | |
| class ImageGenerator: | |
| def __init__(self) -> None: | |
| self.all_urls = [ | |
| "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell", | |
| # "https://api-inference.huggingface.co/models/XLabs-AI/flux-RealismLora", | |
| "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-3.5-large" | |
| ] | |
| self.api_url = random.choice(self.all_urls) | |
| self.headers = {"Authorization": f"Bearer {os.getenv('HUGGING_FACE')}"} | |
| def generate_image(self, prompt): | |
| payload = { | |
| "inputs": prompt, | |
| # "negative_prompt": "ugly, distorted, low quality" | |
| } | |
| response = requests.post(self.api_url, headers=self.headers, json=payload) | |
| # Debugging: Print response status and content type | |
| print(f"Response Status Code: {response.status_code}") | |
| print(f"Response Content Type: {response.headers.get('Content-Type')}") | |
| # Check for valid response | |
| if response.status_code == 200 and response.headers.get('Content-Type').startswith('image'): | |
| image_bytes = response.content | |
| image = Image.open(io.BytesIO(image_bytes)) | |
| return image | |
| else: | |
| # Print the error message if not a valid image | |
| print("Error: Invalid response received from API") | |
| print(response.text) # Print the text content of the response for debugging | |
| raise Exception("Failed to generate image from API") |