GenAILearniverse commited on
Commit
6a0b1b5
Β·
verified Β·
1 Parent(s): ff92d58

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +240 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,246 @@
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
  import streamlit as st
2
+ import base64
3
+ from openai import OpenAI
4
+ from datetime import datetime
5
 
6
+ # Page configuration - MUST be first Streamlit command
7
+ st.set_page_config(
8
+ page_title="Gen AI Learniverse - Project 17: AI Product Design Generator",
9
+ layout="centered",
10
+ page_icon="πŸ§ͺ"
11
+ )
12
+
13
+ # API Key Input Section
14
+ st.markdown("### πŸ”‘ OpenAI API Configuration")
15
+ api_key_input = st.text_input(
16
+ "Enter your OpenAI API Key",
17
+ type="password",
18
+ placeholder="sk-...",
19
+ help="Get your API key from https://platform.openai.com/api-keys"
20
+ )
21
+
22
+ # Initialize OpenAI client with UI input
23
+ client = None
24
+ if api_key_input:
25
+ try:
26
+ client = OpenAI(api_key=api_key_input)
27
+ st.success("βœ… API key provided successfully!")
28
+ except Exception as e:
29
+ st.error(f"❌ Invalid API key: {str(e)}")
30
+ st.stop()
31
+
32
+ def create_enhanced_prompt(description, style, background):
33
+ """Create an optimized prompt for GPT Image"""
34
+
35
+ style_modifiers = {
36
+ "Photorealistic": "photorealistic, high-definition, commercial photography quality",
37
+ "Minimalist": "clean minimalist design, simple geometric forms, uncluttered",
38
+ "Premium": "luxury premium materials, high-end finish, sophisticated design",
39
+ "Industrial": "industrial design aesthetic, functional form, raw materials",
40
+ "Eco-friendly": "sustainable materials, natural textures, environmentally conscious design",
41
+ "Futuristic": "cutting-edge futuristic design, sleek surfaces, advanced technology",
42
+ "Retro": "vintage-inspired design, classic proportions, nostalgic elements"
43
+ }
44
+
45
+ background_settings = {
46
+ "White Studio": "clean white studio background with soft professional lighting",
47
+ "Wooden Table": "natural wood surface with warm ambient lighting",
48
+ "Marble Counter": "elegant marble surface with subtle veining and reflections",
49
+ "Gradient": "smooth gradient background transitioning from light to dark",
50
+ "Natural Light": "soft natural daylight with gentle shadows",
51
+ "Dark Dramatic": "dark moody background with dramatic accent lighting"
52
+ }
53
 
54
+ prompt = f"""
55
+ Product design visualization: {description.strip()}
 
56
 
57
+ Style requirements:
58
+ - {style_modifiers.get(style, style.lower())} aesthetic
59
+ - {background_settings.get(background, background.lower())}
60
+ - Professional product photography composition
61
+ - Sharp focus with appropriate depth of field
62
+ - Consistent lighting that highlights product features and materials
63
+
64
+ Technical specifications:
65
+ - Center the product in frame with balanced composition
66
+ - Include subtle reflections and shadows for realism
67
+ - Maintain accurate proportions and scale
68
+ - Ensure all product details are clearly visible
69
+ - Use studio-quality lighting setup
70
+
71
+ Render as a catalog-ready product image with commercial photography standards.
72
  """
73
 
