Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,15 +11,7 @@ import requests
|
|
| 11 |
from io import BytesIO
|
| 12 |
from transformers import CLIPProcessor, CLIPModel
|
| 13 |
|
| 14 |
-
|
| 15 |
-
HF_TOKEN = os.getenv("HF_API_TOKEN")
|
| 16 |
-
|
| 17 |
-
if not HF_TOKEN:
|
| 18 |
-
print("❌ Token non trouvé! Vérifiez les variables d'environnement")
|
| 19 |
-
else:
|
| 20 |
-
print("✅ Token chargé avec succès")
|
| 21 |
-
|
| 22 |
-
app = FastAPI(title="API TESTEFASHION MODLI")
|
| 23 |
|
| 24 |
# Middleware CORS
|
| 25 |
app.add_middleware(
|
|
@@ -39,7 +31,7 @@ processor = None
|
|
| 39 |
def load_model():
|
| 40 |
global model, processor
|
| 41 |
try:
|
| 42 |
-
model_name = "patrickjohncyh/fashion-clip"
|
| 43 |
model = CLIPModel.from_pretrained(model_name)
|
| 44 |
processor = CLIPProcessor.from_pretrained(model_name)
|
| 45 |
print("✅ Modèle chargé avec succès!")
|
|
@@ -91,28 +83,28 @@ async def classify_fashion(image_data: dict):
|
|
| 91 |
raise HTTPException(status_code=400, detail="imageUrl is required")
|
| 92 |
|
| 93 |
# Télécharger l'image depuis l'URL
|
| 94 |
-
response = requests.get(image_url, timeout=
|
| 95 |
response.raise_for_status()
|
| 96 |
|
| 97 |
# Ouvrir et préparer l'image
|
| 98 |
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 99 |
-
image.thumbnail((512, 512))
|
| 100 |
|
| 101 |
# Préparer toutes les catégories en anglais
|
| 102 |
all_english_categories = []
|
| 103 |
-
category_mapping = {}
|
| 104 |
|
| 105 |
for fr_cat, en_categories in CATEGORIES_FR.items():
|
| 106 |
all_english_categories.extend(en_categories)
|
| 107 |
for en_cat in en_categories:
|
| 108 |
category_mapping[en_cat] = fr_cat
|
| 109 |
|
| 110 |
-
# Traitement
|
| 111 |
inputs = processor(
|
| 112 |
text=all_english_categories,
|
| 113 |
images=image,
|
| 114 |
return_tensors="pt",
|
| 115 |
-
padding=True,
|
| 116 |
truncation=True,
|
| 117 |
max_length=77,
|
| 118 |
return_overflowing_tokens=False
|
|
@@ -127,7 +119,6 @@ async def classify_fashion(image_data: dict):
|
|
| 127 |
logits_per_image = outputs.logits_per_image
|
| 128 |
probs = logits_per_image.softmax(dim=1)
|
| 129 |
|
| 130 |
-
# Convertir en dictionnaire de résultats
|
| 131 |
results = {cat: prob.item() for cat, prob in zip(all_english_categories, probs[0])}
|
| 132 |
|
| 133 |
# Trouver la catégorie avec le meilleur score
|
|
@@ -137,7 +128,6 @@ async def classify_fashion(image_data: dict):
|
|
| 137 |
# Convertir en catégorie française
|
| 138 |
best_french_category = category_mapping.get(best_english_category, "autre")
|
| 139 |
|
| 140 |
-
# Format de réponse exact pour Lovable
|
| 141 |
return {
|
| 142 |
"success": True,
|
| 143 |
"category": best_french_category,
|
|
@@ -151,15 +141,7 @@ async def classify_fashion(image_data: dict):
|
|
| 151 |
raise HTTPException(status_code=400, detail=f"Invalid image URL: {str(e)}")
|
| 152 |
except Exception as e:
|
| 153 |
raise HTTPException(status_code=500, detail=f"Classification error: {str(e)}")
|
| 154 |
-
|
| 155 |
-
# Ancienne route pour compatibilité (si nécessaire)
|
| 156 |
-
@app.post("/analyze")
|
| 157 |
-
async def analyze_image_old():
|
| 158 |
-
return {"error": "Use /classify endpoint instead"}
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
"""Endpoint de test avec une image exemple"""
|
| 164 |
-
test_url = "https://images.unsplash.com/photo-1521572163474-6864f9cf17ab?w=400"
|
| 165 |
-
return await classify_fashion({"imageUrl": test_url})
|
|
|
|
| 11 |
from io import BytesIO
|
| 12 |
from transformers import CLIPProcessor, CLIPModel
|
| 13 |
|
| 14 |
+
app = FastAPI(title="Fashion Classification API")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# Middleware CORS
|
| 17 |
app.add_middleware(
|
|
|
|
| 31 |
def load_model():
|
| 32 |
global model, processor
|
| 33 |
try:
|
| 34 |
+
model_name = "patrickjohncyh/fashion-clip"
|
| 35 |
model = CLIPModel.from_pretrained(model_name)
|
| 36 |
processor = CLIPProcessor.from_pretrained(model_name)
|
| 37 |
print("✅ Modèle chargé avec succès!")
|
|
|
|
| 83 |
raise HTTPException(status_code=400, detail="imageUrl is required")
|
| 84 |
|
| 85 |
# Télécharger l'image depuis l'URL
|
| 86 |
+
response = requests.get(image_url, timeout=30)
|
| 87 |
response.raise_for_status()
|
| 88 |
|
| 89 |
# Ouvrir et préparer l'image
|
| 90 |
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 91 |
+
image.thumbnail((512, 512))
|
| 92 |
|
| 93 |
# Préparer toutes les catégories en anglais
|
| 94 |
all_english_categories = []
|
| 95 |
+
category_mapping = {}
|
| 96 |
|
| 97 |
for fr_cat, en_categories in CATEGORIES_FR.items():
|
| 98 |
all_english_categories.extend(en_categories)
|
| 99 |
for en_cat in en_categories:
|
| 100 |
category_mapping[en_cat] = fr_cat
|
| 101 |
|
| 102 |
+
# Traitement avec padding pour éviter l'erreur tensor
|
| 103 |
inputs = processor(
|
| 104 |
text=all_english_categories,
|
| 105 |
images=image,
|
| 106 |
return_tensors="pt",
|
| 107 |
+
padding=True, # ← CORRECTION IMPORTANTE
|
| 108 |
truncation=True,
|
| 109 |
max_length=77,
|
| 110 |
return_overflowing_tokens=False
|
|
|
|
| 119 |
logits_per_image = outputs.logits_per_image
|
| 120 |
probs = logits_per_image.softmax(dim=1)
|
| 121 |
|
|
|
|
| 122 |
results = {cat: prob.item() for cat, prob in zip(all_english_categories, probs[0])}
|
| 123 |
|
| 124 |
# Trouver la catégorie avec le meilleur score
|
|
|
|
| 128 |
# Convertir en catégorie française
|
| 129 |
best_french_category = category_mapping.get(best_english_category, "autre")
|
| 130 |
|
|
|
|
| 131 |
return {
|
| 132 |
"success": True,
|
| 133 |
"category": best_french_category,
|
|
|
|
| 141 |
raise HTTPException(status_code=400, detail=f"Invalid image URL: {str(e)}")
|
| 142 |
except Exception as e:
|
| 143 |
raise HTTPException(status_code=500, detail=f"Classification error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
import uvicorn
|
| 147 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|