File size: 2,697 Bytes
dee781b | 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | import gradio as gr
import requests
from io import BytesIO
from PIL import Image
HUGGINGFACE_API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2"
HUGGINGFACE_API_TOKEN = "your_huggingface_api_token_here" # Replace with your actual token
headers = {
"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}"
}
def text_to_image(prompt):
if not prompt.strip():
return None
payload = {
"inputs": prompt,
}
response = requests.post(HUGGINGFACE_API_URL, headers=headers, json=payload)
if response.status_code != 200:
return None
image_bytes = BytesIO(response.content)
image = Image.open(image_bytes).convert("RGB")
return image
css = """
body {
background-color: #ffffff;
font-family: 'Inter', sans-serif;
margin: 0; padding: 0;
}
#container {
max-width: 900px;
margin: 3rem auto;
padding: 1rem;
box-sizing: border-box;
}
#header {
font-weight: 700;
font-size: 48px;
color: #111827;
margin-bottom: 0.5rem;
}
#subheader {
color: #6b7280;
font-size: 18px;
margin-bottom: 2rem;
}
#prompt-input textarea {
font-size: 16px;
padding: 0.75rem;
border-radius: 12px;
border: 1px solid #d1d5db;
resize: vertical;
}
#generate-btn {
background-color: #111827;
color: white;
border: none;
padding: 0.75rem 1.5rem;
font-weight: 600;
border-radius: 12px;
cursor: pointer;
margin-top: 1rem;
transition: background-color 0.3s ease;
}
#generate-btn:hover {
background-color: #374151;
}
#output-image {
margin-top: 2rem;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.05);
max-width: 100%;
}
"""
with gr.Blocks(css=css) as demo:
with gr.Row():
with gr.Column(elem_id="container"):
gr.Markdown("<h1 id='header'>🖼️ Text to Visual Image Chatbot</h1>")
gr.Markdown("<p id='subheader'>Enter a descriptive text prompt and get a generated image.</p>")
prompt_input = gr.Textbox(
label="Your text prompt",
placeholder="Describe the image you want to generate...",
lines=3,
elem_id="prompt-input"
)
generate_btn = gr.Button("Generate Image", elem_id="generate-btn")
output_image = gr.Image(type="pil", elem_id="output-image")
def on_generate(prompt):
img = text_to_image(prompt)
if img is None:
return None
return img
generate_btn.click(on_generate, inputs=prompt_input, outputs=output_image)
if __name__ == "__main__":
demo.launch()
|