TextToImage / app.py
Hassan501's picture
Create app.py
bdddd6f verified
Raw History Blame Contribute Delete
2.76 kB
import streamlit as st
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
import os
# Set up the Streamlit page
st.set_page_config(
page_title="Text-to-Image with Hugging Face",
page_icon="🎨",
layout="wide"
)
# --- App Title and Description ---
st.title("🎨 AI Image Generator")
st.markdown(
"Enter a text prompt below and watch as the AI brings your words to life! "
"This app uses the **Stable Diffusion** model from Hugging Face."
)
st.markdown("---")
# --- Model Loading ---
@st.cache_resource
def load_model():
"""
Loads the Stable Diffusion model.
Using st.cache_resource to cache the model so it doesn't reload on every interaction.
"""
# Define the model ID. You can change this to other models on the Hugging Face Hub.
model_id = "runwayml/stable-diffusion-v1-5"
# Load the pipeline
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
# Check for GPU and move model if available
if torch.cuda.is_available():
pipe = pipe.to("cuda")
return pipe
pipeline = load_model()
# --- User Input and Generation ---
col1, col2 = st.columns([2, 1])
with col1:
prompt = st.text_input(
"Enter your prompt:",
placeholder="e.g., A photo of an astronaut riding a horse on Mars, high resolution, detailed"
)
generate_button = st.button("Generate Image")
with col2:
st.markdown("### Settings")
negative_prompt = st.text_area(
"Negative prompt:",
placeholder="e.g., blurry, bad quality, low resolution"
)
st.markdown("---")
# --- Image Display and Generation Logic ---
if generate_button:
if not prompt:
st.warning("Please enter a prompt to generate an image.")
else:
with st.spinner("Generating your image... This may take a moment."):
try:
# Generate the image
image = pipeline(
prompt=prompt,
negative_prompt=negative_prompt
).images[0]
# Display the generated image
st.success("Image generated successfully!")
st.image(image, caption=prompt, use_column_width=True)
# Option to download the image
buf = BytesIO()
image.save(buf, format="PNG")
byte_im = buf.getvalue()
st.download_button(
label="Download Image",
data=byte_im,
file_name=f"{prompt.replace(' ', '_')}.png",
mime="image/png"
)
except Exception as e:
st.error(f"An error occurred: {e}")