|
|
import gradio as gr |
|
|
from diffusers import StableDiffusionPipeline |
|
|
from PIL import Image |
|
|
|
|
|
|
|
|
model_id = "runwayml/stable-diffusion-v1-5" |
|
|
pipe = StableDiffusionPipeline.from_pretrained(model_id) |
|
|
pipe.to("cuda") |
|
|
|
|
|
|
|
|
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] |
|
|
return image |
|
|
except Exception as e: |
|
|
print(f"Error generating image: {e}") |
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
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__": |
|
|
|
|
|
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"], |
|
|
] |
|
|
) |
|
|
|
|
|
|
|
|
iface.launch() |