CoolFace
Apppublic

danielle2003/transferlearning

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py612 linesDownload Raw Back to root
1import cv22import streamlit as st3st.set_page_config(layout="wide")4import streamlit.components.v1 as components5import time6import numpy as np7import tensorflow as tf8import matplotlib.pyplot as plt9import matplotlib.cm as cm10from PIL import Image11from tf_keras_vis.gradcam import Gradcam12from io import BytesIO13 14if "model" not in st.session_state:15    st.session_state.model = tf_model = tf.keras.models.load_model('best_model.h5')16import base6417import os18 19#****************************************/20#   GRAD CAM21#*********************************************#22 23gradcam = Gradcam(st.session_state.model, model_modifier=None, clone=False)24 25def generate_gradcam(pil_image, target_class):26    # Convert PIL to array and preprocess27    img_array = np.array(pil_image)28    img_preprocessed = tf.keras.applications.vgg16.preprocess_input(img_array.copy())29    img_tensor = tf.expand_dims(img_preprocessed, axis=0)30    31    # Generate heatmap32    loss = lambda output: tf.reduce_mean(output[:, target_class])33    cam = gradcam(loss, img_tensor, penultimate_layer=-1)34    35    # Process heatmap36    cam = cam37    if cam.ndim > 2:38        cam = cam.squeeze()39    cam = np.maximum(cam, 0)40    cam = cv2.resize(cam, (224, 224))41    cam = cam / cam.max() if cam.max() > 0 else cam42    return cam43 44def convert_image_to_base64(pil_image):45    buffered = BytesIO()46    pil_image.save(buffered, format="PNG")47    return base64.b64encode(buffered.getvalue()).decode()48 49 50#--------------------------------------------------#51class_labels=[ 'Cyst', 'Normal','Stone', 'Tumor']52def load_tensorflow_model():53    tf_model = tf.keras.models.load_model('best_model.h5')54    return tf_model55def predict_image(image):56    time.sleep(2)  57    image = image.resize((224, 224))  58    image = np.expand_dims(image, axis=0)  59    predictions = st.session_state.model.predict(image)60    return predictions61logo_path = "tensorflow.png"62main_bg_ext = 'png'63main_bg = 'bg1.jpg'64# Read and encode the logo image65with open(logo_path, "rb") as image_file:66    encoded_logo = base64.b64encode(image_file.read()).decode()67 68# Custom CSS to style the logo above the sidebar69st.markdown(70    f"""71    <style>72       /* Container for logo and text */73        .logo-text-container {{74            position: fixed;75            top: 20px; /* Adjust vertical position */76            left: 30px; /* Align with sidebar */77            display: flex;78            align-items: center;79            gap: 5px;80            width: 70%;81            z-index:1000;82        }}83 84        /* Logo styling */85        .logo-text-container img {{86            width: 50px; /* Adjust logo size */87            border-radius: 10px; /* Optional: round edges */88            margin-top:-10px;89            margin-left:-5px;90 91 92        }}93 94        /* Bold text styling */95        .logo-text-container h1 {{96            font-family: Nunito;97            color: #0175C2;            98            font-size: 28px;99            font-weight: bold;100            margin-right :100px;101            padding:0px;102        }}103         .logo-text-container i{{104             font-family: Nunito;105            color: orange;            106            font-size: 15px;107            margin-right :10px;108            padding:0px;109            margin-left:-18.5%;110            margin-top:1%;111         }}112        /* Sidebar styling */113        section[data-testid="stSidebar"][aria-expanded="true"] {{114            margin-top: 100px !important; /* Space for the logo */115            border-radius: 0 60px 0px 60px !important; /* Top-left and bottom-right corners */116            width: 200px !important; /* Sidebar width */117            background:none; /* Gradient background */118           /* box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); /* Shadow effect */119           /* border: 1px solid #FFD700; /* Shiny golden border */120            margin-bottom: 1px  !important;121            color:white !important;122 123        }}124        header[data-testid="stHeader"] {{125            /*background: transparent !important;*/126            background: white;127 128            /*margin-right: 10px !important;*/129            margin-top: 0.5px !important;130            z-index: 1 !important;131            132        color: orange; /* White text */133        font-family:  "Times New Roman " !important; /* Font */134        font-size: 18px !important; /* Font size */135        font-weight: bold !important; /* Bold text */136        padding: 10px 20px; /* Padding for buttons */137        border: none; /* Remove border */138        border-radius: 1px; /* Rounded corners */139        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); /* Shadow effect */140        transition: all 0.3s ease-in-out; /* Smooth transition */141        align-items: left;142        justify-content: center;143        /*margin: 10px 0;*/144        width:100%;145        height:80px;146        backdrop-filter: blur(10px);147        border: 2px solid rgba(255, 255, 255, 0.4); /* Light border */148 149        150        }}151         div[data-testid="stDecoration"]{{152        background-image:none;153        }}154        div[data-testid="stApp"]{{155        /*background: grey;*/156        background: rgba(255, 255, 255, 0.5);  /* Semi-transparent white background */157 158        height: 100vh;  /* Full viewport height */159        width: 99.5%; 160        border-radius: 2px !important;161        margin-left:5px;162        margin-right:5px;163        margin-top:0px;164      /*  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); /* Shadow effect */165 166        167        background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, "rb").read()).decode()});168          background-size: cover;  /* Ensure the image covers the full page */169          background-position: center;170 171        overflow: hidden;172        173        }}174        .content-container {{175            background-color: rgba(173, 216, 230, 0.5); /* Light blue with 50% transparency */176            backdrop-filter: blur(10px); /* Adds a slight blur effect */            border-radius: 1px;177            width: 28%;178            margin-left: 150px;179           /* margin-top: -60px;*/180            margin-bottom: 10px;181            margin-right:10px;182            padding:0;183           /* border-radius:0px 0px 15px 15px ;*/184            border:1px solid transparent;185            overflow-y: auto; /* Enable vertical scrolling for the content */186            position: fixed; /* Fix the position of the container */187            top: 10%; /* Adjust top offset */188            left: 60%; /* Adjust left offset */189            height: 89.5vh;  /* Full viewport height */190 191        }}192         .content-container2 {{193            background-color: rgba(0, 0, 0, 0.1); /* Light blue with 50% transparency */194            backdrop-filter: blur(10px); /* Adds a slight blur effect */            border-radius: 1px;195            width: 90%;196            margin-left: 10px;197           /* margin-top: -10px;*/198            margin-bottom: 160px;199            margin-right:10px;200            padding:0;201            border-radius:1px ;202            border:1px solid transparent;203            overflow-y: auto; /* Enable vertical scrolling for the content */204            position: fixed; /* Fix the position of the container */205            top: 3%; /* Adjust top offset */206            left: 2.5%; /* Adjust left offset */207            height: 78vh;  /* Full viewport height */208 209        }}210        .content-container4 {{211            background-color: rgba(0, 0, 0, 0.1); /* Light blue with 50% transparency */212            backdrop-filter: blur(10px); /* Adds a slight blur effect */                 width: 40%;213            margin-left: 10px;214            margin-bottom: 160px;215            margin-right:10px;216            padding:0;217            overflow-y: auto; /* Enable vertical scrolling for the content */218            position: fixed; /* Fix the position of the container */219            top: 60%; /* Adjust top offset */220            left: 2.5%; /* Adjust left offset */221            height: 10vh;  /* Full viewport height */222 223        }}224        .content-container4 h3 ,p {{225            font-family: "Times New Roman" !important; /* Elegant font for title */226            font-size: 1rem;227            font-weight: bold;228            text-align:center;229        }}230         .content-container5 h3 ,p {{231            font-family: "Times New Roman" !important; /* Elegant font for title */232            font-size: 1rem;233            font-weight: bold;234            text-align:center;235        }}236         .content-container6 h3 ,p {{237            font-family: "Times New Roman" !important; /* Elegant font for title */238            font-size: 1rem;239            font-weight: bold;240            text-align:center;241        }}242         .content-container7 h3 ,p {{243            font-family: "Times New Roman" !important; /* Elegant font for title */244            font-size: 1rem;245            font-weight: bold;246            text-align:center;247        }}248        .content-container5 {{249    background-color: rgba(0, 0, 0, 0.1); /* Light blue with 50% transparency */250            backdrop-filter: blur(10px); /* Adds a slight blur effect */                 width: 40%;251            margin-left: 180px;252            margin-bottom: 130px;253            margin-right:10px;254            padding:0;255            overflow-y: auto; /* Enable vertical scrolling for the content */256            position: fixed; /* Fix the position of the container */257            top: 60%; /* Adjust top offset */258            left: 5.5%; /* Adjust left offset */259            height: 10vh;  /* Full viewport height */260 261        }}262      .content-container3 {{263            background-color: rgba(216, 216, 230, 0.5); /* Light blue with 50% transparency */264            backdrop-filter: blur(10px); /* Adds a slight blur effect */            border-radius: 1px;265            width: 92%;266            margin-left: 10px;267           /* margin-top: -10px;*/268            margin-bottom: 160px;269            margin-right:10px;270            padding:0;271            border: 10px solid white;272            overflow-y: auto; /* Enable vertical scrolling for the content */273            position: fixed; /* Fix the position of the container */274            top: 3%; /* Adjust top offset */275            left: 1.5%; /* Adjust left offset */276            height: 40vh;  /* Full viewport height */277 278        }}279          .content-container6 {{280            background-color: rgba(0, 0, 0, 0.1); /* Light blue with 50% transparency */281            backdrop-filter: blur(10px); /* Adds a slight blur effect */                 width: 40%;282            margin-left: 10px;283            margin-bottom: 160px;284            margin-right:10px;285            padding:0;286            overflow-y: auto; /* Enable vertical scrolling for the content */287            position: fixed; /* Fix the position of the container */288            top: 80%; /* Adjust top offset */289            left: 2.5%; /* Adjust left offset */290            height: 10vh;  /* Full viewport height */291 292        }}293        .content-container7 {{294            background-color: rgba(0, 0, 0, 0.1); /* Light blue with 50% transparency */295            backdrop-filter: blur(10px); /* Adds a slight blur effect */                 width: 40%;296            margin-left: 180px;297            margin-bottom: 130px;298            margin-right:10px;299            padding:0;300            overflow-y: auto; /* Enable vertical scrolling for the content */301            position: fixed; /* Fix the position of the container */302            top: 80%; /* Adjust top offset */303            left: 5.5%; /* Adjust left offset */304            height: 10vh;  /* Full viewport height */305 306        }}307          .content-container2 img {{308              width:99%;309              height:50%;310            311              }}312          .content-container3 img {{313              width:100%;314              height:100%;315             316              }}317    div.stButton > button {{                318        background: rgba(255, 255, 255, 0.2);319        color: blue; /* White text */320        font-family:  "Times New Roman " !important; /* Font */321        font-size: 18px !important; /* Font size */322        font-weight: bold !important; /* Bold text */323        padding: 10px 20px; /* Padding for buttons */324        border: none; /* Remove border */325        border-radius: 15px; /* Rounded corners */326        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); /* Shadow effect */327        transition: all 0.3s ease-in-out; /* Smooth transition */328         display: flex;329        align-items: center;330        justify-content: center;331        margin: 10px 0;332        width:170px;333        height:60px;334        backdrop-filter: blur(10px);335 336    }}337 338    /* Hover effect */339    div.stButton > button:hover {{340        background: rgba(255, 255, 255, 0.2);341        box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.4); /* Enhanced shadow on hover */342        transform: scale(1.05); /* Slightly enlarge button */343        transform: scale(1.1); /* Slight zoom on hover */344        box-shadow: 0px 4px 12px rgba(255, 255, 255, 0.4); /* Glow effect */345    }}346  .titles{{347      margin-top:50px !important;348  }}349    /* Title styling */350    .titles h1{{351   /*font-family: "Times New Roman" !important; /* Elegant font for title */352   /* font-size: 2.9rem;*/353    /*font-weight: bold;*/354    margin-left: 5px;355   /* margin-top:-50px;*/356    margin-bottom:50px;357    padding: 0;358    color: black; /* Neutral color for text */359    }}360 .titles > div{{361   font-family: "Times New Roman" !important; /* Elegant font for title */362    font-size: 1.2rem;363    margin-left: 5px;364    margin-bottom:1px;365    padding: 0;366    color:black; /* Neutral color for text */367    }}368    /* Recently viewed section */369    .recently-viewed {{370    display: flex;371    align-items: center;372    justify-content: flex-start; /* Align items to the extreme left */373    margin-bottom: 10px;374    margin-top: 20px;375    gap: 10px; /* Add spacing between the elements */376    padding-left: 20px; /* Add some padding if needed */377    margin-left:35px;378    height:100px;379 380    }}381 382   383   384   385 386 /* Style for the upload button */387        [class*="st-key-upload-btn"] {{388            position: absolute;389            top: 100%; /* Position from the top of the inner circle */390            left: -3%; /* Position horizontally at the center */391            padding: 10px 20px;392            color: red;393            border: none;394            border-radius: 20px;395            cursor: pointer;396            font-size: 35px !important;397            width:30px;398            height:20px;399        }}400 401        .upload-btn:hover {{402            background-color: rgba(0, 123, 255, 1);403        }}404          div[data-testid="stFileUploader"] label > div > p {{405            display:none;406            color:white !important;407        }}408        section[data-testid="stFileUploaderDropzone"] {{409          width:200px;410        height: 60px;411        background-color: white;412        border-radius: 40px;413        display: flex;414        justify-content: center;415        align-items: center;416        margin-top:-10px;417        box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.3);418        margin:20px;419        background-color: rgba(255, 255, 255, 0.7); /* Transparent blue background */420        color:white;421        }}422        div[data-testid="stFileUploaderDropzoneInstructions"] div > small{{423           color:white !important;424           display:none;425        }}426         div[data-testid="stFileUploaderDropzoneInstructions"] span{{427          margin-left:65px;428          color:orange;429        }}430        div[data-testid="stFileUploaderDropzoneInstructions"] div{{431          display:none;432        }}433       section[data-testid="stFileUploaderDropzone"] button{{434        display:none;435       }}436         div[data-testid="stMarkdownContainer"] p {{437            font-family: "Times New Roman" !important; /* Elegant font for title */438            color:white !important;439        }}440        .highlight {{441        border: 4px solid lime;442        font-weight: bold;443        background: radial-gradient(circle, rgba(0,255,0,0.3) 0%, rgba(0,0,0,0) 70%);444        box-shadow: 0px 0px 30px 10px rgba(0, 255, 0, 0.9), 445                    0px 0px 60px 20px rgba(0, 255, 0, 0.6), 446                    inset 0px 0px 15px rgba(0, 255, 0, 0.8);447        transition: all 0.3s ease-in-out;448            449        }}450        .highlight:hover {{451        transform: scale(1.05);452        background: radial-gradient(circle, rgba(0,255,0,0.6) 0%, rgba(0,0,0,0) 80%);453        box-shadow: 0px 0px 40px 15px rgba(0, 255, 0, 1), 454                    0px 0px 70px 30px rgba(0, 255, 0, 0.7), 455                    inset 0px 0px 20px rgba(0, 255, 0, 1);456    }}457    </style>458<div class="logo-text-container">459<img src="data:image/png;base64,{encoded_logo}" alt="Logo">460<h1>KidneyScan AI<br>461 462</h1>463<i>Empowering Early Diagnosis with AI</ai>464 465 466</div>467    """, unsafe_allow_html=True468)469loading_html = """470<style>471.loader {472  border: 8px solid #f3f3f3;473  border-top: 8px solid #0175C2; /* Blue color */474  border-radius: 50%;475  width: 50px;476  height: 50px;477  animation: spin 1s linear infinite;478  margin: auto;479}480@keyframes spin {481  0% { transform: rotate(0deg); }482  100% { transform: rotate(360deg); }483}484 485</style>486<div class="loader"></div>487"""488 489page = "Home"490 491# Display content based on the selected page492# Define the page content dynamically493if page == "Home":494    495 496    #components.html(html_string)  # JavaScript works497    #st.markdown(html_string, unsafe_allow_html=True)498    image_path = "image.jpg"499 500    st.container()501    st.markdown(f"""502                    503                <div class="titles">504                    <h1>Kidney Disease Classfication</br> Using Transfer learning</h1>505                    <div> This web application utilizes deep learning to classify kidney ultrasound images</br>506                    into four categories: Normal, Cyst, Tumor, and Stone Class.507                    Built with Streamlit and powered by </br>a TensorFlow transfer learning508                    model based on <strong>VGG16</strong>509                     the app provides a simple and efficient way for users </br>510                    to upload kidney scans and receive instant predictions. The model analyzes the image511                    and classifies it based </br>on learned patterns, offering a confidence score for better interpretation.  512                   </div>513                    </div>514                """,515                    unsafe_allow_html=True,516                )517    uploaded_file = st.file_uploader("Choose a file", type=["png", "jpg", "jpeg"],key="upload-btn")518    if uploaded_file is not None:    519        images = Image.open(uploaded_file)520# Rewind file pointer to the beginning521        uploaded_file.seek(0)522    523        file_content = uploaded_file.read()  # Read file once524# Convert to base64 for HTML display525        encoded_image = base64.b64encode(file_content).decode()526      # Read and process image527        pil_image = Image.open(uploaded_file).convert('RGB').resize((224, 224))528        img_array = np.array(pil_image)529    530        prediction = predict_image(images)531        max_index = int(np.argmax(prediction[0]))532        print(f"max index:{max_index}")533        max_score = prediction[0][max_index]534        predicted_class = np.argmax(prediction[0])535 536        highlight_class = "highlight"  # Special class for the highest confidence score537 538         539    # Generate Grad-CAM540        cam = generate_gradcam(pil_image, predicted_class)541        542        # Create overlay543        heatmap = cm.jet(cam)[..., :3]544        heatmap = (heatmap * 255).astype(np.uint8)545        overlayed_image = cv2.addWeighted(img_array, 0.6, heatmap, 0.4, 0)546    547        # Convert to PIL548        overlayed_pil = Image.fromarray(overlayed_image)549        # Convert to base64550        orig_b64 = convert_image_to_base64(pil_image)551        overlay_b64 = convert_image_to_base64(overlayed_pil)552        content = f"""553            <div class="content-container">554                <!-- Title -->555                <!-- Recently Viewed Section -->556                <div class="content-container2">557                <div class="content-container3">558               <img src="data:image/png;base64,{orig_b64}" alt="Uploaded Image">559                    </div>560                <div class="content-container3">561                <img src="data:image/png;base64,{overlay_b64}" class="result-image">562                </div>563                 <div class="content-container4 {'highlight' if max_index == 0 else ''}">564                  <h3>{class_labels[0]}</h3>565                  <p>T Score: {prediction[0][0]:.2f}</p>566                </div>567                <div class="content-container5 {'highlight' if max_index == 1 else ''}">568                 <h3> {class_labels[1]}</h3>569                 <p>T Score: {prediction[0][1]:.2f}</p>570                </div>571                 <div class="content-container6 {'highlight' if max_index == 2 else ''}">572                 <h3> {class_labels[2]}</h3>573                 <p>T Score: {prediction[0][2]:.2f}</p>574                </div>575                <div class="content-container7 {'highlight' if max_index == 3 else ''}">576                 <h3>{class_labels[3]}</h3>577                 <p>T Score: {prediction[0][3]:.2f}</p>578                </div>579                580 581        """582    583    # Close the gallery and content div584 585    # Render the content586        placeholder = st.empty()  # Create a placeholder587        placeholder.markdown(loading_html,unsafe_allow_html=True)588        time.sleep(5)  # Wait for 5 seconds589        placeholder.empty()590        st.markdown(content, unsafe_allow_html=True)591    else:592        default_image_path = "image.jpg"  593        with open(image_path, "rb") as image_file:594            encoded_image = base64.b64encode(image_file.read()).decode()595 596 597            st.markdown(f"""             598                <div class="content-container">599                <!-- Title -->600                <!-- Recently Viewed Section -->601                <div class="content-container2">602                <div class="content-container3">603                 <img src="data:image/png;base64,{encoded_image}" alt="Default Image">604                </div>605                </div>606 607                """,608                    unsafe_allow_html=True,609                )610                 611    612