File size: 1,979 Bytes
5a4f96a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import gradio as gr
import requests
import base64
from PIL import Image
from io import BytesIO
from dotenv import load_dotenv
import os

# Load the .env file
load_dotenv()

# Get the API key from the environment variable
api_key = os.getenv("API_KEY")

# Define the endpoint URL
invoke_url = "https://ai.api.nvidia.com/v1/genai/stabilityai/sdxl-turbo"

# Define the function that interacts with the API
def generate_image(prompt, seed=0, sampler="K_EULER_ANCESTRAL", steps=2):
    # Define the headers with the correct API key
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Accept": "application/json",
    }

    # Define the payload for the POST request
    payload = {
        "text_prompts": [{"text": prompt}],
        "seed": seed,
        "sampler": sampler,
        "steps": steps
    }

    # Make the POST request to the API
    response = requests.post(invoke_url, headers=headers, json=payload)

    # Raise an error if the request was unsuccessful
    response.raise_for_status()

    # Get the response body
    response_body = response.json()

    # Extract the base64 string from the response
    base64_str = response_body['artifacts'][0]['base64']

    # Decode the base64 string
    image_data = base64.b64decode(base64_str)

    # Open the image using PIL
    image = Image.open(BytesIO(image_data))

    return image

# Define the Gradio interface
inputs = [
    gr.Textbox(label="Prompt", placeholder="Enter your image description here"),
    gr.Number(label="Seed", value=0, precision=0),
    gr.Dropdown(label="Sampler", choices=["K_EULER_ANCESTRAL", "DDIM", "PLMS"], value="K_EULER_ANCESTRAL"),
    gr.Slider(label="Steps", minimum=1, maximum=100, value=2)
]

outputs = gr.Image(label="Generated Image")

gr.Interface(
    fn=generate_image,
    inputs=inputs,
    outputs=outputs,
    title="Stable Diffusion XL Image Generator",
    description="Generate images using Stable Diffusion XL by providing a text prompt."
).launch()