Mrhuman1 commited on
Commit
895f9d4
ยท
verified ยท
1 Parent(s): 9379452

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -0
app.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import torch.nn as nn
4
+ import torchvision.transforms as transforms
5
+ from efficientnet_pytorch import EfficientNet
6
+ from PIL import Image
7
+ from datetime import datetime
8
+
9
+ # Define HardSwish activation
10
+ class HardSwish(nn.Module):
11
+ def __init__(self):
12
+ super(HardSwish, self).__init__()
13
+
14
+ def forward(self, x):
15
+ return x * (torch.clamp(x + 3, 0, 6) / 6)
16
+
17
+ # Define custom EfficientNet model
18
+ class CustomEfficientNet(nn.Module):
19
+ def __init__(self, num_classes):
20
+ super(CustomEfficientNet, self).__init__()
21
+ self.model = EfficientNet.from_name('efficientnet-b3')
22
+ num_ftrs = self.model._fc.in_features
23
+ self.model._fc = nn.Sequential(
24
+ nn.Linear(num_ftrs, 512),
25
+ HardSwish(),
26
+ nn.Dropout(p=0.4),
27
+ nn.Linear(512, num_classes)
28
+ )
29
+
30
+ def forward(self, x):
31
+ return self.model(x)
32
+
33
+ # Class names
34
+ class_names = [
35
+ 'No Finding', 'Enlarged Cardiomediastinum', 'Cardiomegaly', 'Lung Opacity',
36
+ 'Lung Lesion', 'Edema', 'Consolidation', 'Pneumonia', 'Atelectasis', 'Pneumothorax',
37
+ 'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'
38
+ ]
39
+
40
+ # Device configuration
41
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
42
+
43
+ # Load model
44
+ @st.cache_resource
45
+ def load_model():
46
+ model = CustomEfficientNet(num_classes=14)
47
+ checkpoint = torch.load('Final_global_model.pth.tar', map_location=device)
48
+ if 'state_dict' in checkpoint:
49
+ model.load_state_dict(checkpoint['state_dict'])
50
+ else:
51
+ model.load_state_dict(checkpoint)
52
+ model = model.to(device)
53
+ model.eval()
54
+ return model
55
+
56
+ model = load_model()
57
+
58
+ # Transformations
59
+ transform = transforms.Compose([
60
+ transforms.Resize((300, 300)),
61
+ transforms.ToTensor(),
62
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
63
+ ])
64
+
65
+ # Prediction function
66
+ def predict(image):
67
+ if image.mode != 'RGB':
68
+ image = image.convert('RGB')
69
+ img = transform(image).unsqueeze(0).to(device)
70
+
71
+ with torch.no_grad():
72
+ outputs = model(img)
73
+ probs = torch.sigmoid(outputs).cpu().numpy()[0]
74
+
75
+ results = {class_names[i]: float(probs[i]) for i in range(len(class_names))}
76
+ sorted_results = dict(sorted(results.items(), key=lambda item: item[1], reverse=True))
77
+ top5 = {k: f"{v*100:.2f}%" for k, v in list(sorted_results.items())[:5]}
78
+
79
+ return top5
80
+
81
+ # ---------------- Streamlit App -----------------
82
+
83
+ st.set_page_config(page_title="Chest X-ray Disease Classifier", page_icon="๐Ÿฉบ", layout="centered")
84
+
85
+ st.markdown(
86
+ """
87
+ <h1 style="text-align:center;">๐Ÿฉบ Chest X-ray Disease Classifier</h1>
88
+ <p style="text-align:center;">Upload a chest X-ray image to get disease predictions.</p>
89
+ """,
90
+ unsafe_allow_html=True
91
+ )
92
+
93
+ # Input form
94
+ with st.form("input_form"):
95
+ patient_name = st.text_input("Patient Name", placeholder="Enter full name...")
96
+ scan_date = st.date_input("Scan Date", value=datetime.today())
97
+ uploaded_file = st.file_uploader("Upload Chest X-ray Image", type=["png", "jpg", "jpeg", "bmp", "tiff"])
98
+ submitted = st.form_submit_button("๐Ÿ” Predict")
99
+
100
+ if submitted:
101
+ if uploaded_file is not None and patient_name:
102
+ image = Image.open(uploaded_file)
103
+
104
+ with st.spinner('Analyzing the X-ray...'):
105
+ top5_predictions = predict(image)
106
+
107
+ st.success('โœ… Prediction completed!')
108
+
109
+ st.markdown("---")
110
+ st.markdown(f"**๐Ÿ“‹ Patient Name:** {patient_name}")
111
+ st.markdown(f"**๐Ÿ“… Scan Date:** {scan_date.strftime('%Y-%m-%d')}")
112
+ st.markdown("### ๐Ÿงช Top 5 Predictions:")
113
+ for disease, probability in top5_predictions.items():
114
+ st.write(f"๐Ÿ”น **{disease}**: {probability}")
115
+
116
+ st.image(image, caption="Uploaded Chest X-ray", use_column_width=True)
117
+ else:
118
+ st.error("โš ๏ธ Please fill all fields and upload an image.")