Update app.py
Browse files1232345677891011121314151314151617181920212222232425262526272829303031323334353636373839404142434142434544454648474849505152545354555756575860596062636162636465666768706970727172747374757776777879import os# Force TensorFlow to look for the legacy Keras 2 behavior if your model was trained on itos.environ["TF_USE_LEGACY_KERAS"] = "1"# 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 # Use tf_keras to avoid version mismatch errorsimport tf_keras as keras # Official "Classic" Keras engineimport 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" # IMPORTANT: Change REPO_ID to your actual Hugging Face repository nameREPO_ID = "mediaportal/BrainTumorMRI" MODEL_FILENAME = "BraintumorMRI99.h5"
model = None
def load_model_with_progress(progress=gr.Progress(track_tqdm=True)): global model try: progress(0, desc="Downloading model from Hugging Face...") progress(0, desc="Downloading Brain Tumor model...") 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 issues 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." 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 load." return "Please wait for the model to finish loading." 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 architectures img = Image.fromarray(img.astype('uint8'), 'RGB').resize((224, 224)) # 1. Preprocessing: Your notebook used (299, 299) for Xception img = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299)) # 2. Convert to array and normalize (1/255.0) # 2. Rescale: Matches 'rescale=1/255' used in your training ImageDataGenerator img_array = np.array(img).astype('float32') / 255.0 # 3. Add batch dimension (1, 224, 224, 3) # 3. Add batch dimension (1, 299, 299, 3) img_array = np.expand_dims(img_array, axis=0) # Inference prediction = model.predict(img_array)[0] # Labels based on your notebook's classes # Class labels sorted alphabetically (default behavior of flow_from_dataframe) labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"] # Return as a dictionary of label: probability # Return as a dictionary of {Label: Probability} return {labels[i]: float(prediction[i]) for i in range(len(labels))}
# --- BUILD GRADIO INTERFACE ---# --- 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.") 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("Analyze MRI", variant="primary") btn = gr.Button("Run Analysis", variant="primary") with gr.Column(): output_label = gr.Label(num_top_classes=4, label="Diagnosis Prediction") output_label = gr.Label(num_top_classes=4, label="Diagnosis")
# Automatically load model when app starts # Automatically trigger model download on page load demo.load(load_model_with_progress, outputs=status_box) # Trigger prediction on button click # Link button to prediction function btn.click(fn=predict, inputs=input_img, outputs=output_label)
if __name__ == "__main__":app.py+24-25