File size: 16,528 Bytes
9be1e6c
 
 
 
 
6d925bd
9be1e6c
 
 
 
01cc876
9be1e6c
 
 
 
 
 
 
 
 
 
 
 
 
 
e967b25
9be1e6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
039500b
885d18e
9be1e6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0be1b9d
b7a27fc
 
 
7995f88
 
b7a27fc
8870850
 
 
039500b
 
 
 
 
 
8870850
 
 
039500b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a84c88
039500b
 
 
 
 
 
 
 
8870850
 
 
 
 
 
 
 
 
6d925bd
 
 
 
 
 
9cb79eb
 
6d925bd
 
 
 
 
 
0be1b9d
6d925bd
7995f88
8870850
 
 
0be1b9d
 
 
 
 
 
 
b7a27fc
9cb79eb
 
 
9be1e6c
039500b
9be1e6c
 
 
 
039500b
 
9be1e6c
039500b
9be1e6c
039500b
 
9be1e6c
 
039500b
 
9be1e6c
039500b
9be1e6c
 
039500b
9be1e6c
 
039500b
9be1e6c
 
 
 
039500b
 
 
 
 
 
 
 
 
 
9be1e6c
 
 
 
01cc876
 
9be1e6c
 
01cc876
9be1e6c
 
01cc876
9be1e6c
 
 
 
7995f88
8870850
 
9be1e6c
039500b
 
0be1b9d
9cb79eb
 
 
8870850
9cb79eb
0be1b9d
 
9be1e6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
039500b
 
9be1e6c
039500b
 
9be1e6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
039500b
9be1e6c
 
 
 
 
 
039500b
9be1e6c
 
9cb79eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
039500b
9cb79eb
 
 
 
 
 
 
 
 
 
039500b
9cb79eb
 
 
039500b
9cb79eb
 
9be1e6c
50ee05f
3309e17
039500b
 
 
 
3309e17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ee05f
 
 
 
 
 
 
9cb79eb
 
 
 
7995f88
e967b25
8870850
 
9be1e6c
9cb79eb
 
 
7995f88
 
 
 
 
 
 
 
9cb79eb
6d925bd
7995f88
 
9cb79eb
7995f88
 
 
 
 
 
 
9cb79eb
 
7995f88
9cb79eb
9be1e6c
 
 
 
 
 
 
 
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# type: ignore -- ignores linting import issues when using multiple virtual environments
import streamlit.components.v1 as components
import streamlit as st
import pandas as pd
import logging
from deeploy import Client, CreateEvaluation
from constants import (
    relationship_dict,
    occupation_dict,
    education_dict,
    type_of_work_dict,
    countries_dict,
    marital_status_dict,
)

# reset Plotly theme after streamlit import
import plotly.io as pio


pio.templates.default = "plotly"

logging.basicConfig(level=logging.INFO)

st.set_page_config(layout="wide")

st.title("Loan application model example")


def get_model_url():
    model_url = st.text_area(
        "Model URL (without the /explain endpoint, default is the demo deployment)",
        "https://api.app.deeploy.ml/workspaces/708b5808-27af-461a-8ee5-80add68384c7/deployments/dc8c359d-5f61-4107-8b0f-de97ec120289/",
        height=125,
    )
    elems = model_url.split("/")
    try:
        workspace_id = elems[4]
        deployment_id = elems[6]
    except IndexError:
        workspace_id = ""
        deployment_id = ""
    return model_url, workspace_id, deployment_id


def ChangeButtonColour(widget_label, font_color, background_color="transparent"):
    # func to change button colors
    htmlstr = f"""
        <script>
            var elements = window.parent.document.querySelectorAll('button');
            for (var i = 0; i < elements.length; ++i) {{ 
                if (elements[i].innerText == '{widget_label}') {{ 
                    elements[i].style.color ='{font_color}';
                    elements[i].style.background = '{background_color}'
                }}
            }}
        </script>
        """
    components.html(f"{htmlstr}", height=0, width=0)


