Spaces:
Sleeping
Sleeping
focusing on mri first
Browse files
app.py
CHANGED
|
@@ -1,99 +1,52 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import tensorflow as tf
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
base_model = tf.keras.applications.EfficientNetB1(
|
| 10 |
-
input_shape=(128, 128, 3),
|
| 11 |
-
include_top=False,
|
| 12 |
-
weights=None
|
| 13 |
-
)
|
| 14 |
-
|
| 15 |
-
# Built as a Sequential model to perfectly match the 3 saved layers in your .h5 file
|
| 16 |
-
model = tf.keras.Sequential([
|
| 17 |
-
base_model, # Layer 1: Backbone
|
| 18 |
-
tf.keras.layers.GlobalAveragePooling2D(), # Layer 2: Pooling
|
| 19 |
-
tf.keras.layers.Dense(14, activation='sigmoid') # Layer 3: Output head
|
| 20 |
-
])
|
| 21 |
-
|
| 22 |
-
try:
|
| 23 |
-
model.load_weights("xray.h5")
|
| 24 |
-
print("X-Ray weights (EfficientNetB1) loaded successfully!")
|
| 25 |
-
return model
|
| 26 |
-
except Exception as e:
|
| 27 |
-
print(f"Error loading X-Ray weights: {e}")
|
| 28 |
-
return None
|
| 29 |
-
|
| 30 |
-
# --- 2. LOAD MRI MODEL ---
|
| 31 |
-
# The zaahaa notebook outputs a standard .keras file, so we load it whole
|
| 32 |
-
try:
|
| 33 |
-
mri_model = tf.keras.models.load_model("mri.keras", compile=False)
|
| 34 |
-
print("MRI model loaded successfully!")
|
| 35 |
-
except Exception as e:
|
| 36 |
-
print(f"MRI Load Error: {e}")
|
| 37 |
-
mri_model = None
|
| 38 |
-
|
| 39 |
-
xray_model = build_xray_model()
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
'Cardiomegaly', 'Emphysema', 'Effusion', 'Hernia', 'Infiltration',
|
| 45 |
-
'Mass', 'Nodule', 'Atelectasis', 'Pneumothorax', 'Pleural_Thickening',
|
| 46 |
-
'Pneumonia', 'Fibrosis', 'Edema', 'Consolidation'
|
| 47 |
-
]
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
if mri_model is None: return {"MRI Model Error - Check Logs": 0.0}
|
| 56 |
-
|
| 57 |
-
# The zaahaa notebook uses Grayscale images. We force Grayscale (L) and 256x256.
|
| 58 |
-
img = img.convert("L").resize((256, 256))
|
| 59 |
-
img_array = np.array(img).astype('float32')
|
| 60 |
-
img_array = img_array.reshape((1, 256, 256, 1)) # Explicitly format to 1 channel
|
| 61 |
-
model, labels = mri_model, mri_labels
|
| 62 |
-
|
| 63 |
-
else:
|
| 64 |
-
if xray_model is None: return {"X-Ray Model Error - Check Logs": 0.0}
|
| 65 |
-
|
| 66 |
-
# Your EfficientNetB1 code used RGB images at 128x128
|
| 67 |
-
img = img.convert("RGB").resize((128, 128))
|
| 68 |
-
img_array = np.array(img).astype('float32')
|
| 69 |
-
img_array = np.expand_dims(img_array, axis=0) # Format to 3 channels
|
| 70 |
-
model, labels = xray_model, xray_labels
|
| 71 |
-
|
| 72 |
-
# Standard normalization used in both Kaggle notebooks
|
| 73 |
-
img_array /= 255.0
|
| 74 |
-
|
| 75 |
-
preds = model.predict(img_array)[0]
|
| 76 |
-
return {labels[i]: float(preds[i]) for i in range(len(labels))}
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
# --- 5. UI APP ---
|
| 82 |
-
with gr.Blocks() as demo:
|
| 83 |
-
gr.Markdown("# 🏥 BTech Medical Diagnostic API")
|
| 84 |
-
gr.Markdown("Upload an image to get a diagnostic prediction.")
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
+
# 1. Load the Keras model directly from the local folder
|
| 7 |
+
print("Loading model...")
|
| 8 |
+
model = tf.keras.models.load_model("mri.keras")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# 2. Class mappings based on the notebook training
|
| 11 |
+
# Order: 'Glioma', 'Meningioma', 'Notumor', 'Pituitary'
|
| 12 |
+
class_names = ['Glioma', 'Meningioma', 'No Tumor', 'Pituitary Tumor']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
def predict(image):
|
| 15 |
+
if image is None:
|
| 16 |
+
return None
|
| 17 |
|
| 18 |
+
# 3. Preprocess the input
|
| 19 |
+
# Expected: 168x168, grayscale, scaled by 1/255.0, with batch dimension
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Convert image to grayscale and resize it to 168x168
|
| 22 |
+
img = Image.fromarray(image).convert('L')
|
| 23 |
+
img = img.resize((168, 168))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# Convert to numpy array and normalize pixel values to [0, 1]
|
| 26 |
+
img_array = np.array(img) / 255.0
|
| 27 |
+
|
| 28 |
+
# The model expects input shape: (batch_size, 168, 168, 1)
|
| 29 |
+
img_array = np.expand_dims(img_array, axis=-1) # Add channel dimension
|
| 30 |
+
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
| 31 |
+
|
| 32 |
+
# 4. Make prediction
|
| 33 |
+
predictions = model.predict(img_array)[0]
|
| 34 |
+
|
| 35 |
+
# 5. Map the output to a clean, human-readable format for Gradio Interface
|
| 36 |
+
# Convert probabilities to a dictionary mapping class name to confidence score
|
| 37 |
+
confidences = {class_names[i]: float(predictions[i]) for i in range(len(class_names))}
|
| 38 |
+
return confidences
|
| 39 |
+
|
| 40 |
+
# 6. Define the Gradio interface
|
| 41 |
+
interface = gr.Interface(
|
| 42 |
+
fn=predict,
|
| 43 |
+
inputs=gr.Image(label="Upload MRI Brain Scan"),
|
| 44 |
+
outputs=gr.Label(num_top_classes=4, label="Prediction Confidence"),
|
| 45 |
+
title="MRI Brain Tumor Classification",
|
| 46 |
+
description="Upload an MRI scan to classify it into one of four categories: Glioma, Meningioma, No Tumor, or Pituitary Tumor.",
|
| 47 |
+
flagging_mode="never"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Launch the app
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
interface.launch()
|