import streamlit as st # Set the page layout st.set_page_config(layout="wide") import time import base64 import tensorflow as tf import numpy as np from PIL import Image import torch import os import torch.nn as nn from torchvision import transforms import torch.nn.functional as F if "model" not in st.session_state: st.session_state.model = tf.keras.models.load_model('best_model.keras') if "choice" not in st.session_state: st.session_state.choice = "tensorflow" #import matplotlib.pyplot as plt # Path to your logo image main_bg_ext = 'png' main_bg = 'download (3).jfif' #**************************************************************** # TENSORFLOW MODEL CONFIGURATION #**************************************************************** class_labels=[ 'Cyst', 'Normal','Stone', 'Tumor'] def load_tensorflow_model(): # Example: Load a pre-trained model (e.g., MobileNetV2) tf_model = tf.keras.models.load_model('best_model.keras') return tf_model def predict_image(image): time.sleep(2) image = image.resize((64, 64)) image = np.array(image) / 255.0 image = np.expand_dims(image, axis=0) predictions = st.session_state.model.predict(image) return predictions #**************************************************************** # PYTORCH MODEL CONFIGURATION #**************************************************************** class CNNModel(nn.Module): def __init__(self, input_channels=3, num_classes=4): super(CNNModel, self).__init__() self.conv1 = nn.Conv2d(input_channels, 32, kernel_size=3, padding=1) self.bn1 = nn.BatchNorm2d(32) self.pool1 = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1) self.bn2 = nn.BatchNorm2d(64) self.pool2 = nn.MaxPool2d(2, 2) self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1) self.bn3 = nn.BatchNorm2d(128) self.pool3 = nn.MaxPool2d(2, 2) self.conv4 = nn.Conv2d(128, 256, kernel_size=3, padding=1) self.bn4 = nn.BatchNorm2d(256) self.pool4 = nn.MaxPool2d(2, 2) self.flatten = nn.Flatten() self.fc1 = nn.Linear(256 * 4 * 4, 512) self.dropout1 = nn.Dropout(0.4) self.fc2 = nn.Linear(512, 256) self.dropout2 = nn.Dropout(0.3) self.fc3 = nn.Linear(256, num_classes) def forward(self, x): x = self.pool1(torch.relu(self.bn1(self.conv1(x)))) x = self.pool2(torch.relu(self.bn2(self.conv2(x)))) x = self.pool3(torch.relu(self.bn3(self.conv3(x)))) x = self.pool4(torch.relu(self.bn4(self.conv4(x)))) x = self.flatten(x) x = self.dropout1(torch.relu(self.fc1(x))) x = self.dropout2(torch.relu(self.fc2(x))) x = self.fc3(x) return x #************************************************************* def predict_with_pytorch(image): # Defining the preprocessing pipeline preprocess = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) # Applying preprocessing transformations image = preprocess(image).unsqueeze(0) # Check if the image has the correct shape print(f"Image shape after preprocessing: {image.shape}") with torch.no_grad(): output = st.session_state.model(image) probabilities = F.softmax(output, dim=1) class_probabilities = probabilities.squeeze().tolist() predicted_classes = torch.argsort(probabilities, dim=1, descending=True) # # Return all classes and their probabilities result_dict = {} for idx, prob in zip(predicted_classes[0], class_probabilities): result_dict[idx.item()] = prob return result_dict #********************************************************** def load_pytorch_model(): # Example: Load a pre-trained model (e.g., ResNet18) model = torch.load('torch_model.pth', map_location=torch.device('cpu')) # Forces the model to load on CPU model.eval() return model #**************************************************************** # PYTORCH MODEL CONFIGURATION #**************************************************************** # Custom CSS to style the logo above the sidebar and other elements st.markdown( f""" """, unsafe_allow_html=True, ) st.markdown( """ """, unsafe_allow_html=True ) # Create the main content area with st.container(key="content-container-3"): col1,_, col2 = st.columns([2,4, 2]) with col1: if st.button(" Tensorflow"): st.session_state.model = load_tensorflow_model() st.session_state.choice = "tensorflow" with col2: if st.button(" Pytorch"): st.session_state.model = load_pytorch_model() st.session_state.choice = "pytorch" with st.container(key="content-container-1"): image_path = "Load.png" col1, col2 = st.columns([1, 9]) with col1: st.write("") with col2: st.write("") if st.session_state.choice == "tensorflow": st.markdown(f"""
Uploaded Image

Tensorflow Model Information

""", unsafe_allow_html=True) st.write("This is a Convolutional Neural Network (CNN) model trained on image data.") st.write(f"Input Shape: (64, 64, 3)") st.write(f"Output Classes: {4} classes") else : st.markdown(f"""
Uploaded Image

Pytorch Model Information

