Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,183 +4,172 @@ import numpy as np
|
|
| 4 |
import pandas as pd
|
| 5 |
from sklearn.neighbors import NearestNeighbors
|
| 6 |
from datasets import load_dataset
|
| 7 |
-
import
|
| 8 |
-
from io import BytesIO
|
| 9 |
-
import json
|
| 10 |
|
| 11 |
-
print("🚀 Chargement du dataset Fashion Product Images...")
|
| 12 |
|
| 13 |
-
# 📦 CHARGEMENT DU DATASET
|
| 14 |
try:
|
| 15 |
dataset = load_dataset("ashraq/fashion-product-images-small")
|
| 16 |
print("✅ Dataset chargé avec succès!")
|
| 17 |
|
| 18 |
-
# Conversion en DataFrame
|
| 19 |
df = dataset['train'].to_pandas()
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
'Apparel'
|
| 27 |
-
'
|
| 28 |
-
'Footwear'
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
-
print(f"📊 {len(df)}
|
|
|
|
| 35 |
|
| 36 |
except Exception as e:
|
| 37 |
print(f"❌ Erreur chargement dataset: {e}")
|
| 38 |
df = None
|
| 39 |
-
|
| 40 |
|
| 41 |
-
# 🎯
|
| 42 |
-
def
|
| 43 |
-
"""
|
| 44 |
try:
|
| 45 |
if df is None:
|
| 46 |
return None
|
| 47 |
-
|
| 48 |
-
# Features pour la similarité (simplifié)
|
| 49 |
-
features = pd.get_dummies(df[['masterCategory', 'subCategory', 'articleType']])
|
| 50 |
-
|
| 51 |
-
# Entraînement du modèle KNN
|
| 52 |
-
knn = NearestNeighbors(n_neighbors=5, metric='cosine')
|
| 53 |
-
knn.fit(features)
|
| 54 |
-
|
| 55 |
-
print("✅ Modèle de similarité entraîné")
|
| 56 |
-
return knn, features
|
| 57 |
-
|
| 58 |
-
except Exception as e:
|
| 59 |
-
print(f"❌ Erreur entraînement modèle: {e}")
|
| 60 |
-
return None
|
| 61 |
-
|
| 62 |
-
# Entraînement au démarrage
|
| 63 |
-
knn_model, feature_matrix = train_similarity_model()
|
| 64 |
-
|
| 65 |
-
def extract_image_features(image):
|
| 66 |
-
"""Extrait les caractéristiques basiques d'une image"""
|
| 67 |
-
try:
|
| 68 |
-
if isinstance(image, str):
|
| 69 |
-
img = Image.open(image)
|
| 70 |
-
else:
|
| 71 |
-
img = image
|
| 72 |
-
|
| 73 |
-
# Conversion en array numpy
|
| 74 |
-
img_array = np.array(img.convert('RGB'))
|
| 75 |
-
|
| 76 |
-
# Caractéristiques simples (couleur moyenne, texture)
|
| 77 |
-
avg_color = np.mean(img_array, axis=(0, 1))
|
| 78 |
-
contrast = np.std(img_array)
|
| 79 |
-
|
| 80 |
-
# Ratio d'aspect
|
| 81 |
-
width, height = img.size
|
| 82 |
-
aspect_ratio = width / height
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
'size_ratio': (width * height) / 1000
|
| 89 |
-
}
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
try:
|
| 98 |
-
if knn_model is None or df is None:
|
| 99 |
-
return None
|
| 100 |
|
| 101 |
-
|
| 102 |
-
# (Dans une version avancée, on utiliserait un vrai modèle de vision)
|
| 103 |
-
simulated_features = np.random.rand(1, feature_matrix.shape[1])
|
| 104 |
-
|
| 105 |
-
# Recherche des voisins les plus proches
|
| 106 |
-
distances, indices = knn_model.kneighbors(simulated_features, n_neighbors=n_neighbors)
|
| 107 |
-
|
| 108 |
-
similar_products = []
|
| 109 |
-
for i, idx in enumerate(indices[0]):
|
| 110 |
-
product = df.iloc[idx]
|
| 111 |
-
similar_products.append({
|
| 112 |
'name': product['productDisplayName'],
|
| 113 |
-
'
|
| 114 |
-
'type': product['articleType'],
|
| 115 |
'color': product['baseColour'],
|
| 116 |
-
'
|
|
|
|
|
|
|
| 117 |
})
|
| 118 |
|
| 119 |
-
return
|
| 120 |
|
| 121 |
except Exception as e:
|
| 122 |
-
print(f"Erreur
|
| 123 |
return None
|
| 124 |
|
| 125 |
-
def
|
| 126 |
-
"""
|
| 127 |
try:
|
| 128 |
if image is None:
|
| 129 |
return "❌ Veuillez uploader une image de vêtement"
|
| 130 |
|
| 131 |
-
if df is None:
|
| 132 |
-
return "❌ Base de données non disponible
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
if features is None:
|
| 137 |
-
return "❌ Impossible d'analyser l'image"
|
| 138 |
|
| 139 |
-
#
|
| 140 |
-
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
|
| 145 |
-
|
| 146 |
-
output = "## 🎯 RÉSULTATS D'ANALYSE AVEC IA\n\n"
|
| 147 |
-
output += "### 🔍 PRODUITS SIMILAIRES TROUVÉS:\n\n"
|
| 148 |
|
| 149 |
-
for i, product in enumerate(
|
| 150 |
output += f"{i}. **{product['name']}**\n"
|
| 151 |
-
output += f" • Catégorie: {product['category']}\n"
|
| 152 |
output += f" • Type: {product['type']}\n"
|
| 153 |
output += f" • Couleur: {product['color']}\n"
|
| 154 |
-
output += f" •
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
#
|
| 157 |
-
|
| 158 |
-
output += "### 🏆
|
| 159 |
-
output += f"**{
|
| 160 |
-
output += f"*{
|
| 161 |
-
output += f"**Confiance: {
|
| 162 |
|
| 163 |
# 📈 STATISTIQUES
|
| 164 |
-
output += "### 📊
|
| 165 |
-
output += f"• **{len(df)}**
|
| 166 |
-
output += f"• **{df['
|
| 167 |
-
output += f"• **{df['
|
| 168 |
|
| 169 |
-
output += "### 💡
|
| 170 |
-
output += "
|
| 171 |
-
output += "
|
|
|
|
|
|
|
| 172 |
|
| 173 |
return output
|
| 174 |
|
| 175 |
except Exception as e:
|
| 176 |
return f"❌ Erreur d'analyse: {str(e)}"
|
| 177 |
|
| 178 |
-
# 🎨 INTERFACE
|
| 179 |
-
with gr.Blocks(title="
|
| 180 |
|
| 181 |
gr.Markdown("""
|
| 182 |
-
# 👗 ASSISTANT IA
|
| 183 |
-
*
|
| 184 |
""")
|
| 185 |
|
| 186 |
with gr.Row():
|
|
@@ -194,26 +183,26 @@ with gr.Blocks(title="AI Fashion Assistant", theme=gr.themes.Soft()) as demo:
|
|
| 194 |
)
|
| 195 |
|
| 196 |
gr.Markdown("""
|
| 197 |
-
### 🎯
|
| 198 |
-
✅ **
|
| 199 |
-
✅ **
|
| 200 |
-
✅ **
|
| 201 |
-
✅ **
|
| 202 |
-
⏱️ **Analyse
|
| 203 |
""")
|
| 204 |
|
| 205 |
-
analyze_btn = gr.Button("
|
| 206 |
-
clear_btn = gr.Button("🧹
|
| 207 |
|
| 208 |
with gr.Column(scale=2):
|
| 209 |
-
gr.Markdown("### 📊 RAPPORT
|
| 210 |
output_text = gr.Markdown(
|
| 211 |
-
value="⬅️ Uploader
|
| 212 |
)
|
| 213 |
|
| 214 |
# 🎮 INTERACTIONS
|
| 215 |
analyze_btn.click(
|
| 216 |
-
fn=
|
| 217 |
inputs=[image_input],
|
| 218 |
outputs=output_text
|
| 219 |
)
|
|
@@ -225,7 +214,7 @@ with gr.Blocks(title="AI Fashion Assistant", theme=gr.themes.Soft()) as demo:
|
|
| 225 |
)
|
| 226 |
|
| 227 |
image_input.upload(
|
| 228 |
-
fn=
|
| 229 |
inputs=[image_input],
|
| 230 |
outputs=output_text
|
| 231 |
)
|
|
|
|
| 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!")
|
| 15 |
|
| 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():
|
|
|
|
| 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
|
| 204 |
analyze_btn.click(
|
| 205 |
+
fn=analyze_clothing,
|
| 206 |
inputs=[image_input],
|
| 207 |
outputs=output_text
|
| 208 |
)
|
|
|
|
| 214 |
)
|
| 215 |
|
| 216 |
image_input.upload(
|
| 217 |
+
fn=analyze_clothing,
|
| 218 |
inputs=[image_input],
|
| 219 |
outputs=output_text
|
| 220 |
)
|