CGAllenger commited on
Commit
1964b53
·
verified ·
1 Parent(s): 5876089

focusing on mri first

Browse files
Files changed (1) hide show
  1. app.py +43 -90
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
- # --- 1. X-RAY MODEL RECONSTRUCTION ---
7
- # Rebuilding exactly based on EfficientNetB1 and 128x128
8
- def build_xray_model():
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
- # --- 3. LABELS ---
42
- mri_labels = ['Glioma', 'Meningioma', 'Pituitary tumor', 'no tumor']
43
- xray_labels = [
44
- 'Cardiomegaly', 'Emphysema', 'Effusion', 'Hernia', 'Infiltration',
45
- 'Mass', 'Nodule', 'Atelectasis', 'Pneumothorax', 'Pleural_Thickening',
46
- 'Pneumonia', 'Fibrosis', 'Edema', 'Consolidation'
47
- ]
48
 
49
- # --- 4. PREDICTION LOGIC ---
50
- def predict(img, model_type):
51
- if img is None: return {"No image provided": 0.0}
52
 
53
- try:
54
- if model_type == "MRI":
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
- except Exception as e:
79
- return {f"Prediction Error: {str(e)}": 0.0}
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
- with gr.Tabs():
87
- with gr.TabItem("Brain MRI Classifier"):
88
- mri_in = gr.Image(type="pil", label="Upload Brain MRI")
89
- mri_out = gr.Label(num_top_classes=1, label="Result")
90
- mri_btn = gr.Button("Analyze MRI", variant="primary")
91
- mri_btn.click(fn=lambda i: predict(i, "MRI"), inputs=mri_in, outputs=mri_out, api_name="predict_mri")
92
-
93
- with gr.TabItem("Chest X-Ray Classifier"):
94
- xray_in = gr.Image(type="pil", label="Upload Chest X-Ray")
95
- xray_out = gr.Label(num_top_classes=1, label="Result")
96
- xray_btn = gr.Button("Analyze X-Ray", variant="primary")
97
- xray_btn.click(fn=lambda i: predict(i, "X-Ray"), inputs=xray_in, outputs=xray_out, api_name="predict_xray")
98
-
99
- demo.launch(theme=gr.themes.Soft())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()