emiL commited on
Commit
db64d27
·
verified ·
1 Parent(s): d7f13af

Upload src/streamlit_app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +377 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,379 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === streamlit_app.py ===
 
 
2
  import streamlit as st
3
+ from utils import load_css, create_prompt_selector, display_image_gallery, generate_image_placeholder
4
+ import time
5
 
6
+ def main():
7
+ st.set_page_config(
8
+ page_title="AI Image Generator - Dramatic Scenes",
9
+ page_icon="🎨",
10
+ layout="wide",
11
+ initial_sidebar_state="expanded"
12
+ )
13
+
14
+ load_css()
15
+
16
+ # Header
17
+ st.markdown("""
18
+ <div class="header">
19
+ <h1>🎬 AI Image Generator - Dramatic Scenes</h1>
20
+ <p>Create hyperrealistic, cinematic images with detailed prompts</p>
21
+ <p style="font-size: 0.9em; opacity: 0.7;">Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">anycoder</a></p>
22
+ </div>
23
+ """, unsafe_allow_html=True)
24
+
25
+ # Sidebar
26
+ with st.sidebar:
27
+ st.markdown("## ⚙️ Generation Settings")
28
+
29
+ # Aspect ratio
30
+ aspect_ratio = st.selectbox(
31
+ "Aspect Ratio",
32
+ options=["4:5", "16:9", "1:1", "3:2", "2:3"],
33
+ index=0
34
+ )
35
+
36
+ # Quality
37
+ quality = st.selectbox(
38
+ "Quality",
39
+ options=["Standard", "High", "Ultra (8K)"],
40
+ index=2
41
+ )
42
+
43
+ # Style
44
+ style = st.selectbox(
45
+ "Style",
46
+ options=["Cinematic", "Photorealistic", "Dramatic", "Hollywood", "Artistic"],
47
+ index=0
48
+ )
49
+
50
+ # Resolution
51
+ resolution = st.selectbox(
52
+ "Resolution",
53
+ options=["1024x1024", "1024x1280", "1280x720", "1920x1080", "2048x2560"],
54
+ index=1
55
+ )
56
+
57
+ st.markdown("---")
58
+ st.markdown("### 📊 Statistics")
59
+ if 'generated_count' not in st.session_state:
60
+ st.session_state.generated_count = 0
61
+ st.metric("Images Generated", st.session_state.generated_count)
62
+
63
+ # Main content
64
+ col1, col2 = st.columns([1, 1])
65
+
66
+ with col1:
67
+ st.markdown("## 📝 Prompt Editor")
68
+
69
+ # Predefined prompts
70
+ prompt_option = st.radio(
71
+ "Choose a scene template:",
72
+ ["Custom Prompt", "Haunted Hut Scene", "Disaster Scene"],
73
+ index=0
74
+ )
75
+
76
+ # Predefined prompts
77
+ prompts = {
78
+ "Haunted Hut Scene": """Hyperrealistic and dramatic scene showing a terrified man sitting on a bamboo bench in a thatch-roofed hut. He's wearing a black T-shirt with "WALIĆ RUDEGO" text and symbolic pattern underneath. A semi-transparent, smoky, ghostly figure emerges from the air beside him, grabbing his neck with a misty hand. The ghost has a skeletal, menacing face and glowing eyes, screaming or roaring. The man looks shocked and terrified, with wide eyes and mouth agape, frozen in fear. Natural lighting with warm sunlight filtering through the hut, background shows green vegetation outside. Intense, eerie, and cinematic atmosphere with strong emotional contrast between ghost and victim. 8K resolution, 4:5 aspect ratio.""",
79
+
80
+ "Disaster Scene": """A man and cat falling through the air. Background: skyscrapers curve dramatically in a wide fisheye perspective, as if the entire city is collapsing inward. Flying debris, concrete chunks, and glass shards fill the air. Action elements: A police car floats behind him - its red and blue sirens flash intensely through dust and smoke. Behind the vehicle follows a powerful explosion, casting orange light and shrapnel across the scene. In the background, a police officer is seen waving arms, thrown by the explosion. Lighting and atmosphere: Cinematic lighting with strong, directional shadows, motion blur, and bright lights from sirens and fireball. Dark and gritty color palette with golden-brown tones punctuated by vivid red, blue, and orange accents from explosions and sirens. Clothing: The man wears a torn, olive-green hoodie and dark, worn pants - flailing wildly in the wind. Hollywood disaster movie style - dramatic freeze-frame with intense city destruction, emotions, and surreal action. Hyperrealistic details in skin texture, movement, and lighting."""
81
+ }
82
+
83
+ # Text area for prompt
84
+ if prompt_option == "Custom Prompt":
85
+ prompt_text = st.text_area(
86
+ "Enter your prompt:",
87
+ height=200,
88
+ placeholder="Describe the image you want to generate in detail..."
89
+ )
90
+ else:
91
+ prompt_text = st.text_area(
92
+ "Edit the preset prompt:",
93
+ value=prompts.get(prompt_option, ""),
94
+ height=200
95
+ )
96
+
97
+ # Negative prompt
98
+ negative_prompt = st.text_area(
99
+ "Negative Prompt (what to avoid):",
100
+ value="blurry, low quality, distorted, deformed, bad anatomy, watermark, text, signature",
101
+ height=100
102
+ )
103
+
104
+ # Generate button
105
+ generate_col1, generate_col2, generate_col3 = st.columns([1, 2, 1])
106
+ with generate_col2:
107
+ if st.button("🎨 Generate Image", type="primary", use_container_width=True):
108
+ if prompt_text:
109
+ with st.spinner("Generating your image..."):
110
+ # Simulate image generation
111
+ time.sleep(2)
112
+
113
+ # Update session state
114
+ if 'generated_images' not in st.session_state:
115
+ st.session_state.generated_images = []
116
+
117
+ # Add new image to gallery
118
+ new_image = {
119
+ 'prompt': prompt_text,
120
+ 'negative_prompt': negative_prompt,
121
+ 'aspect_ratio': aspect_ratio,
122
+ 'quality': quality,
123
+ 'style': style,
124
+ 'timestamp': time.time()
125
+ }
126
+ st.session_state.generated_images.append(new_image)
127
+ st.session_state.generated_count += 1
128
+
129
+ st.success("✅ Image generated successfully!")
130
+ st.rerun()
131
+ else:
132
+ st.error("❌ Please enter a prompt to generate an image.")
133
+
134
+ with col2:
135
+ st.markdown("## 🖼️ Generated Images")
136
+
137
+ if 'generated_images' in st.session_state and st.session_state.generated_images:
138
+ display_image_gallery(st.session_state.generated_images)
139
+ else:
140
+ st.markdown("""
141
+ <div class="empty-state">
142
+ <h3>No images generated yet</h3>
143
+ <p>Enter a prompt and click "Generate Image" to start creating!</p>
144
+ </div>
145
+ """, unsafe_allow_html=True)
146
+
147
+ # Show example placeholders
148
+ st.markdown("### Example Scenes")
149
+ example_col1, example_col2 = st.columns(2)
150
+
151
+ with example_col1:
152
+ st.image(
153
+ generate_image_placeholder("Haunted", "#FF6B6B"),
154
+ caption="Haunted Hut Scene Example",
155
+ use_column_width=True
156
+ )
157
+
158
+ with example_col2:
159
+ st.image(
160
+ generate_image_placeholder("Disaster", "#4ECDC4"),
161
+ caption="Disaster Scene Example",
162
+ use_column_width=True
163
+ )
164
+
165
+ # Footer
166
+ st.markdown("---")
167
+ st.markdown("""
168
+ <div class="footer">
169
+ <p>💡 Tip: Be as detailed as possible in your prompts for better results!</p>
170
+ <p>🎯 Focus on: lighting, atmosphere, emotions, and specific visual elements</p>
171
+ </div>
172
+ """, unsafe_allow_html=True)
173
+
174
+ if __name__ == "__main__":
175
+ main()
176
+
177
+ === utils.py ===
178
+ import streamlit as st
179
+ import base64
180
+ from io import BytesIO
181
+ import time
182
+
183
+ def load_css():
184
+ """Load custom CSS styles"""
185
+ st.markdown("""
186
+ <style>
187
+ .header {
188
+ text-align: center;
189
+ padding: 2rem 0;
190
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
191
+ color: white;
192
+ border-radius: 10px;
193
+ margin-bottom: 2rem;
194
+ }
195
+
196
+ .header h1 {
197
+ margin: 0;
198
+ font-size: 2.5rem;
199
+ font-weight: 700;
200
+ }
201
+
202
+ .header p {
203
+ margin: 0.5rem 0;
204
+ opacity: 0.9;
205
+ }
206
+
207
+ .header a {
208
+ color: #FFD700;
209
+ text-decoration: none;
210
+ font-weight: bold;
211
+ }
212
+
213
+ .header a:hover {
214
+ text-decoration: underline;
215
+ }
216
+
217
+ .image-card {
218
+ background: white;
219
+ border-radius: 10px;
220
+ padding: 1rem;
221
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
222
+ margin-bottom: 1rem;
223
+ transition: transform 0.2s;
224
+ }
225
+
226
+ .image-card:hover {
227
+ transform: translateY(-2px);
228
+ box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
229
+ }
230
+
231
+ .image-container {
232
+ position: relative;
233
+ border-radius: 8px;
234
+ overflow: hidden;
235
+ }
236
+
237
+ .image-overlay {
238
+ position: absolute;
239
+ bottom: 0;
240
+ left: 0;
241
+ right: 0;
242
+ background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
243
+ color: white;
244
+ padding: 1rem;
245
+ opacity: 0;
246
+ transition: opacity 0.3s;
247
+ }
248
+
249
+ .image-container:hover .image-overlay {
250
+ opacity: 1;
251
+ }
252
+
253
+ .empty-state {
254
+ text-align: center;
255
+ padding: 3rem;
256
+ color: #666;
257
+ }
258
+
259
+ .empty-state h3 {
260
+ margin-bottom: 1rem;
261
+ color: #333;
262
+ }
263
+
264
+ .footer {
265
+ text-align: center;
266
+ padding: 1rem;
267
+ color: #666;
268
+ font-size: 0.9em;
269
+ }
270
+
271
+ .prompt-preview {
272
+ background: #f7f7f7;
273
+ padding: 0.5rem;
274
+ border-radius: 5px;
275
+ font-size: 0.85em;
276
+ color: #555;
277
+ margin-top: 0.5rem;
278
+ white-space: nowrap;
279
+ overflow: hidden;
280
+ text-overflow: ellipsis;
281
+ }
282
+
283
+ .stButton > button {
284
+ transition: all 0.2s;
285
+ }
286
+
287
+ .stButton > button:hover {
288
+ transform: translateY(-2px);
289
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
290
+ }
291
+
292
+ .metric-card {
293
+ background: white;
294
+ padding: 1rem;
295
+ border-radius: 8px;
296
+ text-align: center;
297
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
298
+ }
299
+ </style>
300
+ """, unsafe_allow_html=True)
301
+
302
+ def create_prompt_selector():
303
+ """Create a prompt selection interface"""
304
+ pass
305
+
306
+ def display_image_gallery(images):
307
+ """Display a gallery of generated images"""
308
+ cols = st.columns(2)
309
+
310
+ for idx, image_data in enumerate(reversed(images[-6:])): # Show last 6 images
311
+ with cols[idx % 2]:
312
+ st.markdown(f"""
313
+ <div class="image-card">
314
+ <div class="image-container">
315
+ <img src="data:image/png;base64,{create_placeholder_image(image_data['prompt'][:20])}"
316
+ style="width: 100%; border-radius: 8px;">
317
+ <div class="image-overlay">
318
+ <strong>Generated</strong><br>
319
+ {time.strftime('%Y-%m-%d %H:%M', time.localtime(image_data['timestamp']))}
320
+ </div>
321
+ </div>
322
+ <div style="margin-top: 0.5rem;">
323
+ <strong>Style:</strong> {image_data['style']}<br>
324
+ <strong>Quality:</strong> {image_data['quality']}<br>
325
+ <strong>Aspect:</strong> {image_data['aspect_ratio']}
326
+ </div>
327
+ <div class="prompt-preview">
328
+ {image_data['prompt'][:100]}{'...' if len(image_data['prompt']) > 100 else ''}
329
+ </div>
330
+ </div>
331
+ """, unsafe_allow_html=True)
332
+
333
+ if st.button(f"📋 Copy Prompt", key=f"copy_{idx}"):
334
+ st.write(f"**Prompt copied to clipboard:** {image_data['prompt']}")
335
+ st.success("Prompt ready to copy!")
336
+
337
+ def generate_image_placeholder(text, color="#667eea"):
338
+ """Generate a placeholder image with text"""
339
+ # This would normally use an image generation API
340
+ # For now, we'll create a simple placeholder
341
+ return f"https://picsum.photos/seed/{text}/400/500"
342
+
343
+ def create_placeholder_image(seed):
344
+ """Create a base64 encoded placeholder image"""
345
+ # Simple placeholder - in real app this would be the generated image
346
+ placeholder_url = f"https://picsum.photos/seed/{seed}/400/500"
347
+ return ""
348
+
349
+ def save_image_to_history(image_data):
350
+ """Save generated image to session history"""
351
+ if 'image_history' not in st.session_state:
352
+ st.session_state.image_history = []
353
+
354
+ st.session_state.image_history.append({
355
+ 'timestamp': time.time(),
356
+ 'data': image_data
357
+ })
358
+
359
+ # Keep only last 50 images
360
+ if len(st.session_state.image_history) > 50:
361
+ st.session_state.image_history = st.session_state.image_history[-50:]
362
+
363
+ def get_prompt_suggestions():
364
+ """Get prompt suggestions for users"""
365
+ return [
366
+ "Cinematic portrait with dramatic lighting",
367
+ "Fantasy landscape with magical elements",
368
+ "Urban street scene at golden hour",
369
+ "Abstract art with vibrant colors",
370
+ "Historical scene with period accuracy"
371
+ ]
372
+
373
+ === requirements.txt ===
374
+ streamlit
375
+ pillow
376
+ numpy
377
+ requests
378
+ base64
379
+ time