File size: 1,344 Bytes
2a18073
0017a72
96d1185
ccd3d82
0017a72
ccd3d82
 
0017a72
ccd3d82
 
 
 
0017a72
 
 
ccd3d82
c5561b1
 
 
 
ccd3d82
 
 
c5561b1
 
 
 
 
ccd3d82
 
 
0017a72
 
 
 
c5561b1
 
 
ccd3d82
c5561b1
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
import os
os.environ["HF_HOME"] = "/tmp/huggingface"

from fastapi import FastAPI, UploadFile, File
from transformers import SiglipForImageClassification, AutoImageProcessor
from PIL import Image
import torch
import torch.nn.functional as F
import io

app = FastAPI()

model_name = "prithivMLmods/Gender-Classifier-Mini"
model = SiglipForImageClassification.from_pretrained(model_name)
processor = AutoImageProcessor.from_pretrained(model_name)

@app.get("/")
async def root():
    return {"message": "Gender classifier API is running. Use POST /classify/ with an image file."}

@app.post("/classify/")
async def classify_gender(image: UploadFile = File(...)):
    contents = await image.read()
    try:
        img = Image.open(io.BytesIO(contents)).convert("RGB")
    except Exception:
        return {"error": "Invalid image file"}

    inputs = processor(images=img, return_tensors="pt")

    with torch.no_grad():
        outputs = model(**inputs)
        logits = outputs.logits
        probs = F.softmax(logits, dim=1).squeeze().tolist()

    labels = ["Female ♀", "Male ♂"]
    predictions = {labels[i]: round(probs[i], 3) for i in range(len(probs))}
    max_idx = probs.index(max(probs))

    return {
        "predictions": predictions,
        "most_likely": labels[max_idx],
        "confidence": round(probs[max_idx], 3)
    }