Update app.py
Browse files
app.py
CHANGED
|
@@ -1,80 +1,79 @@
|
|
| 1 |
import os
|
| 2 |
-
# Force
|
| 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 #
|
| 8 |
import numpy as np
|
| 9 |
from PIL import Image
|
| 10 |
from huggingface_hub import hf_hub_download
|
| 11 |
|
| 12 |
# --- CONFIGURATION ---
|
| 13 |
-
#
|
| 14 |
-
REPO_ID = "mediaportal/
|
| 15 |
-
MODEL_FILENAME = "
|
| 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
|
| 23 |
path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME)
|
| 24 |
|
| 25 |
-
progress(0.7, desc="Loading weights
|
| 26 |
-
#
|
| 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
|
| 37 |
|
| 38 |
if img is None:
|
| 39 |
return "No image provided."
|
| 40 |
|
| 41 |
-
# 1. Preprocessing:
|
| 42 |
-
|
| 43 |
-
img = Image.fromarray(img.astype('uint8'), 'RGB').resize((224, 224))
|
| 44 |
|
| 45 |
-
# 2.
|
| 46 |
img_array = np.array(img).astype('float32') / 255.0
|
| 47 |
|
| 48 |
-
# 3. Add batch dimension (1,
|
| 49 |
img_array = np.expand_dims(img_array, axis=0)
|
| 50 |
|
| 51 |
# Inference
|
| 52 |
prediction = model.predict(img_array)[0]
|
| 53 |
|
| 54 |
-
#
|
| 55 |
labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]
|
| 56 |
|
| 57 |
-
# Return as a dictionary of
|
| 58 |
return {labels[i]: float(prediction[i]) for i in range(len(labels))}
|
| 59 |
|
| 60 |
-
# ---
|
| 61 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 62 |
-
gr.Markdown("# 🧠 Brain Tumor
|
| 63 |
-
gr.Markdown("
|
| 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("
|
| 71 |
with gr.Column():
|
| 72 |
-
output_label = gr.Label(num_top_classes=4, label="Diagnosis
|
| 73 |
|
| 74 |
-
# Automatically
|
| 75 |
demo.load(load_model_with_progress, outputs=status_box)
|
| 76 |
|
| 77 |
-
#
|
| 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__":
|