File size: 7,926 Bytes
d3669b1
 
861f354
d3669b1
 
 
861f354
39a6d09
d3669b1
861f354
d3669b1
74a5af8
d3669b1
 
 
25a55a5
d3669b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38b6aaf
d3669b1
 
5fde9b8
d3669b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38b6aaf
d3669b1
5fde9b8
d3669b1
 
 
74a5af8
d3669b1
 
858128d
74a5af8
d3669b1
 
74a5af8
 
 
6e63bb7
74a5af8
 
 
d3669b1
 
 
 
 
5fde9b8
8ca3cad
83c060a
5fde9b8
08b0baf
 
 
 
d3669b1
 
 
51e7390
8ca3cad
83c060a
 
51e7390
8ca3cad
83c060a
 
d3669b1
 
 
51e7390
8ca3cad
 
801630b
 
51e7390
8ca3cad
 
801630b
 
74a5af8
6e63bb7
 
 
858128d
8ca3cad
 
858128d
 
08b0baf
 
801630b
08b0baf
 
6e63bb7
858128d
8ca3cad
 
858128d
 
801630b
 
 
 
 
6e63bb7
 
 
 
d7259c8
08b0baf
83c060a
 
6e63bb7
d7259c8
83c060a
08b0baf
83c060a
 
6e63bb7
 
8ca3cad
08b0baf
83c060a
 
6e63bb7
ba1f774
d3669b1
6e63bb7
 
 
 
 
 
74a5af8
 
 
 
 
 
 
6e63bb7
74a5af8
6e63bb7
270b631
74a5af8
1215884
 
 
5ee4e8b
1215884
 
 
 
c1c04e1
5ee4e8b
c1c04e1
5ee4e8b
c2f78d8
 
90f031d
1215884
74a5af8
 
d3669b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2f78d8
d3669b1
 
5fde9b8
 
60434b7
858128d
5fde9b8
551de09
d3669b1
 
74a5af8
 
5fde9b8
74a5af8
 
 
 
c2f78d8
 
ba1f774
858128d
74a5af8
ba1f774
 
74a5af8
08b0baf
858128d
1215884
74a5af8
ba1f774
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 17:45:36 2023.

