Spaces:
Sleeping
Sleeping
Added app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Directory Structure Suggestion:
|
2 |
+
# diabetic_retinopathy_app/
|
3 |
+
# βββ Home.py (Landing Page)
|
4 |
+
# βββ pages/
|
5 |
+
# β βββ 1_Upload_and_Predict.py
|
6 |
+
# β βββ 2_Model_Evaluation.py
|
7 |
+
# βββ assets/
|
8 |
+
# βββ banner.jpg
|
9 |
+
|
10 |
+
# Home.py (Landing Page)
|
11 |
+
import streamlit as st
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
def main():
|
15 |
+
st.set_page_config(page_title="DR Assistive Tool", layout="centered")
|
16 |
+
st.title("Welcome to the Diabetic Retinopathy Assistive Tool")
|
17 |
+
|
18 |
+
st.markdown("""
|
19 |
+
### π Your AI-powered assistant for early detection of Diabetic Retinopathy.
|
20 |
+
|
21 |
+
#### Features:
|
22 |
+
- πΌοΈ Upload a retinal image and receive a prediction of its DR stage.
|
23 |
+
- π Evaluate model performance using real test datasets.
|
24 |
+
|
25 |
+
Select a page from the left sidebar to get started.
|
26 |
+
""")
|
27 |
+
|
28 |
+
# image = Image.open("assets/banner.jpg") # Optional banner image
|
29 |
+
# st.image(image, use_column_width=True)
|
30 |
+
|
31 |
+
if __name__ == '__main__':
|
32 |
+
main()
|
33 |
+
|
34 |
+
|
35 |
+
# pages/1_Upload_and_Predict.py
|
36 |
+
import streamlit as st
|
37 |
+
import torch
|
38 |
+
from torchvision import transforms, models
|
39 |
+
from PIL import Image
|
40 |
+
import numpy as np
|
41 |
+
|
42 |
+
st.title("π· Upload & Predict Diabetic Retinopathy")
|
43 |
+
|
44 |
+
class_names = ['No DR', 'Mild', 'Moderate', 'Severe', 'Proliferative DR']
|
45 |
+
|
46 |
+
def load_model():
|
47 |
+
model = models.densenet121(pretrained=False)
|
48 |
+
num_ftrs = model.classifier.in_features
|
49 |
+
model.classifier = torch.nn.Linear(num_ftrs, len(class_names))
|
50 |
+
model.load_state_dict(torch.load("training/Pretrained_Densenet-121.pth", map_location='cpu'))
|
51 |
+
model.eval()
|
52 |
+
return model
|
53 |
+
|
54 |
+
transform = transforms.Compose([
|
55 |
+
transforms.Resize(256),
|
56 |
+
transforms.CenterCrop(224),
|
57 |
+
transforms.ToTensor(),
|
58 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
59 |
+
])
|
60 |
+
|
61 |
+
def predict_image(model, image):
|
62 |
+
img_tensor = transform(image).unsqueeze(0)
|
63 |
+
with torch.no_grad():
|
64 |
+
outputs = model(img_tensor)
|
65 |
+
_, pred = torch.max(outputs, 1)
|
66 |
+
prob = torch.nn.functional.softmax(outputs, dim=1)[0][pred].item() * 100
|
67 |
+
return class_names[pred.item()], prob
|
68 |
+
|
69 |
+
uploaded_file = st.file_uploader("Choose a retinal image", type=["jpg", "png"])
|
70 |
+
if uploaded_file is not None:
|
71 |
+
image = Image.open(uploaded_file).convert('RGB')
|
72 |
+
st.image(image, caption='Uploaded Retinal Image', use_column_width=True)
|
73 |
+
|
74 |
+
if st.button("π§ Predict"):
|
75 |
+
with st.spinner('Analyzing image...'):
|
76 |
+
model = load_model()
|
77 |
+
pred_class, prob = predict_image(model, image)
|
78 |
+
st.success(f"Prediction: **{pred_class}** ({prob:.2f}% confidence)")
|
79 |
+
|
80 |
+
|
81 |
+
# pages/2_Model_Evaluation.py
|
82 |
+
import streamlit as st
|
83 |
+
import torch
|
84 |
+
from torch.utils.data import DataLoader
|
85 |
+
from torchvision import datasets, transforms, models
|
86 |
+
import torch.nn as nn
|
87 |
+
from tqdm import tqdm
|
88 |
+
|
89 |
+
st.title("π Model Evaluation on Test Dataset")
|
90 |
+
|
91 |
+
@st.cache_data
|
92 |
+
|
93 |
+
def load_test_data():
|
94 |
+
transform = transforms.Compose([
|
95 |
+
transforms.Resize(256),
|
96 |
+
transforms.CenterCrop(224),
|
97 |
+
transforms.ToTensor(),
|
98 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
99 |
+
])
|
100 |
+
test_data = datasets.ImageFolder("test_dataset_path", transform=transform)
|
101 |
+
return DataLoader(test_data, batch_size=32, shuffle=False)
|
102 |
+
|
103 |
+
def evaluate(model, loader):
|
104 |
+
model.eval()
|
105 |
+
correct, total, loss = 0, 0, 0.0
|
106 |
+
criterion = nn.CrossEntropyLoss()
|
107 |
+
with torch.no_grad():
|
108 |
+
for inputs, labels in loader:
|
109 |
+
outputs = model(inputs)
|
110 |
+
loss += criterion(outputs, labels).item()
|
111 |
+
_, pred = torch.max(outputs, 1)
|
112 |
+
correct += (pred == labels).sum().item()
|
113 |
+
total += labels.size(0)
|
114 |
+
return loss / len(loader), correct / total * 100
|
115 |
+
|
116 |
+
if st.button("π§ͺ Evaluate Trained Model"):
|
117 |
+
test_loader = load_test_data()
|
118 |
+
model = models.densenet121(pretrained=False)
|
119 |
+
model.classifier = nn.Linear(model.classifier.in_features, 5)
|
120 |
+
model.load_state_dict(torch.load("dr_densenet121.pth", map_location='cpu'))
|
121 |
+
model.eval()
|
122 |
+
|
123 |
+
loss, acc = evaluate(model, test_loader)
|
124 |
+
st.write(f"**Test Loss:** {loss:.4f}")
|
125 |
+
st.write(f"**Test Accuracy:** {acc:.2f}%")
|