JunaidAliB/BrainTumorDetection
0
1# src/app.py2import os3os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress TensorFlow warnings4 5import streamlit as st6import numpy as np7from PIL import Image8import tensorflow as tf9from tensorflow.keras.applications import efficientnet10import json11 12# -----------------------------13# Fixed paths (model folder inside src/)14# -----------------------------15MODEL_PATH = "saved_model/brain_tumor_classifier.h5"16LABELS_PATH = "saved_model/label_map.json"17 18# -----------------------------19# Load model and labels20# -----------------------------21@st.cache_resource22def load_model_and_labels():23 try:24 model = tf.keras.models.load_model(MODEL_PATH, compile=False)25 except Exception as e:26 st.error(f"Error loading model: {e}")27 return None, None28 29 try:30 with open(LABELS_PATH, "r") as f:31 labels_info = json.load(f)32 idx2label = {int(k): v for k, v in labels_info["index_to_label"].items()}33 except Exception as e:34 st.error(f"Error loading labels: {e}")35 return None, None36 37 return model, idx2label38 39model, idx2label = load_model_and_labels()40if model is None or idx2label is None:41 st.stop() # Stop execution if model or labels not found42 43# -----------------------------44# Streamlit UI45# -----------------------------46st.set_page_config(page_title="Brain Tumor Detection", layout="centered")47st.title("🧠 Brain Tumor Detection App")48st.write("Upload an MRI image and the model will predict if a **Brain Tumor is present (yes)** or **absent (no)**.")49 50# File uploader51uploaded_file = st.file_uploader("Choose an MRI image...", type=["jpg", "jpeg", "png", "bmp", "tif", "tiff"])52 53def confidence_color(conf):54 """Return color code based on confidence score"""55 if conf >= 0.8:56 return "#4CAF50" # green57 elif conf >= 0.5:58 return "#FFC107" # yellow59 else:60 return "#F44336" # red61 62if uploaded_file is not None:63 # Display image64 image = Image.open(uploaded_file).convert("RGB")65 st.image(image, caption="Uploaded MRI Image", use_column_width=True)66 67 # Preprocess68 IMG_SIZE = (224, 224)69 image = image.resize(IMG_SIZE)70 arr = np.array(image).astype(np.float32)71 arr = efficientnet.preprocess_input(arr)72 data = np.expand_dims(arr, axis=0)73 74 # Prediction75 prob = model.predict(data, verbose=0).ravel()[0] # sigmoid output76 pred_idx = int(prob >= 0.5)77 class_name = idx2label[pred_idx]78 79 # Display results80 st.subheader("Prediction")81 st.markdown(f"**Predicted Class:** `{class_name}`")82 83 st.write("**Confidence Scores:**")84 score_yes = prob85 score_no = 1 - prob86 st.metric("no", f"{score_no*100:.2f}%")87 st.metric("yes", f"{score_yes*100:.2f}%")88 89 # Display colored confidence bar90 confidence_score = score_yes if class_name == "yes" else score_no91 color = confidence_color(confidence_score)92 st.markdown(93 f"""94 <div style="background-color:#ddd; border-radius:5px; width:100%; height:25px;">95 <div style="width:{confidence_score*100}%; background-color:{color}; height:100%; border-radius:5px;"></div>96 </div>97 """,98 unsafe_allow_html=True99 )100else:101 st.info("Upload an MRI image to begin.")102 