-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
463 lines (399 loc) Β· 17.5 KB
/
app.py
File metadata and controls
463 lines (399 loc) Β· 17.5 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import streamlit as st
import google.generativeai as genai
from dotenv import load_dotenv
import os
from PIL import Image
import io
import base64
import time
# Load environment variables
load_dotenv()
# Configure page
st.set_page_config(
page_title="Virtual Try-On App",
page_icon="π",
layout="wide",
initial_sidebar_state="collapsed"
)
# Load custom CSS for liquid glass design
def load_css():
st.markdown("""
<style>
/* Import Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
/* Global Styles */
.stApp {
background: linear-gradient(135deg,
rgba(74, 144, 226, 0.1) 0%,
rgba(255, 107, 107, 0.1) 35%,
rgba(142, 68, 173, 0.1) 100%);
font-family: 'Inter', sans-serif;
}
/* Liquid Glass Card Effect */
.glass-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-radius: 20px;
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
padding: 2rem;
margin: 1rem 0;
transition: all 0.3s ease;
}
.glass-card:hover {
transform: translateY(-5px);
box-shadow: 0 15px 40px 0 rgba(31, 38, 135, 0.5);
}
/* Header Styles */
.main-header {
text-align: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-size: 3rem;
font-weight: 700;
margin: 2rem 0;
text-shadow: 0 0 30px rgba(102, 126, 234, 0.5);
}
.sub-header {
text-align: center;
color: rgba(255, 255, 255, 0.8);
font-size: 1.2rem;
font-weight: 300;
margin-bottom: 3rem;
}
/* Upload Area Styles */
.upload-area {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border-radius: 15px;
border: 2px dashed rgba(255, 255, 255, 0.3);
padding: 2rem;
text-align: center;
transition: all 0.3s ease;
margin: 1rem 0;
}
.upload-area:hover {
border-color: rgba(102, 126, 234, 0.6);
background: rgba(102, 126, 234, 0.1);
}
/* Button Styles */
.stButton > button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 50px;
padding: 0.8rem 2rem;
font-weight: 600;
font-size: 1rem;
transition: all 0.3s ease;
box-shadow: 0 4px 15px 0 rgba(102, 126, 234, 0.4);
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px 0 rgba(102, 126, 234, 0.6);
}
/* Progress Bar */
.stProgress > div > div > div > div {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
/* Result Image Container */
.result-container {
background: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(15px);
border-radius: 20px;
padding: 2rem;
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
}
/* Hide Streamlit Components */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
/* Sidebar styling */
.css-1d391kg {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(20px);
}
/* File uploader styling */
.css-1cpxqw2 {
background: rgba(255, 255, 255, 0.05);
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
/* Spinning animation for loading */
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-spinner {
border: 4px solid rgba(255, 255, 255, 0.1);
border-left: 4px solid #667eea;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
</style>
""", unsafe_allow_html=True)
def initialize_gemini():
"""Initialize Gemini AI with API key"""
api_key = os.getenv("GEMINI_API_KEY")
if not api_key or api_key == "your_gemini_api_key_here":
return None
try:
genai.configure(api_key=api_key)
# Try the latest model first, fall back if not available
try:
return genai.GenerativeModel('gemini-2.0-flash-preview-image-generation')
except:
try:
return genai.GenerativeModel('gemini-2.0-flash-preview-image-generation')
except:
return genai.GenerativeModel('gemini-2.0-flash-preview-image-generation')
except Exception as e:
st.error(f"Error initializing Gemini AI: {str(e)}")
return None
def create_virtual_tryon(person_image, clothing_image, model):
"""Create virtual try-on using Gemini 2.0 Flash"""
try:
# Create a detailed prompt for virtual try-on image generation
prompt = """
You are an expert AI fashion designer with advanced image manipulation capabilities.
Please create a realistic virtual try-on image where the person in the first image is wearing the clothing item from the second image.
IMPORTANT INSTRUCTIONS:
1. Analyze the person's body shape, pose, lighting, and position in the first image
2. Extract the clothing item from the second image (dress, shirt, pants, etc.)
3. Digitally place and fit the clothing onto the person's body with:
- Accurate sizing and proportions matching their body type
- Natural fabric draping and realistic wrinkles
4. Match the lighting, shadows, and color temperature from the original person photo
5. Preserve the person's exact pose, facial expression, and body position
6. Keep the background completely unchanged
7. Ensure the clothing appears naturally worn, not just overlaid
8. Pay attention to how the fabric would naturally fall and move on their body
9. Make sure colors and textures of the clothing are preserved but adjusted for lighting
10. Create seamless blending so it looks like they are actually wearing the item
Generate a photorealistic virtual try-on result that looks completely natural and believable.
The output should be an actual image, not a description.
"""
# Convert PIL images to the format expected by Gemini
person_img_bytes = io.BytesIO()
person_image.save(person_img_bytes, format='PNG')
person_img_bytes = person_img_bytes.getvalue()
clothing_img_bytes = io.BytesIO()
clothing_image.save(clothing_img_bytes, format='PNG')
clothing_img_bytes = clothing_img_bytes.getvalue()
# Create the content for Gemini with image generation request
response = model.generate_content([
prompt,
{
"mime_type": "image/png",
"data": person_img_bytes
},
{
"mime_type": "image/png",
"data": clothing_img_bytes
}
])
return response.text, True
except Exception as e:
error_msg = f"Error creating virtual try-on: {str(e)}"
# Handle specific error types
if "quota" in str(e).lower():
error_msg = "β οΈ API quota exceeded. Please try again later or check your API usage limits."
elif "invalid" in str(e).lower() and "key" in str(e).lower():
error_msg = "π Invalid API key. Please check your Gemini API key in the .env file."
elif "network" in str(e).lower() or "connection" in str(e).lower():
error_msg = "π Network error. Please check your internet connection and try again."
elif "timeout" in str(e).lower():
error_msg = "β° Request timed out. Please try with smaller images or try again later."
elif "content" in str(e).lower() and "policy" in str(e).lower():
error_msg = "π« Content policy violation detected. Please ensure your images are appropriate."
elif "model" in str(e).lower():
error_msg = "π€ Model error. The Gemini 2.0 Flash model might not be available in your region yet."
return error_msg, False
def validate_image(image):
"""Validate uploaded image"""
if image is None:
return False, "No image uploaded"
# Check file size (max 10MB)
if len(image.getvalue()) > 10 * 1024 * 1024:
return False, "Image size too large. Please upload an image smaller than 10MB."
try:
# Try to open the image
img = Image.open(image)
# Check image dimensions
if img.width < 100 or img.height < 100:
return False, "Image too small. Please upload an image with minimum dimensions of 100x100 pixels."
if img.width > 4000 or img.height > 4000:
return False, "Image too large. Please upload an image with maximum dimensions of 4000x4000 pixels."
return True, "Image is valid"
except Exception as e:
return False, f"Invalid image format: {str(e)}"
def main():
load_css()
# Header
st.markdown('<h1 class="main-header">β¨ Virtual Try-On Studio</h1>', unsafe_allow_html=True)
st.markdown('<p class="sub-header">Transform your style with AI-powered virtual fashion fitting</p>', unsafe_allow_html=True)
# Add explanation about capabilities
st.markdown("""
<div class="glass-card">
<h3 style="color: #667eea; text-align: center;">π― Real Virtual Try-On</h3>
<p style="text-align: center; margin: 1rem 0;">
This app uses the latest Gemini 2.0 Flash model to create realistic virtual try-on images.
Upload your photo and a clothing item to see yourself actually wearing it!
</p>
</div>
""", unsafe_allow_html=True)
# Initialize Gemini
model = initialize_gemini()
if model is None:
st.markdown("""
<div class="glass-card" style="text-align: center; color: #ff6b6b;">
<h3>β οΈ API Key Required</h3>
<p>Please add your Gemini API key to the .env file to use this application.</p>
<p>Get your API key from <a href="https://makersuite.google.com/app/apikey" target="_blank" style="color: #667eea;">Google AI Studio</a></p>
</div>
""", unsafe_allow_html=True)
return
# Create two columns for uploads
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div class="glass-card">
<h3 style="text-align: center; color: #667eea; margin-bottom: 1rem;">πΈ Upload Your Photo</h3>
</div>
""", unsafe_allow_html=True)
person_image = st.file_uploader(
"Choose your photo",
type=['png', 'jpg', 'jpeg'],
key="person_upload",
help="Upload a clear photo of yourself"
)
if person_image:
# Validate person image
is_valid, message = validate_image(person_image)
if is_valid:
person_img = Image.open(person_image)
st.image(person_img, caption="Your Photo", use_column_width=True)
st.success("β
Photo uploaded successfully!")
else:
st.error(f"β {message}")
person_image = None
with col2:
st.markdown("""
<div class="glass-card">
<h3 style="text-align: center; color: #764ba2; margin-bottom: 1rem;">π Upload Clothing Item</h3>
</div>
""", unsafe_allow_html=True)
clothing_image = st.file_uploader(
"Choose clothing item",
type=['png', 'jpg', 'jpeg'],
key="clothing_upload",
help="Upload a photo of the clothing item you want to try on"
)
if clothing_image:
# Validate clothing image
is_valid, message = validate_image(clothing_image)
if is_valid:
clothing_img = Image.open(clothing_image)
st.image(clothing_img, caption="Clothing Item", use_column_width=True)
st.success("β
Clothing uploaded successfully!")
else:
st.error(f"β {message}")
clothing_image = None
# Try-on section
st.markdown("<br>", unsafe_allow_html=True)
if person_image and clothing_image:
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
if st.button("πͺ Create Virtual Try-On", key="tryon_button"):
with st.spinner("β¨ Creating your virtual try-on..."):
# Add progress bar
progress_bar = st.progress(0)
# Simulate processing steps
for i in range(1, 101):
time.sleep(0.02) # Simulate processing time
progress_bar.progress(i)
# Process the virtual try-on
person_img = Image.open(person_image)
clothing_img = Image.open(clothing_image)
result, success = create_virtual_tryon(person_img, clothing_img, model)
if success:
st.success("π Virtual try-on completed!")
st.markdown("""
<div class="result-container">
<h3 style="text-align: center; color: #667eea;">Your Virtual Try-On Result</h3>
</div>
""", unsafe_allow_html=True)
# Display result
st.markdown("### π Processing Result:")
st.write(result)
# Add note about image generation
st.info("""
**Note**: Gemini 2.0 Flash is primarily a text-based model. For actual image generation virtual try-on,
you may need to integrate with specialized image generation models like:
- Stable Diffusion with ControlNet
- DALL-E 3
- Midjourney
- Specialized virtual try-on APIs like Zyler or TryNow
""")
# Add download option
st.markdown("---")
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.info("π‘ Tip: For now, this provides detailed virtual try-on guidance!")
else:
st.error(f"β {result}")
else:
# Instructions
st.markdown("""
<div class="glass-card">
<h3 style="color: #667eea; text-align: center;">How to Create Virtual Try-On</h3>
<div style="display: flex; justify-content: space-around; margin: 2rem 0;">
<div style="text-align: center; flex: 1; margin: 0 1rem;">
<div style="font-size: 2rem; margin-bottom: 1rem;">πΈ</div>
<h4>Step 1</h4>
<p>Upload a clear photo of yourself</p>
</div>
<div style="text-align: center; flex: 1; margin: 0 1rem;">
<div style="font-size: 2rem; margin-bottom: 1rem;">π</div>
<h4>Step 2</h4>
<p>Upload the clothing item to try on</p>
</div>
<div style="text-align: center; flex: 1; margin: 0 1rem;">
<div style="font-size: 2rem; margin-bottom: 1rem;">πͺ</div>
<h4>Step 3</h4>
<p>Create your virtual try-on</p>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Sidebar with tips
with st.sidebar:
st.markdown("""
<div class="glass-card">
<h3 style="color: #667eea;">π‘ Tips for Best Virtual Try-On</h3>
<ul style="list-style-type: none; padding: 0;">
<li style="margin: 1rem 0;">π· Use well-lit, high-quality photos</li>
<li style="margin: 1rem 0;">π§ Stand straight and face the camera</li>
<li style="margin: 1rem 0;">π Choose clothing images with clear visibility</li>
<li style="margin: 1rem 0;">π― Avoid busy backgrounds</li>
<li style="margin: 1rem 0;">π Ensure good image resolution (min 100x100px)</li>
<li style="margin: 1rem 0;">π Include full-body shots for better results</li>
<li style="margin: 1rem 0;">β¨ Use the latest Gemini 2.0 Flash model</li>
</ul>
</div>
""", unsafe_allow_html=True)
st.markdown("""
<div class="glass-card">
<h3 style="color: #764ba2;">π Privacy & Security</h3>
<p style="font-size: 0.9rem;">Your images are processed securely and are not stored permanently. We respect your privacy and data security.</p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()