File size: 1,110 Bytes
c8c46cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
from PIL import Image
import torch
from transformers import AutoImageProcessor, ViTForImageClassification
from fastapi import FastAPI, File, UploadFile
from io import BytesIO
import shutil

model_path = "./best_model"

app = FastAPI()

processor = AutoImageProcessor.from_pretrained(
    model_path,
    local_files_only=True,
    use_fast=True
)

model = ViTForImageClassification.from_pretrained(
    model_path,
    local_files_only=True,
    id2label={"0": "real", "1": "fake"},
    label2id={"real": 0, "fake": 1}
)

def predict_image(image: Image.Image):
    inputs = processor(image, return_tensors="pt")
    with torch.no_grad():
        outputs = model(**inputs)
        pred_id = torch.argmax(outputs.logits, dim=1).item()
        pred_label = model.config.id2label[str(pred_id)]
    return pred_label

@app.post("/predict/")
async def upload_file(file: UploadFile = File(...)):
    image_data = await file.read()
    image = Image.open(BytesIO(image_data)).convert("RGB")
    prediction = predict_image(image)
    return {"filename": file.filename, "prediction": prediction}