File size: 2,407 Bytes
2a18073
0017a72
96d1185
ccd3d82
0017a72
ccd3d82
 
0017a72
ccd3d82
23dd76e
ccd3d82
 
 
0017a72
 
 
ccd3d82
c5561b1
 
 
 
ccd3d82
 
 
c5561b1
 
 
 
 
ccd3d82
 
 
0017a72
 
 
 
c5561b1
 
 
ccd3d82
c5561b1
 
 
 
 
23dd76e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
from typing import List

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)
    }




@app.post("/classify_batch/")
async def classify_gender_batch(images: List[UploadFile] = File(...)):
    pil_images = []
    for image in images:
        contents = await image.read()
        try:
            img = Image.open(io.BytesIO(contents)).convert("RGB")
            pil_images.append(img)
        except Exception:
            return {"error": f"Invalid image file: {image.filename}"}

    # Batch process
    inputs = processor(images=pil_images, return_tensors="pt")

    with torch.no_grad():
        outputs = model(**inputs)
        logits = outputs.logits
        probs = F.softmax(logits, dim=1).tolist()  # shape: [batch_size, 2]

    labels = ["Female ♀", "Male β™‚"]

    results = []
    for p in probs:
        predictions = {labels[i]: round(p[i], 3) for i in range(len(p))}
        max_idx = p.index(max(p))
        results.append({
            "predictions": predictions,
            "most_likely": labels[max_idx],
            "confidence": round(p[max_idx], 3)
        })

    return {"results": results}