Download app.py from mercelv/brain: direct link, hf CLI and curl.
- Browser
- Download file 9.31 kB
-
https://huggingface.co/spaces/mercelv/brain/resolve/main/app.py
- Command line
-
hf download hf://spaces/mercelv/brain/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mercelv/brain/resolve/main/app.py
9.31 kB
| import streamlit as st | |
| import tensorflow as tf | |
| import numpy as np | |
| from PIL import Image | |
| import cv2 | |
| import os | |
| from tensorflow.keras.applications.resnet50 import preprocess_input | |
| # Load the saved models | |
| model_vgg = tf.keras.models.load_model("brain_tumor_model_26.h5") | |
| classes_vgg = ["No Tumor detected", "Tumor detected"] | |
| model_resnet = tf.keras.models.load_model("Tumor_GliMeninPitu_model.h5") | |
| # model_resnet = tf.keras.models.load_model("model.h5") | |
| classes_resnet = ["Glioma", "Meningioma", "No Tumor", "Pituitary"] | |
| # Function to preprocess image | |
| def preprocess_image_old(uploaded_image, target_size): | |
| img = Image.open(uploaded_image) | |
| # Check if the image is grayscale | |
| if img.mode == 'L': | |
| # Convert grayscale to RGB by repeating the single channel | |
| img = img.convert('RGB') | |
| st.info("Gray scale image has been converted to three channels.") | |
| # Resize the image | |
| img = img.resize(target_size) | |
| # Convert image to numpy array and preprocess | |
| img_array = np.array(img) | |
| # Ensure the image has three channels | |
| if img_array.shape[-1] == 4: | |
| img_array = img_array[:, :, :3] | |
| img_array = tf.keras.applications.vgg16.preprocess_input(img_array) | |
| # Add batch dimension | |
| img_array = np.expand_dims(img_array, axis=0) | |
| return img_array | |
| def preprocess_image_mc(uploaded_image, target_size=(224,224)): | |
| # Read the image from the uploaded file | |
| img = Image.open(uploaded_image) | |
| # Convert the image to RGB format (ResNet50 expects RGB) | |
| img = img.convert("RGB") | |
| # Resize the image to match the target size used during training | |
| img = img.resize(target_size) | |
| # Convert the image to a numpy array | |
| img_array = np.array(img) | |
| # Preprocess the image using ResNet50 preprocessing | |
| img_array = preprocess_input(img_array) | |
| # Expand the dimensions to match the model's input shape (batch size of 1) | |
| img_array = np.expand_dims(img_array, axis=0) | |
| return img_array | |
| def preprocess_image_mcb(image_path, target_size=(224, 224)): | |
| # Read the image from the given path using cv2.imread | |
| img = cv2.imread(image_path) # Use COLOR mode | |
| # Resize the image to match the target size | |
| img = cv2.resize(img, target_size) | |
| # Convert the image to a numpy array | |
| img_array = np.array(img) | |
| # Preprocess the image using ResNet50 preprocessing (if needed) | |
| # img_array = preprocess_input(img_array) | |
| # Expand the dimensions to match the model's input shape (batch size of 1) | |
| img_array = np.expand_dims(img_array, axis=0) | |
| return img_array | |
| def preprocess_image(uploaded_image, target_size=(224, 224)): | |
| if uploaded_image is not None: | |
| # Read the image from BytesIO object | |
| file_bytes = np.asarray(bytearray(uploaded_image.read()), dtype=np.uint8) | |
| img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) | |
| # Resize the image | |
| img = cv2.resize(img, target_size) | |
| # Convert image to RGB if it's not already (OpenCV uses BGR by default) | |
| if img.shape[2] == 3: | |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| # Normalize the pixel values (the model expects values in [0, 1]) | |
| img_array = img.astype('float32') / 255.0 | |
| # Add batch dimension | |
| img_array = np.expand_dims(img_array, axis=0) | |
| return img_array | |
| return None | |
| # Function to analyze binary classification | |
| def analyze_binary(uploaded_image, model, classes): | |
| if uploaded_image is not None: | |
| # Preprocess the uploaded image | |
| img_array = preprocess_image(uploaded_image, (224, 224)) | |
| if img_array is not None: | |
| # Make predictions using the loaded model | |
| predictions = model.predict(img_array) | |
| # Get the class label with the highest probability | |
| class_label = np.argmax(predictions) | |
| pred_class = classes[class_label] | |
| confidence = predictions[0][class_label] | |
| # Display prediction and confidence with stylish colors | |
| st.markdown( | |
| f"<div class='results-text' style='color: #009688;'>Prediction: <span class='results-values'>{pred_class}</span></div>", | |
| unsafe_allow_html=True, | |
| ) | |
| st.markdown( | |
| f"<div class='results-text' style='color: #E91E63;'>Confidence Level: <span class='results-values'>{confidence:.2%}</span></div>", | |
| unsafe_allow_html=True, | |
| ) | |
| else: | |
| st.warning("Please upload an image before clicking 'Analyze Binary'.") | |
| # Function to analyze multiclass classification | |
| def analyze_multiclass(uploaded_image, model, classes): | |
| if uploaded_image is not None: | |
| # Preprocess the uploaded image | |
| img_array = preprocess_image_mcb(uploaded_image, (224, 224)) | |
| if img_array is not None: | |
| # Make predictions using the loaded model | |
| predictions = model.predict(img_array) | |
| # Get the class label with the highest probability | |
| class_label = np.argmax(predictions) | |
| pred_class = classes[class_label] | |
| confidence = predictions[0][class_label] | |
| # Display prediction and confidence with stylish colors | |
| st.markdown( | |
| f"<div class='results-text' style='color: #4CAF50;'>Prediction: <span class='results-values'>{pred_class}</span></div>", | |
| unsafe_allow_html=True, | |
| ) | |
| st.markdown( | |
| f"<div class='results-text' style='color: #FFC107;'>Confidence Level: <span class='results-values'>{confidence:.2%}</span></div>", | |
| unsafe_allow_html=True, | |
| ) | |
| else: | |
| st.warning("Please upload an image before clicking 'Analyze Multiclass'.") | |
| # Set page configuration and layout | |
| st.set_page_config( | |
| page_title="Image Classification App", | |
| page_icon=":camera:", | |
| layout="wide", | |
| ) | |
| # Header logo with a colorful border | |
| st.markdown( | |
| """ | |
| <style> | |
| .header-logo { | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| margin-bottom: 20px; | |
| padding: 20px; | |
| background-color: #2196F3; | |
| border-radius: 10px; | |
| color: white; | |
| } | |
| </style> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| st.markdown("<div class='header-logos'>", unsafe_allow_html=True) | |
| st.image("RCAIoT_logo.png", use_column_width=False) | |
| st.markdown("</div>", unsafe_allow_html=True) | |
| def open_google_maps(): | |
| st.markdown("## Nearest Hospital Location") | |
| st.markdown("Here is the nearest hospital's location on Google Maps:") | |
| # You can replace the following URL with the actual Google Maps URL | |
| google_maps_url = "https://www.google.com/maps" | |
| st.write(f"[Open Google Maps]({google_maps_url})") | |
| # Main content | |
| col1, col2 = st.columns([1, 1]) | |
| with col1: | |
| st.header("Upload Image") | |
| uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"], key="upload_image") | |
| if uploaded_image is not None: | |
| # Create an 'uploads' directory if it doesn't exist | |
| if not os.path.exists('uploads'): | |
| os.makedirs('uploads') | |
| # Construct the path to save the uploaded file | |
| file_path = os.path.join('uploads', uploaded_image.name) | |
| # Save the uploaded file to the 'uploads' directory | |
| with open(file_path, "wb") as f: | |
| f.write(uploaded_image.getbuffer()) | |
| st.image(uploaded_image, caption="Uploaded Image", use_column_width=False, width=300) | |
| st.markdown( | |
| """ | |
| <style> | |
| img { | |
| max-height: 300px; | |
| } | |
| </style> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| with col2: | |
| st.header("Results") | |
| # Stylish Analyze and Reset buttons in a horizontal row | |
| st.markdown( | |
| """ | |
| <style> | |
| .analyze-reset-buttons { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-top: 20px; | |
| } | |
| .analyze-reset-buttons button { | |
| flex: 1; | |
| margin: 10px; | |
| padding: 10px; | |
| background-color: #2196F3; | |
| color: white; | |
| font-size: 16px; | |
| text-align: center; | |
| border: none; | |
| border-radius: 5px; | |
| cursor: pointer; | |
| transition: background-color 0.3s ease; | |
| } | |
| .analyze-reset-buttons button:hover { | |
| background-color: #1565C0; | |
| } | |
| .results-text { | |
| font-size: 24px; | |
| font-weight: bold; | |
| margin-top: 20px; | |
| } | |
| .results-values { | |
| font-size: 18px; | |
| font-weight: bold; | |
| margin-top: 10px; | |
| } | |
| </style> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| st.markdown("<div class='analyze-reset-buttons'>", unsafe_allow_html=True) | |
| if st.button("Detect Tumor", key="analyze_binary_button"): | |
| analyze_binary(uploaded_image, model_vgg, classes_vgg) | |
| if st.button("Help"): | |
| open_google_maps() | |
| if st.button("Classify cancer", key="analyze_multiclass_button"): | |
| analyze_multiclass(file_path, model_resnet, classes_resnet) | |
| if st.button("Help"): | |
| open_google_maps() |