PFEemp2024 commited on
Commit
d54dcc8
1 Parent(s): 42ef8b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +340 -4
app.py CHANGED
@@ -1,7 +1,343 @@
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
1
+ import os
2
+ import zipfile
3
+
4
  import gradio as gr
5
+ import nltk
6
+ import pandas as pd
7
+ import requests
8
+
9
+ from pyabsa import TADCheckpointManager
10
+ from textattack.attack_recipes import (
11
+ BAEGarg2019,
12
+ PWWSRen2019,
13
+ TextFoolerJin2019,
14
+ PSOZang2020,
15
+ IGAWang2019,
16
+ GeneticAlgorithmAlzantot2018,
17
+ DeepWordBugGao2018,
18
+ CLARE2020,
19
+ )
20
+ from textattack.attack_results import SuccessfulAttackResult
21
+ from utils import SentAttacker, get_agnews_example, get_sst2_example, get_amazon_example, get_imdb_example, diff_texts
22
+ # from utils import get_yahoo_example
23
+
24
+ sent_attackers = {}
25
+ tad_classifiers = {}
26
+
27
+ attack_recipes = {
28
+ "bae": BAEGarg2019,
29
+ "pwws": PWWSRen2019,
30
+ "textfooler": TextFoolerJin2019,
31
+ "pso": PSOZang2020,
32
+ "iga": IGAWang2019,
33
+ "ga": GeneticAlgorithmAlzantot2018,
34
+ "deepwordbug": DeepWordBugGao2018,
35
+ "clare": CLARE2020,
36
+ }
37
+
38
+
39
+ def init():
40
+ nltk.download("omw-1.4")
41
+
42
+ if not os.path.exists("TAD-SST2"):
43
+ z = zipfile.ZipFile("checkpoints.zip", "r")
44
+ z.extractall(os.getcwd())
45
+
46
+ for attacker in ["pwws", "bae", "textfooler", "deepwordbug"]:
47
+ for dataset in [
48
+ "agnews10k",
49
+ "amazon",
50
+ "sst2",
51
+ "yahoo",
52
+ # 'imdb'
53
+ ]:
54
+ if "tad-{}".format(dataset) not in tad_classifiers:
55
+ tad_classifiers[
56
+ "tad-{}".format(dataset)
57
+ ] = TADCheckpointManager.get_tad_text_classifier(
58
+ "tad-{}".format(dataset).upper()
59
+ )
60
+
61
+ sent_attackers["tad-{}{}".format(dataset, attacker)] = SentAttacker(
62
+ tad_classifiers["tad-{}".format(dataset)], attack_recipes[attacker]
63
+ )
64
+ tad_classifiers["tad-{}".format(dataset)].sent_attacker = sent_attackers[
65
+ "tad-{}pwws".format(dataset)
66
+ ]
67
+
68
+
69
+ cache = set()
70
+
71
+
72
+ def generate_adversarial_example(dataset, attacker, text=None, label=None):
73
+ if not text or text in cache:
74
+ if "agnews" in dataset.lower():
75
+ text, label = get_agnews_example()
76
+ elif "sst2" in dataset.lower():
77
+ text, label = get_sst2_example()
78
+ elif "amazon" in dataset.lower():
79
+ text, label = get_amazon_example()
80
+ # elif "yahoo" in dataset.lower():
81
+ # text, label = get_yahoo_example()
82
+ elif "imdb" in dataset.lower():
83
+ text, label = get_imdb_example()
84
+
85
+ cache.add(text)
86
+
87
+ result = None
88
+ attack_result = sent_attackers[
89
+ "tad-{}{}".format(dataset.lower(), attacker.lower())
90
+ ].attacker.simple_attack(text, int(label))
91
+ if isinstance(attack_result, SuccessfulAttackResult):
92
+ if (
93
+ attack_result.perturbed_result.output
94
+ != attack_result.original_result.ground_truth_output
95
+ ) and (
96
+ attack_result.original_result.output
97
+ == attack_result.original_result.ground_truth_output
98
+ ):
99
+ # with defense
100
+ result = tad_classifiers["tad-{}".format(dataset.lower())].infer(
101
+ attack_result.perturbed_result.attacked_text.text
102
+ + "$LABEL${},{},{}".format(
103
+ attack_result.original_result.ground_truth_output,
104
+ 1,
105
+ attack_result.perturbed_result.output,
106
+ ),
107
+ print_result=True,
108
+ defense=attacker,
109
+ )
110
+
111
+ if result:
112
+ classification_df = {}
113
+ classification_df["is_repaired"] = result["is_fixed"]
114
+ classification_df["pred_label"] = result["label"]
115
+ classification_df["confidence"] = round(result["confidence"], 3)
116
+ classification_df["is_correct"] = str(result["pred_label"]) == str(label)
117
+
118
+ advdetection_df = {}
119
+ if result["is_adv_label"] != "0":
120
+ advdetection_df["is_adversarial"] = {
121
+ "0": False,
122
+ "1": True,
123
+ 0: False,
124
+ 1: True,
125
+ }[result["is_adv_label"]]
126
+ advdetection_df["perturbed_label"] = result["perturbed_label"]
127
+ advdetection_df["confidence"] = round(result["is_adv_confidence"], 3)
128
+ advdetection_df['ref_is_attack'] = result['ref_is_adv_label']
129
+ advdetection_df['is_correct'] = result['ref_is_adv_check']
130
+
131
+ else:
132
+ return generate_adversarial_example(dataset, attacker)
133
+
134
+ return (
135
+ text,
136
+ label,
137
+ result["restored_text"],
138
+ result["label"],
139
+ attack_result.perturbed_result.attacked_text.text,
140
+ diff_texts(text, text),
141
+ diff_texts(text, attack_result.perturbed_result.attacked_text.text),
142
+ diff_texts(text, result["restored_text"]),
143
+ attack_result.perturbed_result.output,
144
+ pd.DataFrame(classification_df, index=[0]),
145
+ pd.DataFrame(advdetection_df, index=[0]),
146
+ )
147
+
148
+
149
+ def run_demo(dataset, attacker, text=None, label=None):
150
+ try:
151
+ data = {
152
+ "dataset": dataset,
153
+ "attacker": attacker,
154
+ "text": text,
155
+ "label": label,
156
+ }
157
+ response = requests.post('https://rpddemo.pagekite.me/api/generate_adversarial_example', json=data)
158
+ result = response.json()
159
+ print(response.json())
160
+ return (
161
+ result["text"],
162
+ result["label"],
163
+ result["restored_text"],
164
+ result["result_label"],
165
+ result["perturbed_text"],
166
+ result["text_diff"],
167
+ result["perturbed_diff"],
168
+ result["restored_diff"],
169
+ result["output"],
170
+ pd.DataFrame(result["classification_df"]),
171
+ pd.DataFrame(result["advdetection_df"]),
172
+ result["message"]
173
+ )
174
+ except Exception as e:
175
+ print(e)
176
+ return generate_adversarial_example(dataset, attacker, text, label)
177
+
178
+
179
+ def check_gpu():
180
+ try:
181
+ response = requests.post('https://rpddemo.pagekite.me/api/generate_adversarial_example', timeout=3)
182
+ if response.status_code < 500:
183
+ return 'GPU available'
184
+ else:
185
+ return 'GPU not available'
186
+ except Exception as e:
187
+ return 'GPU not available'
188
+
189
+
190
+ if __name__ == "__main__":
191
+ try:
192
+ init()
193
+ except Exception as e:
194
+ print(e)
195
+ print("Failed to initialize the demo. Please try again later.")
196
+
197
+ demo = gr.Blocks()
198
+
199
+ with demo:
200
+ gr.Markdown("<h1 align='center'>Reactive Perturbation Defocusing (Rapid) for Textual Adversarial Defense</h1>")
201
+ gr.Markdown("<h3 align='center'>Clarifications</h2>")
202
+ gr.Markdown("""
203
+ - This demo has no mechanism to ensure the adversarial example will be correctly repaired by Rapid. The repair success rate is actually the performance reported in the paper.
204
+ - The adversarial example and repaired adversarial example may be unnatural to read, while it is because the attackers usually generate unnatural perturbations. Rapid does not introduce additional unnatural perturbations.
205
+ - To our best knowledge, Reactive Perturbation Defocusing is a novel approach in adversarial defense. Rapid significantly (>10% defense accuracy improvement) outperforms the state-of-the-art methods.
206
+ - The DeepWordBug is an unknown attacker to the adversarial detector and reactive defense module. DeepWordBug has different attacking patterns from other attackers and shows the generalizability and robustness of Rapid.
207
+ """)
208
+ gr.Markdown("<h2 align='center'>Natural Example Input</h2>")
209
+ with gr.Group():
210
+ with gr.Row():
211
+ input_dataset = gr.Radio(
212
+ choices=["SST2", "Amazon", "Yahoo", "AGNews10K"],
213
+ value="SST2",
214
+ label="Select a testing dataset and an adversarial attacker to generate an adversarial example.",
215
+ )
216
+ input_attacker = gr.Radio(
217
+ choices=["BAE", "PWWS", "TextFooler", "DeepWordBug"],
218
+ value="TextFooler",
219
+ label="Choose an Adversarial Attacker for generating an adversarial example to attack the model.",
220
+ )
221
+ with gr.Group(visible=False):
222
+
223
+ with gr.Row():
224
+ input_sentence = gr.Textbox(
225
+ placeholder="Input a natural example...",
226
+ label="Alternatively, input a natural example and its original label (from above datasets) to generate an adversarial example.",
227
+ visible=False
228
+ )
229
+ input_label = gr.Textbox(
230
+ placeholder="Original label, (must be a integer, because we use digits to represent labels in training)",
231
+ label="Original Label",
232
+ visible=False
233
+ )
234
+ gr.Markdown(
235
+ "<h3 align='center'>To input an example, please select a dataset which the example belongs to or resembles.</h2>",
236
+ visible=False
237
+ )
238
+
239
+ msg_text = gr.Textbox(
240
+ label="Message",
241
+ placeholder="This is a message box to show any error messages.",
242
+ )
243
+ button_gen = gr.Button(
244
+ "Generate an adversarial example to repair using Rapid (GPU: < 1 minute, CPU: 1-10 minutes)",
245
+ variant="primary",
246
+ )
247
+ gpu_status_text = gr.Textbox(
248
+ label='GPU status',
249
+ placeholder="Please click to check",
250
+ )
251
+ button_check = gr.Button(
252
+ "Check if GPU available",
253
+ variant="primary"
254
+ )
255
+
256
+ button_check.click(
257
+ fn=check_gpu,
258
+ inputs=[],
259
+ outputs=[
260
+ gpu_status_text
261
+ ]
262
+ )
263
+
264
+ gr.Markdown("<h2 align='center'>Generated Adversarial Example and Repaired Adversarial Example</h2>")
265
+
266
+ with gr.Column():
267
+ with gr.Group():
268
+ with gr.Row():
269
+ output_original_example = gr.Textbox(label="Original Example")
270
+ output_original_label = gr.Textbox(label="Original Label")
271
+ with gr.Row():
272
+ output_adv_example = gr.Textbox(label="Adversarial Example")
273
+ output_adv_label = gr.Textbox(label="Predicted Label of the Adversarial Example")
274
+ with gr.Row():
275
+ output_repaired_example = gr.Textbox(
276
+ label="Repaired Adversarial Example by Rapid"
277
+ )
278
+ output_repaired_label = gr.Textbox(label="Predicted Label of the Repaired Adversarial Example")
279
+
280
+ gr.Markdown("<h2 align='center'>Example Difference (Comparisons)</p>")
281
+ gr.Markdown("""
282
+ <p align='center'>The (+) and (-) in the boxes indicate the added and deleted characters in the adversarial example compared to the original input natural example.</p>
283
+ """)
284
+ ori_text_diff = gr.HighlightedText(
285
+ label="The Original Natural Example",
286
+ combine_adjacent=True,
287
+ )
288
+ adv_text_diff = gr.HighlightedText(
289
+ label="Character Editions of Adversarial Example Compared to the Natural Example",
290
+ combine_adjacent=True,
291
+ )
292
+ restored_text_diff = gr.HighlightedText(
293
+ label="Character Editions of Repaired Adversarial Example Compared to the Natural Example",
294
+ combine_adjacent=True,
295
+ )
296
+
297
+ gr.Markdown(
298
+ "## <h2 align='center'>The Output of Reactive Perturbation Defocusing</p>"
299
+ )
300
+ with gr.Row():
301
+ with gr.Column():
302
+ with gr.Group():
303
+ output_is_adv_df = gr.DataFrame(
304
+ label="Adversarial Example Detection Result"
305
+ )
306
+ gr.Markdown(
307
+ "The is_adversarial field indicates if an adversarial example is detected. "
308
+ "The perturbed_label is the predicted label of the adversarial example. "
309
+ "The confidence field represents the confidence of the predicted adversarial example detection. "
310
+ )
311
+ with gr.Column():
312
+ with gr.Group():
313
+ output_df = gr.DataFrame(
314
+ label="Repaired Standard Classification Result"
315
+ )
316
+ gr.Markdown(
317
+ "If is_repaired=true, it has been repaired by Rapid. "
318
+ "The pred_label field indicates the standard classification result. "
319
+ "The confidence field represents the confidence of the predicted label. "
320
+ "The is_correct field indicates whether the predicted label is correct."
321
+ )
322
 
323
+ # Bind functions to buttons
324
+ button_gen.click(
325
+ fn=run_demo,
326
+ inputs=[input_dataset, input_attacker, input_sentence, input_label],
327
+ outputs=[
328
+ output_original_example,
329
+ output_original_label,
330
+ output_repaired_example,
331
+ output_repaired_label,
332
+ output_adv_example,
333
+ ori_text_diff,
334
+ adv_text_diff,
335
+ restored_text_diff,
336
+ output_adv_label,
337
+ output_df,
338
+ output_is_adv_df,
339
+ msg_text
340
+ ],
341
+ )
342
 
343
+ demo.queue(2).launch()