Rihan1729 commited on
Commit
f0a0ef0
·
verified ·
1 Parent(s): 0734ffe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -78
app.py CHANGED
@@ -4,118 +4,108 @@ from PIL import Image, ImageDraw, ImageFont
4
  import torch
5
  import numpy as np
6
 
7
- # --- Model Setup (Unchanged) ---
8
  model_name = "Hemgg/brain-tumor-classification"
9
  processor = AutoImageProcessor.from_pretrained(model_name)
10
  model = AutoModelForImageClassification.from_pretrained(model_name)
11
  class_names = ["🧠 Glioma", "🎯 Meningioma", "✅ No Tumor", "⚡ Pituitary"]
12
 
13
- # --- Custom CSS for Advanced Look ---
14
  custom_css = """
15
- body, .gradio-container {
16
- background-color: #0b0f19 !important;
17
- color: #ffffff !important;
18
- }
19
- .md, .md p, .md h1, .md h2, .md h3 {
20
- color: white !important;
21
- }
22
- #custom-card {
23
- background: rgba(255, 255, 255, 0.05);
24
- border-radius: 15px;
25
  padding: 20px;
26
- border: 1px solid rgba(255, 255, 255, 0.1);
27
  }
28
  .gr-button-primary {
29
- background: linear-gradient(90deg, #2563eb, #7c3aed) !important;
30
  border: none !important;
 
31
  }
 
32
  footer {display: none !important;}
33
  """
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def classify_tumor(image):
36
  if image is None:
37
- return "Please upload a brain MRI", None
38
 
39
  inputs = processor(images=image, return_tensors="pt")
40
  with torch.no_grad():
41
  outputs = model(**inputs)
42
  probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
43
- pred_idx = probs.argmax(-1).item()
44
- confidence = probs[0][pred_idx].item()
45
- tumor_type = class_names[pred_idx]
 
46
 
47
- overlay_img = create_overlay(image, pred_idx, confidence)
48
 
49
- # Advanced Result Formatting
50
- result = f"""
51
- <div style="background: rgba(255,255,255,0.1); padding: 20px; border-radius: 10px; border-left: 5px solid #3b82f6;">
52
- <h2 style="margin:0; color: white;">Analysis: {tumor_type}</h2>
53
- <h3 style="margin:5px 0; color: #93c5fd;">Confidence Score: {confidence:.1%}</h3>
54
- <hr style="opacity: 0.2; margin: 15px 0;">
55
- <p style="color: #cbd5e1;"><b>Probability Distribution:</b></p>
56
- {"".join([f"<div style='margin-bottom:5px;'>{class_names[i]}: <span style='float:right;'>{probs[0][i]:.1%}</span></div>" for i in range(4)])}
 
 
 
 
 
 
 
57
  </div>
58
  """
59
- return result, overlay_img
60
 
61
- def create_overlay(image, tumor_class, confidence):
62
  overlay = image.copy().convert("RGBA")
63
  draw = ImageDraw.Draw(overlay)
64
- w, h = overlay.size
65
-
66
- if tumor_class != 2:
67
- radius = min(w, h) // 4
68
  cx, cy = w // 2, h // 2
69
- alpha = int(140 * confidence)
70
- draw.ellipse([cx-radius, cy-radius, cx+radius, cy+radius],
71
- fill=(255, 0, 0, alpha), outline=(255, 255, 0, 255), width=4)
72
-
73
- try:
74
- font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 24)
75
- except:
76
- font = ImageFont.load_default()
77
-
78
- label = f"REGION OF INTEREST: {class_names[tumor_class]}"
79
- draw.text((20, 20), label, fill=(255, 255, 255), font=font)
80
-
81
  return overlay.convert("RGB")
82
 
83
- # --- Interface ---
84
- with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
 
85
  with gr.Row():
86
- gr.HTML("""
87
- <div style="text-align: center; padding: 20px;">
88
- <h1 style="color: white; font-size: 2.5rem; margin-bottom: 0;">NEURO-SCAN AI</h1>
89
- <p style="color: #94a3b8; font-size: 1.1rem;">Advanced Deep Learning Diagnostic Support System</p>
90
- </div>
91
- """)
92
-
93
- with gr.Tabs():
94
- with gr.TabItem("🔍 Diagnostic Scanner"):
95
- with gr.Row():
96
- with gr.Column(scale=1):
97
- input_img = gr.Image(label="Input MRI Scan", type="pil", height=400)
98
- btn = gr.Button("START NEURAL ANALYSIS", variant="primary")
99
-
100
- with gr.Column(scale=1):
101
- output_html = gr.HTML(label="Diagnostic Report")
102
- overlay_img = gr.Image(label="Visualization Overlay", height=400)
103
-
104
- with gr.TabItem("📖 Tumor Information"):
105
- gr.Markdown("""
106
- ### **Predefined Tumor Classification Reference**
107
 
108
- | Tumor Type | Description | Characteristic |
109
- | :--- | :--- | :--- |
110
- | **Glioma** | Tumors that start in the glial cells of the brain or spine. | Most common primary brain tumor. |
111
- | **Meningioma** | A tumor that arises from the meninges (membranes covering the brain). | Usually slow-growing and benign. |
112
- | **Pituitary** | Abnormal growths that develop in the pituitary gland. | Can affect hormone levels and vision. |
113
- | **No Tumor** | Normal brain tissue detected. | No significant mass effect or abnormal growth seen. |
114
 
115
- > **Disclaimer:** This AI is for educational and research purposes only. Always consult a certified radiologist for medical diagnosis.
116
- """)
117
-
118
- btn.click(classify_tumor, input_img, [output_html, overlay_img])
119
 
120
  if __name__ == "__main__":
121
  demo.launch()
 
4
  import torch
