Spaces:
Sleeping

File size: 7,230 Bytes
9c28f21
 
 
 
 
 
 
 
 
bc933df
9c28f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc933df
9c28f21
 
 
 
 
 
 
 
 
bc933df
 
9c28f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc933df
 
 
 
 
 
 
 
 
 
 
 
9c28f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc933df
 
 
 
 
9c28f21
 
 
 
 
 
 
 
 
 
bc933df
9c28f21
 
bc933df
 
 
 
 
 
 
 
 
 
9c28f21
bc933df
9c28f21
 
 
 
bc933df
9c28f21
 
 
bc933df
9c28f21
 
 
bc933df
9c28f21
 
 
bc933df
 
 
 
 
 
 
 
 
9c28f21
 
bc933df
 
9c28f21
 
bc933df
9c28f21
 
 
 
 
 
bc933df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c28f21
 
 
 
 
bc933df
 
 
9c28f21
 
 
 
 
bc933df
9c28f21
 
 
 
 
bc933df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c28f21
 
 
 
 
 
bc933df
 
 
 
 
 
 
 
 
 
9c28f21
 
 
 
 
bc933df
 
9c28f21
bc933df
9c28f21
 
bc933df
 
 
 
 
 
 
 
 
 
 
 
9c28f21
 
 
 
 
 
 
 
bc933df
9c28f21
 
 
 
bc933df
 
9c28f21
 
bc933df
 
 
 
 
 
9c28f21
 
 
 
 
 
 
 
 
 
bc933df
9c28f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc933df
9c28f21
 
 
 
bc933df
 
 
 
9c28f21
bc933df
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import torch
import torch.nn.functional as F
import timm
import gradio as gr
from PIL import Image
from torchvision import transforms


# -----------------------------
# OCTMNIST class labels
# -----------------------------
CLASS_NAMES = {
    0: "Choroidal Neovascularization",
    1: "Diabetic Macular Edema",
    2: "Drusen",
    3: "Normal"
}


# -----------------------------
# Device
# -----------------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


# -----------------------------
# Image preprocessing
# This should match your notebook preprocessing
# -----------------------------
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.Grayscale(num_output_channels=3),
    transforms.ToTensor(),
])


# -----------------------------
# Load EfficientNetV2-S model
# This must match the architecture used during training
# -----------------------------
model = timm.create_model(
    "efficientnetv2_s",
    pretrained=False,
    num_classes=4
)

state_dict = torch.load("efficient.pth", map_location=device)
model.load_state_dict(state_dict)

model = model.to(device)
model.eval()


# -----------------------------
# Prediction function
# -----------------------------
def predict_oct(image):
    if image is None:
        empty_probs = {
            CLASS_NAMES[i]: 0.0 for i in range(len(CLASS_NAMES))
        }

        message = """
        <div class="result-card">
            <h2>No image uploaded</h2>
            <p>Please upload an OCT image first.</p>
        </div>
        """

        return None, message, empty_probs

    image = image.convert("RGB")

    input_tensor = transform(image).unsqueeze(0).to(device)

    with torch.no_grad():
        outputs = model(input_tensor)
        probs = F.softmax(outputs, dim=1)[0]

    pred_idx = int(torch.argmax(probs).item())
    pred_name = CLASS_NAMES[pred_idx]
    confidence = float(probs[pred_idx].item())

    label_scores = {
        CLASS_NAMES[i]: float(probs[i].item())
        for i in range(len(CLASS_NAMES))
    }

    result_text = f"""
    <div class="result-card">
        <h2>Prediction Result</h2>

        <div class="prediction-main">
            <span class="prediction-label">{pred_name}</span>
        </div>

        <p><b>Predicted Class ID:</b> {pred_idx}</p>
        <p><b>Predicted Class Name:</b> {pred_name}</p>
        <p><b>Confidence:</b> {confidence:.4f}</p>
    </div>
    """

    return image, result_text, label_scores


# -----------------------------
# Description text
# -----------------------------
description = """
### About this demo

Upload a retinal OCT image and the model will classify it into one of the OCTMNIST categories.

**Classes:**

- `0` — Choroidal Neovascularization  
- `1` — Diabetic Macular Edema  
- `2` — Drusen  
- `3` — Normal  

This app uses an EfficientNetV2-S model trained on OCTMNIST.
"""


