File size: 1,742 Bytes
400c508 |
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 |
import streamlit as st
from diffusers import StableDiffusionPipeline
import torch
from PIL import Image
# Title of the app
st.title("Text-to-Image Generator")
st.markdown(
"Generate images from text with Stable Diffusion v1.4 model!"
)
@st.cache_resource
def load_pipeline():
# Load Stable Diffusion v1.4 model
model_id = "CompVis/stable-diffusion-v-1-4-original"
pipe = StableDiffusionPipeline.from_pretrained(
model_id, torch_dtype=torch.float16
)
pipe.to("cpu") # Ensure it runs on CPU
return pipe
# Load the pipeline
pipe = load_pipeline()
# Input field for the prompt
prompt = st.text_input("Enter your prompt:")
# Negative prompt for optional customization
neg_prompt = st.text_input(
"Optional: Enter a negative prompt (to exclude elements, e.g., blurry, low quality):"
)
# Button to generate the image
if st.button("Generate Image"):
if not prompt.strip():
st.error("Please enter a valid prompt.")
else:
with st.spinner("Generating image..."):
# Generate the image
result = pipe(prompt=prompt, negative_prompt=neg_prompt, num_inference_steps=25)
image = result.images[0]
# Display the image
st.image(image, caption="Generated Image", use_column_width=True)
# Option to download the image
img_buffer = Image.new("RGB", image.size, (255, 255, 255))
img_buffer.paste(image, (0, 0))
img_buffer.save("generated_image.png", "PNG")
with open("generated_image.png", "rb") as file:
st.download_button(
label="Download Image",
data=file,
file_name="generated_image.png",
mime="image/png",
)
|