5
  import numpy as np
6
 
 
7
  model_name = "Hemgg/brain-tumor-classification"
8
  processor = AutoImageProcessor.from_pretrained(model_name)
9
  model = AutoModelForImageClassification.from_pretrained(model_name)
10
  class_names = ["🧠 Glioma", "🎯 Meningioma", "✅ No Tumor", "⚡ Pituitary"]
11
 
 
12
  custom_css = """
13
+ .gradio-container {background-color: #050505 !important; color: #ffffff !important;}
14
+ .md, .md p, .md h1, .md h2, .md h3, span, label {color: #ffffff !important;}
15
+ #result-box {
16
+ background-color: #1a1a1a !important;
17
+ border: 2px solid #3b82f6 !important;
18
+ border-radius: 12px;
 
 
 
 
19
  padding: 20px;
20
+ color: #ffffff !important;
21
  }
22
  .gr-button-primary {
23
+ background: linear-gradient(135deg, #1e40af, #7e22ce) !important;
24
  border: none !important;
25
+ font-weight: bold !important;
26
  }
27
+ #result-text * { color: #ffffff !important; }
28
  footer {display: none !important;}
29
  """
30
 
31
+ def get_medical_info(tumor_type):
32
+ info = {
33
+ "🧠 Glioma": {
34
+ "desc": "Gliomas originate in the glial cells that support neurons. They can be fast-growing and may involve surrounding brain tissue.",
35
+ "next": "Urgent consultation with a neuro-oncologist. An MRI with contrast or a biopsy is typically the next diagnostic step."
36
+ },
37
+ "🎯 Meningioma": {
38
+ "desc": "These tumors arise from the meninges, the layers covering the brain. Most are slow-growing and benign but can cause pressure.",
39
+ "next": "Consult a neurosurgeon to evaluate the mass effect. Treatment ranges from 'watchful waiting' to surgical resection."
40
+ },
41
+ "⚡ Pituitary": {
42
+ "desc": "Pituitary adenomas occur in the master gland at the base of the brain. They often affect hormone regulation and vision.",
43
+ "next": "An endocrine workup (blood tests) and a visual field test are recommended to assess hormonal and optic nerve impact."
44
+ },
45
+ "✅ No Tumor": {
46
+ "desc": "The neural network did not detect significant signs of the three primary tumor types in this scan.",
47
+ "next": "If symptoms (headaches, seizures, vision loss) persist, please consult a neurologist for a comprehensive evaluation."
48
+ }
49
+ }
50
+ return info.get(tumor_type, {"desc": "", "next": ""})
51
+
52
  def classify_tumor(image):
53
  if image is None:
54
+ return "<p style='color:white;'>Please upload a scan.</p>", None
55
 
56
  inputs = processor(images=image, return_tensors="pt")
57
  with torch.no_grad():
58
  outputs = model(**inputs)
59
  probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
60
+ idx = probs.argmax(-1).item()
61
+ conf = probs[0][idx].item()
62
+ name = class_names[idx]
63
+ med = get_medical_info(name)
64
 
65
+ overlay = create_overlay(image, idx, conf)
66
 
67
+ html_res = f"""
68
+ <div id="result-box">
69
+ <h2 style="color: #60a5fa; margin-top:0;">{name} Detected</h2>
70
+ <p style="font-size: 1.2em;"><b>Confidence Score:</b> <span style="color: #4ade80;">{conf:.1%}</span></p>
71
+ <div style="margin: 15px 0; padding: 10px; background: #262626; border-radius: 8px;">
72
+ <p style="color: #93c5fd; margin-bottom: 5px;"><b>Clinical Overview:</b></p>
73
+ <p style="color: #ffffff;">{med['desc']}</p>
74
+ </div>
75
+ <div style="margin: 15px 0; padding: 10px; background: #1e3a8a; border-radius: 8px;">
76
+ <p style="color: #bfdbfe; margin-bottom: 5px;"><b>Recommended Next Steps:</b></p>
77
+ <p style="color: #ffffff;">{med['next']}</p>
78
+ </div>
79
+ <p style="font-size: 0.8em; color: #94a3b8; border-top: 1px solid #444; pt-10;">
80
+ Probabilities: {", ".join([f"{class_names[i]}: {probs[0][i]:.1%}" for i in range(4)])}
81
+ </p>
82
  </div>
83
  """
84
+ return html_res, overlay
85
 
86
+ def create_overlay(image, idx, conf):
87
  overlay = image.copy().convert("RGBA")
88
  draw = ImageDraw.Draw(overlay)
89
+ if idx != 2:
90
+ w, h = overlay.size
91
+ r = min(w, h) // 4
 
92
  cx, cy = w // 2, h // 2
93
+ draw.ellipse([cx-r, cy-r, cx+r, cy+r], fill=(255, 0, 0, int(150*conf)), outline=(255, 255, 0, 255), width=5)
 
 
 
 
 
 
 
 
 
 
 
94
  return overlay.convert("RGB")
95
 
96
+ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
97
+ gr.HTML("<h1 style='text-align:center; color:white; font-size: 32px;'>NEURO-DIAGNOSTIC AI STATION</h1>")
98
+
99
  with gr.Row():
100
+ with gr.Column(scale=1):
101
+ img_input = gr.Image(label="Upload Patient MRI", type="pil")
102
+ run_btn = gr.Button("PERFORM NEURAL SCAN", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ with gr.Column(scale=1):
105
+ res_html = gr.HTML(label="Diagnostic Findings", elem_id="result-text")
106
+ img_output = gr.Image(label="Visualization Overlay")
 
 
 
107
 
108
+ run_btn.click(classify_tumor, img_input, [res_html, img_output])
 
 
 
109
 
110
  if __name__ == "__main__":
111
  demo.launch()