MODLI commited on
Commit
6edbd9a
·
verified ·
1 Parent(s): 872ee72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -112
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 (vêtements uniquement)...")
10
 
11
- # 📦 CHARGEMENT ET FILTRAGE DU DATASET
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
- # 🚫 FILTRAGE : UNIQUEMENT LES VÊTEMENTS
20
- VETEMENTS_CATEGORIES = [
21
- 'Apparel', 'Clothing', 'Garments', 'Wearables',
22
- 'Tshirts', 'Shirts', 'Pants', 'Jeans', 'Dresses',
23
- 'Skirts', 'Jackets', 'Coats', 'Sweaters', 'Tops'
24
- ]
 
 
25
 
26
- # Filtrage strict des vêtements
27
- df = df[
28
- (df['masterCategory'].isin(['Apparel'])) &
29
- (df['subCategory'].isin(['Clothing', 'Apparel'])) &
30
- (~df['articleType'].isin(['Accessories', 'Footwear', 'Jewellery', 'Watches', 'Bags', 'Sunglasses']))
 
 
31
  ]
32
 
33
- # Nettoyage et sélection des colonnes
34
- df = df[['id', 'productDisplayName', 'articleType', 'baseColour', 'season', 'usage']].dropna()
 
 
 
 
 
 
35
 
36
- # Mapping des types d'articles en français
 
 
 
37
  FRENCH_TRANSLATIONS = {
38
- 'Tshirts': '👕 T-shirt', 'Shirts': '👔 Chemise', 'Pants': '👖 Pantalon',
39
- 'Jeans': '👖 Jean', 'Dresses': '👗 Robe', 'Skirts': '👗 Jupe',
40
- 'Jackets': '🧥 Veste', 'Coats': '🧥 Manteau', 'Sweaters': '🧥 Pull',
41
- 'Tops': '👕 Haut', 'Shorts': '🩳 Short', 'Leggings': '🧘‍♀️ Legging',
42
- 'Blazers': '👔 Blazer', 'Sweatshirts': '🧥 Sweat', 'Trousers': '👖 Pantalon',
43
- 'Kurtas': '👗 Kurta', 'Sarees': '👗 Sari', 'Blouses': '👚 Blouse',
 
 
 
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
- print(f"📊 {len(df)} vêtements chargés dans la base de données")
50
- print(f"🎯 Types disponibles: {df['articleType'].unique().tolist()[:10]}")
51
-
 
 
52
  except Exception as e:
53
  print(f"❌ Erreur chargement dataset: {e}")
54
- df = None
55
  FRENCH_TRANSLATIONS = {}
56
 
57
- # 🎯 FONCTION DE RECOMMANDATION SIMPLIFIÉE
58
- def get_clothing_recommendation(image):
59
- """Trouve des vêtements similaires dans la base filtrée"""
60
  try:
61
- if df is None:
62
- return None
 
 
63
 
64
- # Sélection aléatoire de vêtements similaires (pour la démo)
65
- # Dans une vraie app, on utiliserait un modèle de vision
66
- sample_size = min(5, len(df))
67
- similar_products = df.sample(sample_size)
68
 
69
- recommendations = []
70
- for _, product in similar_products.iterrows():
71
- french_type = FRENCH_TRANSLATIONS.get(
72
- product['articleType'],
73
- f"👔 {product['articleType']}"
74
- )
 
 
 
 
 
 
 
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  recommendations.append({
77
- 'name': product['productDisplayName'],
78
- 'type': french_type,
79
- 'color': product['baseColour'],
80
- 'season': product['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 recommandation: {e}")
89
  return None
90
 
91
  def analyze_clothing(image):
92
- """Analyse spécialisée pour les vêtements"""
93
  try:
94
  if image is None:
95
  return "❌ Veuillez uploader une image de vêtement"
96
 
97
- if df is None or len(df) == 0:
98
- return "❌ Base de données vêtements non disponible"
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
- # Détection basée sur la forme
110
- if aspect_ratio > 1.8:
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 "❌ Aucun vêtement similaire trouvé"
126
 
127
- # 📝 PRÉPARATION DES RÉSULTATS
128
- output = "## 🎯 ANALYSE SPÉCIALISÉE VÊTEMENTS\n\n"
129
 
130
  output += f"### 🔍 TYPE DÉTECTÉ:\n"
131
- output += f"**{detected_type}** (basé sur la forme)\n\n"
132
 
133
- output += "### 👕 VÊTEMENTS SIMILAIRES DANS NOTRE BASE:\n\n"
134
 
135
- for i, product in enumerate(recommendations, 1):
136
- output += f"{i}. **{product['name']}**\n"
137
- output += f" • Type: {product['type']}\n"
138
- output += f" • Couleur: {product['color']}\n"
139
- output += f" • Saison: {product['season']}\n"
140
- output += f" • Usage: {product['usage']}\n"
141
- output += f" • Correspondance: {product['confidence']}%\n\n"
142
 
143
- # 🏆 MEILLEURE RECOMMANDATION
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
- # 📈 STATISTIQUES
151
- output += "### 📊 BASE DE DONNÉES VÊTEMENTS:\n"
152
- output += f" **{len(df)}** vêtements référencés\n"
153
- output += f"• **{df['articleType'].nunique()}** types différents\n"
154
- output += f"• **{df['baseColour'].nunique()}** couleurs disponibles\n\n"
 
 
 
 
 
155
 
156
- output += "### 💡 CONSEILS POUR L'ANALYSE:\n"
157
- output += "• 📷 Photo nette du vêtement seul\n"
158
- output += "• 🎯 Cadrage serré sur le vêtement\n"
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 SIMPLIFIÉE
168
  with gr.Blocks(title="Assistant Vêtements IA", theme=gr.themes.Soft()) as demo:
169
 
170
  gr.Markdown("""
171
- # 👗 ASSISTANT IA SPÉCIALISÉ VÊTEMENTS
172
- *Reconnaissance précise de vêtements uniquement*
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="Votre vêtement à analyser",
181
  height=300,
182
  sources=["upload"],
183
  )
184
 
185
  gr.Markdown("""
186
- ### 🎯 SPÉCIALISATION:
187
- ✅ **Uniquement des vêtements**
188
- ✅ **Pas d'accessoires**
189
- ✅ **Pas de chaussures**
190
- ✅ **Base de données filtrée**
191
- ⏱️ **Analyse instantanée**
192
  """)
193
 
194
- analyze_btn = gr.Button("🔍 Analyser le vêtement", variant="primary")
195
- clear_btn = gr.Button("🧹 Nouveau", variant="secondary")
196
 
197
  with gr.Column(scale=2):
198
- gr.Markdown("### 📊 RAPPORT VÊTEMENTS")
199
  output_text = gr.Markdown(
200
- value="⬅️ Uploader un vêtement pour analyse"
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