ItqaAkhlaq commited on
Commit
bdb6800
Β·
verified Β·
1 Parent(s): 3bb0129

Create app.py

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