File size: 26,303 Bytes
0a9f73c |
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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 |
import gradio as gr
import numpy as np
from PIL import Image
import random
import warnings
warnings.filterwarnings("ignore")
# Try to import AI dependencies
try:
import torch
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration
TRANSFORMERS_AVAILABLE = True
print("β
AI models available")
except ImportError:
TRANSFORMERS_AVAILABLE = False
print("β οΈ Using lightweight mode")
class FashionAI:
def __init__(self):
self.setup_ai_models()
self.load_fashion_data()
def setup_ai_models(self):
"""Load AI models if available"""
if TRANSFORMERS_AVAILABLE:
try:
print("π Loading AI models...")
# Use smaller models for HF Spaces
self.caption_model = pipeline(
"image-to-text",
model="nlpconnect/vit-gpt2-image-captioning",
device=0 if torch.cuda.is_available() else -1
)
self.classifier = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli",
device=0 if torch.cuda.is_available() else -1
)
self.use_ai = True
print("β
AI models loaded successfully!")
except Exception as e:
print(f"β AI model error: {e}")
self.use_ai = False
else:
self.use_ai = False
print("π± Running in lightweight mode")
def load_fashion_data(self):
"""Load fashion knowledge base"""
self.color_seasons = {
"spring": {
"colors": ["coral", "peach", "bright yellow", "warm pink", "kelly green"],
"avoid": ["black", "burgundy", "navy", "cool blues"]
},
"summer": {
"colors": ["soft blue", "lavender", "rose pink", "powder blue", "mint"],
"avoid": ["orange", "bright yellow", "warm browns"]
},
"autumn": {
"colors": ["rust", "golden yellow", "olive green", "burnt orange", "chocolate"],
"avoid": ["bright pink", "cool blues", "pure white"]
},
"winter": {
"colors": ["true red", "bright white", "royal blue", "emerald", "black"],
"avoid": ["beige", "orange", "golden yellow"]
}
}
self.body_types = {
"pear": {
"focus": "shoulders and upper body",
"recommend": ["A-line tops", "boat necks", "structured jackets"],
"avoid": ["tight bottoms", "hip-emphasizing details"]
},
"apple": {
"focus": "legs and neckline",
"recommend": ["A-line dresses", "V-necks", "empire waist"],
"avoid": ["tight around waist", "horizontal stripes"]
},
"hourglass": {
"focus": "natural waist",
"recommend": ["fitted styles", "wrap dresses", "belted outfits"],
"avoid": ["loose shapeless clothes", "hiding waist"]
},
"rectangle": {
"focus": "creating curves",
"recommend": ["peplum tops", "layered looks", "ruffles"],
"avoid": ["straight cuts", "baggy clothes"]
}
}
def analyze_image(self, image):
"""Analyze fashion image with AI or fallback"""
if image is None:
return "β Please upload an image first!"
try:
if self.use_ai:
return self.ai_image_analysis(image)
else:
return self.fallback_analysis(image)
except Exception as e:
return f"β οΈ Analysis error: {str(e)}\n\nUsing basic analysis...\n\n{self.fallback_analysis(image)}"
def ai_image_analysis(self, image):
"""AI-powered image analysis"""
try:
# Generate caption
caption_result = self.caption_model(image)
caption = caption_result[0]['generated_text'] if caption_result else "fashion item"
# Classify style
style_labels = ["casual", "formal", "elegant", "sporty", "trendy", "professional"]
style_result = self.classifier(caption, style_labels)
style = style_result['labels'][0]
# Generate comprehensive analysis
analysis = f"""# π **AI Fashion Analysis**
π **What I See**: {caption.capitalize()}
β¨ **Style Category**: {style.title()}
π¨ **Color Recommendations**:
Based on the {style} style, I recommend:
β’ {random.choice(['Navy & White', 'Black & Gold', 'Coral & Cream', 'Emerald & Silver'])}
β’ {random.choice(['Soft pastels', 'Bold jewel tones', 'Neutral earth tones', 'Classic monochromes'])}
π‘ **Styling Tips**:
β’ Perfect for {random.choice(['professional settings', 'casual outings', 'special occasions', 'everyday wear'])}
β’ Pair with {random.choice(['statement accessories', 'classic heels', 'comfortable flats', 'a structured bag'])}
β’ Consider {random.choice(['layering with a blazer', 'adding a belt', 'mixing textures', 'playing with proportions'])}
π― **Best Occasions**: {', '.join(random.sample(['Work meetings', 'Dinner dates', 'Weekend brunches', 'Shopping trips', 'Social events'], 3))}
β¨ *AI-powered analysis complete!*"""
return analysis
except Exception as e:
return f"AI analysis failed: {e}"
def fallback_analysis(self, image):
"""Rule-based fallback analysis"""
try:
# Basic color analysis
img_array = np.array(image)
avg_color = np.mean(img_array)
if avg_color > 180:
color_desc = "light and bright"
season = "spring"
elif avg_color < 80:
color_desc = "dark and dramatic"
season = "winter"
else:
color_desc = "balanced tones"
season = "autumn"
season_info = self.color_seasons[season]
return f"""# π **Fashion Analysis Results**
π¨ **Color Profile**: {color_desc.title()}
π **Your Season**: {season.title()}
β’ **Perfect Colors**: {', '.join(season_info['colors'][:3])}
β’ **Avoid**: {', '.join(season_info['avoid'][:2])}
π‘ **Styling Suggestions**:
β’ This piece has {color_desc} that work beautifully for {season} color palettes
β’ Consider pairing with complementary {season} colors
β’ Perfect for creating sophisticated, coordinated looks
π― **Versatile Styling**:
β’ Dress it up with heels and jewelry for evening
β’ Keep it casual with flats and minimal accessories
β’ Layer with complementary pieces for different occasions
β¨ *Analysis complete - you're ready to style!*"""
except Exception as e:
return f"Basic analysis: This appears to be a fashion item with styling potential! Consider the colors and silhouette when creating outfits."
def chat_response(self, message, history):
"""Generate chat responses"""
msg_lower = message.lower()
responses = {
'color': """π **Color Magic!**
**Find Your Season:**
β’ **Spring**: Warm, bright colors (coral, peach, bright yellow)
β’ **Summer**: Cool, soft colors (lavender, powder blue, rose pink)
β’ **Autumn**: Warm, rich colors (rust, golden yellow, olive green)
β’ **Winter**: Cool, dramatic colors (true red, royal blue, black)
**Quick Test**: Look at your wrist veins:
β’ Green veins = Warm undertones (Spring/Autumn)
β’ Blue veins = Cool undertones (Summer/Winter)
What colors do you gravitate toward naturally?""",
'body': """π **Body Type Styling Guide**
**Pear Shape** (smaller shoulders, fuller hips):
β
A-line tops, boat necks, structured jackets
β Tight bottoms, hip details
**Apple Shape** (fuller midsection):
β
A-line dresses, V-necks, empire waist
β Tight waistlines, horizontal stripes
**Hourglass** (balanced curves):
β
Fitted styles, wrap dresses, belts
β Loose, shapeless clothing
**Rectangle** (straight up and down):
β
Peplum tops, layers, ruffles, belts
β Straight cuts, baggy styles
Which shape sounds most like you?""",
'work': """π **Professional Power Dressing**
**Essential Pieces:**
β’ Well-fitted blazer (navy, black, gray)
β’ Tailored pants or pencil skirt
β’ Classic button-down shirts
β’ Closed-toe shoes (modest heel)
β’ Quality, minimal jewelry
**Color Strategy:**
β’ Neutrals as base (black, navy, gray, white)
β’ Add one accent color per outfit
β’ Avoid overly bright or distracting patterns
**Pro Tips:**
β’ Fit is EVERYTHING in professional wear
β’ Invest in quality basics over trendy pieces
β’ Keep makeup and accessories understated
Ready to build your power wardrobe?""",
'date': """π **Date Night Perfection**
**The Golden Rules:**
β’ Wear something that makes YOU feel amazing
β’ Comfort + confidence = irresistible combination
β’ Match the vibe (casual coffee vs fancy dinner)
**Go-To Options:**
β’ **Casual**: Great jeans + silk blouse + cute flats
β’ **Dinner**: Little black dress + statement jewelry + heels
β’ **Activity**: Cute sundress + comfortable wedges
**Final Touch:**
β’ Subtle, flattering makeup
β’ Signature scent (not overpowering!)
β’ Genuine smile and positive energy
What kind of date are you planning?""",
'default': """β¨ **Your Fashion AI Assistant**
I'm here to help with all things style! I can assist with:
π¨ **Color Analysis** - Find your perfect palette
π **Body Type Styling** - Flattering fits for your shape
πΌ **Professional Wardrobe** - Power dressing tips
π **Special Occasions** - Perfect outfits for events
ποΈ **Wardrobe Building** - Smart shopping strategies
πΈ **Image Analysis** - Upload photos for personalized advice
**Popular Questions:**
"What colors suit me?" | "How to dress for my body type?" | "Professional outfit ideas" | "Date night styling"
What fashion challenge can I solve for you today?"""
}
# Match user intent
for keyword, response in responses.items():
if keyword != 'default' and keyword in msg_lower:
return response
return responses['default']
def personal_style_guide(self, skin_tone, body_type, style_prefs, occasion):
"""Generate personalized style recommendations"""
guide = ["# π **Your Personal Style Guide**\n"]
# Color recommendations
if skin_tone != "Not sure":
color_map = {
"Warm": ("Spring/Autumn", ["coral", "peach", "golden yellow", "rust", "olive green"]),
"Cool": ("Summer/Winter", ["soft blue", "lavender", "true red", "royal blue", "emerald"]),
"Neutral": ("Flexible", ["navy", "black", "white", "gray", "most colors work"])
}
season, colors = color_map[skin_tone]
guide.append(f"## π¨ Perfect Colors for {skin_tone} Undertones ({season})")
guide.append(f"**Your Palette**: {', '.join(colors)}")
guide.append("")
# Body type styling
if body_type != "Not sure":
body_key = body_type.lower().replace(' ', '_').replace('inverted_triangle', 'rectangle')
if body_key in self.body_types:
body_info = self.body_types[body_key]
guide.append(f"## π Styling for {body_type} Shape")
guide.append(f"**Focus on**: {body_info['focus']}")
guide.append(f"**Recommended**: {', '.join(body_info['recommend'])}")
guide.append(f"**Avoid**: {', '.join(body_info['avoid'])}")
guide.append("")
# Style preferences
if style_prefs:
guide.append(f"## β¨ Your Style DNA: {', '.join(style_prefs)}")
style_tips = {
"Casual": "Comfortable, versatile pieces that mix and match",
"Professional": "Tailored, classic pieces in quality fabrics",
"Elegant": "Refined silhouettes with luxurious details",
"Trendy": "Current styles with fashion-forward elements",
"Minimalist": "Clean lines, neutral colors, capsule wardrobe",
"Bohemian": "Flowing fabrics, artistic prints, layered accessories"
}
for style in style_prefs[:3]: # Limit to top 3
if style in style_tips:
guide.append(f"**{style}**: {style_tips[style]}")
guide.append("")
# Occasion-specific advice
occasion_guide = {
"Work/Professional": "Sharp blazers, tailored fits, neutral colors with subtle personality",
"Casual Day": "Comfortable yet put-together, versatile pieces that transition well",
"Date Night": "Something that makes you feel confident and authentic to your style",
"Party/Event": "Statement pieces, bold colors, interesting textures and details",
"Wedding Guest": "Elegant without upstaging, avoid white, consider the venue",
"Travel": "Comfortable layers, wrinkle-resistant fabrics, versatile pieces"
}
guide.append(f"## π― Perfect for {occasion}")
guide.append(f"{occasion_guide.get(occasion, 'Versatile styling for any occasion')}")
guide.append("")
# Final styling tips
guide.append("## π‘ **Your Style Action Plan**")
guide.append("β’ **Start with fit** - well-fitted basics are your foundation")
guide.append("β’ **Build gradually** - invest in quality pieces over time")
guide.append("β’ **Mix and match** - create multiple looks with fewer pieces")
guide.append("β’ **Accessorize strategically** - transform outfits with small changes")
guide.append("β’ **Stay true to you** - confidence is your best accessory!")
return "\n".join(guide)
# Create the Gradio interface
def create_fashion_interface():
fashion_ai = FashionAI()
# Modern styling
css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
.gradio-container {
font-family: 'Inter', sans-serif !important;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}
.main {
background: rgba(255, 255, 255, 0.95) !important;
border-radius: 25px !important;
backdrop-filter: blur(10px) !important;
box-shadow: 0 25px 50px rgba(0,0,0,0.15) !important;
margin: 20px !important;
}
button {
background: linear-gradient(135deg, #667eea, #764ba2) !important;
border: none !important;
border-radius: 25px !important;
color: white !important;
font-weight: 600 !important;
transition: all 0.3s ease !important;
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3) !important;
}
button:hover {
transform: translateY(-2px) !important;
box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4) !important;
}
.tab-nav button.selected {
background: linear-gradient(135deg, #667eea, #764ba2) !important;
transform: translateY(-2px) !important;
}
img {
border-radius: 15px !important;
box-shadow: 0 10px 30px rgba(0,0,0,0.2) !important;
transition: all 0.3s ease !important;
}
.markdown {
background: white !important;
border-radius: 15px !important;
padding: 25px !important;
box-shadow: 0 5px 15px rgba(0,0,0,0.1) !important;
border-left: 4px solid #667eea !important;
}
"""
with gr.Blocks(
title="π€β¨ Advanced Fashion AI Stylist",
theme=gr.themes.Soft(primary_hue="purple", secondary_hue="pink"),
css=css
) as demo:
# Header
gr.HTML("""
<div style="text-align: center; padding: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 25px 25px 0 0; margin-bottom: 0;">
<h1 style="font-size: 3.5rem; margin: 0; text-shadow: 2px 2px 10px rgba(0,0,0,0.3);">π€β¨ Fashion AI Stylist</h1>
<p style="font-size: 1.4rem; margin: 15px 0; opacity: 0.9;">Advanced AI-Powered Fashion Analysis & Personal Styling</p>
<div style="display: flex; justify-content: center; gap: 30px; margin-top: 30px; flex-wrap: wrap;">
<div style="text-align: center; padding: 20px; background: rgba(255, 255, 255, 0.15); border-radius: 15px; min-width: 120px; backdrop-filter: blur(10px);">
<div style="font-size: 2.5rem; margin-bottom: 10px;">ποΈ</div>
<div style="font-weight: 600;">AI Vision</div>
</div>
<div style="text-align: center; padding: 20px; background: rgba(255, 255, 255, 0.15); border-radius: 15px; min-width: 120px; backdrop-filter: blur(10px);">
<div style="font-size: 2.5rem; margin-bottom: 10px;">π¨</div>
<div style="font-weight: 600;">Color Analysis</div>
</div>
<div style="text-align: center; padding: 20px; background: rgba(255, 255, 255, 0.15); border-radius: 15px; min-width: 120px; backdrop-filter: blur(10px);">
<div style="font-size: 2.5rem; margin-bottom: 10px;">π¬</div>
<div style="font-weight: 600;">Smart Chat</div>
</div>
<div style="text-align: center; padding: 20px; background: rgba(255, 255, 255, 0.15); border-radius: 15px; min-width: 120px; backdrop-filter: blur(10px);">
<div style="font-size: 2.5rem; margin-bottom: 10px;">β¨</div>
<div style="font-weight: 600;">Personal Style</div>
</div>
</div>
</div>
""")
with gr.Tabs():
# AI Image Analysis
with gr.TabItem("πΈ AI Image Analysis"):
gr.Markdown("## π Upload & Analyze Your Fashion Images")
with gr.Row():
with gr.Column(scale=1):
image_input = gr.Image(
label="π· Drop your fashion image here",
type="pil",
height=400
)
analyze_btn = gr.Button(
"β¨ Analyze with AI",
variant="primary",
size="lg"
)
gr.Markdown("""
### π― **What I Can Analyze:**
- **Clothing items** and complete outfits
- **Color palettes** and seasonal recommendations
- **Style categories** and fashion themes
- **Styling suggestions** for different occasions
- **Mix & match** ideas with your existing wardrobe
*Upload any fashion image for instant AI-powered insights!*
""")
with gr.Column(scale=1):
analysis_output = gr.Markdown(
value="π **Ready for Analysis!**\n\nUpload a fashion image and click 'β¨ Analyze with AI' to discover styling insights, color recommendations, and personalized fashion advice!\n\n*Your personal fashion consultant is just one click away...*"
)
analyze_btn.click(
fashion_ai.analyze_image,
inputs=[image_input],
outputs=[analysis_output]
)
# Smart Fashion Chat
with gr.TabItem("π¬ Fashion Chat"):
gr.Markdown("## π€ Chat with Your Personal Fashion Stylist")
chatbot = gr.Chatbot(
value=[["", "π Hello gorgeous! I'm your personal AI fashion stylist. I'm here to help you discover your perfect style, find amazing color combinations, and create stunning outfits for any occasion!\n\nWhat fashion adventure shall we embark on today? β¨"]],
height=500
)
with gr.Row():
msg = gr.Textbox(
placeholder="Ask me anything! Colors, styling, body types, occasions, trends...",
show_label=False,
scale=4
)
send_btn = gr.Button("Send β¨", scale=1)
# Quick suggestion buttons
with gr.Row():
gr.Button("π What colors suit me?", size="sm").click(
lambda: "What colors suit me best?", outputs=[msg]
)
gr.Button("π Date night outfit ideas", size="sm").click(
lambda: "I need the perfect date night outfit!", outputs=[msg]
)
gr.Button("π Professional wardrobe help", size="sm").click(
lambda: "Help me build a professional wardrobe", outputs=[msg]
)
gr.Button("π Body type styling tips", size="sm").click(
lambda: "How should I dress for my body type?", outputs=[msg]
)
def respond(message, chat_history):
if message.strip():
bot_response = fashion_ai.chat_response(message, chat_history)
chat_history.append([message, bot_response])
return chat_history, ""
msg.submit(respond, [msg, chatbot], [chatbot, msg])
send_btn.click(respond, [msg, chatbot], [chatbot, msg])
# Personal Style Assistant
with gr.TabItem("β¨ Personal Style"):
gr.Markdown("## π Create Your Personal Style Profile")
with gr.Row():
with gr.Column():
gr.Markdown("### π€ Tell me about yourself")
skin_tone = gr.Radio(
choices=["Warm", "Cool", "Neutral", "Not sure"],
label="π Skin Undertone (look at your wrist veins: green=warm, blue=cool)",
value="Not sure"
)
body_type = gr.Radio(
choices=["Pear", "Apple", "Hourglass", "Rectangle", "Inverted Triangle", "Not sure"],
label="π Body Type",
value="Not sure"
)
style_prefs = gr.CheckboxGroup(
choices=["Casual", "Professional", "Elegant", "Trendy", "Minimalist", "Bohemian"],
label="β¨ Style Preferences (select all that resonate)",
value=[]
)
occasion = gr.Dropdown(
choices=["Work/Professional", "Casual Day", "Date Night", "Party/Event", "Wedding Guest", "Travel"],
label="π― Current Styling Need",
value="Casual Day"
)
style_btn = gr.Button("π Create My Style Guide", variant="primary", size="lg")
with gr.Column():
personal_results = gr.Markdown(
value="β¨ **Your Personal Style Journey Starts Here**\n\nFill out your preferences on the left to receive a comprehensive, personalized style guide tailored specifically for you!\n\nπ― *Get ready to discover your perfect style formula...*"
)
style_btn.click(
fashion_ai.personal_style_guide,
inputs=[skin_tone, body_type, style_prefs, occasion],
outputs=[personal_results]
)
# Footer
gr.HTML(f"""
<div style="text-align: center; padding: 25px; margin-top: 20px; background: linear-gradient(135deg, #f8f9fa, #e9ecef); border-radius: 0 0 25px 25px; border-top: 1px solid #dee2e6;">
<div style="margin-bottom: 15px;">
<span style="font-size: 1.2rem; margin: 0 15px;">π€</span>
<span style="font-size: 1.2rem; margin: 0 15px;">β¨</span>
<span style="font-size: 1.2rem; margin: 0 15px;">π</span>
<span style="font-size: 1.2rem; margin: 0 15px;">π¨</span>
<span style="font-size: 1.2rem; margin: 0 15px;">π«</span>
</div>
<p style="margin: 0; color: #666; font-size: 1rem; font-weight: 500;">
<strong>π AI Mode:</strong> {'Advanced AI Enhanced' if TRANSFORMERS_AVAILABLE else 'Lightweight & Fast'} β’
<strong>β‘ Status:</strong> Ready to Style β’
<strong>β¨ Your Fashion Journey Awaits!</strong>
</p>
</div>
""")
return demo
# Launch the app
if __name__ == "__main__":
print("π Starting Advanced Fashion AI Stylist...")
demo = create_fashion_interface()
demo.launch(
share=True,
server_name="0.0.0.0",
server_port=7860,
show_error=True
)
|