mediaportal commited on
Commit
66d9598
·
verified ·
1 Parent(s): 26172ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -27
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import os
2
- # Force Keras 2 logic to prevent the 'recursion depth' and 'quantization' errors
3
  os.environ["TF_USE_LEGACY_KERAS"] = "1"
4
 
5
  import gradio as gr
@@ -10,12 +10,11 @@ from PIL import Image
10
  from huggingface_hub import hf_hub_download
11
 
12
  # --- CONFIGURATION ---
13
- # 1. Ensure this matches your Hugging Face URL exactly.
14
- # If your repo is at huggingface.co/username/repo, use "username/repo"
15
- REPO_ID = "mediaportal/BrainTumorMRI"
16
  MODEL_FILENAME = "BraintumorMRI99.h5"
17
 
18
- # 2. If your repo is PRIVATE, add your token to Space Secrets as 'HF_TOKEN'
19
  hf_token = os.getenv("HF_TOKEN")
20
 
21
  model = None
@@ -23,17 +22,15 @@ model = None
23
  def load_model_with_progress(progress=gr.Progress(track_tqdm=True)):
24
  global model
25
  try:
26
- progress(0, desc="Connecting to Hugging Face...")
27
-
28
- # hf_hub_download will use the token if the repo is private
29
  path = hf_hub_download(
30
  repo_id=REPO_ID,
31
  filename=MODEL_FILENAME,
32
  token=hf_token
33
  )
34
 
35
- progress(0.7, desc="Loading Xception weights (Keras 2)...")
36
- # compile=False is used to skip loading training-specific optimizer states
37
  model = keras.models.load_model(path, compile=False)
38
 
39
  progress(1.0, desc="✅ Model Ready!")
@@ -43,48 +40,42 @@ def load_model_with_progress(progress=gr.Progress(track_tqdm=True)):
43
 
44
  def predict(img):
45
  if model is None:
46
- return "Please wait for the model to finish loading."
47
 
48
  if img is None:
49
  return "No image provided."
50
 
51
- # 1. Preprocessing: Xception requires 299x299 based on your notebook
52
  img = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299))
53
 
54
- # 2. Rescale 1/255 as used in your ImageDataGenerator
55
  img_array = np.array(img).astype('float32') / 255.0
56
-
57
- # 3. Add batch dimension (1, 299, 299, 3)
58
  img_array = np.expand_dims(img_array, axis=0)
59
 
60
- # Inference
61
  prediction = model.predict(img_array)[0]
62
 
63
- # Labels based on the 4 classes in your training data
 
64
  labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]
65
 
66
  return {labels[i]: float(prediction[i]) for i in range(len(labels))}
67
 
68
  # --- GRADIO INTERFACE ---
69
-
70
-
71
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
72
- gr.Markdown("# 🧠 Brain Tumor MRI Identification")
73
- gr.Markdown("Identify Glioma, Meningioma, Pituitary tumors or Healthy scans using Xception Deep Learning.")
74
 
75
- status_box = gr.Markdown("⏳ Initializing system...")
76
 
77
  with gr.Row():
78
  with gr.Column():
79
  input_img = gr.Image(label="Upload MRI Scan")
80
- btn = gr.Button("Analyze MRI", variant="primary")
81
  with gr.Column():
82
- output_label = gr.Label(num_top_classes=4, label="Diagnosis Prediction")
83
 
84
- # Load model on start
85
  demo.load(load_model_with_progress, outputs=status_box)
86
-
87
- # Run prediction on click
88
  btn.click(fn=predict, inputs=input_img, outputs=output_label)
89
 
90
  if __name__ == "__main__":
 
1
  import os
2
+ # Forces the use of Keras 2 logic, preventing common 'recursion' errors in new environments
3
  os.environ["TF_USE_LEGACY_KERAS"] = "1"
4
 
5
  import gradio as gr
 
10
  from huggingface_hub import hf_hub_download
11
 
12
  # --- CONFIGURATION ---
13
+ # Based on your provided link: https://huggingface.co/mediaportal/Braintumor-MRI-detection
14
+ REPO_ID = "mediaportal/Braintumor-MRI-detection"
 
15
  MODEL_FILENAME = "BraintumorMRI99.h5"
16
 
17
+ # If your repo is set to PRIVATE, add your token to Space Secrets as 'HF_TOKEN'
18
  hf_token = os.getenv("HF_TOKEN")
19
 
20
  model = None
 
22
  def load_model_with_progress(progress=gr.Progress(track_tqdm=True)):
23
  global model
24
  try:
25
+ progress(0, desc="Downloading model from Hugging Face...")
 
 
26
  path = hf_hub_download(
27
  repo_id=REPO_ID,
28
  filename=MODEL_FILENAME,
29
  token=hf_token
30
  )
31
 
32
+ progress(0.7, desc="Loading weights into Xception architecture...")
33
+ # compile=False avoids loading the optimizer state from the training session
34
  model = keras.models.load_model(path, compile=False)
35
 
36
  progress(1.0, desc="✅ Model Ready!")
 
40
 
41
  def predict(img):
42
  if model is None:
43
+ return "System is still initializing. Please wait."
44
 
45
  if img is None:
46
  return "No image provided."
47
 
48
+ # Preprocessing based on notebook: Xception requires 299x299
49
  img = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299))
50
 
51
+ # Rescale 1/255 as used in the notebook's ImageDataGenerator
52
  img_array = np.array(img).astype('float32') / 255.0
 
 
53
  img_array = np.expand_dims(img_array, axis=0)
54
 
 
55
  prediction = model.predict(img_array)[0]
56
 
57
+ # Class labels identified from tr_df in the notebook
58
+ # Standard order for this dataset: glioma, meningioma, notumor, pituitary
59
  labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]
60
 
61
  return {labels[i]: float(prediction[i]) for i in range(len(labels))}
62
 
63
  # --- GRADIO INTERFACE ---
 
 
64
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
65
+ gr.Markdown("# 🧠 Brain Tumor MRI Classification")
66
+ gr.Markdown("Identify Glioma, Meningioma, Pituitary tumors, or Healthy scans.")
67
 
68
+ status_box = gr.Markdown("⏳ Initializing... Checking access to " + REPO_ID)
69
 
70
  with gr.Row():
71
  with gr.Column():
72
  input_img = gr.Image(label="Upload MRI Scan")
73
+ btn = gr.Button("Run Diagnosis", variant="primary")
74
  with gr.Column():
75
+ output_label = gr.Label(num_top_classes=4, label="Prediction Result")
76
 
77
+ # Load model immediately upon app startup
78
  demo.load(load_model_with_progress, outputs=status_box)
 
 
79
  btn.click(fn=predict, inputs=input_img, outputs=output_label)
80
 
81
  if __name__ == "__main__":