import streamlit as st import numpy as np from PIL import Image from tensorflow.keras.models import load_model import os import time import requests from io import BytesIO # Function to load the model (cached for efficiency) @st.cache_resource def load_vgg_model(): return load_model("brain_tumor_vgg16_model.keras") # Function to run the prediction and show progress def run_prediction(image_path, model, img_size): # Create a progress bar and status text progress_bar = st.progress(0) status_text = st.empty() for i in range(100): progress_bar.progress(i + 1) status_text.text(f"Processing... {i+1}%") time.sleep(0.01) # Process and predict try: # Check if the input is a file-like object or a string path if isinstance(image_path, str): image = Image.open(image_path).convert("RGB") else: image = Image.open(image_path).convert("RGB") img_array = np.array(image.resize((img_size, img_size))) img_array = np.expand_dims(img_array, axis=0) img_array = img_array / 255.0 prediction = model.predict(img_array) class_predicted = (prediction > 0.5).astype("int32")[0][0] # Display the result if class_predicted == 1: st.error(f"Prediction: Tumor Detected (Probability: {100*prediction[0][0]:.2f}%)") else: st.success(f"Prediction: No Tumor Detected (Probability: {100*(1 - prediction[0][0]):.2f}%)") except Exception as e: st.error(f"An error occurred during classification: {e}") # Clear the progress bar progress_bar.empty() status_text.empty() # Streamlit UI st.title("Brain Tumor MRI Classification App") st.write("Upload your own image to get a prediction.") # Load the model model = load_vgg_model() # Define image size (must match the model's input size) img_size = 150 # --- UI for user image upload --- st.subheader("Upload Your Own Image") uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) if uploaded_file is not None: st.image(uploaded_file, caption='Uploaded MRI Scan', use_container_width=True) # Use a button to trigger the classification explicitly if st.button("Check for Brain Tumor"): run_prediction(uploaded_file, model, img_size)