Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import os# Force TensorFlow to look for the legacy Keras 2 behavior if your model was trained on itos.environ["TF_USE_LEGACY_KERAS"] = "1"import gradio as grimport tensorflow as tfimport tf_keras as keras # Use tf_keras to avoid version mismatch errorsimport numpy as npfrom PIL import Imagefrom huggingface_hub import hf_hub_download# --- CONFIGURATION ---# Replace with your actual Repo ID and .h5 model filename on Hugging FaceREPO_ID = "mediaportal/BrainTumorDetection"MODEL_FILENAME = "brain99.h5"model = Nonedef load_model_with_progress(progress=gr.Progress(track_tqdm=True)):global modeltry:progress(0, desc="Downloading model from Hugging Face...")path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME)progress(0.7, desc="Loading weights using Classic Keras 2 engine...")# Use compile=False to bypass optimizer metadata issuesmodel = keras.models.load_model(path, compile=False)progress(1.0, desc="✅ Model Ready!")return "Model Loaded Successfully."except Exception as e:return f"❌ Error: {str(e)}"def predict(img):if model is None:return "Please wait for the model to load."if img is None:return "No image provided."# 1. Preprocessing: Resize to match the input shape used in your notebook# Your notebook uses 224x224 as standard for these CNN architecturesimg = Image.fromarray(img.astype('uint8'), 'RGB').resize((224, 224))# 2. Convert to array and normalize (1/255.0)img_array = np.array(img).astype('float32') / 255.0# 3. Add batch dimension (1, 224, 224, 3)img_array = np.expand_dims(img_array, axis=0)# Inferenceprediction = model.predict(img_array)[0]# Labels based on your notebook's classeslabels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]# Return as a dictionary of label: probabilityreturn {labels[i]: float(prediction[i]) for i in range(len(labels))}# --- BUILD GRADIO INTERFACE ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🧠 Brain Tumor Identification from MRI")gr.Markdown("This app uses a Deep Learning model to identify tumor types in MRI scans.")status_box = gr.Markdown("⏳ Initializing system...")with gr.Row():with gr.Column():input_img = gr.Image(label="Upload MRI Scan")btn = gr.Button("Analyze MRI", variant="primary")with gr.Column():output_label = gr.Label(num_top_classes=4, label="Diagnosis Prediction")# Automatically load model when app startsdemo.load(load_model_with_progress, outputs=status_box)# Trigger prediction on button clickbtn.click(fn=predict, inputs=input_img, outputs=output_label)if __name__ == "__main__":12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import os# Force Keras 2 logic for backward compatibility with .h5 modelsos.environ["TF_USE_LEGACY_KERAS"] = "1"import gradio as grimport tensorflow as tfimport tf_keras as keras # Official "Classic" Keras engineimport numpy as npfrom PIL import Imagefrom huggingface_hub import hf_hub_download# --- CONFIGURATION ---# IMPORTANT: Change REPO_ID to your actual Hugging Face repository nameREPO_ID = "mediaportal/BrainTumorMRI"MODEL_FILENAME = "BraintumorMRI99.h5"model = Nonedef load_model_with_progress(progress=gr.Progress(track_tqdm=True)):global modeltry:progress(0, desc="Downloading Brain Tumor model...")path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME)progress(0.7, desc="Loading weights into Xception architecture...")# compile=False avoids errors with custom training optimizers (like Adamax)model = keras.models.load_model(path, compile=False)progress(1.0, desc="✅ Model Ready!")return "Model Loaded Successfully. Ready to analyze MRI scans."except Exception as e:return f"❌ Error: {str(e)}"def predict(img):if model is None:return "Please wait for the model to finish loading."if img is None:return "No image provided."# 1. Preprocessing: Your notebook used (299, 299) for Xceptionimg = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299))# 2. Rescale: Matches 'rescale=1/255' used in your training ImageDataGeneratorimg_array = np.array(img).astype('float32') / 255.0# 3. Add batch dimension (1, 299, 299, 3)img_array = np.expand_dims(img_array, axis=0)# Inferenceprediction = model.predict(img_array)[0]# Class labels sorted alphabetically (default behavior of flow_from_dataframe)labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]# Return as a dictionary of {Label: Probability}return {labels[i]: float(prediction[i]) for i in range(len(labels))}# --- GRADIO INTERFACE ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🧠 Brain Tumor MRI Classification")gr.Markdown("Identify tumor types (Glioma, Meningioma, Pituitary) or healthy scans from MRI images.")status_box = gr.Markdown("⏳ Initializing system...")with gr.Row():with gr.Column():input_img = gr.Image(label="Upload MRI Scan")btn = gr.Button("Run Analysis", variant="primary")with gr.Column():output_label = gr.Label(num_top_classes=4, label="Diagnosis")# Automatically trigger model download on page loaddemo.load(load_model_with_progress, outputs=status_box)# Link button to prediction functionbtn.click(fn=predict, inputs=input_img, outputs=output_label)if __name__ == "__main__":
app.py+24-25