Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Add working AI image generator with HF API
Browse files
app.py
CHANGED
|
@@ -1,4 +1,50 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
import os
|
| 6 |
|
| 7 |
+
# Hugging Face Inference API for image generation
|
| 8 |
+
HF_TOKEN = os.getenv('HF_TOKEN')
|
| 9 |
+
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2"
|
| 10 |
+
|
| 11 |
+
def generate_image(prompt):
|
| 12 |
+
"""Generate image from text using Hugging Face API"""
|
| 13 |
+
if not prompt or prompt.strip() == "":
|
| 14 |
+
return None, "Please enter a prompt!"
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 18 |
+
payload = {"inputs": prompt}
|
| 19 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 20 |
+
|
| 21 |
+
if response.status_code == 200:
|
| 22 |
+
image = Image.open(BytesIO(response.content))
|
| 23 |
+
return image, "β
Image generated successfully!"
|
| 24 |
+
else:
|
| 25 |
+
return None, f"β API Error"
|
| 26 |
+
except Exception as e:
|
| 27 |
+
return None, f"β Error: {str(e)}"
|
| 28 |
+
|
| 29 |
+
# Create interface
|
| 30 |
+
with gr.Blocks(title="AI Image Generator") as demo:
|
| 31 |
+
gr.Markdown("# π¨ AI Image Generator")
|
| 32 |
+
gr.Markdown("Generate images from text descriptions")
|
| 33 |
+
|
| 34 |
+
with gr.Row():
|
| 35 |
+
with gr.Column():
|
| 36 |
+
prompt = gr.Textbox(
|
| 37 |
+
label="Enter prompt",
|
| 38 |
+
placeholder="A beautiful sunset over mountains",
|
| 39 |
+
lines=3
|
| 40 |
+
)
|
| 41 |
+
btn = gr.Button("Generate", variant="primary", size="lg")
|
| 42 |
+
status = gr.Textbox(label="Status", interactive=False)
|
| 43 |
+
|
| 44 |
+
with gr.Column():
|
| 45 |
+
output = gr.Image(label="Generated Image", type="pil")
|
| 46 |
+
|
| 47 |
+
btn.click(fn=generate_image, inputs=prompt, outputs=[output, status])
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
demo.launch()
|