# -----------------------------
# Custom CSS
# -----------------------------
custom_css = """
body {
    background: linear-gradient(135deg, #f7fbff 0%, #eef5ff 45%, #ffffff 100%);
}

.gradio-container {
    max-width: 1180px !important;
    margin: auto !important;
}

.main-wrapper {
    background: linear-gradient(135deg, #ffffff, #f4f8ff);
    border: 1px solid #dbe8ff;
    border-radius: 28px;
    padding: 32px;
    box-shadow: 0 14px 40px rgba(23, 50, 77, 0.10);
    margin-bottom: 25px;
}

.main-title {
    text-align: center;
    font-size: 44px;
    font-weight: 900;
    color: #17324d;
    margin-bottom: 8px;
    letter-spacing: -0.5px;
}

.subtitle {
    text-align: center;
    font-size: 18px;
    color: #4c6275;
    margin-bottom: 10px;
}

.badge-row {
    text-align: center;
    margin-top: 18px;
}

.badge {
    display: inline-block;
    background: #e9f2ff;
    color: #25527a;
    border: 1px solid #cfe2ff;
    border-radius: 999px;
    padding: 8px 14px;
    font-weight: 600;
    font-size: 14px;
    margin: 4px;
}

.result-card {
    background: linear-gradient(135deg, #ffffff, #f4f8ff);
    border: 1px solid #dbe8ff;
    border-radius: 22px;
    padding: 24px;
    box-shadow: 0 10px 30px rgba(23, 50, 77, 0.10);
}

.result-card h2 {
    color: #17324d;
    margin-top: 0px;
    margin-bottom: 16px;
}

.result-card p {
    font-size: 17px;
    color: #263849;
    margin: 10px 0px;
}

.prediction-main {
    background: linear-gradient(135deg, #e9f2ff, #ffffff);
    border: 1px solid #cfe2ff;
    border-radius: 18px;
    padding: 18px;
    margin-bottom: 18px;
    text-align: center;
}

.prediction-label {
    font-size: 25px;
    font-weight: 900;
    color: #17324d;
}

.footer-note {
    text-align: center;
    color: #68798a;
    font-size: 14px;
    margin-top: 24px;
}

.upload-note {
    background: #f8fbff;
    border-left: 4px solid #7aaef7;
    padding: 14px 16px;
    border-radius: 12px;
    color: #41576b;
    font-size: 15px;
}
"""


# -----------------------------
# Gradio UI
# In Gradio 6, css and theme go inside launch()
# -----------------------------
with gr.Blocks() as demo:

    gr.HTML("""
        <div class="main-wrapper">
            <div class="main-title">OCTMNIST Retinal Disease Classifier</div>
            <div class="subtitle">
                Upload an OCT image and get the predicted disease class using EfficientNetV2-S
            </div>

            <div class="badge-row">
                <span class="badge">EfficientNetV2-S</span>
                <span class="badge">OCTMNIST</span>
                <span class="badge">4-Class Classification</span>
                <span class="badge">PyTorch + Gradio</span>
            </div>
        </div>
    """)

    with gr.Row():
        with gr.Column(scale=1):
            input_image = gr.Image(
                label="Upload OCT Image",
                type="pil",
                height=380
            )

            predict_button = gr.Button(
                "Classify Image",
                variant="primary",
                size="lg"
            )

            gr.HTML("""
                <div class="upload-note">
                    Upload a retinal OCT image. The app will return both the class ID and the medical class name.
                </div>
            """)

            gr.Markdown(description)

        with gr.Column(scale=1):
            output_image = gr.Image(
                label="Input Preview",
                type="pil",
                height=300
            )

            output_text = gr.HTML(
                label="Prediction Result"
            )

            output_label = gr.Label(
                label="Class Probabilities",
                num_top_classes=4
            )

    predict_button.click(
        fn=predict_oct,
        inputs=input_image,
        outputs=[output_image, output_text, output_label]
    )

    gr.HTML("""
        <div class="footer-note">
            This demo is for educational and research purposes only. It should not be used as a clinical diagnostic tool.
        </div>
    """)


# -----------------------------
# Launch app
# For Hugging Face Spaces, do not need share=True
# -----------------------------
if __name__ == "__main__":
    demo.launch(
        theme=gr.themes.Soft(),
        css=custom_css
    )