with st.sidebar:
    st.image("deeploy_logo_wide.png", width=250)

    # Ask for model URL and token
    host = st.text_input("Host (Changing is optional)", "app.deeploy.ml")
    model_url, workspace_id, deployment_id = get_model_url()
    st.session_state.deployment_id = deployment_id
    deployment_token = st.text_input("Deeploy API token", "my-secret-token")
    if deployment_token == "my-secret-token":
        st.warning("Please enter Deeploy API token.")
    # Split model URL into workspace and deployment ID

    # st.write("Values below are for debug only:")
    # st.write("Workspace ID: ", workspace_id)
    # st.write("Deployment ID: ", deployment_id)

    client_options = {
        "host": host,
        "deployment_token": deployment_token,
        "workspace_id": workspace_id,
    }
    client = Client(**client_options)


if "expander_toggle" not in st.session_state:
    st.session_state.expander_toggle = True

if "evaluation_submitted" not in st.session_state:
    st.session_state.evaluation_submitted = False

if "predict_button_clicked" not in st.session_state:
    st.session_state.predict_button_clicked = False

if "request_body" not in st.session_state:
    st.session_state.request_body = None

if "deployment_id" not in st.session_state:
    st.session_state.deployment_id = None

if "exp" not in st.session_state:
    st.session_state.exp = None

def form_request_body():
    """Create the request body for the prediction endpoint"""
    marital_status_id = marital_status_dict[st.session_state.marital_status]
    native_country_id = countries_dict[st.session_state.native_country]
    relationship_id = relationship_dict[st.session_state.relationship]
    occupation_id = occupation_dict[st.session_state.occupation]
    education_id = education_dict[st.session_state.education]
    type_of_work_id = type_of_work_dict[st.session_state.type_of_work]
    return {
        "instances": [
            [
                st.session_state.age,
                type_of_work_id,
                education_id,
                marital_status_id,
                occupation_id,
                relationship_id,
                st.session_state.capital_gain,
                st.session_state.capital_loss,
                st.session_state.hours_per_week,
                native_country_id,
            ]
        ]
    }


def predict_callback():
    """Callback function to call the prediction endpoint"""
    request_body = form_request_body() # Make sure we have the latest values after user input
    st.session_state.exp = None
    with st.spinner("Loading prediction and explanation..."):
        # Call the explain endpoint as it also includes the prediction
        exp = client.explain(
            request_body=request_body, deployment_id=st.session_state.deployment_id
        )
        st.session_state.exp = exp

    st.session_state.predict_button_clicked = True
    st.session_state.evaluation_submitted = False    

def hide_expander():
    st.session_state.expander_toggle = False

def show_expander():
    st.session_state.expander_toggle = True

def submit_and_clear(agree: str, comment: str = None):
    if agree == "yes":
        evaluation_input: CreateEvaluation = {
            "agree": True,
            "comment": comment,
        }
    else:
        desired_output = not predictions[0]
        evaluation_input: CreateEvaluation = {
            "agree": False,
            "desired_output": { "predictions": [desired_output] },
            "comment": comment,
        }

    try:
        client.evaluate(st.session_state.deployment_id, prediction_log_id, evaluation_input)
        st.session_state.evaluation_submitted = True
        st.session_state.predict_button_clicked = False
        st.session_state.exp = None
        show_expander()
    except Exception as e:
        logging.error(e)
        st.error(
            "Failed to submit feedback."
            + "Check whether you are using the right model URL and token for evaluations. "
            + "Contact Deeploy if the problem persists."
        )

# with st.expander("Debug session state", expanded=False):
#     st.write(st.session_state)

