Spaces:
Runtime error
Runtime error
File size: 1,475 Bytes
e297dff |
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 |
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
from PIL import Image as PILImage
from transformers import AutoImageProcessor, SiglipForImageClassification
import torch
import io
import warnings
MODEL_IDENTIFIER = "Ateeqq/ai-vs-human-image-detector"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Suppress warnings
warnings.filterwarnings("ignore", message="Possibly corrupt EXIF data.")
# Load processor and model once
processor = AutoImageProcessor.from_pretrained(MODEL_IDENTIFIER)
model = SiglipForImageClassification.from_pretrained(MODEL_IDENTIFIER).to(DEVICE)
model.eval()
# FastAPI app
app = FastAPI()
@app.get("/")
def root():
return {"message": "AI vs Human image detector is running."}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
try:
image_bytes = await file.read()
image = PILImage.open(io.BytesIO(image_bytes)).convert("RGB")
inputs = processor(images=image, return_tensors="pt").to(DEVICE)
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=-1)[0]
results = {
model.config.id2label[i]: round(prob.item(), 4)
for i, prob in enumerate(probs)
}
return JSONResponse(content={"prediction": results})
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500) |