import cv2 import streamlit as st st.set_page_config(layout="wide") import streamlit.components.v1 as components import time import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.cm as cm from PIL import Image from tf_keras_vis.gradcam import Gradcam from io import BytesIO from sklearn.metrics import classification_report,confusion_matrix, roc_curve, auc,precision_recall_curve, average_precision_score from sklearn.preprocessing import label_binarize import seaborn as sns import torch import torch.nn as nn import torchvision.models as models from torchvision import datasets, transforms import torchvision.transforms as transforms import torch.nn.functional as F from gradcam import GradCAM # Import your GradCAM class if "model" not in st.session_state: st.session_state.model = tf.keras.models.load_model( "best_model.h5" ) if "framework" not in st.session_state: st.session_state.framework = "Tensorflow" if "menu" not in st.session_state: st.session_state.menu = "1" if st.session_state.menu =="1": st.session_state.show_summary = True st.session_state.show_arch = False st.session_state.show_desc = False elif st.session_state.menu =="2": st.session_state.show_arch = True st.session_state.show_summary = False st.session_state.show_desc = False elif st.session_state.menu =="3": st.session_state.show_arch = False st.session_state.show_summary = False st.session_state.show_desc = True else: st.session_state.show_desc = True import base64 import os import tf_keras_vis # ****************************************/ # GRAD CAM # *********************************************# if st.session_state.framework == "TensorFlow": gradcam = Gradcam(st.session_state.model, model_modifier=None, clone=False) def generate_gradcam(pil_image, target_class): # Convert PIL to array and preprocess img_array = np.array(pil_image) img_preprocessed = tf.keras.applications.vgg16.preprocess_input(img_array.copy()) img_tensor = tf.expand_dims(img_preprocessed, axis=0) # Generate heatmap loss = lambda output: tf.reduce_mean(output[:, target_class]) cam = gradcam(loss, img_tensor, penultimate_layer=-1) # Process heatmap cam = cam if cam.ndim > 2: cam = cam.squeeze() cam = np.maximum(cam, 0) cam = cv2.resize(cam, (224, 224)) cam = cam / cam.max() if cam.max() > 0 else cam return cam if st.session_state.framework == "PyTorch": target_layer = st.session_state.model.conv3 # Typically last convolutional layer #gradcam = GradCAM(st.session_state.model, target_layer) def preprocess_image(image): preprocess = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor() ]) return preprocess(image).unsqueeze(0) # Add batch dimension def generate_gradcams(image, target_class): # Preprocess the image and convert it to a tensor input_image = preprocess_image(image) # Instantiate GradCAM gradcampy = GradCAM(st.session_state.model, target_layer) # Generate the CAM cam = gradcampy.generate(input_image, target_class) return cam def convert_image_to_base64(pil_image): buffered = BytesIO() pil_image.save(buffered, format="PNG") return base64.b64encode(buffered.getvalue()).decode() #------------------------------------------------- #loading pytorch class KidneyCNN(nn.Module): def __init__(self, num_classes=4): super(KidneyCNN, self).__init__() # Convolutional layers self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1) self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1) self.conv4 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1) # Batch normalization layers self.bn1 = nn.BatchNorm2d(32) self.bn2 = nn.BatchNorm2d(64) self.bn3 = nn.BatchNorm2d(128) self.bn4 = nn.BatchNorm2d(256) # Max pooling layers self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) # Fully connected layers self.fc1 = nn.Linear(256 * 14 * 14, 512) self.fc2 = nn.Linear(512, num_classes) # Dropout for regularization self.dropout = nn.Dropout(0.5) def forward(self, x): # Conv block 1 x = self.pool(F.relu(self.bn1(self.conv1(x)))) # Conv block 2 x = self.pool(F.relu(self.bn2(self.conv2(x)))) # Conv block 3 x = self.pool(F.relu(self.bn3(self.conv3(x)))) # Conv block 4 x = self.pool(F.relu(self.bn4(self.conv4(x)))) x = x.view(x.size(0), -1) # Fully connected layers x = self.dropout(F.relu(self.fc1(x))) x = self.fc2(x) return x if st.session_state.framework =="PyTorch": st.session_state.model = torch.load('kidney_model .pth', map_location=torch.device('cpu')) st.session_state.model.eval() print(type(st.session_state.model)) #********************************************* # /#*********************************************/ # LOADING TEST DATASET # ************************************************* if st.session_state.framework == "TensorFlow": test_dir = "test" BATCH_SIZE = 32 IMG_SIZE = (224, 224) test_dataset = tf.keras.utils.image_dataset_from_directory( test_dir, shuffle=False, batch_size=BATCH_SIZE, image_size=IMG_SIZE ) class_names = test_dataset.class_names def one_hot_encode(image, label): label = tf.one_hot(label, num_classes) return image, label # One-hot encode labels using CategoryEncoding class_labels = class_names # One-hot encode labels using CategoryEncoding # One-hot encode labels using CategoryEncoding num_classes = len(class_names) test_dataset = test_dataset.map(one_hot_encode) elif st.session_state.framework == "PyTorch": test_dir = "test" BATCH_SIZE = 32 IMG_SIZE = (224, 224) transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) test_dataset = datasets.ImageFolder(root='test', transform=transform) class_names = test_dataset.classes # One-hot encode labels using CategoryEncoding class_labels = class_names # One-hot encode labels using CategoryEncoding # One-hot encode labels using CategoryEncoding num_classes = len(class_names) ####################################################### # --------------------------------------------------# class_labels = ["Cyst", "Normal", "Stone", "Tumor"] def load_tensorflow_model(): tf_model = tf.keras.models.load_model("best_model.h5") return tf_model if st.session_state.framework =="TensorFlow": def predict_image(image): time.sleep(2) image = image.resize((224, 224)) image = np.expand_dims(image, axis=0) predictions = st.session_state.model.predict(image) return predictions if st.session_state.framework == "PyTorch": logo_path = "pytorch.png" bg_color = "#FF5733" # For example, a warm red/orange bg_color_iv = "orange" # For example, a warm red/orange model = "TENSORFLOW" def predict_image(image): # Preprocess the image to match the model input requirements transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), # Standard VGG16 normalization ]) image = transform(image).unsqueeze(0) # Add batch dimension # Move image to the same device as the model (GPU or CPU) image = image # Set the model to evaluation mode st.session_state.model.eval() with torch.no_grad(): # Disable gradient calculation outputs = st.session_state.model(image) # Forward pass # Get predicted probabilities (softmax for multi-class) if outputs.shape[1] == 1: probs = torch.sigmoid(outputs) # Apply sigmoid activation for binary classification prob_class_1 = probs[0].item() # Probability for class 1 prob_class_0 = 1 - prob_class_1 # Probability for class 0 # If the output has two units (binary classification with softmax) else: probs = torch.nn.functional.softmax(outputs, dim=1) prob_class_0 = probs[0, 0].item() prob_class_1 = probs[0, 1].item() # Get the predicted class print("Raw model output (logits):", outputs) return prob_class_0, prob_class_1, probs else: logo_path = "tensorflow.png" bg_color = "orange" # For example, a warm red/orange bg_color_iv = "#FF5733" # For example, a warm red/orange model = "PYTORCH" #/*******************loading pytorch summary def get_layers_data(model, prefix=""): layers_data = [] for name, layer in model.named_children(): # Iterate over layers full_name = f"{prefix}.{name}" if prefix else name # Track hierarchy try: shape = str(list(layer.parameters())[0].shape) # Get shape of the first param except Exception: shape = "N/A" param_count = sum(p.numel() for p in layer.parameters()) # Count parameters layers_data.append((full_name, layer.__class__.__name__, shape, f"{param_count:,}")) # Recursively get layers inside this layer (for nested structures) layers_data.extend(get_layers_data(layer, full_name)) return layers_data ########################################### main_bg_ext = "png" main_bg = "bg1.jpg" # Read and encode the logo image with open(logo_path, "rb") as image_file: encoded_logo = base64.b64encode(image_file.read()).decode() # Custom CSS to style the logo above the sidebar st.markdown( f"""
T Score: {prediction[0][0]:.2f}
T Score: {prediction[0][1]:.2f}
T Score: {prediction[0][2]:.2f}
T Score: {prediction[0][3]:.2f}
Layer Name | Type | Output Shape | Param # |
---|---|---|---|
{name} | {layer_type} | {shape} | {params} |
T Score: {prediction[0][0]:.2f}
T Score: {prediction[0][1]:.2f}
T Score: {prediction[0][2]:.2f}
T Score: {prediction[0][3]:.2f}
T Score: {prediction[0][0]:.2f}
T Score: {prediction[0][1]:.2f}
T Score: {prediction[0][2]:.2f}
T Score: {prediction[0][3]:.2f}