74
+ return prompt
75
+
76
+ def generate_product_design(description, style, background, size, quality, transparent):
77
+ """Generate product design with improved prompting"""
78
+
79
+ with st.spinner("🎨 Creating your product design... This may take up to 2 minutes for complex designs."):
80
+
81
+ # Parse size selection
82
+ size_map = {
83
+ "1024x1024 (Square)": "1024x1024",
84
+ "1536x1024 (Landscape)": "1536x1024",
85
+ "1024x1536 (Portrait)": "1024x1536"
86
+ }
87
+ selected_size = size_map[size]
88
+
89
+ # Enhanced prompt engineering
90
+ prompt = create_enhanced_prompt(description, style, background)
91
+
92
+ try:
93
+ # Prepare generation parameters
94
+ gen_params = {
95
+ "model": "gpt-image-1",
96
+ "prompt": prompt,
97
+ "size": selected_size,
98
+ "quality": quality,
99
+ "n": 1
100
+ }
101
+
102
+ # Add transparency if requested and compatible
103
+ if transparent and quality in ["medium", "high"]:
104
+ gen_params["background"] = "transparent"
105
+ st.info("🎯 Generating with transparent background")
106
+
107
+ # Generate image
108
+ result = client.images.generate(**gen_params)
109
+
110
+ # Process and display result
111
+ image_base64 = result.data[0].b64_json
112
+ image_bytes = base64.b64decode(image_base64)
113
+
114
+ # Display with better formatting
115
+ st.success("βœ… Product design generated successfully!")
116
+
117
+ col_img, col_info = st.columns([3, 1])
118
+
119
+ with col_img:
120
+ st.image(
121
+ image_bytes,
122
+ caption=f"🎨 {style} Product Design",
123
+ use_column_width=True
124
+ )
125
+
126
+ with col_info:
127
+ st.markdown("**Generation Details:**")
128
+ st.text(f"Size: {selected_size}")
129
+ st.text(f"Quality: {quality}")
130
+ st.text(f"Style: {style}")
131
+ if transparent and quality in ["medium", "high"]:
132
+ st.text("Background: Transparent")
133
+
134
+ # Download options
135
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
136
+ filename = f"product_design_{timestamp}.png"
137
+
138
+ st.download_button(
139
+ label="πŸ“₯ Download High-Quality Image",
140
+ data=image_bytes,
141
+ file_name=filename,
142
+ mime="image/png",
143
+ help="Save your generated product design"
144
+ )
145
+
146
+ except Exception as e:
147
+ st.error(f"❌ Generation failed: {str(e)}")
148
+
149
+ # Provide helpful error guidance
150
+ if "rate limit" in str(e).lower():
151
+ st.info("πŸ•’ Rate limit reached. Please wait a moment before trying again.")
152
+ elif "content policy" in str(e).lower():
153
+ st.warning("⚠️ Your prompt may have triggered content filters. Try rephrasing your description.")
154
+ else:
155
+ st.info("πŸ’‘ Try simplifying your description or reducing the quality setting.")
156
+
157
+ #Main UI
158
+ st.title("Project 17: @GENAILearniverse - AI Product Design Prototype Generator")
159
+ st.markdown("Transform your product ideas into stunning visual prototypes using GPT Image!")
160
+
161
+ # Only show main interface if API key is provided
162
+ if client:
163
+ # Create tabs for better organization
164
+ tab1, tab2 = st.tabs(["🎨 Generate Design", "ℹ️ Tips & Examples"])
165
+
166
+ with tab1:
167
+ # User input with better validation
168
+ product_description = st.text_area(
169
+ "Describe Your Product Idea",
170
+ height=120,
171
+ placeholder="E.g., A sleek wireless charging pad with a transparent glass surface and glowing LED indicators, featuring a minimalist circular design",
172
+ help="Be specific about materials, colors, shapes, and key features"
173
+ )
174
+
175
+ # Enhanced options in columns
176
+ col1, col2, col3 = st.columns(3)
177
+
178
+ with col1:
179
+ style = st.selectbox(
180
+ "Design Style",
181
+ ["Photorealistic", "Minimalist", "Premium", "Industrial", "Eco-friendly", "Futuristic", "Retro"]
182
+ )
183
+
184
+ with col2:
185
+ background = st.selectbox(
186
+ "Background Setting",
187
+ ["White Studio", "Wooden Table", "Marble Counter", "Gradient", "Natural Light", "Dark Dramatic"]
188
+ )
189
+
190
+ with col3:
191
+ image_size = st.selectbox(
192
+ "Image Size",
193
+ ["1024x1024 (Square)", "1536x1024 (Landscape)", "1024x1536 (Portrait)"],
194
+ help="Square is fastest to generate"
195
+ )
196
+
197
+ # Advanced options in expander
198
+ with st.expander("πŸ”§ Advanced Settings"):
199
+ col_adv1, col_adv2 = st.columns(2)
200
+
201
+ with col_adv1:
202
+ quality = st.selectbox(
203
+ "Quality Level",
204
+ ["auto", "high", "medium", "low"],
205
+ help="Higher quality takes longer but produces better results"
206
+ )
207
+
208
+ with col_adv2:
209
+ transparent_bg = st.checkbox(
210
+ "Transparent Background",
211
+ help="Only works with PNG format and medium/high quality"
212
+ )
213
+
214
+ # Generate button with validation
215
+ if st.button("πŸš€ Generate Product Design", type="primary"):
216
+ if not product_description.strip():
217
+ st.error("Please describe your product idea first!")
218
+ else:
219
+ generate_product_design(product_description, style, background, image_size, quality, transparent_bg)
220
+
221
+ with tab2:
222
+ st.markdown("""
223
+ ### πŸ’‘ Tips for Better Results
224
+
225
+ **Be Specific:**
226
+ - Include materials (glass, metal, plastic, wood)
227
+ - Mention colors and finishes (matte black, glossy white, brushed aluminum)
228
+ - Describe size and proportions
229
+ - Add functional details (buttons, screens, ports)
230
+
231
+ **Example Prompts:**
232
+ - "A compact bluetooth speaker with fabric mesh front, rounded corners, and copper accents"
233
+ - "An ergonomic computer mouse with RGB lighting strips and textured grip surfaces"
234
+ - "A sleek water bottle with bamboo cap and measurement markings on the side"
235
+
236
+ **Style Guide:**
237
+ - **Photorealistic**: Perfect for marketing materials
238
+ - **Minimalist**: Clean, simple designs
239
+ - **Premium**: Luxury feel with high-end materials
240
+ - **Industrial**: Raw, functional aesthetic
241
+ """)
242
+
243
+ else:
244
+ st.info("πŸ‘† Please enter your OpenAI API key above to get started!")
245
+
246
+