Tenefix 80cols commited on
Commit
cbfe722
·
verified ·
1 Parent(s): 43cc119

Update app.py (#2)

Browse files

- Update app.py (9a9e943813136d7e7bfb4aa6c35d8db0020da115)


Co-authored-by: Sandro Ferroni <[email protected]>

Files changed (1) hide show
  1. app.py +242 -46
app.py CHANGED
@@ -1,54 +1,250 @@
1
  import gradio as gr
2
- from predictor import predict
3
 
4
- def make_prediction(distance_from_home, distance_from_last_transaction,
5
- ratio_to_median_purchase_price, repeat_retailer,
6
- used_chip, used_pin_number, online_order):
7
  """
8
- Prepares user input data and performs a local prediction.
9
-
10
- Args:
11
- distance_from_home (float): Distance from home.
12
- distance_from_last_transaction (float): Distance from the last transaction.
13
- ratio_to_median_purchase_price (float): Ratio to the median purchase price.
14
- repeat_retailer (bool): Repeated retailer.
15
- used_chip (bool): Used chip.
16
- used_pin_number (bool): Used PIN number.
17
- online_order (bool): Online order.
18
 
19
  Returns:
20
- str: Prediction result ("Fraudulent" or "Non-fraudulent").
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  """
22
- try:
23
- input_data = {
24
- "distance_from_home": distance_from_home,
25
- "distance_from_last_transaction": distance_from_last_transaction,
26
- "ratio_to_median_purchase_price": ratio_to_median_purchase_price,
27
- "repeat_retailer": int(repeat_retailer),
28
- "used_chip": int(used_chip),
29
- "used_pin_number": int(used_pin_number),
30
- "online_order": int(online_order),
31
- }
32
- return predict(input_data)
33
- except Exception as e:
34
- return f"Unexpected error: {e}"
35
-
36
- # Gradio user interface
37
- iface = gr.Interface(
38
- fn=make_prediction,
39
- inputs=[
40
- gr.Number(label="Distance from Home"),
41
- gr.Number(label="Distance from Last Transaction"),
42
- gr.Number(label="Ratio to Median Purchase Price"),
43
- gr.Checkbox(label="Repeat Retailer"),
44
- gr.Checkbox(label="Used Chip"),
45
- gr.Checkbox(label="Used PIN Number"),
46
- gr.Checkbox(label="Online Order"),
47
- ],
48
- outputs=gr.Textbox(label="Output"),
49
- title="Fraud Detection with Local FHE Model",
50
- description="Local interface using a compiled FHE model to detect fraud."
51
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  if __name__ == "__main__":
54
- iface.launch()
 
1
  import gradio as gr
2
+ from predictor import predict, key_already_generated, pre_process_encrypt_send_purchase, decrypt_prediction
3
 
4
+ def key_generated():
 
 
5
  """
6
+ Check if the evaluation keys have already been generated.
 
 
 
 
 
 
 
 
 
7
 
8
  Returns:
9
+ bool: True if the evaluation keys have already been generated, False otherwise.
10
+ """
11
+ if not key_already_generated():
12
+ error_message = (
13
+ f"Error Encountered While generating the evaluation keys."
14
+ )
15
+ print(error_message)
16
+ return {gen_key_btn: gr.update(value=error_message)}
17
+ else:
18
+ print("Keys have been generated ✅")
19
+ return {gen_key_btn: gr.update(value="Keys have been generated ✅")}
20
+
21
+ demo = gr.Blocks(css=".markdown-body { font-size: 18px; }")
22
+
23
+ with demo:
24
+ gr.Markdown(
25
+ """
26
+ <div style="display: flex; justify-content: center; align-items: center;">
27
+ <img style="margin-right: 50px;" width=200 src="https://user-images.githubusercontent.com/5758427/197816413-d9cddad3-ba38-4793-847d-120975e1da11.png">
28
+ <img width=200 src="https://upload.wikimedia.org/wikipedia/fr/d/d8/Epita.png">
29
+ </div>
30
+ """
31
+ )
32
+
33
+ gr.Markdown(
34
+ """
35
+ <h1 style="text-align: center;">Fraud Detection with FHE Model</h1>
36
+ <p align="center">
37
+ <a href="https://github.com/CirSandro/private-fhe-fraud-detection">
38
+ <span style="vertical-align: middle; display:inline-block; margin-right: 3px;">💳</span>private-fhe-fraud-detection
39
+ </a>
40
+
41
+ <a href="https://docs.zama.ai/concrete-ml">
42
+ <span style="vertical-align: middle; display:inline-block; margin-right: 3px;">🔒</span>Documentation Concrete-ML
43
+ </a>
44
+ </p>
45
+ """
46
+ )
47
+
48
+ gr.Markdown(
49
  """
50
+ <p align="center" style="font-size: 16px;">
51
+ How to detect bank fraud without using your personal data ?</p>
52
+ """
53
+ )
54
+
55
+ with gr.Accordion("What is bank fraud detection?", open=False):
56
+ gr.Markdown(
57
+ """
58
+ Bank fraud detection is the process of identifying fraudulent activities or transactions
59
+ that may pose a risk to a bank or its customers. It is essential to detect fraudulent
60
+ activities to prevent financial losses and protect the integrity of the banking system.
61
+ """
62
+ )
63
+
64
+ with gr.Accordion("Why is it important to protect this data?", open=False):
65
+ gr.Markdown(
66
+ """
67
+ Banking and financial data often contain sensitive personal information, such as income,
68
+ spending habits, and account numbers. Protecting this information ensures that customers'
69
+ privacy is respected and safeguarded from unauthorized access.
70
+ """
71
+ )
72
+
73
+ with gr.Accordion("Why is Fully Homomorphic Encryption (FHE) a good solution?", open=False):
74
+ gr.Markdown(
75
+ """
76
+ Fully Homomorphic Encryption (FHE) is a powerful technique for enhancing privacy and accuracy
77
+ in the context of fraud detection, particularly when dealing with sensitive banking data. FHE
78
+ allows for the encryption of data, which can then be processed and analyzed without ever needing
79
+ to decrypt it.
80
+
81
+ Each party involved in the detection process can collaborate without compromising user privacy,
82
+ minimizing the risk of data leaks or breaches. The data remains confidential throughout the entire
83
+ process, ensuring that the privacy of users is maintained.
84
+ """
85
+ )
86
+
87
+ gr.Markdown(
88
+ """
89
+ <p style="text-align: center;">
90
+ 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.
91
+ </p>
92
+ """
93
+ )
94
+
95
+ gr.Markdown(
96
+ """
97
+ <p align="center">
98
+ <img width="75%" height="30%" src="https://raw.githubusercontent.com/kcelia/Img/main/fhe_anonymization_banner.png">
99
+ </p>
100
+ """
101
+ )
102
+
103
+ gr.Markdown("<hr />")
104
+
105
+ ########################## Key Gen Part ##########################
106
+
107
+ gr.Markdown(
108
+ "## Step 1: Generate the keys\n\n"
109
+ """In Fully Homomorphic Encryption (FHE) methods, two types of keys are created. The first
110
+ type, called secret keys, are used to encrypt and decrypt the user's data. The second type,
111
+ called evaluation keys, enables a server to work on the encrypted data without seeing the
112
+ actual data.
113
+ """
114
+ )
115
+
116
+ gen_key_btn = gr.Button("Generate the secret and evaluation keys")
117
+
118
+ gen_key_btn.click(
119
+ key_generated,
120
+ inputs=[],
121
+ outputs=[gen_key_btn],
122
+ )#547
123
+
124
+ gr.Markdown("<hr />")
125
+
126
+ ########################## Encrypt Data ##########################
127
+
128
+ gr.Markdown(
129
+ "## Step 2: Make your purchase\n\n"
130
+ """ 🛍️ It's time to shop! To simulate your latest purchase, please provide the details of your most recent transaction.
131
+ """
132
+ )
133
+
134
+ with gr.Row():
135
+ with gr.Column():
136
+ distance_home = gr.Slider(
137
+ minimum=float(0),
138
+ maximum=float(22000),
139
+ step=1,
140
+ value=10,
141
+ label="Distance from Home",
142
+ info="How far was the purchase from your home (in km)?"
143
+ )
144
+ distance_last = gr.Slider(
145
+ minimum=float(0),
146
+ maximum=float(22000),
147
+ step=1,
148
+ value=1,
149
+ label="Distance from Last Transaction",
150
+ info="Distance between this purchase and the last one (in km)?"
151
+ )
152
+ ratio = gr.Slider(
153
+ minimum=float(0),
154
+ maximum=float(10000),
155
+ step=0.1,
156
+ value=1,
157
+ label="Ratio to Median Purchase Price",
158
+ info="Purchase ratio compared to your average purchase",
159
+ )
160
+ repeat_retailer = gr.Checkbox(
161
+ label="Repeat Retailer",
162
+ info="Check if you are purchasing from the same retailer as your last transaction"
163
+ )
164
+ used_chip = gr.Checkbox(
165
+ label="Used Chip",
166
+ info="Check if you used a chip card for this transaction"
167
+ )
168
+ used_pin_number = gr.Checkbox(
169
+ label="Used Pin Number",
170
+ info="Check if you used your PIN number during the transaction"
171
+ )
172
+ online = gr.Checkbox(
173
+ label="Online Order",
174
+ info="Check if you made your purchase online"
175
+ )
176
+
177
+ with gr.Row():
178
+ with gr.Column(scale=2):
179
+ encrypt_button_applicant = gr.Button("Encrypt the inputs and send to server.")
180
+
181
+ encrypted_input_applicant = gr.Textbox(
182
+ label="Encrypted input representation:", max_lines=2, interactive=False
183
+ )
184
+
185
+ encrypt_button_applicant.click(
186
+ pre_process_encrypt_send_purchase,
187
+ inputs=[distance_home, distance_last, ratio, repeat_retailer, used_chip, used_pin_number, \
188
+ online],
189
+ outputs=[encrypted_input_applicant, encrypt_button_applicant],
190
+ )
191
+
192
+ gr.Markdown("<hr />")
193
+
194
+ ########################## Model Prediction ##########################
195
+
196
+ gr.Markdown("## Step 3: Run the FHE evaluation.")
197
+ gr.Markdown("<span style='color:grey'>Server Side</span>")
198
+ gr.Markdown(
199
+ """
200
+ It's high time to launch our prediction, by pressing the button you will launch the
201
+ fraud analysis that our fictitious bank offers you.
202
+
203
+ This server employs a [Decision Tree (by Concrete-ML)](https://github.com/zama-ai/concrete-ml/blob/release/1.8.x/docs/references/api/concrete.ml.sklearn.tree.md#class-decisiontreeclassifier)
204
+ classifier model that has been trained on a synthetic data-set.
205
+ """
206
+ )
207
+
208
+ execute_fhe_button = gr.Button("Run the FHE evaluation.")
209
+ fhe_execution_time = gr.Textbox(
210
+ label="Total FHE execution time (in seconds):", max_lines=1, interactive=False
211
+ )
212
+
213
+ # Button to send the encodings to the server using post method
214
+ execute_fhe_button.click(predict, outputs=[fhe_execution_time, execute_fhe_button])
215
+
216
+ gr.Markdown("<hr />")
217
+
218
+ ########################## Decrypt Prediction ##########################
219
+
220
+ gr.Markdown("## Step 4: Receive the encrypted output from the server and decrypt.")
221
+ gr.Markdown(
222
+ """
223
+ 🔔 You will receive a notification! Is this a Fraud? The message is decrypted by pressing the button.
224
+ """
225
+ )
226
+
227
+ get_output_button = gr.Button("Decrypt the prediction.")
228
+ prediction_output = gr.Textbox(
229
+ label="Prediction", max_lines=1, interactive=False
230
+ )
231
+ get_output_button.click(
232
+ decrypt_prediction,
233
+ outputs=[prediction_output, get_output_button],
234
+ )
235
+
236
+
237
+ gr.Markdown(
238
+ """
239
+ You now know that it is possible to detect bank fraud without knowing your personal information.
240
+ """
241
+ )
242
+
243
+ gr.Markdown(
244
+ "The app was built with [Concrete-ML](https://github.com/zama-ai/concrete-ml), a "
245
+ "Privacy-Preserving Machine Learning (PPML) open-source set of tools by [Zama](https://zama.ai/). "
246
+ "Try it yourself and don't forget to star on Github &#11088;."
247
+ )
248
 
249
  if __name__ == "__main__":
250
+ demo.launch()