starpreeda commited on
Commit
f1abfa5
·
verified ·
1 Parent(s): a1b704e

Upload 2 files

Browse files
Files changed (1) hide show
  1. train_efficientnetb0_finetuned.py +142 -0
train_efficientnetb0_finetuned.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import urllib.request
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from tensorflow.keras.preprocessing import image
6
+ from tensorflow.keras.applications.efficientnet import preprocess_input
7
+ import gradio as gr
8
+ import cv2
9
+
10
+ MODEL_PATH = "efficientnetb0_finetuned_brain_mri.h5"
11
+
12
+ # Direct download URL from your Hugging Face Repository
13
+ MODEL_URL = "https://huggingface.co/starpreeda/BrainTumorTest/resolve/main/efficientnetb0_finetuned_brain_mri.h5"
14
+
15
+ def load_brain_mri_model():
16
+ """Download model weights if not locally available and load Keras model."""
17
+ if not os.path.exists(MODEL_PATH):
18
+ print("Downloading model weights from Hugging Face Repository...")
19
+ try:
20
+ urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
21
+ print("Model weights downloaded successfully!")
22
+ except Exception as e:
23
+ print(f"Error downloading model: {e}")
24
+ print("Attempting to load from local working directory...")
25
+
26
+ return tf.keras.models.load_model(MODEL_PATH)
27
+
28
+ # Load the model into memory
29
+ model = load_brain_mri_model()
30
+
31
+ CLASS_MAPPING = {
32
+ 'glioma': {
33
+ 'name': 'Glioma Tumor',
34
+ 'desc': 'A type of tumor that originates in the glial cells supporting the brain and spinal cord.'
35
+ },
36
+ 'meningioma': {
37
+ 'name': 'Meningioma Tumor',
38
+ 'desc': 'A tumor arising from the meninges — the protective membranes surrounding the brain and spinal cord.'
39
+ },
40
+ 'notumor': {
41
+ 'name': 'No Tumor Detected',
42
+ 'desc': 'The provided MRI scan shows no clear evidence or signs of brain tumor tissue.'
43
+ },
44
+ 'pituitary': {
45
+ 'name': 'Pituitary Tumor',
46
+ 'desc': 'An abnormal growth located in the pituitary gland at the base of the brain, which can affect hormone levels.'
47
+ }
48
+ }
49
+
50
+ CLASS_NAMES = ['glioma', 'meningioma', 'notumor', 'pituitary']
51
+
52
+ def predict_mri(input_img):
53
+ """Preprocess input image, predict tumor category, and return summary HTML and confidence breakdown."""
54
+ if input_img is None:
55
+ return "<h3 style='color:#d93025;'>Please upload a valid Brain MRI scan image.</h3>", {}
56
+
57
+
58
+ img_resized = cv2.resize(input_img, (224, 224))
59
+ img_array = image.img_to_array(img_resized)
60
+ img_batch = np.expand_dims(img_array, axis=0)
61
+
62
+
63
+ img_preprocessed = preprocess_input(img_batch)
64
+
65
+
66
+ predictions = model.predict(img_preprocessed)[0]
67
+
68
+
69
+ confidences = {}
70
+ for idx, class_key in enumerate(CLASS_NAMES):
71
+ label_text = CLASS_MAPPING[class_key]['name']
72
+ confidences[label_text] = float(predictions[idx])
73
+
74
+
75
+ top_idx = np.argmax(predictions)
76
+ top_key = CLASS_NAMES[top_idx]
77
+ top_confidence = predictions[top_idx] * 100
78
+ info = CLASS_MAPPING[top_key]
79
+
80
+
81
+ summary_html = f"""
82
+ <div style="background-color: #f8f9fa; border-left: 6px solid #1a73e8; padding: 18px; border-radius: 8px; margin-top: 10px;">
83
+ <h3 style="color: #1a73e8; margin-top: 0;">Diagnostic Classification Summary</h3>
84
+
85
+ <p style="font-size: 20px; font-weight: bold; margin-bottom: 8px;">
86
+ Predicted Class: <span style="color: #d93025;">{info['name']}</span>
87
+ </p>
88
+ <p style="font-size: 16px; font-weight: bold; color: #3c4043;">
89
+ Confidence Score: <span style="font-size: 20px; color: #188038;">{top_confidence:.2f}%</span>
90
+ </p>
91
+
92
+ <hr style="border: 0.5px solid #dadce0; margin: 12px 0;">
93
+
94
+ <div style="background-color: #ffffff; padding: 12px; border-radius: 6px; border: 1px solid #e0e0e0;">
95
+ <p style="margin: 4px 0; font-size: 14px; color: #5f6368;"><b>Clinical Note:</b> {info['desc']}</p>
96
+ </div>
97
+ </div>
98
+ """
99
+
100
+ return summary_html, confidences
101
+
102
+ # ====================================================
103
+ # 4. Gradio User Interface (Full English)
104
+ # ====================================================
105
+ with gr.Blocks(title="Brain Tumor MRI Classification", theme=gr.themes.Soft()) as demo:
106
+
107
+ gr.Markdown(
108
+ """
109
+ # 🧠 Brain Tumor MRI Classification System
110
+ ### Fine-Tuned EfficientNetB0 Deep Learning Model
111
+
112
+ Upload a Brain MRI scan to analyze and classify potential tumor types (*Glioma, Meningioma, Pituitary, or No Tumor*).
113
+ """
114
+ )
115
+
116
+ with gr.Row():
117
+ with gr.Column(scale=1):
118
+ image_input = gr.Image(type="numpy", label="Upload Brain MRI Image")
119
+ submit_btn = gr.Button("🔍 Analyze MRI Scan", variant="primary", size="lg")
120
+
121
+ gr.Markdown(
122
+ """
123
+ ---
124
+ ⚠️ **Medical Disclaimer:**
125
+ This AI application is designed strictly for educational, demonstration, and preliminary research purposes. It should **not** be used as a primary diagnostic tool or as a substitute for professional evaluation by a licensed radiologist or healthcare provider.
126
+ """
127
+ )
128
+
129
+ with gr.Column(scale=1):
130
+ result_output = gr.HTML(label="Classification Result")
131
+ label_output = gr.Label(num_top_classes=4, label="Class Probability Distribution")
132
+
133
+ # Event Listener
134
+ submit_btn.click(
135
+ fn=predict_mri,
136
+ inputs=[image_input],
137
+ outputs=[result_output, label_output]
138
+ )
139
+
140
+
141
+ if __name__ == "__main__":
142
+ demo.launch(share=True)