Spaces:
Runtime error
Runtime error
File size: 6,649 Bytes
bdb6800 | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | import streamlit as st
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
import numpy as np
# Set page config
st.set_page_config(
page_title="AI Image Generator",
page_icon="π¨",
layout="centered"
)
# Cache the model loading to avoid reloading on every interaction
@st.cache_resource
def load_model():
"""Load and cache the Stable Diffusion model"""
model_id = "runwayml/stable-diffusion-v1-5"
# Check if CUDA is available
device = "cuda" if torch.cuda.is_available() else "cpu"
# Load the pipeline
pipe = StableDiffusionPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
use_safetensors=True
)
pipe = pipe.to(device)
# Enable memory efficient attention if using CUDA
if device == "cuda":
pipe.enable_attention_slicing()
pipe.enable_memory_efficient_attention()
return pipe
def generate_image(prompt, negative_prompt="", num_inference_steps=20, guidance_scale=7.5, width=512, height=512):
"""Generate image from text prompt"""
try:
pipe = load_model()
# Generate image
with torch.no_grad():
image = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
width=width,
height=height
).images[0]
return image
except Exception as e:
st.error(f"Error generating image: {str(e)}")
return None
def main():
# Header
st.title("π¨ AI Image Generator")
st.markdown("Generate beautiful images from text descriptions using Stable Diffusion!")
# Sidebar for advanced settings
with st.sidebar:
st.header("βοΈ Settings")
# Image dimensions
col1, col2 = st.columns(2)
with col1:
width = st.selectbox("Width", [512, 768, 1024], index=0)
with col2:
height = st.selectbox("Height", [512, 768, 1024], index=0)
# Generation parameters
num_inference_steps = st.slider("Inference Steps", 10, 50, 20,
help="More steps = better quality but slower")
guidance_scale = st.slider("Guidance Scale", 1.0, 20.0, 7.5, 0.5,
help="Higher values = more adherence to prompt")
# Info
st.markdown("---")
st.markdown("### π‘ Tips")
st.markdown("- Be specific in your descriptions")
st.markdown("- Use artistic styles (e.g., 'oil painting', 'digital art')")
st.markdown("- Add quality modifiers (e.g., 'highly detailed', '4k')")
st.markdown("- Use negative prompts to avoid unwanted elements")
# Main content area
col1, col2 = st.columns([2, 1])
with col1:
# Text input for prompt
prompt = st.text_area(
"βοΈ Describe the image you want to generate:",
placeholder="A beautiful sunset over mountains, oil painting style, highly detailed",
height=100
)
# Negative prompt (optional)
negative_prompt = st.text_area(
"β Negative prompt (optional - things to avoid):",
placeholder="blurry, low quality, distorted",
height=60
)
# Generate button
generate_btn = st.button("π Generate Image", type="primary", use_container_width=True)
with col2:
# Example prompts
st.markdown("### π― Example Prompts")
examples = [
"A majestic lion in a savanna at sunset",
"Cyberpunk cityscape at night, neon lights",
"Van Gogh style painting of a coffee shop",
"Cute robot playing with cats in a garden",
"Abstract art with vibrant colors and geometric shapes"
]
for i, example in enumerate(examples):
if st.button(f"Use Example {i+1}", key=f"example_{i}"):
st.session_state.example_prompt = example
# Apply example if selected
if hasattr(st.session_state, 'example_prompt'):
prompt = st.session_state.example_prompt
del st.session_state.example_prompt
st.rerun()
# Generate and display image
if generate_btn and prompt:
with st.spinner("π¨ Creating your masterpiece... This may take a few moments!"):
# Show progress
progress_bar = st.progress(0)
for i in range(100):
progress_bar.progress(i + 1)
if i == 99:
break
# Generate image
image = generate_image(
prompt=prompt,
negative_prompt=negative_prompt,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
width=width,
height=height
)
progress_bar.empty()
if image:
# Display the generated image
st.success("β
Image generated successfully!")
st.image(image, caption=f"Generated from: '{prompt}'", use_column_width=True)
# Download button
img_buffer = io.BytesIO()
image.save(img_buffer, format='PNG')
st.download_button(
label="π₯ Download Image",
data=img_buffer.getvalue(),
file_name=f"generated_image_{hash(prompt) % 10000}.png",
mime="image/png",
use_container_width=True
)
# Show generation parameters
with st.expander("π Generation Details"):
st.json({
"prompt": prompt,
"negative_prompt": negative_prompt,
"dimensions": f"{width}x{height}",
"inference_steps": num_inference_steps,
"guidance_scale": guidance_scale
})
elif generate_btn and not prompt:
st.warning("β οΈ Please enter a prompt to generate an image!")
# Footer
st.markdown("---")
st.markdown(
"Built with β€οΈ using [Streamlit](https://streamlit.io) and "
"[Stable Diffusion](https://huggingface.co/runwayml/stable-diffusion-v1-5)"
)
if __name__ == "__main__":
# Add missing import
import io
main() |