File size: 11,466 Bytes
630ff31
cbfe722
15518d4
 
cbfe722
630ff31
cbfe722
630ff31
 
cbfe722
 
 
 
 
 
 
 
 
 
 
ede387d
cbfe722
105a900
cbfe722
 
a7f0e3c
 
 
 
 
 
 
 
cbfe722
15518d4
 
f35811c
 
ecc38d0
f35811c
 
b425f89
f35811c
 
 
b425f89
f35811c
2816c57
 
b425f89
2816c57
f35811c
 
 
cbfe722
f35811c
 
 
b425f89
f35811c
 
cbfe722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f47273
 
cbfe722
 
 
f35811c
 
 
 
 
 
 
cbfe722
a7f0e3c
 
 
cda447a
a7f0e3c
 
 
cbfe722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15518d4
cbfe722
 
 
 
 
 
 
4d71641
 
 
 
cbfe722
 
 
4d71641
 
 
 
 
 
 
 
 
 
cbfe722
 
e6bd50b
cbfe722
 
 
 
 
 
 
e6bd50b
cbfe722
 
 
 
 
 
 
e6bd50b
cbfe722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d71641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbfe722
 
 
 
 
693ac1c
cbfe722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5703bb
cbfe722
 
5b61b46
cbfe722
c5703bb
 
cbfe722
 
 
 
 
693ac1c
cbfe722
 
15518d4
ddc3b81
 
 
 
 
 
cbfe722
 
 
 
 
 
 
 
6585349
cbfe722
 
 
 
 
 
 
efa07cc
 
cbfe722
 
efa07cc
cbfe722
15518d4
cbfe722
 
 
6585349
cbfe722
 
 
 
 
 
 
 
630ff31
 
78e56d3
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
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"""
        <div style="display: flex; justify-content: center; align-items: center;">
            <img style="margin-right: 50px;" width=200 src="https://huggingface.co/spaces/Tenefix/private-fhe-fraud-detection/resolve/main/Img/zama.png">
            <img width=200 src="https://huggingface.co/spaces/Tenefix/private-fhe-fraud-detection/resolve/main/Img/Epita.png">
        </div>
        """
    )



    gr.Markdown(
        """
        <h1 style="text-align: center;">Confidential Bank Fraud Detection Using Fully Homomorphic Encryption</h1>
        <p align="center">
            <a href="https://github.com/CirSandro/private-fhe-fraud-detection">
                <span style="vertical-align: middle; display:inline-block; margin-right: 3px;">πŸ’³</span>Read the Code
            </a>
            β€”
            <a href="https://docs.zama.ai/concrete-ml">
                <span style="vertical-align: middle; display:inline-block; margin-right: 3px;">πŸ”’</span>Read Zama's Concrete-ML Documentation
            </a>
            β€”
            <a href="https://www.epita.fr/">
                <span style="vertical-align: middle; display:inline-block; margin-right: 3px;">🏫</span>Visit Epita Website
            </a>
        </p>
        """
    )

    gr.Markdown(
    """
    <p align="center" style="font-size: 16px;">
        This application shows you how to detect bank frauds without revealing your personal data using Fully Homomorphic Encryption.</p>
    """
    )

    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(
        """
        <p style="text-align: center;">
            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.
        </p>
        """
    )

    gr.Markdown(
        f"""
        <p align="center">
            <img width="100%" height="45%" src="https://huggingface.co/spaces/Tenefix/private-fhe-fraud-detection/resolve/main/Img/schema.png">
        </p>
        """
    )

    gr.Markdown("<hr />")

    ########################## 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("<hr />")

    ########################## 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("<hr />")

    ########################## Model Prediction ##########################

    gr.Markdown("## Step 3: Run the FHE evaluation.")
    gr.Markdown("<span style='color:grey'>Server Side</span>")
    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("<hr />")

    ########################## 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 &#11088;."
    )

if __name__ == "__main__":
    demo.launch()