xbxbb / app.py
rapid12k4's picture
Create app.py
35da4ff verified
import gradio as gr
from diffusers import StableDiffusionPipeline
from PIL import Image
# Load the Stable Diffusion model (replace with your desired model)
model_id = "runwayml/stable-diffusion-v1-5" # Example: Stable Diffusion v1.5
pipe = StableDiffusionPipeline.from_pretrained(model_id)
pipe.to("cuda") # If you have a CUDA-enabled GPU, use it for faster generation
# otherwise, remove this line to use your CPU (slower)
def generate_image(prompt):
"""
Generates an image from a text prompt using Stable Diffusion.
Args:
prompt (str): The text prompt to guide image generation.
Returns:
PIL.Image.Image: The generated image.
"""
try:
image = pipe(prompt).images[0] # Get the first image from the pipeline output
return image
except Exception as e:
print(f"Error generating image: {e}")
return None # Or return a default image if desired
# Gradio Interface
def gradio_interface(prompt):
"""
Generates an image using the Stable Diffusion model and returns it for the Gradio interface.
Args:
prompt (str): The text prompt for image generation.
Returns:
PIL.Image.Image or str: The generated image or an error message.
"""
image = generate_image(prompt)
if image:
return image
else:
return "Error: Image generation failed. Please try a different prompt or check the console for details."
if __name__ == "__main__":
# Create the Gradio interface
iface = gr.Interface(
fn=gradio_interface,
inputs=gr.Textbox(lines=2, placeholder="Enter your prompt here..."),
outputs=gr.Image(label="Generated Image"),
title="Text-to-Image Generator",
description="Enter a text prompt and let the AI generate an image for you. Uses Stable Diffusion (or your specified model).",
examples=[
["A photo of a cat wearing a hat"],
["A futuristic cityscape at sunset"],
["An abstract painting with vibrant colors"],
]
)
# Launch the interface
iface.launch()