Spaces:
Sleeping

File size: 4,486 Bytes
59ca7d1
8ac0238
 
2143bab
 
 
 
8ac0238
 
 
2143bab
 
 
593df32
2143bab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ac0238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2143bab
 
8434c36
 
 
 
 
 
2143bab
8434c36
2143bab
 
 
8434c36
 
 
8ac0238
8434c36
 
2143bab
8434c36
2143bab
 
 
8434c36
 
 
2143bab
 
8ac0238
 
 
 
 
2143bab
8ac0238
2143bab
 
 
 
 
 
 
8ac0238
2143bab
 
 
8ac0238
2143bab
 
8ac0238
 
2143bab
8ac0238
 
 
2143bab
 
 
 
 
 
 
8ac0238
2143bab
8ac0238
 
 
2143bab
8ac0238
 
 
 
 
 
2143bab
 
8ac0238
 
 
 
2143bab
8ac0238
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import io
import numpy as np
import torch
import torch.nn as nn
import torchvision.models as models
import cv2
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

# Model configuration
CLASS_NAMES = ['No_DR', 'Mild', 'Moderate', 'Severe', 'Proliferative_DR']
IMAGE_SIZE = 512
DEVICE = 'cpu'  # Hugging Face Spaces use CPU

# Model architecture (must match training)
class MobileNet_V3_Large(nn.Module):
    def __init__(self, num_classes=5):
        super(MobileNet_V3_Large, self).__init__()
        self.model = models.mobilenet_v3_large(weights=None)
        self.model.classifier[-1] = nn.Linear(
            self.model.classifier[-1].in_features, 
            num_classes, 
            bias=True
        )
    
    def forward(self, x):
        return self.model(x)

# Setup FastAPI App
app = FastAPI(title="DR Detection API", version="1.0.0")

# Enable CORS for the frontend to call this endpoint
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)

# Global model variable
model = None

@app.on_event("startup")
async def load_model():
    """Load the trained model once at startup."""
    global model
    model_path = "best_val_loss.pt"
    print(f"Loading model from: {model_path}")
    model = MobileNet_V3_Large(num_classes=5)
    model.load_state_dict(torch.load(model_path, map_location=DEVICE, weights_only=False))
    model.to(DEVICE)
    model.eval()
    print(f"Model loaded on {DEVICE}")

def remove_black_borders(img, black_th=5):
    img_t = img.copy()
    img_t = cv2.cvtColor(img_t, cv2.COLOR_RGB2GRAY)

    # x axis
    centre_y = img_t.shape[1] // 2
    black_list = img_t[:, centre_y]
    black_list = np.where(black_list >= black_th)[0]

    if len(black_list) > 1:
        first_non_black = black_list[0]
        reverse_first_non_black = black_list[-1] + 1
        img = img[first_non_black:, :, :]
        img = img[:reverse_first_non_black - first_non_black, :, :]

    # y axis
    centre_x = img_t.shape[0] // 2
    black_list = img_t[centre_x, :]
    black_list = np.where(black_list >= black_th)[0]

    if len(black_list) > 1:
        first_non_black_y = black_list[0]
        reverse_first_non_black_y = black_list[-1] + 1
        img = img[:, first_non_black_y:, :]
        img = img[:, :reverse_first_non_black_y - first_non_black_y, :]

    return img

def preprocess_image(image_bytes: bytes) -> np.ndarray:
    nparr = np.frombuffer(image_bytes, np.uint8)
    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image = remove_black_borders(image)

    height, width, _ = image.shape
    if height > width:
        pad = (height - width) // 2
        image = cv2.copyMakeBorder(image, 0, 0, pad, pad, cv2.BORDER_CONSTANT)
    elif width > height:
        pad = (width - height) // 2
        image = cv2.copyMakeBorder(image, pad, pad, 0, 0, cv2.BORDER_CONSTANT)

    image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
    image = image / 255.0
    image = np.transpose(image, (2, 0, 1))

    return image

@app.post("/api/predict")
async def predict(file: UploadFile = File(...)):
    try:
        contents = await file.read()
        image = preprocess_image(contents)
        tensor = torch.tensor(image, dtype=torch.float32).unsqueeze(0).to(DEVICE)
        
        with torch.no_grad():
            output = model(tensor)
            probabilities = torch.softmax(output, dim=1).cpu().numpy()[0]
        
        predicted_class = int(np.argmax(probabilities))
        predicted_label = CLASS_NAMES[predicted_class]
        confidence = float(probabilities[predicted_class])
        
        class_probs = {}
        for i, name in enumerate(CLASS_NAMES):
            class_probs[name] = round(float(probabilities[i]), 4)
        
        return JSONResponse({
            "success": True,
            "prediction": predicted_label,
            "confidence": round(confidence, 4),
            "class_probabilities": class_probs
        })
        
    except Exception as e:
        return JSONResponse(
            {"success": False, "error": str(e)},
            status_code=500
        )

@app.get("/")
def read_root():
    return {"message": "Welcome to the DR Predictor API. Please use POST /api/predict with an image file."}