MODLI commited on
Commit
b20c963
·
verified ·
1 Parent(s): 07f61b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -119
app.py CHANGED
@@ -5,9 +5,9 @@ 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,67 +15,64 @@ try:
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)
@@ -85,54 +82,57 @@ def detect_clothing_type(image):
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)
@@ -144,103 +144,108 @@ def get_clothing_recommendations():
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():
214
  with gr.Column(scale=1):
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
242
  analyze_btn.click(
243
- fn=analyze_clothing,
244
  inputs=[image_input],
245
  outputs=output_text
246
  )
@@ -252,7 +257,7 @@ with gr.Blocks(title="Assistant Vêtements IA", theme=gr.themes.Soft()) as demo:
252
  )
253
 
254
  image_input.upload(
255
- fn=analyze_clothing,
256
  inputs=[image_input],
257
  outputs=output_text
258
  )
 
5
  from datasets import load_dataset
6
  import random
7
 
8
+ print("🚀 Chargement complet du dataset Fashion...")
9
 
10
+ # 📦 CHARGEMENT COMPLET SANS FILTRAGE
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 statistiques
19
+ print(f"📊 Total produits: {len(df)}")
20
+ print("🎯 Catégories principales:", df['masterCategory'].unique())
21
+ print("👕 Sous-catégories:", df['subCategory'].unique())
22
 
23
+ # Nettoyage des données
24
+ df = df[[
25
+ 'id', 'productDisplayName', 'masterCategory', 'subCategory',
26
+ 'articleType', 'baseColour', 'season', 'usage', 'gender'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  ]].dropna()
28
 
29
+ # 🎯 MAPPING COMPLET EN FRANÇAIS
30
+ FRENCH_CATEGORIES = {
31
+ 'Apparel': '👕 Vêtements',
32
+ 'Accessories': '👜 Accessoires',
33
+ 'Footwear': '👟 Chaussures',
34
+ 'Personal Care': '🧴 Soins',
35
+ 'Free Items': '🎁 Articles divers',
36
+ 'Sporting Goods': '🏀 Sports'
37
+ }
38
 
39
+ FRENCH_ARTICLES = {
40
+ # 👕 Vêtements
41
+ 'Tshirts': '👕 T-shirt', 'Shirts': '👔 Chemise', 'Pants': '👖 Pantalon',
42
+ 'Jeans': '👖 Jean', 'Dresses': '👗 Robe', 'Skirts': '👗 Jupe',
43
+ 'Jackets': '🧥 Veste', 'Coats': '🧥 Manteau', 'Sweaters': '🧥 Pull',
44
+ 'Tops': '👕 Haut', 'Shorts': '🩳 Short', 'Leggings': '🧘‍♀️ Legging',
45
+ 'Blazers': '👔 Blazer', 'Sweatshirts': '🧥 Sweat', 'Trousers': '👖 Pantalon',
46
+ 'Kurtas': '👗 Kurta', 'Sarees': '👗 Sari', 'Blouses': '👚 Blouse',
 
 
 
47
  'Tracksuits': '🏃‍♂️ Survêtement', 'Rain Jacket': '🧥 Veste pluie',
48
+ 'Swimwear': '🩱 Maillot de bain', 'Nightwear': '🌙 Nuit',
49
  'Innerwear': '🩲 Sous-vêtement', 'Sportswear': '🏀 Sport',
50
+
51
+ # 👟 Chaussures
52
  'Casual Shoes': '👟 Casual', 'Formal Shoes': '👞 Formel',
53
  'Sports Shoes': '🏃‍♂️ Sport', 'Sandals': '👡 Sandale',
54
+ 'Flip Flops': '👡 Tong', 'Heels': '👠 Talon', 'Boots': '👢 Botte',
55
+ 'Sneakers': '👟 Sneaker', 'Footwear': '👟 Chaussure',
56
+
57
+ # 👜 Accessoires
58
+ 'Bags': '👜 Sac', 'Handbags': '👜 Sac à main', 'Backpacks': '🎒 Sac à dos',
59
+ 'Wallets': '💼 Portefeuille', 'Belts': '⛓️ Ceinture', 'Sunglasses': '🕶️ Lunettes',
60
+ 'Watches': '⌚ Montre', 'Jewellery': '💍 Bijou', 'Hats': '🧢 Chapeau',
61
+ 'Caps': '🧢 Casquette', 'Scarves': '🧣 Écharpe', 'Gloves': '🧤 Gants',
62
+ 'Accessories': '👜 Accessoire'
63
  }
