Update app.py
Browse files
app.py
CHANGED
|
@@ -5,18 +5,31 @@ from PIL import Image
|
|
| 5 |
import io
|
| 6 |
import base64
|
| 7 |
import json
|
|
|
|
| 8 |
|
| 9 |
class FashionClassifier:
|
| 10 |
def __init__(self):
|
| 11 |
self.api_url = "https://api.marqo.ai/classify"
|
| 12 |
self.api_key = os.getenv("MARQO_API_KEY")
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def classify_image(self, image, max_categories=5, confidence_threshold=0.3):
|
| 15 |
-
"""Classifie une image
|
| 16 |
try:
|
| 17 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
buffered = io.BytesIO()
|
| 19 |
-
image.save(buffered, format="JPEG")
|
| 20 |
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 21 |
|
| 22 |
headers = {
|
|
@@ -33,113 +46,137 @@ class FashionClassifier:
|
|
| 33 |
}
|
| 34 |
}
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return response.json()
|
| 38 |
|
| 39 |
except Exception as e:
|
| 40 |
-
return {"error": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
# Initialiser le classifieur
|
| 43 |
classifier = FashionClassifier()
|
| 44 |
|
| 45 |
def process_image(image, max_categories, confidence):
|
| 46 |
-
"""Fonction de traitement
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
if "error" in result:
|
| 53 |
-
return f"❌ Erreur: {result['error']}"
|
| 54 |
-
|
| 55 |
-
if "predictions" in result and result["predictions"]:
|
| 56 |
-
output = "## 🎯 Résultats de classification:\n\n"
|
| 57 |
-
for i, pred in enumerate(result["predictions"]):
|
| 58 |
-
output += f"{i+1}. **{pred['label']}** - {pred['score']*100:.1f}%\n"
|
| 59 |
|
| 60 |
-
|
| 61 |
-
output += f"\n⏱️ Temps de traitement: {result['processing_time']}s"
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
# Interface Gradio
|
| 68 |
with gr.Blocks(title="Classificateur de Mode") as demo:
|
| 69 |
gr.Markdown("""
|
| 70 |
# 🎨 Classificateur de Vêtements Marqo
|
| 71 |
-
Uploader une image de vêtement pour la classifier automatiquement
|
| 72 |
""")
|
| 73 |
|
| 74 |
with gr.Row():
|
| 75 |
with gr.Column(scale=1):
|
| 76 |
-
#
|
| 77 |
image_input = gr.Image(
|
| 78 |
type="pil",
|
| 79 |
-
label="
|
| 80 |
-
height=300
|
|
|
|
| 81 |
)
|
| 82 |
|
| 83 |
-
# Paramètres
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
minimum=1,
|
| 87 |
-
maximum=10,
|
| 88 |
-
value=5,
|
| 89 |
-
step=1,
|
| 90 |
-
label="Nombre de catégories max"
|
| 91 |
-
)
|
| 92 |
-
confidence = gr.Slider(
|
| 93 |
-
minimum=0.1,
|
| 94 |
-
maximum=1.0,
|
| 95 |
-
value=0.3,
|
| 96 |
-
step=0.1,
|
| 97 |
-
label="Seuil de confiance minimum"
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
# Bouton bien visible
|
| 101 |
-
submit_btn = gr.Button(
|
| 102 |
-
"🚀 Classifier l'image",
|
| 103 |
-
variant="primary",
|
| 104 |
-
size="lg"
|
| 105 |
-
)
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
with gr.Column(scale=2):
|
| 108 |
-
# Résultats
|
| 109 |
output_text = gr.Markdown(
|
| 110 |
-
|
| 111 |
-
value="⬅️ Uploader une image et cliquez sur 'Classifier'"
|
| 112 |
)
|
| 113 |
|
| 114 |
-
# Exemples d'images
|
| 115 |
gr.Examples(
|
| 116 |
examples=[
|
| 117 |
-
["https://
|
| 118 |
-
["https://images.unsplash.com/photo-
|
| 119 |
-
["https://images.unsplash.com/photo-
|
| 120 |
],
|
| 121 |
inputs=image_input,
|
| 122 |
-
label="
|
| 123 |
)
|
| 124 |
|
| 125 |
-
#
|
| 126 |
submit_btn.click(
|
| 127 |
fn=process_image,
|
| 128 |
inputs=[image_input, max_categories, confidence],
|
| 129 |
outputs=output_text
|
| 130 |
)
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
outputs=output_text
|
| 137 |
)
|
| 138 |
|
| 139 |
-
# Lancer
|
| 140 |
if __name__ == "__main__":
|
| 141 |
-
demo.launch(
|
| 142 |
-
share=True,
|
| 143 |
-
server_name="0.0.0.0",
|
| 144 |
-
debug=True
|
| 145 |
-
)
|
|
|
|
| 5 |
import io
|
| 6 |
import base64
|
| 7 |
import json
|
| 8 |
+
import tempfile
|
| 9 |
|
| 10 |
class FashionClassifier:
|
| 11 |
def __init__(self):
|
| 12 |
self.api_url = "https://api.marqo.ai/classify"
|
| 13 |
self.api_key = os.getenv("MARQO_API_KEY")
|
| 14 |
+
|
| 15 |
+
# Vérifier si la clé API est configurée
|
| 16 |
+
if not self.api_key or self.api_key == "your_marqo_api_key":
|
| 17 |
+
print("⚠️ ATTENTION: Clé API Marqo non configurée!")
|
| 18 |
+
print("👉 Ajoutez MARQO_API_KEY dans les secrets Hugging Face")
|
| 19 |
+
|
| 20 |
def classify_image(self, image, max_categories=5, confidence_threshold=0.3):
|
| 21 |
+
"""Classifie une image avec gestion d'erreurs complète"""
|
| 22 |
try:
|
| 23 |
+
# Vérifier si l'image est valide
|
| 24 |
+
if image is None:
|
| 25 |
+
return {"error": "Aucune image fournie"}
|
| 26 |
+
|
| 27 |
+
# Convertir et optimiser l'image
|
| 28 |
+
image = self.prepare_image(image)
|
| 29 |
+
|
| 30 |
+
# Convertir en base64
|
| 31 |
buffered = io.BytesIO()
|
| 32 |
+
image.save(buffered, format="JPEG", optimize=True, quality=85)
|
| 33 |
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 34 |
|
| 35 |
headers = {
|
|
|
|
| 46 |
}
|
| 47 |
}
|
| 48 |
|
| 49 |
+
# Debug: Afficher la requête (dans les logs)
|
| 50 |
+
print(f"📤 Envoi requête à Marqo API...")
|
| 51 |
+
|
| 52 |
+
response = requests.post(self.api_url, headers=headers, json=payload, timeout=30)
|
| 53 |
+
|
| 54 |
+
# Debug: Afficher la réponse
|
| 55 |
+
print(f"📥 Réponse reçue: {response.status_code}")
|
| 56 |
+
|
| 57 |
+
if response.status_code != 200:
|
| 58 |
+
return {
|
| 59 |
+
"error": f"Erreur API {response.status_code}",
|
| 60 |
+
"details": response.text
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
return response.json()
|
| 64 |
|
| 65 |
except Exception as e:
|
| 66 |
+
return {"error": f"Erreur: {str(e)}"}
|
| 67 |
+
|
| 68 |
+
def prepare_image(self, image):
|
| 69 |
+
"""Prépare l'image pour le modèle"""
|
| 70 |
+
# Convertir en RGB si nécessaire
|
| 71 |
+
if image.mode != 'RGB':
|
| 72 |
+
image = image.convert('RGB')
|
| 73 |
+
|
| 74 |
+
# Redimensionner si trop grande (max 1024px)
|
| 75 |
+
max_size = (1024, 1024)
|
| 76 |
+
image.thumbnail(max_size, Image.Resampling.LANCZOS)
|
| 77 |
+
|
| 78 |
+
return image
|
| 79 |
|
| 80 |
# Initialiser le classifieur
|
| 81 |
classifier = FashionClassifier()
|
| 82 |
|
| 83 |
def process_image(image, max_categories, confidence):
|
| 84 |
+
"""Fonction de traitement avec debug"""
|
| 85 |
+
try:
|
| 86 |
+
if image is None:
|
| 87 |
+
return "❌ Veuillez uploader une image valide"
|
| 88 |
+
|
| 89 |
+
print(f"🖼️ Image reçue: {image.size}, mode: {image.mode}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
result = classifier.classify_image(image, max_categories, confidence)
|
|
|
|
| 92 |
|
| 93 |
+
# Debug dans les logs
|
| 94 |
+
print(f"🔍 Résultat brut: {json.dumps(result, indent=2)}")
|
| 95 |
+
|
| 96 |
+
if "error" in result:
|
| 97 |
+
error_msg = f"❌ Erreur de classification:\n\n"
|
| 98 |
+
error_msg += f"**Détails:** {result['error']}\n\n"
|
| 99 |
+
|
| 100 |
+
# Conseils selon le type d'erreur
|
| 101 |
+
if "401" in str(result['error']):
|
| 102 |
+
error_msg += "🔑 **Solution:** Vérifiez votre clé API Marqo dans les secrets Hugging Face"
|
| 103 |
+
elif "timeout" in str(result['error']).lower():
|
| 104 |
+
error_msg += "⏱️ **Solution:** L'image est trop lourde, essayez une image plus petite"
|
| 105 |
+
else:
|
| 106 |
+
error_msg += "💡 **Solution:** Essayez une image plus petite ou un format différent"
|
| 107 |
+
|
| 108 |
+
return error_msg
|
| 109 |
+
|
| 110 |
+
if "predictions" in result and result["predictions"]:
|
| 111 |
+
output = "## 🎯 Résultats de classification:\n\n"
|
| 112 |
+
for i, pred in enumerate(result["predictions"]):
|
| 113 |
+
output += f"{i+1}. **{pred['label']}** - {pred['score']*100:.1f}%\n"
|
| 114 |
+
|
| 115 |
+
if "processing_time" in result:
|
| 116 |
+
output += f"\n���️ Temps de traitement: {result['processing_time']}s"
|
| 117 |
+
|
| 118 |
+
return output
|
| 119 |
+
else:
|
| 120 |
+
return "❌ Aucune prédiction trouvé - Le modèle n'a pas reconnu l'image"
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"❌ Erreur inattendue: {str(e)}"
|
| 124 |
|
| 125 |
+
# Interface Gradio simplifiée et robuste
|
| 126 |
with gr.Blocks(title="Classificateur de Mode") as demo:
|
| 127 |
gr.Markdown("""
|
| 128 |
# 🎨 Classificateur de Vêtements Marqo
|
| 129 |
+
**Uploader une image de vêtement** pour la classifier automatiquement
|
| 130 |
""")
|
| 131 |
|
| 132 |
with gr.Row():
|
| 133 |
with gr.Column(scale=1):
|
| 134 |
+
gr.Markdown("### 📤 Uploader votre image")
|
| 135 |
image_input = gr.Image(
|
| 136 |
type="pil",
|
| 137 |
+
label="Image à classifier",
|
| 138 |
+
height=300,
|
| 139 |
+
sources=["upload", "webcam", "clipboard"]
|
| 140 |
)
|
| 141 |
|
| 142 |
+
gr.Markdown("### ⚙️ Paramètres")
|
| 143 |
+
max_categories = gr.Slider(1, 10, value=5, label="Catégories max")
|
| 144 |
+
confidence = gr.Slider(0.1, 1.0, value=0.3, label="Seuil de confiance")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
+
gr.Markdown("### 🚀 Actions")
|
| 147 |
+
submit_btn = gr.Button("Classifier l'image", variant="primary")
|
| 148 |
+
clear_btn = gr.Button("Effacer", variant="secondary")
|
| 149 |
+
|
| 150 |
with gr.Column(scale=2):
|
| 151 |
+
gr.Markdown("### 📊 Résultats")
|
| 152 |
output_text = gr.Markdown(
|
| 153 |
+
value="⬅️ Uploader une image de vêtement pour commencer"
|
|
|
|
| 154 |
)
|
| 155 |
|
| 156 |
+
# Exemples d'images qui FONCTIONNENT
|
| 157 |
gr.Examples(
|
| 158 |
examples=[
|
| 159 |
+
["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png"],
|
| 160 |
+
["https://images.unsplash.com/photo-1558769132-cb1aea458c5e"],
|
| 161 |
+
["https://images.unsplash.com/photo-1543163521-1bf539c55dd2"]
|
| 162 |
],
|
| 163 |
inputs=image_input,
|
| 164 |
+
label="🖼️ Exemples testés et fonctionnels"
|
| 165 |
)
|
| 166 |
|
| 167 |
+
# Événements
|
| 168 |
submit_btn.click(
|
| 169 |
fn=process_image,
|
| 170 |
inputs=[image_input, max_categories, confidence],
|
| 171 |
outputs=output_text
|
| 172 |
)
|
| 173 |
|
| 174 |
+
clear_btn.click(
|
| 175 |
+
fn=lambda: (None, 5, 0.3, "⬅️ Uploader une nouvelle image"),
|
| 176 |
+
inputs=[],
|
| 177 |
+
outputs=[image_input, max_categories, confidence, output_text]
|
|
|
|
| 178 |
)
|
| 179 |
|
| 180 |
+
# Lancer avec debug
|
| 181 |
if __name__ == "__main__":
|
| 182 |
+
demo.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|