import gradio as gr from predictor import predict, key_already_generated, pre_process_encrypt_send_purchase, decrypt_prediction import base64 def key_generated(): """ Check if the evaluation keys have already been generated. Returns: bool: True if the evaluation keys have already been generated, False otherwise. """ if not key_already_generated(): error_message = ( f"Error Encountered While generating the evaluation keys." ) print(error_message) return {gen_key_btn: gr.update(value=error_message)} else: print("Keys have been generated ✅") return {gen_key_btn: gr.update(value="Keys have been generated ✅")} demo = gr.Blocks(css=".markdown-body { font-size: 18px; }") with demo: gr.Markdown( f"""
""" ) gr.Markdown( """

Confidential Bank Fraud Detection Using Fully Homomorphic Encryption

💳Read the Code 🔒Read Zama's Concrete-ML Documentation 🏫Visit Epita Website

""" ) gr.Markdown( """

This application shows you how to detect bank frauds without revealing your personal data using Fully Homomorphic Encryption.

""" ) with gr.Accordion("What is bank fraud detection?", open=False): gr.Markdown( """ Bank fraud detection is the process of identifying fraudulent activities or transactions that may pose a risk to a bank or its customers. It is essential to detect fraudulent activities to prevent financial losses and protect the integrity of the banking system. """ ) with gr.Accordion("Why is it important to protect this data?", open=False): gr.Markdown( """ Banking and financial data often contain sensitive personal information, such as income, spending habits, and account numbers. Protecting this information ensures that customers' privacy is respected and safeguarded from unauthorized access. """ ) with gr.Accordion("Why is Fully Homomorphic Encryption (FHE) a good solution?", open=False): gr.Markdown( """ Fully Homomorphic Encryption (FHE) is a powerful technique for enhancing privacy and accuracy in the context of fraud detection, particularly when dealing with sensitive banking data. FHE allows for the encryption of data, which can then be processed and analyzed without ever needing to decrypt it. Each party involved in the detection process can collaborate without compromising user privacy, minimizing the risk of data leaks or breaches. The data remains confidential throughout the entire process, ensuring that the privacy of users is maintained. You can consult the ["Introduction to Homomorphic Encryption" page](https://www.zama.ai/introduction-to-homomorphic-encryption). """ ) gr.Markdown( """

Below, we will explain the flow in the image by simulating a purchase you've just made, and show you how our fraud detection model processes the transaction.

""" ) gr.Markdown( f"""

""" ) gr.Markdown("
") ########################## Key Gen Part ########################## gr.Markdown( "## Step 1: Generate the keys\n\n" """In Fully Homomorphic Encryption (FHE) methods, two types of keys are created. The first type, called secret keys, are used to encrypt and decrypt the user's data. The second type, called evaluation keys, enables a server to work on the encrypted data without seeing the actual data. """ ) gen_key_btn = gr.Button("Generate the secret and evaluation keys") gen_key_btn.click( key_generated, inputs=[], outputs=[gen_key_btn], )#547 gr.Markdown("
") ########################## Encrypt Data ########################## gr.Markdown( "## Step 2: Make your purchase\n\n" """ 🛍️ It's time to shop! To simulate your latest purchase, please provide the details of your most recent transaction. If you don't have an idea, you can pre-fill with an example of fraud or non-fraud. """ ) def prefill_fraud(): return 34, 50, 3, False, False, False, True def prefill_no_fraud(): return 12, 2, 0.7, True, False, True, False with gr.Row(): prefill_button = gr.Button("Exemple Fraud") prefill_button_no = gr.Button("Exemple No-Fraud") with gr.Row(): with gr.Column(): distance_home = gr.Number( minimum=float(0), maximum=float(22000), step=1, value=10, label="Distance from Home", info="How far was the purchase from your home (in km)?" ) distance_last = gr.Number( minimum=float(0), maximum=float(22000), step=1, value=1, label="Distance from Last Transaction", info="Distance between this purchase and the last one (in km)?" ) ratio = gr.Number( minimum=float(0), maximum=float(10000), step=0.1, value=1, label="Ratio to Median Purchase Price", info="Purchase ratio compared to your average purchase", ) repeat_retailer = gr.Checkbox( label="Repeat Retailer", info="Check if you are purchasing from the same retailer as your last transaction" ) used_chip = gr.Checkbox( label="Used Chip", info="Check if you used a chip card for this transaction" ) used_pin_number = gr.Checkbox( label="Used Pin Number", info="Check if you used your PIN number during the transaction" ) online = gr.Checkbox( label="Online Order", info="Check if you made your purchase online" ) prefill_button.click( fn=prefill_fraud, inputs=[], outputs=[ distance_home, distance_last, ratio, repeat_retailer, used_chip, used_pin_number, online ] ) prefill_button_no.click( fn=prefill_no_fraud, inputs=[], outputs=[ distance_home, distance_last, ratio, repeat_retailer, used_chip, used_pin_number, online ] ) with gr.Row(): with gr.Column(scale=2): encrypt_button_applicant = gr.Button("Encrypt the inputs and send to server.") encrypted_input_applicant = gr.Textbox( label="Encrypted input representation:", max_lines=4, interactive=False ) encrypt_button_applicant.click( pre_process_encrypt_send_purchase, inputs=[distance_home, distance_last, ratio, repeat_retailer, used_chip, used_pin_number, \ online], outputs=[encrypted_input_applicant, encrypt_button_applicant], ) gr.Markdown("
") ########################## Model Prediction ########################## gr.Markdown("## Step 3: Run the FHE evaluation.") gr.Markdown("Server Side") gr.Markdown( """ It's time to launch our prediction, by pressing the button you will launch the fraud analysis that our fictitious bank offers you. This server employs a [Random Forest (by Concrete-ML)](https://github.com/zama-ai/concrete-ml/blob/release/1.8.x/docs/references/api/concrete.ml.sklearn.rf.md#class-randomforestclassifier) classifier model that has been trained on a synthetic data-set. This part takes a little time (about 140 seconds), since in fact the servers used are only for demonstration and are not very powerful (in the meantime, don't hesitate to take a look at the documentation 🤓👆). """ ) execute_fhe_button = gr.Button("Run the FHE evaluation.") fhe_execution_time = gr.Textbox( label="Total FHE execution time (in seconds):", max_lines=4, interactive=False ) # Button to send the encodings to the server using post method # execute_fhe_button.click(predict, inputs=[], outputs=[fhe_execution_time, execute_fhe_button]) execute_fhe_button.click( fn=predict, inputs=[], outputs=[fhe_execution_time, execute_fhe_button], ) gr.Markdown("
") ########################## Decrypt Prediction ########################## gr.Markdown("## Step 4: Receive the encrypted output from the server and decrypt.") gr.Markdown( """ 🔔 You will receive an encrypted notification from the server! Is this a Fraud? The message is decrypted by pressing the button. """ ) get_output_button = gr.Button("Decrypt the prediction.") prediction_output = gr.Textbox( label="Prediction", max_lines=1, interactive=False ) prediction_bar = gr.HTML(label="Prediction Bar") # For the percentage bar get_output_button.click( decrypt_prediction, outputs=[prediction_output, get_output_button, prediction_bar], ) gr.Markdown( """ You now know that it is possible to detect bank fraud without revealing your personal information. """ ) gr.Markdown( "The app was built with [Concrete-ML](https://github.com/zama-ai/concrete-ml), a " "Privacy-Preserving Machine Learning (PPML) open-source set of tools by [Zama](https://zama.ai/). " "Try it yourself and don't forget to star on Github ⭐." ) if __name__ == "__main__": demo.launch()