brain_tumourrr / app.py
saad1BM's picture
Upload 3 files
a55aba1 verified
# app.py
import streamlit as st
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import numpy as np
from PIL import Image
import cv2 # OpenCV for easy image processing (Make sure it's in requirements.txt)
# --- CONFIGURATION ---
MODEL_PATH = 'model.keras' # Aapka saved model file
IMAGE_SIZE = (224, 224)
CLASS_NAMES = ['No Tumor', 'Tumor'] # 0: No Tumor, 1: Tumor
# --- Helper Function: Load Model ---
# Streamlit mein model ko sirf ek baar load karna chahiye
@st.cache_resource
def load_model():
try:
model = tf.keras.models.load_model(MODEL_PATH)
return model
except Exception as e:
st.error(f"Error loading model: {e}")
return None
# --- Helper Function: Preprocess Image ---
def preprocess_image(img):
"""Uploaded image ko model input ke liye ready karna."""
# Convert PIL image to OpenCV format (numpy array)
img_array = np.array(img.convert('RGB'))
# Resize and Rescale (Jaisa training mein kiya tha)
img_resized = cv2.resize(img_array, IMAGE_SIZE)
img_normalized = img_resized / 255.0 # Normalize to 0-1
# Add batch dimension: (224, 224, 3) -> (1, 224, 224, 3)
img_batch = np.expand_dims(img_normalized, axis=0)
return img_batch
# --- Streamlit UI Start ---
# 1. Page Title (Requirement a)
st.title("🧠 Brain Tumor Detection System (AI Powered)")
# Load the model
model = load_model()
if model is None:
st.warning("Model file 'model.keras' not found. Please run 'train_model.py' first and place the file here.")
else:
# 2. Image Upload Section (Requirement b)
uploaded_file = st.file_uploader(
"Upload a Brain MRI Image (.jpg, .png) for Classification:",
type=["jpg", "png", "jpeg"]
)
if uploaded_file is not None:
# Display image preview (Requirement b)
image_preview = Image.open(uploaded_file)
st.image(image_preview, caption='Uploaded MRI Image', use_column_width=True)
st.write("")
# 3. Prediction Button (Requirement c)
if st.button("🔬 Detect Tumor"):
st.write("Processing...")
# --- Prediction Logic ---
try:
# 1. Preprocess the image
processed_img = preprocess_image(image_preview)
# 2. Predict
prediction = model.predict(processed_img)
# 3. Interpret the result
# Output is a single value, e.g., [0.98] or [0.02]
confidence_score = prediction[0][0] * 100
if confidence_score > 50:
# Confidence is high for Tumor (Class 1)
result_index = 1
else:
# Confidence is high for No Tumor (Class 0)
result_index = 0
# For 'No Tumor', confidence is 100 - (Model's confidence for Tumor)
confidence_score = 100 - confidence_score
predicted_class = CLASS_NAMES[result_index]
# 4. Output Section (Requirement d)
st.subheader("✅ Prediction Results")
if predicted_class == 'Tumor':
st.error(f"**Prediction:** **{predicted_class}** - Immediate medical consultation is advised.")
else:
st.success(f"**Prediction:** **{predicted_class}** - Looks clear.")
# Display Confidence Score
st.info(f"**Confidence Score:** **{confidence_score:.2f}%**")
except Exception as e:
st.error(f"An error occurred during prediction: {e}")
else:
st.info("Please upload an image file to begin detection.")
# --- End of Streamlit App ---