Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from PIL import Image as PILImage
|
| 4 |
+
from transformers import AutoImageProcessor, SiglipForImageClassification
|
| 5 |
+
import torch
|
| 6 |
+
import io
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
MODEL_IDENTIFIER = "Ateeqq/ai-vs-human-image-detector"
|
| 10 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
+
|
| 12 |
+
# Suppress warnings
|
| 13 |
+
warnings.filterwarnings("ignore", message="Possibly corrupt EXIF data.")
|
| 14 |
+
|
| 15 |
+
# Load processor and model once
|
| 16 |
+
processor = AutoImageProcessor.from_pretrained(MODEL_IDENTIFIER)
|
| 17 |
+
model = SiglipForImageClassification.from_pretrained(MODEL_IDENTIFIER).to(DEVICE)
|
| 18 |
+
model.eval()
|
| 19 |
+
|
| 20 |
+
# FastAPI app
|
| 21 |
+
app = FastAPI()
|
| 22 |
+
|
| 23 |
+
@app.get("/")
|
| 24 |
+
def root():
|
| 25 |
+
return {"message": "AI vs Human image detector is running."}
|
| 26 |
+
|
| 27 |
+
@app.post("/predict")
|
| 28 |
+
async def predict(file: UploadFile = File(...)):
|
| 29 |
+
try:
|
| 30 |
+
image_bytes = await file.read()
|
| 31 |
+
image = PILImage.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 32 |
+
|
| 33 |
+
inputs = processor(images=image, return_tensors="pt").to(DEVICE)
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
outputs = model(**inputs)
|
| 36 |
+
probs = torch.softmax(outputs.logits, dim=-1)[0]
|
| 37 |
+
results = {
|
| 38 |
+
model.config.id2label[i]: round(prob.item(), 4)
|
| 39 |
+
for i, prob in enumerate(probs)
|
| 40 |
+
}
|
| 41 |
+
return JSONResponse(content={"prediction": results})
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return JSONResponse(content={"error": str(e)}, status_code=500)
|