Spaces:
Running
Running
File size: 1,638 Bytes
6a6d286 44ad93d 6a6d286 44ad93d 7f6984b 44ad93d 6a6d286 1e8f60b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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") |