Mrhuman1 commited on
Commit
ddaacb7
Β·
verified Β·
1 Parent(s): ad42d37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -17
app.py CHANGED
@@ -1,19 +1,20 @@
1
  import streamlit as st
2
 
3
- # ⚑️ Page config must be FIRST
4
  st.set_page_config(
5
  page_title="Chest X-ray Disease Classifier",
6
  page_icon="🩺",
7
  layout="centered"
8
  )
9
 
10
- # Imports
11
  import torch
12
  import torch.nn as nn
13
  import torchvision.transforms as transforms
14
  from efficientnet_pytorch import EfficientNet
15
  from PIL import Image
16
  from datetime import datetime
 
 
17
 
18
  # --- Define HardSwish activation ---
19
  class HardSwish(nn.Module):
@@ -46,10 +47,10 @@ class_names = [
46
  'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'
47
  ]
48
 
49
- # --- Device configuration ---
50
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
51
 
52
- # --- Load model ---
53
  @st.cache_resource
54
  def load_model():
55
  model = CustomEfficientNet(num_classes=14)
@@ -64,14 +65,14 @@ def load_model():
64
 
65
  model = load_model()
66
 
67
- # --- Transformations ---
68
  transform = transforms.Compose([
69
  transforms.Resize((300, 300)),
70
  transforms.ToTensor(),
71
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
72
  ])
73
 
74
- # --- Prediction function ---
75
  def predict(image):
76
  if image.mode != 'RGB':
77
  image = image.convert('RGB')
@@ -87,25 +88,60 @@ def predict(image):
87
 
88
  return top5
89
 
90
- # --- Streamlit UI ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  st.markdown(
92
  """
93
  <h1 style="text-align: center;">🩺 Chest X-ray Disease Classifier</h1>
94
- <p style="text-align: center;">Upload a chest X-ray image to get disease predictions.<br>Top 5 diseases shown with probability scores.</p>
95
  """,
96
  unsafe_allow_html=True
97
  )
98
 
99
- st.write("") # small space
100
-
101
  with st.form("prediction_form"):
102
- patient_name = st.text_input("πŸ‘€ Patient Name", placeholder="Enter patient's full name...")
103
  scan_date = st.date_input("πŸ“… Scan Date", value=datetime.today())
104
  uploaded_file = st.file_uploader("πŸ“€ Upload Chest X-ray Image", type=["png", "jpg", "jpeg", "bmp", "tiff"])
105
 
106
  submit_button = st.form_submit_button("πŸ” Analyze X-ray")
107
 
108
- # Handle submission
109
  if submit_button:
110
  if not uploaded_file:
111
  st.error("⚠️ Please upload a chest X-ray image.")
@@ -119,19 +155,38 @@ if submit_button:
119
 
120
  st.success('βœ… Analysis Completed!')
121
 
122
- # --- Show results ---
123
  st.markdown("---")
124
  st.subheader("πŸ“‹ Patient Information")
125
  st.write(f"**Name:** {patient_name}")
126
  st.write(f"**Scan Date:** {scan_date.strftime('%Y-%m-%d')}")
127
 
 
128
  st.markdown("---")
129
- st.subheader("πŸ§ͺ Top 5 Predicted Diseases")
130
 
 
 
 
131
  for disease, prob in top5_predictions.items():
132
- st.progress(prob) # show progress bar
133
  st.write(f"πŸ”Ή **{disease}** β€” {prob*100:.2f}%")
134
 
135
  st.markdown("---")
136
- st.subheader("πŸ–ΌοΈ Uploaded X-ray Image")
137
- st.image(image, use_column_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
 
3
+ # Page Config - must be first
4
  st.set_page_config(
5
  page_title="Chest X-ray Disease Classifier",
6
  page_icon="🩺",
7
  layout="centered"
8
  )
9
 
 
10
  import torch
11
  import torch.nn as nn
12
  import torchvision.transforms as transforms
13
  from efficientnet_pytorch import EfficientNet
14
  from PIL import Image
15
  from datetime import datetime
16
+ from io import BytesIO
17
+ from fpdf import FPDF # For PDF generation
18
 
19
  # --- Define HardSwish activation ---
20
  class HardSwish(nn.Module):
 
47
  'Pleural Effusion', 'Pleural Other', 'Fracture', 'Support Devices'
48
  ]
49
 
50
+ # Device configuration
51
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
52
 
53
+ # Load model
54
  @st.cache_resource
55
  def load_model():
56
  model = CustomEfficientNet(num_classes=14)
 
65
 
66
  model = load_model()
67
 
68
+ # Image transforms
69
  transform = transforms.Compose([
70
  transforms.Resize((300, 300)),
71
  transforms.ToTensor(),
72
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
73
  ])
