Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
import torch
|
4 |
+
from torchvision import transforms
|
5 |
+
from PIL import Image
|
6 |
+
import io
|
7 |
+
|
8 |
+
# FastAPI uygulamasını başlat
|
9 |
+
app = FastAPI()
|
10 |
+
|
11 |
+
# Cihaz ayarı
|
12 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
+
|
14 |
+
# Eğitilmiş modeli yükleme
|
15 |
+
model = torch.load("best_model.pth", map_location=device)
|
16 |
+
model.eval()
|
17 |
+
|
18 |
+
# Görüntü dönüşüm pipeline'ı
|
19 |
+
transform = transforms.Compose([
|
20 |
+
transforms.Resize((224, 224)), # Modelle uyumlu olacak şekilde yeniden boyutlandır
|
21 |
+
transforms.ToTensor(), # Tensor'a çevir
|
22 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # Normalize et
|
23 |
+
])
|
24 |
+
|
25 |
+
# Tahmin fonksiyonu
|
26 |
+
def predict(image: Image.Image):
|
27 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
28 |
+
with torch.no_grad():
|
29 |
+
output = model(input_tensor).item() # Tahmini al
|
30 |
+
prediction = "Positive" if output > 0.5 else "Negative"
|
31 |
+
return {"Prediction": prediction, "Probability": round(output, 2)}
|
32 |
+
|
33 |
+
# Ana API rotası
|
34 |
+
@app.post("/predict")
|
35 |
+
async def predict_image(file: UploadFile = File(...)):
|
36 |
+
try:
|
37 |
+
# Görüntüyü oku
|
38 |
+
image_data = await file.read()
|
39 |
+
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
40 |
+
|
41 |
+
# Tahmin yap
|
42 |
+
result = predict(image)
|
43 |
+
return JSONResponse(content=result)
|
44 |
+
except Exception as e:
|
45 |
+
return JSONResponse(content={"error": str(e)}, status_code=400)
|
46 |
+
|
47 |
+
# Ana sayfa
|
48 |
+
@app.get("/")
|
49 |
+
def home():
|
50 |
+
return {"message": "Upload an image to /predict for classification."}
|