@author: Gaspar Avit Ferrero
"""

import os
import streamlit as st
import pandas as pd

from streamlit import session_state as session
from htbuilder import HtmlElement, div, hr, a, p, styles
from htbuilder.units import percent, px
from catboost import CatBoostClassifier
from datetime import datetime


###############################
## ------- FUNCTIONS ------- ##
###############################

def link(link, text, **style):
    return a(_href=link, _target="_blank", style=styles(**style))(text)


def layout(*args):

    style = """
    <style>
      # MainMenu {visibility: hidden;}
      footer {visibility: hidden;}
     .stApp { bottom: 105px; }
    </style>
    """

    style_div = styles(
        position="fixed",
        left=0,
        bottom=0,
        margin=px(0, 0, 0, 0),
        width=percent(100),
        height=px(10),
        color="black",
        text_align="center",
        # height="auto",
        opacity=1
    )

    style_hr = styles(
        display="block",
        margin=px(8, 8, "auto", "auto"),
        border_style="inset",
        border_width=px(0)
    )

    body = p()
    foot = div(
        style=style_div
    )(
        body
    )

    st.markdown(style, unsafe_allow_html=True)

    for arg in args:
        if isinstance(arg, str):
            body(arg)

        elif isinstance(arg, HtmlElement):
            body(arg)

    st.markdown(str(foot), unsafe_allow_html=True)


def footer():
    myargs = [
        "Made by ",
        link("https://www.linkedin.com/in/gaspar-avit/", "Gaspar Avit"),
    ]  # with ❤️
    layout(*myargs)


def update_prediction(input_data):
    """Callback to automatically update prediction if button has already been
    clicked"""
    if IS_CLICKED:
        launch_prediction(input_data)


def get_input_data():
    """
    Generate input layout and get input values.

    -return: DataFrame with input data.
    """
    session.input_data = pd.DataFrame()

    input_expander = st.expander('Input parameters', True)
    with input_expander:
        # Row 1
        col_age, col_sex = st.columns(2)
        with col_age:
            session.input_data.loc[0, 'age'] = st.slider('Age', 18, 75)
            # on_change=update_prediction(session.input_data)
        with col_sex:
            session.input_data.loc[0, 'gender'] = st.radio(
                'Sex', ['Female', 'Male'])
            session.input_data["gender"] = session.input_data["gender"].astype(
                'category')

        # Row 2
        col_height, col_weight = st.columns(2)
        with col_height:
            session.input_data.loc[0, 'height'] = st.slider('Height', 140, 200)
            session.input_data["height"] = session.input_data["height"].astype(
                int)
        with col_weight:
            session.input_data.loc[0, 'weight'] = st.slider('Weight', 40, 140)
            session.input_data["weight"] = session.input_data["weight"].astype(
                int)

        # Row 3
        col_ap_hi, col_ap_lo = st.columns(2)
        with col_ap_hi:
            session.input_data.loc[0, 'ap_hi'] = st.slider(
                'Systolic blood pressure', 90, 200)
            session.input_data["ap_hi"] = session.input_data["ap_hi"].astype(
                int)
        with col_ap_lo:
            session.input_data.loc[0, 'ap_lo'] = st.slider(
                'Diastolic blood pressure', 50, 120)
            session.input_data["ap_lo"] = session.input_data["ap_lo"].astype(
                int)

        # Row 4
        col_chole, col_gluc = st.columns(2)
        with col_chole:
            cholest = st.radio(
                'Cholesterol', ['Normal', 'Above normal', 'Well above normal'])
            session.input_data.loc[0, 'cholesterol'] = [
                1 if 'Normal' in cholest else 2 if 'Above normal' in cholest
                else 3][0]
            session.input_data["cholesterol"] = (session
                                                 .input_data["cholesterol"]
                                                 .astype(int)
                                                 .astype('category')
                                                 )
        with col_gluc:
            gluc = st.radio(
                'Glucose', ['Normal', 'Above normal', 'Well above normal'])
            session.input_data.loc[0, 'gluc'] = [
                1 if 'Normal' in gluc else 2 if 'Above normal' in gluc
                else 3][0]
            session.input_data["gluc"] = (session
                                          .input_data["gluc"]
                                          .astype(int)
                                          .astype('category')
                                          )

        # Row 5
        col_alco, col_smk = st.columns(2)
        with col_alco:
            alco = st.radio('Alcohol intake', ['Yes', 'No'], 1)
            session.input_data.loc[0, 'alco'] = [1 if 'Yes' in alco else 0][0]
            session.input_data["alco"] = session.input_data["alco"].astype(
                bool)
        with col_smk:
            smoke = st.radio('Smoking', ['Yes', 'No'], 1)
            session.input_data.loc[0, 'smoke'] = [1 if 'Yes' in smoke
                                                  else 0][0]
            session.input_data["smoke"] = session.input_data["smoke"].astype(
                bool)

        # Row 6
        active = st.radio('Physical activity', ['Yes', 'No'])
        session.input_data.loc[0, 'active'] = [1 if 'Yes' in active else 0][0]
        session.input_data["active"] = session.input_data["active"].astype(
            bool)

        st.write("")

    # Compute extra features
    session.input_data["bmi"] = session.input_data["weight"] \
        / (session.input_data["height"]/100)**2
    session.input_data["bad_habits"] = session.input_data["smoke"] \
        & session.input_data["alco"]

    return session.input_data


def generate_prediction(input_data):
    """
    Generate prediction of cardiovascular disease probability based on input
    data.

    -param input_data: DataFrame with input data

    -return: predicted probability of having a cardiovascular disease
    """
    # Compute probability
    probs = MODEL.predict_proba(input_data)    
    positive_proba = round(probs[0,1]*100)

    # Show results
    st.markdown("<h2 style='text-align: center; color: black;'>\
                Predicted cardiovascular disease probability:</h2>",
                unsafe_allow_html=True)
    st.markdown(f"<h1 style='text-align: center; color: grey;'>\
                {positive_proba} %</h1>",
                unsafe_allow_html=True)
    st.progress(positive_proba)
    st.text("")
    st.text("")
    
    return probs


###############################
## --------- MAIN ---------- ##
###############################


if __name__ == "__main__":

    ## --- Page config ------------ ##
    # Set page title
    st.title("""
    Cardiovascular Disease predictor
    #### This app aims to give a scoring of how probable is that an individual \
    would suffer from a cardiovascular disease given its physical \
         characteristics
    #### Just enter your info and get a prediction.
    """)
    st.text("")

    # Set page footer
    # footer()

    # Initialize clicking flag
    IS_CLICKED = False

    ## --------------------------- ##

    # Load classification model
    MODEL = CatBoostClassifier()
    MODEL.load_model('./model.cbm')

    # Get inputs
    session.input_data = get_input_data()

    # Create button to trigger poster generation
    st.text("")
    st.text("")
    buffer1, col1, buffer2 = st.columns([1.3, 1, 1])
    IS_CLICKED = col1.button(label="Generate predictions")

    st.text("")
    st.text("")

    # Generate prediction
    if IS_CLICKED:
        predicted_probs = generate_prediction(session.input_data)

    st.text("")
    st.text("")