CoolFace
Apppublic

Prabuddha21/encrypted_credit_scoring

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py403 linesDownload Raw Back to root
1"""A gradio app for credit card approval prediction using FHE."""2 3import subprocess4import time5import gradio as gr6 7from settings import (8    REPO_DIR,9    ACCOUNT_MIN_MAX,10    CHILDREN_MIN_MAX,11    INCOME_MIN_MAX,12    AGE_MIN_MAX,13    FAMILY_MIN_MAX,14    INCOME_TYPES,15    OCCUPATION_TYPES,16    HOUSING_TYPES,17    EDUCATION_TYPES,18    FAMILY_STATUS,19    YEARS_EMPLOYED_BINS,20    INCOME_VALUE,21    AGE_VALUE,22)23from backend import (24    keygen_send,25    pre_process_encrypt_send_applicant,26    pre_process_encrypt_send_bank,27    pre_process_encrypt_send_credit_bureau,28    run_fhe,29    get_output_and_decrypt,30    explain_encrypt_run_decrypt,31)32 33 34subprocess.Popen(["uvicorn", "server:app"], cwd=REPO_DIR)35time.sleep(3)36 37 38demo = gr.Blocks()39 40 41print("Starting the demo...")42with demo:43 44    # gr.Markdown(45    #     """46    #         <p align="center">47    #             <img width=200 src="https://user-images.githubusercontent.com/5758427/197816413-d9cddad3-ba38-4793-847d-120975e1da11.png">48    #         </p>49    #     """50    # )51    # gr.Markdown(52    #     """53    #     <h1 align="center">Encrypted Credit Card Approval Prediction Using Fully Homomorphic Encryption</h1>54    #     <p align="center">55    #         <a href="https://github.com/zama-ai/concrete-ml"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="file/images/logos/github.png">Concrete-ML</a>56    #         —57    #         <a href="https://docs.zama.ai/concrete-ml"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="file/images/logos/documentation.png">Documentation</a>58    #         —59    #         <a href="https://zama.ai/community"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="file/images/logos/community.png">Community</a>60    #         —61    #         <a href="https://twitter.com/zama_fhe"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="file/images/logos/x.png">@zama_fhe</a>62    #     </p>63    #     """64    # )65 66    with gr.Accordion("What is credit scoring for card approval?", open=False):67        gr.Markdown(68            """69            It is a complex process that involves several entities: the applicant, the bank, the 70            credit bureau, and the credit scoring agency. When you apply for a credit card, you71            provide personal and financial information to the bank. This might include your income,72            employment status, and existing debts. The bank uses this information to assess your 73            creditworthiness. To do this, they often turn to credit bureaus and credit scoring 74            agencies. 75            - Credit bureaus collect and maintain data on consumers' credit and payment 76            histories. This data includes your past and current debts, payment history, and the 77            length of your credit history. 78            - Credit scoring agencies use algorithms to analyze 79            the data from credit bureaus and generate a credit score. This score is a numerical 80            representation of your creditworthiness. 81            - The bank uses your credit score, along with 82            the information you provided, to make a decision on your credit card application. A 83            higher credit score generally increases your chances of being approved and may result 84            in better terms (like a lower interest rate). 85            """86        )87 88    with gr.Accordion("Why is it critical to add a new privacy layer to this process?", open=False):89        gr.Markdown(90            """91            The data involved is highly sensitive. It includes personal details like your Social 92            Security number, income, and credit history. There's significant sharing of data 93            between different entities. Your information is not just with the bank, but also with 94            credit bureaus and scoring agencies. The more entities that have access to your data, 95            the greater the risk of a data breach. This can lead to identity theft and financial 96            fraud. There's also the issue of data accuracy. Mistakes in credit reports can lead to 97            unjustly low credit scores, affecting your ability to get credit. 98            """99        )100 101    with gr.Accordion(102        "Why is Fully Homomorphic Encryption (FHE) a solution for better credit scoring?", 103        open=False,104    ):105        gr.Markdown(106            """107            Fully Homomorphic Encryption (FHE) is seen as an ideal solution for enhancing privacy 108            and accuracy in credit scoring processes involving multiple parties like applicants, 109            banks, credit bureaus, and credit scoring agencies. It allows data to be encrypted and 110            processed without ever needing to decrypt it. This means that sensitive data can be 111            shared and analyzed without exposing the actual information to any of the parties or 112            the server processing it. In the context of credit scoring, this would enable a more 113            thorough and accurate assessment of a person's creditworthiness. Data from various 114            sources can be combined and analyzed to make a more informed decision, yet each party's 115            data remains confidential. As a result, the risk of data leaks or breaches is 116            significantly minimized, addressing major privacy concerns. 117 118            To summarize, FHE provides a means to make more accurate credit eligibility decisions 119            while maintaining strict data privacy, offering a sophisticated solution to the delicate 120            balance between data utility and confidentiality.121            """122        )123 124    gr.Markdown(125        """126        <p align="center">127            <img src="https://raw.githubusercontent.com/kcelia/Img/main/credit_scoring_banner.png"128        </p>129        """130    )131 132    gr.Markdown("## Step 1: Generate the keys.")133    gr.Markdown("<hr />")134    gr.Markdown("<span style='color:grey'>Applicant, Bank and Credit bureau setup</span>")135    gr.Markdown(136        """137        - The private key is generated jointly by the entities that collaborate to compute the 138            credit score. It is used to encrypt and decrypt the data and shall never be shared with 139            any other party.140        - The evaluation key is a public key that the server needs to process encrypted data. It is141        therefore transmitted to the server for further processing as well.142        """143    )144    keygen_button = gr.Button("Generate the keys and send evaluation key to the server.")145    evaluation_key = gr.Textbox(146        label="Evaluation key representation:", max_lines=2, interactive=False147    )148    client_id = gr.Textbox(label="", max_lines=2, interactive=False, visible=False)149    150    # Button generate the keys151    keygen_button.click(152        keygen_send,153        outputs=[client_id, evaluation_key, keygen_button],154    )155 156    gr.Markdown("## Step 2: Fill in some information.")157    gr.Markdown("<hr />")158    gr.Markdown("<span style='color:grey'>Applicant, Bank and Credit bureau setup</span>")159    gr.Markdown(160        """161        Select the information that corresponds to the profile you want to evaluate. Three sources 162        of information are represented in this model:163        - the applicant's personal information in order to evaluate his/her credit card eligibility;164        - the applicant bank account history, which provides any type of information on the 165        applicant's banking information relevant to the decision (here, we consider duration of 166        account);167        - and credit bureau information, which represents any other information (here, 168        employment history) that could provide additional insight relevant to the decision.169        170        Please always encrypt and send the values (through the buttons on the right) once updated171        before running the FHE inference.172        """173    )174 175    with gr.Row():176        with gr.Column():177            gr.Markdown("### Step 2.1 - Applicant information 🧑‍💻")178            bool_inputs = gr.CheckboxGroup(179                ["Car", "Property", "Mobile phone"], 180                label="Which of the following do you actively hold or own?"181            )182            num_children = gr.Slider(183                **CHILDREN_MIN_MAX, 184                step=1, 185                label="Number of children", 186                info="How many children do you have ?"187            )188            household_size = gr.Slider(189                **FAMILY_MIN_MAX, 190                step=1, 191                label="Household size", 192                info="How many members does your household have ?"193            )194            total_income = gr.Slider(195                **INCOME_MIN_MAX,196                value=INCOME_VALUE,197                label="Income", 198                info="What's you total yearly income (in euros) ?"199            )200            age = gr.Slider(201                **AGE_MIN_MAX,202                value=AGE_VALUE, 203                step=1, 204                label="Age", 205                info="How old are you ?"206            )207 208        with gr.Column():209            income_type = gr.Dropdown(210                choices=INCOME_TYPES, 211                value=INCOME_TYPES[0], 212                label="Income type", 213                info="What is your main type of income ?"214            )215            education_type = gr.Dropdown(216                choices=EDUCATION_TYPES, 217                value=EDUCATION_TYPES[0], 218                label="Education", 219                info="What is your education background ?"220            )221            family_status = gr.Dropdown(222                choices=FAMILY_STATUS, 223                value=FAMILY_STATUS[0], 224                label="Family", 225                info="What is your family status ?"226            )227            occupation_type = gr.Dropdown(228                choices=OCCUPATION_TYPES, 229                value=OCCUPATION_TYPES[0], 230                label="Occupation", 231                info="What is your main occupation ?"232            )233            housing_type = gr.Dropdown(234                choices=HOUSING_TYPES, 235                value=HOUSING_TYPES[0], 236                label="Housing", 237                info="In what type of housing do you live ?"238            )239 240    with gr.Row():241        with gr.Column(scale=2):242            encrypt_button_applicant = gr.Button("Encrypt the inputs and send to server.")243            244            encrypted_input_applicant = gr.Textbox(245                label="Encrypted input representation:", max_lines=2, interactive=False246            )247 248    gr.Markdown("<hr />")249    with gr.Column():250        gr.Markdown("### Step 2.2 - Bank information 🏦")251        account_age = gr.Slider(252            **ACCOUNT_MIN_MAX, 253            step=1, 254            label="Account age (months)", 255            info="How long have this person had this bank account (in months) ?"256        )257 258    with gr.Row():259        with gr.Column(scale=2):260            encrypt_button_bank = gr.Button("Encrypt the inputs and send to server.")261 262            encrypted_input_bank = gr.Textbox(263                label="Encrypted input representation:", max_lines=2, interactive=False264            )265 266    gr.Markdown("<hr />")267    with gr.Column():268        gr.Markdown("### Step 2.3 - Credit bureau information 🏢")269        employed = gr.Radio(["Yes", "No"], label="Is the person employed ?", value="Yes")270        years_employed = gr.Dropdown(271            choices=YEARS_EMPLOYED_BINS, 272            value=YEARS_EMPLOYED_BINS[0], 273            label="Years of employment", 274            info="How long have this person been employed (in years) ?"275        )276 277    with gr.Row():278        with gr.Column(scale=2):279            encrypt_button_credit_bureau = gr.Button("Encrypt the inputs and send to server.")280 281            encrypted_input_credit_bureau = gr.Textbox(282                label="Encrypted input representation:", max_lines=2, interactive=False283            )284 285    # Button to pre-process, generate the key, encrypt and send the applicant inputs from the client 286    # side to the server287    encrypt_button_applicant.click(288        pre_process_encrypt_send_applicant,289        inputs=[client_id, bool_inputs, num_children, household_size, total_income, age, \290                income_type, education_type, family_status, occupation_type, housing_type],291        outputs=[encrypted_input_applicant, encrypt_button_applicant],292    )293 294    # Button to pre-process, generate the key, encrypt and send the bank inputs from the client 295    # side to the server296    encrypt_button_bank.click(297        pre_process_encrypt_send_bank,298        inputs=[client_id, account_age],299        outputs=[encrypted_input_bank, encrypt_button_bank],300    )301 302    # Button to pre-process, generate the key, encrypt and send the credit bureau inputs from the 303    # client side to the server    304    encrypt_button_credit_bureau.click(305        pre_process_encrypt_send_credit_bureau,306        inputs=[client_id, years_employed, employed],307        outputs=[encrypted_input_credit_bureau, encrypt_button_credit_bureau],308    )309 310    gr.Markdown("## Step 3: Run the FHE evaluation.")311    gr.Markdown("<hr />")312    gr.Markdown("<span style='color:grey'>Server Side</span>")313    gr.Markdown(314        """315        Once the server receives the encrypted inputs, it can compute the prediction without ever 316        needing to decrypt any value.317 318        This server employs a [Decision Tree](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html)319        classifier model that has been trained on a synthetic data-set.320        """321    )322 323    execute_fhe_button = gr.Button("Run the FHE evaluation.")324    fhe_execution_time = gr.Textbox(325        label="Total FHE execution time (in seconds):", max_lines=1, interactive=False326    )327 328    # Button to send the encodings to the server using post method329    execute_fhe_button.click(run_fhe, inputs=[client_id], outputs=[fhe_execution_time, execute_fhe_button])330 331    gr.Markdown("## Step 4: Receive the encrypted output from the server and decrypt.")332    gr.Markdown("<hr />")333    gr.Markdown("<span style='color:grey'>Applicant, Bank and Credit bureau decryption</span>")334    gr.Markdown(335        """336        Once the server completed the inference, the encrypted output is returned to the applicant.337 338        The three entities that provide the information to compute the credit score are the only 339        ones that can decrypt the result. They take part in a decryption protocol that allows to 340        only decrypt the full result when all three parties decrypt their share of the result.341        """342    )343    gr.Markdown(344        """345        The first value displayed below is a shortened byte representation of the actual encrypted 346        output.347        The applicant is then able to decrypt the value using its private key.348        """349    )350 351    get_output_button = gr.Button("Receive the encrypted output from the server.")352    encrypted_output_representation = gr.Textbox(353        label="Encrypted output representation: ", max_lines=2, interactive=False354    )355    prediction_output = gr.Textbox(356        label="Prediction", max_lines=1, interactive=False357    )358 359    # Button to send the encodings to the server using post method360    get_output_button.click(361        get_output_and_decrypt, 362        inputs=[client_id], 363        outputs=[prediction_output, encrypted_output_representation, get_output_button],364    )365 366    gr.Markdown("## Step 5: Explain the prediction (only if your credit card is likely to be denied).")367    gr.Markdown("<hr />")368    gr.Markdown(369        """370        In case the credit card is likely to be denied, the applicant can ask for how many years of 371        employment would most likely be required in order to increase the chance of getting a 372        credit card approval.373        374        All of the above steps are combined into a single button for simplicity. The following 375        button therefore encrypts the same inputs (except the years of employment, which varies) 376        from all three parties, runs the new prediction in FHE and decrypts the output. 377        378        In case the following states to try a new "Years of employment" input, one can simply 379        update the value in Step 2 and directly run Step 6 once more.  380        """381    )382    explain_button = gr.Button(383        "Encrypt the inputs, compute in FHE and decrypt the output."384    )385    explain_prediction = gr.Textbox(386        label="Additional years of employed required.", interactive=False387    )388 389    # Button to explain the prediction390    explain_button.click(391        explain_encrypt_run_decrypt,392        inputs=[client_id, prediction_output, years_employed, employed],393        outputs=[explain_prediction, explain_button],394    )395 396    gr.Markdown(397        "The app was built with [Concrete-ML](https://github.com/zama-ai/concrete-ml), a "398        "Privacy-Preserving Machine Learning (PPML) open-source set of tools by [Zama](https://zama.ai/). "399        "Try it yourself and don't forget to star on Github &#11088;."400    )401 402demo.launch(share=False)403