VaneshDev commited on
Commit
8d06626
·
verified ·
1 Parent(s): 29b04e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -24
app.py CHANGED
@@ -6,11 +6,11 @@ import fitz # PyMuPDF
6
  import logging
7
  import os
8
 
9
- # Logging setup
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
- # List of possible conditions
14
  conditions = [
15
  "Normal", "Pneumonia", "Cancer", "TB", "Other",
16
  "Coronary Artery Disease", "Aortic Aneurysm", "Stroke", "Peripheral Artery Disease",
@@ -20,7 +20,7 @@ conditions = [
20
  "Appendicitis", "Gallstones", "Kidney Stones", "Infections", "Abdominal Aortic Aneurysm", "Diverticulitis"
21
  ]
22
 
23
- # Details for each condition
24
  condition_details = {
25
  "Normal": {"description": "No abnormal signs detected.", "recommendation": "Routine check-ups recommended."},
26
  "Pneumonia": {"description": "Lung inflammation detected, possibly infectious.", "recommendation": "Seek medical attention for treatment."},
@@ -49,7 +49,7 @@ condition_details = {
49
  "Diverticulitis": {"description": "Inflammation of diverticula in the colon.", "recommendation": "Gastroenterology consultation."}
50
  }
51
 
52
- # Load and configure the model
53
  try:
54
  model = models.densenet121(weights="IMAGENET1K_V1")
55
  except AttributeError:
@@ -57,22 +57,21 @@ except AttributeError:
57
 
58
  model.classifier = torch.nn.Linear(model.classifier.in_features, len(conditions))
59
  model.eval()
60
-
61
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
62
  model.to(device)
63
 
64
- # Load trained weights if available
65
  model_path = os.getenv("MODEL_PATH", "xray_model.pth")
66
  if os.path.exists(model_path):
67
  try:
68
  model.load_state_dict(torch.load(model_path, map_location=device))
69
- logger.info("Loaded custom model weights.")
70
  except Exception as e:
71
  logger.warning(f"Failed to load model weights: {e}")
72
  else:
73
- logger.info("No model weights found. Using random weights.")
74
 
75
- # Preprocess uploaded image
76
  def preprocess_image(image):
77
  transform = transforms.Compose([
78
  transforms.Resize((224, 224)),
@@ -81,7 +80,7 @@ def preprocess_image(image):
81
  ])
82
  return transform(image).unsqueeze(0).to(device)
83
 
84
- # Predict X-ray condition
85
  def predict_xray(image):
86
  try:
87
  if image is None:
@@ -90,12 +89,23 @@ def predict_xray(image):
90
  img_tensor = preprocess_image(image)
91
  with torch.no_grad():
92
  output = model(img_tensor)
 
93
  probs = torch.nn.functional.softmax(output, dim=1)[0]
94
  results = {conditions[i]: probs[i].item() * 100 for i in range(len(conditions))}
95
 
96
  top_condition = max(results, key=results.get)
97
  confidence = results[top_condition]
98
 
 
 
 
 
 
 
 
 
 
 
99
  info = condition_details.get(top_condition, condition_details["Other"])
100
  return f"""
101
  <div style="font-family:Arial">
@@ -105,20 +115,21 @@ def predict_xray(image):
105
  <p><b>Recommendation:</b> {info['recommendation']}</p>
106
  </div>
107
  """
 
108
  except Exception as e:
109
- return f"Prediction failed: {str(e)}"
 
110
 
111
- # Analyze PDF medical report
112
  def analyze_report(file):
113
  if not file or not file.name.endswith(".pdf"):
114
- return "Please upload a valid PDF report."
115
-
116
  try:
117
  doc = fitz.open(file.name)
118
  text = "".join(page.get_text() for page in doc)
119
  doc.close()
120
 
121
- condition, disease, status = "Unclear", "Unknown", "Pending evaluation"
122
 
123
  if "stroke" in text.lower():
124
  condition, disease, status = "Stroke", "Brain Disorder", "Urgent Care Needed"
@@ -127,30 +138,30 @@ def analyze_report(file):
127
  elif "fracture" in text.lower():
128
  condition, disease, status = "Fracture", "Bone Injury", "Orthopedic Attention Required"
129
 
130
- return f"Condition: {condition}\nDisease: {disease}\nStatus: {status}\n\nPreview:\n{text[:300]}..."
 
131
 
132
  except Exception as e:
133
- return f"Failed to analyze PDF: {str(e)}"
134
 
135
  # Gradio interface
136
  def create_interface():
137
  with gr.Blocks() as demo:
138
- gr.Markdown("<h1 style='text-align:center;'>🩻 RadiologyScan AI</h1><p style='text-align:center;'>AI-powered X-ray and PDF report analysis</p>")
139
 
140
  with gr.Tabs():
141
  with gr.TabItem("X-ray Analysis"):
142
- xray_input = gr.Image(label="Upload Chest X-ray", type="pil")
143
- xray_output = gr.HTML()
144
- gr.Button("Analyze X-ray").click(predict_xray, inputs=xray_input, outputs=xray_output)
145
 
146
  with gr.TabItem("Report Analysis"):
147
- pdf_input = gr.File(label="Upload Medical Report (PDF)", file_types=[".pdf"])
148
- pdf_output = gr.Textbox(label="Report Summary", lines=10)
149
  gr.Button("Analyze Report").click(analyze_report, inputs=pdf_input, outputs=pdf_output)
150
 
151
  return demo
152
 
153
- # Launch app
154
  if __name__ == "__main__":
155
  demo = create_interface()
156
  demo.launch(server_port=7860, ssr_mode=False)
 
6
  import logging
7
  import os
8
 
9
+ # Setup logging
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # Condition list
14
  conditions = [
15
  "Normal", "Pneumonia", "Cancer", "TB", "Other",
16
  "Coronary Artery Disease", "Aortic Aneurysm", "Stroke", "Peripheral Artery Disease",
 
20
  "Appendicitis", "Gallstones", "Kidney Stones", "Infections", "Abdominal Aortic Aneurysm", "Diverticulitis"
21
  ]
22
 
23
+ # Condition details
24
  condition_details = {
25
  "Normal": {"description": "No abnormal signs detected.", "recommendation": "Routine check-ups recommended."},
26
  "Pneumonia": {"description": "Lung inflammation detected, possibly infectious.", "recommendation": "Seek medical attention for treatment."},
 
49
  "Diverticulitis": {"description": "Inflammation of diverticula in the colon.", "recommendation": "Gastroenterology consultation."}
50
  }
51
 
52
+ # Load model
53
  try:
54
  model = models.densenet121(weights="IMAGENET1K_V1")
55
  except AttributeError:
 
57
 
58
  model.classifier = torch.nn.Linear(model.classifier.in_features, len(conditions))
59
  model.eval()
 
60
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
61
  model.to(device)
62
 
63
+ # Load model weights if available
64
  model_path = os.getenv("MODEL_PATH", "xray_model.pth")
65
  if os.path.exists(model_path):
66
  try:
67
  model.load_state_dict(torch.load(model_path, map_location=device))
68
+ logger.info("Model loaded from file.")
69
  except Exception as e:
70
  logger.warning(f"Failed to load model weights: {e}")
71
  else:
72
+ logger.info("No custom model weights found.")
73
 
74
+ # Image preprocessing
75
  def preprocess_image(image):
76
  transform = transforms.Compose([
77
  transforms.Resize((224, 224)),
 
80
  ])
81
  return transform(image).unsqueeze(0).to(device)
82
 
83
+ # X-ray prediction function with confidence threshold
84
  def predict_xray(image):
85
  try:
86
  if image is None:
 
89
  img_tensor = preprocess_image(image)
90
  with torch.no_grad():
91
  output = model(img_tensor)
92
+
93
  probs = torch.nn.functional.softmax(output, dim=1)[0]
94
  results = {conditions[i]: probs[i].item() * 100 for i in range(len(conditions))}
95
 
96
  top_condition = max(results, key=results.get)
97
  confidence = results[top_condition]
98
 
99
+ if confidence < 50:
100
+ return f"""
101
+ <div style="font-family:Arial">
102
+ <h3>Prediction: <span style="color:#D62828;">Uncertain</span></h3>
103
+ <p><b>Confidence:</b> {confidence:.2f}%</p>
104
+ <p><b>Note:</b> The model is not confident enough to provide a clear diagnosis.</p>
105
+ <p><b>Recommendation:</b> Please consult a radiologist or upload a better-quality image.</p>
106
+ </div>
107
+ """
108
+
109
  info = condition_details.get(top_condition, condition_details["Other"])
110
  return f"""
111
  <div style="font-family:Arial">
 
115
  <p><b>Recommendation:</b> {info['recommendation']}</p>
116
  </div>
117
  """
118
+
119
  except Exception as e:
120
+ logger.error(f"Error in prediction: {e}")
121
+ return f"Error: {str(e)}"
122
 
123
+ # Analyze PDF report
124
  def analyze_report(file):
125
  if not file or not file.name.endswith(".pdf"):
126
+ return "Please upload a valid PDF file."
 
127
  try:
128
  doc = fitz.open(file.name)
129
  text = "".join(page.get_text() for page in doc)
130
  doc.close()
131
 
132
+ condition, disease, status = "Unclear", "Unknown", "Pending"
133
 
134
  if "stroke" in text.lower():
135
  condition, disease, status = "Stroke", "Brain Disorder", "Urgent Care Needed"
 
138
  elif "fracture" in text.lower():
139
  condition, disease, status = "Fracture", "Bone Injury", "Orthopedic Attention Required"
140
 
141
+ preview = text[:300] + "..." if text else "No readable content."
142
+ return f"Condition: {condition}\nDisease: {disease}\nStatus: {status}\n\nPreview:\n{preview}"
143
 
144
  except Exception as e:
145
+ return f"Failed to process PDF: {str(e)}"
146
 
147
  # Gradio interface
148
  def create_interface():
149
  with gr.Blocks() as demo:
150
+ gr.Markdown("<h1 style='text-align:center;'>🩻 RadiologyScan AI</h1><p style='text-align:center;'>AI-powered X-ray and Report Analysis</p>")
151
 
152
  with gr.Tabs():
153
  with gr.TabItem("X-ray Analysis"):
154
+ img_input = gr.Image(label="Upload Chest X-ray", type="pil")
155
+ img_output = gr.HTML()
156
+ gr.Button("Analyze X-ray").click(predict_xray, inputs=img_input, outputs=img_output)
157
 
158
  with gr.TabItem("Report Analysis"):
159
+ pdf_input = gr.File(label="Upload PDF Report", file_types=[".pdf"])
160
+ pdf_output = gr.Textbox(label="Extracted Summary", lines=10)
161
  gr.Button("Analyze Report").click(analyze_report, inputs=pdf_input, outputs=pdf_output)
162
 
163
  return demo
164
 
 
165
  if __name__ == "__main__":
166
  demo = create_interface()
167
  demo.launch(server_port=7860, ssr_mode=False)