Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,10 +14,18 @@ model_name = "prithivMLmods/Gender-Classifier-Mini"
|
|
| 14 |
model = SiglipForImageClassification.from_pretrained(model_name)
|
| 15 |
processor = AutoImageProcessor.from_pretrained(model_name)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
@app.post("/classify/")
|
| 18 |
async def classify_gender(image: UploadFile = File(...)):
|
| 19 |
contents = await image.read()
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
inputs = processor(images=img, return_tensors="pt")
|
| 22 |
|
| 23 |
with torch.no_grad():
|
|
@@ -25,7 +33,12 @@ async def classify_gender(image: UploadFile = File(...)):
|
|
| 25 |
logits = outputs.logits
|
| 26 |
probs = F.softmax(logits, dim=1).squeeze().tolist()
|
| 27 |
|
| 28 |
-
labels =
|
| 29 |
-
predictions = {labels[
|
|
|
|
| 30 |
|
| 31 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
model = SiglipForImageClassification.from_pretrained(model_name)
|
| 15 |
processor = AutoImageProcessor.from_pretrained(model_name)
|
| 16 |
|
| 17 |
+
@app.get("/")
|
| 18 |
+
async def root():
|
| 19 |
+
return {"message": "Gender classifier API is running. Use POST /classify/ with an image file."}
|
| 20 |
+
|
| 21 |
@app.post("/classify/")
|
| 22 |
async def classify_gender(image: UploadFile = File(...)):
|
| 23 |
contents = await image.read()
|
| 24 |
+
try:
|
| 25 |
+
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 26 |
+
except Exception:
|
| 27 |
+
return {"error": "Invalid image file"}
|
| 28 |
+
|
| 29 |
inputs = processor(images=img, return_tensors="pt")
|
| 30 |
|
| 31 |
with torch.no_grad():
|
|
|
|
| 33 |
logits = outputs.logits
|
| 34 |
probs = F.softmax(logits, dim=1).squeeze().tolist()
|
| 35 |
|
| 36 |
+
labels = ["Female ♀", "Male ♂"]
|
| 37 |
+
predictions = {labels[i]: round(probs[i], 3) for i in range(len(probs))}
|
| 38 |
+
max_idx = probs.index(max(probs))
|
| 39 |
|
| 40 |
+
return {
|
| 41 |
+
"predictions": predictions,
|
| 42 |
+
"most_likely": labels[max_idx],
|
| 43 |
+
"confidence": round(probs[max_idx], 3)
|
| 44 |
+
}
|