mediaportal commited on
Commit
ecd3438
·
verified ·
1 Parent(s): 05693d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -25
app.py CHANGED
@@ -1,80 +1,79 @@
1
  import os
2
- # Force TensorFlow to look for the legacy Keras 2 behavior if your model was trained on it
3
- os.environ["TF_USE_LEGACY_KERAS"] = "1"
4
 
5
  import gradio as gr
6
  import tensorflow as tf
7
- import tf_keras as keras # Use tf_keras to avoid version mismatch errors
8
  import numpy as np
9
  from PIL import Image
10
  from huggingface_hub import hf_hub_download
11
 
12
  # --- CONFIGURATION ---
13
- # Replace with your actual Repo ID and .h5 model filename on Hugging Face
14
- REPO_ID = "mediaportal/BrainTumorDetection"
15
- MODEL_FILENAME = "brain99.h5"
16
 
17
  model = None
18
 
19
  def load_model_with_progress(progress=gr.Progress(track_tqdm=True)):
20
  global model
21
  try:
22
- progress(0, desc="Downloading model from Hugging Face...")
23
  path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME)
24
 
25
- progress(0.7, desc="Loading weights using Classic Keras 2 engine...")
26
- # Use compile=False to bypass optimizer metadata issues
27
  model = keras.models.load_model(path, compile=False)
28
 
29
  progress(1.0, desc="✅ Model Ready!")
30
- return "Model Loaded Successfully."
31
  except Exception as e:
32
  return f"❌ Error: {str(e)}"
33
 
34
  def predict(img):
35
  if model is None:
36
- return "Please wait for the model to load."
37
 
38
  if img is None:
39
  return "No image provided."
40
 
41
- # 1. Preprocessing: Resize to match the input shape used in your notebook
42
- # Your notebook uses 224x224 as standard for these CNN architectures
43
- img = Image.fromarray(img.astype('uint8'), 'RGB').resize((224, 224))
44
 
45
- # 2. Convert to array and normalize (1/255.0)
46
  img_array = np.array(img).astype('float32') / 255.0
47
 
48
- # 3. Add batch dimension (1, 224, 224, 3)
49
  img_array = np.expand_dims(img_array, axis=0)
50
 
51
  # Inference
52
  prediction = model.predict(img_array)[0]
53
 
54
- # Labels based on your notebook's classes
55
  labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]
56
 
57
- # Return as a dictionary of label: probability
58
  return {labels[i]: float(prediction[i]) for i in range(len(labels))}
59
 
60
- # --- BUILD GRADIO INTERFACE ---
61
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
62
- gr.Markdown("# 🧠 Brain Tumor Identification from MRI")
63
- gr.Markdown("This app uses a Deep Learning model to identify tumor types in MRI scans.")
64
 
65
  status_box = gr.Markdown("⏳ Initializing system...")
66
 
67
  with gr.Row():
68
  with gr.Column():
69
  input_img = gr.Image(label="Upload MRI Scan")
70
- btn = gr.Button("Analyze MRI", variant="primary")
71
  with gr.Column():
72
- output_label = gr.Label(num_top_classes=4, label="Diagnosis Prediction")
73
 
74
- # Automatically load model when app starts
75
  demo.load(load_model_with_progress, outputs=status_box)
76
 
77
- # Trigger prediction on button click
78
  btn.click(fn=predict, inputs=input_img, outputs=output_label)
79
 
80
  if __name__ == "__main__":
 
1
  import os
2
+ # Force Keras 2 logic for backward compatibility with .h5 models
3
+ os.environ["TF_USE_LEGACY_KERAS"] = "1"
4
 
5
  import gradio as gr
6
  import tensorflow as tf
7
+ import tf_keras as keras # Official "Classic" Keras engine
8
  import numpy as np
9
  from PIL import Image
10
  from huggingface_hub import hf_hub_download
11
 
12
  # --- CONFIGURATION ---
13
+ # IMPORTANT: Change REPO_ID to your actual Hugging Face repository name
14
+ REPO_ID = "mediaportal/BrainTumorMRI"
15
+ MODEL_FILENAME = "BraintumorMRI99.h5"
16
 
17
  model = None
18
 
19
  def load_model_with_progress(progress=gr.Progress(track_tqdm=True)):
20
  global model
21
  try:
22
+ progress(0, desc="Downloading Brain Tumor model...")
23
  path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME)
24
 
25
+ progress(0.7, desc="Loading weights into Xception architecture...")
26
+ # compile=False avoids errors with custom training optimizers (like Adamax)
27
  model = keras.models.load_model(path, compile=False)
28
 
29
  progress(1.0, desc="✅ Model Ready!")
30
+ return "Model Loaded Successfully. Ready to analyze MRI scans."
31
  except Exception as e:
32
  return f"❌ Error: {str(e)}"
33
 
34
  def predict(img):
35
  if model is None:
36
+ return "Please wait for the model to finish loading."
37
 
38
  if img is None:
39
  return "No image provided."
40
 
41
+ # 1. Preprocessing: Your notebook used (299, 299) for Xception
42
+ img = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299))
 
43
 
44
+ # 2. Rescale: Matches 'rescale=1/255' used in your training ImageDataGenerator
45
  img_array = np.array(img).astype('float32') / 255.0
46
 
47
+ # 3. Add batch dimension (1, 299, 299, 3)
48
  img_array = np.expand_dims(img_array, axis=0)
49
 
50
  # Inference
51
  prediction = model.predict(img_array)[0]
52
 
53
+ # Class labels sorted alphabetically (default behavior of flow_from_dataframe)
54
  labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]
55
 
56
+ # Return as a dictionary of {Label: Probability}
57
  return {labels[i]: float(prediction[i]) for i in range(len(labels))}
58
 
59
+ # --- GRADIO INTERFACE ---
60
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
61
+ gr.Markdown("# 🧠 Brain Tumor MRI Classification")
62
+ gr.Markdown("Identify tumor types (Glioma, Meningioma, Pituitary) or healthy scans from MRI images.")
63
 
64
  status_box = gr.Markdown("⏳ Initializing system...")
65
 
66
  with gr.Row():
67
  with gr.Column():
68
  input_img = gr.Image(label="Upload MRI Scan")
69
+ btn = gr.Button("Run Analysis", variant="primary")
70
  with gr.Column():
71
+ output_label = gr.Label(num_top_classes=4, label="Diagnosis")
72
 
73
+ # Automatically trigger model download on page load
74
  demo.load(load_model_with_progress, outputs=status_box)
75
 
76
+ # Link button to prediction function
77
  btn.click(fn=predict, inputs=input_img, outputs=output_label)
78
 
79
  if __name__ == "__main__":