-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
47 lines (33 loc) · 1.51 KB
/
app.py
File metadata and controls
47 lines (33 loc) · 1.51 KB
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
from fastapi import FastAPI, File, UploadFile, HTTPException
from PIL import Image
import io
import torch
from transformers import AutoImageProcessor, AutoModelForImageClassification
app = FastAPI(title="image-moderation-api")
print("Loading Hugging Face model into RAM...")
model_name = "prithivMLmods/Nsfw_Image_Detection_OSS"
processor = AutoImageProcessor.from_pretrained(model_name)
model = AutoModelForImageClassification.from_pretrained(model_name)
model.eval()
print("Model loaded and ready!")
LABELS = {0: "SFW", 1: "NSFW"}
@app.post("/classify")
async def classify_image(file: UploadFile = File(...)):
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File provided is not an image.")
try:
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
probs = torch.nn.functional.softmax(logits, dim=1).squeeze().tolist()
results = [{"label": LABELS[i], "score": round(probs[i], 4)} for i in range(len(probs))]
results.sort(key=lambda x: x["score"], reverse=True)
return {
"filename": file.filename,
"predictions": results
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")