64
 
65
+ print(f"📊 {len(df)} produits dans la base de données")
66
+ print(f"🎯 Types d'articles: {len(df['articleType'].unique())}")
67
+
 
 
68
  except Exception as e:
69
  print(f"❌ Erreur chargement dataset: {e}")
70
+ df = None
71
+ FRENCH_CATEGORIES = {}
72
+ FRENCH_ARTICLES = {}
73
 
74
+ def detect_item_type(image):
75
+ """Détection du type d'article basée sur la forme"""
76
  try:
77
  if isinstance(image, str):
78
  pil_image = Image.open(image)
 
82
  width, height = pil_image.size
83
  aspect_ratio = width / height
84
 
85
+ # 🔍 DÉTECTION INTELLIGENTE TOUS TYPES
86
+ if aspect_ratio > 2.5:
87
+ return "👗 Robe", 88
88
+ elif aspect_ratio > 2.0:
89
+ return "🧥 Manteau", 85
90
  elif aspect_ratio > 1.5:
91
+ return "👔 Chemise", 82
92
+ elif aspect_ratio > 1.2:
93
  return "👕 T-shirt/Haut", 85
94
+ elif aspect_ratio > 0.9:
95
+ return "🧥 Veste/Pull", 80
96
+ elif aspect_ratio > 0.7:
97
+ return "👜 Sac", 78
98
  elif aspect_ratio > 0.5:
99
  return "👖 Pantalon/Jean", 90
100
+ elif aspect_ratio > 0.3:
101
+ return "👟 Chaussure", 83
102
+ elif aspect_ratio > 0.2:
103
+ return "🩳 Short", 79
104
  else:
105
+ return "💍 Accessoire", 75
106
 
107
  except:
108
+ return "🎁 Article mode", 70
109
 
110
+ def get_all_recommendations():
111
+ """Retourne des recommandations de tous types"""
112
  try:
113
+ if df is None or len(df) == 0:
114
+ # Mode démo avec tous types
115
  return [
116
+ {'name': 'Cotton T-Shirt', 'type': '👕 T-shirt', 'category': '👕 Vêtements', 'color': 'White', 'confidence': 88.5},
117
+ {'name': 'Slim Fit Jeans', 'type': '👖 Jean', 'category': '👕 Vêtements', 'color': 'Blue', 'confidence': 92.3},
118
+ {'name': 'Leather Handbag', 'type': '👜 Sac', 'category': '👜 Accessoires', 'color': 'Black', 'confidence': 85.7},
119
+ {'name': 'Running Shoes', 'type': '👟 Chaussure', 'category': '👟 Chaussures', 'color': 'White', 'confidence': 89.1},
120
+ {'name': 'Summer Dress', 'type': '👗 Robe', 'category': '👕 Vêtements', 'color': 'Floral', 'confidence': 90.2}
 
 
 
 
 
 
 
 
 
121
  ]
122
 
123
+ # Sélection aléatoire de tous types
124
+ sample_size = min(5, len(df))
125
+ sample = df.sample(sample_size)
126
 
127
  recommendations = []
128
  for _, row in sample.iterrows():
