-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.py
2205 lines (2084 loc) · 83.2 KB
/
index.py
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os.path as osp
import interface
import os, json, datetime, time, base64, threading
import pytz,shutil
from IOtool import IOtool
from flask import render_template, redirect, url_for, Flask, request, jsonify, send_from_directory, send_file, make_response
from flask import current_app as abort
from flask_cors import *
ROOT = os.getcwd()
poollist = []
# {tid:{stid:feature}}
task_list = {}
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(ROOT, 'static'), 'favicon.ico')
@app.route('/', methods=['GET'])
def index():
'''
首页
'''
if request.method == "GET":
return render_template("index.html")
@app.route('/index_function_introduction', methods=['GET'])
def index_function_introduction():
'''
任务中心页
'''
if request.method == "GET":
# return render_template("index_function_introduction.html")
return render_template("task_center.html")
@app.route('/ex/uploadModel', methods=['POST'])
def ExUploadModel():
'''
攻击机理分析上传模型
ex_upload_model:上传模型
'''
fileinfo = request.files.get("ex_upload_model")
filepath = "model/ckpt/ex_upload_model.pt"
if osp.exists(filepath):
os.remove(filepath)
fileinfo.save(filepath)
res={
"code":10000,
"msg":"success"
}
return jsonify(res)
@app.route('/fairness/uploadModel', methods=['POST'])
def FairnessUploadModel():
'''
公平性模块上传模型
ckpt:上传模型
'''
fileinfo = request.files.get("ckpt")
filepath = "output/cache/fairness/ckpt.pth"
if not osp.exists('output/cache/fairness'):
os.makedirs('output/cache/fairness')
modelpath, modelname = os.path.split(filepath)
if osp.exists(filepath):
os.remove(filepath)
fileinfo.save(filepath)
res={
"code":10000,
"msg":"success",
'filepath':modelpath,
'filename':modelname
}
return jsonify(res)
@app.route('/login', methods=['POST'])
def login():
'''
登录
username:用户名
password:密码
'''
if request.method == 'POST' and request.form.get('username') and request.form.get('password'):
datax = request.form.to_dict()
usernamx = datax.get("username")
passwordx = datax.get("password")
print(usernamx,passwordx)
if osp.exists(os.path.join(ROOT,"output","user_info.json")):
userinfo = IOtool.load_json(osp.join(ROOT,"output","user_info.json"))
if usernamx in userinfo.keys() and userinfo[usernamx] == passwordx:
resp = {
"code":"1",
"msg":"Login Success"
}
else:
resp = {
"code":"-1",
"msg":"Login Fail"
}
else:
resp = {
"code":"-1",
"msg":"Login Fail"
}
return jsonify(resp)
else:
abort(403)
@app.route('/register', methods=['POST'])
def register():
'''
注册
username:用户名
password:密码
'''
if request.method == 'POST' and request.form.get('username') and request.form.get('password'):
datax = request.form.to_dict()
usernamx = datax.get("username")
passwordx = datax.get("password")
if osp.exists(os.path.join(ROOT,"output","user_info.json")):
userinfo = IOtool.load_json(osp.join(ROOT,"output","user_info.json"))
else:
userinfo = {}
if usernamx in userinfo.keys() or usernamx=='unknown':
resp = {"code":-1,"msg":"You input the user name already exists, please re-entry."}
else:
userinfo.update({usernamx:passwordx})
IOtool.write_json(userinfo, osp.join(ROOT,"output","user_info.json"))
resp = {
"code":1,
"msg":"success"
}
return jsonify(resp)
else:
return "no"
# ---------------模板:数据集公平性评估---------
@app.route('/DataFairnessEvaluate', methods=['POST'])
def DataFairnessEvaluate():
"""
数据集公平性评估
输入:tid:主任务ID
dataname:数据集名称
senAttrList:敏感属性列表
tarAttrList:目标属性列表
staAttrList:统计属性列表
"""
if (request.method == "POST"):
inputParam = json.loads(request.data)
dataname = inputParam["dataname"]
# 获取主任务ID
tid = inputParam["tid"]
# 生成子任务ID
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
# 添加任务信息到taskinfo
value = {
# 任务类型,注意任务类型不能重复,用于结果返回的key值索引
"type":"data_evaluate",
# 任务状态:0 未执行;1 正在执行;2 执行成功;3 执行失败
"state":0,
# 方法名称:如对抗攻击中的fgsm,ffgsm等,呈现在结果界面
"name":["data_evaluate"],
# 数据集信息,呈现在结果界面,若干有选择模型还需增加模型字段:model
"dataset":dataname,
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataname)
try:
senAttrList=json.loads(inputParam["senAttrList"])
tarAttrList=json.loads(inputParam["tarAttrList"])
staAttrList=json.loads(inputParam["staAttrList"])
except:
senAttrList=inputParam["senAttrList"]
tarAttrList=inputParam["tarAttrList"]
staAttrList=inputParam["staAttrList"]
logging = IOtool.get_logger(stid, tid)
# 执行任务,运行时间超过3分钟的请使用多线程,参考DataFairnessDebias函数的执行部分
from function.fairness import run_dataset_evaluate
pool = IOtool.get_pool(tid)
t2 = pool.submit(run_dataset_evaluate, dataname, sensattrs=senAttrList, targetattrs=tarAttrList, staAttrList=staAttrList, logging=logging)
IOtool.add_task_queue(tid, stid, t2, 300)
res = t2.result()
# res = run_dataset_evaluate(dataname, sensattrs=senAttrList, targetattrs=tarAttrList, staAttrList=staAttrList, logging=logging)
# 执行完成,结果中的stop置为1,表示结束
res["stop"] = 1
# 保存结果
IOtool.write_json(res, osp.join(ROOT,"output", tid, stid+"_result.json"))
# 将taskinfo中的状态置为2 代表子任务结果执行成功,此步骤为每个子任务必要步骤,请勿省略
IOtool.change_subtask_state(tid, stid, 2)
IOtool.change_task_success_v2(tid=tid)
return jsonify(res)
else:
abort(403)
# 数据集公平性提升
@app.route('/DataFairnessDebias', methods=['POST'])
def DataFairnessDebias():
"""
数据集公平性提升
输入:tid:主任务ID
dataname:数据集名称
datamethod:数据集优化算法名称
senAttrList:敏感属性列表
tarAttrList:目标属性列表
staAttrList:统计属性列表
"""
global LiRPA_LOGS
if (request.method == "POST"):
inputParam = json.loads(request.data)
dataname = inputParam["dataname"]
datamethod = inputParam["datamethod"]
tid = inputParam["tid"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
value = {
"type":"data_debias",
"state":0,
"name":["data_debias"],
"dataset":dataname,
"datamethod":datamethod,
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataname)
try:
senAttrList=json.loads(inputParam["senAttrList"])
tarAttrList=json.loads(inputParam["tarAttrList"])
staAttrList=json.loads(inputParam["staAttrList"])
except:
senAttrList=inputParam["senAttrList"]
tarAttrList=inputParam["tarAttrList"]
staAttrList=inputParam["staAttrList"]
# 执行任务
pool = IOtool.get_pool(tid)
t2 = pool.submit(interface.run_data_debias_api, tid, stid, dataname, datamethod, senAttrList, tarAttrList, staAttrList)
IOtool.add_task_queue(tid, stid, t2, 300)
# interface.run_data_debias_api(tid, stid, dataname, datamethod, senAttrList, tarAttrList, staAttrList)
res = {
"tid":tid,
"stid":stid
}
return jsonify(res)
else:
abort(403)
# 模型公平性评估
@app.route('/ModelFairnessEvaluate', methods=['POST'])
def ModelFairnessEvaluate():
"""
模型公平性评估
输入:tid:主任务ID
dataname:数据集名称
modelname:模型名称
metrics:公平性评估算法列表
senAttrList:敏感属性列表
tarAttrList:目标属性
staAttrList:统计属性列表
"""
global LiRPA_LOGS
if (request.method == "POST"):
inputParam = json.loads(request.data)
dataname = inputParam["dataname"]
tid = inputParam["tid"]
modelname = inputParam["modelname"]
model_path = inputParam["modelpath"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
value = {
"type":"model_evaluate",
"state":0,
"name":["model_evaluate"],
"dataset":dataname,
"model":modelname,
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataname)
IOtool.change_task_info(tid, "model", modelname)
pool = IOtool.get_pool(tid)
# IOtool.add_task_queue(tid, stid, t2, 300)
if dataname in ["Compas", "Adult", "German"]:
try:
metrics = json.loads(inputParam["metrics"])
senAttrList=json.loads(inputParam["senAttrList"])
tarAttrList=inputParam["tarAttrList"]
staAttrList=json.loads(inputParam["staAttrList"])
except:
metrics = inputParam["metrics"]
senAttrList=inputParam["senAttrList"]
tarAttrList=inputParam["tarAttrList"]
staAttrList=inputParam["staAttrList"]
t2 = pool.submit(interface.run_model_eva_api, tid, stid, dataname, model_path=model_path, modelname=modelname, metrics = metrics, senAttrList = senAttrList, tarAttrList = tarAttrList, staAttrList = staAttrList)
# interface.run_model_eva_api(tid, stid, dataname, model_path=model_path, modelname=modelname, metrics = metrics, senAttrList = senAttrList, tarAttrList = tarAttrList, staAttrList = staAttrList)
else:
dataname = dataname.lower()
if dataname == "cifar10-s":
dataname = "cifar-s"
try:
metrics = json.loads(inputParam["metrics"])
except:
metrics = inputParam["metrics"]
test_mode = inputParam["test_mode"]
t2 = pool.submit(interface.run_model_eva_api, tid, stid, dataname, model_path=model_path, modelname=modelname, metrics = metrics, test_mode = test_mode)
# interface.run_model_eva_api(tid, stid, dataname, model_path=model_path, modelname=modelname, metrics = metrics, test_mode = test_mode)
IOtool.add_task_queue(tid, stid, t2, 300)
# interface.run_model_eva_api( tid, stid, dataname, modelname, metrics = metrics, test_mode = test_mode)
res = {
"tid":tid,
"stid":stid
}
return jsonify(res)
else:
abort(403)
# 模型公平性提升
@app.route('/ModelFairnessDebias', methods=['POST'])
def ModelFairnessDebias():
"""
模型公平性提升
输入:tid:主任务ID
dataname:数据集名称
modelname:模型名称
algorithmname:模型优化算法名称
metrics:公平性评估算法列表
senAttrList:敏感属性列表
tarAttrList:目标属性
staAttrList:统计属性列表
"""
global LiRPA_LOGS
if (request.method == "POST"):
inputParam = json.loads(request.data)
dataname = inputParam["dataname"]
modelname = inputParam["modelname"]
tid = inputParam["tid"]
algorithmname = inputParam["algorithmname"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
AAtid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, AAtid + "_param.json"))
value = {
"type":"model_debias",
"state":0,
"name":["model_debias"],
"dataset":dataname,
"model":modelname,
"algorithmname":algorithmname
}
IOtool.add_subtask_info(tid, AAtid, value)
IOtool.change_task_info(tid, "dataset", dataname)
IOtool.change_task_info(tid, "model", modelname)
pool = IOtool.get_pool(tid)
# IOtool.add_task_queue(tid, AAtid, t2, 300)
save_folder = osp.join(ROOT,"output", "cache", "fairness")
model_path = inputParam["modelpath"]
if dataname in ["Compas", "Adult", "German"]:
try:
metrics = json.loads(inputParam["metrics"])
senAttrList=json.loads(inputParam["senAttrList"])
tarAttrList=inputParam["tarAttrList"]
staAttrList=json.loads(inputParam["staAttrList"])
except:
metrics = inputParam["metrics"]
senAttrList=inputParam["senAttrList"]
tarAttrList=inputParam["tarAttrList"]
staAttrList=inputParam["staAttrList"]
t2 = pool.submit(interface.run_model_debias_api, tid, AAtid, dataname, modelname, algorithmname, metrics, sensattrs = senAttrList,
targetattr = tarAttrList, staAttrList = staAttrList, model_path=model_path, save_folder=save_folder)
# interface.run_model_debias_api(tid, AAtid, dataname, modelname, algorithmname, metrics, sensattrs = senAttrList,
# targetattr = tarAttrList, staAttrList = staAttrList, model_path=model_path, save_folder=save_folder)
else:
dataname = dataname.lower()
# time.sleep(20)
if dataname == "cifar10-s":
dataname = "cifar-s"
try:
metrics = json.loads(inputParam["metrics"])
except:
metrics = inputParam["metrics"]
test_mode = inputParam["test_mode"]
t2 = pool.submit(interface.run_model_debias_api, tid, AAtid, dataname, modelname, algorithmname, metrics,
test_mode = test_mode, model_path=model_path, save_folder=save_folder)
# interface.run_model_debias_api(tid, AAtid, dataname, modelname, algorithmname, metrics,
# test_mode = test_mode, model_path=model_path, save_folder=save_folder)
# time.sleep(20)
IOtool.add_task_queue(tid, AAtid, t2, 30000)
res = {
"tid":tid,
"stid":AAtid
}
return jsonify(res)
else:
abort(403)
# 任务列表查询
@app.route('/Task/QueryTask', methods=['GET'])
def query_task():
'''任务列表查询
输入:
record:待查询的首条记录,从哪条开始查询,不填从最新一条查起
count:数量,查几条,不填从record开始查所有
输出:
TaskList:任务列表
Number:查到的任务数量
'''
record = -1
count = -1
if request.form.get("record"):
record = IOtool.atoi(request.form.get("record"))
if request.form.get("count"):
count = IOtool.atoi(request.form.get("count"))
taskinfo = IOtool.get_task_info()
start_num = 0
end_num = 0
taskresult = {}
username = request.headers.get('user') if request.headers.get('user') else 'unknown'
if osp.exists(osp.join(ROOT,"output","task_list.json")):
task_user_info = IOtool.load_json(osp.join(ROOT,"output","task_list.json"))
if username not in task_user_info.keys():
body = {"code":1,"msg":"success","TaskList":{},"Number":0}
return jsonify(body)
tasklist = task_user_info[username]
else:
body = {"code":1001,"msg":"fail,parameter error","TaskList":{}}
return jsonify(body)
task_num = len(tasklist)
if count < 0 and record < 0:
for temp in tasklist:
taskresult.update({temp:taskinfo[temp]})
body = {"code":1,"msg":"success","TaskList":taskresult,"Number":len(taskresult)}
return jsonify(body)
elif count >= 0 and record < 0:
start_num = 0
if count <task_num:
end_num = count
else:
end_num = task_num
elif count < 0 and record >= 0:
if record > task_num:
body = {"code":1001,"msg":"fail,parameter error","TaskList":{}}
return jsonify(body)
else:
start_num = record
end_num = task_num
else:
start_num = record
end_num = record+count
if start_num > task_num:
body = {"code":1001,"msg":"fail,parameter error","TaskList":{}}
return jsonify(body)
elif end_num > task_num:
end_num = task_num
for i in range(start_num,end_num):
taskresult.update({tasklist[i]:taskinfo[tasklist[i]]})
body = {"code":1,"msg":"success","TaskList":taskresult,"Number":len(taskresult)}
return jsonify(body)
# 单个任务查询
@app.route('/Task/QuerySingleTask', methods=['GET'])
def query_single_task():
'''单个任务查询
输入:
Taskid:主任务id
'''
if request.method == "GET":
inputdata = json.loads(request.data)
tid = inputdata["Taskid"]
taskinfo = IOtool.get_task_info()
if tid not in taskinfo.keys():
return jsonify({"code":1002,"msg":"fail,taskid not found!"})
return jsonify({"code":1,"msg":"success","result":taskinfo[tid]})
else:
abort(403)
# 主任务创建
@app.route('/Task/CreateTask', methods=['POST'])
def creat_task():
'''创建主任务
输入:
AttackAndDefenseTask:是否创建对抗攻击任务
输出:
Taskid:总任务ID
'''
if request.method == "POST":
format_time = str(datetime.datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y%m%d%H%M"))
tid = IOtool.get_task_id(str(format_time))
username = request.headers.get('user') if request.headers.get('user') else 'unknown'
outpath = osp.join(ROOT,"output",tid)
cachepath = osp.join(ROOT,"output/cache")
if not osp.exists(outpath):
os.makedirs(outpath)
if not osp.exists(cachepath):
os.makedirs(cachepath)
curinfo = {
"state":0,
"createtime":format_time,
"dataset":"",
"model":"",
"function":{}
}
if not osp.exists(osp.join(ROOT,"output","task_info.json")):
file = open(osp.join(ROOT,"output","task_info.json"),"w")
file.close()
data = {}
IOtool.reset_task_info(data)
IOtool.add_task_info(tid, curinfo)
if osp.exists(osp.join(ROOT,"output","task_list.json")):
task_user_info = IOtool.load_json(osp.join(ROOT,"output","task_list.json"))
else:
task_user_info = {"unknown":[]}
file = open(osp.join(ROOT,"output","task_list.json"),"w")
file.close()
if username in task_user_info.keys():
task_user_info[username].append(tid)
else:
task_user_info.update({username:[tid]})
IOtool.write_json(task_user_info, osp.join(ROOT,"output","task_list.json"))
IOtool.add_pool(tid)
data = {"Taskid": tid}
return jsonify(data)
# 日志查询
@app.route('/Task/QueryLog', methods=['GET'])
def query_log():
'''任务日志查询
输入:
Taskid:主任务id
输出:
Log:返回日志信息
'''
Log = {}
stid_list = []
tid = request.args.get("Taskid")
if not tid:
inputdata = json.loads(request.data)
tid = inputdata["Taskid"]
if not tid:
body = {"code":1001,"msg":"fail,parameter error"}
return jsonify(body)
taskinfo = IOtool.get_task_info()
stid_list =taskinfo[tid]["function"].keys()
path = osp.join(ROOT, "output", tid)
for stid in stid_list:
Log[stid]=[]
filenamelist = os.listdir(path)
filenames = sorted(filenamelist,key=lambda x : os.path.getmtime(osp.join(path, x)))
for filename in filenames:
if stid in filename and osp.isfile(osp.join(path, filename)) and "_log" in filename :
with open(osp.join(path, filename), "r") as fp:
Log[stid] += fp.readlines()
if len(stid_list)==0:
body = {"code":1003,"msg":"fail,log is NULL","Log":Log}
else:
body = {"code":1,"msg":"success","Log":Log}
return jsonify(body)
# 删除任务
@app.route('/Task/DeleteTask', methods=['DELETE'])
def delete_task():
'''删除任务
输入:
Taskid:主任务id
'''
tid = None
tid = request.args.get("Taskid")
if not tid:
body = {"code":1001,"msg":"fail,parameter error"}
return jsonify(body)
username = request.headers.get('user') if request.headers.get('user') else 'unknown'
if osp.exists(osp.join(ROOT,"output","task_list.json")):
task_user_info = IOtool.load_json(osp.join(ROOT,"output","task_list.json"))
else:
taskinfo = IOtool.del_task_info(tid)
body = {"code":1002,"msg":"fail,tasklist not found"}
return jsonify(body)
if username not in task_user_info.keys():
return jsonify({"code":1003,"msg":"fail,uesr not found"})
else:
if tid not in task_user_info[username]:
return jsonify({"code":1002,"msg":"fail,task not found in list"})
else:
task_user_info[username].remove(tid)
taskinfo = IOtool.del_task_info(tid)
IOtool.write_json(task_user_info, osp.join(ROOT,"output","task_list.json"))
outpath = osp.join(ROOT,"output",tid)
if osp.exists(outpath):
shutil.rmtree(outpath)
body = {"code":1,"msg":"success"}
return jsonify(body)
@app.route('/Task/UploadPic', methods=['POST'])
def UploadPic():
if request.method == "POST":
file = request.files.get('avatar')
basePath = os.path.abspath(os.path.dirname(__file__)).rsplit('/', 1)
save_dir = os.path.join(basePath[0], 'dataset/data/ckpt',"upload.jpg")
if os.path.exists(save_dir):
os.remove(save_dir)
file.save(save_dir)
return jsonify({'save_dir': save_dir})
# 结果输出
@app.route("/output/Resultdata", methods=["GET"])
def get_result():
'''
结果查询接口
输入:
Taskid:主任务id
'''
if request.method == "GET":
stidlist = []
# 使用postman获取参数
try:
inputdata = json.loads(request.data)
tid = inputdata["Taskid"]
stidlist = inputdata["sid"]
except:
pass
# 从web上传下来的参数
if request.args.get("Taskid") != None:
tid = request.args.get("Taskid")
taskinfo = IOtool.get_task_info()
if stidlist== []:
stidlist = taskinfo[tid]["function"].keys()
# 如果能获取到子任务列表就使用获取,否则读取主任务下的所有子任务
if request.args.get("stid") != None:
stidlist = request.args.get("stid")
result = {}
result['param'] = {}
result['stidlist'] = {}
for stid in stidlist:
attack_type = taskinfo[tid]["function"][stid]["type"]
# 如果子任务状态不是执行成功,则返回子任务结果为空
if taskinfo[tid]["function"][stid]["state"] < 2 :
result[attack_type]= {}
# 如果子任务状态成功,结果文件不存在,则返回子任务结果为空
elif not osp.exists(osp.join(ROOT,"output",tid,stid+"_result.json")):
result[attack_type]= {}
else:
result[attack_type] = (IOtool.load_json(osp.join(ROOT,"output",tid,stid+"_result.json")))
if osp.exists(osp.join(ROOT,"output", tid, stid+"_param.json")):
result['param'][attack_type] = IOtool.load_json(osp.join(ROOT,"output",tid,stid+"_param.json"))
result['stidlist'][attack_type] = stid
stopflag = 1
for temp in result.keys():
if temp in ['param','stidlist']:
continue
if "stop" not in result[temp].keys():
stopflag = 0
elif result[temp]["stop"] == 0:
stopflag = 0
elif result[temp]["stop"] == 2:
stopflag = 2
# print(result)
# print("stopflag", stopflag)
result['tid'] = tid
return jsonify({"code":1,"msg":"success","result":result,"stop":stopflag})
# ----------------- 课题1 对抗攻击评估 -----------------
@app.route('/Attack/AdvAttack', methods=['POST'])
def AdvAttack():
"""
对抗攻击评估
输入:tid:主任务ID
Dataset:数据集名称
Model:模型名称
Method:list 对抗攻击算法名称
"""
global LiRPA_LOGS
if (request.method == "POST"):
inputParam = json.loads(request.data)
tid = inputParam["Taskid"]
# inputParam["device"] = "cuda:0"
dataname = inputParam["Dataset"]
model = inputParam["Model"]
sample_num = inputParam["sample_num"]
try:
adv_method = json.loads(inputParam["Method"])
except:
adv_method = inputParam["Method"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
value = {
"type":"adv_attack",
"state":0,
"name":["adv_attack"],
"dataset":dataname,
"method":adv_method,
"model":model,
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataname)
IOtool.change_task_info(tid, "model", model)
# 执行任务
pool = IOtool.get_pool(tid)
t2 = pool.submit(interface.run_adv_attack, tid, stid, dataname, model, adv_method, inputParam, sample_num)
print(inputParam)
IOtool.add_task_queue(tid, stid, t2, 72000*len(adv_method))
# interface.run_adv_attack(tid, stid, dataname, model, adv_method, inputParam)
res = {
"tid":tid,
"stid":stid
}
return jsonify(res)
else:
abort(403)
# ----------------- 课题1 后门攻击评估 -----------------
@app.route('/Attack/BackdoorAttack', methods=['POST'])
def BackdoorAttack():
"""
后门攻击评估
输入:tid:主任务ID
Dataset:数据集名称
Model:模型名称
Method:list 后门算法名称
attackparam:攻击参数
"""
global LiRPA_LOGS
if (request.method == "POST"):
inputParam = json.loads(request.data)
print(request.data)
tid = inputParam["Taskid"]
# inputParam["device"] = "cuda:0"
dataname = inputParam["Dataset"]
model = inputParam["Model"]
try:
adv_method = json.loads(inputParam["Method"])
except:
adv_method = inputParam["Method"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
value = {
"type":"backdoor_attack",
"state":0,
"name":["adv_attack"],
"dataset":dataname,
"method":adv_method,
"model":model,
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataname)
IOtool.change_task_info(tid, "model", model)
# 执行任务
pool = IOtool.get_pool(tid)
t2 = pool.submit(interface.run_backdoor_attack, tid, stid, dataname, model, adv_method, inputParam)
IOtool.add_task_queue(tid, stid, t2, 72000*len(adv_method))
# interface.run_backdoor_attack(tid, stid, dataname, model, adv_method, inputParam)
# t2 = threading.Thread(target=interface.run_backdoor_attack,args=(tid, stid, dataname, model, adv_method, inputParam))
# t2.setDaemon(True)
# t2.start()
res = {
"code":1,
"msg":"success",
"tid":tid,
"stid":stid
}
return jsonify(res)
else:
abort(403)
# ----------------- 课题1 攻击机理分析 -----------------
@app.route('/Attack/AttackDimReduciton', methods=['POST'])
def AttackDimReduciton():
"""
数据降维分布解释
输入:tid:主任务ID
Dataset:数据集名称
Model:模型名称
AdvMethods:list 对抗攻击算法名称
VisMethods:list 数据降维方法
"""
global LiRPA_LOGS
if (request.method == "POST"):
inputParam = json.loads(request.data)
tid = inputParam["Taskid"]
print("tid:",tid)
datasetparam = inputParam["DatasetParam"]
modelparam = inputParam["ModelParam"]
adv_methods = inputParam["AdvMethods"]
vis_methods = inputParam["VisMethods"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
value = {
"type":"attack_dim_reduciton",
"state":0,
"name":["adv_attack"],
"dataset":datasetparam["name"],
"method":adv_methods,
"model":modelparam["name"],
"vis_method":vis_methods
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", datasetparam["name"])
IOtool.change_task_info(tid, "model", modelparam["name"])
# 执行任务
datasetparam["name"] = datasetparam["name"].lower()
modelparam["name"] = modelparam["name"].lower()
pool = IOtool.get_pool(tid)
t2 = pool.submit(interface.run_dim_reduct, tid, stid, datasetparam, modelparam, vis_methods, adv_methods)
IOtool.add_task_queue(tid, stid, t2, 4000 * len(vis_methods) + 3000*len(adv_methods))
# interface.run_dim_reduct(tid, stid, datasetparam, modelparam, vis_methods, adv_methods)
# t2 = threading.Thread(target=interface.run_dim_reduct,args=(tid, stid, datasetparam, modelparam, vis_methods, adv_methods, device))
# t2.setDaemon(True)
# t2.start()
res = {
"code":1,
"msg":"success",
"tid":tid,
"stid":stid
}
return jsonify(res)
else:
abort(403)
@app.route('/reach',methods=["GET","POST"])
def model_reach():
'''
可达性验证
输入:
pic:上传样本
label:真实标签
target:目标标签
tid:主任务id
'''
if request.method=='POST':
inputParam = json.loads(request.data)
dataset=inputParam['dataset']
pic=inputParam['pic']
label=inputParam['label']
target=inputParam['target']
tid = inputParam["tid"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
img_dir=os.path.join(os.getcwd(),"output",tid, stid)
if not os.path.exists(img_dir):
os.mkdir(img_dir)
pic_path=os.path.join(img_dir,'input.png')
if "image/jpeg;" in pic:
with open( pic_path, 'wb') as f:
f.write(base64.b64decode(pic.replace('data:image/jpeg;base64,','')))
f.close()
else:
with open( pic_path, 'wb') as f:
f.write(base64.b64decode(pic.replace('data:image/png;base64,','')))
f.close()
value = {
"type":"model_reach",
"state":0,
"dataset":dataset,
"model":'CNN',
'label':label,
'target':target,
'pic':pic_path
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataset)
IOtool.change_task_info(tid, "model", 'CNN')
pool = IOtool.get_pool(tid)
t2 = pool.submit(interface.reach, tid,stid,dataset.upper(),pic_path,label,target)
IOtool.add_task_queue(tid, stid, t2, 300)
# interface.reach(tid, stid, dataset.upper(), pic_path, label, target)
resp = t2.result()
print(resp)
return jsonify(resp)
@app.route('/knowledge_consistency',methods=["GET","POST"])
def model_consistency():
'''
一致性验证
输入:
net:模型名称
layer:模型层
pic:上传样本
dataset:数据集名称
tid:主任务id
'''
if request.method=='POST':
inputParam = json.loads(request.data)
tid = inputParam["tid"]
net=inputParam['net']
layer=inputParam['layer']
dataset=inputParam['dataset']
pic=inputParam['pic']
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
img_dir=os.path.join(os.getcwd(),"output",tid, stid)
if not os.path.exists(img_dir):
os.mkdir(img_dir)
pic_path=os.path.join(img_dir,'input.png')
try:
os.mkdir(os.path.join(img_dir,tid))
except:
pass
if "image/jpeg;" in pic:
with open( pic_path, 'wb') as f:
f.write(base64.b64decode(pic.replace('data:image/jpeg;base64,','')))
f.close()
else:
with open( pic_path, 'wb') as f:
f.write(base64.b64decode(pic.replace('data:image/png;base64,','')))
f.close()
value = {
"type":"model_consistency",
"state":0,
"dataset":dataset,
"layer":layer,
"model":net,
}
IOtool.add_subtask_info(tid, stid, value)
IOtool.change_task_info(tid, "dataset", dataset)
IOtool.change_task_info(tid, "model", net)
pool = IOtool.get_pool(tid)
t2 = pool.submit(interface.knowledge_consistency, tid, stid, net, dataset, pic_path,layer)
IOtool.add_task_queue(tid, stid, t2, 300)
# interface.knowledge_consistency(tid, stid, net, dataset, pic_path,layer)
resp = t2.result()
# resp=interface.knowledge_consistency(tid, stid, net,dataset,pic_path,layer)
return json.dumps(resp,ensure_ascii=False)
# return render_template('knowledge_consistency.html')
@app.route('/auto_verify_img',methods=["GET","POST"])
def auto_verify_img():
if request.method=='POST':
inputParam = json.loads(request.data)
tid = inputParam["tid"]
format_time = str(datetime.datetime.now().strftime("%Y%m%d%H%M"))
stid = "S"+IOtool.get_task_id(str(format_time))
IOtool.write_json(inputParam, osp.join(ROOT,"output", tid, stid + "_param.json"))
net=inputParam['net']
if 'eps' in inputParam:
eps=float(inputParam['eps'])
else:
eps=0.1
pic=inputParam['pic']
dataset=inputParam['dataset']
img_dir=os.path.join(os.getcwd(),"output",tid, stid)
if not os.path.exists(img_dir):
os.mkdir(img_dir)
pic_path=os.path.join(img_dir,'input.png')
try:
os.mkdir(os.path.join(img_dir,tid))
except:
pass
if "image/jpeg;" in pic:
with open( pic_path, 'wb') as f:
f.write(base64.b64decode(pic.replace('data:image/jpeg;base64,','')))
f.close()
else:
with open( pic_path, 'wb') as f:
f.write(base64.b64decode(pic.replace('data:image/png;base64,','')))
f.close()
value = {
"type":"auto_verify",
"state":0,
"dataset":dataset,
"pic_path":pic_path,
'eps':eps,