74
 
75
+ # Predict function
76
  def predict(image):
77
  if image.mode != 'RGB':
78
  image = image.convert('RGB')
 
88
 
89
  return top5
90
 
91
+ # PDF generator
92
+ def generate_pdf(name, date, image, comment):
93
+ pdf = FPDF()
94
+ pdf.add_page()
95
+
96
+ # Title
97
+ pdf.set_font("Arial", 'B', 20)
98
+ pdf.cell(0, 10, "Chest X-ray AI Report", ln=True, align="C")
99
+ pdf.ln(10)
100
+
101
+ # Patient Info
102
+ pdf.set_font("Arial", '', 12)
103
+ pdf.cell(0, 10, f"Patient Name: {name}", ln=True)
104
+ pdf.cell(0, 10, f"Scan Date: {date.strftime('%Y-%m-%d')}", ln=True)
105
+ pdf.ln(10)
106
+
107
+ # X-ray image
108
+ image_buffer = BytesIO()
109
+ image.save(image_buffer, format='JPEG')
110
+ image_buffer.seek(0)
111
+
112
+ # Save to temp file because fpdf only accepts filename
113
+ with open("temp_xray.jpg", "wb") as f:
114
+ f.write(image_buffer.read())
115
+
116
+ pdf.image("temp_xray.jpg", x=30, w=150) # resize image
117
+ pdf.ln(10)
118
+
119
+ # AI Comment
120
+ pdf.set_font("Arial", 'B', 14)
121
+ pdf.cell(0, 10, "AI Analysis:", ln=True)
122
+ pdf.set_font("Arial", '', 12)
123
+ pdf.multi_cell(0, 10, comment)
124
+
125
+ return pdf.output(dest='S').encode('latin1')
126
+
127
+ # ----------------- Streamlit App -------------------
128
+
129
  st.markdown(
130
  """
131
  <h1 style="text-align: center;">🩺 Chest X-ray Disease Classifier</h1>
132
+ <p style="text-align: center;">Upload a chest X-ray image to get disease predictions and AI report.</p>
133
  """,
134
  unsafe_allow_html=True
135
  )
136
 
 
 
137
  with st.form("prediction_form"):
138
+ patient_name = st.text_input("πŸ‘€ Patient Name", placeholder="Enter full name...")
139
  scan_date = st.date_input("πŸ“… Scan Date", value=datetime.today())
140
  uploaded_file = st.file_uploader("πŸ“€ Upload Chest X-ray Image", type=["png", "jpg", "jpeg", "bmp", "tiff"])
141
 
142
  submit_button = st.form_submit_button("πŸ” Analyze X-ray")
143
 
144
+ # Process the form
145
  if submit_button:
146
  if not uploaded_file:
147
  st.error("⚠️ Please upload a chest X-ray image.")
 
155
 
156
  st.success('βœ… Analysis Completed!')
157
 
158
+ # Display Info
159
  st.markdown("---")
160
  st.subheader("πŸ“‹ Patient Information")
161
  st.write(f"**Name:** {patient_name}")
162
  st.write(f"**Scan Date:** {scan_date.strftime('%Y-%m-%d')}")
163
 
164
+ # Display Predictions
165
  st.markdown("---")
166
+ st.subheader("πŸ§ͺ Top 5 Predictions")
167
 
168
+ most_likely_disease = list(top5_predictions.items())[0]
169
+ ai_comment = f"The most likely disease is **{most_likely_disease[0]}** with a probability of **{most_likely_disease[1]*100:.2f}%**."
170
+
171
  for disease, prob in top5_predictions.items():
172
+ st.progress(prob)
173
  st.write(f"πŸ”Ή **{disease}** β€” {prob*100:.2f}%")
174
 
175
  st.markdown("---")
176
+ st.subheader("πŸ–ΌοΈ Uploaded X-ray Image (Resized)")
177
+ width, height = image.size
178
+ resized_image = image.resize((width//2, height//2))
179
+ st.image(resized_image, caption="Uploaded Chest X-ray", use_column_width=False)
180
+
181
+ st.markdown("---")
182
+ st.subheader("πŸ’¬ AI Comment")
183
+ st.info(ai_comment)
184
+
185
+ # Generate PDF
186
+ pdf_bytes = generate_pdf(patient_name, scan_date, resized_image, ai_comment)
187
+ st.download_button(
188
+ label="πŸ“„ Download PDF Report",
189
+ data=pdf_bytes,
190
+ file_name=f"{patient_name.replace(' ', '_')}_Xray_Report.pdf",
191
+ mime="application/pdf"
192
+ )