129
+ article_type = FRENCH_ARTICLES.get(row['articleType'], f"👔 {row['articleType']}")
130
+ category = FRENCH_CATEGORIES.get(row['masterCategory'], row['masterCategory'])
131
+
132
  recommendations.append({
133
  'name': row['productDisplayName'],
134
+ 'type': article_type,
135
+ 'category': category,
136
  'color': row['baseColour'],
137
  'season': row['season'],
138
  'confidence': round(random.uniform(75, 95), 1)
 
144
  print(f"Erreur recommandations: {e}")
145
  return None
146
 
147
+ def analyze_fashion_item(image):
148
+ """Analyse complète de tout article de mode"""
149
  try:
150
  if image is None:
151
+ return "❌ Veuillez uploader une image"
152
 
153
  # 🔍 Détection du type
154
+ detected_type, confidence = detect_item_type(image)
155
 
156
  # 📊 Recommandations
157
+ recommendations = get_all_recommendations()
158
 
159
  if not recommendations:
160
+ return "❌ Aucune donnée disponible"
161
 
162
  # 📝 Préparation des résultats
163
+ output = "## 🎯 ANALYSE COMPLÈTE MODE\n\n"
164
 
165
  output += f"### 🔍 TYPE DÉTECTÉ:\n"
166
  output += f"**{detected_type}** - {confidence}% de confiance\n\n"
167
 
168
+ output += "### 🛍️ ARTICLES 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" • Catégorie: {item['category']}\n"
174
  output += f" • Couleur: {item['color']}\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['category']}*\n"
182
  output += f"**Confiance: {best_match['confidence']}%**\n\n"
183
 
184
+ # 📈 Statistiques complètes
185
+ if df is not None:
186
+ output += "### 📊 BASE DE DONNÉES COMPLÈTE:\n"
187
+ output += f"• **{len(df)}** articles de mode\n"
188
+ output += f"• **{df['masterCategory'].nunique()}** catégories principales\n"
189
+ output += f"• **{df['articleType'].nunique()}** types différents\n"
190
+ output += f"• **{df['baseColour'].nunique()}** couleurs disponibles\n\n"
191
+
192
+ # Répartition par catégorie
193
+ category_counts = df['masterCategory'].value_counts()
194
+ output += "### 📦 RÉPARTITION PAR CATÉGORIE:\n"
195
+ for category, count in category_counts.items():
196
+ french_category = FRENCH_CATEGORIES.get(category, category)
197
+ output += f"• {french_category}: {count} articles\n"
198
 
199
+ output += "\n### 💡 CONSEILS POUR L'ANALYSE:\n"
200
  output += "• 📷 Photo nette et bien cadrée\n"
201
+ output += "• 🎯 Article bien visible\n"
202
  output += "• 🌞 Bon éclairage sans ombres\n"
203
+ output += "• 🧹 Fond uni de préférence\n"
204
 
205
  return output
206
 
207
  except Exception as e:
208
  return f"❌ Erreur d'analyse: {str(e)}"
209
 
210
+ # 🎨 INTERFACE COMPLÈTE
211
+ with gr.Blocks(title="Assistant Mode IA", theme=gr.themes.Soft()) as demo:
212
 
213
  gr.Markdown("""
214
+ # 🛍️ ASSISTANT IA MODE COMPLET
215
+ *Reconnaissance de tous les articles de mode*
216
  """)
217
 
218
  with gr.Row():
219
  with gr.Column(scale=1):
220
+ gr.Markdown("### 📤 UPLOADER UN ARTICLE")
221
  image_input = gr.Image(
222
  type="pil",
223
+ label="Vêtement, chaussure, sac ou accessoire",
224
  height=300,
225
  sources=["upload"],
226
  )
227
 
228
  gr.Markdown("""
229
+ ### 🎯 RECONNAÎT:
230
+ ✅ **Vêtements** (T-shirts, robes, jeans...)
231
+ ✅ **Chaussures** (baskets, talons, sandales...)
232
+ ✅ **Sacs** (sacs à main, sacs à dos...)
233
+ ✅ **Accessoires** (bijoux, ceintures, lunettes...)
234
+ **Articles de sport**
235
  """)
236
 
237
  analyze_btn = gr.Button("🔍 Analyser", variant="primary")
238
  clear_btn = gr.Button("🧹 Effacer", variant="secondary")
239
 
240
  with gr.Column(scale=2):
241
+ gr.Markdown("### 📊 RAPPORT COMPLET")
242
  output_text = gr.Markdown(
243
+ value="⬅️ Uploader un article pour analyse"
244
  )
245
 
246
  # 🎮 INTERACTIONS
247
  analyze_btn.click(
248
+ fn=analyze_fashion_item,
249
  inputs=[image_input],
250
  outputs=output_text
251
  )
 
257
  )
258
 
259
  image_input.upload(
260
+ fn=analyze_fashion_item,
261
  inputs=[image_input],
262
  outputs=output_text
263
  )