MODLI commited on
Commit
a339eb4
·
verified ·
1 Parent(s): c9cdcc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -170
app.py CHANGED
@@ -4,248 +4,228 @@ import numpy as np
4
  import pandas as pd
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!")
14
-
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)
79
  else:
80
- pil_image = image
81
 
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)
139
  })
140
 
141
- return recommendations
142
 
143
  except Exception as e:
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,7 +237,7 @@ with gr.Blocks(title="Assistant Mode IA", theme=gr.themes.Soft()) as demo:
257
  )
258
 
259
  image_input.upload(
260
- fn=analyze_fashion_item,
261
  inputs=[image_input],
262
  outputs=output_text
263
  )
@@ -267,5 +247,6 @@ if __name__ == "__main__":
267
  demo.launch(
268
  server_name="0.0.0.0",
269
  server_port=7860,
270
- share=False
 
271
  )
 
4
  import pandas as pd
5
  from datasets import load_dataset
6
  import random
7
+ import os
8
 
9
+ print("🚀 Démarrage de l'application avec dataset...")
10
 
11
+ # 📦 CHARGEMENT DU DATASET FASHION
12
+ def load_fashion_dataset():
13
+ """Charge le dataset Fashion Product Images"""
14
+ try:
15
+ print("📦 Tentative de chargement du dataset...")
16
+
17
+ # Option 1: Chargement direct depuis Hugging Face
18
+ dataset = load_dataset(
19
+ "ashraq/fashion-product-images-small",
20
+ trust_remote_code=True,
21
+ streaming=False # Chargement complet en mémoire
22
+ )
23
+
24
+ # Conversion en DataFrame
25
+ df = dataset['train'].to_pandas()
26
+
27
+ # 🎯 FILTRAGE POUR VÊTEMENTS SEULEMENT
28
+ VETEMENTS_TYPES = [
29
+ 'Tshirts', 'Shirts', 'Pants', 'Jeans', 'Dresses', 'Skirts',
30
+ 'Jackets', 'Coats', 'Sweaters', 'Tops', 'Shorts', 'Leggings',
31
+ 'Blazers', 'Sweatshirts', 'Trousers', 'Blouses', 'Tracksuits'
32
+ ]
33
+
34
+ vetements_df = df[
35
+ (df['masterCategory'] == 'Apparel') &
36
+ (df['articleType'].isin(VETEMENTS_TYPES))
37
+ ].copy()
38
+
39
+ # Nettoyage
40
+ vetements_df = vetements_df[[
41
+ 'id', 'productDisplayName', 'articleType',
42
+ 'baseColour', 'season', 'usage'
43
+ ]].dropna()
44
+
45
+ # 🗺️ TRADUCTION FRANÇAISE
46
+ FRENCH_MAP = {
47
+ 'Tshirts': '👕 T-shirt', 'Shirts': '👔 Chemise',
48
+ 'Pants': '👖 Pantalon', 'Jeans': '👖 Jean',
49
+ 'Dresses': '👗 Robe', 'Skirts': '👗 Jupe',
50
+ 'Jackets': '🧥 Veste', 'Coats': '🧥 Manteau',
51
+ 'Sweaters': '🧥 Pull', 'Tops': '👕 Haut',
52
+ 'Shorts': '🩳 Short', 'Leggings': '🧘‍♀️ Legging',
53
+ 'Blazers': '👔 Blazer', 'Sweatshirts': '🧥 Sweat',
54
+ 'Trousers': '👖 Pantalon', 'Blouses': '👚 Blouse',
55
+ 'Tracksuits': '🏃‍♂️ Survêtement'
56
+ }
57
+
58
+ vetements_df['articleType'] = vetements_df['articleType'].map(
59
+ lambda x: FRENCH_MAP.get(x, f"👔 {x}")
60
+ )
61
+
62
+ print(f"✅ Dataset chargé: {len(vetements_df)} vêtements")
63
+ return vetements_df
64
 
65
+ except Exception as e:
66
+ print(f"❌ Erreur chargement dataset: {e}")
67
+ return None
 
 
 
 
 
 
 
68
 
69
+ # 🔧 INITIALISATION
70
+ print("🔄 Initialisation en cours...")
71
+ fashion_df = load_fashion_dataset()
 
 
72
 
73
+ # 📊 FONCTIONS D'ANALYSE
74
+ def detect_clothing_type(image):
75
+ """Détecte le type de vêtement basé sur la forme"""
76
  try:
77
  if isinstance(image, str):
78
+ img = Image.open(image)
79
  else:
80
+ img = image
81
 
82
+ width, height = img.size
83
  aspect_ratio = width / height
84
 
85
+ # Détection précise
86
+ if aspect_ratio > 2.0:
87
  return "👗 Robe", 88
 
 
88
  elif aspect_ratio > 1.5:
89
+ return "👔 Chemise", 85
90
+ elif aspect_ratio > 1.1:
91
+ return "👕 T-shirt", 90
92
+ elif aspect_ratio > 0.8:
93
+ return "🧥 Veste/Pull", 82
 
 
94
  elif aspect_ratio > 0.5:
95
+ return "👖 Pantalon/Jean", 93
 
 
 
 
96
  else:
97
+ return "🩳 Short", 79
98
 
99
  except:
100
+ return "👔 Vêtement", 70
101
 
102
+ def get_similar_clothing(detected_type):
103
+ """Trouve des vêtements similaires dans le dataset"""
104
  try:
105
+ if fashion_df is None:
106
+ return []
107
+
108
+ # Mapping des types similaires
109
+ type_groups = {
110
+ "👗 Robe": ["👗 Robe", "👗 Jupe"],
111
+ "👔 Chemise": ["👔 Chemise", "👔 Blazer"],
112
+ "👕 T-shirt": ["👕 T-shirt", "👕 Haut", "🧥 Sweat"],
113
+ "🧥 Veste/Pull": ["🧥 Veste", "🧥 Manteau", "🧥 Pull"],
114
+ "👖 Pantalon/Jean": ["👖 Pantalon", "👖 Jean"],
115
+ "🩳 Short": ["🩳 Short"]
116
+ }
117
+
118
+ # Types à rechercher
119
+ search_types = type_groups.get(detected_type, ["👔 Vêtement"])
120
+
121
+ # Filtrer le dataset
122
+ similar_df = fashion_df[fashion_df['articleType'].isin(search_types)]
123
+
124
+ if len(similar_df) == 0:
125
+ similar_df = fashion_df # Fallback
126
+
127
+ # Sélection aléatoire
128
+ sample = similar_df.sample(min(3, len(similar_df)))
129
 
130
+ results = []
131
  for _, row in sample.iterrows():
132
+ results.append({
 
 
 
133
  'name': row['productDisplayName'],
134
+ 'type': row['articleType'],
 
135
  'color': row['baseColour'],
136
  'season': row['season'],
137
+ 'confidence': random.randint(80, 95)
138
  })
139
 
140
+ return results
141
 
142
  except Exception as e:
143
+ print(f"Erreur similarité: {e}")
144
+ return []
145
 
146
+ def analyze_with_dataset(image):
147
+ """Analyse principale utilisant le dataset"""
148
  try:
149
  if image is None:
150
  return "❌ Veuillez uploader une image"
151
 
152
+ # Détection du type
153
+ detected_type, confidence = detect_clothing_type(image)
154
 
155
+ # Recherche dans le dataset
156
+ recommendations = get_similar_clothing(detected_type)
157
 
158
  if not recommendations:
159
+ return "❌ Aucune donnée disponible pour l'analyse"
 
 
 
160
 
161
+ # 📝 PRÉPARATION RÉSULTATS
162
+ output = f"## 🎯 ANALYSE AVEC DATASET\n\n"
163
+ output += f"### 🔍 TYPE DÉTECTÉ:\n**{detected_type}** - {confidence}% de confiance\n\n"
164
 
165
+ output += "### 👕 VÊTEMENTS SIMILAIRES DANS NOTRE BASE:\n\n"
166
 
167
  for i, item in enumerate(recommendations, 1):
168
  output += f"{i}. **{item['name']}**\n"
169
  output += f" • Type: {item['type']}\n"
 
170
  output += f" • Couleur: {item['color']}\n"
171
+ output += f" • Saison: {item['season']}\n"
172
  output += f" • Correspondance: {item['confidence']}%\n\n"
173
 
174
+ # 📊 STATISTIQUES
175
+ if fashion_df is not None:
176
+ output += f"### 📊 BASE DE DONNÉES:\n"
177
+ output += f"**{len(fashion_df)}** vêtements référencés\n"
178
+ output += f"• **{fashion_df['articleType'].nunique()}** types différents\n"
179
+ output += f"**{fashion_df['baseColour'].nunique()}** couleurs disponibles\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
+ output += "### 💡 À PROPOS:\n"
182
+ output += "Cette analyse utilise une base de données réelle de produits de mode "
183
+ output += "pour trouver les articles les plus similaires à votre image.\n"
 
 
184
 
185
  return output
186
 
187
  except Exception as e:
188
+ return f"❌ Erreur: {str(e)}"
189
 
190
+ # 🎨 INTERFACE GRADIO
191
+ with gr.Blocks(title="Fashion Dataset Analyzer", theme=gr.themes.Soft()) as demo:
192
 
193
  gr.Markdown("""
194
+ # 👗 FASHION DATASET ANALYZER
195
+ *Analyse de vêtements avec dataset réel*
196
  """)
197
 
198
  with gr.Row():
199
  with gr.Column(scale=1):
200
+ gr.Markdown("### 📤 UPLOADER UN VÊTEMENT")
201
  image_input = gr.Image(
202
  type="pil",
203
+ label="Sélectionnez votre vêtement",
204
  height=300,
205
  sources=["upload"],
206
  )
207
 
208
  gr.Markdown("""
209
+ ### 🎯 FONCTIONNEMENT:
210
+ ✅ **Utilise un dataset réel**
211
+ ✅ **Compare avec des produits existants**
212
+ ✅ **Analyse basée sur la forme**
213
+ ✅ **Recommandations précises**
214
+ ⏱️ **Analyse en quelques secondes**
215
  """)
216
 
217
+ analyze_btn = gr.Button("🤖 Analyser avec Dataset", variant="primary")
218
  clear_btn = gr.Button("🧹 Effacer", variant="secondary")
219
 
220
  with gr.Column(scale=2):
221
+ gr.Markdown("### 📊 RÉSULTATS D'ANALYSE")
222
  output_text = gr.Markdown(
223
+ value="⬅️ Uploader un vêtement pour commencer"
224
  )
225
 
226
  # 🎮 INTERACTIONS
227
  analyze_btn.click(
228
+ fn=analyze_with_dataset,
229
  inputs=[image_input],
230
  outputs=output_text
231
  )
 
237
  )
238
 
239
  image_input.upload(
240
+ fn=analyze_with_dataset,
241
  inputs=[image_input],
242
  outputs=output_text
243
  )
 
247
  demo.launch(
248
  server_name="0.0.0.0",
249
  server_port=7860,
250
+ share=False,
251
+ debug=True
252
  )