# Attributes
with st.expander("**Loan application form**", expanded=st.session_state.expander_toggle):
    # Split view in 2 columns
    col1, col2 = st.columns(2)
    with col1:
        # Create input fields for attributes from constant dicts
        age = st.number_input("Age", min_value=10, max_value=100, value=30, key="age", on_change=predict_callback)
        marital_status = st.selectbox("Marital Status", marital_status_dict.keys(), key="marital_status", on_change=predict_callback,)
        native_country = st.selectbox(
            "Native Country", countries_dict.keys(), index=len(countries_dict) - 1, key="native_country",on_change=predict_callback
        )
        relationship = st.selectbox("Family situation", relationship_dict.keys(), key="relationship", on_change=predict_callback)
        occupation = st.selectbox("Occupation", occupation_dict.keys(), index=1, key="occupation", on_change=predict_callback)

    with col2:
        education = st.selectbox("Highest education level", education_dict.keys(), key="education", index=4, on_change=predict_callback)
        type_of_work = st.selectbox("Type of work", type_of_work_dict.keys(), key="type_of_work", on_change=predict_callback)
        hours_per_week = st.number_input(
            "Working hours per week", min_value=0, max_value=100, value=40, key="hours_per_week", on_change=predict_callback,
        )
        capital_gain = st.number_input(
            "Yearly income [€]", min_value=0, max_value=10000000, value=70000, key="capital_gain", on_change=predict_callback,
        )
        capital_loss = st.number_input(
            "Yearly expenditures [€]", min_value=0, max_value=10000000, value=60000, key="capital_loss", on_change=predict_callback,
        )
    data_df = pd.DataFrame(
        [
            [
                st.session_state.age,
                st.session_state.type_of_work,
                st.session_state.education,
                st.session_state.marital_status,
                st.session_state.occupation,
                st.session_state.relationship,
                st.session_state.capital_gain,
                st.session_state.capital_loss,
                st.session_state.hours_per_week,
                st.session_state.native_country,
            ]
        ],
        columns=[
            "Age",
            "Type of work",
            "Highest education level",
            "Marital Status",
            "Occupation",
            "Family situation",
            "Yearly Income [€]",
            "Yearly expenditures [€]",
            "Working hours per week",
            "Native Country",
        ],
    )
    data_df_t = data_df.T

# Show predict button if token is set
if deployment_token != "my-secret-token" and st.session_state.exp is None:
    predict_button = st.button(
        "Send loan application", key="predict_button", help="Click to get the AI prediction.", on_click=predict_callback,
    )        

if st.session_state.evaluation_submitted:
    st.success("Evaluation submitted successfully!")

