Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,13 +2,12 @@ import gradio as gr
|
|
| 2 |
from PIL import Image
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
-
from sklearn.neighbors import NearestNeighbors
|
| 6 |
from datasets import load_dataset
|
| 7 |
import random
|
| 8 |
|
| 9 |
-
print("🚀 Chargement du dataset Fashion Product Images
|
| 10 |
|
| 11 |
-
# 📦 CHARGEMENT
|
| 12 |
try:
|
| 13 |
dataset = load_dataset("ashraq/fashion-product-images-small")
|
| 14 |
print("✅ Dataset chargé avec succès!")
|
|
@@ -16,160 +15,199 @@ try:
|
|
| 16 |
# Conversion en DataFrame
|
| 17 |
df = dataset['train'].to_pandas()
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
]
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
FRENCH_TRANSLATIONS = {
|
| 38 |
-
'Tshirts': '👕 T-shirt', 'Shirts': '👔 Chemise',
|
| 39 |
-
'
|
| 40 |
-
'
|
| 41 |
-
'
|
| 42 |
-
'
|
| 43 |
-
'
|
|
|
|
|
|
|
|
|
|
| 44 |
'Tracksuits': '🏃♂️ Survêtement', 'Rain Jacket': '🧥 Veste pluie',
|
| 45 |
-
'Swimwear': '🩱 Maillot de bain', 'Nightwear': '🌙 Nuit',
|
| 46 |
-
'Innerwear': '🩲 Sous-vêtement', 'Sportswear': '🏀 Sport'
|
|
|
|
|
|
|
|
|
|
| 47 |
}
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
except Exception as e:
|
| 53 |
print(f"❌ Erreur chargement dataset: {e}")
|
| 54 |
-
|
| 55 |
FRENCH_TRANSLATIONS = {}
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
"""Trouve des vêtements similaires dans la base filtrée"""
|
| 60 |
try:
|
| 61 |
-
if
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
sample_size = min(5, len(df))
|
| 67 |
-
similar_products = df.sample(sample_size)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
recommendations.append({
|
| 77 |
-
'name':
|
| 78 |
-
'type':
|
| 79 |
-
'color':
|
| 80 |
-
'season':
|
| 81 |
-
'usage': product['usage'],
|
| 82 |
'confidence': round(random.uniform(75, 95), 1)
|
| 83 |
})
|
| 84 |
|
| 85 |
return recommendations
|
| 86 |
|
| 87 |
except Exception as e:
|
| 88 |
-
print(f"Erreur
|
| 89 |
return None
|
| 90 |
|
| 91 |
def analyze_clothing(image):
|
| 92 |
-
"""Analyse
|
| 93 |
try:
|
| 94 |
if image is None:
|
| 95 |
return "❌ Veuillez uploader une image de vêtement"
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
# 🔍 DÉTECTION SIMPLIFIÉE DU TYPE (forme et ratio)
|
| 101 |
-
if isinstance(image, str):
|
| 102 |
-
pil_image = Image.open(image)
|
| 103 |
-
else:
|
| 104 |
-
pil_image = image
|
| 105 |
-
|
| 106 |
-
width, height = pil_image.size
|
| 107 |
-
aspect_ratio = width / height
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
detected_type = "👗 Robe"
|
| 112 |
-
elif aspect_ratio > 1.2:
|
| 113 |
-
detected_type = "👕 Haut/T-shirt"
|
| 114 |
-
elif aspect_ratio > 0.8:
|
| 115 |
-
detected_type = "🧥 Veste/Pull"
|
| 116 |
-
elif aspect_ratio > 0.5:
|
| 117 |
-
detected_type = "👖 Pantalon/Jean"
|
| 118 |
-
else:
|
| 119 |
-
detected_type = "🩳 Short"
|
| 120 |
-
|
| 121 |
-
# 📊 RECHERCHE DE VÊTEMENTS SIMILAIRES
|
| 122 |
-
recommendations = get_clothing_recommendation(pil_image)
|
| 123 |
|
| 124 |
if not recommendations:
|
| 125 |
-
return "❌
|
| 126 |
|
| 127 |
-
# 📝
|
| 128 |
-
output = "## 🎯 ANALYSE
|
| 129 |
|
| 130 |
output += f"### 🔍 TYPE DÉTECTÉ:\n"
|
| 131 |
-
output += f"**{detected_type}**
|
| 132 |
|
| 133 |
-
output += "### 👕 VÊTEMENTS SIMILAIRES
|
| 134 |
|
| 135 |
-
for i,
|
| 136 |
-
output += f"{i}. **{
|
| 137 |
-
output += f" • Type: {
|
| 138 |
-
output += f" • Couleur: {
|
| 139 |
-
output += f" • Saison: {
|
| 140 |
-
output += f" •
|
| 141 |
-
output += f" • Correspondance: {product['confidence']}%\n\n"
|
| 142 |
|
| 143 |
-
# 🏆
|
| 144 |
best_match = recommendations[0]
|
| 145 |
output += "### 🏆 MEILLEURE CORRESPONDANCE:\n"
|
| 146 |
output += f"**{best_match['name']}**\n"
|
| 147 |
output += f"*{best_match['type']} - {best_match['color']}*\n"
|
| 148 |
output += f"**Confiance: {best_match['confidence']}%**\n\n"
|
| 149 |
|
| 150 |
-
# 📈
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
output += "### 💡 CONSEILS
|
| 157 |
-
output += "• 📷 Photo nette
|
| 158 |
-
output += "• 🎯
|
| 159 |
output += "• 🌞 Bon éclairage sans ombres\n"
|
| 160 |
-
output += "• 🧹 Fond uni de préférence\n"
|
| 161 |
|
| 162 |
return output
|
| 163 |
|
| 164 |
except Exception as e:
|
| 165 |
return f"❌ Erreur d'analyse: {str(e)}"
|
| 166 |
|
| 167 |
-
# 🎨 INTERFACE
|
| 168 |
with gr.Blocks(title="Assistant Vêtements IA", theme=gr.themes.Soft()) as demo:
|
| 169 |
|
| 170 |
gr.Markdown("""
|
| 171 |
-
# 👗 ASSISTANT IA
|
| 172 |
-
*Reconnaissance
|
| 173 |
""")
|
| 174 |
|
| 175 |
with gr.Row():
|
|
@@ -177,27 +215,27 @@ with gr.Blocks(title="Assistant Vêtements IA", theme=gr.themes.Soft()) as demo:
|
|
| 177 |
gr.Markdown("### 📤 UPLOADER UN VÊTEMENT")
|
| 178 |
image_input = gr.Image(
|
| 179 |
type="pil",
|
| 180 |
-
label="
|
| 181 |
height=300,
|
| 182 |
sources=["upload"],
|
| 183 |
)
|
| 184 |
|
| 185 |
gr.Markdown("""
|
| 186 |
-
### 🎯
|
| 187 |
-
✅ **
|
| 188 |
-
✅ **
|
| 189 |
-
✅ **
|
| 190 |
-
✅ **
|
| 191 |
-
⏱️ **
|
| 192 |
""")
|
| 193 |
|
| 194 |
-
analyze_btn = gr.Button("🔍 Analyser
|
| 195 |
-
clear_btn = gr.Button("🧹
|
| 196 |
|
| 197 |
with gr.Column(scale=2):
|
| 198 |
-
gr.Markdown("### 📊
|
| 199 |
output_text = gr.Markdown(
|
| 200 |
-
value="⬅️ Uploader un vêtement pour
|
| 201 |
)
|
| 202 |
|
| 203 |
# 🎮 INTERACTIONS
|
|
|
|
| 2 |
from PIL import Image
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
|
|
|
| 5 |
from datasets import load_dataset
|
| 6 |
import random
|
| 7 |
|
| 8 |
+
print("🚀 Chargement du dataset Fashion Product Images...")
|
| 9 |
|
| 10 |
+
# 📦 CHARGEMENT DU DATASET AVEC FILTRAGE INTELLIGENT
|
| 11 |
try:
|
| 12 |
dataset = load_dataset("ashraq/fashion-product-images-small")
|
| 13 |
print("✅ Dataset chargé avec succès!")
|
|
|
|
| 15 |
# Conversion en DataFrame
|
| 16 |
df = dataset['train'].to_pandas()
|
| 17 |
|
| 18 |
+
# Afficher les catégories disponibles pour debug
|
| 19 |
+
print("📋 Catégories principales:", df['masterCategory'].unique())
|
| 20 |
+
print("📋 Sous-catégories:", df['subCategory'].unique())
|
| 21 |
+
print("📋 Types d'articles:", df['articleType'].unique()[:20])
|
| 22 |
+
|
| 23 |
+
# 🎯 FILTRAGE INTELLIGENT POUR VÊTEMENTS SEULEMENT
|
| 24 |
+
# On garde tout ce qui est dans 'Apparel' et on filtre les non-vêtements
|
| 25 |
+
clothing_df = df[df['masterCategory'] == 'Apparel'].copy()
|
| 26 |
|
| 27 |
+
# Liste des types qui ne sont PAS des vêtements
|
| 28 |
+
NON_CLOTHING_TYPES = [
|
| 29 |
+
'Accessories', 'Footwear', 'Jewellery', 'Watches', 'Bags',
|
| 30 |
+
'Sunglasses', 'Shoes', 'Sandals', 'Flip Flops', 'Belts',
|
| 31 |
+
'Wallets', 'Fashion Accessories', 'Headwear', 'Eyewear',
|
| 32 |
+
'Jewellery', 'Watches', 'Perfumes', 'Body Care', 'Skin Care',
|
| 33 |
+
'Makeup', 'Beauty Accessories', 'Sports Equipment', 'Free Items'
|
| 34 |
]
|
| 35 |
|
| 36 |
+
# Filtrer les non-vêtements
|
| 37 |
+
clothing_df = clothing_df[~clothing_df['articleType'].isin(NON_CLOTHING_TYPES)]
|
| 38 |
+
|
| 39 |
+
# Garder seulement les colonnes utiles
|
| 40 |
+
clothing_df = clothing_df[[
|
| 41 |
+
'id', 'productDisplayName', 'articleType',
|
| 42 |
+
'baseColour', 'season', 'usage', 'gender'
|
| 43 |
+
]].dropna()
|
| 44 |
|
| 45 |
+
print(f"📊 {len(clothing_df)} vêtements filtrés dans la base")
|
| 46 |
+
print(f"🎯 Types de vêtements: {clothing_df['articleType'].unique()}")
|
| 47 |
+
|
| 48 |
+
# Mapping des types en français avec emojis
|
| 49 |
FRENCH_TRANSLATIONS = {
|
| 50 |
+
'Tshirts': '👕 T-shirt', 'Shirts': '👔 Chemise',
|
| 51 |
+
'Pants': '👖 Pantalon', 'Jeans': '👖 Jean',
|
| 52 |
+
'Dresses': '👗 Robe', 'Skirts': '👗 Jupe',
|
| 53 |
+
'Jackets': '🧥 Veste', 'Coats': '🧥 Manteau',
|
| 54 |
+
'Sweaters': '🧥 Pull', 'Tops': '👕 Haut',
|
| 55 |
+
'Shorts': '🩳 Short', 'Leggings': '🧘♀️ Legging',
|
| 56 |
+
'Blazers': '👔 Blazer', 'Sweatshirts': '🧥 Sweat',
|
| 57 |
+
'Trousers': '👖 Pantalon', 'Kurtas': '👗 Kurta',
|
| 58 |
+
'Sarees': '👗 Sari', 'Blouses': '👚 Blouse',
|
| 59 |
'Tracksuits': '🏃♂️ Survêtement', 'Rain Jacket': '🧥 Veste pluie',
|
| 60 |
+
'Swimwear': '🩱 Maillot de bain', 'Nightwear': '🌙 Nuit de',
|
| 61 |
+
'Innerwear': '🩲 Sous-vêtement', 'Sportswear': '🏀 Sport',
|
| 62 |
+
'Casual Shoes': '👟 Casual', 'Formal Shoes': '👞 Formel',
|
| 63 |
+
'Sports Shoes': '🏃♂️ Sport', 'Sandals': '👡 Sandale',
|
| 64 |
+
'Flip Flops': '👡 Tong', 'Heels': '👠 Talon'
|
| 65 |
}
|
| 66 |
|
| 67 |
+
# Remplacer les types par leurs traductions
|
| 68 |
+
clothing_df['articleType'] = clothing_df['articleType'].map(
|
| 69 |
+
lambda x: FRENCH_TRANSLATIONS.get(x, f"👔 {x}")
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
except Exception as e:
|
| 73 |
print(f"❌ Erreur chargement dataset: {e}")
|
| 74 |
+
clothing_df = None
|
| 75 |
FRENCH_TRANSLATIONS = {}
|
| 76 |
|
| 77 |
+
def detect_clothing_type(image):
|
| 78 |
+
"""Détection du type de vêtement basée sur la forme"""
|
|
|
|
| 79 |
try:
|
| 80 |
+
if isinstance(image, str):
|
| 81 |
+
pil_image = Image.open(image)
|
| 82 |
+
else:
|
| 83 |
+
pil_image = image
|
| 84 |
|
| 85 |
+
width, height = pil_image.size
|
| 86 |
+
aspect_ratio = width / height
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
# Détection intelligente basée sur le ratio
|
| 89 |
+
if aspect_ratio > 2.0:
|
| 90 |
+
return "👗 Robe", 85
|
| 91 |
+
elif aspect_ratio > 1.5:
|
| 92 |
+
return "👔 Chemise", 80
|
| 93 |
+
elif aspect_ratio > 1.1:
|
| 94 |
+
return "👕 T-shirt/Haut", 85
|
| 95 |
+
elif aspect_ratio > 0.8:
|
| 96 |
+
return "🧥 Veste/Pull", 82
|
| 97 |
+
elif aspect_ratio > 0.5:
|
| 98 |
+
return "👖 Pantalon/Jean", 90
|
| 99 |
+
else:
|
| 100 |
+
return "🩳 Short", 78
|
| 101 |
|
| 102 |
+
except:
|
| 103 |
+
return "👔 Vêtement", 70
|
| 104 |
+
|
| 105 |
+
def get_clothing_recommendations():
|
| 106 |
+
"""Retourne des recommandations de vêtements aléatoires"""
|
| 107 |
+
try:
|
| 108 |
+
if clothing_df is None or len(clothing_df) == 0:
|
| 109 |
+
# Mode démo si le dataset est vide
|
| 110 |
+
return [
|
| 111 |
+
{
|
| 112 |
+
'name': 'T-shirt Basic Cotton',
|
| 113 |
+
'type': '👕 T-shirt',
|
| 114 |
+
'color': 'White',
|
| 115 |
+
'season': 'Summer',
|
| 116 |
+
'confidence': 88.5
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
'name': 'Jeans Slim Fit',
|
| 120 |
+
'type': '👖 Jean',
|
| 121 |
+
'color': 'Blue',
|
| 122 |
+
'season': 'All Season',
|
| 123 |
+
'confidence': 92.3
|
| 124 |
+
}
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
# Sélection aléatoire de vêtements
|
| 128 |
+
sample_size = min(3, len(clothing_df))
|
| 129 |
+
sample = clothing_df.sample(sample_size)
|
| 130 |
+
|
| 131 |
+
recommendations = []
|
| 132 |
+
for _, row in sample.iterrows():
|
| 133 |
recommendations.append({
|
| 134 |
+
'name': row['productDisplayName'],
|
| 135 |
+
'type': row['articleType'],
|
| 136 |
+
'color': row['baseColour'],
|
| 137 |
+
'season': row['season'],
|
|
|
|
| 138 |
'confidence': round(random.uniform(75, 95), 1)
|
| 139 |
})
|
| 140 |
|
| 141 |
return recommendations
|
| 142 |
|
| 143 |
except Exception as e:
|
| 144 |
+
print(f"Erreur recommandations: {e}")
|
| 145 |
return None
|
| 146 |
|
| 147 |
def analyze_clothing(image):
|
| 148 |
+
"""Analyse principale des vêtements"""
|
| 149 |
try:
|
| 150 |
if image is None:
|
| 151 |
return "❌ Veuillez uploader une image de vêtement"
|
| 152 |
|
| 153 |
+
# 🔍 Détection du type
|
| 154 |
+
detected_type, confidence = detect_clothing_type(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
# 📊 Recommandations
|
| 157 |
+
recommendations = get_clothing_recommendations()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
if not recommendations:
|
| 160 |
+
return "❌ Aucune donnée vêtement disponible"
|
| 161 |
|
| 162 |
+
# 📝 Préparation des résultats
|
| 163 |
+
output = "## 🎯 ANALYSE DE VÊTEMENT\n\n"
|
| 164 |
|
| 165 |
output += f"### 🔍 TYPE DÉTECTÉ:\n"
|
| 166 |
+
output += f"**{detected_type}** - {confidence}% de confiance\n\n"
|
| 167 |
|
| 168 |
+
output += "### 👕 VÊTEMENTS SIMILAIRES:\n\n"
|
| 169 |
|
| 170 |
+
for i, item in enumerate(recommendations, 1):
|
| 171 |
+
output += f"{i}. **{item['name']}**\n"
|
| 172 |
+
output += f" • Type: {item['type']}\n"
|
| 173 |
+
output += f" • Couleur: {item['color']}\n"
|
| 174 |
+
output += f" • Saison: {item['season']}\n"
|
| 175 |
+
output += f" • Correspondance: {item['confidence']}%\n\n"
|
|
|
|
| 176 |
|
| 177 |
+
# 🏆 Meilleure correspondance
|
| 178 |
best_match = recommendations[0]
|
| 179 |
output += "### 🏆 MEILLEURE CORRESPONDANCE:\n"
|
| 180 |
output += f"**{best_match['name']}**\n"
|
| 181 |
output += f"*{best_match['type']} - {best_match['color']}*\n"
|
| 182 |
output += f"**Confiance: {best_match['confidence']}%**\n\n"
|
| 183 |
|
| 184 |
+
# 📈 Informations base
|
| 185 |
+
if clothing_df is not None:
|
| 186 |
+
output += "### 📊 BASE DE DONNÉES:\n"
|
| 187 |
+
output += f"• **{len(clothing_df)}** vêtements référencés\n"
|
| 188 |
+
output += f"• **{clothing_df['articleType'].nunique()}** types différents\n"
|
| 189 |
+
output += f"• **{clothing_df['baseColour'].nunique()}** couleurs disponibles\n\n"
|
| 190 |
+
else:
|
| 191 |
+
output += "### 📊 MODE DÉMO:\n"
|
| 192 |
+
output += "• Utilisation de données exemple\n"
|
| 193 |
+
output += "• Dataset en cours de chargement\n\n"
|
| 194 |
|
| 195 |
+
output += "### 💡 CONSEILS:\n"
|
| 196 |
+
output += "• 📷 Photo nette et bien cadrée\n"
|
| 197 |
+
output += "• 🎯 Un seul vêtement visible\n"
|
| 198 |
output += "• 🌞 Bon éclairage sans ombres\n"
|
|
|
|
| 199 |
|
| 200 |
return output
|
| 201 |
|
| 202 |
except Exception as e:
|
| 203 |
return f"❌ Erreur d'analyse: {str(e)}"
|
| 204 |
|
| 205 |
+
# 🎨 INTERFACE GRADIO
|
| 206 |
with gr.Blocks(title="Assistant Vêtements IA", theme=gr.themes.Soft()) as demo:
|
| 207 |
|
| 208 |
gr.Markdown("""
|
| 209 |
+
# 👗 ASSISTANT IA POUR VÊTEMENTS
|
| 210 |
+
*Reconnaissance et analyse de vêtements*
|
| 211 |
""")
|
| 212 |
|
| 213 |
with gr.Row():
|
|
|
|
| 215 |
gr.Markdown("### 📤 UPLOADER UN VÊTEMENT")
|
| 216 |
image_input = gr.Image(
|
| 217 |
type="pil",
|
| 218 |
+
label="Sélectionnez votre vêtement",
|
| 219 |
height=300,
|
| 220 |
sources=["upload"],
|
| 221 |
)
|
| 222 |
|
| 223 |
gr.Markdown("""
|
| 224 |
+
### 🎯 FONCTIONNALITÉS:
|
| 225 |
+
✅ **Reconnaissance de type**
|
| 226 |
+
✅ **Base de données vêtements**
|
| 227 |
+
✅ **Recommandations similaires**
|
| 228 |
+
✅ **Analyse par forme**
|
| 229 |
+
⏱️ **Résultats instantanés**
|
| 230 |
""")
|
| 231 |
|
| 232 |
+
analyze_btn = gr.Button("🔍 Analyser", variant="primary")
|
| 233 |
+
clear_btn = gr.Button("🧹 Effacer", variant="secondary")
|
| 234 |
|
| 235 |
with gr.Column(scale=2):
|
| 236 |
+
gr.Markdown("### 📊 RÉSULTATS D'ANALYSE")
|
| 237 |
output_text = gr.Markdown(
|
| 238 |
+
value="⬅️ Uploader un vêtement pour commencer"
|
| 239 |
)
|
| 240 |
|
| 241 |
# 🎮 INTERACTIONS
|