File size: 1,291 Bytes
b1521ca
 
 
 
 
 
 
 
 
 
 
731fe3d
b1521ca
 
 
9e215b3
 
 
 
b1521ca
 
 
 
9e215b3
 
 
 
 
 
 
 
 
 
b1521ca
 
 
 
 
 
 
 
 
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
39
40
41
42
43
import requests
import gradio as gr
from PIL import Image
import io
from transformers import utils
utils.move_cache()
import os

hf_token = os.getenv('HF_TOKEN')

API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
headers = {"Authorization": f"Bearer {hf_token}"}

def query(payload):
    response = requests.post(API_URL, headers=headers, json=payload)
    if response.status_code != 200:
        # If the response is not successful, return None or handle it accordingly
        print("Error from the API:", response.text)  # For debugging
        return None
    return response.content

def generate_image(prompt):
    image_bytes = query({"inputs": prompt})
    if image_bytes is None:
        # Handle the case where the API did not return image data
        return "The API call was unsuccessful. Check the logs for details."
    
    try:
        image = Image.open(io.BytesIO(image_bytes))
        return image
    except IOError:
        # Handle cases where PIL cannot open the bytes received
        return "The returned data could not be recognized as an image."

iface = gr.Interface(
    fn=generate_image,
    inputs="text",
    outputs="image",
    title="Stable-Diffusion-XL for high quality image generation"
)

iface.launch()