# Show prediction and explanation after predict button is clicked
elif st.session_state.predict_button_clicked and st.session_state.exp is not None:
    try:
        exp = st.session_state.exp
        # Read explanation to dataframe from json
        predictions = exp["predictions"]
        request_log_id = exp["requestLogId"]
        prediction_log_id = exp["predictionLogIds"][0]

        exp_df = pd.DataFrame(
            [exp["explanations"][0]["shap_values"]], columns=exp["featureLabels"]
        )

        exp_df.columns = data_df.columns

        exp_df_t = exp_df.T

        # Merge data and explanation
        exp_df_t = data_df_t.merge(exp_df_t, left_index=True, right_index=True)

        weight_feat = "Weight"
        feat_val_col = "Value"
        exp_df_t.columns = [feat_val_col, weight_feat]
        exp_df_t["Feature"] = exp_df_t.index
        exp_df_t = exp_df_t[["Feature", feat_val_col, weight_feat]]
        exp_df_t[feat_val_col] = exp_df_t[feat_val_col].astype(str)
        
        # Filter values below 0.01
        exp_df_t = exp_df_t[
            (exp_df_t[weight_feat] > 0.01) | (exp_df_t[weight_feat] < -0.01)
        ]
        exp_df_t[weight_feat] = exp_df_t[weight_feat].astype(float).round(2)

        pos_exp_df_t = exp_df_t[exp_df_t[weight_feat] > 0]
        pos_exp_df_t = pos_exp_df_t.sort_values(by=weight_feat, ascending=False)

        neg_exp_df_t = exp_df_t[exp_df_t[weight_feat] < 0]
        neg_exp_df_t = neg_exp_df_t.sort_values(by=weight_feat, ascending=True)
        neg_exp_df_t[weight_feat] = neg_exp_df_t[weight_feat].abs()

        # Get 3 features with highest positive relevance score
        pos_feats = pos_exp_df_t[weight_feat].nlargest(3).index.tolist()
        # For feature, get feature value and concatenate into a single string
        pos_feats = [
            f"{feat}: {pos_exp_df_t.loc[feat, feat_val_col]}"
            for feat in pos_feats
        ]
        # Get 3 features with highest negative relevance score
        neg_feats = neg_exp_df_t[weight_feat].nlargest(3).index.tolist()
        # For feature, get feature value and concatenate into a single string
        neg_feats = [
            f"{feat}: {neg_exp_df_t.loc[feat, feat_val_col]}"
            for feat in neg_feats
        ]
        if predictions[0]:
            # Show prediction
            st.subheader("Loan Decision: :green[Approve]", divider="green")
            # Format subheader to green
            st.markdown(
                "<style>.css-1v3fvcr{color: green;}</style>", unsafe_allow_html=True
            )
            col1, col2 = st.columns(2)
            with col1:
                # If prediction is positive, first show positive features, then negative features
                st.success(
                    "The most important characteristics in favor of loan approval are:  \n - "
                    + "  \n- ".join(pos_feats)
                )
            with col2:
                st.error(
                    "However, the following features weight against the loan applicant:  \n - "
                    + "  \n- ".join(neg_feats)
                    # + "  \n For more details, see full explanation of the credit assessment below.",
                )
        else:
            st.subheader("Loan Decision: :red[Reject]", divider="red")
            col1, col2 = st.columns(2)
            with col1:
                # If prediction is negative, first show negative features, then positive features
                st.error(
                    "The most important reasons for loan rejection are:  \n - "
                    + "  \n - ".join(neg_feats)
                )
            with col2:
                st.success(
                    "However, the following factors weigh in favor of the loan applicant:  \n - "
                    + "  \n - ".join(pos_feats)
                )
        try:
            # Show explanation
            if predictions[0]:
                col_pos, col_neg = st.columns(2)
            else:
                col_neg, col_pos = st.columns(2) # Swap columns if prediction is negative
            with col_pos:
                st.subheader("Factors :green[in favor] of loan approval")
                # st.success("**Factors in favor of loan approval**")
                st.dataframe(
                    pos_exp_df_t,
                    hide_index=True,
                    width=600,
                    column_config={
                        "Weight": st.column_config.ProgressColumn(
                            "Weight",
                            width="small",
                            format=" ",
                            min_value=0,
                            max_value=1,
                        )
                    },
                )

            with col_neg:
                st.subheader("Factors :red[against] loan approval")
                # st.error("**Factors against loan approval**")
                st.dataframe(
                    neg_exp_df_t,
                    hide_index=True,
                    width=600,
                    column_config={
                        "Weight": st.column_config.ProgressColumn(
                            "Weight",
                            width="small",
                            format=" ",
                            min_value=0,
                            max_value=1,
                        )
                    },
                )
        except Exception as e:
            logging.error(e)
            st.error(
                "Failed to show the explanation."
                + "Refresh the page to reset the application."
                + "Contact Deeploy if the problem persists."
            )

        st.divider()

        if not st.session_state.evaluation_submitted:
            # Add prediction evaluation
            st.subheader("Evaluation: Do you agree with the loan assessment?")
            st.write(
                "AI model predictions always come with a certain level of uncertainty. Evaluate the correctness of the assessment based on your expertise and experience."
            )
            st.session_state.evaluation_input = {}
            comment = st.text_input("Your assessment:", placeholder="For example: 'Income is too low, given applicant's background'")

            cols = st.columns(4)
            col_yes, col_no = cols[:2]
            with col_yes:
                yes_button = st.button(
                    "Yes, I agree",
                    key="yes_button",
                    use_container_width=True,
                    help="Click if you agree with the prediction",
                    on_click=submit_and_clear,
                    args=["yes", comment]
                )
                ChangeButtonColour("Yes, I agree", "white", "green")

            with col_no:
                no_button = st.button(
                    "No, I disagree",
                    key="no_button",
                    use_container_width=True,
                    help="Click if you disagree with the prediction",
                    type="primary",
                    on_click=submit_and_clear,
                    args=["no"]
                )
                ChangeButtonColour("No, I disagree", "white", "#DD360C") # Red color for disagree button

    except Exception as e:
        logging.error(e)
        st.error(
            "Failed to retrieve the prediction or explanation."
            + "Check whether you are using the right model URL and Token. "
            + "Contact Deeploy if the problem persists."
        )