Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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("🚀
|
| 9 |
|
| 10 |
-
# 📦 CHARGEMENT
|
| 11 |
-
|
| 12 |
-
dataset
|
| 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 |
-
'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 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
FRENCH_CATEGORIES = {}
|
| 72 |
-
FRENCH_ARTICLES = {}
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
|
|
|
| 76 |
try:
|
| 77 |
if isinstance(image, str):
|
| 78 |
-
|
| 79 |
else:
|
| 80 |
-
|
| 81 |
|
| 82 |
-
width, height =
|
| 83 |
aspect_ratio = width / height
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
if aspect_ratio > 2.
|
| 87 |
return "👗 Robe", 88
|
| 88 |
-
elif aspect_ratio > 2.0:
|
| 89 |
-
return "🧥 Manteau", 85
|
| 90 |
elif aspect_ratio > 1.5:
|
| 91 |
-
return "👔 Chemise",
|
| 92 |
-
elif aspect_ratio > 1.
|
| 93 |
-
return "👕 T-shirt
|
| 94 |
-
elif aspect_ratio > 0.
|
| 95 |
-
return "🧥 Veste/Pull",
|
| 96 |
-
elif aspect_ratio > 0.7:
|
| 97 |
-
return "👜 Sac", 78
|
| 98 |
elif aspect_ratio > 0.5:
|
| 99 |
-
return "👖 Pantalon/Jean",
|
| 100 |
-
elif aspect_ratio > 0.3:
|
| 101 |
-
return "👟 Chaussure", 83
|
| 102 |
-
elif aspect_ratio > 0.2:
|
| 103 |
-
return "🩳 Short", 79
|
| 104 |
else:
|
| 105 |
-
return "
|
| 106 |
|
| 107 |
except:
|
| 108 |
-
return "
|
| 109 |
|
| 110 |
-
def
|
| 111 |
-
"""
|
| 112 |
try:
|
| 113 |
-
if
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
]
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
|
| 128 |
for _, row in sample.iterrows():
|
| 129 |
-
|
| 130 |
-
category = FRENCH_CATEGORIES.get(row['masterCategory'], row['masterCategory'])
|
| 131 |
-
|
| 132 |
-
recommendations.append({
|
| 133 |
'name': row['productDisplayName'],
|
| 134 |
-
'type':
|
| 135 |
-
'category': category,
|
| 136 |
'color': row['baseColour'],
|
| 137 |
'season': row['season'],
|
| 138 |
-
'confidence':
|
| 139 |
})
|
| 140 |
|
| 141 |
-
return
|
| 142 |
|
| 143 |
except Exception as e:
|
| 144 |
-
print(f"Erreur
|
| 145 |
-
return
|
| 146 |
|
| 147 |
-
def
|
| 148 |
-
"""Analyse
|
| 149 |
try:
|
| 150 |
if image is None:
|
| 151 |
return "❌ Veuillez uploader une image"
|
| 152 |
|
| 153 |
-
#
|
| 154 |
-
detected_type, confidence =
|
| 155 |
|
| 156 |
-
#
|
| 157 |
-
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 |
-
|
| 166 |
-
output
|
|
|
|
| 167 |
|
| 168 |
-
output += "###
|
| 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 |
-
#
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 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 += "
|
| 200 |
-
output += "
|
| 201 |
-
output += "
|
| 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
|
| 209 |
|
| 210 |
-
# 🎨 INTERFACE
|
| 211 |
-
with gr.Blocks(title="
|
| 212 |
|
| 213 |
gr.Markdown("""
|
| 214 |
-
#
|
| 215 |
-
*
|
| 216 |
""")
|
| 217 |
|
| 218 |
with gr.Row():
|
| 219 |
with gr.Column(scale=1):
|
| 220 |
-
gr.Markdown("### 📤 UPLOADER UN
|
| 221 |
image_input = gr.Image(
|
| 222 |
type="pil",
|
| 223 |
-
label="
|
| 224 |
height=300,
|
| 225 |
sources=["upload"],
|
| 226 |
)
|
| 227 |
|
| 228 |
gr.Markdown("""
|
| 229 |
-
###
|
| 230 |
-
✅ **
|
| 231 |
-
✅ **
|
| 232 |
-
✅ **
|
| 233 |
-
✅ **
|
| 234 |
-
|
| 235 |
""")
|
| 236 |
|
| 237 |
-
analyze_btn = gr.Button("
|
| 238 |
clear_btn = gr.Button("🧹 Effacer", variant="secondary")
|
| 239 |
|
| 240 |
with gr.Column(scale=2):
|
| 241 |
-
gr.Markdown("### 📊
|
| 242 |
output_text = gr.Markdown(
|
| 243 |
-
value="⬅️ Uploader un
|
| 244 |
)
|
| 245 |
|
| 246 |
# 🎮 INTERACTIONS
|
| 247 |
analyze_btn.click(
|
| 248 |
-
fn=
|
| 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=
|
| 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 |
)
|