""", unsafe_allow_html=True) st.write("This is a Convolutional Neural Network (CNN) model trained on image data.") st.write(f"Input Shape: (64, 64, 3)") st.write(f"Output Classes: {4} classes") col3, col4 = st.columns([3, 7]) with col3: uploaded_file = st.file_uploader("Choose a file", type=["png", "jpg", "jpeg"],key="upload-btn") if uploaded_file is not None: with open(image_path, "rb") as image_file: encoded_image = base64.b64encode(image_file.read()).decode() # Display the circular container with the image inside st.markdown( f"""
Uploaded Image
""", unsafe_allow_html=True, ) else: default_image_path = "Load.png" with open(default_image_path, "rb") as image_file: encoded_image = base64.b64encode(image_file.read()).decode() # Display the circular container with the image inside st.markdown( f"""
Default Image
""", unsafe_allow_html=True, ) with col4: with st.container(key="content-container-2"): if uploaded_file != None: images = Image.open(uploaded_file) with st.spinner("Processing the image..."): progress_bar = st.progress(0) for i in range(1, 11): time.sleep(0.6) # Simulated delay for each progress increment progress_bar.progress(i * 10) if st.session_state.choice == "tensorflow": prediction = predict_image(images) max_index = int(np.argmax(prediction[0])) max_score = prediction[0][max_index] descriptive_message = "" if max_index == 0: descriptive_message = f""" This image is likely to represent a {class_labels[max_index]} kideney ,which is an indication of healthy tissue with no signs of abnormal growth. We recommend maintaining a healthy lifestyle and continuing regular health check-ups to ensure the body remains in a natural, healthy state. """ elif max_index == 1: descriptive_message = f""" This image is likely to represent a {class_labels[max_index]} kideney, which is a fluid-filled sac that forms in various body parts. Cysts are typically benign and may not require treatment unless they grow large or become infected. We recommend monitoring the cyst and consulting a healthcare provider if you notice any changes. """ elif max_index == 2: descriptive_message = f""" This image is likely to represent a {class_labels[max_index]} kideney, which is a solid mass that forms in organs like the kidneys or bladder due to crystallization of minerals or salts. Stones can be painful, and treatment may include passing them naturally or removing them surgically. We recommend staying hydrated and avoiding excessive salt intake to prevent stones from forming. """ else: descriptive_message = f""" This image is likely to represent a {class_labels[max_index]} kideney, which is an abnormal growth of tissue. Tumors can be benign or malignant, and further testing is required to determine the exact nature. We recommend consulting a healthcare provider for further investigation and treatment if necessary. """ if prediction is not None and len(prediction) > 0: # Check if prediction is valid divs = f"""

{class_labels[0]}

T Score: {prediction[0][0]:.2f}

{class_labels[1]}

T Score: {prediction[0][1]:.2f}

{class_labels[2]}

T Score: {prediction[0][2]:.2f}

{class_labels[3]}

T Score: {prediction[0][3]:.2f}

Prediction: {class_labels[max_index]} with confidence {prediction[0][max_index]:.2f}

{descriptive_message}

""" st.markdown(divs, unsafe_allow_html=True) else : predictions = predict_with_pytorch(images) predictiont =list( predictions.keys()) predicted_index = max(predictions, key=predictions.get) print(f"classe {predictions}") print(f"classes {predicted_index}") descriptive_message = "" if predicted_index == 0: descriptive_message = f""" This image is likely to represent a {class_labels[predicted_index]} kideney, which is an indication of healthy tissue with no signs of abnormal growth. We recommend maintaining a healthy lifestyle and continuing regular health check-ups to ensure the body remains in a natural, healthy state. """ elif predicted_index == 1: descriptive_message = f""" This image is likely to represent a {class_labels[predicted_index]} kideney, which is a fluid-filled sac that forms in various body parts. Cysts are typically benign and may not require treatment unless they grow large or become infected. We recommend monitoring the cyst and consulting a healthcare provider if you notice any changes. """ elif predicted_index == 2: descriptive_message = f""" This image is likely to represent a {class_labels[predicted_index]} kideney, which is a solid mass that forms in organs like the kidneys or bladder due to crystallization of minerals or salts. Stones can be painful, and treatment may include passing them naturally or removing them surgically. We recommend staying hydrated and avoiding excessive salt intake to prevent stones from forming. """ else: descriptive_message = f""" This image is likely to represent a {class_labels[predicted_index]} kideney, which is an abnormal growth of tissue. Tumors can be benign or malignant, and further testing is required to determine the exact nature. We recommend consulting a healthcare provider for further investigation and treatment if necessary. """ # Once preprocessing is done, show the content (grid in your case) if predictiont: st.markdown(f"""

{class_labels[predictiont[0]]}

T Score: {predictions[predictiont[0]]:.2f}

{class_labels[predictiont[1]]}

T Score: {predictions[predictiont[1]]:.2f}

{class_labels[predictiont[2]]}

T Score: {predictions[predictiont[2]]:.2f}

{class_labels[predictiont[3]]}

T Score: {predictions[predictiont[3]]:.2f}

Prediction: {class_labels[predicted_index]} with confidence {predictions[predicted_index]:.2f}

{descriptive_message}

""", unsafe_allow_html=True )