File size: 1,976 Bytes
c2a8649
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
import os

# Environment variables for API details
API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")  # Fetching the API token from environment variable

# Function to query Hugging Face API
def query_huggingface_api(api_url, prompt):
    headers = {"Authorization": f"Bearer {API_TOKEN}"}
    data = {"inputs": prompt}
    response = requests.post(api_url, headers=headers, json=data)
    
    if response.status_code == 200:
        # Assuming the API returns binary image data
        return response.content
    else:
        return None, f"Error {response.status_code}: {response.text}"

# Gradio function for generating the image
def generate_image(api_url, prompt):
    result, error = query_huggingface_api(f"https://api-inference.huggingface.co/models/{api_url}", prompt)
    
    if result:
        return result, None
    else:
        return None, error

# Create Gradio Blocks Interface
with gr.Blocks() as demo:
    gr.Markdown(
        """
        # Text to Image Generator
        Enter a text prompt, and the custom model will generate an image.
        """
    )

    with gr.Row():
        with gr.Column():
            text_input = gr.Textbox(
                label="Enter your prompt", 
                placeholder="Type something here..."
            )
            model_input = gr.Textbox(
                label="Model URL", 
                placeholder="Enter the model URL...",
                value="user/sdwarm"
            )
            generate_btn = gr.Button("Generate Image")
        
        with gr.Column():
            image_output = gr.Image(label="Generated Image")
            error_output = gr.Textbox(label="Error", interactive=False)

    # Define the action for the button
    generate_btn.click(
        fn=generate_image, 
        inputs=[model_input, text_input],  # Pass both model URL and prompt
        outputs=[image_output, error_output]
    )

# Launch the Gradio Blocks WebUI
demo.launch()