ml-in-cloud-ca / app.py
danielle2003's picture
Update app.py
6228c9c verified
import streamlit as st
import os
from PIL import Image
# Set the page layout
st.set_page_config(layout="wide")
import json
import base64
import time
from dotenv import load_dotenv
import os
import requests
import pickle
import numpy as np
# Load model once
with open("best_clf.pkl", "rb") as file:
best_clf = pickle.load(file)
# Try loading environment variables locally
try:
from dotenv import load_dotenv
load_dotenv()
except:
pass
# Get the token from environment variables
HF_TOKEN = os.environ.get("HF_TOKEN")
def query_huggingface_model(selected_model: dict, input_data, input_type="text",max_tokens=512,task="text-classification",temperature=0.7, top_p=0.9 ):
API_URL = selected_model.get("url")
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
try:
if input_type == "text":
if task == "text-generation":
payload = {
"messages": [
{
"role": "user",
"content": input_data
}
],
"model":selected_model.get("model")
}
else:
payload = {
"inputs": input_data ,
}
response = requests.post(API_URL, headers=headers, json=payload)
elif input_type == "image":
with open(input_data, "rb") as f:
data = f.read()
response = requests.post(API_URL, headers=headers, data=data)
else:
return {"error": f"Unsupported input_type: {input_type}"}
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
def extract_response_content(response):
print(f"Response is: {response}")
# For text generation or image captioning
if isinstance(response, list):
if response and isinstance(response[0], dict) and "generated_text" in response[0]:
return response[0]["generated_text"]
elif response and isinstance(response[0], list) and "label" in response[0][0]:
# For text classification
return [(item["label"], round(item["score"], 3)) for item in response[0]]
# For OpenAI-style chat responses
elif isinstance(response, dict):
if "choices" in response and isinstance(response["choices"], list):
try:
return response["choices"][0]["message"]["content"]
except (KeyError, IndexError, TypeError):
return "Error: Could not extract message from choices"
elif "error" in response:
return f"Error: {response['error']}"
return "Unknown response format"
# --- Step 1 ---
if 'name' not in st.session_state:
st.session_state.name = "Paul"
if 'gender' not in st.session_state:
st.session_state.gender = "Male"
if 'age' not in st.session_state:
st.session_state.age = 25
if 'currentSmoker' not in st.session_state:
st.session_state.currentSmoker = "Yes"
if 'cigsPerDay' not in st.session_state:
st.session_state.cigsPerDay = 0
if 'BPMeds' not in st.session_state:
st.session_state.BPMeds = False
if 'diabetes' not in st.session_state:
st.session_state.diabetes = False
# --- Step 2 ---
if 'totChol' not in st.session_state:
st.session_state.totChol = 180 # mg/dL
if 'sysBP' not in st.session_state:
st.session_state.sysBP = 120 # mmHg
if 'diaBP' not in st.session_state:
st.session_state.diaBP = 80 # mmHg
# --- Step 3 ---
if 'BMI' not in st.session_state:
st.session_state.BMI = 22.0
if 'heartRate' not in st.session_state:
st.session_state.heartRate = 70 # bpm
if 'glucose' not in st.session_state:
st.session_state.glucose = 90 # mg/dL
# Optional: prediction result
if 'Risk' not in st.session_state:
st.session_state.Risk = 1
if 'proba' not in st.session_state:
st.session_state.proba = 80
if "framework" not in st.session_state:
st.session_state.framework = "gen"
# Initialize state
if "form1" not in st.session_state:
st.session_state.form1 = "back"
if "form2" not in st.session_state:
st.session_state.form2 = "back"
if "form3" not in st.session_state:
st.session_state.form3 = "back"
if "form4" not in st.session_state:
st.session_state.form4 = "back"
if "form5" not in st.session_state:
st.session_state.form5 = "back"
if "form6" not in st.session_state:
st.session_state.form6 = "back"
if st.session_state.form1 == "next":
start1 = 46
back1 = "#6dc9e4"
background = "#f3f3f4"
fill = '#6dc9e4'
back2 = "#4794ff"
back3 = "#6dc9e4"
back4 = "#6dc9e4"
elif st.session_state.form1 == "back":
start1 = 0
back1 = "#4794ff"
back2 = "#6dc9e4"
back3 = "#6dc9e4"
back4 = "#6dc9e4"
background =" white"
fill = "#f7f7f7"
##################################
if st.session_state.form2 == "next":
start2 = 46
background2 = "#f3f3f4"
fill2 = '#6dc9e4'
back3 = "#4794ff"
back2 = "#6dc9e4"
back1 = "#6dc9e4"
back4 = "#6dc9e4"
elif st.session_state.form2 == "back":
start2 = 0
background2 =" white"
fill2 = "#f7f7f7"
####################################
if st.session_state.form3 == "next":
start3 = 46
background3 = "#f3f3f4"
back4 = "#4794ff"
back2 = "#6dc9e4"
back1 = "#6dc9e4"
back3 = "#6dc9e4"
fill3 = '#6dc9e4'
border = "grey"
elif st.session_state.form3 == "back":
start3 = 0
background3 =" white"
fill3 = "#f7f7f7"
####################################
if st.session_state.form4 == "next":
start4 = 46
background4 = "#f3f3f4"
fill4 = '#6dc9e4'
back4 = "#6dc9e4"
elif st.session_state.form4 == "back":
start4 = 0
background4 =" white"
fill4 = "#f7f7f7"
if st.session_state.framework == "gen":
encoded_logo = "hugging.png"
main_bg_ext = "png"
main_bg = "image.gif"
st.markdown(
f"""
<style>
/* Container for logo and text */
/* Container for logo and text */
.logo-text-container {{
position: fixed;
top: 20px; /* Adjust vertical position */
left: 30px; /* Align with sidebar */
display: flex;
align-items: center;
gap: 10px;
width: 70%;
z-index:1000;
}}
/* Logo styling */
.logo-text-container img {{
width: 90px; /* Adjust logo size */
border-radius: 10px; /* Optional: round edges */
margin-left:-5px;
margin-top: -15px;
}}
/* Bold text styling */
.logo-text-container h1 {{
font-family: Nunito;
color: #0175C2;
font-size: 20px;
font-weight: bold;
margin-left :-30px;
padding:0px;
top:0;
margin-top: 10px;
}}
.logo-text-container h1 span{{
font-family: Nunito;
color: green;
font-size: 20px;
margin-right :10px;
font-weight: bold;
padding:0px;
margin-left:1px;
margin-top:2% !important;
}}
/* Sidebar styling */
section[data-testid="stSidebar"][aria-expanded="true"] {{
margin-top: 100px !important; /* Space for the logo */
border-radius: 0 60px 0px 60px !important; /* Top-left and bottom-right corners */
width: 300px !important; /* Sidebar width */
background: none; /* No background */
color: white !important;
}}
header[data-testid="stHeader"] {{
background: #e4f8f8 !important;
margin-left: -80px !important;
margin-top: 1px !important;
z-index: 1 !important;
color: blue; /* White text */
font-family: "Times New Roman " !important; /* Font */
font-size: 18px !important; /* Font size */
font-weight: bold !important; /* Bold text */
padding: 10px 20px; /* Padding for buttons */
border-top-left-radius: 30px;
border-top-right-radius: 30px;
transition: all 0.3s ease-in-out; /* Smooth transition */
display: flex;
align-items: center;
justify-content: center;
margin: 10px 0;
width:100% !important;
left:5.5%;
height:420px;
margin-top:30px;
backdrop-filter: blur(10px);
}}
div[data-testid="stDecoration"] {{
background-image: none;
}}
div[data-testid="stApp"] {{
background-size: cover; /* Ensure the image covers the full page */
background-position: center;
background-repeat:no-repeat;
height: 98vh;
width: 99.3%;
border-radius: 20px !important;
margin-left: 5px;
margin-right: 20px;
margin-top: 10px;
overflow: hidden;
backdrop-filter: blur(10px); /* Glass effect */
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2); /* Light border */
border-radius:25px;
}}
[class*="st-key-main"] {{
position: absolute;
width: 85vw !important;
margin-left: 50px;
z-index:10000000;
border-radius:30px;
padding: 10px;
margin-top:-20px;
background:white;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); /* Shadow effect */
height: 61vh;
width: 95.3%;
}}
[class*="st-key-side"] {{
position: absolute;
width: 40vw !important;
margin-left: 5px;
z-index:10000000;
border-radius:30px;
padding: 10px;
background-image: url(data:image/png;base64,{base64.b64encode(open('back.gif', "rb").read()).decode()});
margin-top:10px;
background-size: cover; /* Ensure the image covers the full page */
background-position: center;
background-repeat:no-repeat;
box-shadow: -5px 0px 10px rgba(0, 0, 0, 0.1); /* Shadow on the left */
height: 56vh;
border-bottom-right-radius: 0px ;
border-top-right-radius: 0px ;
border-left:2px solid #4794ff;
border-right:2px solid #4794ff;
width: 95.3%;
}}
.result{{
}}
.result h3{{
font-family: "Times New Roman" !important;
font-size:16px;
margin-top:-30px;
}}
[class*="st-key-result"]{{
height: 56vh;
border-radius:30px;
margin-top:10px;
position:absolute;
margin-left:-5px !important;
box-shadow: 6px 0px 10px rgba(0, 0, 0, 0.1);
border-right:2px solid #4794ff;
}}
[class*="st-key-explain"]{{
background-image: url(data:image/png;base64,{base64.b64encode(open("gem.jpg", "rb").read()).decode()});
background-size: contain; /* size of the image */
background-repeat: no-repeat;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); /* Shadow effect */
width:250px;
margin-left:370px;
border-radius: 30px;
height:50px !important;
margin-top:50px;
border-right:2px solid #4794ff;
border-left:2px solid #4794ff;
}}
[class*="st-key-explain"] > div.stButton > button{{
width:300px;
background: transparent;
border-radius:35px;
height:30px;
}}
[class*="st-key-explain"] > div.stButton > button p{{
margin-left:5px;
color :#0175C2 !important;
align-item:center;
font-size:14px !important;
margin-top:5px;
}}
[class*="st-key-explain"] > div.stButton{{
border-radius:35px;
}}
[class*="st-key-expert"]{{
overflow-y:scroll;
max-height:380px;
}}
[class*="st-key-step_"] {{
width:100px;
height:60px;
border-radius:50px;
margin-left:490px;
margin-bottom:20px;
margin-top:15px;
}}
[class*="st-key-step_1"] {{
background:{background};
border:2px solid {back1};
padding-left:{start1}px;
}}
[class*="st-key-step_2"] {{
border:2px solid {back2};
background:{background2};
padding-left:{start2}px;
}}
[class*="st-key-step_3"] {{
border:2px solid {back3};
background:{background3};
padding-left:{start3}px;
}}
[class*="st-key-step_4"] {{
border:2px solid {back4};
background:{background4};
padding-left:{start4}px;
}}
[class*="st-key-step_1"] > div.stButton > button{{
background:{fill} !important;
border:2px solid #00e7df;
}}
[class*="st-key-step_2"] > div.stButton > button{{
background:{fill2} !important;
border:2px solid #00e7df;
}}
[class*="st-key-step_3"] > div.stButton > button{{
background:{fill3} !important;
border:2px solid #00e7df;
}}
[class*="st-key-step_4"] > div.stButton > button{{
background:{fill4} !important;
border:2px solid #00e7df;
}}
[class*="st-key-step_"] > div.stButton > button{{
background:#e7e7e7;
border:2px solid linear-gradient(145deg, #007BFF, #005FCC);
}}
[class*="st-key-step_"] > div.stButton > button:active{{
border:2px solid green !important;
}}
[class*="st-key-step_"] > div.stButton > button:not(:active){{
border:2px solid #00e7df !important;
}}
section[data-testid="stMain"] {{
overflow:hidden !important;
}}
div[data-testid="stSlider"] {{
margin-top:45px;
}}
label[data-testid="stWidgetLabel"]{{
margin-left:20px !important;
}}
div[data-baseweb="slider"] {{
border-radius: 30px;
padding-right:40px;
z-index: 1;
/* Glass effect background */
backdrop-filter: blur(2px);
-webkit-backdrop-filter: blur(12px);
/* Shiny blue borders (left & right) */
border-top: 2px solid rgba(255, 255, 155, 0.4); /* Light border */
margin-left:13px;
border-bottom: 2px solid rgba(255, 255, 155, 0.4); /* Light border */
}}
div[data-baseweb="slider"] > :nth-child(1)> div {{
margin-left:20px !important;
margin-top:10px;
}}
div[data-testid="stSliderTickBarMin"]{{
background:none !important;
margin-left:20px !important;
font-size:12px;
margin-bottom:5px;
font-family: "Times New Roman " !important; /* Font */
}}
div[data-testid="stSliderTickBarMax"]{{
background:none !important;
font-size:12px;
margin-bottom:5px;
font-family: "Times New Roman " !important; /* Font */
}}
div[data-testid="stSliderThumbValue"]{{
font-size:12px;
font-family: "Times New Roman " !important; /* Font */
}}
div[data-testid="stProgress"]{{
margin-right:25px;
margin-top:-70px;
height:10px !important;
}}
[class*="st-key-content-container-3"] {{
margin-top: 50px; /* Adjust top margin */
margin-left:500px !important;
color:orange;
font-size:2.2rem;
}}
div[data-testid="stForm"]{{
}}
[class*="st-key-form-head"] {{
margin-top:-50px;
}}
[class*="st-key-form-head"] img {{
align-self:center;
width:40%;
margin-left:250px;
height:120px;
}}
[class*="st-key-form-content"] {{
margin-top:-65px;
height:405px;
border-radius:35px;
}}
[class*="st-key-form-content1"] {{
margin-top:5px;
height:405px;
border-radius:35px;
margin-bottom:15px;
border-top:none;
}}
[class*="st-key-currentSmoker"]>div>label>div > p {{
margin-left:-20px;
}}
[class*="st-key-form-content2"] {{
margin-top:5px;
height:405px;
border-radius:35px;
margin-bottom:15px;
}}
[class*="st-key-form-content3"] {{
margin-top:5px;
height:405px;
border-radius:35px;
margin-bottom:15px;
}}
/* Button row styling */
.button-row {{
display: flex;
justify-content: flex-start;
gap: 20px;
margin-bottom: 20px;
}}
.custom-button:hover {{
background-color: #0056b3;
}}
div.stButton > button p{{
color: green !important;
font-weight:bold;
}}
div.stButton > button {{
color: green !important; /* White text */
font-family: "Times New Roman " !important; /* Font */
font-size: 18px !important; /* Font size */
font-weight: bold !important; /* Bold text */
padding: 10px 20px; /* Padding for buttons */
border: none; /* Remove border */
border-radius: 35px; /* Rounded corners */
transition: all 0.3s ease-in-out; /* Smooth transition */
display: flex;
align-items: center;
transform: scale(1.05); /* Slightly enlarge button */
transform: scale(1.1); /* Slight zoom on hover */
justify-content: center;
}}
/* Hover effect */
div.stButton > button:hover {{
background: rgba(255, 255, 255, 0.2);
box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.4); /* Enhanced shadow on hover */
transform: scale(1.05); /* Slightly enlarge button */
transform: scale(1.1); /* Slight zoom on hover */
box-shadow: 0px 4px 12px rgba(255, 255, 255, 0.4); /* Glow effect */
}}
div[data-testid="stFormSubmitButton"] button{{
font-family: "Times New Roman " !important; /* Font */
font-size: 18px !important; /* Font size */
font-weight: bold !important; /* Bold text */
padding: 10px 20px; /* Padding for buttons */
border: none; /* Remove border */
border-radius: 35px; /* Rounded corners */
transition: all 0.3s ease-in-out; /* Smooth transition */
display: flex;
align-items: center;
transform: scale(1.05); /* Slightly enlarge button */
transform: scale(1.1); /* Slight zoom on hover */
justify-content: center;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); /* Shadow effect */
width:110px;
}}
div[data-testid="stFormSubmitButton"] button:active{{
background-color: #6dc9e4 !important;
}}
div[data-testid="stMarkdownContainer"] p {{
font-family: "Times New Roman" !important; /* Elegant font for title */
color:black !important;
}}
.titles{{
margin-top:-60px !important;
margin-left:40px;
margin-bottom:50px;
text-align:center;
align-items:center;
z-index:10000;
position:relative;
font-family: "Times New Roman" !important;
}}
.header {{
align-items: center;
gap: 20px; /* Optional: adds space between image and text */
}}
/* Title styling */
.header h1{{
font-size: 1.7rem;
font-weight: bold;
margin-left: 5px;
/* margin-top:-100px;*/
margin-bottom:10px;
padding: 0;
color: black; /* Neutral color for text */
}}
.titles .content{{
font-family: "Times New Roman" !important; /* Elegant font for title */
font-size: 1rem;
margin-bottom:1px;
padding: 0;
color:black; /* Neutral color for text */
}}
</style>
""",
unsafe_allow_html=True,
)
# Overlay container
st.markdown(
f"""
<style>
.logo-text-containers {{
position: absolute;
top: -60px;
right: 40px;
background-color: rgba(255, 255, 255, 0.9);
padding: 15px;
border-radius: 12px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
z-index: 10;
width:80vw;
height:620px;
}}
.logo-text-containers img {{
height: 40px;
right:0;
}}
.logo-text-containers h1 {{
display: inline;
font-size: 20px;
vertical-align: middle;
}}
div[class*="st-key-try"] >div>button > div >p{{
top: 5px;
font-size: 30px !important;
font-weight: bold !important;
cursor: pointer;
color:orange !important;
z-index:1000;
}}
div[class*="st-key-try"] >div>button {{
height:70px !important;
width:250px !important;
background: rgba(255, 255, 255, 0.2) !important;
backdrop-filter: blur(10px) !important;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2); /* Shadow effect */
margin-left:20px;
}}
[class*="st-key-close-btn"]:hover {{
color: #f00;
}}
[class*="st-key-divider-col"] {{
border-left: 3px solid rgba(255, 255, 155, 0.5); /* Light border */
border-radius: 35px; /* Rounded corners */
margin-top:-15px;
margin-left:3px;
}}
[class*="st-key-col1"] {{
border-right: 3px solid rgba(255, 255, 155, 0.5); /* Light border */
border-radius: 35px; /* Rounded corners */
margin-left:20px;
margin-top:-15px;
}}
[class*="st-key-form"] >div >div >div >p {{
font-weight:bold;
color :green !important;
font-size:20px;
}}
[class*="st-key-logo-text-containers"] {{
margin: 10px; /* Set a margin inside the container */
max-width: 100%;
overflow: hidden;
position: absolute;
top:-43px;
left:10px;
overflow: hidden;
background-color: tansparent;
padding: 15px;
border-radius: 30px;
padding-right:40px;
z-index: 1;
width:88vw;
height:660px;
/* Glass effect background */
background: rgba(255, 255, 255, 0.15);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
/* Shiny blue borders (left & right) */
border-left: 3px solid rgba(255, 255, 255, 0.9); /* Light border */
border-right: 3px solid rgba(255, 255, 255, 0.9); /* Light border */
}}
@media (max-width: 768px) {{
.logo-text-container h1 {{
font-size: 12px;
}}
.logo-text-container i {{
font-size: 10px;
ma
}}
.logo-text-container img {{
width: 30px; /* Adjust logo size */
border-radius: 10px; /* Optional: round edges */
margin-left:15px;
margin-top: -35px;
}}
}}
</style>
""",
unsafe_allow_html=True,
)
st.markdown("""
<style>
/* Number input */
input:focus {
/* border: 2px solid grey !important; /* change to your desired color */
outline: none;
}
/* Radio buttons (kind of hacky since they use labels) */
.stRadio > div[role='radiogroup'] > label:focus-within {
border-radius: 4px;
}
div[data-testid="stTextInputRootElement"]{
border:1px solid #CCC;
}
div[data-testid="stNumberInputContainer"].focused{
border:1px solid #CCC !important;
}
button[data-testid="stNumberInputStepDown"]:hover:enabled,
button[data-testid="stNumberInputStepDown"]:focus:enabled{
background-color: #6dc9e4 !important;
}
button[data-testid="stNumberInputStepUp"]:hover:enabled,
button[data-testid="stNumberInputStepUp"]:focus:enabled{
background-color: #6dc9e4 !important;
}
label[data-baseweb="radio"]> :nth-child(1){
background-color: #6dc9e4 !important;
}
</style>
""", unsafe_allow_html=True)
st.markdown(
f""" <div class="logo-text-container">
<img src="data:image/png;base64,{base64.b64encode(open("download.png","rb").read()).decode()}" alt="Uploaded Image">
<h1>HeartCheck <span> AI </span> </h1>
</div>
""",
unsafe_allow_html=True,
)
st.markdown(
f""" <div class="titles">
<div class = "header">
<h1></br><span>Predict Your Risk, Protect Your Heart
</h1>
</div>
<div class="content">
HeartCheck uses intelligent risk analysis to predict your likelihood of <br>heart disease.
β€”empowering you with personalized insights, early warnings, and lifestyle tips to keep your heart healthy and strong.
</div>
</div>
""",
unsafe_allow_html=True,
)
with st.container(key = "main"):
col1,col2 = st.columns([3,3])
with col1:
with st.container(key= "side"):
if st.button("1",key="step_1"):
st.session_state.form1 = "back"
st.session_state.form2 = "back"
st.session_state.form3 = "back"
st.session_state.form4 = "back"
st.session_state.form5 = "back"
st.rerun()
if st.button("2",key="step_2"):
st.session_state.form2 = "back"
st.session_state.form3 = "back"
st.session_state.form4 = "back"
st.session_state.form5 = "back"
st.rerun()
if st.button("3",key="step_3"):
st.session_state.form3 = "back"
st.session_state.form4 = "back"
st.session_state.form5 = "back"
st.rerun()
if st.button("4",key="step_4"):
st.session_state.form4 = "back"
st.session_state.form5 = "back"
st.rerun()
with col2:
if st.session_state.form1 == "back":
with st.container(key="form1"):
st.write("🧍 Step 1: Personal Info")
with st.container(key="form-head"):
st.image("icon.png")
with st.form( key="first"):
with st.container(key="form-content"):
# Input fields
st.session_state.name = st.text_input("Name", value=st.session_state.name)
st.session_state.age = st.number_input("Age", min_value=0, max_value=120, step=1, value=st.session_state.age)
st.session_state.gender = st.radio("Sex:", ["Male", "Female"], horizontal=True, index=0 if st.session_state.gender == "Male" else 1)
# Navigation buttons
col1, col2 = st.columns([4, 1])
next = col2.form_submit_button("Next ")
if next:
st.session_state.form1 = "next"
st.rerun()
elif st.session_state.form1 == "next" and st.session_state.form2 == "back":
with st.container(key="form2"):
st.write("🚬 Step 2: Clinical History")
st.radio("Do you currently smoke?", ["Yes", "No"], horizontal=True, key="currentSmoker")
print(st.session_state.currentSmoker)
with st.form("form_step_2"):
with st.container(key="form-content1"):
# Show 'cigsPerDay' only if smoker
if st.session_state.currentSmoker == "Yes":
if st.session_state.cigsPerDay == 0:
st.session_state.cigsPerDay = 1
else:
st.session_state.cigsPerDay = st.session_state.cigsPerDay
print(f"tessst:{st.session_state['currentSmoker']}")
st.session_state.cigsPerDay = st.number_input("How many cigarettes per day?", min_value=1, max_value=60, step=1,value = st.session_state.cigsPerDay)
else:
st.session_state.cigsPerDay = 0 # default to 0 if non-smoker
r1,r2 = st.columns([6,3])
with r1:
if st.session_state.BPMeds == "Yes":
bp = 0
else:
bp = 1
st.session_state.BPMeds = st.radio("Do you take blood pressure medication?", ["Yes", "No"], horizontal=True,index = bp)
with r2:
if st.session_state.diabetes == "Yes":
db = 0
else:
db = 1
st.session_state.diabetes = st.radio("Do you have diabetes?", ["Yes", "No"], horizontal=True,index = db )
col1, col2 = st.columns([4,1])
back = col1.form_submit_button("Back")
if back:
st.session_state.form1 = "back"
st.rerun()
next = col2.form_submit_button("Next")
if next:
st.session_state.form2 = "next"
st.rerun()
elif st.session_state.form2 == "next" and st.session_state.form3 == "back":
with st.container(key="form2"):
st.write("πŸ’‰ Step 3: Vital Signs & Cholesterol")
with st.form("form_step_2"):
with st.container(key="form-content2"):
# Step 3 inputs
st.session_state.totChol = st.number_input("Total Cholesterol (mg/dL)", min_value=100, max_value=400, step=1,value= st.session_state.totChol)
st.session_state.sysBP = st.number_input("Systolic Blood Pressure (mmHg)", min_value=80, max_value=250, step=1,value = st.session_state.sysBP)
st.session_state.diaBP = st.number_input("Diastolic Blood Pressure (mmHg)", min_value=50, max_value=150, step=1,value= st.session_state.diaBP)
col1, col2 = st.columns([4,1])
back = col1.form_submit_button("Back")
if back:
st.session_state.form2 = "back"
st.rerun()
next = col2.form_submit_button("Next")
if next:
st.session_state.form3 = "next"
st.rerun()
elif st.session_state.form3 == "next" and st.session_state.form4 == "back":
with st.container(key="form3"):
st.write("πŸ§ͺ Step 4: Body Metrics & Glucose")
with st.form("form_step_3"):
with st.container(key="form-content3"):
# Step 3 inputs
st.session_state.BMI = st.number_input("Body Mass Index (BMI)", min_value=10.0, max_value=60.0, step=0.1,value=st.session_state.BMI)
st.session_state.heartRate = st.number_input("Heart Rate (bpm)", min_value=40, max_value=200, step=1,value= st.session_state.heartRate)
st.session_state.glucose = st.number_input("Glucose Level (mg/dL)", min_value=50, max_value=300, step=1,value= st.session_state.glucose)
col1, col2 = st.columns([4,1])
back = col1.form_submit_button("Back")
if back:
st.session_state.form3 = "back"
st.rerun()
next = col2.form_submit_button("predict")
if next:
st.session_state.form4 = "next"
st.rerun()
elif st.session_state.form4 == "next" and st.session_state.form5 == "back":
# Construct input array from collected values
new_data = np.array([[
1 if st.session_state.gender == "Male" else 0, # gender
st.session_state.age,
1 if st.session_state.currentSmoker == "Yes" else 0,
float(st.session_state.cigsPerDay),
1.0 if st.session_state.BPMeds else 0.0,
1 if st.session_state.diabetes else 0,
st.session_state.totChol,
st.session_state.sysBP,
st.session_state.diaBP,
st.session_state.BMI,
st.session_state.heartRate,
st.session_state.glucose
]])
loading_placeholder = st.empty()
with loading_placeholder.container():
# Make prediction
with st.spinner("Analyzing your heart health..."):
st.image('load.gif', use_container_width=True)
time.sleep(3) # Wait for 1 second
# Remove the loading image
loading_placeholder.empty()
prediction = best_clf.predict(new_data)
prediction_proba = best_clf.predict_proba(new_data)
st.session_state.Risk = prediction
risk_percent = prediction_proba[0][1]*100
risk_label = "At Risk of having a heart failure"
st.session_state.proba = risk_percent
name = st.session_state.name # Get from session or fallback
with st.container(key = "result"):
# Display result
st.markdown(f"""
<div class = "result" style="text-align: center; padding-top: 30px;">
<h1 style="color: #444;">Hi {name} πŸ‘‹, you are</h1>
<h1 class = "name" style="font-size: 80px; color: #0175C2; margin-top: -5px ;">{risk_percent:.2f}%</h1>
<h3 style="color: {'#d9534f' if prediction == 1 else '#28a745'}; margin-bottom: 10px;">{risk_label}</h3>
</div>
""", unsafe_allow_html=True)
st.session_state.form5 = "next"
if st.button("explain the result", key = "explain"):
st.session_state.form5 = "next"
st.rerun()
elif st.session_state.form5 == "next" :
def generate_stream_response(text):
# Yield the string one character at a time (for streaming)
for char in text:
yield char
time.sleep(0.02)
selected_model = {
"url": "https://router.huggingface.co/nebius/v1/chat/completions", # Replace with the Hugging Face API URL for your model
"model": "deepseek-ai/DeepSeek-V3" # Replace with the model name
}
task = "text-generation"
prompt = f"""
Hi! A person named {st.session_state.name} has just been assessed for heart disease risk.
πŸ” **Prediction**: {"High Risk" if st.session_state.Risk == 1 else "Low Risk"}
πŸ“Š **Risk Percentage**: {st.session_state.proba:.2f}%
πŸ“Œ **Input Parameters**:
- Sex: {st.session_state.gender}
- Age: {st.session_state.age}
- Current Smoker: {st.session_state.currentSmoker}
- Cigarettes per Day: {st.session_state.cigsPerDay}
- On Blood Pressure Meds: {"Yes" if st.session_state.BPMeds else "No"}
- Has Diabetes: {"Yes" if st.session_state.diabetes else "No"}
- Total Cholesterol: {st.session_state.totChol} mg/dL
- Systolic BP: {st.session_state.sysBP} mmHg
- Diastolic BP: {st.session_state.diaBP} mmHg
- BMI: {st.session_state.BMI}
- Heart Rate: {st.session_state.heartRate} bpm
- Glucose: {st.session_state.glucose} mg/dL
πŸ’¬ Please give a personalized, kind, and easy-to-understand explanation of this result. Include practical lifestyle advice and possible early warning signs to watch for. Use an encouraging, empathetic tone.and sign with {selected_model['model']}
"""
with st.container(key = "expert"):
with st.spinner("Model is Analysing your Results..."):
result = query_huggingface_model(selected_model, prompt , input_type="text",task=task)
response = extract_response_content(result)
st.markdown(f"""
<div style="
font-size: 18px;
font-weight: 600;
color: #0175C2;
margin-top: 5px;
margin-bottom: 20px;
padding: 10px 20px;
border-radius: 10px;
background: #f4faff;
display: flex;
align-items: center;
justify-content: center;
margin-left:-20px !important;
gap: 15px;
font-family: 'Times New Roman', Times, serif;
">
<img src="data:image/png;base64,{base64.b64encode(open("gem.png","rb").read()).decode()}" alt="Uploaded Image"width="40" height="40" style="margin-right: 10px;" >
Personalized Heart Health Advice
</div>
""", unsafe_allow_html=True)
st.write_stream(generate_stream_response(response)) # This will stream the text one character at a time